Custom XML dynamic configuration program, custom xml dynamic

Source: Internet
Author: User

Custom XML dynamic configuration program, custom xml dynamic
Overview

1. When developing programs, we often need to use the following two basic modules:

1> set basic program parameters, such as paging parameters and mail parameters;

2> in table-based development, some judgment logic is placed in table data;

2. In these two basic scenarios, we have the following requirements:

1> Centralized Management;

2> to be configurable, modify the parameters without restarting the system;

3> easy to use.

Main functions of the program

1> set basic program parameters, such as paging parameters and mail parameters;

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

2> in table-based development, some judgment logic is placed in table data;

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

Main Code

1. First define and 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. The basic configuration information of the program is configured in AppSettings.

Under the 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 required to load the XML configuration information in 2 to the object in 1.

Public static class ConfigManager {public static Dictionary etting rule etting; private static string xmlPath; public static Dictionary <string, Dictionary <string, string> dictappsettionary = new Dictionary <string, Dictionary <string, string >>(); static ConfigManager () {xmlPath = System. IO. path. combine (AppDomain. currentDomain. baseDirectory. toString (), "AppConfig. xml "); LoadSettings (xmlPath);} private stati C void LoadSettings (string path) {DictAppSettings. clear (); // load all the keys and values in XML and convert them to the Dictionary object 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 ();} dictpolicettings. add (dictType. attributes ["name"]. value. trim (), dict);} // convert a Dictionary object to an object field and var serializer = new JavaScriptSerializer () on the corresponding dctionary (); // convert etettings to json string jAppSetting = serializer. serialize (DictAppSettings ["AppSettings"]); DictAppSettings. remove ("deleetask"); // convert the information except the deleetaskinto json string jDict = serializer. serialize (D Ictappsettionary); // loads the appsettionary and other Dictionary into the corresponding object. String json = string. format ("{0}, {1}", jreceivetting. remove (jAppSetting. length-1), jDict. remove (0, 1); receivetting = serializer. deserialize <deleetting> (json); // reload XML FileHelper when the file is modified. cacheDependencyFile (path, CacheRemovedCallback);} private static void CacheRemovedCallback (string key, object value, CacheItemRemovedReason reason) {// This method comes from Fish. li string xmlFilePath = (string) value; // when an event occurs, The file may not be completely closed, so you have to wait for the program. 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 runs for the first time, the corresponding configuration information is output.

2. When you modify some parameters, you can obtain the latest information without restarting them. Note: After modifying the parameters for 3 seconds, refresh the page.

 

Download complete code

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.