Click here to Skip to main content
Click here to Skip to main content

Manage ASP.NET Session Variables using the Facade Design Pattern

By , 6 Nov 2012
 

Introduction

Just about every ASP.NET application needs to keep track of data for a user's 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.

But (there is always a but) this flexibility does not come without a cost. The cost is the ease with which bugs can be introduced into your application. Many of the bugs that can be introduced will not be found by unit testing, and probably not by any form of structured testing. These bugs often only surface when the application has been deployed to the production environment. When they do surface it is often very difficult, if not impossible, to determine how they occurred and be able to reproduce the bug. This means they are very expensive to fix.

This article presents a strategy to help prevent this type of bug. It uses a Design Pattern called a Facade, in that it wraps the very free interface provided by the HttpSessionState class (that can meet the requirements of any application) with a well designed and controlled interface that is the purpose built for a specific application. If you are not familiar with Design Patterns or the Facade pattern, a quick internet search of "facade design pattern" will provide you with plenty of background. However, you do not have to understand design patterns in order to understand this article.

The example code shown in this article is written in C#, but the concepts are applicable to any .NET language.

What is the Problem?

In this section of the article, I will describe the problems with direct access to the HttpSessionState class, without the facade. I will describe the kinds of bugs that can be introduced.

The following shows the typical code written to access session-state variables.

// Save a session variable
Session["some string"] = anyOldObject;
// Read a session variable
DateTime startDate = (DateTime)Session["StartDate"];

The problems arise from the flexible interface provided by HttpSessionState: the keys are just strings and the values are not strongly typed.

Using String Literals as Keys

If string literals are used as the keys, the string value of the key is not checked by the compiler. It is easy to create new session values by simple typing errors.

Session["received"] = 27;
...
Session["recieved"] = 32;

In the code above, two separate session values have been saved.

Most bugs like this will be identified by unit testing – but not always. It may not always be apparent that the value has not changed as expected.

We can avoid this kind of bug by using constants:

private const string received = "received";
...
Session[received] = 27;
...
Session[received] = 32;

No Type Checking

There is no type checking of the values being stored in session variables. The compiler cannot check correctness of what is being stored.

Consider the following code:

Session["maxValue"] = 27;
...
int maxValue = (int)Session["maxValue"];

Elsewhere the following code is used to update the value:

Session["maxValue"] = 56.7;

If the code to read the "maxValue" session variable into the maxValue int variable is executed again there will be an InvalidCastException thrown.

Most bugs like this will be identified by unit testing – but not always.

Re-using a Key Unintentionally

Even when we define constants on each page for the session keys, it is possible to unintentionally use the same key across pages. Consider the following example:

Code on one page:

private const string edit = "edit";
...
Session[edit] = true;

Code on a second page, displayed after the first page:

private const string edit = "edit";
...
if ((bool)Session[edit])
{
    ...
}

Code on a third, unrelated, page:

private const string edit = "edit";
...
Session[edit] = false;

If the third page is displayed for some reason before the second page is displayed, the value may not be what was expected. The code will probably still run, but the results will be wrong.

Usually this bug will NOT be picked up in testing. It is only when a user does some particular combination of page navigation (or opening a new browser window) that the bug manifests.

At its worst, no one is aware that the bug has manifested, we may just end up modifying data to an unintended value.

Re-using a Key Unintentionally - Again

In the example above, the same data type was stored in the session variable. Because there is no type checking of what gets stored, the problem of incompatible data types can also occur.

Code on one page:

Session["FollowUp"] = "true";

Code on a second page:

Session["FollowUp"] = 1;

Code on a third page:

Session["FollowUp"] = true;

When the bug manifests, there will be an InvalidCastException thrown.

Usually this bug will NOT be picked up in testing. It is only when a user does some particular combination of page navigation (or opening a new browser window) that the bug manifests.

What Can We Do?

The First Quick Fix

The first and most simple thing we can do is make sure we never use string literals for session keys. Always use constants and so avoid simple typing mistakes.

private const string limit = "limit";
...
Session[limit] = 27;
...
Session[limit] = 32;

However, when constants are defined locally (e.g. at page level), we might still re-use the same key unintentionally.

A Better Quick Fix

Rather than define constants on each page, group all session key constants into a single location and provide documentation that will appear in Intellisense. The documentation should clearly indicate what the session variable is used for. For example, define a class just for the session keys:

public static class SessionKeys
{
    /// <summary>
    ///     The maximum ...
    /// </summary>
    public const string Limit = "limit";
}

...

    Session[SessionKeys.Limit] = 27;

When you need a new session variable, if you choose a name that has already been used you will know this when you add the constant to the SessionKeys class. You can see how it is currently being used and can determine if you should be using a different key.

However, we are still not ensuring consistency of data type.

A Much Better Way - Using a Facade

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 will be exposed as properties of the facade class.

This has the same advantages as using a single class for all the session keys, plus the following advantages:

  • 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 Session Facade Class

Here is an example class to implement the Session facade for an application called MyApplication.

/// <summary>
///     MyApplicationSession provides a facade to the ASP.NET Session object.
///     All access to Session variables must be through this class.
/// </summary>
public static class MyApplicationSession
{
    # region Private Constants
    //---------------------------------------------------------------------
    private const string userAuthorisation = "UserAuthorisation";
    private const string teamManagementState = "TeamManagementState";
    private const string startDate = "StartDate";
    private const string endDate = "EndDate";
    //---------------------------------------------------------------------
    # endregion

    # region Public Properties
    //---------------------------------------------------------------------
    /// <summary>
    ///     The Username is the domain name and username of the current user.
    /// </summary>
    public static string Username
    {
        get { return HttpContext.Current.User.Identity.Name; }
    }


    /// <summary>
    ///     UserAuthorisation contains the authorisation information for
    ///     the current user.
    /// </summary>
    public static UserAuthorisation UserAuthorisation
    {
        get 
        {
            UserAuthorisation userAuth 
                     = (UserAuthorisation)HttpContext.Current.Session[userAuthorisation];

            // Check whether the UserAuthorisation has expired
            if (
                 userAuth == null || 
                 (userAuth.Created.AddMinutes(
                   MyApplication.Settings.Caching.AuthorisationCache.CacheExpiryMinutes)) 
                     < DateTime.Now
               )
            {
                userAuth = UserAuthorisation.GetUserAuthorisation(Username);
                UserAuthorisation = userAuth;
            }

            return userAuth;
        }

        private set
        {
            HttpContext.Current.Session[userAuthorisation] = value;
        }
    }

    /// <summary>
    ///     TeamManagementState is used to store the current state of the 
    ///     TeamManagement.aspx page.
    /// </summary>
    public static TeamManagementState TeamManagementState
    {
        get 
        {
            return (TeamManagementState)HttpContext.Current.Session[teamManagementState];
        }

        set
        {
            HttpContext.Current.Session[teamManagementState] = value;
        }
    }

    /// <summary>
    ///     StartDate is the earliest date used to filter records.
    /// </summary>
    public static DateTime StartDate
    {
        get 
        {
            if (HttpContext.Current.Session[startDate] == null)
                return DateTime.MinValue;
            else
                return (DateTime)HttpContext.Current.Session[startDate];
        }

        set
        {
            HttpContext.Current.Session[startDate] = value;
        }
    }

    /// <summary>
    ///     EndDate is the latest date used to filter records.
    /// </summary>
    public static DateTime EndDate
    {
        get 
        {
            if (HttpContext.Current.Session[endDate] == null)
                return DateTime.MaxValue;
            else
                return (DateTime)HttpContext.Current.Session[endDate];
        }

        set
        {
            HttpContext.Current.Session[endDate] = value;
        }
    }
    //---------------------------------------------------------------------
    # endregion
}

The class demonstrates the use of property getters that can provide default values if a value has not been explicitly stored. For example, the StartDate property provides DateTime.MinValue as a default.

The property getter for the UserAuthorisation property provides a simple cache of the UserAuthorisation class instance, ensuring that the instance in the session variables is kept up to date. This property also shows the use of a private setter, so that the value in the session variable can only be set under the control of facade class.

The Username property demonstrates a value that may once have been stored as a session variable but is no longer stored this way.

The following code shows how a session variable can be accessed through the facade. Note that there is no need to do any casting in this code.

// Save a session variable
MyApplicationSession.StartDate = DateTime.Today.AddDays(-1);
// Read a session variable
DateTime startDate = MyApplicationSession.StartDate;

Additional Benefits

An additional benefit of the facade design pattern is that it hides the internal implementation from the rest of the application. Perhaps in the future you may decide to use another mechanism of implementing session-state, other than the built-in ASP.NET HttpSessionState class. You only need to change the internals of the facade - you do not need to change anything else in the rest of the application.

Summary

The use of a facade for HttpSessionState provides a much more robust way to access session variables. This is a very simple technique to implement, but with great benefit.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

David Hay
Web Developer
Australia Australia
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5memberHumayun Kabir Mamun2 May '13 - 23:00 
Very helpful
QuestionNot bad.membermark merrens5 Apr '13 - 10:49 
Done something similar for a while though I use resource files to store key names - find that easier to manage and document.
"If you think it's expensive to hire a professional to do the job, wait until you hire an amateur." Red Adair.
nils illegitimus carborundum
 
me, me, me

GeneralMy vote of 5memberttatum25 Mar '13 - 10:02 
I've just put all my application level configuration parameters into a singleton. Next step. Put all the session level parameters the a facade.
 
Thanks David!
GeneralMy vote of 5memberPhat (Phillip) H. VU27 Dec '12 - 15:54 
Nice post.
GeneralMy vote of 5memberSavalia Manoj M7 Nov '12 - 1:07 
Good one
GeneralMy vote of 5memberJ. Wijaya6 Nov '12 - 22:58 
Nice
QuestionNice sharememberJ. Wijaya6 Nov '12 - 22:58 
I've used this pattern for the last few years.
but that time i dont know what pattern i use
i thought everyone already used it. Big Grin | :-D
 

give it 5 from me.
Thirst for knowledge ...

GeneralMy vote of 4membern.podbielski6 Nov '12 - 5:52 
I did something like this myself. An I think this could be done even better. This is nice though
GeneralMy vote of 4mvpPaulo Zemek6 Nov '12 - 4:25 
This is a good practice, but I would add that an interface should be used to get access to those properties. So, the natural implementation will use the real asp.net session, but unit testing could use a completely unrelated implementation.
QuestionSpellcheck ravaged this example.....memberSarah Cartwright5 Nov '12 - 23:03 
Using String Literals as Keys
 
If string literals are used as the keys, the string value of the key is not checked by the compiler. It is easy to create new session values by simple typing errors.
 
Session["received"] = 27;
...
Session["received"] = 32;
 
(They're both spelt the same!)
AnswerRe: Spellcheck ravaged this example.....memberDavid Hay6 Nov '12 - 3:04 
Thanks Sarah
 
I just checked the revision history of the article. It was "corrected" by a CodeProject editor back in 2010! I have just submitted an update with one of the "received" changed back to "recieved". The update needs to get approved for publication though, so not sure when it will be visible.
 
Regards
David
GeneralIs there any way to restrict direct access to HttpContext.Current.Session?memberjuancamilo20 May '11 - 10:41 
Thanks for the article.
For a larger group of developers (300 +), enforcing the use of a wrapper / facade can be a challnege on its own. Is there any way to restrict the direct access to the HttpContext.Current.Session in the application / .NET solution?
AnswerRe: Is there any way to restrict direct access to HttpContext.Current.Session?memberDavid Hay20 May '11 - 19:03 
Not that I am aware of.
 
What I have done is periodcally do a check of the code to "find all references" to HttpContext.Current.Session. These should only ever be found in the facade class. It does not take long in Visual Studio to do this. This could possible be automated as a check-in policy.
 
But I have not bothered as at the same time as checking there are no stray references to HttpContext.Current.Session, I have also taken the time to review the new code that has been added to the facade class.
GeneralFacade Patternmemberrahpune19998 Dec '09 - 20:36 
I tried to use the code as it is for learning purpose. when i tried to compile I got error as "The type or namespace name 'UserAuthorisation' could not be found (are you missing a using directive or an assembly )
 
could you please let me know from where I should get the UserAuthorization namespace
 
sfsfasdfs

AnswerRe: Facade PatternmemberDavid Hay9 Dec '09 - 10:56 
The code is sample code only and will not compile just by copying the code into your application. You will have the same problem with other things such as ","TeamManagementState" and "MyApplication.Settings.Caching.AuthorisationCache.CacheExpiryMinutes" These classes are application specific examples.
 
The intention of the article is not to show a real working application but to show a better way of accessing the HttpSessionState for the current user.
 
The example MyApplicationSession class is used to demonstrate the ideas in the article, such as the class being static, using constants rather than strings when accessing HttpContext.Current.Session, using strongly typed properties, using appropriately scoped property getters and setters, including validation of values in property setters, and providing default initialisation in property getters.
 
Regards
David
GeneralRe: Facade PatternmemberNEMEE11 Jan '13 - 4:20 
Hi David Hay,
Thanks alot for this knowledge.Can you provided me a demo application (for a example)with this (Manage ASP.NET Session variables using the Facade design pattern) implemented. I want to use this in my application.
GeneralThank youmemberyaron1130 Aug '09 - 14:02 
it helped me a lot Thumbs Up | :thumbsup: Blush | :O
GeneralSession Variables Are Not Persisting Between Pagesmemberrconnell25 Feb '09 - 10:20 
I set the variables like your example but when I try to access them on another page they return null. :(
GeneralRe: Session Variables Are Not Persisting Between PagesmemberDavid Hay25 Feb '09 - 11:35 
Have you enabled using session state? Make sure the mode attribute of the element in your web.config is not set to "off".
 
Otherwise you will need to post the code you are using.
 
David

QuestionHow to Share Session State Between aspx page and asp pagememberNidhiKanu7 Jan '09 - 20:44 
Hi ,
 
      i have added one session variable on code behind of one aspx page( Session.Add("strPendingEnquiryQry", strQry);) and trying to access it on asp page( Response.Write "alert('" & Session("strPendingEnquiryQry") & "');" & vbcrlf) but not able to access it .
AnswerRe: How to Share Session State Between aspx page and asp pagememberAnjum.Rizwi11 Jan '09 - 19:19 
ASP.Net does not support session sharing between Asp & Asp.net.
 
Other alternate way of session sharing is by posting & retrieving all session variable on dummy asp page then redirect to original page. Let me know if need more explanation on this.
 
Hope this will help you.
 
Thanks
Anjum Rizwi
GeneralRe: How to Share Session State Between aspx page and asp pagememberNidhiKanu11 Jan '09 - 19:46 
Thanx,i have changed my way for accessing these values.
GeneralGratefulmemberMember 218346921 Nov '08 - 4:50 
David, this article is the answer to my prayers
Gary in Texas
GeneralI did something like thismemberbigbrownbeaver31 Jul '08 - 4:44 
I also did a class similar to yours, after following the same path of using constants to store session variable names. What you didn't mention is the benefit of XML comments for the properties. They make it easier for the next guy to understand your code.
 
My implemetation was slightly leaner. I Made a parent class that stores the Session state in a property Named Session. I then inherit the class and it is like working with the Session in the usual way in the subclass without calling CurrentContext. The only downside to this is of course the fact that I had to initialize an instance of the class in every page.
 
It's really nice to see someone wrote this article. Smile | :)
 
I think that it's a big flaw in ASP .Net that they didnt incorporate more sane session variable management.
 
Keep up the good work!
GeneralRe: I did something like thismemberobinna_eke7 Nov '08 - 0:33 
BigBrown, can I have your session class
GeneralNice but...memberGBAR412 Apr '08 - 8:14 
I am newbees on asp.net.
Where should i do the declaration of my static class to get access to it on any page of the site?
 
Thanks
AnswerRe: Nice but...memberDavid Hay14 Apr '08 - 13:10 
You can add the class anywhere in your site. A common place is the App_Code folder.
QuestionUnique session keys?memberrizzy25024 Oct '07 - 7:57 
Hi, this is a good article. However, what about uniqueness of the session keys? For example if i have a user control that uses session variables, and I place it on different pages, then the variables would all be cross accessed. Any solutions? I've tried using combination of this.UniqueID + variablename, but if the user control instances placed on different pages happen to have same IDs, then it's no use! Any solutions?
 
Rizzy
AnswerRe: Unique session keys?memberDavid Hay24 Oct '07 - 14:22 
Hi Rizzy
 
I don't know the data you are putting into session for these user control's, but depending on what it is, it may be appropriate to use View State for these rather than Session State. Usually for data that is related to a particular instance of a control, rather than to the user's session as a whole, it is more appropriate to use View State for the control.
 
But this is not always the case.
 
The issue you describe is also an issue if you have an application where you want to allow the user to open two windows that both display the same pages but for different data and rely on unique values in session variables. This needs to be done under control of the application rather than just having the user open a new browser window that is tied to the same ASP.NET session (e.g. File --> New --> Window menu in IE).
 
What I do in these circumstances is have a unique window instance key for each window. This is stored in a hidden field or view state for the page. When the user requests to open another window through the application, a new window instance key is generarate for each window. Then I change the properties in my session facade class to be a Dictionary of the underlying type, keyed by the window instance key.
 
You could use this same approach for different instances of your user control.
 
Hope this helps
David
GeneralRe: Unique session keys?memberboy.pockets20 Nov '07 - 16:33 
I had the same problems as described by Rizzy: a Session variable in a UserControl that is to be used in multiple places on a single page. This causes each instance of the User Control to access the same Session variable.
 
Using the ViewState instead of the Session object seems to have solved this issue.
 
Thankyou David.
Generala better solution!!membergizmoworks1 Aug '07 - 8:51 
It's seems like a great idea but i think there should be a better way!
 
What I want is a class (or a list or whatever) where I can say
 
String ClientName;
String DealerID;
 
and it would generate the code for me like
 
public static string ClientName{
get
{
object obj = HttpContext.Current.Session["clientName"];
if (obj != null)
return (string)obj;
return null;

}
set
{
HttpContext.Current.Session["clientName"] = value;
}
 
}
 
One way may be to use reflections but I don't know how.
Another solution maybe to use typed datasets but again I don't know how.
 
Does anybody know how?
 
BTW, I'm sure you could do this using Rails/Groovy, definitely Lisp!
 

 
A
GeneralVery nicememberwconnors17 Jul '07 - 10:48 
This rocks! Thanks!
 
wconnors

GeneralHi,memberAnjum.Rizwi12 Jun '07 - 20:19 
Hi,
 
Can any one provide sample application, because I cant understand about these class "UserAuthorisation","TeamManagementState" and "MyApplication.Settings.Caching.AuthorisationCache.CacheExpiryMinutes"
 
Thank You,
Anjum Rizwi
 
Anjum Rizwi
AnswerRe: Hi,memberDavid Hay12 Jun '07 - 20:52 
Hi Anjum
 
These classes are application specific examples. The intention of the article is not to show a real working application but to show a better way of accessing the HttpSessionState for the current user.
 
The example MyApplicationSession class is used to demonstrate the ideas in the article, such as the class being static, using constants rather than strings when accessing HttpContext.Current.Session, using strongly typed properties, using appropriately scoped property getters and setters, including validation of values in property setters, and providing default initialisation in property getters.
 
Regards
David
GeneralRe: Hi,memberAnjum.Rizwi12 Jun '07 - 20:59 
Wow, Quick Response, Got the concept
Thank you
GeneralEnjoyed your articlemembercykophysh3915 May '07 - 9:03 
I enjoyed your article and found it really intresting and learned a thing or two
 
Keep up the good work
 
Kind Regards,
Gary


My Website || My Blog || My Articles

GeneralVery nicely written articlememberRajiv Gowda14 May '07 - 0:51 
Thanks for the Simple and Precise article.
 
Rajiv Gowda
CodeTheatre
GeneralPlease post same class in VBmemberpop83in31 Mar '07 - 3:14 
Above example and code is C#.
Same class in vb would be apprciated
 

Thanks in advance
QuestionYou can comile static class?memberxibeifeijian27 Mar '07 - 20:53 
public static class MyApplicationSession
 
In vs2003 ,I got a compile error that static can't decorate the class!
AnswerRe: You can comile static class?memberDavid Hay27 Mar '07 - 21:25 
In .NET 1.x I don't think you can explicitly define a class as static. Instead, to stop an instance being created you have to define a private default constructor.
 
Also, .NET 1.x does not support having different access modifiers for set and get. To achieve this, you only define get on the public property and then provide a private method to do the set.
 
Regards
David
GeneralExcellentmemberChris Fulstow26 Mar '07 - 20:41 
Great article, David. This technique might also be useful for other Hashtable-like objects such as the Cache.
 
Chris
QuestionObjectDataSource SelectParameters?memberwk63318 Dec '06 - 12:48 
I have done essentially this before, creating a static class with a bunch of properties, and my properties access my session, and my presentation layer accesses my static class properties.
 
However, I'm now working on a project where I have to use ObjectDataSource, and there seems to be no other way than to specify the literal string of my session key. I wish ObjectDataSource would let you specify a static object and property as SelectParameters.
 
Anyone have any better options?
AnswerRe: ObjectDataSource SelectParameters?memberDavid Hay18 Dec '06 - 14:28 
You can do this. Using parameters that are in session variables directly (using the SessionParameter class for your parameters) is only one option for providing parameters to ObjectDataSource. Other built in parameters sources are:
  • Another control (ControlParameter)
  • A cookie (CookieParameter)
  • A form field (FormParameter)
  • A query string value (QueryStringParameter)
  • Another control (ControlParameter)
 
These classes all extend the System.Web.UI.WebControls.Parameter base class. You can extend the base class yourself to provide any custom parameter type. Have a look at MSDN at http://msdn2.microsoft.com/en-us/library/system.web.ui.webcontrols.parameter.aspx[^]. There is an example there of creating a StaticParameter class that uses ViewState to store the value.
GeneralVery helpfulmemberAsween14 Dec '06 - 1:00 
Nice article David! It has helped me immensely to clear up my code.
 
Asween
QuestionPerformance issue ??membermarcin.rawicki14 Dec '06 - 0:27 
Don't you warry about to much calls to HttpContext. It's cost (a time and memory)!
 
marcin.rawicki
AnswerRe: Performance issue ??memberDavid Hay14 Dec '06 - 0:45 
There are no more calls to HttpContext.Current.Session than would normally be the case. When a developer just accesses the Session property on an ASP page they are simply accessing the same HttpContext.Current.Session object, just via a property on the current page. Accessing the HttpContext.Current.Session object via the new facade class is no additional overhead.
 
Regards
David
GeneralVery nice example of FacadememberAshish Basran13 Dec '06 - 5:47 

This is very nice example of Facade Pattern.
The kind of mistakes you talked about.. yes, we all do those silly things sometime..
 
It would be great if you can provide this kind of examples for other patterns
 
- ashish

GeneralGreat example of the facade patternmemberchristopherbarrow7 Dec '06 - 3:50 
Clear, precise and easy to understand and implement. Nice work!
 
Chris...;)

GeneralAnother approachmemberdapoussin7 Dec '06 - 0:23 
Thanks for this article, it allowed to put a name on a design pattern I've been using for a long time Smile | :)
But personally I prefer to use both a facade and direct session variables. As you explained, a facade is a life saver in code behind, but is a pain in markup when you reference ObjectDataSources parameters like this :

<asp:ObjectDataSource ID="odsUsers" runat="server" SelectMethod="GetUsersLST" TypeName="Users" CacheDuration="120" CacheKeyDependency="users" EnableCaching="True">
<SelectParameters>
<asp:SessionParameter Name="ClientID" SessionField="ClientID" Type="String" />
</SelectParameters>
</asp:ObjectDataSource>

 
Forgive me if I'm wrong but, if you want to use a facade, I think you have to set SelectParameters in code behind, and you loose all the ASP.NET benefites in markup Frown | :( (I like to use markup as much as possible)
 
I also wanted to say that I prefer to set my facade as a MasterPage property, because I can then interact with Response object and redirect user to login page if session state is invalid. For example :

public partial class MasterPage2 : System.Web.UI.MasterPage
{
public SessionData UserSessionData
{
get
{
SessionData data = new SessionData();
if (Session["UserSessionData"] != null)
{
try
{
data = (SessionData)Session["UserSessionData"];
}
catch
{
FormsAuthentication.RedirectToLoginPage();
Response.End();
}
}
else
{
FormsAuthentication.RedirectToLoginPage();
Response.End();
}
return data;
}
set
{
Session["UserSessionData"] = value;
}
}
...
}

 
To access UserSessionData directly in pages code behind, I then have to add the following line in the header of all my pages :
<%@ MasterType VirtualPath="~/MasterPage2.master" %>
 
And my facade is now accessible in code behind with :
Master.UserSessionData
 
Last point, I didn't test your code but it might throw NullReferenceExceptions if HttpContext.Current.Session[userAuthorisation] is null (not sure about that) Confused | :confused:
 
Cheers.
Laurent
GeneralRe: Another approachmemberDavid Hay7 Dec '06 - 11:51 
Thanks for the comments.
 
Using the caching capabilities of ObjectDataSource and using Session are two separate things. Use each where appropriate. But if you put things in Session, use a facade. I do not think what you have done is actually a facade.
 
The code does not throw NullReferenceExceptions. If you access Session with a string key that is not in the collection, null is returned, and casting null returns null. So no exceptions.
 
Some comments on the code in your master page:
 
1. Declaring the data variable as
    SessionData data = new SessionData();
should be just
    SessionData data;
It is a waste to create a new instance of the class here when you are never going to use it - you either replace it with a value from Session or redirect to the login page.
 
2. In fact, as a result of null being returned when you access Session with a key that is not in the collection, you can simplify your code dramatically to just:
 
public partial class MasterPage2 : System.Web.UI.MasterPage
{
    public SessionData UserSessionData
    {
        get
        {
            SessionData data = (SessionData)Session["UserSessionData"];
 
            if (data == null)
            {
                FormsAuthentication.RedirectToLoginPage();
                Response.End();
            }
 
            return data;
        }
 
        set
        {
            Session["UserSessionData"] = value;
        }
    }
    ...
}
 
3. What you have is not actually a facade to the HttpSessionState class, but implemented a single class (SessionData) to hold all session state information, which is then stored in Session. The problem with your approach is that you only expose access to it through the UserSessionData property of the master page. If you use nested master pages, you have to keep passing the property back through each level of master page. What about access to it in code in other places in your application that does not know a specific page? This all complicates access to the SessionData instance. If you want to implement your session data in this way, you should consider using the Singleton design pattern for your SessionData class. This would provide a much better implementation.

4. If you want to detect new sessions, instead of detecting that a value stored in Session is null, use the IsNewSession property of the HttpSessionState class. This property is provided for just this purpose.
 
Regards
David

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130516.1 | Last Updated 6 Nov 2012
Article Copyright 2006 by David Hay
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid