Click here to Skip to main content
Click here to Skip to main content
Go to top

Clean Up that Bloated Web.Config! An Application Settings Manager that's Easy to Use

, 3 Dec 2004
Rate this:
Please Sign up or sign in to vote.
An application settings manager that allows you to quickly categorize and manage all those miscellaneous application settings that are clogging up your web.config file. As a bonus, you can let your end users manage their own settings with the supplied editor.

Sample Image - AppSettingsConfigure.jpg

Introduction

Most applications of any size require application settings. While the web.config file provides a handy way to store and retrieve application settings using the ConfigurationSettings.AppSettings["..."] syntax, it can become cumbersome if you have more than a few settings. As well, application settings accessed with ConfigurationSettings.AppSettings are all grouped together. It would be handy to be able to group them into categories. While this can be done with subsections in web.config, it requires some coding. Perhaps most importantly though, it's often a requirement to allow the end user or administrator edit application settings.

This article presents an application settings manager that allows you to quickly and easily manage a large number of application settings. The application settings manager has the following features:

  1. Settings are grouped by category.
  2. Easily manages large numbers of settings.
  3. Settings editor makes it easy for end users to edit the settings.
  4. Editor runs in Configure Settings mode. In this mode, new settings are easily created and grouped under categories.
  5. Settings have descriptions associated with them. The descriptions appear next to the setting at edit time to guide the person editing the setting.
  6. Referring to a setting at runtime follows a similar syntax to referring to an appsetting in web.config.
  7. Helper syntax allows you to refer to an integer or bool setting without having to convert it from a string.

Storing and Retrieving the Settings

The settings are stored in two small SQL tables, Settings and SettingCategories. The Settings table is linear, in that each setting is represented by a record. Settings of all types (string, int, bool) are stored as strings in the Value field in much the same way that settings are all stored as strings in web.config. Storing and retrieval of settings is through a set of simple stored procedures. Scripts for creating the tables and stored procs is included with the source.

Editing the Settings

The settings are edited using a web user control supplied in the source as AppSettings.ascx. The control has two modes, Edit Mode and Configure Mode. You can switch between the modes by clicking a button on the form. In Edit Mode, you can browse through the settings by category and edit the values of the settings. In Configure Mode, you can add, edit and delete categories; and under each category, you can add, edit and delete settings. When you configure a setting, you can specify the setting type, the number of lines the editor should present if the setting is a text type, and optionally a list of choices. At edit time, the description of the setting will appear next to the edit box to help the person editing the value fill it in correctly. The editor takes a different form, depending on the type of the setting. Text settings use a text box. Bool settings use a True/False radio button selector. Integer settings use a small text box. If you specified a list of choices, the editor will use a combo box from which the person editing can select.

The three screen shots below show the editor idle, in Configure Mode, and in Edit Mode:

Application settings

Application Settings

Configure application settings

Configuring Application Settings

Edit application settings

Editing Application Settings

Code for the Editor

The code for the editor is not very interesting. It's just a lot of fiddling with showing and hiding UI elements to try to create a nice user experience. I won't bore you with going into it here.

Notice at the bottom of the editor there's a Load Settings Into Application button. Because the application settings are normally loaded only at application startup, it's necessary to provide this button to re-load them after they've been edited and saved to the database. The next section covers application settings loading in detail.

Loading Application Settings

Loading of the application settings is managed by a class supplied in the code called AppSettings. Here is the listing of the AppSettings code:

 /// <span class="code-SummaryComment"><summary>
</span>
 /// A list of the application settings
 /// <span class="code-SummaryComment"></summary>
</span>
 public class AppSettings : Hashtable
 {
  public AppSettings()
  {
   SqlDataReader dr = ExClassLib.Sql.SPHelper.ExecuteReader( 
      ConfigurationSettings.AppSettings["ConnectionString"], 
      CommandType.StoredProcedure, "Fx_AppSettings_GetAll" );
   while( dr.Read() )
   {
    string key = ( (string)dr["Category"] ).ToUpper() + "." + 
      ( (string)dr["Name"] ).ToUpper();
    string value = (string)dr["Value"];
    Add( key, value );
   }
   dr.Close();
  }

  public string this[string name]
  {
   get
   {
    string key = name.Trim().ToUpper();
    if( base[key] == null )
    {
     HttpContext.Current.Response.Redirect( 
       "~/AppSettings.aspx?BadAppSetting=" + name );
     return null;
    }
    else
     return (string)base[key];
   }
   set
   {
    base[name] = value;
   }
  }
 }

As you can see, the constructor simply gets the list of settings from the table using the stored procedure for that purpose, and stuffs them into a HashTable. The key for the HashTable is the setting category and setting name, separated by a period. We'll use this in a minute when retrieving the app settings.

The other method is the "this" indexed property, which provides us with a nice syntax for referring to the properties. Notice also in the code for this property, there is a check to see if the property exists. If the property doesn't exist, the application is redirected to AppSettings.aspx, and the missing setting is sent in the URL. We'll see in a minute how this helps ensure that all the required settings are available for the application.

Using the Application Settings

To use the application settings, you need to create an instance of AppSettings and store it somewhere where it can be globally referred to. At Exia Corp., we store it in our Framework class. You might put it in Global, or some other global class you have. The AppSettings class only needs to be instantiated once for the application, so make sure you create it in the Application_Start event and not on every request.

Next, you simply refer to application settings using the following syntax:

string xyz = myGlobalClass.AppSettings[ "category.name" ];

Helper methods: You may want to write three helper methods in your global class so that you can refer to application settings without having to do type conversion all the time. Here's the code for the AppSettingBool method that you could put in your global class that contains the AppSettings:

  public static bool AppSettingBool( string name )
  {
   if( AppSettings[name] == null )
    return false;
   else
    return AppSettings[name].ToUpper() == "TRUE";
  }

Now you can write code like this...

bool abc = myGlobalClass.AppSettingBool( "category.name" );

... which is a nice time saver.

Similar methods for AppSetting and AppSettingInt are included in the source.

Handling Missing App Settings

Missing or bad application settings are a problem. What happens when a required application setting is missing and the application won't run? Now you can't run the application, so you can't get into the application editor to fix the setting. Well, you can always open up the tables and manually adjust the settings, but this is cumbersome. What you need is a standalone form that you know you can always open to adjust the application settings. This form is supplied in the source as AppSettings.aspx. The form's purpose is to house the AppSettings.ascx control that edits the settings.

Now, look back at the AppSettings class code listing. Remember, we mentioned that the code for retrieving an app setting checks to see if the setting exists. If the setting doesn't exist, the class is hard-wired to open up this form. This way, if you mess up on a setting, forgot one, or misspelled one, the form will open right away to allow you to adjust the settings.

[Is hard-wiring a middle-tier class to call a form a good idea? Probably not, but in the Exia Framework, we're so confident that the AppSettings form will always be there that we took this as a mulligan. A better method is to rework the AppSettings class to raise an event when it encounters a bad setting, and trap the event in your UI layer.]

If you open the form manually, it will present the editor. However if it's opened by the system, a parameter is passed with the name of the bad setting, and the form presents you with a nice explanatory error message, as shown below:

Sample screenshot

Application Settings Editor in Error Mode

Tweaking You'll Have to Do

In our shop, we use a modified version of the Microsoft Data Access Block to call stored procedures. You'll have to do some minor code tweaks to fit this code to your own method of calling stored procs.

Complete Sample Application

The supplied source code contains everything you need to set up the application settings manager. However, it requires a bit of tweaking. For those who want to use it without tweaking, a complete version is available for free download here where it's embedded in the Exia Web Solution Framework.

Securing Application Settings

The simplest way to secure the settings is don't give your end users access to the editor form, or give only administrators access.

If you need more granular control over security of the settings, for instance, if you want to let some groups manage some settings, while other groups manage others, then you might want to consider a GUID-based security scheme, such as the one in our Exia Fx framework. This type of scheme enables you to secure anything to which a GUID can be attached, so you could secure the settings at either the group level or at the individual setting level.

Conclusion

This article has presented a simple, easy to use application settings manager, and a user interface that allows you or your customers to edit settings easily. As well, the interface makes it easy for you to configure the settings and organize them into groups, and attach descriptions that are useful at edit time. With this system, you can clean up a lot of the junk in your web config file, and have easier control over your application settings at the same time.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

Nigel Shaw
President Exia Corp.
Canada Canada
I grew up in a small town outside Montreal, Canada, where I grew to appreciate the Francophone culture, the hospitality of rural Quebec and the awesome skiing of the Eastern Townships. I studied Computer Science at the University of Waterloo, Classical Guitar at the University of Toronto, Electrical Engineering at the University of Ottawa, and earned an MBA at Queen's University.
 
I'm a partner in Exia Corp, developers of The Exia Process for better software project management.

Comments and Discussions

 
GeneralAnyone has one that works PinmemberMember 391535423-Sep-09 19:29 
QuestionIs this available in VB somewhere? PinmemberMember 12500726-May-09 12:37 
GeneralFramework Pinmemberbidulle29-Jan-08 12:50 
Generalit looks like the company's self-advertising! PinmemberOlegNY14-Oct-07 9:37 
GeneralRe: it looks like the company's self-advertising! PinmemberNigel Shaw14-Oct-07 11:20 
Generalconfig PinmemberVlastaH20-Oct-05 4:03 
GeneralExcellent Utility PinmemberAther Ali Shaikh13-Jul-05 2:41 
GeneralMounting the project PinmemberFausto Luis9-Dec-04 0:55 
GeneralRe: Mounting the project PinmemberNigel Shaw9-Dec-04 1:39 
GeneralRe: Mounting the project PinmemberNigel Shaw9-Dec-04 1:44 
GeneralRe: Mounting the project PinmemberJC@Rio5-Sep-06 4:22 
GeneralVery useful application PinmemberJackTheGambler8-Dec-04 19:59 
GeneralRe: Very useful application PinmemberNigel Shaw9-Dec-04 0:40 
Generalnice app PinmemberAshley van Gerven3-Dec-04 13:52 
GeneralRe: nice app PinmemberNigel Shaw3-Dec-04 15:15 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140916.1 | Last Updated 3 Dec 2004
Article Copyright 2004 by Nigel Shaw
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid