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
SiteSession.SessionObjects.Add("AccountNo", 1046);
SiteSession.SessionObjects.Add("Amount", 25756.69M);
SiteSession.SessionObjects.Add("DepositDate", DateTime.Now);
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; }
}
Product obj = new Product
{
ProductId = 1,
ProductName = "Bottle",
Price = 25.64M
};
SiteSession.SessionObjects.Add("Product", obj);
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.