Configuration Setting Management: The Personality of Your Applications
page 1 of 1
Published: 27 Apr 2004
Unedited - Community Contributed
Abstract
This article deals with a method of designing your classes to efectively manage your configuration settings from multiple sources, and works especially well within a team of application developers. Abstracting the actual source of the configuration data, as well as providing strongly-typed, Intellisense type help with the configuration classes themselves.
by Paul Glavich
Feedback
Average Rating: 
Views (Total / Last 10 Days): 10096/ 19

Managing Application Configuration Settings
The ability to be able to configure your application for a number of different parameters and scenarios is important to almost every single application, whether it be an ASP.NET application or a WinForms application. The Framework's support for managing this information is good, and in this article I present techniques to develop and manage your applications' configuration and allow an easy way for other developers who might be in your development team to utilize the configuration information within the application.

Assumptions

This article assumes some familiarity with the Framework-supplied method of reading application values from the <appSettings> element within the applications configuration file (via the System.Configuration.ConfigurationSettings.AppSettings object) and assumes the reader has some familiarity with the registry.

The Joy of AppSettings

The System.Configuration.ConfigurationSettings.AppSettings object provides easy access to configuration values stored within an application's configuration file. This is typically the 'web.config' for ASP.NET applications and the "App.Config" (actually "YourApp.EXE.Config") for WinForms or console applications. This inbuilt mechanism provides an easy-to-use method of accessing configuration settings and is a recognition of the fact that all applications will typically need to access some form of configuration data, whether it be simple default values or critical operational parameters.

Optionally, an application can define its own custom configuration section within the configuration file; however, this article will be concentrating on the former method. Defining a custom configuration section involves more work on the part of the developer, and, due to the fact it requires considerable customization, it is not applicable to the technique being described here.

One of the issues experienced by developers when using this method (i.e., accessing data via the <appSettings> element within the application cofnguration file) is the fact that accessing the configuration data is performed in a weakly-typed manner. That is, the data accessed is always retrieved as a string, and explicit knowledge of the configuration key used to access the configuration value is required. The simple example below illustrates this.

C#
using System.Configuration;
string itemValue =
ConfigurationSettings.AppSettings["itemKey"];
VB.NET
Imports System.Configuration
Dim itemValue as String
itemValue =
ConfigurationSettings.AppSettings("itemKey")

In the above example, the "itemValue" variable will contain the configuration value, and the "itemKey" literal string represents the configuration key. If the configuration value actually represents a value other than a string, such as a boolean (true/false) or numeric value, then this must be converted by the calling code each time the configuration value is accessed.

Furthermore, the configuration key must be explicitly known for the call to be successfull. This not only adds extra work on the part of each developer having to access these values, but also introduces potential areas of errors that can be easily introduced into the application.

 

Making Things Easier

What would be nice is a method of accessing configuration values where we don't have to worry about converting it from its string/textual representation within the configuration file into its actual data type and also not having to worry about the literal text configuration key name to access a particular configuration value.

How about a method of exposing configuration values as strongly-typed properties, allowing for multiple configuration sources and comments that provide easy use when using these properties via Intellisense?

Using static properties that only expose the 'accessor' method and contain full XML style comments will provide this for us. Also, the 'accessor' property method can test to see if the value extracted from the configuration file was successful and, if not, attempt to read the configuration value from another source, such as the registry.

Examine the code segment below. Note: All further code examples will be given in C# due to its native support of XML comments and the advantage this allows for the technique being described.

using System.Configuration;

///<SUMMARY> ///My Test configuration class ///</SUMMARY> public class TestConfig { private TestConfig() { } ///<SUMMARY> /// Database connection string ///</SUMMARY> public static string DBConnectionString { get { const string KEYVAL = "DBConnectionString"; const string DEFVAL = ""; string strVal =
ConfigurationSettings.AppSettings[KEYVAL]; if (strVal == null || strVal == String.Empty) strVal = DEFVAL; return strVal; } } ///<SUMMARY> /// Should we enable our fandangled tracing feature ///</SUMMARY> public static bool EnableTracing { get { bool retVal = false; const string KEYVAL = "EnableTracing"; const string DEFVAL = "false"; string strVal =
ConfigurationSettings.AppSettings[KEYVAL]; if (strVal == null || strVal == String.Empty) strVal = DEFVAL; if (strVal.ToUpper() == "TRUE") retVal = true; return retVal; } } }
Using the above class from your application code would look something like this:
SqlConnection myConnection = 
new SqlConnection(TestConfig.DBConnectionString);
if (TestConfig.EnableTracing)
{
   // do some tracing stuff
}
The above code is greatly simplified; no conversion code is in place (to convert from the string Boolean property to the correct boolean data type), and the configuration properties were easily accessible via the Intellisense dropdown list help within the Visual Studio.NET IDE. Developers find this method easy and intuitive to use from within their applications.

The Benefits

So, what are all the benefits of using this approach? Glad you asked....

1. Strongly-typed method of accessing configuration properties.
2. Full Intellisense support within the Visual Studio.NET IDE.
3. No need to rely on the AppSettings class and know AppSettings key values to retrieve configuration settings from the configuration file.
4. Configuration values can be "massaged" or "altered" prior to returning them to the caller. This can be as simple as returning a default value if no configuration entry is present or more complex manipulations.
5. The configuration file need not be the only source of configuraiton data. For example, if a value does not exist in the configuration file, it can be retrieved from the registry or the database automatically (the demo code generator supplied provides support for this). This has the advantage of being able to use a single configuration class, whether it be from a web application (using Web.Config) or within the same app but as a COM+/Enterprise Services component (and perhaps using the registry). It all looks the same to the caller.
6. Consistent configuration data access for all developers within your team with ability to generate documentation (via XML commenting and auto-documentation features) for your configuration settings class.
7. No class instantiation required because of the use of static members.

 

So here is something we have prepared earlier....

Accompanying this article is a windows application that generates a static configuration class for you. Its a simple application that allows you to define namespaces, class names, configuration properties with associated configuration entry keys to access the data as well as comments to describe the class and each configuration entry. C# is the only language supportted; however, full source code is provided, so using an easy abstracted design to add your own support for Visual Basic.NET (or any other language if you desire) should be no problem.

In the case of a missing configuration entry, you can elect to have support for reading from a selected registry key to access the same configuration values, all using the same configuration entry defined in the list.

Conclusion

As an application architect and developer, I find this method of accessing configuration data to be very intuitive, particularly in a team of developers who are very used to object oriented programming. This method also provides a good deal of flexibility and consistency in using your applications configuration parameters.

Download the Demo Code

If you have any questions, please feel free to email me, Paul Glavich


User Comments

Title: configuration setting   
Name: george
Date: 2009-08-11 8:40:19 AM
Comment:
i need a conplite configuration setting code which will enable me to configued my hand sett, please.
thank
you.
Title: ClassFromConfig   
Name: Mikhail Diatcheko
Date: 2007-10-20 4:52:02 AM
Comment:
Here's another code generated for you config files: http://wiki.webgear.co.nz/ClassFromConfig.ashx

It automatically recognizes types and integrates into Visual Studio.
Title: Good One   
Name: Jinesh
Date: 2006-09-21 3:14:00 AM
Comment:
Thanks A Tone Man ....
noce work .... nice article.

Thanks
Title: Re: Good, but how about this, less code   
Name: Paul Glavich
Date: 2004-07-08 6:41:56 AM
Comment:
David,

The web.config is cached so its quite fast. The next step is ofcourse to cache the values within the class itself, and yes, you would typically issue a "FillCache" type command, to pre-fill all your config values into your static variables on initial application loading. The extra lines of code are for flexibility. You can either massage the values once you have reas them from your web.config, or possibly access them from elsewhere, dependent on the value itself. Just returning what is in the web.config verbatim invariably means you have to do some code manipulation within your app to get it in the form you want. This class alleviates that. Also, this class will quite happilly access values from the registry (but potentially any other source without modification, and without you having to do anything else except put your values in the registry (ie. if it does not find it in the web.config. then it looks in the registry). In some environments, this is very handy when you have this class shared between components, some of which are hosted in COM+ for example.
The SyncLock hint you mentioned is not really necessary in a read only scenario. Sure if there is the ability to have multiple users/threads modify the data, then you would need a form of serialisation of access/sunchronisation of access but this in itself limits throuhgput, but that is not what this kind of class is designed for. The article provides mostly the concept, with the ability to easily extend, particularly the caching aspects, to whatever suits your preferences.

You could also abstract away the massaging of data into its various forms and create a much nicer object tree to deal with this, but again, its really beyond the scope and intent of the article.

Thanks for your, and everyone elses comments.
Title: Good, but how about this, less code   
Name: David Storfer
Date: 2004-07-07 10:55:57 AM
Comment:
I've never been able to find out for sure if the appSettings are cached or read from file on each access (which would make the above method terribly inefficient), but in any case, I use the following in my ASP.NET projects:

In the Global.asax I declare Public Shared variables at the module level. These variables are now accessible everywhere in the project as Global.VarName. In the Application_Start routine, I simply load them all from the appSettings, then they are ready to be accessed at any time. That's really only 2 lines of code as compared to the 10+ for each variable above. (You may also want to read the details on SyncLock if you plan on modifying those values anywhere else.)
Title: Another Toll To add to the mix   
Name: nick katsivelos
Date: 2004-07-06 10:44:40 PM
Comment:
Here is the post - for your convenience - please put all comments in the real thread at GotDotNet. I think there are some real synergies here - for something that is really useful - so here goes

I am wondering if you know of a utility/VS.NET plug-in that will accomplish the following

I am in the code editor window, well, writing code when I find that I am hardwiring the value for a property. Let's say it is a database connection string. What I want to be able to do is type in the value that I want as the default, and then I highlight that value, right click and select MoveMe2Config from the context menu. This brings up a pop-up that - upon initialization scans my project for any config files which I might use for this piece of code (it may already be declared somewhere, or be the default as in web.config). If none exists it will offer to create one for you. If one or more do exist, it will let you choose. If your code does not import systems.configuration, it will add that declaration. It will then grab the default value you have typed and put that in a text box and also let you add a neame for the key to that value - checking to make sure it doesn't already exist. It will also have an editable comments field that will be added to the config file.
By default it will add the type information for that property and any discoverable constraints. Hit the OK button and the key/value pair is added to the config file and the appropriate reference to it is placed where you had typed the default value in your code.

The next level of complexity would allow you to right click in the code editor and select GetMeFromConfig which would provide you with a listing of all the key value pairs in the config file - and - if know - their type.

The final level of complexity would be to have this UI actually driving a wrapper class that would provide strongly-typed access to your config file.

Does anyone know of anything like this? Would anyone care to build it - I wou
Title: Big deal   
Name: douche
Date: 2004-07-03 1:42:56 PM
Comment:
If you have not thought about this and you're an asp.net programmer, and you read this article and say oh wow, you need to be more creative rather than being a code monkey. thanks.
Title: Great Artical   
Name: Prakash
Date: 2004-07-01 1:04:24 PM
Comment:
Awesome stuff!!!!

This is really a easy way of handling the config info and this method can be adopted for handling the session variables too.

Thank you once again.
Title: .NET Developer   
Name: Shravan Addaypally
Date: 2004-06-30 10:16:51 AM
Comment:
Good Article. Nice thought about having a class which does this for you instead of having to remember the cumbersome key value pairs from the configuration file.
Title: Nice Article   
Name: Darren Neimke
Date: 2004-06-30 1:00:09 AM
Comment:
Thanks in particular for the free tool :-)






Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-04-19 3:53:12 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search