in

code for eternity !!!

community website for .net freaks ;-)

Technology

Handling ASP.NET Session Variables Efficiently

One of the most common mistakes ASP.NET developers make is while accessing session variables. Have a look at the code below:

C#:

    // Writing to session variable
    Session["UserCountry"] = ddlUserCountry.SelectedValue;
       
    // Reading from session variable
    string userCountry = Session["UserCountry"].ToString();

VB:

    ' Writing to session variable
    Session("UserCountry") = ddlUserCountry.SelectedValue

    ' Reading from session variable
    Dim userCountry As String = Session("UserCountry").ToString()

I have seen such code across multiple aspx and ascx code behind pages and it is a disaster waiting to happen and has many drawbacks as follows:

1) If a session variable is read before it has been assigned or if the current session times out, it will result in NullReferenceException as no null checking happens before reading from session variable.

2) A simple spelling mistake of the key name used to identify the session variable ("UserCountry" in above example) will result in NullReferenceException (if no null checking is being done) or incorrect data (if null checking is being done).

3) In large ASP.NET projects where many developers are coding at the same time, very often two developers end up using the same key names for two different session variables meant for two different purposes. I have seen developers use the wildest key names for session variables like "Name" which is so common, it can be used by one developer to save the user's first name, and by another developer to save the user's user name. When such a situation arises, one of the session variable's key name would have to be changed across multiple aspx and ascx code behind pages, making sure that the other session variable sharing the same key name but meant for a different purpose is not changed by accident. This will result in complete chaos, and debugging and testing for such changes becomes a nightmare.

4) There is no easy way to track the usage of session variables, their key names, their data types, the approximate memory being used per session, etc.

However, with just a few extra lines of code and effort, we can get rid of above problems. To address above problems, we can create a single static / shared class (lets call it SessionHandler) which exposes all session variables through strongly typed static / shared properties. No aspx and ascx code behind pages should ever access session variables directly but instead access the strogly typed static / shared properties of the SessionHandler class. All the code to access session variables should exist ONLY in the SessionHandler class. Also, the SessionHandler class should use string variables to save key names of different session variables it exposes in order to avoid spelling mistakes. Have a look at the code below:

C#:

    // Static / shared class for handling session variables
    public static class SessionHandler
    {
    
        // Declare a string variable to hold the key name of the session variable
        // and use this string variable instead of typing the key name
        // in order to avoid spelling mistakes
        private static string _userCountryKey = "UserCountry";
       
        // Declare a static / shared strongly typed property to expose session variable
        public static string UserCountry
        {
       
            get
            {
           
                // Check for null first
                if (HttpContext.Current.Session[SessionHandler._userCountryKey] == null)
                {
                    // Return an empty string if session variable is null
                    return string.Empty;
                }
                else
                {
                    return HttpContext.Current.Session[SessionHandler._userCountryKey].ToString();
                }

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

        }

    }

VB:

    ' Static / shared class for handling session variables
    Public Class SessionHandler

        ' Declare a string variable to hold the key name of the session variable
        ' and use this string variable instead of typing the key name
        ' in order to avoid spelling mistakes
        Private Shared _userCountryKey As String = "UserCountry"

        ' Declare a static / shared strongly typed property to expose session variable
        Public Shared Property UserCountry() As String

            Get

                ' Check for null first
                If (HttpContext.Current.Session(SessionHandler._userCountryKey) Is Nothing) Then
                    ' Return an empty string if session variable is null
                    Return String.Empty
                Else
                    Return HttpContext.Current.Session(SessionHandler._userCountryKey).ToString()
                End If

            End Get

            Set(ByVal value As String)
                HttpContext.Current.Session(SessionHandler._userCountryKey) = value
            End Set

        End Property

    End Class

Once we have the SessionHandler class in place, all aspx and ascx code behind pages can access session variables through this class like below. Notice that we dont access session variables directly anymore and let the SessionHandler class do all the required work to access session variables.

C#:

    // Writing to session variable
    SessionHandler.UserCountry = ddlCountry.SelectedValue;
       
    // Reading from session variable
    string userCountry = SessionHandler.UserCountry;

VB:

    ' Writing to session variable
    SessionHandler.UserCountry = ddlUserCountry.SelectedValue

    ' Reading from session variable
    Dim userCountry As String = SessionHandler.UserCountry

Now since all the code to access session variables exists in one single class, it becomes really easy to track their usage, their key names, their data types, the approximate memory being used per session, etc. Also notice how easy it would be to change the key name of a session variable if required. All you would have to do is change the value of one private static / shared variable ("_userCountryKey" in above example). Also, we can be 100% sure that we are not using duplicate key names for multiple session variables by simply checking the value of all existing private static / shared string variables being used to save key names by the SessionHandler class.

Note: We can use the same above architecture (with slight changes to code) to access data from ASP.NET Cache as well as Application Settings. I will blog about it in a future post.

Cheers,
Raj

~~~ CODING FOR ETERNITY !!! ~~~


I would really appreciate votes / kicks for this blog post if you found it useful ;-)

  kick it on DotNetKicks.com     Receive Email Updates


Comments

 

Ahmed said:

Thanks it's a good idea now I'm trying it,and if there are any comments i'll report it to you

Admed

SofteWare Developer

ama8382@yahoo.com

January 19, 2008 3:52 AM
 

Neeraj said:

Excellent way method to handle Session Variables.

January 28, 2008 3:13 AM
 

Sara said:

I was able to implement your suggestion however I do have a question, it worked for me intially but now the variable is null again.  Any other suggestion.

February 3, 2008 10:54 AM
 

ASP@PRO said:

The static variables have the application scope in  asp.ne, right?.Then definitly there  will be problems in using these static variables instead of session variables??????

February 6, 2008 2:05 AM
 

raj said:

Hi Sara,

Apologies for the delayed response. I was on vacation and hence the delay in responding back.

I guess there is something wrong with your code. Once you assign a value to a session variable and access the same before session timeout happens (20 minutes by default in ASP.NET), there is no way it can return null (Unless you explicitly assign it to null again ofcourse).

You can email me your code if you want and I can have a look at it to see for possible bugs with the same.

Cheers,
Raj

~~~ CODING FOR ETERNITY !!! ~~~

February 6, 2008 8:00 AM
 

raj said:

Hi ASP@PRO,

Yes, static variables do have application scope. However there wont be any problems accessing session variables through static properties (and not variables as you typed above) because:

1) If you have a look at the code example in above post, although we use static properties, it is actually making use of session variables in the get and set, and sessions are per user basis, not per application basis.

2) .NET Framework guarantees about thread safety while using static classes and its members.

Try the above code example with different browser windows for multiple sessions to actually see the above code work without any issues. Good question though :-) I was actually wondering why people havent raised this question yet :-)

Cheers,
Raj

~~~ CODING FOR ETERNITY !!! ~~~

February 6, 2008 8:08 AM
 

Rajendra madahv said:

Excellent

February 13, 2008 5:20 AM
 

Jeffrey Allan said:

Excellent Post!  Helped me organize my session variables.  I do store a data table in session once and a while.  How would I handle that with this solution?  I have tried but with no luck.

February 15, 2008 7:42 AM
 

raj said:

Hi Jeffrey Allan,

Below code explains how you can access a DataTable object from ASP.NET sessions using above mentioned architecture. All you need to do is declare a private static / shared string variable to save the session key name for the DataTable object, declare a strongly typed static / shared property which is of type DataTable and return a DataTable instance by casting the session object into DataTable (if the session object is not null). Code as follows:

C#:

        private static string _dataTableKey = "DataTableKey";
       
        public static DataTable DataTableObject
        {
            get
            {
                if (HttpContext.Current.Session[SessionHandler._dataTableKey] == null)
                {
                    return null;
                }
                else
                {
                    return (DataTable) HttpContext.Current.Session[SessionHandler._dataTableKey];
                }
            }
            set
            {
                HttpContext.Current.Session[SessionHandler._dataTableKey] = value;
            }
        }

VB:

    Private Shared _dataTableKey As String = "DataTableKey"

    Public Shared Property DataTableObject() As DataTable
        Get
            If (HttpContext.Current.Session(SessionHandler._dataTableKey) Is Nothing) Then
                Return Nothing
            Else
                Return CType(HttpContext.Current.Session(SessionHandler._dataTableKey), DataTable)
            End If
        End Get
        Set(ByVal value As DataTable)
            HttpContext.Current.Session(SessionHandler._dataTableKey) = value
        End Set
    End Property

Cheers,
Raj

~~~ CODING FOR ETERNITY !!! ~~~

February 15, 2008 12:07 PM
 

DotNetKicks.com said:

You've been kicked (a good thing) - Trackback from DotNetKicks.com

February 16, 2008 7:34 AM
 

Chad Green said:

I just wanted to compliment you on your post.  I've been using the technique for quite some time and have been surprised that so many didn't think of it also.  But what I really liked about your blog is that the examples are in both VB and C#.  Keep up the good work.

February 16, 2008 7:48 PM
 

Bart Czernicki said:

Raj,

"2) .NET Framework guarantees about thread safety while using static classes and its members."

That is a BIG misconception.  Check this article out on static members and thread-safety:

odetocode.com/.../314.aspx

Secondly,  hopefully people start transitioning into the newer syntaxes.  I know if/else statements and curly brackets are "cool"...but you can save some lines of code in ur getter with one line of code:

return (HttpContext.Current.Session["SessionHandler._dataTableKey"] ?? null) as DataTable;

February 17, 2008 1:45 AM
 

raj said:

Hey Guys,

Thanks for all your encouraging feedback and appreciation.

Cheers,
Raj

~~~ CODING FOR ETERNITY !!! ~~~

February 17, 2008 1:49 AM
 

raj said:

Hi Bart,

Best feedback I ever got on CodeForEternity.com till date and thanks for the same :-)

The correct link to the excellent post by K. Scott Allen on thread safety for static / shared classes and their members is http://odetocode.com/Articles/314.aspx. I would update my above comment for ASP@PRO to clearly tell the difference regading thread safety between static / shared methods and static / shared variables (fields). However, as I pointed out before, code in the above post would execute without any problems because it is actually making use of session variables and not static / shared variables to save session data.

Regarding switching over to newer syntaxes like ??, the only reason I have not used it in my above post is majority of the developers do null checking using the old if / else way and would not even be aware of the ?? opertor and might get confused with the ?? operator. My intention was to make my code really simple to understand and follow. However, its worth including an update in the above post with an example using the ?? operator.

Once again, thanks for your excellent feedback. Do you blog on .NET? If yes, please let me know your blog url. I would be very interested in reading what you write on .NET ;-)

Cheers,
Raj

~~~ CODING FOR ETERNITY !!! ~~~

February 17, 2008 5:13 AM
 

Matthew Weaver said:

I have set up the sessionhandler as outlined and find it seems to reset or clear inconsistently when navigating from page to page.  I have not changed any web.config defaults and do not have anything set that I am aware of to clear session variables.  I am using ASP.Net with net 3 or 3.5 installed.  Programming is typically in VB using VS2005.  Here is my code:

sessionhandler.vb:

Imports Microsoft.VisualBasic

'Static / shared class for handling session variables

Public Class SessionHandler

   Private Shared _userIDKey As String = "UserID"

   ' Declare a static / shared strongly typed property to expose session variable

   Public Shared Property UserID() As String

       Get

           ' Check for null first

           If (HttpContext.Current.Session(SessionHandler._userIDKey) Is Nothing) Then

               ' Return an empty string if session variable is null

               Return String.Empty

           Else

               Return HttpContext.Current.Session(SessionHandler._userIDKey).ToString()

           End If

       End Get

       Set(ByVal value As String)

           HttpContext.Current.Session(SessionHandler._userIDKey) = value

       End Set

   End Property

   ' Declare a string variable to hold the key name of the session variable

   ' and use this string variable instead of typing the key name

   ' in order to avoid spelling mistakes

   Private Shared _userClassKey As String = "UserClass"

   ' Declare a static / shared strongly typed property to expose session variable

   Public Shared Property UserClass() As String

       Get

           ' Check for null first

           If (HttpContext.Current.Session(SessionHandler._userClassKey) Is Nothing) Then

               ' Return an empty string if session variable is null

               Return String.Empty

           Else

               Return HttpContext.Current.Session(SessionHandler._userClassKey).ToString()

           End If

       End Get

       Set(ByVal value As String)

           HttpContext.Current.Session(SessionHandler._userClassKey) = value

       End Set

   End Property

[and several others not included here in this example]

End Class

I have an initial include page called that sets the default public values, e.g. userclass.  Then, in a separate page, when someone logs in they are assigned their userid and userclass.  This appears fine initially but within a few (appears to be any) page views the session is cleared or reset.  When a new page is called (all on same domain) it is via the full HTTP address or simply by file name  Using IE7 with normal settings and also Firefox.  I am not seeing a pattern to the lost sessions, except their frequency.

Thanks,

Matthew

Matthew

February 27, 2008 4:23 PM
 

raj said:

Hi Matthew,

Apologies for the delayed response. I dont see anything wrong with your code. I think your sessions might be getting timed out? I will email you the source code for the test website which uses the above architecture shortly and I hope that would solve your problem.

Cheers,
Raj

~~~ CODING FOR ETERNITY !!! ~~~

March 3, 2008 4:45 AM
 

Marty America said:

Excellent post! It is like strongly typed datasets for sessions.

March 8, 2008 7:29 AM
 

Jack Lucky said:

raj,

Thanks for the info. I'm just getting started with asp.net after dabbling in VB. I have one question: if the session variable has not yet been instantiated with Session.Add("VariableName","stringValue"), will assigning a variable via SessionHandler.VariableName = "stringValue" return an error? If so, would it be good to put a conditional statement like:

Set(ByVal value As String)

   ' Check for null first

   If (HttpContext.Current.Session(SessionHandler._userCountryKey) Is Nothing) Then

       'Create session variable and assign value

HttpContext.Current.Session.Add(SessionHandler._userCountryKey,value)

   Else

       HttpContext.Current.Session(SessionHandler._userCountryKey) = value

   End If

End Set

Let me know if I'm completely off base or creating needless code.

Thanks,

Jack

March 21, 2008 5:35 AM
 

kmenezes said:

Great post, but having a problem implementing this.

I have multiple session variables I am tracking for multiple fields on my aspx page. Somehow, when the text property is assigned to the sessionahandler variable, the same value gets stamped in all variables...

Attached is an example of my code. What am I doing wrong?

Thank you very much

aspx

Protected Sub txtJobNumber_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtJobNumber.TextChanged

           SessionHandler.JobNumber = txtJobNumber.Text

   End Sub

   Protected Sub txtFeature_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtFeature.TextChanged

       SessionHandler.Feature = txtFeature.Text

   End Sub

sessionhandler.vb

Private Shared _jobnumber As String = String.Empty

   Private Shared _feature As String = String.Empty

Public Shared Property JobNumber() As String

       Get

           If (HttpContext.Current.Session(SessionHandler._jobnumber) Is Nothing) Then

               Return String.Empty

           Else

               Return HttpContext.Current.Session(SessionHandler._jobnumber).ToString()

           End If

       End Get

       Set(ByVal value As String)

           HttpContext.Current.Session(SessionHandler._jobnumber) = value

       End Set

   End Property

   Public Shared Property Feature() As String

       Get

           If (HttpContext.Current.Session(SessionHandler._feature) Is Nothing) Then

               Return String.Empty

           Else

               Return HttpContext.Current.Session(SessionHandler._feature).ToString()

           End If

       End Get

       Set(ByVal value As String)

           HttpContext.Current.Session(SessionHandler._feature) = value

       End Set

   End Property

March 24, 2008 1:54 PM
 

kmenezes said:

I solved my problem. Thanks if you did try to figure it out. The problem was I was initializing my keys to string.empty, instead of giving them a value...

March 24, 2008 4:36 PM
 

raj said:

Hi kmenezes,

Yes, the problem indeed was because you were using the same keys (string.empty) multiple times. Glad you found this post useful.

Cheers,
Raj

~~~ CODING FOR ETERNITY !!! ~~~

March 25, 2008 2:11 AM
 

Pete O'Hanlon said:

This is an interesting post, but there is a mistake in the code. You do this:

get

{

 // Check for null first

 if (HttpContext.Current.Session[SessionHandler._userCountryKey] == null)

 {

   // Return an empty string if session variable is null

   return string.Empty;

 }

 else

 {

   return HttpContext.Current.Session[SessionHandler._userCountryKey].ToString();

 }

}

When you could actually do this:

get

{

 object check = HttpContext.Current.Session[SessionHandler._userCountryKey];

 // Check for null first

 if (check == null)

 {

   // Return an empty string if session variable is null

   return string.Empty;

 }

 else

 {

   return check.ToString();

 }

}

In your example, there is the possibility (slight but it does exist and I have been hit by this nasty) that between you looking at the session variable and then returning it, the session times out.

For a more complex type, you may want to use the as keyword, e.g.

MyClass check = HttpContext.Current.Session[SessionHandler._userCountryKey] as MyClass;

March 26, 2008 4:42 AM
 

raj said:

Hi Pete O'Hanlon,

You talk like a real geek :-) Great observation indeed. I would update this post accordingly pointing out to few of the great comments this post has received so far.

Cheers,
Raj

~~~ CODING FOR ETERNITY !!! ~~~

March 26, 2008 5:30 AM
 

Pete O'Hanlon said:

Raj

No problem. I am indeed a geek and proud of it;->. I will be pointing people to this article from here on in.

March 27, 2008 8:29 AM
 

taheer72 said:

hi raj

a great lines of code, but I have one doubt

generally casting is done using Session variables

like

dtCustomerDetails = (DataTable)Session["CustomerDetails"]

thankx in advance

how this can be achived using the SessionHandler mentioned above

March 27, 2008 11:19 PM
 

raj said:

Hi Jack Lucky,

Apologies for the delay. Please note that you do not need to have any of those null checking codes while trying to SET a value using the SessionHandler class. It WONT result in an error.

Cheers,
Raj

~~~ CODING FOR ETERNITY !!! ~~~

March 28, 2008 6:07 AM
 

raj said:

Hi taheer72,

Can you please refer to my reply to Jeffrey Allan's comment (9th comment from top) where I have explained how to return a DataTable object using the SessionHandler class. My reply clearly explains how to handle casting using SessionHandler class. Hope this helps.

Cheers,
Raj

~~~ CODING FOR ETERNITY !!! ~~~

March 28, 2008 6:13 AM
 

DenverMike said:

Hi Raj,

Thanks for a great article!  What are your thoughts about extending your solution so you can also remove session variables (ie using the Session.Remove method)?

I suppose you could make the Key values public so you could, in turn, pass them into a Session.Remove, but there's probably a better way.

Curious to know your thoughts on that!

April 3, 2008 1:27 PM
 

raj said:

Hi DenverMike,

For Session.Remove, I would have a public static / shared method like Remove[PropertyName]. So if we wanted to add a remove method for UserCountry property in the above code example, we could add the following static / shared method to our SessionHandler class:

C#:

   public static void RemoveUserCountry()
   {
       HttpContext.Current.Session.Remove(SessionHandler._userCountryKey);
   }

VB:

   Public Shared Sub RemoveUserCountry()
       HttpContext.Current.Session.Remove(SessionHandler._userCountryKey)
   End Sub

Hope this helps.

Cheers,
Raj

~~~ CODING FOR ETERNITY !!! ~~~

April 5, 2008 2:48 AM
 

DenverMike said:

Gee, Raj, that was easier than I though it would be. Thanks very much!

April 5, 2008 11:13 PM
 

Sobin said:

Good job Raj! Very useful for a beginner like me...

Its  the best way to handle session variables i think...

April 16, 2008 4:32 AM
 

Yaris said:

Sorry i am new for ASP.Net. What should we have to use for long data type to return if null. like for following:

public static long CustomerID

       {

           get

           {                

               //get session variable

               object customerID = HttpContext.Current.Session[SessionHandler._customerID];

               //check for null first

               if (customerID == null)

               {

                   // Return an empty string if session variable is null

                   return  null ????

               }

               else

               {

                   return (long)customerID ;  

               }

           }

           set

           {

               //set session variable

               HttpContext.Current.Session[SessionHandler._customerID] = value;

           }

       }

April 28, 2008 8:03 AM
 

raj said:

Hi Yaris,

You can either return null or return the default value for that type. So for long, you can either return null else return 0. I personally prefer returning 0 for long data types.

Cheers,
Raj

~~~ CODING FOR ETERNITY !!! ~~~

April 28, 2008 8:42 AM
 

Yaris said:

Thanks Raj, but for long type return null gives error.

April 28, 2008 10:02 AM
 

miky said:

raj, thanks for the post.  are there any security concerns here making this class public/static?  does this expose the session values to objects that might come along side?

May 5, 2008 11:54 AM
 

Lars Corneliussen said:

May 19, 2008 1:11 AM
 

Wok said:

Hi Raj,

I found this post, think it is great and I am going to change my whole page to use your suggestion. I have a problem related to session variables and thought you might be able to help. I currently use the session variables like in your example above: Session["UserCountry"] = ddlUserCountry.SelectedValue;

   // Reading from session variable

   string userCountry = Session["UserCountry"].ToString();

My problem is that if I log on as user1 (User_ID = 1), set some variables whos values are stored in session variables, then log off and log on as user2 (User_ID = 2) I get the values for the session variables that where set for user1 and if I click F5 it will reset to correct values for user2. One example of a session variable is User_ID. So when I log in, it shows the correct username, User2 (I get the username based on the User_ID) and when I go to the search page, for example, the username has changed to User1 and if I hit F5 it will change to User2. It looks to me like it is using the previous session variable value.

The stangest part is that is not consistent and only seems to happen on two specific PC's (so far)

When I log off I do do a Session.Remove("VariableName") for each session variable and a session.Abandon() but that does not seem to help.

If anyone has any suggestions I would love to hear them because I have search ed for this problem with no solution,

thanks a million

June 4, 2008 8:14 AM
 

raj said:

Hi Wok,

Are you using the same browser window for testing this? If yes, that is your problem. Try opening different browser windows for different users, I bet you wont get this error if your code is alright. (Thats because by default, a new browser window creates a new session)

If you are really using the same browser window, the moment you log out as user1 and log in as user2, and hit some url which has been accessed before, your browser is fetching that data from local browser cache (thats why when you do F5, you see the correct values as the browser hits your asp.net server to get fresh content).

In real world scanerio, you wont face this problem as no 2 users would use the same browser window to access your asp.net site

Cheers,
Raj

~~~ CODING FOR ETERNITY !!! ~~~

June 5, 2008 7:59 AM
 

Wok said:

Hi Raj,

Thanks for the quick reply. After enabling tracing and some more testing I found that it is actually a setting in Internet Explorer. If you go to Tools->Internet Options.. and on the general tab click on the settings button you will see some optoins for "Check for new versions of stored pages" and the two Pc's that were giving the problem were set to "never" instead of "Automatic" so it would always use the page in cache which is why it gave the wrong info and if you hit F5 it got the correct data because it forced the page to be reloaded from the server.

I am not sure if it is possible to find out through code if this setting is enabled, I highly doubt it but I will let you know if I find anything.

I hope this can help anyone out there if they have the same issue.

Thanks again for your feedback

June 5, 2008 9:56 AM
 

Annie said:

Hey Raj, Good work on the code. I have one question though. Where are you placing the SessionHandler class code? and also I am using 3 dropdowns and I need to capture the selected value of each ddl and send them to a link to display a chart...any ideas on how to do that?

Thanks

June 10, 2008 7:29 AM
 

Annie said:

Raj, this is what I did....can you tell me how to bind the session variables to the chart so that the chart loads dynamically from the sql database.

Public Class SessionHandler

   Private Shared _perkey As String = "Period"

   Private Shared _fackey As String = "Period"

   Private Shared _provkey As String = "Period"

   Public Shared Property Period() As String

       Get

           If (HttpContext.Current.Session(SessionHandler._perkey) Is Nothing) Then

               Return String.Empty

           Else

               Return HttpContext.Current.Session(SessionHandler._perkey).ToString()

               Return HttpContext.Current.Session(SessionHandler._fackey).ToString()

               Return HttpContext.Current.Session(SessionHandler._provkey).ToString()

           End If

       End Get

       Set(ByVal value As String)

           HttpContext.Current.Session(SessionHandler._perkey) = value

           HttpContext.Current.Session(SessionHandler._fackey) = value

           HttpContext.Current.Session(SessionHandler._provkey) = value

       End Set

   End Property

End Class

Protected Sub patients_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles patients.Click

       SessionHandler.Period = ddlPeriod.SelectedValue

       Dim periodvalue As String = SessionHandler.Period

       MsgBox("My value is:" & periodvalue)

       SessionHandler.Period = ddlfacility.SelectedValue

       Dim facvalue As String = SessionHandler.Period

       MsgBox("My value is:" & facvalue)

       SessionHandler.Period = ddlprovider.SelectedValue

       Dim provvalue As String = SessionHandler.Period

       MsgBox("My value is:" & provvalue)

       Me.ChartGenre.Visible = True

       Me.ChartGenre.Data.DataSource = GetColumnData()

       Me.ChartGenre.Data.DataBind()

   End Sub

June 10, 2008 8:09 AM
 

raj said:

Hi Annie,

I use the SessionHandler class inside the App_Code folder for ASP.NET 2.0 applications.

I guess you need to define 3 different string properties to save three different string values instead of just 1 (which you are currently doing). Your current code appears to be wrong.

Cheers,
Raj

~~~ CODING FOR ETERNITY !!! ~~~

June 11, 2008 7:53 AM
 

Annie said:

Thanks Raj,

I am using ASP.NET 3. I am new at this, so can you point out where am I going wrong please?

Thanks

June 11, 2008 9:50 AM
 

Pete said:

Annie I see you want multiple session handlers I have done an example string and then int below, you don't put them all in the same get and set propery.

public static class SessionHandler

   {

       private static string _userCountryKey = "UserCountry";

       public static string UserCountry

       {

           get

           {

               if (HttpContext.Current.Session[SessionHandler._userCountryKey] == null)

               {

                   return string.Empty;

               }

               else

               {

                   return HttpContext.Current.Session[SessionHandler._userCountryKey].ToString();

               }

           }

           set

           {

               HttpContext.Current.Session[SessionHandler._userCountryKey] = value;

           }

       }

private static string _userCountryKey = "UserID";

       public static int UserID

       {

           get

           {

               if (HttpContext.Current.Session[SessionHandler._userCountryKey] == null)

               {

                   return 0;

               }

               else

               {

                   return int.Parse(HttpContext.Current.Session[SessionHandler._userCountryKey]);

               }

           }

           set

           {

               HttpContext.Current.Session[SessionHandler._userCountryKey] = value.ToString();

           }

       }

   }

June 12, 2008 11:59 AM
 

Pete said:

forgot then to get the variables it is:

SessionHandler.UserCountry

SessionHandler.UserID

June 12, 2008 12:00 PM
 

Pankaj said:

Hi Raj

I was reading through your post and i also want to implement this in my project as well.. but i had few doubts..so i hope you wont mind that.

1. Consider the following problem I m using ajax/update panel. when the page loads for the first time user enters some search criteria and click on search button. he will see the results accordingly in the grid. In the grid i have list of PO's which contains the hyperlinks to the other page which contains po details. When i navigate to PO details hyperlink and then click on BACK button from the browser. i dont see the data in grid . So in order to preserve the data i m storing all the search criteria in a session. besides this i m also creating a session variable name session["srchcriteria"] when the user loads the page for the first time if will be null but when the user click on search button session["srchcriteria"] will contain the value "Y" and addtionally i m declaring other session variables to store the search criteria. Now when the user navigate to PO details screen and come back it will gain check the srch_criteria flag if the search criteria is there in the session then execute the query using the search criteria. Now suppose user goes to some other page on that page as well i m checking if session["srchcriteria"]=="y" then take the search criteria from the session and execute the query.

Now according the your solution if i use the session["searchcriteria"] variable it will store the value "Y" each time the user navigates to some other page...

I hope you understood my problem..

Thanks

June 18, 2008 9:29 AM
 

Ted said:

Ok I was good until this statement

MyClass check = HttpContext.Current.Session[SessionHandler._userCountryKey] as MyClass;

object I understood but MyClass is what, the whole article is about Sessionhandler class

can you explan this ?

July 3, 2008 7:18 AM
 

Amby said:

Nice work Raj!

July 23, 2008 2:54 AM
 

Jim said:

I'm using ASP.NET 1.1.   I've tried the code above saving a DataTable.  When I have two instances of IE open for the same web page, the datatable from the second page that I've opened is then used in the first page.  I've checked "Tools> Internet Options> Settings", and "Newer Versions" is set to Automatic.  How do I prevent this from happening?

The class is coded as follows:

Public Class SessionHandler

   Private Shared _userDataTableKey As String = "DataTableKey"

   Public Shared Property MyDataTable() As DataTable

       Get

           If (HttpContext.Current.Session(SessionHandler._userDataTableKey) Is Nothing) Then

               Return Nothing

           Else

               Return CType(HttpContext.Current.Session(SessionHandler._userDataTableKey), DataTable)

           End If

       End Get

       Set(ByVal value As DataTable)

           HttpContext.Current.Session(SessionHandler._userDataTableKey) = value

       End Set

   End Property

End Class

The application globally defines the following:

   Private myDataTable As DataTable

The "Setting" command is

  SessionHandler.MyDataTable = myDataTable

The "Getting" command is:

  myDataTable = SessionHandler.MyDataTable

July 24, 2008 1:43 PM
 

Aries said:

Hey Raj!

I am an absolute beginer as far as .net is concerned.. I am trying to store a session attribute on page1 and retrieve it on pag2 , 3, 4 etc..

Let me show hoe i am doing it:

Page1.aspx

Session("s_name")="some name"

---------------------------------------------------------

page2.aspx

<script runat="server">

   Dim knam As String = CType(Session("nn"), String)

...

..

</script>

--------------------------------------------------------------------

And i get this error:

=======================================

Server Error in '/3' Application.

--------------------------------------------------------------------------------

Session state can only be used when enableSessionState is set to true, either in a configuration file or in the Page directive. Please also make sure that System.Web.SessionStateModule or a custom session state module is included in the <configuration>\<system.web>\<httpModules> section in the application configuration.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Web.HttpException: Session state can only be used when enableSessionState is set to true, either in a configuration file or in the Page directive. Please also make sure that System.Web.SessionStateModule or a custom session state module is included in the <configuration>\<system.web>\<httpModules> section in the application configuration.

=======================================

Please help me resolve this. I am really LOST bro!

Thanks

July 30, 2008 9:01 PM
 

Sreeraj N R said:

hai  Raj...

I have successfully implemented your session state management technique in my project.But I have a doubt  

If a large number of requests occurs simultaneously to access a session variable which is managed with the static  property  ,how it will be handled?? will it be resulted in a performance degradation???

October 11, 2008 4:52 AM
 

adarsh said:

can anyone temme how to use this for arraylist.. my proj s to pass a chunk of textbox values from one page to another display them in textboxes and make calculations in them and again display the results in other set of new textboxes..

October 28, 2008 5:40 PM
 

Cliff Chambers said:

I have an issue with this where it will not work during debugging. I get the error "Object reference not set to an instance of an object." when performing the 4th line in this:

   Private Shared _UserID As String = "UserID"

   Public Shared Property UserID() As String

       Get

           If (HttpContext.Current.Session(sessionHandler._UserID) Is Nothing) Then

               Return String.Empty

           Else

               Return HttpContext.Current.Session(sessionHandler._UserID).ToString()

           End If

       End Get

       Set(ByVal value As String)

           HttpContext.Current.Session(sessionHandler._UserID) = value

       End Set

   End Property

Like I said, it only happens in debug mode, with vs 2008 and asp.net 3.5. Anyone know why?

November 17, 2008 4:03 AM
 

Carl said:

Great stuff Raj. Thanks for this, very clear & concise and beautifully done.

December 29, 2008 1:11 PM
 

Rohit said:

is there a need to check for null and redirection to error

page in case a session is timed out

January 14, 2009 7:24 AM
 

eb said:

One nice use of a session variable is to have the variable available as a parameter to an object data source to pull data into a formview easily without codebehind using the asp:SessionParameter in the ODS such as:

<asp:SessionParameter Name="someFormID" SessionField="someFormID" Type="Int32" />

Is there still away to make use of the SessionHandler class variable in the object datasource behind the formview or do you have to resort to code behind?

January 29, 2009 2:46 PM
 

Wynand said:

Hi Raj, I am experiencing a session variable problem beyond my understanding and would really appreciate ANY input!

When a user logs into my system, I assign the user's primary key value to my session variable like this:

session("Logged_User_ID") = dsLogin.tables(0).rows(0).item("ID")

It works perfectly, BUT after redirecting around a bit throughout my application's ASPX pages, the session variable loses its value completely!! This is NOT because of a session expiry, it is NOT because of assigning a different value to the session variable, I ONLY read from it, and the mind-boggling things is the fact that it occurs RANDOMLY..or...it surely seems like it!! There's no way of knowing when it will occur. When it happens, it happens mostly when I response.redirect from one page to another.

Sometimes after refreshing the page, it actually picks up the session variable again ?!

My set up is as follows:

Im NOT using IIS on my development machine, I am using ASP.NET Development Server as built into Visual Studio 2008. However, I publish my application to a host, it obviously runs on IIS.

Could this be because of "Application Recycling" on the IIS server?

Thanking you in advance since I am so desperate as to consider storing my session variables in my database, thus exchanging my frustration for sloppy coding.

February 3, 2009 8:19 AM
 

Brent said:

Thanks for this post.  I created a test app and everything works.  I just new it had to be a better way  of storing sessions than using directly in the application.

February 19, 2009 9:58 AM
 

Matt Weber said:

Can you please tell me how to track memory usage per session as you mentioned in your article?  That is extremely interesting, but I cannot find information on this topic.  Thanks a ton!

March 12, 2009 9:55 PM
 

sterling said:

I tried to use you code above in my local server it works fine but when  I uploaded it in our testing server. my session variables is empty. Can you help me in this problem?

Thanks and Regards,

Rowell

May 5, 2009 9:23 PM
 

CP said:

This is exactly what I needed!!  Thank you so much!

May 22, 2009 9:30 AM

Leave a Comment

(required)  
(optional)
(required)  
Add
Powered by Community Server (Non-Commercial Edition), by Telligent Systems