CODEDIGEST
Home » Articles
Search
 

Technologies
 

Sponsored links
 

CodeDigest Navigation
 

Technology News
No News Feeds available at this time.
 

Community News
No News Feeds available at this time.
 
Creating Custom Configuration Section and Elements in ASP.Net

By Bala Murugan
Posted On Feb 03,2011
Article Rating:
Be first to rate
this article.
No of Comments: 5
Category: ASP.Net
Print this article.

Creating Custom Configuration Section and Elements in ASP.Net

If you consider any application it will have some settings that should be configurable easily for the application to function.  Normally, these settings will be captured in XML files or database tables whichever suits the need.  Likewise, ASP.Net application includes a special type of XML file called Web.config file which stores some framework related configuration settings that helps the ASP.Net application to work. Apart from the framework related settings, Web.config file allows us to put some of our application specific settings in a section called appSettings. We can configure appSettings with some key value pair of setting information which can be across the application.

Sometimes, it is necessary where we will require a custom configuration sections or elements where we can put some configuration settings. For example, when you develop a custom framework component or custom control for your project you may want to put its configuration setting in a more specific way rather than putting it into appSettings. For this purpose, the System.Configuration namespace has 3 abstract classes packed with it namely ConfigurationSection, ConfigurationElement and ConfigurationElementCollection.

Moving forward, we will understand how to create custom configuration sections and elements in this article. For understanding this article, we will assume we are creating eLearning site where you want to store the information related to the eLearning like below.

<eLearning category="Cooking" mode="Offline"> </eLearning>

 

Steps

1.      Create an Asp.Net application with C# as language in your Visual Studio 2008.

2.      Include a class called eLearningConfigSection in your solution and inherit it from ConfigurationSection class in System.Configuration namespace. Create two public properties called Category and Mode by decorating it with ConfigurationProperty attribute. You can configure the name, default value and specify if the property is mandatory using ConfigurationProperty attribute. See below,

public class eLearningConfigSection : ConfigurationSection

{

    [ConfigurationProperty("category", DefaultValue = "Technology", IsRequired = false)]

    public string Category

    {

        get

        {

            return this["category"] as string;

        }

    }

 

    [ConfigurationProperty("mode", IsRequired = true)]

    public string Mode

    {

        get

        {

            return this["mode"] as string;

        }

    }  

 

}

 

Please note that whatever name you specify in ConfigurationProperty attribute will be the actual property name in custom configuration section in web.config file and is case sensitive. Also, include System.Configuration namespace for the above code to work.

3.      Now, to use the above configuration section in your web.config file we need to first register the section with its type in <configSections>. Navigate to the Web.Config file and find the configSections node. Here, we can see other sections registered by the .netframework already. Include our eLearningSection and the type which the ASP.Net should use for our new configuration section like below,

<configSections>

<!-- Other sections -->

<section name="eLearning" type="eLearningConfigSection"/>

</configSections>

 

Make sure you are configuring this setting at right place otherwise you may get an error like “Unrecognized configuration section eLearning.” This setting needs to be directly inside <configSections> tag.

4.      We can now define our custom config section like below.

<eLearning category="Cooking" mode="Offline">  

</eLearning>

 

Make sure you are putting this section out of <system.web> tag.

5.      That’s it; you are now done with adding your new custom config section. Next, we will see how to access or read these settings from code.

 

Read Custom Config Values in Code

We can use ConfigurationManager.GetSection("sectionname") method to read the values from custom config section. See the below code,

    protected void Page_Load(object sender, EventArgs e)

    {

        eLearningConfigSection elearnsetting = ConfigurationManager.GetSection("eLearning") as eLearningConfigSection;

 

        Response.Write(elearnsetting.Category);

        Response.Write("<br>");

        Response.Write(elearnsetting.Mode);

    }

 

The GetSection() method will read xml config values and will desterilize it to the .net object, eLearningConfigSection in our case.

At times, we may also need to add another element inside the custom configuration section. For example, see below.

<eLearning category="Cooking" mode="Offline">

    <company name="Classic Cooks" location="IN"></company>

  </eLearning>

 

To do this, we need to define this new object and make it as a member of our eLearningConfigSection class. Also, this new object should inherit from ConfigurationElement class. To do this, add a new class to your solution called as Company and define 2 properties Name and Location. See below,

public class Company : ConfigurationElement

{

    [ConfigurationProperty("name", IsRequired = true)]

    public string Name

    {

        get

        {

            return this["name"] as string;

        }

    }

 

    [ConfigurationProperty("location", DefaultValue = "US", IsRequired = false)]

    public string Location

    {

        get

        {

            return this["location"] as string;

        }

    }

}

 

Again, note that whatever name you specify in ConfigurationProperty attribute will be the actual property name in custom configuration section and is case sensitive. Also, include System.Configuration namespace for the above code to work.

Next, we have to go back to our eLearningConfigSection class and add Company object as a new property. Refer the below code,

public class eLearningConfigSection : ConfigurationSection

{

    [ConfigurationProperty("category", DefaultValue = "Technology", IsRequired = false)]

    public string Category

    {

        get

        {

            return this["category"] as string;

        }

    }

 

 

    [ConfigurationProperty("mode", IsRequired = true)]

    public string Mode

    {

        get

        {

            return this["mode"] as string;

        }

    }

 

    [ConfigurationProperty("company")]

    public Company Company

    {

        get

        {

            return this["company"] as Company;

        }

    }

}

 

That’s it. You can define a new element called company with name and location inside eLearning section like below,

<eLearning category="Cooking" mode="Offline">

    <company name="Classic Cooks" location="IN"></company>

  </eLearning>

 

To read the above setting in code,

protected void Page_Load(object sender, EventArgs e)

    {

        eLearningConfigSection elearnsetting = ConfigurationManager.GetSection("eLearning") as eLearningConfigSection;

 

        Response.Write(elearnsetting.Category);

        Response.Write("<br>");

        Response.Write(elearnsetting.Mode);

        Response.Write("<br>");

        Response.Write(elearnsetting.Company.Name);

        Response.Write("<br>");

        Response.Write(elearnsetting.Company.Location);

        Response.Write("<br>");

    }

 




Adding Collection of config settings inside Custom Configuration

Sometimes, we may also need to add some collection of key value pairs as configurable items inside our custom configuration settings. In our example, it will be similar to the below,

<eLearning category="Cooking" mode="Offline">

      <company name="Classic Cooks" location="IN"></company>

   <Courses>

     <add name="Burger" duration="2"></add>

     <add name="Pizza" duration="3"></add>

     <add name="Popcorn" duration="2"></add>

   </Courses> 

 </eLearning>

 

To do this, we need to define a property called Courses in eLearningConfigSection class which should be a collection and should inherit from ConfigurationElementCollection object. The new object defined by the collection should have name and duration as properties. See below,

 

public class Course : ConfigurationElement

{

    [ConfigurationProperty("name", IsRequired = true)]

    public string Name

    {

        get

        {

            return this["name"] as string;

        }

    }

 

    [ConfigurationProperty("duration", DefaultValue = "10", IsRequired = true)]

    public int Duration

    {

        get

        {

            return (int)this["duration"];

        }

    }

}

 

 

public class CourseCollection : ConfigurationElementCollection

{

    protected override ConfigurationElement CreateNewElement()

    {

        return new Course();

    }

 

    protected override object GetElementKey(ConfigurationElement element)

    {

        return ((Course)element).Name;

    }

}

 

The CourseCollection object should override CreateNewElement() and GetElementKey() methods of ConfigurationElementCollection to create new object for the elements added in the collection and to get the particular element’s key in the collection.

Finally, add the Courses property of type CourseCollection in eLearningConfigSection class.

public class eLearningConfigSection : ConfigurationSection

{

   //Other properties...

 

    [ConfigurationProperty("Courses")]

    public CourseCollection Courses

    {

        get

        {

            return this["Courses"] as CourseCollection;

        }

    }

}

 

That’s it; you can now configure our custom config section with Courses collection like above.

 

We can also group our custom section inside a section group like below,

  <Learning>

    <eLearning category="Cooking" mode="Offline">

      <company name="Classic Cooks" location="IN"></company>

   <Courses>

     <add name="Burger" duration="2"></add>

     <add name="Pizza" duration="3"></add>

     <add name="Popcorn" duration="2"></add>

   </Courses> 

 </eLearning>

 </Learning>

 

To do this, add the custom configuration’s name and type configuration setting inside <sectionGroup> tag by specifying a group tag name. See below,

<configSections>

<!-- Other sections -->   

   <sectionGroup name="Learning">

      <section name="eLearning" type="eLearningConfigSection"/>

    </sectionGroup>

</configSections>

 

To read the values in code, you need to pass the custom configuration section name as “Learning/eLearning” in order to read successfully. See the below code,

 

eLearningConfigSection elearnsetting = ConfigurationManager.GetSection("Learning/eLearning") as eLearningConfigSection;

 

Downloads

Downloads

Conclusion

Thus, we have seen how to create a new configuration section in asp.net and using it. Also, one has to decide when to use this and it is not advisable to put huge configuration settings data in web.config file as it may be an overhead in a long run. It is indeed a great feature when you would like to make the configuration settings more meaningful by giving the functionality specific custom tags.

Download the source attached with this article and see it in action.

 

Similar Articles
You can contribute to CodeDiget.Com:
Donate to CodeDigest.com
Article Feedback
Comments
You're a real deep t
You're a real deep thrneki. Thanks for sharing. http://cxocoudey.com [url=http://mltxezfchy.com]mltxezfchy[/url] [link=http://awbqde.com]awbqde[/link]
Yo, that's what's up
Yo, that's what's up <a href="http://dnekxzquius.com">truulftlhy.</a>
Finindg this post ha
Finindg this post has solved my problem http://adyztile.com [url=http://niczwhjlty.com]niczwhjlty[/url] [link=http://rbicxudxc.com]rbicxudxc[/link]
I was really confuse
I was really confused, and this answered all my <a href="http://zczzqwmjbp.com">queotisns.</a>
That's really thnnik
That's really thnnikig out of the box. Thanks!