Wednesday, July 22, 2015

Step By Step : Custom Configuration Section in Configuration File

Hi,

Welcome to my blog. In this post we will see how to add custom configuration section to your config files and read those values. I added a custom configuration section called CountriesConfigSection in my App.config and will read values from it and access them in my Windows form application. In my App.config, the CountriesConfigSection will have entries for states belonging to a particular country. As shown below, I have 4 states for USA country and I will display names of USA states in a combobox in my Windows Form application.

App.Config

















This is just one of the way which I followed  I am not saying this is the best and it doesnot have cons. My main aim is to share my experience so that it will be useful for the needy. I tried to make this post as much interesting as possible. Please excuse me for my grammatical errors and typos. I welcome your constructive comments and suggestions which helps in improving this post and my technical skills.

Overview: 
In this example we will see how we can create custom configuration section in our app.config and how we can access the values in our code. We will create the following projects

1) CustomConfigSections : This is Windows Forms project.

Now let's start our work
For this article, I am using the following tools/technologies to develop a my sample application
Visual Studio 2013
C#
.NET Framework 4.5

I always have the habit of creating empty solution first and then work on it. Here also I did same thing. I created an empty visual studio solution titled "CustomConfigSections"
 I added a new Windows Forms project called "CustomConfigSections".
Solution






















































































Steps:
1) Open your App.config and add do below steps. Please see below screen shot
a) Inside <conifguration> add this
    <configSections>
    <section name="CountriesConfigSection" type="CustomConfigSections.CountriesConfigSection, CustomConfigSections"></section>
  </configSections>

 This step is important. It tells that we are adding our custom configuration section with name and of particular type.
  b) After above step add this
   <CountriesConfigSection>
    <USA>
      <State name="Alabama" capital="Montgomery" symbol ="AL" population="100"/>
      <State name="Alaska" capital="Juneau" symbol ="AS" population="50"/>
      <State name="Arizona" capital="Phoeniz" symbol ="AZ" population="300"/>
      <State name="California" capital="Sacremento" symbol ="CA" population="600"/>
    </USA>
  </CountriesConfigSection>

This is our actual custom config section. Please make sure that it matches the name in step 1 ( above )
App.config must be like below

















Close your App.config and save it and build your solution to make sure nothing broke.

2) Add System.Configuration to your Windows Forms project. 




















3) Create a new class and name it as CountriesConfigSection.cs and add using System.Configuration at top

4) If you examine our custom config section (<CountriesConfigSection>) in App.config you will notice that we have hierarchical structure. We have collection of countries section (CountriesConfigSection) and in that for each country ( USA ) we have State. So lets start from lowest level ( State ) first. Open CountriesConfigSection.cs and create State class which is a Configuration Element like below which creates properties and matches to respective attribute in <State> Configuration Element in App.config inside our custom config section (<CountriesConfigSection>)

public class State : ConfigurationElement
    {
        [ConfigurationProperty("name", IsRequired = true)]
        public string Name
        {
            get { return (string)this["name"]; }
            set { this["name"] = value; }
        }

        [ConfigurationProperty("capital", DefaultValue = "", IsRequired = true)]
        public string Capital
        {
            get { return (string)this["capital"]; }
            set { this["capital"] = value; }
        }

        [ConfigurationProperty("symbol", DefaultValue = "", IsRequired = true)]
        public string Symbol
        {
            get { return (string)this["Symbol"]; }
            set { this["Symbol"] = value; }
        }

        [ConfigurationProperty("population", DefaultValue = "", IsRequired = true)]
        public string Population
        {
            get { return (string)this["population"]; }
            set { this["population"] = value; }
        }       
    }

After State configuration Element we need to create ConfigurationElementCollection that stores all Configuration Elements. Lets create USAStatesCollection class like below

public class USAStatesCollection : ConfigurationElementCollection
    {
        protected override ConfigurationElement CreateNewElement()
        {
            return new State();
        }

        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((State)element).Name;
        }
    }


