Creating a Simple Configuration Section Handler Using ASP.NET 2.0
 
Published: 20 Jul 2006
Unedited - Community Contributed
Abstract
In this article Jason examines how to create a simple configuration section handler using ASP.NET 2.0 with the help of code samples.
by Jason N. Gaylord
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 41933/ 47

Introduction

In ASP.NET 1.x it was fairly difficult to create a custom configuration section in ASP.NET 2.0. Many enterprise applications then relied upon the AppSettings section, saving the configuration in an XML file or storing the settings in another data medium.  Microsoft recognized this and decided to enhance the Configuration API.  For the purpose of this article we will create a simple, one line configuration section with two attributes.  We will also assume that we will be adding the code files to the App_Code folder in our project.

Creating the Configuration Handler

To create the configuration handler, we will need to create a new class and import the System.Configuration namespace.  Our new class will also have to inherit the ConfigurationSection class.  In version 1.x the handler would implement the IConfigurationSectionHandler interface.  However, that interface has now deprecated.  Continuing on, we will add an empty construct and a "loaded" construct.  I consider a class containing a construct with all attributes a loaded construct.  We will also add two properties to the class and two attributes to each property.  In Listing 1 an example of this is shown in both Visual Basic and C#.

Listing 1 - An example of a Configuration Handler in Visual Basic .NET and C#

[Visual Basic .NET]

'Class that creates the configuration handler
 
