PM's Blog

Pramod Mohanan's notes about ASP.NET, MVC, C#, SQL, jQuery, Bootstrap

Accessing values from config files

Accessing static values from resource files or other external files such as XML is common in programming. An example is accessing a value such as a ConnectionString or any other statuc value from AppSettings in the config file.

   int Port = Parse.Int(ConfigurationManager.AppSettings["PortNum"]);

However in large applications we will prefer to have this within a static method or as a property in some utility class which we can call from different parts of the application’s code. Here is a performance effective way to code this in a method

public static T GetAppSettingValue<T>(string Key, T defaultValue)
{
   object Val = ConfigurationManager.AppSettings[key];
   if(Val == null)
      return defaultValue;
   return (T) Convert.ChangeType(Val, typeof(T));
}

apart from reusability of this piece of code, an obvious benefit is that we will not have to do any further type casting as we are the method returns the desired data type. Here are some examples of how you can use it

private int PortNumber = 0;
private long AccountNum = 0;
private string Email = "";

private void Page_Load(object sender, EventArgs e)
{
   PortNumber = GetAppSettingValue<int>("PortNumber", 25);
   Email = GetQueryStringValue<string>("EmailAddress", "admin@pramodmohanan.net");
   AccountNum = GetQueryStringValue<long>("AccountNumber", 0);
}

Isn’t that much better? And we can of course apply a similar logic for accessing QueryString Values, Cookies, Session Variables etc.

Leave a Reply

Your email address will not be published. Required fields are marked *

PM's Blog © 2018