Sessions and cookies can be used to persist visitor
information. In this article Himanshu shows us how to
main session state with ASP using a combination of cookies,
sessions and the global.asa file.Session and application
variables are an important part of ASP programming.
Whether it's developing simple hit counters or developing
advanced chat servers, session and application variables
are a must have feature of many applications.
In this article we are going to learn:
How session and application variables work
What the benefits are of using session and application
variables
Which events are available to both session and application
variables
How we implement session and application variables
The global.asa file and the standard events in global.asa
How to maintain a client state using cookies
To understand the concepts that I'm about to explain,
you will need the following:
A web server (IIS or PWS) capable of running ASP scripts
Basic knowledge of ASP
By the end of this article you will have a thorough
understanding of sessions, application variables and
cookies, and will be fully prepared to start using
them in your applications.
The session object is used to store variables for
each specific visitor to your web site. These variables
could represent anything from how many pages the user
has viewed to their login details. A session is defined
as the time from when the user visits your site to
the time when he leaves – session variables
die after a visitor closes their web browser (i.e.
they are not persistent).
Variables stored in the session object are available
to all ASP pages on that particular web site. Common
information stored in session variables includes name,
id, and personalization preferences. The server creates
a new session object for each new user and destroys
the session object when the session expires.
A session object is specific for every user and varies
from user to user. IIS will maintain these variables
when the client moves across pages within the site.
Syntax:
Session.collection|property|method
Properties:
SessionID: A long number that returns the session
identifier for this client.
Timeout: An integer that specifies a timeout period
in minutes. If the client doesn't refresh or request
any page from your site within this timeout period
then the server ends the current session. If you do
not specify any timeout period then the default timeout
period of 20 minutes is used.
Methods:
Abandon: Destroys the current session object and
releases its resources, meaning that if the client
requests any page from your site after the Session.Abandon
method has been called then a new session will be
started.
Session_OnEnd: This event occurs when the session
is abandoned or times out for a specific user.
Session_OnStart: Occurs when a new session is started.
All ASP objects are available for you to use. You
can define your session wide variables here.
Example:
You can store any value you like in the session object.
Information stored in the session object is available
for the entire session and has "session scope".
The following script demonstrates how two types of
variables are stored:
Session("username") = "Janine"
Session("age") = 42
The Application object is used to store variables
and to access variables from any page. All users share
one Application object.
All variables created within the application object
have application level scope, meaning that they are
accessible to all users who visit your site. All ASP
pages in a virtual directory and its subdirectories
come under the application scope, so more than one
user shares application level variables at any time.
Syntax:
Application.method
Methods:
Lock: Prevents other users from changing
the application objects properties
Unlock: Allows other users to change the application
objects properties
Events:
Application_OnEnd: This routine is called when all
user sessions expire and the application quits. This
event lives in the global.asa file, which we will
look at shortly.
Application_OnStart: This routine is called when the
application object is first references. This event
lives in the global.asa file as well.
Example:
This example uses an application variable to determine
the uptime of the server. To achieve this we simply
add an application variable to the OnStart event in
the global.asa file, which needs to exist in the root
directory of your web server:
<script language="VBScript"
runat="Server">
Sub Application_OnStart
Application("startTime") = Now
End Sub
</script>
The following VBScript will display the uptime:
<% @ language="vbscript" %>
<% Option Explicit %>
<%
Dim days, hours, minutes, seconds, startTime, runTime
' Read the start time from the
' Application variable
startTime = CDate(Application("startTime"))
' Take the difference
runTime = CDate(Now - startTime)
' Calculate the time components
If DateDiff("d", startTime, Now) = 0 Then
days = 0
Else
days = Day(runTime)
End If
hours = Hour(runTime)
minutes = Minute(runTime)
seconds = Second(runTime)
' Display the uptime
Response.Write "Uptime: " & days &
" days(s), "
Response.Write hours & " hour(s), "
Response.Write minutes & " minute(s), and
"
Response.Write seconds & " second(s)"
%>
The global.asa file is an optional file where you
can specify event scripts and declare session and
application objects that can be accessed by every
page in your ASP application, as we saw in the example
on the previous page.
Note: The global.asa file must be
stored in the root directory of the ASP application
and each application can only have one global.asa
file.
Standard Events in Global.asa
In the global.asa file you can tell the application
and session objects what to do when the application/session
starts and what to do when the application/session
ends. The code for this is placed into event handlers.
The global.asa file can contain four types of events:
Application_OnStart: This event occurs when the FIRST
user calls the first page from an ASP application.
This event also occurs after the web server is restarted
or after the global.asa file is edited. When this
procedure is complete, the "Session_OnStart"
procedure runs.
Session_OnStart: This event occurs EVERY time a user
visits your web site and requests the first page.
Session_OnEnd: This event occurs EVERY time a user
ends a session. A user ends a session after a page
has not been requested by the user for a specific
amount of time (this is 20 minutes by default).
Application_OnEnd: This event occurs after the LAST
user has ended the session. Typically, this event
occurs when a web server is stopped/restarted. This
procedure is used to clean up settings after the application
stops, such as deleting records or writing log information
to text files.
Example:
A global.asa file with empty event scripts
would look like this:
<script language=vbscript runat=server>
SUB Application_OnStart
END SUB
SUB Application_OnEnd
END SUB
SUB Session_OnStart
END SUB
SUB Session_OnEnd
END SUB
</script>
In this example we will create a global.asa
file that counts the number of current visitors:
The Application_OnStart sets the Application variable
visitors to 0 when the server starts
The Session_OnStart subroutine adds one to the variable
visitors every time a new visitor arrives
The Session_OnEnd subroutine subtracts one from visitors
each time this subroutine is triggered
The Global.asa file:
<script language="vbscript" runat="server">
Sub Application_OnStart
Application("visitors")=0
End Sub
Sub Session_OnStart
Application.Lock
Application("visitors")=Application("visitors")+1
Application.UnLock
End Sub
Sub Session_OnEnd
Application.Lock
Application("visitors")=Application("visitors")-1
Application.UnLock
End Sub
</script>
To display the number of current visitors
in an ASP file:
<html>
<head>
</head>
<body>
<p>
There are <%response.write(Application("visitors"))%>
online now!
</p>
</body>
</html>
Maintaining Client State With Cookies
If a visitor comes to your site and types his name
into a form then you might want to remember that information.
You may only want to remember it for his current visit
(session), or for all subsequent visits for personalization
( i.e. "Welcome back Mike"). The term state
describes all client browser data for the session.
ASP uses client browser side cookies to remember (or
persist) this data.
Cookies are small text files stored on the visitors
PC, usually in %root% \ Windows \ Temporary Internet
Files \ Cookie:
user_ name@Host_Name file. These text files are editable
with notepad or Microsoft Word. Two types of information
are stored in the cookie files:
Client Data: The variables that make up the cookie
for the visitor. These are stored as name/value pairs,
such as name=john.
Unique Cookie ID: This allows the ASP Session to identify
the client browser on a page to page and visit to
visit basis.
Example:
<%
Response.Cookies("myCookie")("myValue1")
= 1
%>
... and then to retrieve the value of the cookie:
<% =Request.Cookies("myCookie")("myValue1")
%>
In this article we've seen how to effectively use
the session and application objects, the global.asa
file, as well as cookies. Here's a quick list of tips
to recap what we've just learnt:
An application object is used to share information
among all the users of a specific web site.
The start and end of the application can be controlled
using the Application_OnStart and Application_OnEnd
events in the global.asa file.
A session object is used to store the information
needed for a particular user in a session. The variables
stored in a session object are not discarded when
the user switches between pages. These variables remain
valid for the entire session.
The start and end of the session can be controlled
using the Session_OnStart and Session_OnEnd events
in the global.asa file.
You can use the cookies collection of the response
object to store client state information. You can
use the request object to retrieve the client state
information from the cookies.