/// <summary>
        /// Load the configuration from an XML source file.
        /// </summary>
        /// <param name="configFile">the file to load from</param>
        public void LoadFromXMLFile(FileInfo configFile)
        {
            if (configFile == null)
            {
                throw new ArgumentNullException("configFile");
            }

            XMLConfigFile xmlConfig = XMLConfigFile.ParseXMLFile(configFile);

            LoadFromConfig(xmlConfig);
        }
        /// <summary>
        /// Saves the values to the given XML configuration file.
        /// </summary>
        /// <param name="configFile">the file to save to</param>
        public void SaveToXMLFile(FileInfo configFile)
        {
            if (configFile == null)
            {
                throw new ArgumentNullException("configFile");
            }

            var config = new XMLConfigFile();

            SaveToConfig(config);

            config.Save(configFile);
        }
Example #3
0
		/// <summary>
		/// Compiles the scripts into an assembly
		/// </summary>
		/// <param name="compileVB">True if the source files will be in VB.NET</param>
		/// <param name="path">Path to the source files</param>
		/// <param name="dllName">Name of the assembly to be generated</param>
		/// <param name="asm_names">References to other assemblies</param>
		/// <returns>True if succeeded</returns>
		public static bool CompileScripts(bool compileVB, string path, string dllName, string[] asm_names)
		{
			if (!path.EndsWith(@"\") && !path.EndsWith(@"/"))
				path = path + "/";

			//Reset the assemblies
			m_compiledScripts.Clear();

			//Check if there are any scripts, if no scripts exist, that is fine as well
			IList<FileInfo> files = ParseDirectory(new DirectoryInfo(path), compileVB ? "*.vb" : "*.cs", true);
			if (files.Count == 0)
			{
				return true;
			}

			//Recompile is required as standard
			bool recompileRequired = true;

			//This file should hold the script infos
			FileInfo configFile = new FileInfo(dllName + ".xml");

			//If the script assembly is missing, recompile is required
			if (!File.Exists(dllName))
			{
				if (log.IsDebugEnabled)
					log.Debug("Script assembly missing, recompile required!");
			}
			else
			{
				//Script assembly found, check if we have a file modify info
				if (configFile.Exists)
				{
					//Ok, we have a config file containing the script file sizes and dates
					//let's check if any script was modified since last compiling them
					if (log.IsDebugEnabled)
						log.Debug("Found script info file");

					try
					{
						XMLConfigFile config = XMLConfigFile.ParseXMLFile(configFile);

						//Assume no scripts changed
						recompileRequired = false;

						Dictionary<string, ConfigElement> precompiledScripts = new Dictionary<string, ConfigElement>(config.Children);

						//Now test the files
						foreach (FileInfo finfo in files)
						{
							if (config[finfo.FullName]["size"].GetInt(0) != finfo.Length
							    || config[finfo.FullName]["lastmodified"].GetLong(0) != finfo.LastWriteTime.ToFileTime())
							{
								//Recompile required
								recompileRequired = true;
								break;
							}
							precompiledScripts.Remove(finfo.FullName);
						}

						recompileRequired |= precompiledScripts.Count > 0; // some compiled script was removed

						if (recompileRequired && log.IsDebugEnabled)
						{
							log.Debug("At least one file was modified, recompile required!");
						}
					}
					catch (Exception e)
					{
						if (log.IsErrorEnabled)
							log.Error("Error during script info file to scripts compare", e);
					}
				}
				else
				{
					if (log.IsDebugEnabled)
						log.Debug("Script info file missing, recompile required!");
				}
			}
			
			//If we need no compiling, we load the existing assembly!
			if (!recompileRequired)
			{
				try
				{
					Assembly asm = Assembly.LoadFrom(dllName);
					AddOrReplaceAssembly(asm);

					if (log.IsDebugEnabled)
						log.Debug("Precompiled script assembly loaded: " + asm.FullName);
				}
				catch (Exception e)
				{
					if (log.IsErrorEnabled)
						log.Error("Error loading precompiled script assembly, recompile required!", e);
					
					recompileRequired = true;
				}
				
				if (!recompileRequired)
				{
					//Return success!
					return true;
				}
			}

			//We need a recompile, if the dll exists, delete it firsthand
			if (File.Exists(dllName))
				File.Delete(dllName);

			CompilerResults res = null;
			try
			{
				CodeDomProvider compiler;

				if (compileVB)
				{
					compiler = new VBCodeProvider();
				}
				else
				{
					compiler = new CSharpCodeProvider(new Dictionary<string, string> { { "CompilerVersion", "v4.0" } });
				}
				
				// Graveen: allow script compilation in debug or release mode
				#if DEBUG
				CompilerParameters param = new CompilerParameters(asm_names, dllName, true);
				#else
				CompilerParameters param = new CompilerParameters(asm_names, dllName, false);
				#endif
				param.GenerateExecutable = false;
				param.GenerateInMemory = false;
				param.WarningLevel = 2;
				param.CompilerOptions = string.Format("/optimize /lib:.{0}lib", Path.DirectorySeparatorChar);
				param.ReferencedAssemblies.Add("System.Core.dll");

				string[] filepaths = new string[files.Count];
				for (int i = 0; i < files.Count; i++)
					filepaths[i] = ((FileInfo)files[i]).FullName;

				res = compiler.CompileAssemblyFromFile(param, filepaths);

				//After compiling, collect
				GC.Collect();

				if (res.Errors.HasErrors)
				{
					foreach (CompilerError err in res.Errors)
					{
						if (err.IsWarning) continue;

						StringBuilder builder = new StringBuilder();
						builder.Append("   ");
						builder.Append(err.FileName);
						builder.Append(" Line:");
						builder.Append(err.Line);
						builder.Append(" Col:");
						builder.Append(err.Column);
						if (log.IsErrorEnabled)
						{
							log.Error("Script compilation failed because: ");
							log.Error(err.ErrorText);
							log.Error(builder.ToString());
						}
					}

					return false;
				}

				AddOrReplaceAssembly(res.CompiledAssembly);
			}
			catch (Exception e)
			{
				if (log.IsErrorEnabled)
					log.Error("CompileScripts", e);
				m_compiledScripts.Clear();
			}
			//now notify our callbacks
			bool ret = false;
			if (res != null)
			{
				ret = !res.Errors.HasErrors;
			}
			if (ret == false)
				return ret;

			XMLConfigFile newconfig = new XMLConfigFile();
			foreach (FileInfo finfo in files)
			{
				newconfig[finfo.FullName]["size"].Set(finfo.Length);
				newconfig[finfo.FullName]["lastmodified"].Set(finfo.LastWriteTime.ToFileTime());
			}
			if (log.IsDebugEnabled)
				log.Debug("Writing script info file");

			newconfig.Save(configFile);

			return true;
		}
Example #4
0
        /// <summary>
        /// Loads the xml configuration from a file
        /// </summary>
        /// <param name="configFile">The config file</param>
        /// <returns>The parsed config</returns>
        public static XMLConfigFile ParseXMLFile(FileInfo configFile)
        {
            if (configFile == null)
            {
                throw new ArgumentNullException("configFile");
            }

            var root = new XMLConfigFile();

            if (!configFile.Exists)
            {
                return(root);
            }

            ConfigElement current = root;

            using (var reader = new XmlTextReader(configFile.OpenRead()))
            {
                while (reader.Read())
                {
                    if (reader.NodeType == XmlNodeType.Element)
                    {
                        if (reader.Name == "root")
                        {
                            continue;
                        }

                        if (reader.Name == "param")
                        {
                            string name = reader.GetAttribute("name");

                            if (name != null && name != "root")
                            {
                                var newElement = new ConfigElement(current);
                                current[name] = newElement;
                                current       = newElement;
                            }
                        }
                        else
                        {
                            var newElement = new ConfigElement(current);
                            current[reader.Name] = newElement;
                            var isNotSingleTag = !reader.IsEmptyElement;
                            if (isNotSingleTag)
                            {
                                current = newElement;
                            }
                        }
                    }
                    else if (reader.NodeType == XmlNodeType.Text)
                    {
                        current.Set(reader.Value);
                    }
                    else if (reader.NodeType == XmlNodeType.EndElement)
                    {
                        if (reader.Name != "root")
                        {
                            current = current.Parent;
                        }
                    }
                }
            }

            return(root);
        }
Example #5
0
		/// <summary>
		/// Loads the xml configuration from a file
		/// </summary>
		/// <param name="configFile">The config file</param>
		/// <returns>The parsed config</returns>
		public static XMLConfigFile ParseXMLFile(FileInfo configFile)
		{
			if (configFile == null)
				throw new ArgumentNullException("configFile");

			var root = new XMLConfigFile();

			if (!configFile.Exists)
				return root;

			ConfigElement current = root;
			using(var reader = new XmlTextReader(configFile.OpenRead()))
			{
				while (reader.Read())
				{
					if (reader.NodeType == XmlNodeType.Element)
					{
						if (reader.Name == "root")
							continue;

						if (reader.Name == "param")
						{
							string name = reader.GetAttribute("name");

							if (name != null && name != "root")
							{
								var newElement = new ConfigElement(current);
								current[name] = newElement;
								current = newElement;
							}
						}
						else
						{
							var newElement = new ConfigElement(current);
							current[reader.Name] = newElement;
							current = newElement;
						}
					}
					else if (reader.NodeType == XmlNodeType.Text)
					{
						current.Set(reader.Value);
					}
					else if (reader.NodeType == XmlNodeType.EndElement)
					{
						if (reader.Name != "root")
						{
							current = current.Parent;
						}
					}
				}
			}

			return root;
		}
Example #6
0
		public static bool Init()
		{
			XMLConfigFile xmlConfig = new XMLConfigFile();
			FileInfo file = new FileInfo("./config/MailConfig.xml");

			try
			{
				if (file.Exists)
				{
					xmlConfig = XMLConfigFile.ParseXMLFile(file);
					m_enable = xmlConfig["Enable"].GetBoolean(false);
					if (m_enable)
					{
						m_username = xmlConfig["Username"].GetString("");
						m_password = xmlConfig["Password"].GetString("");
						m_emailAddress = xmlConfig["EmailAddress"].GetString("");
						m_smtpServer = xmlConfig["SMTPServer"].GetString("");
						m_ssl = xmlConfig["SSL"].GetBoolean(false);
						Logger.Info("Mail enabled");
					}
					else
					{
						Logger.Info("Mail disabled");
					}
				}
				else
				{
					//create and add default values
					xmlConfig["Username"].Set("");
					xmlConfig["Password"].Set("");
					xmlConfig["EmailAddress"].Set("");
					xmlConfig["SMTPServer"].Set("");
					xmlConfig["SSL"].Set(false);
					xmlConfig["Enable"].Set(false);
					file.Refresh();
					xmlConfig.Save(file);
				}
			}
			catch (Exception e)
			{
				Logger.Error(e);
				return false;
			}

			SmtpClient = new SmtpClient(m_smtpServer);
			SmtpClient.UseDefaultCredentials = false;
			SmtpClient.EnableSsl = m_ssl;
			SmtpClient.Credentials = new NetworkCredential(m_username, m_password);

			if (DOL.GS.ServerProperties.Properties.LOG_EMAIL_ADDRESSES != "")
				SendLogs(DOL.GS.ServerProperties.Properties.LOG_EMAIL_ADDRESSES);

			if (m_enable)
			{
				//create callback thread for the send mail queue
				m_timer = new Timer(new TimerCallback(RunTask), null, m_mailFrequency, 0);
			}

			return true;
		}
Example #7
0
		/// <summary>
		/// Saves the values to the given XML configuration file.
		/// </summary>
		/// <param name="configFile">the file to save to</param>
		public void SaveToXMLFile(FileInfo configFile)
		{
			if (configFile == null)
				throw new ArgumentNullException("configFile");

			var config = new XMLConfigFile();
			SaveToConfig(config);

			config.Save(configFile);
		}