using System; using System.Collections.Generic; using System.IO; using System.Xml; using System.Web; using NLog; namespace dariog { public class AppConfig { private static Logger logger = LogManager.GetCurrentClassLogger(); private static AppConfig config = null; public static AppConfig Current { get { if(config == null) { lock(typeof(AppConfig)) { if(config == null) { config = new AppConfig(); } } } return config; } } private Dictionary items = null; private object locker = new object(); private AppConfig() { this.LoadItems(); } private void LoadItems() { items = new Dictionary(); string file = Path.Combine(HttpRuntime.AppDomainAppPath, "App_Data\\config\\application.xml"); if (File.Exists(file)) { XmlDocument xml = new XmlDocument(); xml.Load(file); foreach (XmlNode node in xml.DocumentElement) { if (node.NodeType != XmlNodeType.Comment) { XmlElement e = node as XmlElement; items.Add(e.Name, e.InnerText); } } string machine = System.Environment.MachineName.ToLower(); file = Path.Combine( HttpRuntime.AppDomainAppPath, "App_Data\\config\\application.{0}.xml".FormatThis(machine)); if (File.Exists(file)) { xml = new XmlDocument(); xml.Load(file); foreach (XmlNode node in xml.DocumentElement) { if (node.NodeType != XmlNodeType.Comment) { XmlElement e = node as XmlElement; if (items.ContainsKey(e.Name)) { items[e.Name] = e.InnerText; } else { logger.Warn("Key exists in extended configuration file {0} but doesn't exists in base configuration file 'application.xml'.", file); } } } } } else { logger.Error("File configuration {0} doesn't exists.", file); } } public T GetItem(string key) { lock (locker) { if (!items.ContainsKey(key)) { throw new NotImplementedException(String.Format("The key '{0}' is not defined in application config file.", key)); } return (T)Convert.ChangeType(items[key], typeof(T)); } } public T GetItem(string key, T defaultValue) { lock (locker) { if (items.ContainsKey(key)) { return (T)Convert.ChangeType(items[key], typeof(T)); } return defaultValue; } } } }