Click here to Skip to main content
15,881,882 members
Articles / Web Development / ASP.NET
Article

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

Rate me:
Please Sign up or sign in to vote.
4.36/5 (23 votes)
3 Dec 20048 min read 83.8K   755   91   15
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:

C#
/// <summary>
/// A list of the application settings
/// </summary>
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:

C#
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:

C#
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...

C#
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


Written By
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 Pin
gideonseroney@yahoo.com23-Sep-09 19:29
gideonseroney@yahoo.com23-Sep-09 19:29 
QuestionIs this available in VB somewhere? Pin
Member 12500726-May-09 12:37
Member 12500726-May-09 12:37 
GeneralFramework Pin
bidulle29-Jan-08 12:50
bidulle29-Jan-08 12:50 
Generalit looks like the company's self-advertising! Pin
OlegNY14-Oct-07 9:37
OlegNY14-Oct-07 9:37 
GeneralRe: it looks like the company's self-advertising! Pin
Nigel Shaw14-Oct-07 11:20
Nigel Shaw14-Oct-07 11:20 
Generalconfig Pin
VlastaH20-Oct-05 4:03
VlastaH20-Oct-05 4:03 
GeneralExcellent Utility Pin
Ather Ali Shaikh13-Jul-05 2:41
professionalAther Ali Shaikh13-Jul-05 2:41 
GeneralMounting the project Pin
Fausto Jesus Luis9-Dec-04 0:55
professionalFausto Jesus Luis9-Dec-04 0:55 
GeneralRe: Mounting the project Pin
Nigel Shaw9-Dec-04 1:39
Nigel Shaw9-Dec-04 1:39 
GeneralRe: Mounting the project Pin
Nigel Shaw9-Dec-04 1:44
Nigel Shaw9-Dec-04 1:44 
GeneralRe: Mounting the project Pin
JC@Rio5-Sep-06 4:22
JC@Rio5-Sep-06 4:22 
GeneralVery useful application Pin
JackTheGambler8-Dec-04 19:59
JackTheGambler8-Dec-04 19:59 
GeneralRe: Very useful application Pin
Nigel Shaw9-Dec-04 0:40
Nigel Shaw9-Dec-04 0:40 
Generalnice app Pin
Ashley van Gerven3-Dec-04 13:52
Ashley van Gerven3-Dec-04 13:52 
GeneralRe: nice app Pin
Nigel Shaw3-Dec-04 15:15
Nigel Shaw3-Dec-04 15:15 

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

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