AspAlliance.com LogoASPAlliance: Articles, reviews, and samples for .NET Developers
URL:
http://aspalliance.com/articleViewer.aspx?aId=924&pId=-1
Creating a Simple Configuration Section Handler Using ASP.NET 2.0
page
by Jason N. Gaylord
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 41686/ 35

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.


Product Spotlight
Product Spotlight 

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