PageRenderTime 58ms CodeModel.GetById 8ms RepoModel.GetById 1ms app.codeStats 0ms

/DICK.Core/Engine.cs

https://bitbucket.org/williamybs/uidipythontool
C# | 922 lines | 681 code | 72 blank | 169 comment | 39 complexity | 9677ca8ed8d7be2886ed90a1db419e93 MD5 | raw file
  1. /* This file is part of DI Construction Kit.
  2. *
  3. * DI Construction Kit is free software: you can redistribute it and/or modify
  4. * it under the terms of the GNU Lesser General Public License as published by
  5. * the Free Software Foundation, either version 3 of the License, or
  6. * (at your option) any later version.
  7. *
  8. * DI Construction Kit is distributed in the hope that it will be useful,
  9. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. * GNU Lesser General Public License for more details.
  12. *
  13. * You should have received a copy of the GNU Lesser General Public License
  14. * along with DI Construction Kit. If not, see <http://www.gnu.org/licenses/>.
  15. *
  16. */
  17. using System;
  18. using System.Collections;
  19. using System.Collections.Generic;
  20. using System.Xml;
  21. using System.Xml.Schema;
  22. using System.IO;
  23. using System.Diagnostics;
  24. using System.Data;
  25. using System.Reflection;
  26. using Microsoft.CSharp;
  27. using System.CodeDom.Compiler;
  28. using System.Text;
  29. using System.Text.RegularExpressions;
  30. using System.Web;
  31. using DICK.Core.JobManagement;
  32. namespace DICK.Core
  33. {
  34. /// <summary>
  35. /// Engine is a singleton class that manages those core functionalities of DICK that are independent of DI API and IronPython.
  36. /// These functions include log management, job management, system configurations management, configuration directory settings.
  37. /// DICK.B1.B1Engine extends this class.
  38. /// </summary>
  39. /// <seealso cref="B1Engine"/>
  40. public class Engine
  41. {
  42. private static log4net.ILog docLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
  43. public static readonly string VERSIONTEXT = "DI Construction Kit R2.01";
  44. /// <summary>
  45. /// Singleton instance of Engine. Visibility is set to protected because B1Engine inheritss this class.
  46. /// </summary>
  47. private static Engine instance;
  48. private static string basedirectory;
  49. protected static FileHelpers.FileHelperEngine filehelpersengine;
  50. private static readonly string installDirectory = AppDomain.CurrentDomain.BaseDirectory;
  51. /// <summary>
  52. /// Returns the directory path where the DICK binaries are installed.
  53. /// </summary>
  54. public static string InstallDirectory
  55. {
  56. get { return Engine.installDirectory; }
  57. }
  58. protected static void SetInstance(Engine _instance)
  59. {
  60. //Do not set an initialized instance to null
  61. if (instance != null && _instance == null)
  62. {
  63. throw new DICKException();
  64. }
  65. else
  66. {
  67. instance = _instance;
  68. }
  69. }
  70. public static string BaseDirectory
  71. {
  72. get { return Engine.basedirectory; }
  73. set { Engine.basedirectory = value; }
  74. }
  75. public static string confdirectory;
  76. private static string systemconfigurationdirectory;
  77. public static string scriptdirectory;
  78. public static string SystemConfigurationDirectory
  79. {
  80. get { return Engine.systemconfigurationdirectory; }
  81. set { Engine.systemconfigurationdirectory = value; }
  82. }
  83. private static string logdirectory;
  84. public static string LogDirectory
  85. {
  86. get { return Engine.logdirectory; }
  87. set { Engine.logdirectory = value; }
  88. }
  89. private static string templatedirectory;
  90. public static string TemplateDirectory
  91. {
  92. get { return templatedirectory; }
  93. set { templatedirectory = value; }
  94. }
  95. public static string exportjobdirectory;
  96. public static string importjobdirectory;
  97. public static string genericjobdirectory;
  98. public static string pythonjobdirectory;
  99. public string Db
  100. {
  101. get;
  102. set;
  103. }
  104. public string User
  105. {
  106. get;
  107. set;
  108. }
  109. /// <summary>
  110. /// Overridden in B1Engine
  111. /// </summary>
  112. public string Password { get; set; }
  113. public string Host { get; set; }
  114. public string LicenseServer { get; set; }
  115. public bool autologin;
  116. public bool forceDB;
  117. private bool useTrusted;
  118. public bool UseTrusted
  119. {
  120. get { return useTrusted; }
  121. set { useTrusted = value; }
  122. }
  123. public string dbusername;
  124. public string dbpwd;
  125. public string dataservertype;
  126. private string connectionString;
  127. public string ConnectionString
  128. {
  129. get { return connectionString; }
  130. set { connectionString = value; }
  131. }
  132. public Dictionary<string, string> Parameters;
  133. //private ExportJob currentExportJob;
  134. public string loglevel;
  135. public enum FileOperationRequirement { READ, READWRITE };
  136. public SortedDictionary<string, SystemConfiguration> systemlookup = new SortedDictionary<string, SystemConfiguration>();
  137. public List<SystemConfiguration> systems = new List<SystemConfiguration>();
  138. private System.Collections.Generic.Dictionary<string, object> context = new Dictionary<string, object>();
  139. public object GetFromContext(string key)
  140. {
  141. return context[key];
  142. }
  143. public void AddToContext(string key, object _value)
  144. {
  145. context[key] = _value;
  146. }
  147. public void RemoveFromContext(string key)
  148. {
  149. context[key] = null;
  150. }
  151. /// <summary>
  152. /// The constructor is protected in order to implement a singleton pattern but enables subclassing by B1.B1Engine
  153. /// </summary>
  154. protected Engine()
  155. { }
  156. /// <summary>
  157. /// Used to retrieve the singleton instance of Engine. The singleton is initialized when this method is called for the first time.
  158. /// </summary>
  159. /// <returns>The singleton instance of Engine.</returns>
  160. public static Engine GetInstance()
  161. {
  162. if (instance == null)
  163. {
  164. InitializeEngine();
  165. if (instance != null)
  166. {
  167. instance.LogDebug("GETINSTANCE: ENGINE INITIALIZED !!");
  168. }
  169. }
  170. return instance;
  171. }
  172. /// <summary>
  173. /// Used to verify that a path specified by a parameter points to a directory path that exists and that the identity under which DICK is executed has read/write rights to that directory.
  174. /// </summary>
  175. /// <param name="pathparameter">The parameter that holds the path to be checked.</param>
  176. /// <param name="defaultpath">The default path that is to be used if the result of the test is negative.</param>
  177. /// <param name="fileop">Required file operation (read/write)</param>
  178. /// <param name="message">A MessageToken instance that is used to pass detailed information to the caller.</param>
  179. /// <returns></returns>
  180. public static string CheckDirectory(string pathparameter, string defaultpath, FileOperationRequirement fileop, ref MessageToken message)
  181. {
  182. message.AddTextToBody("Checking for parameter " + pathparameter + "...");
  183. string path = System.Configuration.ConfigurationManager.AppSettings[pathparameter];
  184. if (path != null && !path.Trim().Equals(""))
  185. {
  186. message.AddTextToBody("Found " + path);
  187. message.AddTextToBody("Validating path...");
  188. DirectoryInfo di = new DirectoryInfo(path);
  189. if (di.Exists)
  190. {
  191. message.AddTextToBody("Path ok.");
  192. if (fileop.Equals(FileOperationRequirement.READWRITE))
  193. {
  194. try
  195. {
  196. string testpath = di.FullName + "DICKtest.txt";
  197. File.Create(testpath);
  198. File.Delete(testpath);
  199. }
  200. catch (Exception ex)
  201. {
  202. message.AddTextToBody("Write failed for " + pathparameter);
  203. message.AddTextToBody(ex.Message);
  204. message.AddTextToBody("Reverting to default path:");
  205. message.AddTextToBody(defaultpath);
  206. return defaultpath;
  207. }
  208. }
  209. return path;
  210. }
  211. else
  212. {
  213. message.AddTextToBody("Path not valid. Using default path instead");
  214. message.AddTextToBody(defaultpath);
  215. return defaultpath;
  216. }
  217. }
  218. else
  219. {
  220. message.AddTextToBody("No " + pathparameter + " parameter set. Using the default path");
  221. message.AddTextToBody(defaultpath);
  222. return defaultpath;
  223. }
  224. }
  225. /// <summary>
  226. ///
  227. /// </summary>
  228. /// <returns></returns>
  229. /// <exclude></exclude>
  230. protected static MessageToken InitializeEngine()
  231. {
  232. return InitializeEngine(null);
  233. }
  234. /// <summary>
  235. ///
  236. /// </summary>
  237. /// <returns></returns>
  238. /// <exclude></exclude>
  239. protected static MessageToken InitializeEngine(string workdirectory)
  240. {
  241. MessageToken msg = new MessageToken();
  242. if (workdirectory == null)
  243. {
  244. workdirectory = InstallDirectory;
  245. }
  246. BaseDirectory = workdirectory; //USE WORKING DIRECTORY AS DEFAULT
  247. msg.AddTextToBody("Working directory of this application is: " + BaseDirectory);
  248. BaseDirectory = CheckDirectory("basedirectory", BaseDirectory, FileOperationRequirement.READ, ref msg);
  249. CreateMissingDirectory(BaseDirectory);
  250. //SET DEFAULTS, CHECK FOR PATH PARAMETERS AND SET NEW PATHS WHEN NECESSARY
  251. confdirectory = CheckDirectory("configurationdirectory", BaseDirectory + @"etc\", FileOperationRequirement.READ, ref msg);
  252. SystemConfigurationDirectory = CheckDirectory("systemdirectory", confdirectory + @"systems\", FileOperationRequirement.READ, ref msg);
  253. CreateMissingDirectory(SystemConfigurationDirectory);
  254. //BY DEFAULT, LOG FILES WILL BE STORED IN THE LOGS FOLDER UNDER THE WORK DIRECTORY
  255. //OTHER FOLDERS REFERRED TO HERE WILL BE BY DEFAULT UNDER THE BASEDIRECTORY (WHICH MAY BE ELSEWHERE THAN UNDER THE WORK DIRECTORY)
  256. LogDirectory = CheckDirectory("logdirectory", workdirectory + @"logs\", FileOperationRequirement.READWRITE, ref msg);
  257. CreateMissingDirectory(LogDirectory);
  258. exportjobdirectory = @confdirectory + @"exportjobs\";
  259. CreateMissingDirectory(exportjobdirectory);
  260. importjobdirectory = @confdirectory + @"importjobs\";
  261. CreateMissingDirectory(importjobdirectory);
  262. genericjobdirectory = @confdirectory + @"genericjobs\";
  263. pythonjobdirectory = @confdirectory + @"pythonjobs\";
  264. CreateMissingDirectory(pythonjobdirectory);
  265. TemplateDirectory = CheckDirectory("templatedirectory", @confdirectory + @"templates\", FileOperationRequirement.READ, ref msg);
  266. CreateMissingDirectory(templatedirectory);
  267. scriptdirectory = Engine.confdirectory + @"scripts\";
  268. CreateMissingDirectory(scriptdirectory);
  269. msg.OK = true;
  270. bool ok = true;
  271. DirectoryInfo di = new DirectoryInfo(LogDirectory);
  272. if (di.Exists)
  273. {
  274. try
  275. {
  276. using (StreamWriter initWriter = new StreamWriter(di.FullName + "init.log", false))
  277. {
  278. initWriter.WriteLine("init started.");
  279. // READ SYSTEM CONFIGURATION
  280. ArrayList errorMessages = new ArrayList();
  281. initWriter.WriteLine("Configuration directory is " + Engine.confdirectory + ".");
  282. initWriter.WriteLine("Calling initializeApplication...");
  283. initWriter.Flush();
  284. //Only initiate the instance if it's not been done already
  285. //B1Engine sets the instance of Engine to itself before calling this method.
  286. if (instance == null)
  287. {
  288. instance=new Engine();
  289. }
  290. MessageToken result = instance.ReloadSystemConfigurations();
  291. if (!result.OK)
  292. {
  293. initWriter.WriteLine("Engine.InitializeEngine: Failed to load Configuration parameters.");
  294. initWriter.WriteLine(result.GetMessageBody());
  295. msg.OK = false;
  296. ok = false;
  297. return msg;
  298. }
  299. instance.InitializeNVelocity(initWriter);
  300. if (ok)
  301. {
  302. instance.LogInfo("DICK initialized successfully on " + DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss."));
  303. // Siirretty: NVelocity.App.Velocity.SetProperty("file.resource.loader.path", TemplateDirectory);
  304. }
  305. else
  306. {
  307. msg.Header = "Startup failed";
  308. msg.AddTextToBody("Error in initialization:\r" + msg.GetMessageBody());
  309. msg.OK = false;
  310. }
  311. initWriter.WriteLine(ok ? "succeeded" : "failed");
  312. initWriter.WriteLine("I've done my job. See the velocity and DICK logs for more details.");
  313. return msg;
  314. }
  315. }
  316. catch (Exception ex)
  317. {
  318. msg.AddTextToBody("Engine.CoreInit: An unexpected error occurred.");
  319. msg.OK = false;
  320. msg.AddTextToBody(ex.Message);
  321. msg.AddTextToDetails(ex.StackTrace);
  322. return msg;
  323. }
  324. }
  325. else
  326. {
  327. msg.AddTextToBody("Engine.InitializeEngine: The log directory " + di.FullName + " does not exist!");
  328. msg.OK = false;
  329. return msg;
  330. }
  331. }
  332. private static void CreateMissingDirectory(string dirpath)
  333. {
  334. DirectoryInfo dir = new DirectoryInfo(dirpath);
  335. if (!dir.Exists)
  336. {
  337. dir.Create();
  338. }
  339. }
  340. /// <summary>
  341. /// Sets the login parameters of Engine according to the system configuration specified by systemID.
  342. /// </summary>
  343. /// <param name="systemID">ID of the system configuration to be loaded</param>
  344. /// <returns>A MessageToken that contains detailed information of the end result</returns>
  345. public MessageToken LoadSystemParameters(string systemID)
  346. {
  347. MessageToken res = new MessageToken();
  348. if (this.systemlookup.ContainsKey(systemID))
  349. {
  350. SystemConfiguration system = this.systemlookup[systemID];
  351. //TODO connectionString = system.ConnectionString;
  352. User = system.User;
  353. if (system.Password.StartsWith("FILE!!"))
  354. {
  355. using (StreamReader pwReader = new StreamReader(system.Password.Substring(6)))
  356. {
  357. Password = pwReader.ReadLine();
  358. }
  359. }
  360. else
  361. {
  362. Password = system.Password;
  363. }
  364. useTrusted = system.UseTrusted;
  365. forceDB = system.ForceDB;
  366. Db = system.DataBase;
  367. dbusername = system.DBUserName;
  368. dbpwd = system.DBPassword;
  369. Host = system.Server;
  370. LicenseServer = system.LicenseServer;
  371. dataservertype = system.DBServerType;
  372. loglevel = system.LogLevel;
  373. connectionString = system.ConnectionString;
  374. res.OK = true;
  375. }
  376. else
  377. {
  378. string message = "System ID " + systemID + " was not found. Please check that you have the correct ID";
  379. res.AddTextToBody(message);
  380. LogDebug(message);
  381. res.OK = false;
  382. }
  383. return res;
  384. }
  385. /// <summary>
  386. /// Reloads all the system configurations from the system directory.
  387. /// </summary>
  388. /// <returns>A MessageToken that gives detailed information about the end result.</returns>
  389. public MessageToken ReloadSystemConfigurations()
  390. {
  391. systems.Clear();
  392. systemlookup.Clear();
  393. MessageToken res = new MessageToken();
  394. res.OK = true;
  395. DirectoryInfo di = new DirectoryInfo(SystemConfigurationDirectory);
  396. if (di.Exists)
  397. {
  398. FileInfo[] files = di.GetFiles("*.xml");
  399. if (files.Length > 0)
  400. {
  401. foreach (FileInfo fi in files)
  402. {
  403. XmlDocument doc = new XmlDocument();
  404. try
  405. {
  406. doc.Load(fi.FullName);
  407. string sysid = fi.Name.Substring(0, fi.Name.Length - 4);
  408. SystemConfiguration config = new SystemConfiguration(sysid, doc.DocumentElement);
  409. if (config != null)
  410. {
  411. systemlookup.Add(sysid, config);
  412. systems.Add(config);
  413. }
  414. }
  415. catch (Exception ex)
  416. {
  417. res.AddTextToBody("Failed processing XML in file " + fi.FullName + ". Message:" + ex.Message);
  418. }
  419. }
  420. if (systems.Count == 0)
  421. {
  422. res.OK = false;
  423. res.AddTextToBody("There were no valid system configuration files in folder " + di.FullName);
  424. }
  425. SystemConfiguration defaultsystem = SystemConfiguration.GetNullConfiguration();
  426. systems.Add(defaultsystem);
  427. systemlookup.Add(defaultsystem.SystemID, defaultsystem);
  428. }
  429. else
  430. {
  431. res.AddTextToBody("There are no system configuration files in directory " + SystemConfigurationDirectory + ". Exiting.");
  432. res.OK = false;
  433. }
  434. }
  435. else
  436. {
  437. res.AddTextToBody("Directory " + SystemConfigurationDirectory + " does not exist. Exiting.");
  438. res.OK = false;
  439. }
  440. return res;
  441. }
  442. private MessageToken InitializeNVelocity(StreamWriter initWriter)
  443. {
  444. //Intialize the Velocity Template Engine
  445. try
  446. {
  447. NVelocity.App.Velocity.Init(confdirectory + "nvelocity.properties");
  448. initWriter.WriteLine("Velocity initialized with " + confdirectory + "nvelocity.properties");
  449. initWriter.WriteLine("Overriding file.resource.loader.path from nvelocity.properties with:");
  450. initWriter.WriteLine(TemplateDirectory);
  451. NVelocity.App.Velocity.SetProperty("file.resource.loader.path", TemplateDirectory);
  452. }
  453. catch (Exception ex)
  454. {
  455. initWriter.Write("FATAL ERROR! Initialization of the template engine failed.");
  456. initWriter.Write("Please check that the templateengineproperties value is correctly set in DICK.xml");
  457. initWriter.Write(ex.StackTrace);
  458. }
  459. MessageToken result = new MessageToken();
  460. OpenNewLogFile(result, loglevel);
  461. //TODO add possible changes to result ?
  462. return result;
  463. }
  464. /// <summary>
  465. /// Closes the current log file and starts a new one
  466. /// </summary>
  467. /// <param name="result">A MessageToken for returning the result of the operation.</param>
  468. /// <param name="loglevel">The log level to be used: ERROR, INFO, DEBUG </param>
  469. public static void OpenNewLogFile(MessageToken result, string loglevel)
  470. {
  471. string logfilename = ("DICK_log_" + DateTime.Now.ToString("yyyyMMddHHmmssff")).Replace(@"\", @"\\") + ".log";
  472. result.AddTextToBody("Setting default logpath: " + Engine.LogDirectory + logfilename);
  473. OpenNewLogFile(result, loglevel, logfilename, Engine.LogDirectory);
  474. }
  475. public static void OpenNewLogFile(string loglevel)
  476. {
  477. string logfilename = ("DICK_log_" + DateTime.Now.ToString("yyyyMMddHHmmssff")) + ".log";//.Replace(@"\", @"\\")
  478. OpenNewLogFile(loglevel, logfilename, Engine.LogDirectory);
  479. }
  480. public static void OpenNewLogFile(string loglevel, string logfilename)
  481. {
  482. OpenNewLogFile(loglevel, logfilename, Engine.LogDirectory);
  483. }
  484. public static void OpenNewLogFile(string loglevel, string logfilename, string logdirectory)
  485. {
  486. MessageToken result = new MessageToken();
  487. result.AddTextToBody("Setting default logpath: " + Engine.LogDirectory + logfilename);
  488. OpenNewLogFile(result, loglevel, logfilename, logdirectory);
  489. }
  490. public static void OpenNewLogFile(MessageToken result, string loglevel, string logfilename)
  491. {
  492. result.AddTextToBody("Setting default logdirectory: " + Engine.LogDirectory + " with filename:" + logfilename);
  493. OpenNewLogFile(result, loglevel, logfilename, Engine.LogDirectory);
  494. }
  495. public static void OpenNewLogFile(MessageToken result, string loglevel, string logfilename, string logdirectory)
  496. {
  497. //Initialize the Log4NET environment
  498. NVelocity.VelocityContext log4NetContext = new NVelocity.VelocityContext();
  499. log4NetContext.Put("logpath", (logdirectory + logfilename).Replace(@"\", @"\\"));
  500. log4NetContext.Put("loglevel", loglevel);
  501. System.IO.StringWriter logparameters = new System.IO.StringWriter(new System.Text.StringBuilder());
  502. try
  503. {
  504. NVelocity.App.Velocity.MergeTemplate("log4net.vm", log4NetContext, logparameters);
  505. logparameters.Flush();
  506. System.Xml.XmlDocument doc = new XmlDocument();
  507. doc.LoadXml(logparameters.ToString());
  508. log4net.Config.DOMConfigurator.Configure(doc.DocumentElement);
  509. }
  510. catch (System.Exception ex)
  511. {
  512. result.AddTextToBody("FATAL ERROR! Unable to initialize the Log4NET environment.");
  513. result.AddTextToDetails(ex.Message);
  514. result.AddTextToDetails(ex.StackTrace);
  515. result.OK = false;
  516. }
  517. }
  518. /// <summary>
  519. /// Returns a list of ExportJobs. Used by the DICK Client for displaying the available jobs.
  520. /// </summary>
  521. /// <returns>A list of ExportJobs loaded to memory</returns>
  522. public List<ExportJob> ListExports()
  523. {
  524. DirectoryInfo di = new DirectoryInfo(exportjobdirectory);
  525. System.Collections.Generic.List<ExportJob> exports = new System.Collections.Generic.List<ExportJob>();
  526. if (di.Exists)
  527. {
  528. FileInfo[] exportfiles = di.GetFiles("*.xml");
  529. foreach (FileInfo file in exportfiles)
  530. {
  531. XmlDocument doc = new XmlDocument();
  532. doc.Load(file.FullName);
  533. try
  534. {
  535. exports.Add(new ExportJob(file.Name.Substring(0, file.Name.Length - 4), doc.DocumentElement));
  536. }
  537. catch (Exception ex)
  538. {
  539. Engine.GetInstance().LogDebug("Failed to initialize ExportJob " + file.Name + ". Errormessage:" + ex.Message);
  540. }
  541. }
  542. }
  543. else
  544. {
  545. LogError("The exportjob directory " + di.FullName + " does not exist! ");
  546. }
  547. return exports;
  548. }
  549. public List<GenericJob> ListOtherJobs()
  550. {
  551. List<GenericJob> jobs = new List<GenericJob>();
  552. DirectoryInfo di = new DirectoryInfo(genericjobdirectory);
  553. if (di.Exists)
  554. {
  555. FileInfo[] files = di.GetFiles("*.xml");
  556. foreach (FileInfo file in files)
  557. {
  558. XmlDocument doc = new XmlDocument();
  559. doc.Load(file.FullName);
  560. try
  561. {
  562. jobs.Add(new GenericJob(file.Name.Substring(0, file.Name.Length - 4), doc.DocumentElement));
  563. }
  564. catch (Exception ex)
  565. {
  566. Engine.GetInstance().LogDebug("Failed to initialize GenericJob " + file.Name + ". Errormessage:" + ex.Message);
  567. }
  568. }
  569. }
  570. else
  571. {
  572. LogError("The genericjob directory " + di.FullName + " does not exist! ");
  573. }
  574. return jobs;
  575. }
  576. #region Current Job Management
  577. /*public ExportJob SetCurrentExportJob(string epName)
  578. {
  579. ExportJob job=GetExportJob(epName);
  580. if (job != null)
  581. {
  582. currentExportJob = job;
  583. return job;
  584. }
  585. else
  586. {
  587. LogError("SetCurrentExportJob: Could not create job " + epName);
  588. return null;
  589. }
  590. }
  591. public ExportJob GetCurrentExportJob()
  592. {
  593. if (currentExportJob == null)
  594. {
  595. LogError("ENGINE.currentExportJob is NULL!!!");
  596. return null;
  597. }
  598. return currentExportJob;
  599. }*/
  600. public ExportJob GetExportJob(string name)
  601. {
  602. if (name != null && name.Trim().Length > 0)
  603. {
  604. FileInfo fi = new FileInfo(exportjobdirectory + name + ".xml");
  605. if (fi.Exists)
  606. {
  607. XmlDocument doc = new XmlDocument();
  608. try
  609. {
  610. doc.Load(fi.FullName);
  611. //Calling the virtual method here - it's overridden in B1Engine
  612. return GetRealJob(name, doc.DocumentElement);
  613. }
  614. catch (XmlException xex)
  615. {
  616. LogError("Failed parsing the xml document for ExportJob " + name + ":" + xex.Message);
  617. return null;
  618. }
  619. }
  620. else
  621. {
  622. LogError("ExportJob " + fi.FullName + " not found!");
  623. return null;
  624. }
  625. }
  626. else
  627. {
  628. LogError("ENGINE.GETEXPORTJOB: job name is null or empty !!!!");
  629. return null;
  630. }
  631. }
  632. /// <summary>
  633. ///
  634. /// </summary>
  635. /// <param name="jobid"></param>
  636. /// <param name="exp"></param>
  637. /// <returns></returns>
  638. /// <exclude/>
  639. protected virtual ExportJob GetRealJob(string jobid, XmlElement exp)
  640. {
  641. return new ExportJob(jobid, exp);
  642. }
  643. /*public ExportJob CurrentExportJob
  644. {
  645. get { return currentExportJob; }
  646. set { currentExportJob = value; }
  647. }*/
  648. private string currentGenericJob;
  649. public string CurrentGenericJob
  650. {
  651. get { return currentGenericJob; }
  652. set { currentGenericJob = value; }
  653. }
  654. public GenericJob SetCurrentGenericJob(string jobName)
  655. {
  656. currentGenericJob = jobName;
  657. return GetGenericJob(jobName);
  658. }
  659. public GenericJob GetCurrentGenericJob()
  660. {
  661. return GetGenericJob(currentGenericJob);
  662. }
  663. public GenericJob GetGenericJob(string name)
  664. {
  665. FileInfo fi = new FileInfo(genericjobdirectory + name + ".xml");
  666. if (fi.Exists)
  667. {
  668. XmlDocument doc = new XmlDocument();
  669. try
  670. {
  671. doc.Load(fi.FullName);
  672. return new GenericJob(name, doc.DocumentElement);
  673. }
  674. catch (XmlException xex)
  675. {
  676. LogError("Failed parsing the xml document for GenericJob " + name + ":" + xex.Message);
  677. return null;
  678. }
  679. }
  680. else
  681. {
  682. LogError("GenericJob " + fi.FullName + " not found!");
  683. return null;
  684. }
  685. }
  686. #endregion
  687. #region Log file management
  688. /// <summary>
  689. /// Adds DEBUG level information to the currently open log.
  690. /// </summary>
  691. /// <param name="value">Information to be logged</param>
  692. public void LogDebug(string value)
  693. {
  694. docLog.Debug(value);
  695. }
  696. /// <summary>
  697. /// Adds INFO level information to the currently open log.
  698. /// </summary>
  699. /// <param name="value">Information to be logged</param>
  700. public void LogInfo(string value)
  701. {
  702. docLog.Info(value);
  703. }
  704. /// <summary>
  705. /// Adds WARN level information to the currently open log.
  706. /// </summary>
  707. /// <param name="value">Information to be logged</param>
  708. public void LogWarn(string value)
  709. {
  710. docLog.Warn(value);
  711. }
  712. /// <summary>
  713. /// Adds ERROR level information to the currently open log.
  714. /// </summary>
  715. /// <param name="value">Information to be logged</param>
  716. public void LogError(string value)
  717. {
  718. docLog.Error(value);
  719. }
  720. public void SpitFile(string path, string value)
  721. {
  722. using (StreamWriter sw = File.CreateText(@path))
  723. {
  724. sw.WriteLine(value);
  725. sw.Close();
  726. }
  727. }
  728. /// <summary>
  729. /// Adds INFO level information to the currently open log.
  730. /// </summary>
  731. /// <param name="value">The MessageToken that contains the error information in header and body</param>
  732. public void LogErrorMessage(MessageToken message)
  733. {
  734. LogError(message.Header);
  735. LogError(message.GetMessageBody());
  736. }
  737. /// <summary>
  738. ///Used to delete files in a particular directory based on the time stamp selected by the user.
  739. ///Adapted from code written By Arunkumar Viswanathan.
  740. /// </summary>
  741. /// <param name="usrDir">Directory in which the files exist</param>
  742. /// <param name="intDays">Number of days since the file was created</param>
  743. /// <param name="intHours">Number of hours</param>
  744. /// <param name="intMinutes">Number of minutes</param>
  745. /// <param name="intSeconds">Number of seconds</param>
  746. ///
  747. /// License: Anybody can use it and modify it. You can refer Mr. Viswanathan's name in your code
  748. /// if you are kind enough :))))
  749. public static void RemoveFilesByTimeStamp(string usrDir, int intDays, int intHours, int intMinutes, int intSeconds)
  750. {
  751. Engine engine = Engine.GetInstance();
  752. DirectoryInfo dirInfo = new DirectoryInfo(usrDir);
  753. try
  754. {
  755. if (!dirInfo.Exists)
  756. {
  757. engine.LogError("The directory " + usrDir + " does not exist!");
  758. }
  759. else
  760. {
  761. foreach (FileInfo f in dirInfo.GetFiles())
  762. {
  763. DateTime systemDt = DateTime.Now;
  764. DateTime fileDt = f.LastWriteTime;
  765. DateTime cpmTime;
  766. //IF SYSTEM TIME < FILE WRITE TIME - send a warning message since anyway the file won't be deleted with the current logic
  767. if (f.LastWriteTime > systemDt)
  768. engine.LogError("Someone messed the system clock or the file write time was in a different time zone!!!");
  769. TimeSpan customTSpan = new TimeSpan(intDays, intHours, intMinutes, intSeconds);
  770. cpmTime = fileDt + customTSpan;
  771. //CHECKING IF THE FILE LIFE TIME IS MORE THAN THE CURRENT SYSTEM TIME. IF YES FILE IS VALID
  772. if (DateTime.Compare(cpmTime, systemDt) > 0)
  773. engine.LogDebug("Still Valid!");
  774. else //CHECKING IF THE FILE LIFE TIME IS <= THE CURRENT SYSTEM TIME. IF YES - FILE IS SET FOR DELETION
  775. {
  776. engine.LogInfo("Deleting:" + f.Name);
  777. f.Delete();
  778. engine.LogInfo("File " + f.Name + " has been deleted!");
  779. }
  780. }
  781. }
  782. }
  783. catch (Exception exp)
  784. {
  785. engine.LogError("Engine.RemoveFilesByTimeStamp Failed:" + exp.Message);
  786. }
  787. }
  788. #endregion
  789. #region external processes
  790. /// <summary>
  791. /// Opens the given directory path in Windows Explorer
  792. /// </summary>
  793. /// <param name="directorypath">The path to open</param>
  794. /// <returns>A process handle (or null if the call fails.)</returns>
  795. public static Process Explore(string directorypath)
  796. {
  797. InitializeEngine();
  798. try
  799. {
  800. return Process.Start("explorer.exe", directorypath);
  801. }
  802. catch (Exception ex)
  803. {
  804. GetInstance().LogError("Failed to start Windows Explorer:" + ex.Message);
  805. return null;
  806. }
  807. }
  808. /// <summary>
  809. /// Starts an external application
  810. /// </summary>
  811. /// <param name="path">The path/filename of the application</param>
  812. /// <param name="arguments">Commandline arguments</param>
  813. /// <returns>A boolean value indicating if the call succeeded.</returns>
  814. public static bool StartApplication(string path, string arguments)
  815. {
  816. try
  817. {
  818. GetInstance().LogDebug("Starting application " + path + " with arguments " + arguments);
  819. Process p = new Process();
  820. p.StartInfo.FileName = path;
  821. p.StartInfo.Arguments = arguments;
  822. return p.Start();
  823. }
  824. catch (Exception ex)
  825. {
  826. GetInstance().LogError("Failed to start application " + path + ":" + ex.Message);
  827. return false;
  828. }
  829. }
  830. #endregion
  831. public string ToString()
  832. {
  833. StringBuilder sb = new StringBuilder();
  834. sb.AppendLine("DICK version: " + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString());
  835. sb.AppendLine("Installed in:" + InstallDirectory);
  836. sb.AppendLine("Current base directory: "+ Engine.BaseDirectory);
  837. sb.AppendLine("Active configuration directory:" + Engine.confdirectory);
  838. sb.AppendLine("System directory:" + Engine.SystemConfigurationDirectory);
  839. sb.AppendLine("Active templates directory:" + Engine.TemplateDirectory);
  840. sb.AppendLine("Active script directory:" + Engine.scriptdirectory);
  841. sb.AppendLine("Active log directory:" + Engine.LogDirectory);
  842. sb.AppendLine("Active Export job directory:" + Engine.exportjobdirectory);
  843. sb.AppendLine("Active Import job directory:" + Engine.importjobdirectory);
  844. sb.AppendLine("Active Generic job directory:" + Engine.scriptdirectory);
  845. sb.AppendLine("Active Python job directory:" + Engine.pythonjobdirectory);
  846. return sb.ToString();
  847. }
  848. }
  849. }