Click here to Skip to main content
Licence CPOL
First Posted 5 Mar 2008
Views 10,256
Downloads 53
Bookmarked 12 times

Generic Reading of Configuration Sections

By | 5 Mar 2008 | Article
Generic reading of configuration sections.

Contents

Introduction

Getting and storing settings is a needed skill in programming. If you need to store and retrieve configuration sections in a generic and type safe way, then this article will be of help.

The demo application is a Windows socket client that I use for testing the socket protocol.

Common Settings

The common way for storing and retrieving settings is by using AppSettings or ConnectionString, and these are used for simple configurations.

When you need to create objects from a configuration file, then creating sections is the way to go. The class that will consume the configuration section will be derived from the ConfigurationSection class.

ConfigurationSection

Deriving from ConfigurationSection is a simple and powerful way to use configuration sections in an object oriented way.

The application configuration will store the data and link them to their type.

class OptionsConfigHandler : ConfigurationSection
{
    [ConfigurationProperty("HostName", IsRequired = true, 
      IsKey = false, DefaultValue = "127.0.0.1")]
    public string HostName
    {
        get { return (string)base["HostName"]; }
        set { base["HostName"] = value; }
    }

    [ConfigurationProperty("Port", IsRequired = true, 
      IsKey = false, DefaultValue = "4433")]
    public string Port
    {
        get { return (string)base["Port"]; }
        set { base["Port"] = value; }
    }
}

The OptionsConfigHandler class can be used to retrieve data from a section in the application configuration file. When this class is used to store data to the application setting, the setting will look like:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <section name="OptionSection" 
          type="SocketTest.OptionsConfigHandler, SocketTest, Version=1.0.0.0,
Culture=neutral, PublicKeyToken=null" allowLocation="true"
allowDefinition="Everywhere"
allowExeDefinition="MachineToApplication"
overrideModeDefault="Allow"
restartOnExternalChanges="true" requirePermission="true" />
    </configSections>
    <OptionSection HostName="127.0.0.1" Port="4433" />
</configuration>

The Class

public class ExeConfig
{
    private static Configuration config;
    public static Configuration Config
    {
        get
        {
            if (config == null)
                config = ConfigurationManager.OpenExeConfiguration(
                                      ConfigurationUserLevel.None);
            return config;
        }
    }

    public static T GetSection<T>(string sectionName) where T : 
                                                  ConfigurationSection
    {
        T options = null;
        try
        {
            options = Config.GetSection(sectionName) as T;
        }
        catch
        {
            // Ignore, it is up to the user to check for null values
        }

        return options;
    }

    public static void AddSection(string name, ConfigurationSection section)
    {
        config.Sections.Add(name, section);
        Config.Save(ConfigurationSaveMode.Full);
    }

    public static void Save()
    {
        Config.Save(ConfigurationSaveMode.Modified);
    }
}

This class reads and writes sections to the configuration file, and it is all you need to get started.

Reading a Section

To read the OptionsConfigHandler section from the configuration file, here is the code:

OptionsConfigHandler options = ExeConfig.GetSection<OptionsConfigHandler>(sectionName);

Writing a Section

To write the OptionsConfigHandler section to the configuration file, here is the code:

OptionsConfigHandler options = 
     ExeConfig.GetSection<OptionsConfigHandler>(sectionName);
if (options == null)
{
    options = new OptionsConfigHandler();
    ExeConfig.AddSection(sectionName, options);
}
ExeConfig.Save();

Voila!

Revision History

License

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

About the Author

Guy Baseke

Software Developer (Senior)

Canada Canada

Member

Software engineer

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
-- There are no messages in this forum --
Permalink | Advertise | Privacy | Mobile
Web03 | 2.5.120517.1 | Last Updated 5 Mar 2008
Article Copyright 2008 by Guy Baseke
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid