Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Config Helper

0.00/5 (No votes)
28 Jun 2004 2  
Eases the use of keys defined under appSettings.

Introduction

Helps using the key values located under <appSettings>, either its in web.config or in YourApp.exe.config.

Background

To access application settings, we all must have used the web.config before. I try to keep most of the variables (which I think would require changes overtime) in the web.config file when I'm developing a web project. That way, future changes doesn't require recompiling the code. For e.g., if you have cookie time out or if you are using a webservice, you might write the code as follows to access the keys from web.config:

// accessing cookie time out

int cookieTimeOut =  40  ; // 40 mintues, default value

// to avoid exception if key not defined

if( System.Configuration.ConfigurationSettings.AppSettings["CookieTimeOut"] != 
                                               null )
{
    cookieTimout = Int32.Parse( 
      System.Configuration.ConfigurationSettings.AppSettings["CookieTimeOut"] ) ;
}

So, as you can see above, you'll have to write an if statement and use the Int32 to parse the integer. This code will require changes if you have to get a double, string or bool from <appSettings>. Let's use this class to see how it'll get the value.

Using the code

using vs.helpers // namespace for ConfigHelper class


int cookieTimeOut = ConfigHelper.GetInt32("CookieTimeOut", 40); // for integer


// for other types of values you can use one of the following also

string connString = ConfigHelper.GetString("ConnString", 
   "your default connection string"); 
double currencyUnit = ConfigHelper.GetDouble("CurrencyUnit", 1.5);
bool persistantCookie = ConfigHelper.GetBoolean("PersistantCookie", false);

It does reduce some if statements in your code and makes it more readable. You don't have to use the long statement ( System.Configuration.ConfigurationSettings.AppSettings["key"] ) and no value parsing.

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