Click here to Skip to main content
15,884,298 members
Articles / Web Development / ASP.NET
Tip/Trick

Session Management With Generics

Rate me:
Please Sign up or sign in to vote.
4.33/5 (2 votes)
10 Mar 2013CPOL1 min read 17K   11   7
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)


Written By
Software Developer (Senior)
India India
Eager to contribute highly applicable application development skills and ability to personalize service delivery to analyzing business needs and translating them into executable strategies.

Comments and Discussions

 
QuestionRegarding the implementation of this approach Pin
arpan sharma12-May-14 1:27
arpan sharma12-May-14 1:27 
AnswerRe: Regarding the implementation of this approach Pin
Kundan Singh Chouhan24-May-14 1:46
Kundan Singh Chouhan24-May-14 1:46 
Questionnice article.. Pin
vishwaraj8-Nov-13 5:57
vishwaraj8-Nov-13 5:57 
AnswerRe: nice article.. Pin
Kundan Singh Chouhan8-Nov-13 6:05
Kundan Singh Chouhan8-Nov-13 6:05 
GeneralStatic would made Session accessible across application Pin
M AZZAAAM12-Mar-13 4:35
M AZZAAAM12-Mar-13 4:35 
GeneralRe: Static would made Session accessible across application Pin
Kundan Singh Chouhan12-Mar-13 9:12
Kundan Singh Chouhan12-Mar-13 9:12 
QuestionClone your references Pin
egilagre11-Mar-13 6:04
egilagre11-Mar-13 6:04 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.