Click here to Skip to main content
15,886,519 members
Articles / Programming Languages / C#
Tip/Trick

Easy Sessions using Extension Methods

Rate me:
Please Sign up or sign in to vote.
4.33/5 (2 votes)
22 May 2014CPOL 12.1K   8   1
How to make sessions easy to use by extending .NET object class

Introduction

Working with sessions in ASP.NET can often be uncomfortable and lead to errors. By using these extension methods, this task will be much easier.

Background

You are used to program with C#, ASP.NET, sessions and extension methods.

Using the Code

The Extension Methods

Extending object class in order to add all objects methods to save sessions.

C#
public static class Sessions
{
    public static object ToSession(this object obj)
    {
        string sessionId = obj.GetType().FullName;

        System.Web.HttpContext.Current.Session.Remove(sessionId);
        System.Web.HttpContext.Current.Session.Add(sessionId, obj);

        return obj;
    }

    public static object FromSessionOrNew(this object obj, object objNew=null)
    {
        string sessionId = obj.GetType().FullName;

        if ((System.Web.HttpContext.Current.Session[sessionId] as object) != null){
            obj = System.Web.HttpContext.Current.Session[sessionId] as object;
        }
        else{
            obj = objNew;

            System.Web.HttpContext.Current.Session.Remove(sessionId);
            System.Web.HttpContext.Current.Session.Add(sessionId, obj);
        }

        return obj;
    }

    public static void RemoveFromSession(this object obj)
    {
        string sessionId = obj.GetType().FullName;
        System.Web.HttpContext.Current.Session.Remove(sessionId);
    }
}

Sample of Use of FromSessionOrNew

It is an instance of an object from session. Optionally, if session is null, a default instance (Foo() {Name="Lois"}) can be returned and stored in session, so, this method is useful both get an object from session and store it for the first time.

C#
public class Foo
{
    public string Name { get; set; }
    public int Age { get; set; }
}

public ActionResult Index()
{
    foo = (Foo)new Foo().FromSessionOrNew(new Foo() { Name = "Lois", Age = 30 });
}  

To store an object to session or remove it, use these methods:

C#
foo.ToSession();
foo.RemoveSession(); 

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)
Unknown
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
SuggestionTemplated version Pin
John Brett3-Jun-14 2:30
John Brett3-Jun-14 2:30 

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.