0% found this document useful (0 votes)
49 views

Lectures & Exercises: Application) Which The Web Application Developer Can Use To Store State

The document discusses state management in web application development using ASP.NET. It describes how the HTTP protocol is stateless and how state can be maintained either on the client or server side. ASP.NET provides the Session and Application objects to store state variables on the server side. The Session object stores data for each user session while the Application object stores global data for the entire application. Cookies can also be used to store small amounts of data on the client side to maintain state across requests.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views

Lectures & Exercises: Application) Which The Web Application Developer Can Use To Store State

The document discusses state management in web application development using ASP.NET. It describes how the HTTP protocol is stateless and how state can be maintained either on the client or server side. ASP.NET provides the Session and Application objects to store state variables on the server side. The Session object stores data for each user session while the Application object stores global data for the entire application. Cookies can also be used to store small amounts of data on the client side to maintain state across requests.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Web Application Development Using ASP.

NET
Lectures & Exercises

CHAPTER III: STATE MANAGEMENT

 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.

Two (2) important configuration files which developers use to store


configurable parameters will also be introduced: Global.asax and Web.config.

There are two (2) exercises in this chapter:

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

3.1 State Management Using the Session and Application Objects

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?

In a multi-user environment, there may be many concurrent visits to 1stpage.aspx


from different clients. And because ASP.NET is multi-threaded (of course server
applications have to be multi-threaded!), you might have inconsistencies when the same
statement attempting to update a variable into Application executes simultaneously by
more than 1 client.
To prevent other clients from executing such statements at the same time, the
Application.Lock() method is invoked first. Only one of many concurrently running
processes can execute statements within the ‘critical section’ (between the Lock() and
UnLock() statements). Only when that process which is executing statements within the
critical section calls Application.UnLock() can other processes go into the critical section.
This prevents multiple, concurrent access to the Application object, and is a good
practice that should be followed.

Syntax: (1stpage.aspx)

private void btnSubmit_Click(object sender, System.EventArgs e)


{
Application.Lock();
Application("StudID") = txtStudID.Text;
Application.UnLock();
Session("name") = txtName.Text;
Response.Redirect("2ndpage.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)

private void Page_Load(object sender, System.EventArgs e)


{
// Put user code to initialize the page here
lb_statement1.Text = "Hi, " + Session["name"];
lb_statement2.Text = "Your Student No. is " + Application["StudID"];
}

The expression Session["name"] returns the value stored in the variable


name in the Session object, and the expression Application["StudID"] returns the value
stored in the variable StudID in the Application object.

3.1.1 Understand the difference between storing variables in Application and


Session.
While keeping the current IE window still open, start up a new IE window,
and type in the URL for 2ndpage.aspx (not 1stpage.aspx) in the Address field.
You would have noticed that in this second IE client, 2ndpage.aspx is unable to
retrieve the name variable from the Session object, but can still retrieve and
display the day variable from the Application object

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.

3.2 Using Cookies


 Using the Session and Application object to store state information is a
common but expensive solution to maintain a conversational state at the
server side.
 Cookies is another commonly employed solution to store state information
at theclient side.
 Cookies are usually used to ‘remind’ a Web application that a particular
client has previously visited the same site, and store useful information such
as her user preferences (preferred color, area of interest etc).
 A cookie is a small text file that can be used to store small amounts of
information needed to maintain state. Cookies are saved in the client’s
browser cache, and hence maintaining state using cookies is considered a
client-side state management method, rather than server-side.
 When the client browser requests for a page, it sends the information in the
cookie along with the request information.
 There are two (2) types of cookies: temporary and persistent. Temporary
cookies are also known as session cookies, and exist in the memory of the
client browser. They are removed when the browser is closed. Persistent

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)

'Readjust values and set cookie


noOfVisits += 1
SetCookie(noOfVisits)
End Sub

Write a new method called SetCookie which takes in the new counter value as an Integer:

Private Sub SetCookie(ByVal counterValue As Integer)


'newC is the new cookie to be set
Dim newC As New HttpCookie("visitCookie")
'create & set cookie to client

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.)

 In order to create a persistent cookie, you need to insert an additional statement


into your SetCookie method:

'Create & set cookie to client


newC.Values.Add("time", Now())
newC.Values.Add("count", counterValue)
newC.Expires = Now.AddHours(1)
Response.Cookies.Add(newC)

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

Here are the codes on how to set a cookie:


HttpCookie c = new HttpCookie("cookieName");
c.Values.Add("param1", "some value");
c.Values.Add("param2", "some other value");
c.Values.Add("param3", "yet some other value");

Here are the codes on how to retrieve a cookie:


HttpCookie c = Request.Cookies["cookieName"];
string temp1 = c.Values("param1");
string temp2 = c.Values("param2");
string temp3 = c.Values("param3");

By: Jefferson A. Costales, MIT, IBM -CDA, MCTS, ZCE, OCE Chapter 3 of 9
Web Application Development Using ASP.NET
Lectures & Exercises

Exercise No. 3.1 Grade: ______________

Time: 45 Minutes Time Started: ________


Directory Folder: C:\inetpub\wwwroot\LNFNMI\ Time Finished: ________

File Name: Exer3Session.aspx

File to use: Use existing Exercise 2. (Exer2RegiCaptcha.aspx)

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.

Exercise No. 3.2 Grade: ______________

Time: 30 Minutes Time Started: ________


Directory Folder: C:\inetpub\wwwroot\LNFNMI\ Time Finished: ________

File Name: Exer3_1Cookies.aspx


File to use: Use existing Exercise 2. (Exer2RegiCaptcha.aspx)

Create and design your session page using Cookies.

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

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy