HomeASP.NET Application and Session Objects in ASP.NET
Application and Session Objects in ASP.NET
Sessions serve as a way to transport and maintain user data in web pages, such as forums, or e-commerce websites. In this article, Aayish takes us on a quick tour of both session and application objects, and gives us practical examples as to their uses.
Contributed by Aayush Puri Rating: / 124 March 01, 2004
A session is the time for which a particular user interacts with a web application. During a session the unique identity of the user is maintained internally. A session ends if there is a session timeout or if you end the visitor session in code.
What’s the use of sessions?
Sessions helps to preserve data across successive accesses. These can be done on a per user basis, via the use of session objects. Session objects give us the power to preserve user preferences and other user information when browsing a web application. To better understand the use of sessions, consider an example: Suppose you own a website in which you give the visitors the option to choose the background color of the pages they will browse. In such a case you need to remember the user’s choice on each of the page. This task can be accomplished using sessions.
A more practical example is the case of an e-commerce website where the visitor browses through many pages and wants to keep track of the products ordered.
This assigns the values “Aayush Puri” and “Blue” to the session variables “username” and “color”, respectively. If I need to know the “username” or “color” in subsequent pages, I can use Session(“username”), Session(“color”).
Sessions in ASP.NET are identified using 32-bit long integers known as Session IDs. The ASP engine generates these session ID’s so that uniqueness is guaranteed.
Let’s now see how you can configure the session object depending on the requirements of your Web Application.
Session Type
What it does
Example
Session.Abandon
Abandons (cancels) the current session.
Session.Remove
Delete an item from the session-state collection.
Session(“username”) = “Aayush Puri” (Initialize a session variable)
Session.Remove(“username”) (Deletes the session variable “username”)
Session.RemoveAll
Deletes all session state items
Session.Timeout
Set the timeout (in minutes) for a session
Session.Timeout=30 (If a user does NOT request a page of the ASP.NET application within 30 minutes then the session expires.)
Session.SessionID
Get the session ID (read only property of a session) for the current session.
Session.IsNewSession
This is to check if the visitor’s session was created with the current request i.e. has the visitor just entered the site. The IsNewSession property is true within the first page of the ASP.NET application.
As we saw in the previous section, sessions help us preserve data on a per user basis. What if we want to initialize variables that are available in a session and that are the same for all users? This means that a change in the value of an application variable is reflected in the current sessions of all users. For example, we may like to fix variables like tax rate, discount rate, company name, etc., that will be specified once for all variables we can access in a session. This is where application variables come in. Heck, they can even be used to show legal notices at the bottom of every page!
Creating an application variable is similar to session variables.
Application
(“legal_notice”) = “No part of this article may be reproduced without prior permission”
There is a concern when changing the value of an application variable: at any particular instant, multiple sessions might be trying to change the value, although only one session can be allowed to change it. ASP.NET has an in built mutual exclusion for dealing with these types of problems.
Application.Lock – Locks the application variables
Application.Unlock – Unlocks the application variables
Once application variables are locked sessions that attempt to change them have to wait.
You might need to redirect the visitor to a particular page if some error has occurred. On the redirected page, you’ll need to display the error message. A session variable initialized to an error message fits the bill. Here’s an example: Suppose you are writing a function check_string() (as a part of page named page1.aspx) which accepts no other string than “ASP.NET Rocks!” If the string passed as an argument does not match, then you need to redirect to a page (“page2.aspx”) and display the error.
Page1.aspx:
Public Sub check_string
(ByVal str As String) If Not Str.equals("ASP.NET Rocks") Then Session("error_message") = "The string was NOT ""ASP.NET Rocks"" " Response.Redirect("page2.aspx") End If End Sub
Page2.aspxThis next fucntion will display the error message.
Private Sub Page_Load
(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load If Session("message") <> "" Then Response.Write(Session("message")) Session.Remove("message") 'Make the session variable null End If End Sub
I include this piece of code in the function “Page_load” to check for any error message on every visit to this page.
Here’s a personal example of having to use sessions: I had to design a website which had three types of users, all requiring authorization. All users were divided into three categories, and each category had a well defined set of rules and permissions.
While writing server-side scripts, I had to ensure that a particular script run only for qualified users. The information in the database showed which user belonged to which category. Querying the database was too cumbersome, so a simple and elegant solution was to use session variables.
At the time of authorization I queried the category of the user and stored the result in a session variable.
At the time of authorization also fetch the category type Session
(“category”) = Get_category(username)
And that’s it--small, quick, and to the point. Would that all were as simple as sessions… but that’s neither here nor there. Enjoy!