SingingEels : Development Community & Resource

Login

Articles

  • ADO.NET (2)
  • ASP.NET (35)
  • LINQ (4)
  • Security (2)
  • Silverlight (2)
  • SQL (7)
  • Standards (5)
  • WCF (2)

Syndication

  • Articles RSS
  • Blogs RSS

Contribute

  • Our Authors List
  • Member Sign-Up
  • Suggestions Box
ASP.NET Hosting with MS SQL 2008 – Click Here!

Creating Custom Configuration Sections In ASP.NET

(Oct 16 2007 - 08:13:53 PM by Timothy Khouri) - [print article]

As you advance in your usage of ASP.NET, you will likely get into building your own control libraries, helper classes or any other bit of "common" functionality that you have needed on multiple projects. A powerful feature of ASP.NET is the concept of a configuration file (the web.config) that lets you tailor custom classes for each project without changing any code. This article will show how to build your own custom class and custom configuration section in ASP.NET.

First off, it's good to know a little background of configuration sections and the web.config file (or app.config file if you are building a non-web application). If you've been using ASP.NET for a while now (and particularly ASP.NET 2.0 or above), you've probably already messed with the web.config file a good deal. From the simple: adding app settings and connection strings; to the more in depth: configuring membership, profiles, roles etc.

Examples in ASP.NET

It's important for you to know that these configuration sections that you are altering are nothing more than a class somewhere in the .NET framework that you are setting properties on during the site's initial in-memory compilation. For instance, if you've ever set the properties in your web.config to setup the "profiles" API, you may have added something like this in your web.config file:

<profile defaultProvider="eelsProfileProvider">
   <properties>
       <add name="FirstName" type="System.String" />
       <add name="LastName" type="System.String" />
       <add name="EmailAddress" type="System.String" />
   </properties>
   <providers>
       <add name="eelsProfileProvider"
           applicationName="SingingEels"
           connectionStringName="SingingEelsConnection"
           type="System.Web.Profile.SqlProfileProvider" />
   </providers>
</profile>

You may think (as I did before I learned about configuration sections) that ASP.NET 'knows' the "<profile>" tag, and does all the special mapping that it needs to for that section. But thinking about it, that would be ignorant for the ASP.NET runtime to just have a hard coded list of hundreds of configuration section tags and all the properties there in.

Instead, the profile configuration does things just like any other .NET configuration section... There is a class that inherits from "System.Configuration.ConfigurationSection", and it specifies (by using attributes) what properties to assign the values to based on the web.config (or app.config if you're doing non-web development).

Here is what the ProfileSection class looks like:

public class ProfileSection : ConfigurationSection
{
   [ConfigurationProperty("defaultProvider")]
   public string DefaultProvider
   get
   {
       return (string) base[_propDefaultProvider];
   }

   set
   {
       base[_propDefaultProvider] = value;
   }

   // ... and a whole lot more that I'll leave out :)

}

I've left a lot out simply because this is enough to show you how this all works. Notice that the class inherits from ConfigurationSection, and notice the property up there called "DefaultProfider" which has a "ConfigurationProperty" attribute. This attribute states that there should be an attribute on the section called "defaultProvider" (which is case sensitive by the way) in the web.config file. This is how the .NET framework knows what values in the web.config file apply to what values in the class.

Making Your Own Configuration Section

Making a configuration section is actually pretty easy to do, and it can be fun as you realize that you can build your classes more generically and configure its behavior in a config section. This might seem a bit overkill at first when you could just hard code things, but once you begin to reuse your code you'll quickly realize that all those hard coded values would have been much better placed in a config file.

Let's look at the few steps it takes to make our own configurable class in ASP.NET. The class we are going to build is an "error logger" class that will write exceptions to a log file. The part that we want to be configurable is the path to the log file (just to keep it simple).

First, let's build our class in C#:

// Inherit from "ConfigurationSection"... simple enough!
public class ErrorLoggerSection : ConfigurationSection
{
   // I only want one property... LogFilePath, and I'm

   // here telling .NET to look for an attribute in the

   // config file called 'logFilePath' to get the value from.

   [ConfigurationProperty("logFilePath", IsRequired = true)]
   public string LogFilePath
   {
       get
       {
           return (string)base["logFilePath"];
       }

       set
       {
           base["logFilePath"] = value;
       }
   }
}

The above doesn't take much explaining, so now we can take a look at what we need to add to our web.config file:

<configuration>
   <configSections>
       <section name="eelsErrorLogger" type="SingingEels.ErrorLoggerSection"/>
   </configSections>
   <eelsErrorLogger logFilePath="~/loggyFiley.txt"/>
</configuration>

That's actually my entire web.config file for this project. Notice that all I have to do is define the custom section and give it a name (to which I chose 'eelsErrorLogger'). Then, you have to specify the 'type' (meaning what class in your DLL or project will map to the configuration section). It's good to note that what you name the section here is important if you are planning on getting the section info by name like I did:

ErrorLoggerSection configInstance = ConfigurationManager.GetSection("eelsErrorLogger") as ErrorLoggerSection;

That's really all there is to making your own configuration section in .NET (whether ASP.NET or non-web applications). You can download a sample website that has the above code in working in action. Here's the demo web site: SingingEels_CustomConfigurationSection.zip. I plan on showing a real world example that I needed to use my own configuration section for in my next article (about a custom RoleProvider instance based off of Active Directory groups).

  • Jul 24 2008 - 11:16:29 PM nandita

    Hi,

    Could you please explain how one can have long type information in section tag as shown below. Is it required version, culture an publickey info in type value? if yes, what is the importance of it?

    is it required to type all these info manually or it gets added somehow automatically? Please reply me on nanditar@datacom.co.nz

    type="TestHost.GroupedConnectionStrings, TestHost, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"

You must be logged in to add comments. If you have not already done so, you can create an account here. If you already are a member, you first need to login before you can comment.

Developer / Architect / Author

People to Follow

Experts in the categories related to this article.

  • Jonathan Carter

Related Blogs

These are the most recent blog posts related to this article.

  • A Change to the MVC "ActionSelectionAttribute"?
  • How to Handle "Side Content" in ASP.NET MVC
  • LINQ to SQL - Am I Hitting The Database?
  • ASP.NET MVC - Issue with CSS Class Name on ActionLinks
  • Site Updates, Bug Fixes and Syndication in .NET 3.5

Related Ads

SingingEels.com as of Nov 21 2008 - 07:59:39 PM - (0.0937476)