Click here to Skip to main content
15,881,455 members
Articles / Web Development / ASP.NET

Custom Configuration Sections in app.config or web.config

Rate me:
Please Sign up or sign in to vote.
3.86/5 (7 votes)
31 Jul 2011CPOL2 min read 55.2K   18   3
How to define our own custom configuration section

There are certain scenarios where we need to define our own custom configuration section. I have recently faced one where I had to Store the key value pairs as given below:

XML
<FilterHashKey>
  <FilterKeys>
    <add key="722ACP" value="722ACP" />
    <add key="722ARI" value="722ARI" />
    <add key="722BIA" value="722BIA" />
    <add key="722MHI" value="722MHI" />
    <add key="722PSP" value="722PSP" />
    <add key="722TCP" value="722TCP" />
    <add key="722OCS" value="722OCS" />
    <add key="722KCD" value="722KCD" />
    <add key="722KRT" value="722KCD" />
  </FilterKeys>
</FilterHashKey>

It should be flexible enough so that the users can add or delete the key values at any point of time without building and deploying the code again and again for every change.

Before I get into this topic, I guess you should familiarize yourself with the following few terms:

  • ConfigurationSection -- This is the returned object that will hold onto your custom element
  • ConfigurationElementCollection -- This is the element that you create the describes your collection of data
  • ConfigurationElement -- This is the element that you create that will describe your object/entity for the data.

Now add an app.config or web.config in your application if you don't have one already present.

Once you finished adding the app.config, add the following few lines inside the <configSections>.

XML
<configSections>
  <section name="FilterHashKey" 
  type="CustomConfigApp.ConfigHelper, CustomConfigApp"/>
</configSections>

Here in the configuration above, the name attribute should be exactly the same as that of the Custom configuration section which is given below:

XML
<FilterHashKey>
  <FilterKeys>
    <add key="722ACP" value="722ACP" />
    <add key="722ARI" value="722ARI" />
    <add key="722BIA" value="722BIA" />
    <add key="722MHI" value="722MHI" />
    <add key="722PSP" value="722PSP" />
    <add key="722TCP" value="722TCP" />
    <add key="722OCS" value="722OCS" />
    <add key="722KCD" value="722KCD" />
    <add key="722KRT" value="722KCD" />
  </FilterKeys>
</FilterHashKey>

In the section given above, we have given the actual data which is going to hold the key value pairs information.

Now since our app.config file is ready with all the information, let's move to the code where we are going to use some of the System.Configuration classes and methods. To start with this, I had created a file called ConfigHelper.cs. This class consists of three classes, namely ConfigHelper (derived from ConfigurationSection), FilterHashKeyCollection, (derived from ConfigurationElementCollection) and FilterHashKeyElement (derived from ConfigurationElement). The code is given below:

C#
using System.Configuration;
 
namespace CustomConfigApp
{
    public class ConfigHelper : ConfigurationSection
    {
        [ConfigurationProperty("FilterKeys")]
        public FilterHashKeyCollection HashKeys
        {
            get { return ((FilterHashKeyCollection)(base["FilterKeys"])); }
        }
    }
 
    [ConfigurationCollection(typeof(FilterHashElement))]
    public class FilterHashKeyCollection : ConfigurationElementCollection
    {
        protected override ConfigurationElement CreateNewElement()
        {
            return new FilterHashElement();
        }
 
        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((FilterHashElement)(element)).Key;
        }
 
        public FilterHashElement this[int idx]
        {
            get
            {
                return (FilterHashElement)BaseGet(idx);
            }
        }
    } 
    
    public class FilterHashElement : ConfigurationElement
    {
        [ConfigurationProperty("key", DefaultValue = "", 
         IsKey = true, IsRequired = true)]
        public string Key
        {
            get
            {
                return ((string)(base["key"]));
            }
            set
            {
                base["key"] = value;
            }
        }
 
        [ConfigurationProperty("value", 
          DefaultValue = "", IsKey = false, IsRequired = false)]
        public string Value
        {
            get
            {
                return ((string)(base["value"]));
            }
            set
            {
                base["value"] = value;
            }
        }
    }
}

Here, the ConfigurationSection helps us to populate the custom handler at runtime from the ConfigurationManager. The ConfigurationProperty(“FilterKeys”) should match the root node that contains all the items in app.config. FilterHashCollection is holding each of the custom config elements and finally the class FilterHashElement will describe the custom data from app.config file. The ConfigurationProperty(“key’) needs to map to the XML element in the app.config one-to-one for each of the elements.

Now that we have all the data and classes setup, here is how you actually get the data out of the app.config file and into your custom data model.

Well that’s it, you can refer to this link for more information. And you can download the sample code from here.  Hope this helps!

~Brij Mohan

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead Mphasis Limited
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionHow do you modify the section type? Pin
VcDevelopment2-May-13 20:23
VcDevelopment2-May-13 20:23 
GeneralMy vote of 3 Pin
AmitMukherjee4-Mar-13 0:26
AmitMukherjee4-Mar-13 0:26 
GeneralMy vote of 1 Pin
ojanacek16-Feb-13 2:27
ojanacek16-Feb-13 2:27 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.