Monday, June 2, 2008

Perfect ASP.NET application, Part 1

Database connection string and other application settings...

I hope that everybody knows that it's a bad practice to hardcode everything. We as a programmers must (at least try to) write a maintenance free application. Once we gave our application to the client it must live without our everyday supervision. Let's take a database connection string for example. You do not want to have to recompile your application every time SQL server changes name or you want to change login information. ASP.NET gives you web.config to keep your settings. So we add our setting to web.config

<appsettings>
    <add value="server=(local);Trusted_Connection=false;database=Database;User ID=User;Password=Password" key="ConnectionString">
    <add value="10" key="Timeout">
</appsettings>

And now every time we need to connect to SQL server we get our connection string like this

sConnection = System.Configuration.ConfigurationManager.AppSettings["ConnectionString"];

Not really convenient. Plus we spending some runtime on a Hashtable look-up every time. Minimal but still a waste. So here is solution

Let's make clsGlobal class. Like this

public class clsGlobal 

    public static string sConnection; 
    public static int _iAmountOfThreads; 

    public static void Init() 
    { 
        sConnection = System.Configuration.ConfigurationManager.AppSettings["ConnectionString"]; 
        _iAmountOfThreads = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["AmountOfThreads"]); 
    } 
}

And in our global.asax write following code to initialize the clsGlobal

void Application_Start(object sender, EventArgs e) 

    clsGlobal.Init(); 
}

Now every time we need to get a connection string (or any other setting) we would use

clsGlobal.sConnection or clsGlobal._iAmountOfThreads

Benefits:

  1. No runtime waste
  2. Type safe. If we have it defined as a string or Int32 we do not need to convert it every time.

Note: The key here is that we defined everything in clsGlobal as static. It allows us to access those members/functions without actually creating instance of clsGlobal.

PS: I use _ to prefix members variables. But sConnection is an exception. It's used so often i do not want to type an extra characters.

PPS: One smart guy gave me a good advice. Make a static constructor in clsGlobal and move all Init code there. Then there is no need to call clsGlobal.init in Application_Start. You might want to do it that way.

Continue >>

No comments: