Click here to Skip to main content
13,406,629 members (39,658 online)
Click here to Skip to main content
Add your own
alternative version


27 bookmarked
Posted 29 Dec 2007

Strongly Typed Custom Configuration Sections using XML Serialization

, 7 Jan 2008
Rate this:
Please Sign up or sign in to vote.
This article demonstrates a simple approach to get strongly typed configuration objects to use in your code using XML serialization


This article describes a simple mechanism to use XML serialization within configuration files to support strongly typed configuration items in your projects.


This article uses the following concepts (and readers are expected to have a basic understanding of the same):

  1. Generic classes
  2. XML serialization
  3. Handling configuration files

Using the Code

Note: The code is provided as two separate solution file downloads, one uses the IConfigurationSectionHandler interface (which is deprecated in .NET v2.0 and above), the other uses the ConfigurationSection class to implement the same. Both projects are made up of two class libraries:

  1. Citrus.Configuration - Class library
  2. Citrus.Configuration.Demo - Demo application

Strongly typed configuration entities are very much advantageous in terms of code clarity and readability, ease of programming, etc. Consider a hypothetical situation where we need to save the name and IP of an email server within our configuration file. We need to be able to retrieve these details from the configuration file as strongly typed entities. Meaning, we could do with a EmailServerSettings object that has two properties Name and IP that can be accessed off of it.

Of course this is just an example, and the approach can be easily reused and extended for configurable entities of your choice.

The first thing is to define the EmailServerSettings class that represents our strongly typed entity:

/// <span class="code-SummaryComment"><summary></span>
/// This is a sample class that is used
/// to describe XML serialization based configuration
/// section usage
/// <span class="code-SummaryComment"></summary></span>
public class EmailServerSettings
    // note the use of implicit property accessors in C# 3.0
    public string IP { get; set; }

    public string Name { get; set; }

    #region Overrides
    public override string ToString()
        return String.Format("{0} email server ({1})", Name, IP);

This is really straightforward. To allow for XML serialization, we mark up the properties and class with the necessary XML attributes.

.NET 1.1 Approach

Next, we define a generic XML serialization based configuration section handler. What this class does is it implements the IConfigurationSectionHandler interface. This interface is deprecated in .NET version 2.0 and above. For implementing the same in .NET 2.0, refer to the section .NET 2.0 Approach.

/// <span class="code-SummaryComment"><summary></span>
/// Handles the access to a generic configuration section using
/// XML serialization
/// <span class="code-SummaryComment"></summary></span>
/// <span class="code-SummaryComment"><typeparam name="T">The type of the configuration section</typeparam></span>
public class XmlSectionHandler<T> : IConfigurationSectionHandler
    #region Properties and fields

    private XmlSerializer serializer = new XmlSerializer(typeof(T));
    public XmlSerializer Serializer { get; set; }


    #region IConfigurationSectionHandler Members

    public virtual object Create(object parent, object configContext, XmlNode section)
        return serializer.Deserialize(new StringReader(section.OuterXml));


XmlSectionHandler is a generic class; it uses the type associated with it to create a serializer that does the core XML deserialization.

At this stage, we have the fundamental blocks required; a simple helper class that gives us the strongly typed configuration entities is also written.

/// <span class="code-SummaryComment"><summary></span>
/// Configuration helper class that exposes generic
/// section retrieval functionality
/// <span class="code-SummaryComment"></summary></span>
public static class ConfigurationHelper
    /// <span class="code-SummaryComment"><summary></span>
    /// Retrieves a typed configuration section for
    /// the current application's default configuration
    /// <span class="code-SummaryComment"></summary></span>
    /// <span class="code-SummaryComment"><typeparam name="T"></span>
    /// The type to bind to the configuration section<span class="code-SummaryComment"></typeparam></span>
    /// <span class="code-SummaryComment"><param name="sectionName"></span>
    /// The name of the configuration section<span class="code-SummaryComment"></param></span>
    /// <span class="code-SummaryComment"><returns></returns></span>
    public static T GetSection<T>(string sectionName)
        return (T)ConfigurationManager.GetSection(sectionName);

    /// <span class="code-SummaryComment"><summary></span>
    /// Retrieves a typed configuration section for
    /// the current application's default configuration
    /// <span class="code-SummaryComment"></summary></span>
    /// <span class="code-SummaryComment"><typeparam name="T"></span>
    /// The type to bind to the configuration section<span class="code-SummaryComment"></typeparam></span>
    /// <span class="code-SummaryComment"><returns></returns></span>
    public static T GetSection<T>()
        return (T)ConfigurationManager.GetSection(typeof(T).Name);

All the helper class does is provide some useful routines that cast the configuration objects to the specified type. That's it. These three classes form the core classes in the Citrus.Configuration class library.

To use them, first we need to update our configuration file. The following is a simple configuration file that uses EmailServerSettings and XmlSectionHandler in a custom config section:

<?xml version="1.0" encoding="utf-8" ?>
    <!--<span class="code-comment"> The following is used to describe our custom section --></span>
    <section name="EmailServerSettings"

      Version=, Culture=neutral,
      PublicKeyToken=null" />
  <!--<span class="code-comment"> Now that our section has been declared, use it --></span>
  <EmailServerSettings configSource="EmailServerSettings.config" />

The external EmailServerSettings.config file is essentially the XML serialized version of the class.

<!--<span class="code-comment"> A simple XML file containing settings for a email server --></span>

Now we are ready to actually use all this in code:

// The following will give us the email server settings
EmailServerSettings emailServerSettings1 =
EmailServerSettings emailServerSettings2 = 

// Print the information out

In fact you can easily use emailServerSettings1.Name and emailServerSettings1.IP, giving us strongly typed configuration entities.

To extend this for your requirements, you would need to define your own configuration specific classes (like the EmailServerSettings class) and add an appropriate configuration section in your config file.

.NET 2.0 Approach

Since the IConfigurationSectionHandler is deprecated in this version, we have to redefine the XmlSectionHandler class as one that derives from ConfigurationSection instead:

public class XmlSection<T> : ConfigurationSection where T: class

(Note the class name has changed in the .NET 2.0 version). Subtle modifications have to be made to allow the class to handle XML serialization in this case. These changes include overriding the Init() and DeserializeSection() methods of ConfigurationSection. Also, XmlSection implements a basic support to save modified configuration details back to the configuration file. To use the XmlSection class, refer to the code snippet below:

// The object that represents our email server's settings
EmailServerSettings anEmailServer;
// Get the section that is specified an external configuration file
anEmailServer = XmlSection<EmailServerSettings>.GetSection("EmailSettings");

// Update the section, refresh and load it again
Config.Configuration c = Config.ConfigurationManager.OpenExeConfiguration
XmlSection<EmailServerSettings>.GetSection("EmailSettings", c).Name = "Hello";
anEmailServer = XmlSection<EmailServerSettings>.GetSection("EmailSettings");

// Get settings that are specified inline
anEmailServer = XmlSection<EmailServerSettings>.GetSection("ProxyEmailServer");

The corresponding config file is as follows:

        <section name="EmailSettings"

[[Citrus.Configuration.EmailServerSettings, Citrus.Configuration]],
        <section name="ProxyEmailServer"

[[Citrus.Configuration.EmailServerSettings, Citrus.Configuration]],
    <EmailSettings configSource="EmailSettings.config" />

Let me know if all this is helpful in some way to you. Enjoy.


[ .] Initial version
[+] New release. .NET 2.0 specific implementation using the ConfigurationSection class
[+] 7-Jan-2008. (v1.1)  
In the previous version, XmlSerializers were created on the fly using the XmlSerializer(Type, XmlRootAttribute) constructor. By nature of design, using this constructor is not very efficient. Therefore, a simple SerializerCache is implemented that caches XmlSerializer objects so that they can be reused, making usage faster and efficient. Another minor change made was to move the EmailServerSettings class outside of the Citrus.Configuration library.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Benzi K. Ahamed
Web Developer
United Kingdom United Kingdom
I work as a Technology Lead for an IT services company based in India.

Passions include programming methodologies, compiler theory, cartooning and calligraphy.

You may also be interested in...

Comments and Discussions

NewsDesign-time tool now available to do similar thing Pin
rohancragg29-Oct-09 7:49
memberrohancragg29-Oct-09 7:49 
GeneralconfigSource = unc share Pin
Ashish Mundra21-Sep-09 14:00
memberAshish Mundra21-Sep-09 14:00 
GeneralAttributes instead of elements Pin
ckarky10-Oct-08 14:35
memberckarky10-Oct-08 14:35 
GeneralRe: Attributes instead of elements Pin
Benzi K. Ahamed11-Nov-08 6:51
memberBenzi K. Ahamed11-Nov-08 6:51 
GeneralI'm Disappointed... Pin
Drew Loika29-Jul-08 17:06
memberDrew Loika29-Jul-08 17:06 
Questionxml attribute mystery [modified] Pin
mlhmlh13-Jun-08 6:35
membermlhmlh13-Jun-08 6:35 
AnswerRe: xml attribute mystery Pin
Benzi K. Ahamed13-Jun-08 11:18
memberBenzi K. Ahamed13-Jun-08 11:18 
AnswerRe: xml attribute mystery Pin
mlhmlh15-Jun-08 23:06
membermlhmlh15-Jun-08 23:06 
GeneralInteresting and a few questions Pin
BillWoodruff20-Jan-08 23:10
memberBillWoodruff20-Jan-08 23:10 
GeneralNot needed any more in .NET 2.0 Pin
Rama Krishna Vavilala29-Dec-07 11:41
mvpRama Krishna Vavilala29-Dec-07 11:41 
GeneralRe: Not needed any more in .NET 2.0 Pin
Benzi K. Ahamed4-Jan-08 5:21
memberBenzi K. Ahamed4-Jan-08 5:21 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02-2016 | 2.8.180212.1 | Last Updated 7 Jan 2008
Article Copyright 2007 by Benzi K. Ahamed
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid