Wednesday, March 18, 2009

ConfigurationSection that reports missing sections in config

It has long annoyed me taken other frameworks that need config sections defined and spending the time copying the sections over, it would be so much easier if the Framework told you what bit of configuration it was trying to load. So I always use this abstract class for all of my config sections.

public abstract class SimianConfigurationSection : ConfigurationSection
/// <summary>
Gets the section.
/// </summary>
/// <param name="definedName">
Name of the defined.</param>
/// <returns></returns>
public static ConfigurationSection GetSection(string definedName)
ConfigurationSection section = ConfigurationManager.GetSection(definedName) as ConfigurationSection;

if (section == null)
throw new ConfigurationErrorsException("The <" + definedName +
"> section is not defined in your .config file!");

return section;

Next derive from this class rather than the .Net Framework class. e.g.

public class EmailTemplatesSection : SimianConfigurationSection

Once this has been completed your application will report a simple configuration exception if it cannot find your section in the config file. This takes 5 minutes to implement, but helps so much when you are configuring frameworks.

This then allows a really simple pattern when you want your configuration section.

return DBCategoryProviderSection.GetSection("nopDataProviders/CategoryProvider") as DBCategoryProviderSection;

You will no longer get an “Object is not a reference . . . “ exception.

No comments: