1/30/2011

Session handling using facade design pattern : ASP.NET web development

I work with a team of x developers and I always see problems with the usage of session variables in the application. It introduces bugs in the application which can not be traced by Unit testing and may be not with any kind of testing that happens before deployment :). They surface only when application is deployed in production and its very difficult to trace such bugs which turns out to be a expensive. So how to best deal with session management ?

Let me give a small idea of how this session work. To store information that is specific to a user session , ASP.NET provides the HttpSessionState class to store session-state values. An instance of the HttpSessionState class for each HTTP request is accessible throughout your application using the static HttpContext.Current.Session property. Access to the same instance is made simpler on every Page and UserControl using the Session property of the Page or UserControl.

The HttpSessionState class provides a collection of key/value pairs, where the keys are of type String and the values are of type Object. This means that Session is extremely flexible and you can store just about any type of data in Session. You can store any Type in session variable and cast it back where ever required. This also brings a new problem of people not doing Type checks. They use the session key repeatedly instead of reusing and also store everything in sessions. When I want to see all the sessions used in my code in one place, I could never find them. To deal with all these things, we use a pattern called Facade pattern.

What is Facade design pattern ?

A facade is an object that provides a simplified interface to a larger body of code, such as a class library. A facade can:

* make a software library easier to use, understand and test, since the facade has convenient methods for common tasks;
* make code that uses the library more readable, for the same reason;
* reduce dependencies of outside code on the inner workings of a library, since most code uses the facade, thus allowing more flexibility in developing the system;
* wrap a poorly-designed collection of APIs with a single well-designed API (as per task needs).


With this pattern, we can build simplified interfaces that points to different areas of complex code structure.

So How to we use this facade to do organized session management in our application ?

We make developers to only access the HttpSessionState from within one single static class in your application - the facade. There must be no direct access to the Session property from within code on pages or controls, and no direct access to HttpContext.Current.Session other than from within the facade.

All session variables should be exposed as properties of the facade class which gives us extra control over the different session variables used with in the application.

It also ensures the following :

  • Strong typing of what gets put into session variables.
  • No need for casting in code where session variables are used.
  • All the benefits of property setters to validate what gets put into session variables (more than just type).
  • All the benefits of property getters when accessing session variables. For example, initialising a variable the first time it is accessed.

An Example of Facade Class :

public static class SessionVars

{

///


///
///

///
///
///

internal bool SetHttpSessionObject(string key, object value)
{
bool writtenAck = false;
if (IsSessionValid)
{
HttpContext.Current.Session[key] = value;
writtenAck = true;
}

return writtenAck;

}

///


///
///

///
///

internal object GetHttpSessionObject(string key)
{
return IsSessionValid
? HttpContext.Current.Session[key]
: null;
}

///


///
///

public bool IsApprover
{
get
{
bool IsApprove = false;
object IsApproverVal = GetHttpSessionObject("IsApprover");
if (IsApproverVal != null)
{
IsApprove = bool.Parse(IsApproverVal.ToString());
}

return IsApprove;
}
set
{
SetHttpSessionObject("IsApprover", value);
}
}
///


///
///

public string UserID
{
get
{
string UserIDval = "";
object UserVal = GetHttpSessionObject("UserID");
if (UserVal != null)
{
UserIDval = UserVal.ToString();
}
return UserIDval;
}
set
{
SetHttpSessionObject("appUserID", value);
}
}

}

The above class demonstrates how we can define session variables in facade and make use of

HttpContext.Current.Session

Now let me explain how to make use of these properties in your Code which is quite simple.

string VirUser = SessionVars.UserID

This gives you the advantage of not casting the object everytime you use it. Also it does help you in isolating the internal implementation from the rest of your code.

Next time you choose to implement session in different way, All you have to do is change it here but not everywhere. Cool Ain't it ?

The technique seems quite simple but believe me , it has lot of added advantages for you.

The implementation of Session can be again separated from this class through the usage of partial class and could be made really isolated.I will talk about Singleton and Partial class integration in my next article. Stay tuned :)..

Love ASP.NET tips ? For more Subscribe here or click here to get updates via email

11 comments:

How would you define/implement IsSessionValid?

internal bool IsSessionValid
{
get { return (HttpContext.Current != null) && (HttpContext.Current.Session != null); }
}

I think this will not be very optimized implementation,Say if i want to Access SessionVars.UserID in 4 Different Classes,then every time .net need to Type Cast Each Call from Object to Desired return type.
Better way would be have some private field
private static string _userId and Check If _userId==0 then fetch from Session else return from field itself

But again it will create concurrency issue on static fields
Can u suggest its workaround...

But the casting need to be done only once on the page(Dont think its a overhead).If you use it multiple times on the page, you can assign it to some variable and reuse it.

I think ASP is a good programming language when it comes web design.

perth website design

This is best article so far I have read online. I would like to appreciate you for making it very simple and easy. I have found another nice post related to this post over the internet which also explained very well. Here I am sharing that post url it might also be useful for you.

http://www.mindstick.com/Articles/701259d3-ec8d-4881-8b18-b65923e9f59c/?Session%20in%20ASP.Net

Thanks everyone for your precious post.

This comment has been removed by the author.

Lovely I used it my currnet project, keep it up dude!

Post a Comment