Click here to Skip to main content
Click here to Skip to main content
Technical Blog

Custom Configuration Sections in app.config or web.config

, 31 Jul 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
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.

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

Before I get into this topic I guess you should get yourself familiarise 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>

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

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

<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, lets move to the code where we are going to use some if 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 of which is given below.

using System.Configuration;
 
namespace CustomConfigApp
{
    public class ConfigHelper : ConfigurationSection
    {
        /// <span class="code-SummaryComment"><summary>
</span>        /// The value of the property here "Folders"
        /// needs to match that of the config file section
        /// <span class="code-SummaryComment"></summary>
</span>        [ConfigurationProperty("FilterKeys")]
        public FilterHashKeyCollection HashKeys
        {
            get { return ((FilterHashKeyCollection)(base["FilterKeys"])); }
        }
    }
 
    /// <span class="code-SummaryComment"><summary>
</span>    /// The collection class that will store the list of each element/item that
    /// is returned back from the configuration manager.
    /// <span class="code-SummaryComment"></summary>
</span>    [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);
            }
        }
    }
 
    /// <span class="code-SummaryComment"><summary>
</span>    /// The class that holds onto each element returned by the configuration manager.
    /// <span class="code-SummaryComment"></summary>
</span>    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 element.

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.

ConfigHelper section = (ConfigHelper)ConfigurationManager.GetSection("FilterHashKey");
if (section != null)
{
    foreach(FilterHashElement element in section.HashKeys)
        Console.WriteLine(String.Format("Key {0}, Value {1} ", element.Key, element.Value));
 
    Console.WriteLine("\nPress any key to exit...");
    Console.ReadLine();
}

Well that’s it, you can refer http://msdn.microsoft.com/en-us/library/2tw134k3.aspx for more information. And you can download the sample code from here.  Hope this help.

~Brij Mohan

License

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

Share

About the Author

Brij M
Technical Lead Mphasis Limited
India India
No Biography provided
Follow on   Twitter

Comments and Discussions

 
QuestionHow do you modify the section type? PinmemberVcDeveloper12-May-13 21:23 
GeneralMy vote of 3 PinmemberAmitMukherjee4-Mar-13 1:26 
GeneralMy vote of 1 PinmemberFaithcz16-Feb-13 3:27 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.1411023.1 | Last Updated 31 Jul 2011
Article Copyright 2011 by Brij M
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid