Brothers In Code

...a serious misallocation of .net resources

Simple Custom Configuration

A lot of these posts are merely for my own quick reference.  The upside of that is that you'll get a taste for the way I actually do something rather than just a rehash of a reference page.

For simpler projects I just create a class with some static properties that just pull from AppConfig variables.  At least from there I have intellisense to help me remember all of my configuration variables.  But the appSettings section app.config or web.config can get messy pretty fast so creating a custom section isn't that much work to clean it up.

First I'll create a ConfigurationSections folder (which creates an automatic namespace) and an AppConfig class:


The GeneralConfigurationSectionClass looks like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;

namespace MyCust.MyProj.ConfigurationSections
  public class GeneralConfigurationSection : ConfigurationSection
    public String TestKey
      get { return (String)this["TestKey"]; }
      set { this["TestKey"] = value; }

    public String ConnectionString
      get { return (String)this["ConnectionString"]; }
      set { this["ConnectionString"] = value; }


Then I'll create a property that pulls the config data and returns this class in the AppConfig.cs

  public class AppConfig
    public static GeneralConfigurationSection General
        return (GeneralConfigurationSection)ConfigurationManager.GetSection("MyCust.MyProj/General");


And last add the new section to the app/web.config.  First add the section group:

  <sectionGroup name="MyCust.MyProj.WebServices">
    <section name="General" type="MyCust.MyProj.WebServices.ConfigurationSections.GeneralConfigurationSection, MyCust.MyProj.WebServices" allowLocation="true" allowDefinition="Everywhere"/>

And then add the section itself into the configuration element:

    ConnectionString="Data Source=SqlServer;User Id=sa_app;Password=pwd;"

Usage is then a nice and clean line: