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:
int cookieTimeOut = 40 ;
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
int cookieTimeOut = ConfigHelper.GetInt32("CookieTimeOut", 40);
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.