Lectures & Exercises: Application) Which The Web Application Developer Can Use To Store State
Lectures & Exercises: Application) Which The Web Application Developer Can Use To Store State
NET
Lectures & Exercises
It is a well-known fact that HTTP is a stateless protocol, and that it doesn’t keep
state information in between POST or GET requests from the browser client to
the Web server.
Web applications ‘remember’ a particular client, and relate a client request to
subsequent ones via ‘artificial means’ such as using cookies deposited at the
client’s cookie cache.
Nevertheless, most Web applications need to be able to maintain some unique
state information for each client which visits the Web site.
There are two (2) general ways to maintain state information: at the client, or at
the server. ASP.NET provides 2 useful universal objects (the Session and the
Application) which the Web application developer can use to store state
variables at the server.
The exercises in this chapter will explore the usage of the Session and
Application object, and cookies for storing state information.
Exercise 3.1: State Management Using the Application and Session Objects
Exercise 3.2: Using Cookies
By: Jefferson A. Costales, MIT, IBM -CDA, MCTS, ZCE, OCE Chapter 3 of 9
Web Application Development Using ASP.NET
Lectures & Exercises
Calling Application.Lock() and UnLock(): You would have noticed that the statement
which actually modifies the variables stored with the Application object are between 2
statements: Application.Lock() and Application.UnLock(). Why should you call these
methods before and after setting variables to the Application object?
Syntax: (1stpage.aspx)
Using the Application or Session object: It’s extremely easy to place state variables
into the Application or Session object.
By: Jefferson A. Costales, MIT, IBM -CDA, MCTS, ZCE, OCE Chapter 3 of 9
Web Application Development Using ASP.NET
Lectures & Exercises
The following statement stores a variable called myvar with the corresponding
string value "The sky is blue" into the Session object:
Session["myvar"] = "The sky is blue"
To retrieve the value stored in myvar from the Session object, just access it using
Session["myvar"]
The following statement retrieves the string value stored in the variable myvar in
Session and stores it in another pre-declared string variable called temp:
temp = Session["myvar"]
To store or retrieve variables from the Application object, just use Application
instead of Session:
Application ["myvar"] = "The sky is blue"
temp = Application ["myvar"]
Syntax: (2ndpage.aspx)
By: Jefferson A. Costales, MIT, IBM -CDA, MCTS, ZCE, OCE Chapter 3 of 9
Web Application Development Using ASP.NET
Lectures & Exercises
Variables stored in the Application object are available, whereas
variables stored in the Session object are not shared between unique sessions.
Variables stored in the Application object are shared by all clients
to the same Web application. You can view it as a location to
store ‘global’ variables which any Web form in your Web
application can set or retrieve.
On the other hand, every unique client will have its own Session
object. When a new client visits a Web page in your Web
application, IIS creates a new Session object for storing state
variables. When the same client visits any Web page in the same
Web application again (before the session expires), IIS is able to
match this client with the same Session object.
3.1.2 Set Session Time-out
Because HTTP is a client-driven protocol, there is no way the server knows
if a client is still active unless it sends a POST or GET request over.
Web applications keep track of whether a particular client is still active in a
passive way by setting a time-out period for each user session.
If the Web server doesn’t receive any request within this time-out period, the
Web application will assume that this client is no longer active (though the
user might just have gone off for a long coffee break).
The default timeout period for ASP.NET is set to 20 minutes.You can
change this value in Web.config.
Open up Web.config by double clicking it in Solution Explorer. Scroll down
until you see the <sessionState> element, and change the timeout
attribute’s value from 20 to 1. Save Web.config.
Syntax:
<sessionState
mode="InProc"
stateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString=
"data source=127.0.0.1;Trusted_Connection=yes"
cookieless="false"
timeout="1" />
By: Jefferson A. Costales, MIT, IBM -CDA, MCTS, ZCE, OCE Chapter 3 of 9
Web Application Development Using ASP.NET
Lectures & Exercises
From this point onwards, all user sessions will expire in 1 minute’s time.
Upon time-out, the Session object will be invalidated, and all the variables
associated with it will be lost.
To prove that this is true, open up 1stpage.aspx again, fill in the Name
TextBox (this value is stored in the Session object) and submit. You will
see the entered name in 2ndpage.aspx. Refresh the page a few times,
and notice that the name is still there.
Wait for 1 minute and refresh the page again. This time you will notice
that the name variable has been removed because your session has
already expired.
Killing a session programmatically: You can programmatically invalidate
a user session by calling the Session.Abandon() method.
By: Jefferson A. Costales, MIT, IBM -CDA, MCTS, ZCE, OCE Chapter 3 of 9
Web Application Development Using ASP.NET
Lectures & Exercises
cookies are stored in the client’s machine. For IE, persistent cookies are
stored in C:\Documents and Settings\<username>\Cookies (where
<username> refers to the account name used to log into Windows). Check
out this folder, and you will find that each cookie file is named using the
format username@domainname.txt. When the same user visits a Web page
in the same domain, the associated cookie information will be sent over to
the Web server automatically. Persistent cookies have life spans, which can
be set by the Web application. Upon expiry, they will no longer be valid.
For Windows XP
Example:
"C:\Documents and Settings\[ your account name ]\Cookies"
For Windows 7
Example:
C:\Users\jeffcute\AppData\Local\Microsoft\Windows\Temporary Internet
Files
For Windows 8 and 8.1
Example:
C:\Users\jeffcute\AppData\Local\Microsoft\Windows\INetCookies
Syntax:
Private Sub Page_Load _ (ByVal sender As System.Object, ByVal e As
System.EventArgs)_Handles MyBase.Load
'1st visit
If Request.Cookies("visitCookie") Is Nothing Then
lb_statement.Text = "Welcome to this site!"
SetCookie(1)
Return
End If
'Subsequent visits
Dim c As HttpCookie = Request.Cookies("visitCookie")
Dim noOfVisits As Integer
Dim lastTime As DateTime
By: Jefferson A. Costales, MIT, IBM -CDA, MCTS, ZCE, OCE Chapter 3 of 9
Web Application Development Using ASP.NET
Lectures & Exercises
noOfVisits = c.Values("count")
lastTime = c.Values("time")
lb_statement.Text = "You have visited this site " + _
Convert.ToString(noOfVisits) + _
" times. Your last visit was " + _
Convert.ToString(lastTime)
Write a new method called SetCookie which takes in the new counter value as an Integer:
newC.Values.Add("time", Now())
newC.Values.Add("count", counterValue)
Response.Cookies.Add(newC)
End Sub
Read the codes and try to understand what you have written. In VB.NET, the
Now() method returns the current system time as a DateTime object. (In C#/J#, you can
use DateTime.Now instead.)
This statement sets our new cookie to expire 1 hour later. You can use Now.AddDays() or
Now.AddMonths()or even Now.AddYears() if your cookie is to be long-living.
By: Jefferson A. Costales, MIT, IBM -CDA, MCTS, ZCE, OCE Chapter 3 of 9
Web Application Development Using ASP.NET
Lectures & Exercises
By: Jefferson A. Costales, MIT, IBM -CDA, MCTS, ZCE, OCE Chapter 3 of 9
Web Application Development Using ASP.NET
Lectures & Exercises
Create and design your session page using Application Object and Session
Object.
Customize your file. Optional: Create other features using the previous topic on
State Management.
Customize your file. Optional: Create other features using the previous topic on
State Management.
By: Jefferson A. Costales, MIT, IBM -CDA, MCTS, ZCE, OCE Chapter 3 of 9