Home > Programming > Cleaner Configuration Code for .Net

Cleaner Configuration Code for .Net

January 6th, 2009

Microsoft’s configuration system is very handy, but often configuration access code can get pretty nasty and result in a lot of duplication. In preparation for another article I am creating for the site, I decided to share a simple technique I use for managing my config code.

The Normal Way

Suppose that you have a few config settings in the config file. Our example has three settings. Two of the settings are strings and the last one should be cast to a long. Let us also suppose that we want to throw an exception reminding the developer that the application is not configured correctly if either of the string settings are missing. For the long setting, we do not wish to throw an error if the setting is missing. We would prefer to assume a default value unless the config file says otherwise. If we don’t have a class in which to house these policies, the code gets pretty messy. Below is and example of a few simple calls with no wrapper.

public void Before()
{
    // get the connection string for the database
 
    if (ConfigurationManager.ConnectionStrings["CacheDBConnection"] == null)
        throw new Exception("Config setting 'CacheDBConnection' does not exist in the config file.");
 
    // if the exception doesn’t throw, we can keep going
    string _ConnectionString = ConfigurationManager.ConnectionStrings["CacheDBConnection"].ConnectionString;
 
    // get the default size for the cache from the config file
 
    long _CacheSize = 0;
 
    if (ConfigurationManager.ConnectionStrings["CacheSizeLimit"] != null)
        _CacheSize = long.Parse(ConfigurationManager.AppSettings["CacheSizeLimit"]);
}

The above approach has many disadvantages including the following items.

  • It is verbose
  • Making several calls like this would generate a lot of duplicate code. This is a real problem for maintenance.
  • It is likely that many people would not put in repetitious checks for a valid configuration out of sheer laziness.
  • You have to remember the name of the config settings without any help from intellisense while you’re in the heat of coding.

A Solution to Messy Config Code

The manager class I created here was built for a caching manager, so it is called ObjectCacheConfig. You can build your config class to your own specifications taking some inspiration from the class presented. The class file may be downloaded by clicking here.

I built this class as a static class to avoid the need for an instance. This is a fairly common pattern in .Net and I use it frequently for utility classes which need no state. The public static properties access the appropriate config file settings and perform any validity checks and casting required. The VerifyAppSetting() helper method allows some flexibility in your policy regarding missing config settings. VerifyConnectionString() will throw an error if the connection string does not exist.

Note: In the code example below, I was unable to include my usual XML documentation comments due to formatting problems with my source code display plugin. The XML comments are included with the actual source file.

using System;
using System.Text;
using System.Configuration;
 
namespace ObjectCacheCore
{
 
    public class ObjectCacheConfig
    {
 
        #region Static Properties
 
        public static string CacheDBConnection
        {
            get
            {
                VerifyConnectionString("CacheDBConnection");
 
                return ConfigurationManager.ConnectionStrings["CacheDBConnection"].ConnectionString;
            }
        }
 
        public static string CacheDBTable
        {
            get
            {
                VerifyAppSetting("CacheDBTable", true);
 
 
                return ConfigurationManager.ConnectionStrings["CacheDBTable"].ConnectionString;
            }
 
        }
 
        public static long CacheSizeLimit
        {
            get
            {
                long _SizeLimit = 0;
                if (VerifyAppSetting("CacheSizeLimit", false))
                {
                    _SizeLimit = long.Parse(ConfigurationManager.AppSettings["CacheSizeLimit"]);
                }
 
                return _SizeLimit;
            }
 
        }
 
        #endregion
 
        #region Helper Methods
 
        private static bool VerifyAppSetting(string settingName, bool throwIfNull)
        {
            bool _Exists = ConfigurationManager.AppSettings[settingName] != null;
 
            if (!_Exists && throwIfNull)
            {
                string _Message = "Application setting '" + settingName + "' does not exist in the config file.";
                throw new ConfigurationErrorsException(_Message);
            }
 
            return _Exists;
        }
 
        private static void VerifyConnectionString(string connectionName)
        {
            bool _Exists = ConfigurationManager.ConnectionStrings[connectionName] != null;
 
            if (!_Exists)
            {
                string _Message = "Connection string '" + connectionName + "' does not exist in the config file.";
                throw new ConfigurationErrorsException(_Message);
            }
 
        }
 
        #endregion
    }
 
}

Life After the Config Class

Let’s see what our access code would look like now that the config manager class has been written. The code below accomplishes the same result as our first code sample in the article.

public void After()
{
    // get the connection string
    string _ConnectionString = ObjectCacheConfig.CacheDBConnection;
 
    // get the configured cache size limit
    long _CacheSize = ObjectCacheConfig.CacheSizeLimit;
 
}

In Conclusion

Using a pattern similar to the above class can really clean up your application code with regard to config access. We reduced the code size and eliminated duplicate code. Now, while coding, Visual Studio will give you a drop down menu of your config settings with full documentation for the setting if you have your xml comments in place. It is a simple pattern, yet it could change your code dramatically if you use a lot of config settings.

Happy coding!

Did you like this? If so, please bookmark it,
tell a friend
about it, and subscribe to the blog RSS feed.

Programming ,

  1. Nate Matzer
    January 13th, 2009 at 11:22 | #1

    Excellent pattern; greatly increases readability and decreases footprint (maintenance) of configuration code! I can’t see myself ever going back to using it in-line.

    Also useful as a quick ConfigurationManager reference for those that aren’t used to using it.

    I know it’s out of scope for this article but perhaps you can make a reference to more detailed info for newbies (or people who forget like me) on how to implement the configuration file side of it.
    Here’s a simple example of the config XML:

    -Nate

  2. Nate Matzer
    January 13th, 2009 at 11:24 | #2

    The URL I added to my comment didn’t take.
    URL to simple config XML example: http://www.csharpfriends.com/Articles/getArticle.aspx?articleID=45

  1. No trackbacks yet.