Jul 22 2007

Endless appSettings vs. Custom Configuration Sections

Category: Tips and TricksJoeGeeky @ 20:57

At some point in your career you will come across an application config file or Web.Config with some ridiculous number of appSetting items. While easy to use, they have a number of specific shortfalls. Namely, appSettings are not hierarchal and as such, establishing relationships is left to naming conventions which will likely become unwieldy. appSetting also lack the ability to support any form of arrays unless you count comma delimited lists. Not to worry though... these limitations and others can easily be overcome using custom configuration sections. Here is a quick How to...

  • The first thing you need to do is create a class using standard properties to define your configuration structure.
  • Modify the class to inherit from System.Configuration.ConfigurationSection
  • Modify the class by decorating the properties with the ConfigurationProperty attribute
using System.Configuration;
public class MyConfigSection : ConfigurationSection
{
     private bool _enableautologon;
     
     private string _username;
     
     private string _password;
     
     public MyConfigSection() {
          base.Init();
     }
     
     [ConfigurationProperty("enabledAutoLogon")]
     public bool EnableAutoLogon {
          get {
               return this._enableautologon;
          }
          set {
               this._enableautologon = value;
          }
     }
     
     [ConfigurationProperty("username")]
     public string Username {
          get {
               return this._username;
          }
          set {
               this._username = value;
          }
     }
     
     [ConfigurationProperty("password")]
     public string Password {
          get {
               return this._password;
           
          set {
               this._password = value;
          }
     }
 }
  • Save and compile your project
  • In the target applications Configuration File (Ex. App.Config, Web.Config, etc...) add a configuration section to define your new config section
  • Add your config section details
<?xml version="1.0"?>
<configuration>
    <configSections>
        <section name="MyConfigSection" 
       type="MyConfigSection, 
            MyConfigSectionAssembly" />
    </configSections>
    <MyConfigSection 
      enabledAutoLogon="true" 
      username="user"
      password="pass01" />
</configuration>



Thats it! This is relatively easy and there are a lot of additional options available if you check MSDN.  Enjoy...

 

Tags:

Comments

1.
trackback Smelser.NET says:

Wrap config settings for speedier access

Wrap config settings for speedier access

Comments are closed