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
Rating: 4 stars4 stars4 stars4 stars4 stars / 124
March 01, 2004
Rate this Article:
MEH MEH++


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement

So what is a session?
 
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.

Our First Session

Sessions in ASP.NET are simply hash tables in the memory with a timeout specified. Consider the following examples


Session(“username”) = “Aayush Puri”
Session
(“color”) = “Blue”

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 TypeWhat it doesExample
Session.AbandonAbandons (cancels) the current session. 
Session.RemoveDelete an item from the session-state collection.

Session(“username”) = “Aayush Puri”
(
Initialize a session variable)

Session.Remove(“username”) 
(
Deletes the session variable “username”)

Session.RemoveAllDeletes all session state items 
Session.TimeoutSet the timeout (in minutes) for a sessionSession.Timeout=30 (If a user does NOT request a page of the ASP.NET application within 30 minutes then the session expires.)
Session.SessionIDGet the session ID (read only property of a session) for the current session. 
Session.IsNewSessionThis 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. 

Application Objects

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.

Practical Examples Showing the Use of Sessions

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.aspx  This next fucntion will display the error message.


Private Sub Page_Load(ByVal sender As System.ObjectByVal e As System.EventArgsHandles 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!

blog comments powered by Disqus
ASP.NET ARTICLES

- Implementing ASP.NET 4.0 Page.MetaDescriptio...
- ASP.Net Development Tips
- Intro to Sessions in ASP.Net
- Google Maps API Introduction in ASP.NET usin...
- Creating an ASP.NET 3.5 Gridview Image Galle...
- Encrypt QueryString in ASP.NET 3.5 using VB....
- ASP.NET 3.5 Drop Down List Controls
- Connect to Access Database with ASP.Net
- Secure Audio Streaming with ASP.Net and Flash
- Dynamic Sitemap and Navigation in ASP.Net
- Implement Gzip and Deflate Compression in AS...
- Run ASP.Net in Ubuntu with Apache
- ASP.Net Mono Website Contact Forms
- ASP.Net URL Rewriting Methods
- Murach`s ASP.NET 4 Web Programming with C# 2...

ASP Web Hosting ASP.Net Web Hosting Windows Web Hosting
 
 
 

ASP Free Forums 
 RSS  Tutorials RSS
 RSS  Forums RSS
 RSS  All Feeds
Site Map 
Request Media Kit
Write For Us Get Paid 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Privacy Policy 
Support 


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 1 - Follow our Sitemap
Most Popular Topics
All ASP.Net Tutorials