Now at last we need to create a class to hold our Custom Configuration Section itself. So lets create CountriesConfigSection like below.
This will have a method (GetConfig) that will read App.config and get our custom config section. This also has a property to hold our ConfigurationElementCollection of type <USA>.

public class CountriesConfigSection : ConfigurationSection
    {
        public static CountriesConfigSection GetConfig()
        {
            return (CountriesConfigSection)System.Configuration.ConfigurationManager.GetSection("CountriesConfigSection") ?? new CountriesConfigSection();
        }

        [System.Configuration.ConfigurationProperty("USA")]
        [ConfigurationCollection(typeof(USAStatesCollection), AddItemName = "State")]
        public USAStatesCollection USAStates
        {
            get
            {
                object o = this["USA"];
                return o as USAStatesCollection;
            }
        }
    }

   
At last our CountriesConfigSection.cs must look like below

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;

namespace CustomConfigSections
{
    public class CountriesConfigSection : ConfigurationSection
    {
        public static CountriesConfigSection GetConfig()
        {
            return (CountriesConfigSection)System.Configuration.ConfigurationManager.GetSection("CountriesConfigSection") ?? new CountriesConfigSection();
        }

        [System.Configuration.ConfigurationProperty("USA")]
        [ConfigurationCollection(typeof(USAStatesCollection), AddItemName = "State")]
        public USAStatesCollection USAStates
        {
            get
            {
                object o = this["USA"];
                return o as USAStatesCollection;
            }
        }
    }


    public class State : ConfigurationElement
    {
        [ConfigurationProperty("name", IsRequired = true)]
        public string Name
        {
            get { return (string)this["name"]; }
            set { this["name"] = value; }
        }

        [ConfigurationProperty("capital", DefaultValue = "", IsRequired = true)]
        public string Capital
        {
            get { return (string)this["capital"]; }
            set { this["capital"] = value; }
        }

        [ConfigurationProperty("symbol", DefaultValue = "", IsRequired = true)]
        public string Symbol
        {
            get { return (string)this["Symbol"]; }
            set { this["Symbol"] = value; }
        }

        [ConfigurationProperty("population", DefaultValue = "", IsRequired = true)]
        public string Population
        {
            get { return (string)this["population"]; }
            set { this["population"] = value; }
        }       
    }

    public class USAStatesCollection : ConfigurationElementCollection
    {
        protected override ConfigurationElement CreateNewElement()
        {
            return new State();
        }

        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((State)element).Name;
        }
    }
}


Now save all items and build your solutions to make sure you donot have any errors.

5) Thats all we are done setting up to read custom configuration section in App.config. The final step is to access them and use them in our Winforms application. Please see below code which self explanatory. I am trying to get USA States name and display them in Combobox as shown in below screen shot.

 private void Form1_Load(object sender, EventArgs e)
        {
            List<string> usaStatesNames = null;
            CountriesConfigSection config = CountriesConfigSection.GetConfig();
            if (config != null && config.USAStates != null && config.USAStates.Count > 0)
            {
                usaStatesNames = new List<string>();
                foreach(State usaState in config.USAStates)
                {
                   
                    usaStatesNames.Add(usaState.Name);
                }
            }

            cmbStates.DataSource = usaStatesNames;
            cmbStates.SelectedIndex = 0;
        }




















That's it. Build your code and run the app and if everything goes fine you will get something like shown in above image.

Conclusion:
In this article we learned how we can add custom configuration section in our App.config and how to read them and access them in our Windows Forms application.

Please feel free to let me know your valuable and constructive comments and suggestions which can help me to make this article better and improve my technical and written skills. Last but not the least please excuse me for my grammar and typos.

Thanks and have a nice and wonderful day.

No comments:

Post a Comment

Please add your comments. Please avoid personal attacks and racist comments. Your constructive comments are always welcome. I will try my best to address your comments in time.