Search the articles  
  

• Using Server Side variables with Class

Monday, July 27, 2009

I really hate seeing the same session variable and cookie variable everywhere scattering through out the whole entire project.

For example,
In order to maintain Order ID in shopping cart,
Session["ORDERID"] or Response.Cookies("ORDERID").Value method can be used but it is truly unwise to reuse the same variable name again and again every time when you need to get the Order ID value.

What if you need to change the "ORDERID" variable name to "$_ORDERID_$", you will have to find and replace all the same variable in the files.

What if you need to apply encryption/decryption method to the sensitive data storing in Session variables, again you will have to find and apply the method to all the same variable in the files.

In order to avoid such a hassle method looking for the same variable in every places, this is how I always practice using and referencing the server side variables with class.

Create a new class, OrderID.cs, file in your project.
The file structure will be looked like this.


Inside the OrderID.cs, copy and place these codes.
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

namespace MySession
{
public class OrderID
{
//Assign the Order ID value into to current HTTP session variable $_ORDER_ID_$
public static string Set
{
set { HttpContext.Current.Session["$_ORDERID_$"] = value; }
}

//Get the Order ID value from current HTTP session variable $_ORDER_ID_$
public static string Get
{
get { return GetString(HttpContext.Current.Session["$_ORDERID_$"]); }
}

//Delete session variable $_ORDER_ID_$ from current HTTP
public static void Clear()
{
HttpContext.Current.Session.Remove("$_ORDER_ID_$");
}

//////////////////////////////////////////////////////////////////////////////////////////////////////
//This GetString Method should not be in this class,
//This method should put into seperate class which hold a collection of getting standard data type
//////////////////////////////////////////////////////////////////////////////////////////////////////
public static string GetString(object value)
{
try
{
return Convert.ToString(value);
}
catch
{
return String.Empty;
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
}



Now, you are ready to start using Session variable through the class.

To assign your "OrderID" to the session variable, just simple assign as below
MySession.OrderID.Set = "12345";

To get your "OrderID" from session variable,
############## = MySession.OrderID.Get;

To clear the "OrderID" from session variable when it is not longer used.
MySession.OrderID.Clear();


No comments:

Post a Comment