Home > .net 2.0, .net 3.0, .net 3.5, c#, Microsoft, Visual Studio 2008 > Handling Sessions Objects with a Custom Session Manager

Handling Sessions Objects with a Custom Session Manager

September 18, 2008

I try not to abuse Session objects too much—keep them simple types, not too many, etc.  However, on a recent project where there was a few of us dinking with the code, it became an issue with how the keys were named, where they were created, etc. 

To correct the problem on future projects, I tossed together a little class in the mix to manage the “keys”.

public class SessionManager

{

protected HttpSessionState session;

 

       public SessionManager(HttpSessionState httpSessionState)

       {

              session = httpSessionState;

}

 

public SessionManager()

       {

              session = HttpContext.Current.Session;

}

 

       public void Dispose()

       {

              session.Clear();

              session.Abandon();

       }

 

       public bool IsFoo

       {

              get { return

session[“IsFoo”].ConvertTo<bool>(); }

set { session[“IsFoo”] = value; }

}

 

       public string FooId

       {

              get { return

session[“FooId”].ConvertTo<string>(); }

set { session[“FooId”] = value; }

}

}

The two constructors allow the consumer to either accept the default HttpContext.Current session object or provide their own.  From there, the “keys” are coded within this page rather than in every code block throughout the site. 

To use the SessionManager:

I inherit all of my pages from a default page (DefaultPage, for lack of a better name) and place the session manager as a public field.

DefaultPage.cs:

public class DefaultPage : Page

{

public SessionManager CurrentSession;

      

protected void Page_PreInit(object sender, EventArgs e)

       {

              CurrentSession = new SessionManager();

}

}

To use the CurrentSession field, simply reference it.  This makes reading/writing to session easy on the inheriting pages.

private List<Foo> GetFooList()

{

var foo = sessionManager.IsFoo

              ? Foo.GetFooById(sessionManager.FooId)

: new List<Foo> { Foo.GetEmptyFoo() };

return foo;

}

Still tweaking to do, but it works and seems clean enough.

Suggestions or better ideas? :) 

%d bloggers like this: