Create a custom configuration node (both web.config and app.config are applicable)

Create a custom configuration node (both web.config and app.config are applicable)

  Annoyed! I accidentally clicked on the full screen mode and lost everything I just wrote! ! Start all over again! ! !

  Whether it is a web program, a windows program, or a windows service program, configuration files are indispensable. We are all used to putting the connection string in the ConnectionString node and the settings of the program in the appSetting node. The configuration file management program provides us with a convenient management method, so how do we customize the configuration node?

  There are two methods. One is to inherit IConfigurationSectionHandler and implement the Create method. This method is very flexible, we need to parse the XmlNode of the custom node, so it is more complicated to implement. 2. inherit ConfigurationSection, this method is much simpler, you only need to specify the corresponding attribute name.

  This article aims to use the least code to implement a custom configuration node, so decisively abandon the first method and use the second method to implement a custom configuration node.

  Just talk about the fake handle, and then we will start to use the second method to implement custom configuration nodes. Proceed as follows:

  1. Define custom configuration node information in the configSections node

  <configSections>
    <section name="custom" type="SampleWebConfigSection.Configuration.customSection, SampleWebConfigSection"/>
  </configSections>
  • name: the name of the custom configuration node
  • type: type, the data type corresponding to the custom configuration node

  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 = "~!@#$%^&*()[]{}/;'\"|\\", 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 tag: Instructs the .NET Framework to instantiate the field value of the object through the properties of the custom node. For each property marked with this characteristic, the .NET Framework uses reflection to read the decorated parameters and create related ConfigurationProperty instances.
  • StringValidator tag: Instructs the .NET Framework to perform string validation on configuration properties in a declarative manner.
  • LongValidator tag: Instructs the .NET Framework to perform long integer validation on configuration properties in a declarative manner.
  • TimeSpanValidator tag: Instructs .NET Framework to perform time validation on configuration properties in a declarative manner.

  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 sentence of code, we get the custom node through ConfigurationManager.GetSection, and force the type conversion to our custom node, so that it can be used conveniently.

  OK, the first example is complete. In fact, this example is from MSDN. I will take it down and explain it a little bit.

  Of course, only the above content is not enough for the home page. The above example does not fully meet our regular needs, and we can even put these configurations in appSetting to replace our custom configuration nodes. Here is a practical requirement:

  In the construction of the website, we hope to put the title, subtitle and URL of the website in a configuration, because the website has a file upload function, we want to limit the size of the uploaded file in the configuration, and place the file in accordance with different upload types In different directories. The node structure after setting is as follows:

  <webSetting>
    <base title="Thatched House&Waste Pickup" subTitle="A seven-kilometer deep blue blog" url="http://youring2.cnblogs.com"></base>
    <fileUpload>
      <file name="headPhoto" path="upload/image/headPhoto" size="200"></file>
      <file name="album" path="upload/image/album" size="1024"></file>
    </fileUpload>
  </webSetting>

  To complete this custom configuration node, following the steps in the first example, we need to configure the custom node information in configSections now:

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

  No explanation, next we need to complete four categories:

  • webSettingSection
  • baseSection
  • fileUploadSection
  • fileSection

  These four classes correspond to the four nodes in this configuration: webSetting, base, fileUpload, and file.

using System.Configuration;

namespace SampleWebConfigSection.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, it contains two attributes: 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 attribute
        [ConfigurationProperty("title", IsKey = true, IsRequired = true)]
        public string title {get {return (string)base["title"];} set {title = value;}}
       //subTitle attribute
        [ConfigurationProperty("subTitle", IsRequired = false, DefaultValue="")]
        public string subTitle {get {return (string)base["subTitle"];} set {subTitle = value;}}
       //url attribute
        [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 contained 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, it contains a collection of fileSection.

  This class uses the following tags:

[ConfigurationCollection(typeof(fileSection), AddItemName = "file")]

  This is a description of a set of sub-elements. The first type parameter is required. 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 did not use the default value, but used "file", so we specified it here.

  In addition, this class also implements methods to obtain a fileSection by index and name, which are this[int index] and this[string name], respectively. The base class itself has a method to obtain child elements through a string, so the new keyword is used here.

using System.Configuration;

namespace SampleWebConfigSection.Configuration
{
    public class fileSection: ConfigurationElement
    {
       //name attribute
        [ConfigurationProperty("name", IsKey = true, IsRequired = true)]
        public string name {get {return (string)this["name"];} set {name = value;}}
       //path attribute
        [ConfigurationProperty("path", IsRequired = true)]
        public string path {get {return (string)this["path"];} set {path = value;}}
       //size attribute
        [ConfigurationProperty("size", IsRequired = true, DefaultValue = 1024)]
        public int size {get {return (int)this["size"];} set {size = value;}}
    }
}

  Derived from ConfigurationElement. Its properties are very simple and do not explain.

  We can use this configuration node in the same way as the custom configuration node 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");
    }
}

  To test whether our custom configuration node works well, add the following code to the page of the website:

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <h2>
        <asp:Label ID="lblTitle" Text="" runat="server"/>
    </h2>
    <h3>
         <asp:Label ID="lblSubTitle" Text="" runat="server"/>
    </h3>
    Address: <asp:Label ID="lblUrl" Text="" runat="server"/>
    <p></p><p></p>
    <asp:GridView ID="gvFileUploadSetting" runat="server" Width="300" BackColor="#F0F8FF" AutoGenerateColumns="false">
        <Columns>
            <asp:TemplateField HeaderText="name">
                <HeaderStyle Width="80px" Font-Bold="true"/>
                <ItemStyle Font-Bold="false"/>
                <ItemTemplate>
                    <%#Eval("name")%>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Path">
                <HeaderStyle Width="160px" Font-Bold="true"/>
                <ItemStyle Font-Bold="false"/>
                <ItemTemplate>
                    <%#Eval("path")%>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Size">
                <HeaderStyle Width="60px" Font-Bold="true"/>
                <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();
        }

  Run the website, we can see the following interface, indicating that our configuration node is available:

We can rest, haha, attach the source code: http://files.cnblogs.com/youring2/SampleWebConfigSection.rar

In addition, by implementing the System.Configuration.IConfigurationSectionHandler interface to achieve custom configuration nodes interested friends can click here

Attach the addresses of the two implementation methods on MSDN:

http://msdn.microsoft.com/zh-cn/library/2tw134k3(v=VS.100).aspx

http://msdn.microsoft.com/zh-cn/library/ms228056.aspx

We can really take a break. If you think this article is good, clicking on the referral link will not take much effort, but it can give me a lot of encouragement. Thank you for your attention!

-------------------------------------------------

ps. Add a little Configuration custom node structure:

  • ConfigurationSection: the outermost node corresponding to the entire custom node Xml
  • ConfigurationElement: a child node under the Section node, does not contain a collection
  • ConfigurationElementCollection: corresponding to the Element collection
Reference: https://cloud.tencent.com/developer/article/1513835 Create a custom configuration node (both web.config and app.config are applicable)-Cloud + Community-Tencent Cloud