Session
Object (IIS)
You can use the Session object to store
information needed for a particular user session. Variables stored in the Session object are not
discarded when the user jumps between pages in the application; instead, these
variables persist for the entire user session.
The Web server
automatically creates a Session object when a
Web page from the application is requested by a user who does not already have
a session. The server destroys the Session object when
the session expires or is abandoned.
One common use for the Session object is to
store user preferences. For example, if a user indicates that they prefer not
to view graphics, you could store that information in the Session object. For
more information about using the Session object, see Managing Sessions in the
Active Server Pages & Web Application Guide section.
Note:
|
Session state is only
maintained for browsers that support cookies.
|
Methods
The Session object defines the
following methods.
Method
|
Description
|
|
This method destroys a
Session object and
releases its resources.
|
|
This method deletes an
item from the Contents collection.
|
|
This method deletes
all items from the Contents collection.
|
Abandon
The Abandon method destroys a user session.
Note: When this method is called, the current Session object is
not deleted until all of the script on the current page have been processed.
This means that it is possible to access session variables on the same page as
the call to Abandon, but not from another Web page.
Syntax
Examples
File1.asp:
<%
Session("name")="abcd"
Session.Abandon
Response.Write(Session("name"))
%>
Output:
abcd
|
File2.asp:
<%
Response.Write(Session("name"))
%>
Output:
(none)
|
The Session object defines the
following properties.
Property
|
Description
|
|
Returns the session
identification for this user.
|
|
Contains the objects
created by using the <OBJECT> tag and given session scope.
|
|
The time-out period
for the session state for this application, in minutes.
|
Events
The Session object defines the following events.
Event
|
Description
|
|
Occurs when a session
is abandoned or times out.
|
|
Occurs when the server
creates a session.
|
<%
Session("username") =
"Janine"
Session("age") = 24
%>
However, if you store an
object in the Session object and use
VBScript as your primary scripting language, you must use the Set keyword, as illustrated
in the following script.
VBScript
<% Set Session("Obj1") =
Server.CreateObject("MyComponent.class1") %>
You can then use the
methods and properties exposed by MyComponent.class1 on subsequent Web pages, by using the
following:
VBScript
<% Session("StoredArray")(3) =
"new value" %>
The preceding script
does not work because the Session object is
implemented as a collection. The array element StoredArray(3) does not receive the new value. Instead, the
value is indexed into the collection, overwriting any information stored at
that location.
It is strongly
recommended that if you store an array in the Session object, you
retrieve a copy of the array before retrieving or changing any of the elements
of the array. When you are finished using the array, you should store the array
in the Session object again,
so that any changes you made are saved, as demonstrated in the following
example:
VBScript
<%
'Creating and initializing the array
Dim MyArray()
Redim MyArray(5)
MyArray(0) = "hello"
MyArray(1) = "some other string"
'Storing the array in the Session object.
Session("StoredArray") = MyArray
Response.Redirect("file2.asp")
%>
--- File2.asp ---
<%
'Retrieving the array from the Session Object
'and modifying its second element.
LocalArray = Session("StoredArray")
LocalArray(1) = " there"
'Printing out the string "hello
there."
Response.Write(LocalArray(0)&LocalArray(1))
'Re-storing the array in the Session object.
'This overwrites the values in StoredArray with
the new values.
Session("StoredArray") = LocalArray
%>
Example Code
The following code assigns the string "MyName" to a
session variable named name, assigns a value to a session variable named year, and assigns an
instance of the some.Obj component to a variable named myObj:
VBScript
<%
Session("name") =
"MyName"
Session("year") = 96
Set Session("myObj") =
Server.CreateObject("someObj")
%>
Session_OnStart
Event
<SCRIPT LANGUAGE=ScriptLanguage
RUNAT=Server>
Sub Session_OnStart
. . .
End Sub
</SCRIPT>
Parameters
ScriptLanguage
Specifies the scripting language used to write
the event script. It can be any supported scripting language, such as VBScript
or JScript. If more than one event uses the same scripting language, they can
be combined under a single set of <SCRIPT> tags.
Remarks
You should note that any
Session_OnStart event
script that follows a call to the Response.Redirect
method is not executed. For this reason, you should call the Redirect method last
in your event script, as shown in the following example.
Example Code
You can call the Response.Redirect
method in the Session_OnStart event,
for example, to ensure that users always start a session at a particular Web
page. When the user initially opens the application, the server creates a
session for that user and processes the Session_OnStart event
script. You can include script in this event to check whether the page opened by
the user is the starting page and, if not, direct the user to the starting page
by calling the Response.Redirect
method, as shown in the following example.
Note:
|
This example only works
for browsers that support cookies. Because a browser that does not support
cookies does not return the SessionID cookie,
the server creates a new session each time the user requests a page. Thus,
for each request, the server processes the Session_OnStart
script and redirects the user to the starting page. If you use the following
script, it is recommended that you put a notice on your starting page to
inform users that the site requires a browser that is enabled to use cookies.
|
<SCRIPT RUNAT=Server Language=VBScript>
Sub Session_OnStart
'Make
sure that new users start on the correct
'page of
the ASP application.
'Replace
the value given to startPage below
'with
the virtual path to your application's
'start
page.
startPage = "file1.asp"
currentPage = Request.ServerVariables("SCRIPT_NAME")
'Do a
case-insensitive comparison, and if they
'don't
match, send the user to the start page.
If
strcomp(currentPage,startPage,1) then
Response.Redirect(startPage)
End If
End Sub
</SCRIPT>
Session_OnEnd
Event
<SCRIPT LANGUAGE=ScriptLanguage
RUNAT=Server>
Sub Session_OnEnd. . . End Sub
</SCRIPT>
Parameters
ScriptLanguage
Specifies the scripting language used to write
the event script. It may be any supported scripting language, such as VBScript
or JScript. If more than one event uses the same scripting language, they can
be combined under a single set of <SCRIPT> tags.
Application
Object (IIS)
You can use the Application object to
share information among all users of a given application. An ASP-based
application is defined as all the .asp files in a virtual directory and its
subdirectories. Because the Application object can
be shared by more than one user, there are Lock and Unlock methods to
ensure that multiple users do not try to alter a property simultaneously.
Methods
The Application object defines the
following methods.
Method
|
Description
|
|
|
|
|
|
Prevents other clients
from modifying Application object
properties.
|
|
Allows other clients
to modify Application object
properties
|
Properties
The Application object defines the
following properties.
Property
|
Description
|
|
Contains all of the
items that have been added to the application through script commands.
|
|
Contains all of the
objects added to the session with the <OBJECT> tag
|
Events
The Application object defines the
following events.
Event
|
Description
|
|
Occurs when the
application quits, after the Session_OnEnd event. Only the Application Object
and Server Object built-in objects are available.
|
|
Occurs before the
first new session is created, that is, before the Session_OnStart event. Only
the Application Object and Server Object built-in objects are available.
Referencing the Session Object, Request Object, or Response Object objects in
the Application_OnStart event script causes an error
|
Remarks
You can store values in
the Application Collections.
Information stored in the Application
collections is available throughout the application and has application scope.
The following script demonstrates storage of two types of variables.
VBScript
<%
Application("greeting") =
"Welcome to My Web World!"
Application("num") = 25
%>
You can also assign a
component instance to a variable that has application scope. If you assign a
component instance to a variable with the Server.CreateObject method, the variable
will be a member of the Application.Contents
collection. If the variable is assigned with the <OBJECT> tag, the
variable will be a member of the Application.StaticObjects
Collection.
You should be careful
about assigning component instances to variables with application scope because
some components are not designed to be given application scope. For more
information, see the Platform Software Development Kit (SDK).
If you assign a
component instance to a variable in the Application.Contents Collection
and use Microsoft ® Visual Basic ® Scripting Edition (VBScript) as your primary
scripting language, you must use the Set keyword, as illustrated in the following
script.
VBScript
<% Set Application("Obj1") =
Server.CreateObject("MyComponent") %>
You can then reference
the methods and properties of MyComponent on subsequent Web pages by using the following
script:
Another way to create
objects with application scope is by using the <OBJECT> tag in the
Global.asa file. For more information, see Global.asa Syntax.
If you store an array in
an Application object,
you should not attempt to alter the elements of the stored array directly. For
example, the following script does not work:
VBScript
<% Application("StoredArray")(3) =
"new value" %>
The preceding script
does not work because the Application object is
implemented as a collection. The array element StoredArray(3) does not receive the new value. Instead, the
value is included in the Application object
collection and overwrites any information that had previously been stored at
that location.
It is strongly
recommended that if you store an array in the Application object,
you retrieve a copy of the array before retrieving or changing any of the
elements of the array. When you are done with the array, you should store the
array in the Application object
again, so that any changes you made are saved, as shown in the following
scripts.
VBScript
--- File1.asp ---
<%
'Creating and initializing the array.
dim MyArray()
Redim MyArray(5)
MyArray(0) = "hello"
MyArray(1) = "some other string"
'Storing the array in the Application object.
Application.Lock
Application("StoredArray") = MyArray
Application.Unlock
Server.Transfer("file2.asp")
%>
--- File2.asp ---
<%
'Retrieving the array from the Application
Object
'and modifying its second element.
LocalArray =
Application("StoredArray")
LocalArray(1) = " there"
'Printing out the string "hello
there."
Response.Write(LocalArray(0)&LocalArray(1))
'Re-storing the array in the Application object.
'This overwrites the values in StoredArray with
the new values.
Application.Lock
Application("StoredArray") =
LocalArray
Application.Unlock
%>
Example Code
The following example uses the application variable NumVisits to store the number of
times that a particular page has been accessed. The Lock method is called
to ensure that only the current client can access or alter NumVisits. Calling the Unlock method then
enables other users to access the Application object.
VBScript
<%
Application.Lock
Application("NumVisits") =
Application("NumVisits") + 1
Application.Unlock
%>
This application page has been visited
<%= Application("NumVisits") %>
times!
Application.Contents.Remove
Method
Contents.Remove(
id
)
Parameters
id
A string or an integer
identifying the item in the colleciton to be removed. If id is a string, the method
searches the contents collection for an item with that name and removes it. If id is an integer, the
method counts that number of items from the start of the collection and removes
the corresponding item.
Return Values
This method has no
return values.
Remarks
Although ASP collections
are similar to the Visual Basic Collection object, there are some differences. ASP
collections support the Count property and the Item, Remove, and RemoveAll methods.
They do not support the Add method.
Example Code
The following example
adds three items to the Application.Contents
collection and removes two. At the end of the example, Application(str3) is the first item
instead of the third.
VBScript
<%@ Language="VBScript" %>
<%
Response.Write("<br/>Before Remove<br/>")
Application.Lock
Application.Contents.Item("str1") = ("First thing")
Application.Contents("str2") = ("Second thing")
Application("str3") = ("Third thing")
Application.Unlock
For Each
Key in Application.Contents
Response.Write Key + " = " + Application(Key) +
"<br/>"
Next
Response.Write("<br/>After Remove<br/>")
Application.Lock
Application.Contents.Remove("str1")
Application.Contents.Remove("str2")
Application.Unlock
For Each
Key in Application.Contents
Response.Write Key + " = " + Application(Key) +
"<br/>"
Next
%>
<%@ Language="JScript" %>
<%
Response.Write("<br/>Before Remove<br/>");
Application.Lock();
Application.Contents.Item("str1") = ("First thing");
Application.Contents("str2") = ("Second thing");
Application("str3") = ("Third thing");
Application.Unlock();
e = new
Enumerator(Application.Contents);
for (;
!e.atEnd(); e.moveNext()) {
Response.Write(e.item() + " = " + Application(e.item()) +
"<br/>");
}
Response.Write("<br/>After Remove<br/>");
Application.Lock();
Application.Contents.Remove("str1");
Application.Contents.Remove("str2");
Application.Unlock();
e = new
Enumerator(Application.Contents);
for (;
!e.atEnd(); e.moveNext()) {
Response.Write(e.item() + " = " + Application(e.item()) +
"<br/>");
}
%>
Application.Contents.RemoveAll
Method
Contents.RemoveAll(
)
Parameters
This method has no
parameters.
Return Values
This method has no
return values.
Application.Lock
Method
The Lock method blocks
other clients from modifying the variables stored in the Application object,
ensuring that only one client at a time can alter or access the Application variables.
If you do not call the Application.Unlock
method explicitly, the server unlocks the locked Application object
when the .asp file ends or times out.
Lock(
)
Parameters
This method has no
parameters.
Return Values
This method has no
return values.
Remarks
A lock on the
Application object persists for a very short time because the application
object is unlocked when the page completes processing or times out.
If one page locks the
application object and a second page tries to do the same while the first page
still has it locked, the second page will wait for the first to finish, or
until the Server.ScriptTimeout
limit is reached. If the Server.ScriptTimeout
limit is reached, the following ASP error is returned which cannot be captured:
Note:
|
A page does not need
to lock the application object to edit the application collection. If one
page tries to edit the application collection without locking and a second
page also tries to edit the collection, no error is sent by IIS and the
Application object ends up in an inconsistent state.
|
Applies To
Example Code
In the following example, the Lock method prevents
more than one client at a time from accessing the variable NumVisits. If the application had
not been locked, two clients could simultaneously try to increment the variable
NumVisits.
VBScript
<%@ Language="VBScript" %>
<%
Application.Lock
Application("NumVisits") =
Application("NumVisits") + 1
Application("datLastVisited") =
Now()
Application.Unlock
%>
This application page has been visited
<%= Application("NumVisits")
%> times
Application.Unlock
Method
The Unlock method enables
other clients to modify the variables stored in the Application object
after it has been locked using the Application.Lock
method. If you do not call this method explicitly, the Web server unlocks the Application Object
when the .asp file ends or times out.
Unlock(
)
Parameters
This method has no
parameters.
Return Values
This method has no
return values.
Remarks
The application Lock method is
cumulative, meaning that if the same script calls Lock several times, it
must also call Unlock the same number
of times to fully release the application. If this does not occur, the
application lock will be held until the script is finished running.
A lock on the
Application object persists for a very short time because the application
object is unlocked when the page completes processing or times out.
If one page locks the
application object and a second page tries to do the same while the first page
still has it locked, the second page will wait for the first to finish, or
until the Server.ScriptTimeout
limit is reached. If the Server.ScriptTimeout
limit is reached, the following ASP error is returned which cannot be captured:
Note:
|
A page does not need
to lock the application object to edit the application collection. If one
page tries to edit the application collection without locking and a second
page also tries to edit the collection, no error is sent by IIS and the
Application object ends up in an inconsistent state.
|
Applies To
Example Code
In the following example, the Unlock method releases
the locked object so that the next client can increment NumVisits.
VBScript
<%@ Language="VBScript" %>
<%
Application.Lock
Application("NumVisits") =
Application("NumVisits") + 1
Application("datLastVisited") =
Now()
Application.Unlock
%>
This application page has been visited
<%= Application("NumVisits")
%> times!
Application.Contents
Collection
The Contents collection
contains all the items that have been added to the application through a script
command. You can use the Contents collection to
obtain a list of items that have been given application scope or to specify a
particular item to be the target of an operation. You can also remove items
from the collection by using the Remove and RemoveAll methods.
Syntax
Application.Contents( Key)
Parameters
Key
Specifies the name of the item to retrieve.
Methods
|
Deletes an item from
the collection.
|
|
Deletes all items from
the collection.
|
Remarks
The Contents collection
contains those items that have been declared at the application level without
using the <OBJECT> tags. This would include both objects created by using
Server.CreateObject, as well as scalar
variables established through an Application declaration.
In the following script, for example, both "strHello" and objCustom would be members of the
Contents collection.
<%
Application("strHello") =
"Hello"
Set
Application("objCustom") =
Server.CreateObject("MyComponent") %>
The Contents collection
supports For...Each and For...Next iteration. The following script illustrates each of these methods
of iterating through the Contents collection:
<%
Application("strText1") = "1234567890"
Application("strText2") = "ABCDEFGHIJ"
Application("strText3") = "A1B2C3D4E5"
%>
<%
For Each
Key in Application.Contents
Response.Write Key + " = " + Application(Key) +
"<BR>"
Next
%>
<%
For
intItem = 1 to Application.Contents.Count
Response.Write CStr(intItem) + " = "
Response.Write Application.Contents(intItem) + "<BR>"
Next
%>
Application.StaticObjects
Collection
The StaticObjects
collection contains all of the objects created by using the <OBJECT> tags
within the scope of the Application object.
You can use the collection to determine the value of a specific property for an
object or to iterate through the collection and retrieve all properties for all
static objects.
Syntax
Application.StaticObjects( Key)
Parameters
Key
Specifies the name of the item to retrieve.
Remarks
You can use an iterating
control structure to loop through the keys of the StaticObjects
collection, as shown in the following example.
<%
Dim
strKey
For Each
strKey In Application.StaticObjects
Response.Write strKey & " =
<i>(object)</i><BR>"
Next
%>
Application_OnStart
Event
<SCRIPT LANGUAGE=ScriptLanguage
RUNAT=Server>
Sub Application_OnStart. . . End Sub
</SCRIPT>
Parameters
ScriptLanguage
Specifies the scripting language used to write
the event script. It may be any supported scripting language, such as VBScript
or JScript. If more than one event uses the same scripting language, they can
be combined under a single set of <SCRIPT> tags.
Example Code
Sub Application_OnStart
Application("NumberofVisitors") = 0
End Sub
Application_OnEnd
Event
<SCRIPT LANGUAGE=ScriptLanguage
RUNAT=Server>
Sub Application_OnEnd. . . End Sub
</SCRIPT>
Parameters
ScriptLanguage
Specifies the scripting language used to write
the event script. It can be any supported scripting language, such as VBScript
or JScript. If more than one event uses the same scripting language, they can
be combined under a single set of <SCRIPT> tags.
Remarks
You cannot call the Server.MapPath method
in the Application_OnEnd
script. By default, Application_OnEnd runs
as the Anonymous User, as defined for the application. In the event that there
isn't an Anonymous user, or the Logon for the Anonymous user fails, the OnEnd function will not be
called, and an event will be logged.
Examples
Global.asa:
<script
language="vbscript" runat="server">
Sub Application_OnEnd()
Application("totvisitors")=Application("visitors")
End Sub
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>
|