How to add custom configuration in Web. config or App. config

Source: Internet
Author: User

The System. Configuration namespace in. Net provides perfect support for custom Configuration in web. config or app. config. Recently, some projects are still using custom xml files for program configuration, so you can't help writing an article about System custom configuration.
If you are familiar with custom configurations, ignore this article.
Let's take a look at a simple custom configuration. Copy codeThe Code is as follows: <? Xml version = "1.0" encoding = "UTF-8"?>
<Configuration>
<ConfigSections>
<Section name = "simple" type = "ConfigExample. Configuration. SimpleSection, ConfigExample"/>
</ConfigSections>
<Simple maxValue = "20" minValue = "1"> </simple>
</Configuration>

To use custom configuration in the configuration file, you must add a section element in configSections and specify the type and name of the section element. Then add the custom configuration under the configuration root node, as shown in the preceding example, the simple node. A simple node has only two integer attributes: maxValue and minValue.
To use custom configuration in a program, we also need to implement the type of access to this configuration block. Generally, we need to do the following three things:
1. The definition type is inherited from System. Configuration. ConfigurationSection.
2. Define the attributes of the configuration class. These attributes need to be modified using the ConfigurationProperty feature, and specify the names and other restrictions of the attributes in the configuration section.
3. get, set
It is very simple and natural. The following is the implementation of the configuration class above:
Copy codeThe Code is as follows: public class SimpleSection: System. Configuration. ConfigurationSection
{
[ConfigurationProperty ("maxValue", IsRequired = false, DefaultValue = Int32.MaxValue)]
Public int MaxValue
{
Get
{
Return (int) base ["maxValue"];
}
Set
{
Base ["maxValue"] = value;
}
}

[ConfigurationProperty ("minValue", IsRequired = false, DefaultValue = 1)]
Public int MinValue
{
Get {return (int) base ["minValue"];}
Set {base ["minValue"] = value ;}
}

[ConfigurationProperty ("enabled", IsRequired = false, DefaultValue = true)]
Public bool Enable
{
Get
{
Return (bool) base ["enabled"];
}
Set
{
Base ["enabled"] = value;
}
}
}

This completes a simple configuration class. How can I use this configuration in a program? You can use the GetSection method of the ConfigurationManager class (to reference System. configuration. dll, which is available only in Versions later than. Net2.0) to obtain the configuration. The following code:Copy codeThe Code is as follows: SimpleSection simple = ConfigurationManager. GetSection ("simple") as SimpleSection;
Console. WriteLine ("simple minValue = {0} maxValue = {1}", simple. MinValue, simple. MaxValue );

This configuration class is too simple, and sometimes we need more complex structures, such as using classes in the configuration class to represent a group of data, the following describes a slightly more complex custom configuration.Copy codeThe Code is as follows: <? Xml version = "1.0" encoding = "UTF-8"?>
<Configuration>
<ConfigSections>
<Section name = "complex" type = "ConfigExample. Configuration. ComplexSection, ConfigExample"/>
</ConfigSections>
<Complex height = "190">
<Child firstName = "James" lastName = "Bond"/>
</Complex>
</Configuration>

The name of this configuration is complex, which has a property height. There is also a child element in his node. This element has two attributes firstName and lastName. How can this embedded node be implemented? First, we need to define a class to inherit from the ConfigurationElement class, and then use a method similar to SimpleSection to define some attributes modified with the ConfigurationProperty Property. Of course, the get attribute value, set also uses the base class indexer. Implementation:Copy codeThe Code is as follows: public class ComplexSection: ConfigurationSection
{
[ConfigurationProperty ("height", IsRequired = true)]
Public int Height
{
Get
{
Return (int) base ["height"];
}
Set
{
Base ["height"] = value;
}
}

[ConfigurationProperty ("child", IsDefaultCollection = false)]
Public ChildSection Child
{
Get
{
Return (ChildSection) base ["child"];
}
Set
{
Base ["child"] = value;
}
}
}

Public class ChildSection: ConfigurationElement
{
[ConfigurationProperty ("firstName", IsRequired = true, IsKey = true)]
Public string FirstName
{
Get
{
Return (string) base ["firstName"];
}
Set
{
Base ["firstName"] = value;
}
}

[ConfigurationProperty ("lastName", IsRequired = true)]
Public string LastName
{
Get
{
Return (string) base ["lastName"];
}
Set
{
Base ["lastName"] = value;
}
}
}

A little more complex, we may need to configure a group of nodes of the same type in the configuration, that is, a set of nodes. The configuration is as follows:Copy codeThe Code is as follows: <? Xml version = "1.0" encoding = "UTF-8"?>
<Configuration>
<ConfigSections>
<Section name = "complex" type = "ConfigExample. Configuration. ComplexSection, ConfigExample"/>
</ConfigSections>
<Complex height = "190">
<Child firstName = "James" lastName = "Bond"/>

<Children>
<Add firstName = "Zhao" lastName = "yukai"/>
<Add firstName = "Lee" lastName = "yukai"/>
<Remove firstName = "Zhao"/>
</Children>
</Complex>
</Configuration>

See the children node. It is a collection class that defines a set of add elements. You can also remove the added configuration from the remove node.
To use a custom node set, you need to inherit a custom class from the ConfigurationElementCollection class, and then implement the GetElementKey (ConfigurationElement element) and ConfigurationElement CreateNewElement () methods; to facilitate access to sub-nodes, you can define the read-only indexer in this class. See the following implementationCopy codeThe Code is as follows: public class Children: ConfigurationElementCollection
{
Protected override object GetElementKey (ConfigurationElement element)
{
Return (ChildSection) element). FirstName;
}

Protected override ConfigurationElement CreateNewElement ()
{
Return new ChildSection ();
}

Public ChildSection this [int I]
{
Get
{
Return (ChildSection) base. BaseGet (I );
}
}

Public ChildSection this [string key]
{
Get
{
Return (ChildSection) base. BaseGet (key );
}
}

}

To use this collection class, we must add an attribute of this collection class to the Complex class, and specify attributes such as the element type of the Collection class, as follows:Copy codeThe Code is as follows: [ConfigurationProperty ("children", IsDefaultCollection = false)]
[ConfigurationCollection (typeof (ChildSection), CollectionType = ConfigurationElementCollectionType. AddRemoveClearMap, RemoveItemName = "remove")]
Public Children
{
Get
{
Return (Children) base ["children"];
}
Set
{
Base ["children"] = value;
}
}

We often use the construction of key-value pairs similar to the appSettings configuration section. At this time, we don't have to implement it ourselves. We can directly use the existing System. configuration. nameValueConfigurationCollection class to define a custom key-value pair. The following attributes can be defined in the Complex class:Copy codeThe Code is as follows: [ConfigurationProperty ("NVs", IsDefaultCollection = false)]
Public System. Configuration. NameValueConfigurationCollection NVs
{
Get
{
Return (NameValueConfigurationCollection) base ["NVs"];
}
Set
{
Base ["NVs"] = value;
}
}

Then, add the key-Value Pair configuration in the complex section of the configuration file.Copy codeThe Code is as follows: <NVs>
<Add name = "abc" value = "123"/>
<Add name = "abcd" value = "12d3"/>
</NVs>

This basically satisfies all the Configuration Requirements. However, a larger but not complex concept is the sectionGroup. We can customize the SectionGroup and configure multiple sections in the sectionGroup. grouping is meaningful for large applications.
The following configuration configures a sectionGroup that contains simple and complex sections.
Copy codeThe Code is as follows: <? Xml version = "1.0" encoding = "UTF-8"?>
<Configuration>
<ConfigSections>
<SectionGroup type = "ConfigExample. Configuration. SampleSectionGroup, ConfigExample" name = "sampleGroup">
<Section type = "ConfigExample. Configuration. SimpleSection, ConfigExample" allowDefinition = "Everywhere" name = "simple"/>
<Section type = "ConfigExample. Configuration. ComplexSection, ConfigExample" allowDefinition = "Everywhere" name = "complex"/>
</SectionGroup>
</ConfigSections>
<SampleGroup>
<Simple maxValue = "20" minValue = "1">
</Simple>

<Complex height = "190">
<Child firstName = "James" lastName = "Bond"/>
<Children>
<Add firstName = "Zhao" lastName = "yukai"/>
<Add firstName = "Lee" lastName = "yukai"/>
<Remove firstName = "Zhao"/>
</Children>
<NVs>
<Add name = "abc" value = "123"/>
<Add name = "abcd" value = "12d3"/>
</NVs>
</Complex>
</SampleGroup>
</Configuration>

To facilitate the access to the section in sectionGroup, we can implement a custom class inherited from the System. Configuration. ConfigurationSectionGroup class. The implementation is simple, that is, the Section is returned through the base class Sections ["sectionName"] indexer. As follows:Copy codeThe Code is as follows: public class SampleSectionGroup: System. Configuration. ConfigurationSectionGroup
{
Public SimpleSection Simple
{
Get
{
Return (SimpleSection) base. Sections ["simple"];
}
}

Public ComplexSection Complex
{
Get
{
Return (ComplexSection) base. Sections ["complex"];
}
}
}

Note that SectionGroup cannot be obtained using the ConfigurationManager. GetSection (string) method. To obtain the sectionGroup, you must use the SectionGroups [string] indexer of the Configuration class. The following sample code:Copy codeThe Code is as follows: SampleSectionGroup sample = (SampleSectionGroup) ConfigurationManager. OpenExeConfiguration (ConfigurationUserLevel. None). SectionGroups ["sampleGroup"];

Summary:
. Net framework provides us with a very convenient configuration library, we only need to inherit the corresponding class simple configuration, you can easily use in the web. config or app. the custom node configured in config.
Source code of the custom configuration file section

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.