Tuesday, June 3, 2008

Perfect ASP.NET application, Part 2

clsGlobal and it's benefits.

We now have a static class clsGlobal. Let fill it with our little helpers that simplify our lives.

The first thing that comes in mind methods to work with database

public static DataTable GetData(string sSql)
{
    SqlConnection con = new SqlConnection(sConnection);
    SqlDataAdapter ad = new SqlDataAdapter(sSql, con);
    DataTable dt = new DataTable();
    try
    {
        con.Open();
        ad.Fill(dt);
        return dt;
     }
    finally
    {
        ad.Dispose();
        con.Close();
    }
}
public static void ExecuteSql(string sSql)
{
    SqlConnection con = new SqlConnection(sConnection);
    SqlCommand com = new SqlCommand(sSql, con);
    try
    {
        con.Open();
        com.ExecuteNonQuery();
    }
    finally
    {
        com.Dispose();
        con.Close();
    }
}
public static object ExecuteScalar(string sSql)
{
    SqlConnection con = new SqlConnection(sConnection);
    SqlCommand com = new SqlCommand(sSql, con);
    try
    {
        con.Open();
        object objTmp = com.ExecuteScalar();
        return objTmp;
    }
    finally
    {
        com.Dispose();
        con.Close();
    }
    return null;
}

Now we want to be consistent everywhere in our web site so let's introduce couple of methods
public static string GetDateTime(DateTime dt)
{
    return dt.ToString("MM/dd/yy hh:mm tt");
}

public static string GetMoneyHtml(object objVal)
{
    return ((decimal)objVal).ToString("$0.00");
}

Benefits:

  1. Convenient and save methods to get DataTable or run SQL statement. You will not forget to close .NET connection.
  2. Unified look of our website. Everywhere where we need to show DateTime we use <%=clsGlobal.GetDateTime(DateTime.Now) %> or like this in a table <%# clsGlobal.GetMoneyHtml(Eval("amount"))%>

I hope you got an idea and will put bunch of helpers in this class. Just do not forget to make them static.

Continue >>

No comments: