. Net configuration file--Inherit configurationsection implement custom processing class handle custom Configuration node

Source: Internet
Author: User

In addition to using inherited IConfigurationSectionHandler methods to define classes that handle custom nodes, you can also achieve the same effect by inheriting the ConfigurationSection class.

First of all. Net config file in one of the unspoken rules:

When you configure a node, there are two ways to store the parameter data: one that is stored in the properties of the node, and one that is stored in the text of the node.

Because a node can have many properties, but as long as a innertext, and in the program to distinguish between the two forms of the complexity of the meeting. To avoid this problem,. NET configuration files are only stored with attributes instead of using innertext.

Next, let's write a custom configuration file that fits this unspoken rule to facilitate testing:

<mailservergroup provider= "www.baidu.com" >    <mailServers>      <mailserver client= "http// blog.csdn.net/lhc1105 "address=" [email protected] "username=" LHC "password=" 2343254 "/>      <mailserver Client = "http://blog345.csdn.net/lhc1105" address= "[email protected]" username= "dfshs paddy fields like Ya"  password= " 2334t243 safin 234254 "/>      <mailserver client=" http://blog436.csdn.net/lhc1105 "address=" [email protected] " Username= "Sdfhdfs paddy field such as Ya"  password= "23ewrty2343 safin 234254"/> <mailserver      client= "/http blo345734g.csdn.net/lhc1105 "address=" [email protected] "username=" sdfher paddy field like ya password= 23erwt43 safin  234254 "/ >    </mailServers>  </mailServerGroup>

Next, we write the corresponding processing class, here we write from the inward:

The first is the mailserver of the inner layer:

 

 <summary>///Class mailserverelement: For mapping mailserver nodes, here is where the data is actually stored;///</summary>//<rema RKS&GT;EDITOR:V-LIUHCH CREATETIME:2015/6/27 21:51:57</remarks> public sealed class Mailserverelement:configura        Config element in tionelement//config file {///<summary>//sets the client. </summary>//<value>the client.</value>//<remarks>editor:v-liuhch Createtim E:2015/6/27 22:05:40</remarks> [ConfigurationProperty ("client", IsKey = True, IsRequired = True)]//client is a must                Required Key property, something like the primary key, for example, if you define multiple clients with the same node, the loop reads only the last value of the public string Client {get {            Return this["Client"] as String;            } set {this["client"] = value;        }}///<summary>//sets the address. </summary>//<value>the address.</value>        <remarks>editor:v-liuhch CREATETIME:2015/6/27 22:05:38</remarks> [ConfigurationProperty ("Ad Dress ")] public string Address {get {return this[" address "] as String            ;            } set {this["address"] = value;        }}///<summary>//sets the name of the user.  </summary>//<value>the name of the user.</value>//&LT;REMARKS&GT;EDITOR:V-LIUHCH        Createtime:2015/6/27 22:05:35</remarks> [ConfigurationProperty ("UserName")] public string userName            {get {return this["UserName"] as String;            } set {this["userName"] = value;        }}///<summary>//sets the password. </summary>//<value>the Password.</value>//<remarks>editor:v-liuhch createtime:2015/6/27 22:05:33</remarks> [ConfigurationProper Ty ("password")] public string Password {get {return this["password"]            As String;            } set {this["password"] = value; }        }    }

Next is Mailservers, which is a collection of mailserver:

 <summary>///class Mailservercollection: Map the Mailservers node as a collection class, plus a lot of operations on the node, Most inherited from ConfigurationElementCollection//</summary>//&LT;REMARKS&GT;EDITOR:V-LIUHCH CREATETIME:2015/6/27 21 :52:00</remarks> public sealed class Mailservercollection:configurationelementcollection {//<su        Mmary>///Gets the type of <see cref= "T:System.Configuration.ConfigurationElementCollection"/>. </summary>//<value>the type of the collection.</value>///<returns> this collection < See cref= "T:System.Configuration.ConfigurationElementCollectionType"/>. </returns>//<remarks>editor:v-liuhch createtime:2015/6/27 22:05:08</remarks> public ove Rride Configurationelementcollectiontype CollectionType {get {return Configu            Rationelementcollectiontype.basicmap; }}///<summary>//when inWhen overridden in a derived class, creates a new <see cref= "T:System.Configuration.ConfigurationElement"/>. </summary>///<returns> new <see cref= "T:System.Configuration.ConfigurationElement"/>. </returns>//<remarks>editor:v-liuhch CREATETIME:2015/6/27 22:05:03</remarks> protected        Override ConfigurationElement Createnewelement () {return new mailserverelement ();        }///<summary>///When overridden in a derived class, gets the element key for the specified configuration element. </summary>//<param name= "element" > <see for which to return the key cref= "T:system.configuration.configurationelem Ent "/>. </param>///<returns> a <see cref= "T:System.Object"/&GT;, as specified <see cref= "t:system.configuration . ConfigurationElement "/> The key. </returns>//<remarks>editor:v-liuhch CREATETIME:2015/6/27 22:04:51</remarks> protected Override Object Getelementkey (configurationelement Element) {return (element as Mailserverelement).        Client;        }///<summary>////Gets the name that is used to identify the collection of this element in the configuration file when overridden in a derived class. </summary>//<value>the name of the element.</value>///<returns> collection; otherwise null character String. The default value is an empty string. </returns>//<remarks>editor:v-liuhch CREATETIME:2015/6/27 23:41:40</remarks> protected            Override string ElementName {get {return ' mailserver ';        }}///<summary>//Gets the number of elements in the collection. </summary>//<value>the count.</value>///<returns> the number of elements in the collection.  </returns>//&LT;REMARKS&GT;EDITOR:V-LIUHCH CREATETIME:2015/6/27 22:08:24</remarks> Public New int Count {get {return base. Count;        }}///<summary>////To get or set the properties, attributes, or child elements of this configuration element.  </summary>//<param name= "index" >the index.</param>      <returns>MailServerElement.</returns>//<remarks>Editor:v-liuhch</remarks>            Public mailserverelement This[int Index] {get {return Baseget (index) as mailserverelement;}                 set {if (Baseget (index) = null) {baseremoveat (index);            } baseadd (index, value);        }}///<summary>////To get or set the properties, attributes, or child elements of this configuration element. </summary>//<param name= "name" >the name.</param>//<returns>mailservereleme nt.</returns>//<remarks>Editor:v-liuhch</remarks> new public mailserverelement This[str        ing Name] {get {return Baseget (name) as Mailserverelement;}        }///<summary>//Indexes the. </summary>//<param name= "element" >the element.</param>/<returns>System.Int32.</returns>//<remarks>editor:v-liuhch CREATETIME:2015/6/27 22:24:16&lt        ;/remarks> public int IndexOf (mailserverelement element) {return baseindexof (element);        }///<summary>//Adds the specified element. </summary>//<param name= "element" >the element.</param>//<remarks>editor:v-            Liuhch createtime:2015/6/27 22:26:06</remarks> public void Add (mailserverelement element) {        Baseadd (Element);        }///<summary>//removes the specified element. </summary>//<param name= "element" >the element.</param>//<remarks>editor:v-            Liuhch createtime:2015/6/27 22:27:01</remarks> public void Remove (mailserverelement element) { if (Baseindexof (Element) > 0) {baseremove (Element). ClieNT);        }}///<summary>//removes at. </summary>//<param name= "index" >the index.</param>//<remarks>editor:v-liuh CH createtime:2015/6/27 22:33:29</remarks> public void RemoveAt (int index) {baseremoveat (i        NDEX);        }///<summary>//removes the specified client. </summary>//<param name= "Client" >the client.</param>//<remarks>editor:v-li Uhch createtime:2015/6/27 22:34:04</remarks> public void Remove (string client) {Baseremove        (client);        }///<summary>//clears this instance.  </summary>//<remarks>editor:v-liuhch CREATETIME:2015/6/27 22:34:29</remarks> Public        void Clear () {baseclear (); }    }

Finally, the outermost group:

 <summary>///Class mailserversection for entrance:///</summary>/&LT;REMARKS&GT;EDITOR:V-LIUHCH Cre        ATETIME:2015/6/27 21:41:02</remarks> public class mailserversection:configurationsection//inherit config file in section { <summary>//Gets the provider.: Provider for mapping Mailservergroup nodes///</summary>/// Lt;value>the provider.</value>//<remarks>editor:v-liuhch CREATETIME:2015/6/27 22:05:59</remark s> [ConfigurationProperty ("provider", IsKey = True)] public string Provider {get {return this[' provider        "] As String;}}        <summary>//Gets or sets the mail servers.: Maps the newly added node Mailservers node, which also contains several mailserver nodes, so it is a collection class  </summary>//<value>the mail servers.</value>//&LT;REMARKS&GT;EDITOR:V-LIUHCH Createtime:2015/6/27 22:05:56</remarks> [ConfigurationProperty ("mailservers", IsDefaultCollection = False)]        Public mailservercollection Mailservers {get {return this["MailServe            RS "] as mailservercollection;            } set {this["mailservers"] = value; }        }    }

Similarly, associative processing classes and nodes:

<section name= "Mailservergroup" type= "Inherits ConfigurationSection base class. Mailserversection, inheriting ConfigurationSection base class"/ >     </configSections>

Then do a test:

Class Program {static void Main (string[] args) {Test (); }///<summary>//Tests This instance.: Read Node value example///</summary>//<remarks&gt ; Editor:v-liuhch createtime:2015/6/27 23:04:53</remarks> private static void Test () {mailserversec            tion mailsection = (mailserversection) configurationmanager.getsection ("Mailservergroup");            Console.WriteLine ("Mailserversection provider attribute value:" +mailsection.provider); foreach (mailserverelement config in mailsection.mailservers) {Console.WriteLine ("-------------                ---------------------"); Console.WriteLine (the "Client value is:" +config.                Client); Console.WriteLine ("Address value is:" +config.                Address); Console.WriteLine ("Username value is:" +config.                UserName); Console.WriteLine ("Password value is:" +config.                Password);   Console.WriteLine ("----------------------------------");         } console.readkey (); }    }

. Net configuration file--Inherit configurationsection implement custom processing class handle custom Configuration node

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.