Click here to Skip to main content
Click here to Skip to main content

Session Management With Generics

, 10 Mar 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
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:

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
//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
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)

Share

About the Author

Kundan Singh Chouhan
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 Pinmemberarpan sharma12-May-14 2:27 
AnswerRe: Regarding the implementation of this approach PinmemberKundan Singh Chouhan24-May-14 2:46 
Questionnice article.. Pinmembervishwaraj8-Nov-13 6:57 
AnswerRe: nice article.. PinmemberKundan Singh Chouhan8-Nov-13 7:05 
GeneralStatic would made Session accessible across application PinmemberM AZZAAAM12-Mar-13 5:35 
GeneralRe: Static would made Session accessible across application [modified] PinmemberKundan Singh Chouhan12-Mar-13 10:12 
QuestionClone your references Pinmemberegilagre11-Mar-13 7:04 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.141223.1 | Last Updated 10 Mar 2013
Article Copyright 2013 by Kundan Singh Chouhan
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid