CSharpFeeds - All your C# feeds in one place.

Sponsors

Tuesday, February 02, 2010

ASP.NET Session Stuff

by moomi via Brain. Fruit. Code. on 2/2/2010 5:23:00 AM

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)

email it!bookmark it!digg it!

Original Post: ASP.NET Session Stuff

Subscribe

New Feed

Product Spotlight

Recently Updated Sources

Legal Note

The content of the postings is owned by the respective author. CSharpFeeds is not responsible for the contents of the postings. This site is automatically generated and cannot be reviewed for abusive content. If you find abusive content on CSharpFeeds, please contact us. Designated trademarks and brands are the property of their respective owners. All rights reserved.

Advertise with us