Create custom configuration nodes (both Web. config and app. config apply)

Source: Internet
Author: User

Both Web programs, Windows programs, Windows service programs, and configuration files are indispensable. We're all used to it. Place the connection string in the ConnectionString node and place the program's settings in the AppSetting node. The configuration file management program gives us a convenient way to manage, so how do we customize the configuration node?

There are two ways, one, to inherit IConfigurationSectionHandler, by implementing the Create method. The flexibility of this method is very large, we need to resolve the XmlNode of the custom node, so it is more complicated to implement. Second, the inheritance of ConfigurationSection, this method is much simpler, only need to specify the corresponding property name.

The purpose of this article is to implement a custom configuration node with minimal code, so you decisively discard the first method and use the second method to implement a custom configuration node.

Light say no practice fake bashi, next we proceed to implement the custom configuration node using the second method. The steps are as follows:

1. Define Custom Configuration node information in the configsections node

  <configSections>
<section name= "Custom" type= "SampleWebConfigSection.Configuration.customSection, samplewebconfigsection"/>
</configSections>
    • Name: Names of custom configuration nodes
    • Type: types, custom configuration node corresponding data type
2. Complete the structure of the Custom configuration node
<custom filename= "Default.txt" maxusers= "2500" maxidletime= "00:10:00"/>

3. Programming to achieve node access

Using System.Configuration;
Using System;

Namespace Samplewebconfigsection.configuration
{
public class Customsection:configurationsection
{
[ConfigurationProperty ("FileName", defaultvalue = "Default.txt", IsRequired = True, IsKey = False)]
[Stringvalidator (invalidcharacters = "[Email protected]#$%^&* () []{}/; ') \ "|\\", MinLength = 1, MaxLength = 60)]
public string FileName
{
get {return (string) this["FileName"];}
set {this["fileName"] = value;}
}

[ConfigurationProperty ("maxUsers", DefaultValue = (long) 10000, isrequired = False)]
[Longvalidator (MinValue = 1, MaxValue = 10000000, Excluderange = False)]
Public long MaxUsers
{
get {return (long) this["MaxUsers"];}
set {this["maxUsers"] = value;}
}

[ConfigurationProperty ("MaxIdleTime", defaultvalue = "0:10:0", IsRequired = False)]
[Timespanvalidator (minvaluestring = "0:0:30", maxvaluestring = "5:00:0", Excluderange = False)]
Public TimeSpan MaxIdleTime
{
get {return (TimeSpan) this["MaxIdleTime"];}
set {this["maxidletime"] = value;}
}
}
}
    • ConfigurationProperty flag: Instructs the. NET Framework to instantiate the field values of an object through the properties of the custom node. For each property marked with this attribute, the. NET Framework uses reflection to read the decorated parameters and creates the associated ConfigurationProperty instance.
    • Stringvalidator markup: Declaratively instructs the. NET Framework to perform string validation on configuration properties.
    • Longvalidator markup: Declaratively indicates the. NET Framework pair Configuration properties for the CEO integer validation.
    • Timespanvalidator markup: Declaratively instructs the. NET Framework to perform time validation on configuration properties.
4. Use of custom configuration nodes
    CustomSection custom = (customsection) System.Configuration.ConfigurationManager.GetSection ("Custom");
Response.Write (Custom. FileName + "|" + Custom. Maxusers.tostring () + "|" + Custom. MaxIdleTime);

In the first line of code, we get the custom node through configurationmanager.getsection and force the type to be converted to our custom node, which makes it easy to use.

OK, the first example is done. In fact, this example is on MSDN, I took it down, a little bit of clarification.

Of course, only the above content is not enough to put the home page. The above example does not fully meet our regular requirements, and even we can put these configurations in appsetting instead of our custom configuration nodes. Here's a real-world requirement:

In the construction of the website, we want to put the title, subtitle and URL of the site in a configuration, because the site has the file upload function, we want to limit the size of the upload file in the configuration, and for different upload types to put the file in a different directory. The following node structure is determined:

  <webSetting>
<base title= "thatched &amp; scavenger" subtitle= "7-kilometer Deep Blue Blog" url= "http://youring2.cnblogs.com" ></base>
<fileUpload>
<file name= "Headphoto" path= "Upload/image/headphoto" size= "></file>"
<file name= "album" Path= "Upload/image/album" size= "1024x768" ></file>
</fileUpload>
</webSetting>

To complete this custom configuration node, follow the first example step and we need to configure the custom node information in configsections now:

<section name= "websetting" type= "SampleWebConfigSection.Configuration.webSettingSection, Samplewebconfigsection "/>

Not explained, next we need to complete four classes:

    • Websettingsection
    • Basesection
    • Fileuploadsection
    • Filesection
These four classes correspond to the four nodes in this configuration: websetting, Base, FileUpload, and file.
Using System.Configuration;


{
public class Websettingsection:configurationsection
{
Base node
[ConfigurationProperty ("base")]
Public basesection basesetting {get {return (basesection) base["base"];}}

FileUpload node
[ConfigurationProperty ("FileUpload")]
Public fileuploadsection fileuploadsetting {get {return (fileuploadsection) base["FileUpload"];}}
}
}

Derived from ConfigurationSection, contains two properties: Basesetting and fileuploadsetting, which correspond to the two child nodes base and FileUpload in the configuration file, respectively.

Using System.Configuration;

Namespace Samplewebconfigsection.configuration
{
public class Basesection:configurationelement
{
Title Property
[ConfigurationProperty ("title", IsKey = True, IsRequired = True)]
public string Title {get {return (string) base["title"];} set {title = value;}}
Subtitle Property
[ConfigurationProperty ("SubTitle", isrequired = False, Defaultvalue= "")]
public string SubTitle {get {return (string) base["SubTitle"];} set {subTitle = value;}}
URL Properties
[ConfigurationProperty ("url", IsRequired = True)]
public string URL {get {return (string) base["url"];} set {url = value;}}
}
}

Derived from ConfigurationElement because it is a child element and is included in the Websettingsection class. Several of its properties are not explained.

Using System.Configuration;

Namespace Samplewebconfigsection.configuration
{
[Configurationcollection (typeof (Filesection), additemname = "file")]
public class Fileuploadsection:configurationelementcollection
{
protected override ConfigurationElement Createnewelement ()
{
return new Filesection ();
}

protected override Object Getelementkey (configurationelement Element)
{
Return ((filesection) Element). Name;
}

Public filesection This[int Index]
{
get {return (filesection) base. Baseget (index); }
}

New public filesection this[string name]
{
get {return (filesection) base. Baseget (name); }
}
}
}

Derived from ConfigurationElementCollection because it is a collection of child elements that contains a collection of filesection.

This class uses the following markup:

[Configurationcollection (typeof (Filesection), additemname = "file")]

This is a description of the collection of child elements, the first type parameter is required, and it specifies the type that contains the subset. The second parameter is optional, it specifies the node name of the child node to be added to the collection, the default is add, we do not use the default value, but instead uses "file", so it is specified here.

In addition, this class implements the method of obtaining a filesection through index and name, respectively This[int index] and this[string name]. The base class itself has a way to get child elements through a string, so use the new keyword here.

Using System.Configuration;

Namespace Samplewebconfigsection.configuration
{
public class Filesection:configurationelement
{
Name property
[ConfigurationProperty ("name", IsKey = True, IsRequired = True)]
public string Name {get {return (string) this["name"];} set {name = value;}}
Path property
[ConfigurationProperty ("path", IsRequired = True)]
public string Path {get {return (string) this["path"];} set {path = value;}}
Size Property
[ConfigurationProperty ("size", IsRequired = true, DefaultValue = 1024)]
public int Size {get {return (int) this["size"];} set {size = value;}}
}
}

Derived from ConfigurationElement. Its properties are simple and not explained.

We can use this configuration node using a method that uses a custom configuration node as in the first example. But usually we don't want to reload the configuration item every time we use it, so we access this configuration node through a static object:

Namespace Samplewebconfigsection.configuration
{
public class Websettingmanager
{
public static Websettingsection websetting = (websettingsection) System.Configuration.ConfigurationManager.GetSection ("websetting");
}
}

Test if our custom configuration node works, add the following code to the site's page:

<asp:content id= "bodycontent" runat= "Server" contentplaceholderid= "MainContent" >
<asp:label id= "Lbltitle" text= "" runat= "Server"/>
<asp:label id= "Lblsubtitle" text= "" runat= "Server"/>
Address: <asp:label id= "Lblurl" text= "" runat= "Server"/>
<p></p><p></p>
<asp:gridview id= "gvfileuploadsetting" runat= "Server" width= "backcolor=" #F0F8FF "autogeneratecolumns=" false ">
<Columns>
<asp:templatefield headertext= "Name" >
<itemstyle font-bold= "false"/>
<ItemTemplate>
<% #Eval ("name")%>
</ItemTemplate>
</asp:TemplateField>
<asp:templatefield headertext= "Path" >
<itemstyle font-bold= "false"/>
<ItemTemplate>
<% #Eval ("path")%>
</ItemTemplate>
</asp:TemplateField>
<asp:templatefield headertext= "Size" >
<itemstyle font-bold= "false"/>
<ItemTemplate>
<% #Eval ("size")%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</asp:Content>

  

        protected void Page_Load (object sender, EventArgs e)
{
This. Title = WebSettingManager.WebSetting.BaseSetting.title + "-" + WebSettingManager.WebSetting.BaseSetting.subTitle;
This.lblTitle.Text = WebSettingManager.WebSetting.BaseSetting.title;
This.lblSubTitle.Text = WebSettingManager.WebSetting.BaseSetting.subTitle;
This.lblUrl.Text = WebSettingManager.WebSetting.BaseSetting.url;

This.gvFileUploadSetting.DataSource = WebSettingManager.WebSetting.FileUploadSetting;
This.gvFileUploadSetting.DataBind ();
}

Create custom configuration nodes (both Web. config and app. config apply)

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.