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.
<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" />
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 a 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>
Here in the configuration above the name attribute should be exactly same as of the Custom configuration section which is given below
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.
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.
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.