Click here to Skip to main content
11,483,586 members (69,653 online)
Click here to Skip to main content

Generic Reading of Configuration Sections

, 5 Mar 2008 CPOL 13K 95 12
Rate this:
Please Sign up or sign in to vote.
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)

Share

About the Author

Guy Baseke
Software Developer (Senior)
Canada Canada
Software engineer

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150520.1 | Last Updated 5 Mar 2008
Article Copyright 2008 by Guy Baseke
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid