. 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 configuration 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, just one Inner text, The complexity of meeting these two forms in the program. in order to avoid this problem,. Net configuration file is only stored with attributes and not using the innertext.






Next, we to write a custom profile that conforms to this unspoken rule for easy testing:




<mailServerGroup provider="www.baidu.com">

     <mailServers>

       <mailServer client="http://blog.csdn.net/lhc1105" address="13232@qq.com" userName="lhc" password="2343254"/>

       <mailServer client="http://blog345.csdn.net/lhc1105" address="132wdfgdsggtaewg32@qq.com" userName="dfshs paddy field ya" password="2334t243 of Safin 234254"/>

       <mailServer client="http://blog436.csdn.net/lhc1105" address="132wdgadsfgdtaewg32@qq.com" userName="sdfhdfs paddy field ya" password="23ewrty2343 of Safin 234254"/>

       <mailServer client="http://blo345734g.csdn.net/lhc1105" address="132wdgdfagdstaewg32@qq.com" userName="sdfher Iwata Ruiya" password="23erwt43 of Safin 234254"/>

     </mailServers>

   </mailServerGroup>


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


 



First, the most inner mailserver:

/// <summary>

   /// Class MailServerElement: used to map the mailServer node, here is the place where the data is actually stored;

   /// </summary>

   /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 21:51:57</remarks>

   Public sealed class MailServerElement : ConfigurationElement / / configuration elements in the configuration file

   {

 

       /// <summary>

       /// Gets or sets the client.

       /// </summary>

       /// <value>The client.</value>

       /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:05:40</remarks>

       [ConfigurationProperty("client", IsKey = true, IsRequired = true)] //client is a required key attribute, a bit of a primary key. For example, if you define multiple nodes with the same client, read only if you read them in a loop. To the last value

       Public string Client

       {

           Get

           {

               Return this["client"] as string;

           }

           Set

           {

               This["client"] = value;

           }

 

       }

       /// <summary>

       /// Gets or sets the address.

       /// </summary>

       /// <value>The address.</value>

       /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:05:38</remarks>

       [ConfigurationProperty("address")]

       Public string Address

       {

           Get

           {

               Return this["address"] as string;

           }

           Set

           {

               This["address"] = value;

           }

 

       }

       /// <summary>

       /// Gets or sets the name of the user.

       /// </summary>

       /// <value>The name of the user.</value>

       /// <remarks>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>

       /// Gets or sets the password.

       /// </summary>

       /// <value>The password.</value>

       /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:05:33</remarks>

       [ConfigurationProperty("password")]

       Public string Password

       {

 

           Get

           {

               Return this["password"] as string;

           }

           Set

           {

               This["password"] = value;

           }

 

       }

 

 

 

   }


Next is mailServers, which is a collection of mailServers:


/// <summary>

   /// Class MailServerCollection: maps the mailServers node as a collection class. It also contains a lot of operations on the nodes, most of which are inherited from the ConfigurationElementCollection.

   /// </summary>

   /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 21:52:00</remarks>

   Public sealed class MailServerCollection : ConfigurationElementCollection

   {

       /// <summary>

       /// Get the type of <see cref="T:System.Configuration.ConfigurationElementCollection" />.

       /// </summary>

       /// <value>The type of the collection.</value>

       /// <returns> <see cref="T:System.Configuration.ConfigurationElementCollectionType" /> of this collection. </returns>

       /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:05:08</remarks>

       Public override ConfigurationElementCollectionType CollectionType

       {

           Get

           {

               Return ConfigurationElementCollectionType.BasicMap;

           }

         

       }

 

 

       /// <summary>

       /// When overriding in a derived class, create 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>

       /// Gets the element key of the specified configuration element when overridden in a derived class.

       /// </summary>

       /// <param name="element"><see cref="T:System.Configuration.ConfigurationElement" /> for which to return the key. </param>

       /// <returns> A <see cref="T:System.Object" /> used as the key to specify <see cref="T:System.Configuration.ConfigurationElement" />. </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 used to identify this collection of elements in the configuration file when overridden in a derived class.

       /// </summary>

       /// <value>The name of the element.</value>

       /// <returns> the name of the collection; otherwise an empty string. The default 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>

       /// Get the number of elements in the collection.

       /// </summary>

       /// <value>The count.</value>

       /// The number of elements in the <returns> collection. </returns>

       /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:08:24</remarks>

       Public new int Count

       {

           Get { return base.Count; }

       }

 

       /// <summary>

       /// Gets or sets the properties, properties, 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>

       /// Gets or sets the properties, properties, or child elements of this configuration element.

       /// </summary>

       /// <param name="Name">The name.</param>

       /// <returns>MailServerElement.</returns>

       /// <remarks>Editor:v-liuhch</remarks>

       New public MailServerElement this[string Name]

       {

           Get { return BaseGet(Name) as MailServerElement; }

       }

 

       /// <summary>

       /// Indexes the of.

       /// </summary>

       /// <param name="element">The element.</param>

       /// <returns>System.Int32.</returns>

       /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:24:16</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-liuhch CreateTime:2015/6/27 22:33:29</remarks>

       Public void RemoveAt(int index)

       {

           BaseRemoveAt(index);

       }

 

       /// <summary>
/// Removes the specified client.

        /// </summary>

        /// <param name="client">The client.</param>

        /// <remarks>Editor:v-liuhch 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 is the entry:

   /// </summary>

   /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 21:41:02</remarks>

   Public class MailServerSection : ConfigurationSection //Inherit the section in the configuration file

   {

       /// <summary>

       /// Gets the provider.: Map provider for the mailServerGroup node

       /// </summary>

       /// <value>The provider.</value>

       /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:05:59</remarks>

       [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; this node also contains several mailServer nodes, so it is a collection class

       /// </summary>

       /// <value>The mail servers.</value>

       /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 22:05:56</remarks>

       [ConfigurationProperty("mailServers", IsDefaultCollection = false)]

       Public MailServerCollection MailServers

       {

           Get

           {

               Return this["mailServers"] as MailServerCollection;

           }

           Set

           {

               This["mailServers"] = value;

           }

 

       }

   }


Similarly, associative processing classes and nodes:

<section name="mailServerGroup" type="Inherit the ConfigurationSection base class.MailServerSection, inherit the ConfigurationSection base class"/>

  </configSections>


Then do a test:


Class Program

    {

        Static void Main(string[] args)

        {

            Test();

 

        }

 

        /// <summary>

        /// Tests this instance.: Example of reading node values

        /// </summary>

        /// <remarks>Editor:v-liuhch CreateTime:2015/6/27 23:04:53</remarks>

        Private static void Test() {

 

            MailServerSection mailSection = (MailServerSection)ConfigurationManager.GetSection("mailServerGroup");

            Console.WriteLine("MailServerSection provider property value: "+mailSection.provider);

            Foreach (MailServerElement config in mailSection.MailServers)

            {

                Console.WriteLine("----------------------------------");

                Console.WriteLine("client value: "+config.Client);

                Console.WriteLine("address value: "+config.Address);

                Console.WriteLine("username value: "+config.UserName);

                Console.WriteLine("password value:"+config.Password);

                Console.WriteLine("----------------------------------");

            }

 

            Console.ReadKey();

 

        }

 

    }



Originally also want to pass a result diagram, but slow speed, calculate, like to play the children's shoes run under the results .....



The above is the. Net configuration file--Inherit configurationsection implement custom processing class handle the content of custom configuration node, more related content please pay attention to topic.alibabacloud.com (www.php.cn)!


  • 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.