Feb022010

ASP.NET Session Stuff

Published by moomi at 5:23 AM under session

Today I’ll present a tidy way to manage session objects without all the tedious checking for existence. The thought of seeing this in code makes me cringe:

if (Session["something"] == null)
{
   Session["something"] = new Something();
}

 

Come on, man! If you have any kind of session objects, you’re going to do this once for every object. I’ve been using a session class extension that handles the default creation of objects in one line. The two methods of the SessionExtensinos class use lambda expressions to create objects that don’t exist in session store. Instead of the code above, you would write:

var something = Session.GetSessionClass<Something>("Session.Something", () => new Something());

The GetSessionClass method checks for the existence of the object in session store. If it exists, it returns it. If it does not exist, it executes the lambda method to create the object.

The second method of the class handles native objects:

var value = Session.GetSessionValue<int>("Session.Value", () => 42);

For ASP.NET pages, the strategy is to load session objects with an override to OnInit, and to store changes to them in an override to OnUnload. In the sample project I’ve included with this post, graphic_heisman_bw_sm I created a web page that is initialized with the name of a Heisman trophy winner. The winner and the year are stored in an entity class that is handled with the GetSessionClass method. I’ve also tracked the number of posts in an integer handled by the GetSessionValue method. When you enter a new name and number and post them, the values are stored in session.

protected override void OnInit (EventArgs e)
{
   base.OnInit (e);
   NameAndNum = Session.GetSessionClass<NameAndNumber> ("SessionStuff.NameAndNum",
      () => new NameAndNumber () { Name = "Ernie Davis", Year = 1961 });
   Posts = Session.GetSessionValue<int>("SessionStuff.Posts", () => 0);
}
 
protected override void OnUnload (EventArgs e)
{
   base.OnUnload (e);         
   Session["SessionStuff.NameAndNum"] = NameAndNum;
   Session["SessionStuff.Posts"] = Posts;
}



 

Download SessionStuff.zip (7.81 kb)



[KickIt] [Dzone] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Tags:

E-mail | Permalink | Trackback | Post RSSRSS comment feed 0 Responses | Sign in to comment