Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Session Management With Generics

4.33/5 (2 votes)
10 Mar 2013CPOL1 min read 17.7K  
Manage multiple sessions in a single property

Introduction

This code snippet is very beneficial to manage multiple sessions in a single property.

Background

We all know the use of sessions. Over time, many developers create multiple session objects or properties for their desired task. But handling these multiple sessions becomes a nightmare to the developers. So to overcome this headache, I wrote a script with generics to encapsulate these sessions in a single unit.

Using the Code

The code is quite simple. In the below snippets, a static class is created with the name as SiteSession. In this class, a property and an extension method are defined as below:

C#
public static class SiteSession
{
   public static Dictionary<string,object> SessionObjects
   {
    get 
    {
        if (HttpContext.Current.Session["SessionObjects"] == null)  
              HttpContext.Current.Session["SessionObjects"] = new Dictionary<string, object>(); 
       
           return (Dictionary<string, object>)HttpContext.Current.Session["SessionObjects"]; 
    }
   }

   public static T GetValueOrDefault<T>(this Dictionary<string, object> DICT, string Key)
   {
    return DICT.ContainsKey(Key) ? (T)Convert.ChangeType(DICT[Key], typeof(T)) : default(T);
   }
}

In the above, the property is used to handle the main session object, as it has the type Dictionary<string, object>, so it contains the <Key, Value> pair where key would be the name of session variable and value would be any kind of object bounded to this key.

The class has an Extension Method which is used to retrieve the specific key's value from the SessionObject property according to its type.

Sample Usage of "SiteSession" Class

For Value Types
C#
//Set the value in Session

SiteSession.SessionObjects.Add("AccountNo", 1046);            // int type
SiteSession.SessionObjects.Add("Amount", 25756.69M);          // decimal type
SiteSession.SessionObjects.Add("DepositDate", DateTime.Now);  // datetime type

//Get the value from Session along with type  

int AccountNo = SiteSession.SessionObjects.GetValueOrDefault<int>("AccountNo");
decimal Amount = SiteSession.SessionObjects.GetValueOrDefault<decimal>("Amount");
DateTime DepositDate = SiteSession.SessionObjects.GetValueOrDefault<DateTime>("DepositDate"); 
For Reference Types
C#
Class Product
{ 
    public int ProductId { get;set; }
    public string ProductName { get;set; }
    public decimal Price { get;set; }
}

//Set the value in Session

Product obj = new Product 
              { 
                 ProductId = 1,
                 ProductName = "Bottle",
                 Price = 25.64M
              };

SiteSession.SessionObjects.Add("Product", obj);    

//Get the value from Session 

Product obj = SiteSession.SessionObjects.GetValueOrDefault<Product>("Product");

The above example describes how SessionObject can be used with Value Types and Reference Types both.

Points of Interest

  • Handle multiple session objects with a single property
  • Retrieve the value of session according to its type without taking care of boxing-unboxing complex code
  • Easy to implement

Thanks for reading. Happy coding.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)