Public Class MyCustomConfigurationHandler
  Inherits ConfigurationSection
 
  'Empty Construct
 
  Public Sub MyCustomConfigurationHandler()
  End Sub
 
  'Loaded Construct
 
  Public Sub MyCustomConfigurationHandler(ByVal firstValue As Integer, _
                                          secondValue As Integer)
 
    FirstNumber = firstValue
    SecondNumber = secondValue
  End Sub
 
  'First Number Property
  <ConfigurationProperty("firstNumber", DefaultValue
   = 1, IsRequired
   = True)> _
     <IntegerValidator(MinValue
   = -100, MaxValue
   = 100)> _
     Public Property FirstNumber() As Integer
  Get
  Return CInt(Me("firstNumber"))
  End Get
  Set(ByVal Value As Integer)
  Me("firstNumber"= Value
  End Set
End Property
 
'Second Number Property
<ConfigurationProperty("secondNumber", DefaultValue
 = 1, IsRequired
 = True)> _
   <IntegerValidator(MinValue
 = -100, MaxValue
 = 100)> _
   Public Property SecondNumber() As Integer
Get
Return CInt(Me("secondNumber"))
End Get
Set(ByVal Value As Integer)
Me("secondNumber"= Value
End Set
End Property
 
End Class

[Visual C# .NET]

// Class that creates the configuration handler
public class MyCustomConfigurationHandler: ConfigurationSection
{
 
// Empty Construct
  public MyCustomConfigurationHandler(){}
 
// Loaded Construct
  public MyCustomConfigurationHandler(Int32 firstValue, Int32 secondValue)
  {
    FirstNumber = firstValue;
    SecondNumber = secondValue;
  }
 
// First Number Property
  [ConfigurationProperty("firstNumber", DefaultValue = 1, IsRequired = true)
    ][IntegerValidator(MinValue =  - 100, MaxValue = 100)]
  public Int32 FirstNumber
  {
    get
    {
      return (Int32)this["firstNumber"];
    }
    set
    {
      this["firstNumber"= value;
    }
  }
 
// Second Number Property
  [ConfigurationProperty("secondNumber", DefaultValue = 1, IsRequired = true)
    ][IntegerValidator(MinValue =  - 100, MaxValue = 100)]
  public Int32 SecondNumber
  {
    get
    {
      return (Int32)this["secondNumber"];
    }
    set
    {
      this["secondNumber"= value;
    }
  }
}

The ConfigurationProperty attribute for the property has only one required field and that is the property name as specified in the web.config file.  The DefaultValue attribute field is just that.  It is the default value for the property.  The IsRequired attribute field specifies whether or not the property is required to be contained in the configuration section's attribute list.

Adding the Handler to the web.config File

Now that the handler has been created, we need to add a reference to it in the web.config file.  To do so we will add a new section under <configuration> called <configSections>.  This section lists all configuration sections that we would like to add to the web.config file besides the sections already specified in the machine.config.  Within the <configSections> section, we will add another new section called <sectionGroup>.  The <sectionGroup> section will also have a name attribute that will need to be set.  This defines the section group name that we will use within our web.config file.  Finally, we add one more section below the <sectionGroup> called <section>. We will need to add the name and type to this section.  The name specifies the name of the section and the type specifies the class declaration type for the section.  An example of the web.config file is shown is Listing 2.

Listing 2 - Adding a configuration section to the web.config file

<configSections>
  <sectionGroup name="customSection">
    <section name="settings" type="MyCustomConfigurationHandler"
      allowLocation="true" allowDefinition="Everywhere" />
  </sectionGroup>
</configSections>

Since we have placed our code file in the App_Code folder, our type will only need to be our class name.  However, this is not always the case.  Let us say we built our handler and placed it inside of the namespace "MyApplication."  We then compiled the code and placed it into our bin file.  The compiled DLL had a name of MyApplication.dll.  In this case, our configuration section would appear similar to the one in Listing 3.

Listing 3 - Adding a configuration section to the web.config file if the configuration section is in a namespace and a compiled DLL

<configSections>
  <sectionGroup name="customSection">
    <section name="settings" type="MyApplication.MyCustomConfigurationHandler,
      MyApplication" allowLocation="true" allowDefinition="Everywhere" />
  </sectionGroup>
</configSections>

We can add some additional attributes to the type definition, such as version number and locale.

Now that the configuration section has been added to the <configSections> section, we can use it.  Listing 4 shows an example of how to use the section in the web.config file.

Listing 4 - Using the newly added section in the web.config file

<customSection>
  <settings firstNumber="20" secondNumber="43" />
</customSection>
Using the Configuration Section in Code

Now that we have our configuration section setup, we can use the new settings in our code.  In ASP.NET 2.0, Microsoft introduced a new class in System.Configuration called ConfigurationManager.  The ConfigurationManager class is very useful as it will allow us to retrieve and set nearly any value in our web application.  In our application we will use the GetSection method and pass in an XPath value.  An example of how to retrieve the settings in Visual Basic and C# are shown in Listing 5.

Listing 5 - Referencing values in the new configuration section

[Visual Basic .NET]

Dim config As New MyCustomConfigurationHandler
config = System.Configuration.ConfigurationManager.GetSection("customSection/settings")
Response.Write(config.FirstNumber.ToString())
Response.Write(config.SecondNumber.ToString())

[Visual C# .NET]

MyCustomConfigurationHandler config =
 (MyCustomConfigurationHandler)
System.Configuration.ConfigurationManager.GetSection("customSection/settings");
Response.Write(config.FirstNumber.ToString());
Response.Write(config.SecondNumber.ToString());
Downloads

Conclusion

As you can see, it is fairly simple to create a custom configuration section in ASP.NET 2.0.  In this article you read about the process from start to finish.  You can download the sample template projects in both Visual Basic and C# formats by clicking on the download link.  The download is a zip file containing a Visual Studio Installer (VSI) file.  To install, download the zip file, extract the VSI file, double-click on the file, and follow the instructions.



User Comments

Title: 2012 NFL jerseys   
Name: NIKE NFL jerseys
Date: 2012-07-02 10:11:22 AM
Comment:
http://www.jersey2shop.com
http://www.cheapjersey2store.com
http://www.jerseycaptain.com
http://www.yourjerseyhome.com
We are professional jerseys manufacturer from china,wholesal.cheap nike nfl jerseys, mlb jerseys, nhl jerseys,nba jerseys and shoes
Cheap NFL,NBA,MLB,NHL
,heap jerseys,2012 nike nfl Jerseys,nba jersey and shorts,oklahoma city thunder jersey,official jeremy lin new york knicks jersey,NFL Jerseys Wholesale,blake griffin jersey blue,NFL jerseys For Sale online.All Our Jerseys Are Sewn On and Directly From Chinese Jerseys Factory
,Wholesale cheap jerseys,Cheap mlb jerseys,]Nike NFL Jerseys,Cheap China Wholesae,Wholesale jerseys From China,2012 nike nfl Jerseys,Jerseys From China,,2012 nike nfl Jerseys,Revolution 30 nba jerseys,jersey of nba chicago bulls direk rose ,nfl jerseys,green bay packers jerseys wholesale,Buffalo Bills nike nfl jerseys sale,good supplier soccer jerseys,cool base mlb jerseys,Revolution 30 nba jerseys,2012 stanley cup nhl jersey,
We are professional jerseys manufacturer from china,wholesal.cheap nike nfl jerseys, mlb jerseys, nhl jerseys,nba jerseys and shoes. www.yourjerseyhome.com
Title: Thank you.   
Name: Gordon
Date: 2011-05-07 5:23:11 PM
Comment:
Wow, you wouldn't believe how hard it is to find such a clear way to implement a custom section handler. You rock.
Title: Thanks   
Name: Andre Albuquerque
Date: 2011-05-06 12:37:15 PM
Comment:
Thanks for your article. Simple enough to absorb the CustomConfigurationHandler thing.

I was having trouble with the
type= "MyApplication.MyCustomConfigurationHandler, MyApplication" part because MyApplication was in the form ABC-Program, so the Handler was converted to (note the _) ABC_Program.MyCustomConfigurationHandler and the .dll was ABC-Program.dll

Without your explanation I would have lost much more time, since the Exception thrown hadn't any useful details (System.Exception._COMPlusExceptionCode with the value -532459699).

Thanks again,

Andre
Title: Thanks RustInRivers   
Name: C.VENDEESHWARAN
Date: 2011-04-01 6:00:46 AM
Comment:
How to enable th debugging using asp.net
Title: Thanks RustInRivers   
Name: c.vendeeshwaran
Date: 2011-04-01 5:58:40 AM
Comment:
I want to be able to write values to the configuration, can I do this?
Title: Thanks RustInRivers   
Name: MrCricket
Date: 2010-09-28 11:03:25 PM
Comment:
That answer saved my a load of time
Title: Thanks!   
Name: coder
Date: 2010-05-25 3:30:53 PM
Comment:
Ditto that, RustInRivers - I was missing that name of the dll, because my original project was a web.config where it did not seem to have a problem, but creating a unit test app that used an app config required that extra specification, which I had missed.
Thanks!
Title: Excellent   
Name: Michel
Date: 2010-05-14 5:20:18 PM
Comment:
RustInRivers : you saved my day, i had the problem in a test project. I had to supply the name of the DLL (where you type 'MyApplication') where the object was in, in my case Project.Core, so it would be

type="Project.Core.Config.MyCustomConfigurationHandler,
Project.Core"

for me.

Thanks for getting me on track.
Title: hello   
Name: van le
Date: 2009-12-01 5:32:53 AM
Comment:
goog luck!
Title: Saved my day!   
Name: Vijay
Date: 2008-09-10 4:51:25 PM
Comment:
Was wrestling with plethora of related .NET classes on the MSDN site trying to get them to work. You just saved my day! Thanks!
Title: Getting it to work for console applications   
Name: RustInRivers
Date: 2007-08-09 3:56:01 PM
Comment:
Hey renee I ran into the same problem when trying to get it to work in a console application. You have to use the config section in Listing 3 where the assembly is specified.

type="MyApplication.MyCustomConfigurationHandler,
MyApplication"

The last MyApplication would be the name of your console application.
Title: Great walkthrough   
Name: Eran Nachum
Date: 2007-05-30 9:03:41 AM
Comment:
Jason, very good step by step explanations, helped me a lot.
You invited to check my weblog sometime at http://www.eranachum.com
Title: Write to configuration   
Name: Linus Joseph
Date: 2007-01-30 4:52:12 PM
Comment:
Daniel Archer,

Here is how to write to configuration. In fact i have added a tool to manage configuration

http://blogs.covarius.com/PermaLink,guid,4b1fe1b7-883e-444b-92f9-f8c4758d6c79.aspx
Title: Good article, but can you write to the configuration?   
Name: Daniel Archer
Date: 2006-10-19 12:14:37 AM
Comment:
Hi, great example, but I want to be able to write values to the configuration, can I do this?
Title: good   
Name: renee
Date: 2006-10-06 6:32:51 PM
Comment:
worked in web.config but not in windows console app. I get following error-
An error occurred creating the configuration section handler for customSection/settings: Could not load type 'MyCustomConfigurationHandler' from assembly 'System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.
Title: Great Work!   
Name: Mumtaz Ali Sarki
Date: 2006-09-07 7:24:17 AM
Comment:
This really a great example for creating Configuration Sections.
Title: Beautiful Example   
Name: Vikram
Date: 2006-09-05 1:06:31 AM
Comment:
This is beautiful example of how to Create the Configuration Handler
Thanks
Title: Great starting point!   
Name: John Mencias
Date: 2006-08-30 6:40:13 PM
Comment:
Muchas gracias. This provided me with a simple but solid starting point. Maybe you can now do an article about Advanced Configuration Handlers where instead of attributes being mapped to namevalue pairs we have xml nodes being mapped to objects. In other words, properties are returned as objects rather than simple strings or ints. Again, thanks!
Title: Great description   
Name: Mikhail Panshenskov
Date: 2006-08-29 9:58:22 PM
Comment:
Thanx, man!
Title: More information   
Name: Lotfi Zrikem
Date: 2006-08-26 10:46:42 AM
Comment:
Thanks for your example very helpful. I wanna know how can i loop over elements il my section and construct a collection of elements ?
Thanks a lot
Title: Very Gud   
Name: Umesh V
Date: 2006-08-23 1:28:07 AM
Comment:
very useful example. can be used in all the projects where we can stop using everything from AppSettings.
Title: Really Great One   
Name: sanu
Date: 2006-08-21 1:32:31 AM
Comment:
This is the one of the best example to start with Configuration Section Handler. Its really helpfull.
Thank yaar.
Keep it Up!!
Title: @tomgron   
Name: sudhan
Date: 2006-08-17 10:21:28 AM
Comment:
It does work on WinForms. I actually used it in a Windoes Console Application using C#, because that what I was required to do. And as the author mentioned, its tough before you figure it out, I couldnt find such nice doc anywhere else.

Really cool
Title: Great!   
Name: peter
Date: 2006-08-11 1:46:06 PM
Comment:
I'm gonna try it and put it in our new project! :)
Title: Excellent   
Name: tomgron
Date: 2006-08-11 10:40:35 AM
Comment:
I think this is excellent example of using different configuration sections in ASP.NET, although I guess this might run on WinForms apps with very little modifications as well. And as this can be used in order to configure and use plugins in applications, the use of this kind of thing is endless. I have previously tried to follow the code in DotNetNuke where this functionality has been implemented, but without luck since it's done originally on top of .NET 1.1 and has rather complex structure as most of functions that are built in in ASP.NET 2.0 were coded into DotNetNuke's framework.

Good job !

Product Spotlight
Product Spotlight 





Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-03-29 10:04:59 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search