Home  >  Article  >  Backend Development  >  Sample code sharing of custom XML dynamic configuration program

Sample code sharing of custom XML dynamic configuration program

黄舟
黄舟Original
2017-03-22 16:46:371845browse

Overview

1 When doing program development, we often use the following two basic modules

1> Set the basic parameters of the program, such as paging parameters, email parameters, etc.;

2> When developing based on table-driven development, some judgment logic is placed in the table data;

2 Among these two basic applications, we have the following requirements:

1> It must be managed centrally;

2> It must be configurable, that is, the parameters can be modified without restarting the system;

3> It must be easy to use.

Main functions of the program

1> Set the basic parameters of the program, such as paging parameters, email parameters, etc.;

----Automatically add configuration information in XML to the corresponding entity.

2> When developing based on table-driven development, some judgment logic is placed in the table data;

----Automatically load the Dctionary data in XML to the corresponding entity . However, this method needs to continue to be optimized. Now it only supports loading Dictionary and needs to support more complex structures.

Main code

1 First define, reference the entity in the code.

Example

public class AppSetting
{
    public string PageSize;
    public string WebUrl;
 
    public Dictionary<string, string> IsPartialPayment;
    public Dictionary<string, string> EntityCurrency;
}

2 Define the corresponding XML file. Among them, the basic configuration information of the program is configured under the AppSettings

node.

<?xml version="1.0" encoding="utf-8" ?>
<settings>
  <DictSettings>
    <Dict name="AppSettings" >
      <add key="PageSize" value="2"></add>
      <add key="WebUrl" value="www.baidu.com"></add>
    </Dict>
    <Dict name="IsPartialPayment">
      <add key="TTPART" value="true"></add>
      <add key="TT50/50" value="true"></add>
    </Dict>
    <Dict name="EntityCurrency">
      <add key="China" value="CNY"></add>
      <add key="HQ" value="USD"></add>
      <add key="Default" value="USD"></add>
    </Dict>
  </DictSettings>
</settings>

3 Finally, a piece of XML loading code is needed to load the XML configuration information in 2 into the entity in 1.

public static class ConfigManager
    {
        public static AppSetting AppSetting;
        private static string xmlPath;
 
        public static Dictionary<string, Dictionary<string, string>> DictAppSettings = new Dictionary<string, Dictionary<string, string>>();
        static ConfigManager()
        {
            xmlPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory.ToString(), "AppConfig.xml");
            LoadSettings(xmlPath);
        }
 
        private static void LoadSettings(string path)
        {
            DictAppSettings.Clear();
            //加载XML中所有的key,value,并转换成Dictionary对象
            XmlNode dictRootNode = FileHelper.GetXMLNode(path, "/settings/DictSettings");
            foreach (XmlNode dictType in dictRootNode.ChildNodes)
            {
                Dictionary<string, string> dict = new Dictionary<string, string>();
                foreach (XmlNode dictItem in dictType.ChildNodes)
                {
                    dict.Add(dictItem.Attributes["key"].Value.Trim(), dictItem.Attributes["value"].Value.Trim());
                }
                DictAppSettings.Add(dictType.Attributes["name"].Value.Trim(), dict);
            }
 
            //将Dictionary 对象转换成实体的字段和对应dctionary上
            var serializer = new JavaScriptSerializer();
            //将AppSettings转成json
            string jAppSetting = serializer.Serialize(DictAppSettings["AppSettings"]);
            DictAppSettings.Remove("AppSettings");
            //将除AppSettings中的信息转成json
            string jDict = serializer.Serialize(DictAppSettings);
            //将AppSettings和其它的Dictionary 加载到对应的实体中去。
            string json = string.Format("{0},{1}", jAppSetting.Remove(jAppSetting.Length - 1), jDict.Remove(0, 1));
            AppSetting = serializer.Deserialize<AppSetting>(json);
 
            //当修改文件时,重新加载XML
            FileHelper.CacheDependencyFile(path, CacheRemovedCallback);
        }
 
        private static void CacheRemovedCallback(string key, object value, CacheItemRemovedReason reason)
        {
            //此方法来自Fish.Li
            string xmlFilePath = (string)value;
 
            // 由于事件发生时,文件可能还没有完全关闭,所以只好让程序稍等。
            System.Threading.Thread.Sleep(3000);
 
            LoadSettings(xmlFilePath);
        }
    }
 
    public static class FileHelper
    {
        public static XmlNode GetXMLNode(string path, string xPath)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(path);
            return xmlDoc.SelectSingleNode(xPath);
        }
 
        public static void CacheDependencyFile(string path, CacheItemRemovedCallback removedCallback)
        {
            CacheDependency dep = new CacheDependency(path);
            HttpRuntime.Cache.Insert(Guid.NewGuid().ToString(), path, dep,
                Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, removedCallback);
        }
    }

Final effect

1 When the program is run for the first time, the corresponding configuration information is output

Sample code sharing of custom XML dynamic configuration program

2 When some parameters are modified , you can get the latest information without restarting. Note that after modifying the parameters for 3 seconds, refresh the page

Sample code sharing of custom XML dynamic configuration program

The above is the detailed content of Sample code sharing of custom XML dynamic configuration program. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn