/DICK.Core/Engine.cs
C# | 922 lines | 681 code | 72 blank | 169 comment | 39 complexity | 9677ca8ed8d7be2886ed90a1db419e93 MD5 | raw file
- /* This file is part of DI Construction Kit.
- *
- * DI Construction Kit is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Lesser General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * DI Construction Kit is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with DI Construction Kit. If not, see <http://www.gnu.org/licenses/>.
- *
- */
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Xml;
- using System.Xml.Schema;
- using System.IO;
- using System.Diagnostics;
- using System.Data;
- using System.Reflection;
- using Microsoft.CSharp;
- using System.CodeDom.Compiler;
- using System.Text;
- using System.Text.RegularExpressions;
- using System.Web;
- using DICK.Core.JobManagement;
-
- namespace DICK.Core
- {
- /// <summary>
- /// Engine is a singleton class that manages those core functionalities of DICK that are independent of DI API and IronPython.
- /// These functions include log management, job management, system configurations management, configuration directory settings.
- /// DICK.B1.B1Engine extends this class.
- /// </summary>
- /// <seealso cref="B1Engine"/>
-
- public class Engine
- {
- private static log4net.ILog docLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
- public static readonly string VERSIONTEXT = "DI Construction Kit R2.01";
- /// <summary>
- /// Singleton instance of Engine. Visibility is set to protected because B1Engine inheritss this class.
- /// </summary>
- private static Engine instance;
- private static string basedirectory;
- protected static FileHelpers.FileHelperEngine filehelpersengine;
- private static readonly string installDirectory = AppDomain.CurrentDomain.BaseDirectory;
-
- /// <summary>
- /// Returns the directory path where the DICK binaries are installed.
- /// </summary>
- public static string InstallDirectory
- {
- get { return Engine.installDirectory; }
- }
-
- protected static void SetInstance(Engine _instance)
- {
- //Do not set an initialized instance to null
- if (instance != null && _instance == null)
- {
- throw new DICKException();
- }
- else
- {
- instance = _instance;
- }
- }
-
- public static string BaseDirectory
- {
- get { return Engine.basedirectory; }
- set { Engine.basedirectory = value; }
- }
- public static string confdirectory;
- private static string systemconfigurationdirectory;
-
- public static string scriptdirectory;
-
- public static string SystemConfigurationDirectory
- {
- get { return Engine.systemconfigurationdirectory; }
- set { Engine.systemconfigurationdirectory = value; }
- }
- private static string logdirectory;
-
- public static string LogDirectory
- {
- get { return Engine.logdirectory; }
- set { Engine.logdirectory = value; }
- }
- private static string templatedirectory;
-
- public static string TemplateDirectory
- {
- get { return templatedirectory; }
- set { templatedirectory = value; }
- }
- public static string exportjobdirectory;
- public static string importjobdirectory;
- public static string genericjobdirectory;
- public static string pythonjobdirectory;
-
- public string Db
- {
- get;
- set;
- }
-
- public string User
- {
- get;
- set;
- }
-
- /// <summary>
- /// Overridden in B1Engine
- /// </summary>
- public string Password { get; set; }
- public string Host { get; set; }
- public string LicenseServer { get; set; }
- public bool autologin;
- public bool forceDB;
- private bool useTrusted;
-
- public bool UseTrusted
- {
- get { return useTrusted; }
- set { useTrusted = value; }
- }
- public string dbusername;
- public string dbpwd;
- public string dataservertype;
- private string connectionString;
-
- public string ConnectionString
- {
- get { return connectionString; }
- set { connectionString = value; }
- }
- public Dictionary<string, string> Parameters;
- //private ExportJob currentExportJob;
-
- public string loglevel;
-
-
- public enum FileOperationRequirement { READ, READWRITE };
-
- public SortedDictionary<string, SystemConfiguration> systemlookup = new SortedDictionary<string, SystemConfiguration>();
- public List<SystemConfiguration> systems = new List<SystemConfiguration>();
-
- private System.Collections.Generic.Dictionary<string, object> context = new Dictionary<string, object>();
-
- public object GetFromContext(string key)
- {
- return context[key];
- }
-
- public void AddToContext(string key, object _value)
- {
- context[key] = _value;
- }
-
- public void RemoveFromContext(string key)
- {
- context[key] = null;
- }
-
- /// <summary>
- /// The constructor is protected in order to implement a singleton pattern but enables subclassing by B1.B1Engine
- /// </summary>
- protected Engine()
- { }
-
- /// <summary>
- /// Used to retrieve the singleton instance of Engine. The singleton is initialized when this method is called for the first time.
- /// </summary>
- /// <returns>The singleton instance of Engine.</returns>
- public static Engine GetInstance()
- {
- if (instance == null)
- {
- InitializeEngine();
- if (instance != null)
- {
- instance.LogDebug("GETINSTANCE: ENGINE INITIALIZED !!");
- }
- }
- return instance;
- }
-
- /// <summary>
- /// 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.
- /// </summary>
- /// <param name="pathparameter">The parameter that holds the path to be checked.</param>
- /// <param name="defaultpath">The default path that is to be used if the result of the test is negative.</param>
- /// <param name="fileop">Required file operation (read/write)</param>
- /// <param name="message">A MessageToken instance that is used to pass detailed information to the caller.</param>
- /// <returns></returns>
- public static string CheckDirectory(string pathparameter, string defaultpath, FileOperationRequirement fileop, ref MessageToken message)
- {
- message.AddTextToBody("Checking for parameter " + pathparameter + "...");
- string path = System.Configuration.ConfigurationManager.AppSettings[pathparameter];
- if (path != null && !path.Trim().Equals(""))
- {
- message.AddTextToBody("Found " + path);
- message.AddTextToBody("Validating path...");
- DirectoryInfo di = new DirectoryInfo(path);
- if (di.Exists)
- {
- message.AddTextToBody("Path ok.");
- if (fileop.Equals(FileOperationRequirement.READWRITE))
- {
- try
- {
- string testpath = di.FullName + "DICKtest.txt";
- File.Create(testpath);
- File.Delete(testpath);
- }
- catch (Exception ex)
- {
- message.AddTextToBody("Write failed for " + pathparameter);
- message.AddTextToBody(ex.Message);
- message.AddTextToBody("Reverting to default path:");
- message.AddTextToBody(defaultpath);
- return defaultpath;
- }
- }
- return path;
- }
- else
- {
- message.AddTextToBody("Path not valid. Using default path instead");
- message.AddTextToBody(defaultpath);
- return defaultpath;
- }
- }
- else
- {
- message.AddTextToBody("No " + pathparameter + " parameter set. Using the default path");
- message.AddTextToBody(defaultpath);
- return defaultpath;
- }
- }
-
- /// <summary>
- ///
- /// </summary>
- /// <returns></returns>
- /// <exclude></exclude>
- protected static MessageToken InitializeEngine()
- {
- return InitializeEngine(null);
- }
-
- /// <summary>
- ///
- /// </summary>
- /// <returns></returns>
- /// <exclude></exclude>
- protected static MessageToken InitializeEngine(string workdirectory)
- {
- MessageToken msg = new MessageToken();
- if (workdirectory == null)
- {
- workdirectory = InstallDirectory;
- }
- BaseDirectory = workdirectory; //USE WORKING DIRECTORY AS DEFAULT
- msg.AddTextToBody("Working directory of this application is: " + BaseDirectory);
- BaseDirectory = CheckDirectory("basedirectory", BaseDirectory, FileOperationRequirement.READ, ref msg);
- CreateMissingDirectory(BaseDirectory);
-
- //SET DEFAULTS, CHECK FOR PATH PARAMETERS AND SET NEW PATHS WHEN NECESSARY
- confdirectory = CheckDirectory("configurationdirectory", BaseDirectory + @"etc\", FileOperationRequirement.READ, ref msg);
- SystemConfigurationDirectory = CheckDirectory("systemdirectory", confdirectory + @"systems\", FileOperationRequirement.READ, ref msg);
- CreateMissingDirectory(SystemConfigurationDirectory);
-
- //BY DEFAULT, LOG FILES WILL BE STORED IN THE LOGS FOLDER UNDER THE WORK DIRECTORY
- //OTHER FOLDERS REFERRED TO HERE WILL BE BY DEFAULT UNDER THE BASEDIRECTORY (WHICH MAY BE ELSEWHERE THAN UNDER THE WORK DIRECTORY)
- LogDirectory = CheckDirectory("logdirectory", workdirectory + @"logs\", FileOperationRequirement.READWRITE, ref msg);
-
- CreateMissingDirectory(LogDirectory);
- exportjobdirectory = @confdirectory + @"exportjobs\";
- CreateMissingDirectory(exportjobdirectory);
- importjobdirectory = @confdirectory + @"importjobs\";
- CreateMissingDirectory(importjobdirectory);
- genericjobdirectory = @confdirectory + @"genericjobs\";
- pythonjobdirectory = @confdirectory + @"pythonjobs\";
- CreateMissingDirectory(pythonjobdirectory);
- TemplateDirectory = CheckDirectory("templatedirectory", @confdirectory + @"templates\", FileOperationRequirement.READ, ref msg);
- CreateMissingDirectory(templatedirectory);
- scriptdirectory = Engine.confdirectory + @"scripts\";
- CreateMissingDirectory(scriptdirectory);
- msg.OK = true;
- bool ok = true;
-
- DirectoryInfo di = new DirectoryInfo(LogDirectory);
- if (di.Exists)
- {
- try
- {
- using (StreamWriter initWriter = new StreamWriter(di.FullName + "init.log", false))
- {
- initWriter.WriteLine("init started.");
- // READ SYSTEM CONFIGURATION
- ArrayList errorMessages = new ArrayList();
- initWriter.WriteLine("Configuration directory is " + Engine.confdirectory + ".");
- initWriter.WriteLine("Calling initializeApplication...");
- initWriter.Flush();
- //Only initiate the instance if it's not been done already
- //B1Engine sets the instance of Engine to itself before calling this method.
- if (instance == null)
- {
- instance=new Engine();
- }
- MessageToken result = instance.ReloadSystemConfigurations();
-
- if (!result.OK)
- {
- initWriter.WriteLine("Engine.InitializeEngine: Failed to load Configuration parameters.");
- initWriter.WriteLine(result.GetMessageBody());
- msg.OK = false;
- ok = false;
- return msg;
- }
- instance.InitializeNVelocity(initWriter);
- if (ok)
- {
- instance.LogInfo("DICK initialized successfully on " + DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss."));
- // Siirretty: NVelocity.App.Velocity.SetProperty("file.resource.loader.path", TemplateDirectory);
- }
- else
- {
- msg.Header = "Startup failed";
- msg.AddTextToBody("Error in initialization:\r" + msg.GetMessageBody());
- msg.OK = false;
- }
- initWriter.WriteLine(ok ? "succeeded" : "failed");
- initWriter.WriteLine("I've done my job. See the velocity and DICK logs for more details.");
- return msg;
- }
- }
- catch (Exception ex)
- {
- msg.AddTextToBody("Engine.CoreInit: An unexpected error occurred.");
- msg.OK = false;
- msg.AddTextToBody(ex.Message);
- msg.AddTextToDetails(ex.StackTrace);
- return msg;
- }
- }
- else
- {
- msg.AddTextToBody("Engine.InitializeEngine: The log directory " + di.FullName + " does not exist!");
- msg.OK = false;
- return msg;
- }
- }
-
- private static void CreateMissingDirectory(string dirpath)
- {
- DirectoryInfo dir = new DirectoryInfo(dirpath);
- if (!dir.Exists)
- {
- dir.Create();
- }
- }
-
- /// <summary>
- /// Sets the login parameters of Engine according to the system configuration specified by systemID.
- /// </summary>
- /// <param name="systemID">ID of the system configuration to be loaded</param>
- /// <returns>A MessageToken that contains detailed information of the end result</returns>
- public MessageToken LoadSystemParameters(string systemID)
- {
- MessageToken res = new MessageToken();
- if (this.systemlookup.ContainsKey(systemID))
- {
- SystemConfiguration system = this.systemlookup[systemID];
- //TODO connectionString = system.ConnectionString;
- User = system.User;
- if (system.Password.StartsWith("FILE!!"))
- {
- using (StreamReader pwReader = new StreamReader(system.Password.Substring(6)))
- {
- Password = pwReader.ReadLine();
- }
- }
- else
- {
- Password = system.Password;
- }
- useTrusted = system.UseTrusted;
- forceDB = system.ForceDB;
- Db = system.DataBase;
- dbusername = system.DBUserName;
- dbpwd = system.DBPassword;
- Host = system.Server;
- LicenseServer = system.LicenseServer;
- dataservertype = system.DBServerType;
- loglevel = system.LogLevel;
- connectionString = system.ConnectionString;
- res.OK = true;
- }
- else
- {
- string message = "System ID " + systemID + " was not found. Please check that you have the correct ID";
- res.AddTextToBody(message);
- LogDebug(message);
- res.OK = false;
- }
- return res;
- }
-
- /// <summary>
- /// Reloads all the system configurations from the system directory.
- /// </summary>
- /// <returns>A MessageToken that gives detailed information about the end result.</returns>
- public MessageToken ReloadSystemConfigurations()
- {
- systems.Clear();
- systemlookup.Clear();
- MessageToken res = new MessageToken();
- res.OK = true;
- DirectoryInfo di = new DirectoryInfo(SystemConfigurationDirectory);
- if (di.Exists)
- {
- FileInfo[] files = di.GetFiles("*.xml");
- if (files.Length > 0)
- {
- foreach (FileInfo fi in files)
- {
- XmlDocument doc = new XmlDocument();
- try
- {
- doc.Load(fi.FullName);
- string sysid = fi.Name.Substring(0, fi.Name.Length - 4);
- SystemConfiguration config = new SystemConfiguration(sysid, doc.DocumentElement);
- if (config != null)
- {
- systemlookup.Add(sysid, config);
- systems.Add(config);
- }
- }
- catch (Exception ex)
- {
- res.AddTextToBody("Failed processing XML in file " + fi.FullName + ". Message:" + ex.Message);
- }
- }
- if (systems.Count == 0)
- {
- res.OK = false;
- res.AddTextToBody("There were no valid system configuration files in folder " + di.FullName);
- }
- SystemConfiguration defaultsystem = SystemConfiguration.GetNullConfiguration();
- systems.Add(defaultsystem);
- systemlookup.Add(defaultsystem.SystemID, defaultsystem);
- }
- else
- {
- res.AddTextToBody("There are no system configuration files in directory " + SystemConfigurationDirectory + ". Exiting.");
- res.OK = false;
- }
- }
- else
- {
- res.AddTextToBody("Directory " + SystemConfigurationDirectory + " does not exist. Exiting.");
- res.OK = false;
- }
- return res;
- }
-
-
- private MessageToken InitializeNVelocity(StreamWriter initWriter)
- {
- //Intialize the Velocity Template Engine
- try
- {
- NVelocity.App.Velocity.Init(confdirectory + "nvelocity.properties");
- initWriter.WriteLine("Velocity initialized with " + confdirectory + "nvelocity.properties");
- initWriter.WriteLine("Overriding file.resource.loader.path from nvelocity.properties with:");
- initWriter.WriteLine(TemplateDirectory);
- NVelocity.App.Velocity.SetProperty("file.resource.loader.path", TemplateDirectory);
- }
- catch (Exception ex)
- {
- initWriter.Write("FATAL ERROR! Initialization of the template engine failed.");
- initWriter.Write("Please check that the templateengineproperties value is correctly set in DICK.xml");
- initWriter.Write(ex.StackTrace);
- }
- MessageToken result = new MessageToken();
- OpenNewLogFile(result, loglevel);
- //TODO add possible changes to result ?
- return result;
- }
-
- /// <summary>
- /// Closes the current log file and starts a new one
- /// </summary>
- /// <param name="result">A MessageToken for returning the result of the operation.</param>
- /// <param name="loglevel">The log level to be used: ERROR, INFO, DEBUG </param>
- public static void OpenNewLogFile(MessageToken result, string loglevel)
- {
- string logfilename = ("DICK_log_" + DateTime.Now.ToString("yyyyMMddHHmmssff")).Replace(@"\", @"\\") + ".log";
- result.AddTextToBody("Setting default logpath: " + Engine.LogDirectory + logfilename);
- OpenNewLogFile(result, loglevel, logfilename, Engine.LogDirectory);
- }
-
- public static void OpenNewLogFile(string loglevel)
- {
- string logfilename = ("DICK_log_" + DateTime.Now.ToString("yyyyMMddHHmmssff")) + ".log";//.Replace(@"\", @"\\")
- OpenNewLogFile(loglevel, logfilename, Engine.LogDirectory);
- }
-
- public static void OpenNewLogFile(string loglevel, string logfilename)
- {
- OpenNewLogFile(loglevel, logfilename, Engine.LogDirectory);
- }
-
- public static void OpenNewLogFile(string loglevel, string logfilename, string logdirectory)
- {
- MessageToken result = new MessageToken();
- result.AddTextToBody("Setting default logpath: " + Engine.LogDirectory + logfilename);
- OpenNewLogFile(result, loglevel, logfilename, logdirectory);
- }
-
- public static void OpenNewLogFile(MessageToken result, string loglevel, string logfilename)
- {
- result.AddTextToBody("Setting default logdirectory: " + Engine.LogDirectory + " with filename:" + logfilename);
- OpenNewLogFile(result, loglevel, logfilename, Engine.LogDirectory);
- }
-
-
- public static void OpenNewLogFile(MessageToken result, string loglevel, string logfilename, string logdirectory)
- {
- //Initialize the Log4NET environment
- NVelocity.VelocityContext log4NetContext = new NVelocity.VelocityContext();
- log4NetContext.Put("logpath", (logdirectory + logfilename).Replace(@"\", @"\\"));
- log4NetContext.Put("loglevel", loglevel);
- System.IO.StringWriter logparameters = new System.IO.StringWriter(new System.Text.StringBuilder());
- try
- {
- NVelocity.App.Velocity.MergeTemplate("log4net.vm", log4NetContext, logparameters);
- logparameters.Flush();
- System.Xml.XmlDocument doc = new XmlDocument();
- doc.LoadXml(logparameters.ToString());
- log4net.Config.DOMConfigurator.Configure(doc.DocumentElement);
- }
- catch (System.Exception ex)
- {
- result.AddTextToBody("FATAL ERROR! Unable to initialize the Log4NET environment.");
- result.AddTextToDetails(ex.Message);
- result.AddTextToDetails(ex.StackTrace);
- result.OK = false;
- }
- }
-
- /// <summary>
- /// Returns a list of ExportJobs. Used by the DICK Client for displaying the available jobs.
- /// </summary>
- /// <returns>A list of ExportJobs loaded to memory</returns>
- public List<ExportJob> ListExports()
- {
- DirectoryInfo di = new DirectoryInfo(exportjobdirectory);
- System.Collections.Generic.List<ExportJob> exports = new System.Collections.Generic.List<ExportJob>();
- if (di.Exists)
- {
- FileInfo[] exportfiles = di.GetFiles("*.xml");
- foreach (FileInfo file in exportfiles)
- {
- XmlDocument doc = new XmlDocument();
- doc.Load(file.FullName);
- try
- {
- exports.Add(new ExportJob(file.Name.Substring(0, file.Name.Length - 4), doc.DocumentElement));
- }
- catch (Exception ex)
- {
- Engine.GetInstance().LogDebug("Failed to initialize ExportJob " + file.Name + ". Errormessage:" + ex.Message);
- }
- }
- }
- else
- {
- LogError("The exportjob directory " + di.FullName + " does not exist! ");
- }
- return exports;
- }
-
- public List<GenericJob> ListOtherJobs()
- {
- List<GenericJob> jobs = new List<GenericJob>();
- DirectoryInfo di = new DirectoryInfo(genericjobdirectory);
- if (di.Exists)
- {
- FileInfo[] files = di.GetFiles("*.xml");
- foreach (FileInfo file in files)
- {
- XmlDocument doc = new XmlDocument();
- doc.Load(file.FullName);
- try
- {
- jobs.Add(new GenericJob(file.Name.Substring(0, file.Name.Length - 4), doc.DocumentElement));
- }
- catch (Exception ex)
- {
- Engine.GetInstance().LogDebug("Failed to initialize GenericJob " + file.Name + ". Errormessage:" + ex.Message);
- }
- }
- }
- else
- {
- LogError("The genericjob directory " + di.FullName + " does not exist! ");
- }
- return jobs;
- }
-
- #region Current Job Management
-
- /*public ExportJob SetCurrentExportJob(string epName)
- {
- ExportJob job=GetExportJob(epName);
- if (job != null)
- {
- currentExportJob = job;
- return job;
- }
- else
- {
- LogError("SetCurrentExportJob: Could not create job " + epName);
- return null;
- }
- }
-
- public ExportJob GetCurrentExportJob()
- {
- if (currentExportJob == null)
- {
- LogError("ENGINE.currentExportJob is NULL!!!");
- return null;
- }
- return currentExportJob;
- }*/
-
- public ExportJob GetExportJob(string name)
- {
- if (name != null && name.Trim().Length > 0)
- {
- FileInfo fi = new FileInfo(exportjobdirectory + name + ".xml");
- if (fi.Exists)
- {
- XmlDocument doc = new XmlDocument();
- try
- {
- doc.Load(fi.FullName);
- //Calling the virtual method here - it's overridden in B1Engine
- return GetRealJob(name, doc.DocumentElement);
- }
- catch (XmlException xex)
- {
- LogError("Failed parsing the xml document for ExportJob " + name + ":" + xex.Message);
- return null;
- }
- }
- else
- {
- LogError("ExportJob " + fi.FullName + " not found!");
- return null;
- }
- }
- else
- {
- LogError("ENGINE.GETEXPORTJOB: job name is null or empty !!!!");
- return null;
- }
- }
- /// <summary>
- ///
- /// </summary>
- /// <param name="jobid"></param>
- /// <param name="exp"></param>
- /// <returns></returns>
- /// <exclude/>
- protected virtual ExportJob GetRealJob(string jobid, XmlElement exp)
- {
- return new ExportJob(jobid, exp);
- }
-
-
- /*public ExportJob CurrentExportJob
- {
- get { return currentExportJob; }
- set { currentExportJob = value; }
- }*/
-
- private string currentGenericJob;
-
- public string CurrentGenericJob
- {
- get { return currentGenericJob; }
- set { currentGenericJob = value; }
- }
-
- public GenericJob SetCurrentGenericJob(string jobName)
- {
- currentGenericJob = jobName;
- return GetGenericJob(jobName);
- }
-
- public GenericJob GetCurrentGenericJob()
- {
- return GetGenericJob(currentGenericJob);
- }
-
- public GenericJob GetGenericJob(string name)
- {
- FileInfo fi = new FileInfo(genericjobdirectory + name + ".xml");
- if (fi.Exists)
- {
- XmlDocument doc = new XmlDocument();
- try
- {
- doc.Load(fi.FullName);
- return new GenericJob(name, doc.DocumentElement);
- }
- catch (XmlException xex)
- {
- LogError("Failed parsing the xml document for GenericJob " + name + ":" + xex.Message);
- return null;
- }
- }
- else
- {
- LogError("GenericJob " + fi.FullName + " not found!");
- return null;
- }
- }
-
- #endregion
-
- #region Log file management
-
- /// <summary>
- /// Adds DEBUG level information to the currently open log.
- /// </summary>
- /// <param name="value">Information to be logged</param>
- public void LogDebug(string value)
- {
- docLog.Debug(value);
- }
-
- /// <summary>
- /// Adds INFO level information to the currently open log.
- /// </summary>
- /// <param name="value">Information to be logged</param>
- public void LogInfo(string value)
- {
- docLog.Info(value);
- }
-
- /// <summary>
- /// Adds WARN level information to the currently open log.
- /// </summary>
- /// <param name="value">Information to be logged</param>
- public void LogWarn(string value)
- {
- docLog.Warn(value);
- }
-
- /// <summary>
- /// Adds ERROR level information to the currently open log.
- /// </summary>
- /// <param name="value">Information to be logged</param>
- public void LogError(string value)
- {
- docLog.Error(value);
- }
-
- public void SpitFile(string path, string value)
- {
- using (StreamWriter sw = File.CreateText(@path))
- {
- sw.WriteLine(value);
- sw.Close();
- }
- }
-
- /// <summary>
- /// Adds INFO level information to the currently open log.
- /// </summary>
- /// <param name="value">The MessageToken that contains the error information in header and body</param>
- public void LogErrorMessage(MessageToken message)
- {
- LogError(message.Header);
- LogError(message.GetMessageBody());
- }
-
- /// <summary>
- ///Used to delete files in a particular directory based on the time stamp selected by the user.
- ///Adapted from code written By Arunkumar Viswanathan.
- /// </summary>
- /// <param name="usrDir">Directory in which the files exist</param>
- /// <param name="intDays">Number of days since the file was created</param>
- /// <param name="intHours">Number of hours</param>
- /// <param name="intMinutes">Number of minutes</param>
- /// <param name="intSeconds">Number of seconds</param>
- ///
- /// License: Anybody can use it and modify it. You can refer Mr. Viswanathan's name in your code
- /// if you are kind enough :))))
-
- public static void RemoveFilesByTimeStamp(string usrDir, int intDays, int intHours, int intMinutes, int intSeconds)
- {
- Engine engine = Engine.GetInstance();
- DirectoryInfo dirInfo = new DirectoryInfo(usrDir);
- try
- {
- if (!dirInfo.Exists)
- {
- engine.LogError("The directory " + usrDir + " does not exist!");
- }
- else
- {
- foreach (FileInfo f in dirInfo.GetFiles())
- {
- DateTime systemDt = DateTime.Now;
- DateTime fileDt = f.LastWriteTime;
- DateTime cpmTime;
- //IF SYSTEM TIME < FILE WRITE TIME - send a warning message since anyway the file won't be deleted with the current logic
- if (f.LastWriteTime > systemDt)
- engine.LogError("Someone messed the system clock or the file write time was in a different time zone!!!");
-
- TimeSpan customTSpan = new TimeSpan(intDays, intHours, intMinutes, intSeconds);
- cpmTime = fileDt + customTSpan;
-
- //CHECKING IF THE FILE LIFE TIME IS MORE THAN THE CURRENT SYSTEM TIME. IF YES FILE IS VALID
- if (DateTime.Compare(cpmTime, systemDt) > 0)
- engine.LogDebug("Still Valid!");
- else //CHECKING IF THE FILE LIFE TIME IS <= THE CURRENT SYSTEM TIME. IF YES - FILE IS SET FOR DELETION
- {
- engine.LogInfo("Deleting:" + f.Name);
- f.Delete();
- engine.LogInfo("File " + f.Name + " has been deleted!");
- }
- }
- }
- }
- catch (Exception exp)
- {
- engine.LogError("Engine.RemoveFilesByTimeStamp Failed:" + exp.Message);
- }
- }
- #endregion
-
- #region external processes
-
- /// <summary>
- /// Opens the given directory path in Windows Explorer
- /// </summary>
- /// <param name="directorypath">The path to open</param>
- /// <returns>A process handle (or null if the call fails.)</returns>
- public static Process Explore(string directorypath)
- {
- InitializeEngine();
- try
- {
- return Process.Start("explorer.exe", directorypath);
- }
- catch (Exception ex)
- {
- GetInstance().LogError("Failed to start Windows Explorer:" + ex.Message);
- return null;
- }
- }
-
- /// <summary>
- /// Starts an external application
- /// </summary>
- /// <param name="path">The path/filename of the application</param>
- /// <param name="arguments">Commandline arguments</param>
- /// <returns>A boolean value indicating if the call succeeded.</returns>
- public static bool StartApplication(string path, string arguments)
- {
- try
- {
- GetInstance().LogDebug("Starting application " + path + " with arguments " + arguments);
- Process p = new Process();
- p.StartInfo.FileName = path;
- p.StartInfo.Arguments = arguments;
- return p.Start();
- }
- catch (Exception ex)
- {
- GetInstance().LogError("Failed to start application " + path + ":" + ex.Message);
- return false;
- }
- }
- #endregion
-
- public string ToString()
- {
- StringBuilder sb = new StringBuilder();
- sb.AppendLine("DICK version: " + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString());
- sb.AppendLine("Installed in:" + InstallDirectory);
- sb.AppendLine("Current base directory: "+ Engine.BaseDirectory);
- sb.AppendLine("Active configuration directory:" + Engine.confdirectory);
- sb.AppendLine("System directory:" + Engine.SystemConfigurationDirectory);
- sb.AppendLine("Active templates directory:" + Engine.TemplateDirectory);
- sb.AppendLine("Active script directory:" + Engine.scriptdirectory);
- sb.AppendLine("Active log directory:" + Engine.LogDirectory);
- sb.AppendLine("Active Export job directory:" + Engine.exportjobdirectory);
- sb.AppendLine("Active Import job directory:" + Engine.importjobdirectory);
- sb.AppendLine("Active Generic job directory:" + Engine.scriptdirectory);
- sb.AppendLine("Active Python job directory:" + Engine.pythonjobdirectory);
- return sb.ToString();
- }
- }
- }