65.9K
CodeProject is changing. Read more.
Home

Config Helper

starIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIconemptyStarIcon

1.72/5 (8 votes)

Jun 29, 2004

viewsIcon

34049

downloadIcon

376

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.