:::: MENU ::::

Monday, May 12, 2008

ntroduction (more about the ASP.NET session)

If you are developing ASP.NET web applications, you surely had to store and retrieve some persistent values belonging to each user navigating through your ASP.NET Web Application’s pages, so you naturally have used Session.

More information on using the Session is available here: MSDN

Session is nothing but a Dictionary (a collection based on key/value pairs) whose key type is a string and the value type is an object (i.e., any serializable object inheriting from object).

You can access the Session from "everywhere" using the current HTTP context System.Web.HttpContext.Current.Session or from the page’s shortcut reference in System.Web.UI.Page.Session.

Concretely, when you want to store a value in the Session, you may write such a line of code (without taking care of any session manager):

// Store value to session
int myValue = 10;
Session["MyKey"] = myValue;

Then, here is the code you may write to retrieve the previously stored value, mostly but not only from another page (or control):

// Retrieve value from session (up cast needed) 
int myValue = (int)Session["MyKey"];

Note that if you write you own class and want it to be stored to Session, you’ll need to add the [Serializable] attribute.

Session is raw, here is SessionHelper

As you see, Session is somewhat raw, and you’ll be quickly annoyed when you want to use advanced features such as categorized values, values belonging to a page or a control, etc.

In these cases, you should (you must) use the Session, but you should have some collision problems, a day or another!

A solution to this problem (let me know your feedback about it) is to use "scoped and categorized" session values. This is not a feature of the ASP.NET framework, but a session helper that I built and used with success, so I’m pleased to share this tip with you.

What is a "scoped and categorized" session value? Nothing but a session value whose key is generated from several parameters: its scope (for example: "Global"), its optional category (for example: "Filter"), and its handle/key (for example: "ItemsPerPage").

So, instead of using raw key / value pairs, we’ll use formatted key / value pairs this way (note that each token is separated by dots):

Session["Scope.Category.Key"]

  • Available scopes are the following (you can invent and implement yours):
    • Global (the same scope as raw session)
    • Page (current page, excluding query string parameters)
    • PageAndQuery (current page, including query string parameters)
  • Available scope’s categories are just limited to your imagination, for example, "Visitor" or "Filter" ones.
  • The key is the name / handle to the final value; choose a short and clear one, for example: "Surname".

 

More

Categories: