Chapter 6-State Management
Chapter 6-State Management
Chapter 6
What Are You Going To Learn?
• At the end of this lesson, you will be able to:
– Explain HTTP Protocol
– Differentiate cookie, query string, session variable,
application variable and cache to retain
information
– Use Global.asax file
– Choose and apply appropriate mechanism to
maintain state
2/1
HTTP: HyperText Transfer Protocol
• A communication protocol of the TCP/IP Suit
with the Web server, used for retrieving
hypertext.
• The most common used protocol is HTTP/1.1
• HTTP is a request/response standard between
a client and a server.
3/1
HTTP: HyperText Transfer Protocol
• Typically an HTTP client initiates a Request, which
establishes a TCP connection to a particular port
(usually port 80) on a host (server).
• Upon receiving the request, the server sends back
the requested resource as Response.
• Resources to be accessed by HTTP are indentified
using Uniform Resource Identifiers (URIs) (i.e.
Uniform Resource Locator (URL) using the http: (or
https:) URI schemes.
4/1
How HTTP works:
5/1
How HTTP works:
obtain IP address from DNS
services
establish TCP connection to the IP
2 (on Port 80).
6/1
How HTTP works:
client’s packet (HTTP request) is transported to the server
GET /Index.html HTTP/1.1\r\n
Connection: Keep-Alive\r\n
Accept: */*\r\n User-Agent: Chrome/5.0 \r\n
Host: www.tarc.edu.my\r\n\r\n
7/1
How HTTP works:
• Note the first request contains the GET command.
• It requests the web server to provide the URL path
'/'. It is followed by the HTTP version number: 1.1.
• The Host tag tells the web server which web site's '/'
path is needed (This is important as more than one
website is usually hosted on a single machine).
• The User-Agent tag gives the web server information
about what browser you are using.
8/1
How HTTP works:
HTTP/1.1 200 OK
Server: Microsoft-IIS/5.0\r\n
Content-Location: http://www.tarc.edu.myindex.html\r\n
Date: Tue, 25 Jun 2002 19:33:18 GMT\r\n
Content-Type: text/html\r\n
11/1
What is state?
• A program stores data in variables (memory
locations). The contents of the memory
locations at the given point in the program
execution, is called state.
• State refers to the current status of the
properties, variables, and other data maintained
by an application for a single user.
• The application must maintain a separate state
for each user.
12/1
HTTP is stateless
• It doesn’t keep track of state between round
trips.
• Each request is standalone and considered a
new request from a new user.
• Once a browser makes a request that receives
a response, the application terminates and its
state is lost.
13/1
Different way to manage web page’s state
14/1
Client-side state management options
15/1
Client-side state management options
• View state can be disabled, but control state cannot.
• Control state is used to store essential data that must
be used during postback (not to worry whether the
viewstate is enabled or not).
• However, use control state only for small amounts of
critical data that are essential for the control across
postbacks. Do not use control state as an alternative
to view state.
16/1
Server-side state management options
17/1
Client-side state management
18/1
WhatCookies
are cookies?
19/1
How Cookies Work
• A web application sends a cookie to a browser
via an HTTP response.
• Then, each time the browser sends and HTTP
request to the server, it attaches any cookies
that are associated with that server.
20/1
How Cookies Work
21/1
How Cookies Work
22/1
Cookies
• A cookie is a set of properties in the form of
name=value pairs (separated by commas)that is
stored in the user’s browser or on the user’s disks.
23/1
Viewing cookies from the browser
25/1
Cookies usage
• Used to store client preferences, such as:
– ____________________________
– ____________________________
• Details of the last visited date and time
• Some user details, such as:
– user name
– password?? (should we?)
• Previous search details
26/1
Creating cookies
• First method:
HttpCookie identifier= new HttpCookie(CookieName);
cookie.Value = SomeValue;
• Example:
HttpCookie cookie = new HttpCookie ("LastSearch”);
cookie.Value = txtSearch.Text;
27/1
Creating cookies
• Second method:
HttpCookie identifier= new HttpCookie(CookieName,value);
• Example:
HttpCookie
HttpCookie cookie
cookie == new
new HttpCookie
HttpCookie ("LastSearch”,
("LastSearch”, txtSearch.Text);
txtSearch.Text);
28/1
Reading a cookie
• Syntax:
Request.Cookies[CookieName].Value
• Examples:
if(Request.Cookies[“LastSearch”]
if(Request.Cookies[“LastSearch”] != != null)
null)
{{
txtSearch.Text = Request.Cookies["LastSearch"].Value;
}}
29/1
HttpCookie property
• Expires
A DateTime value that indicates when the cookie
should expire.
• Name
The cookie’s name.
• Value
The string value assigned to the cookie.
30/1
HttpCookieCollection class
• Cookies are managed in collection defined by
the HttpCookieCollection class.
• Property
Count :The number of cookies in the collection.
• Methods
Add(cookie) : Adds a cookie to the collection.
Clear( ) : Removes all cookies from the collection.
Remove(name) : Removes a cookie.
chap6\Cookies folder
31/1
Advantages of cookies
• Since cookies persist on the client’s computer,
space does not need to be allocated on the
web server to store user-specific information
• Cookies can save small amounts of
information for very long periods of time
• Cookies can be used to customize a user’s visit
to your web site
32/1
Disadvantages of cookies
• Users can choose not to accept cookies on
their Web browsers (they can block the
cookies)
• Users can manually delete cookies
• Cookies are unable to save large objects,
arrays, or other complex data types. Cookies
can only save string, date, or numeric data
types
33/1
When to use cookies?
• Store small piece of data that are not crucial
to your application
• Never use cookies to store sensitive
information
• Can be configured to expire after any length of
time
• However, cookies can be blocked at the client
end.
34/1
Query String
35/1
Query String
• Used in Anchor tags and hyperlinks (URLs) to pass
information from one page to the other.
• Query string syntax (after ? mark) Query String
– pass 1 value:
URL?name=value
Example:
Example: http://www.shop.com/shop.aspx?prod=tx0002
– pass >1 value
URL? name1=value1&name2=value2
name1=value1&name2=value2
Example:
Example: Order.aspx?cat=1&prod=tx0002
Order.aspx?cat=1&prod=tx0002
36/1
Passing a Query String
• Example 1 (with Anchor tag)
<a href=“product.aspx?cat=tx&prod=fog01”> Fog machine</a>
• Example 2 (with button)
<asp:Button PostBackUrl = “shop.aspx?prod=tx0002”
ID=“btnShop” runat=“server” />
• Example 3 (Response.Redirect)
Response.Redirect(“Order.aspx?cat=“
Response.Redirect(“Order.aspx?cat=“ ++ txtcategoryID.Text);
37/1
Query String
• Statements that retrieve the values of the
query string attributes
Request.QueryString[“name”]
• Example:
– The following query string is passed to “product.aspx”
<a href=“product.aspx?cat=tx&prod=fog01”>
href=“product.aspx?cat=tx&prod=fog01”> Fog machine</a>
– In “product.aspx”, retrieve the values
string
string categoryID = Request.QueryString[“cat”];
string
string productID= Request.QueryString[“prod”];
38/1
QueryString Demo
chap6\QueryString folder
39/1
Server-side state management
40/1
Understanding scope
• Function
– Visible within the function
• Page
– Visible within the page
• Session
– Visible from page to page during a session
– Session variables can be used in all the pages in an
application for a particular session
• Application
– Visible throughout the whole application lifetime
41/1
Understanding scope (cont’)
42/1
What is session?
• Time spent browsing a site
• from the moment you first start browsing to the moment you
close your browser (Persists its value until a session ended or
user leaves the website)
• Each visitor is assigned an individual session (Data stored in
session variables are not shared among different users)
• A new instance of browser is considered a new session
• A session object is created for each session
43/1
How session work ?
44/1
Creating session variables
Can store any type
• Syntax
– Session[“ItemName”] = Content;
• Examples
Session[“username”]=“Patrick”;
Session[“email”]=txtEmailAddress.Text;
Session[“quantity”] = 100;
Session[“StudentList”] = studentList;
45/1
Retrieving session variables
• Session variable used to store objects (in any type)
• Type casting is needed to assign the value of a session
object to a variable. Type casting
• Examples
lblUserName.Text = Session[“username”].ToString();
int quantity = Convert.ToInt32(Session[“quantity”]);
List<string>
List<string> studList = (List<string>)Session[“studentList”];
46/1
Controlling when a session ends
• Default timeout – 20 minutes
• Set timeout to other values by using Timeout
property (in minutes)
Session.Timeout = 60; //set session timeout to 60 mins)
47/1
Session methods (cont’)
• Add(name, value)
– Adds an item to the session state collection.
• Clear( )
– Clears all values from the session but leaves the
session active
• Remove(name)
– Removes an item
• Abandon( )
– Force to end the current session
48/1
Session methods (cont’)
Methods:
Session.Add
Session.Remove
Session.Clear
Session.Abandon
Property:
Session.SessionID
49/1
When to use sessions?
• Used to maintain user-specific information
• Can store any variable type
• Best choice when you need to maintain state
only for the user’s visit to your site.
• However, if you receive many concurrent
users or place large object in the Session
object, your Web server performance will
degrade
50/1
Session Demo
chap6\Session folder
Application objects
• Designed to maintain state globally, across the
entire website
• Application variables can be accessed by all
the pages and by all the users of the
application
• Similar to Session, it can store any data types
including objects and arrays
52/1
Application usage
• To store global application data such as
discount terms and tax rates.
• Display tips of the day or news update
• Record the number of times a banner
advertisement was clicked
• Record the running count of the visitors
53/1
Creating application variables
• Syntax Can store any type
– Application[“ItemName”] = Content;
• Examples
– Application[“TipsOfTheDay”]=“Failing in the past
does not mean you will fail again in the future”;
– Application[“visitor”] = 0;
54/1
Retrieving application variables
• Application variable used to store objects (in any
type)
• Type casting is needed to assign the value of a
application object to a variable.
• Examples
lblDisplay.Text = Application[“TipsOfTheDay”].ToString();
int visitorCount = (int)Application[“visitor”];
55/1
Application Methods
• Add(name, value)
– Adds an item to the application state collection.
• Clear( )
– Removes all items from the application state
collection.
• Remove(name)
– Removes a particular item.
56/1
Application Methods
• Application.Lock( )
– Locks the application state collection so only the
current user can access it.
• Application.UnLock( )
– Unlocks the application state collection so other
users can access it.
57/1
Application Property
• Count
– The number of items in the application state
collection.
58/1
Working with application events
• Global.asax is a code-only file that provides event
handlers for responding to application events.
• Only scripts and objects are allowed
• Cannot include scripts that produces output
(HTML tags or Response.Write method)
• for responding to events that occur for the
application as a whole, or for the session as a
whole.
59/1
Events handlers in Global.asax
60/1
Application events
• Application_Start
– Raised when the first page of an application is
requested by any user.
– Raised when web server restarted
– Raised when Global.asax file is edited
• Application_End
– Raised when application is about to terminate.
• Application_Error
– Raised when an unhandled error occurs
61/1
Application events (cont’)
• Session_Start
– Raised when a user starts a session
• Session_End
– Raised when a user session ends
• Profile_OnMigrateAnonymous [Not covered]
– Raised when an anonymous user logs in, and
allows migration of any Profile properties
62/1
When to use applications?
• Used to maintain information that is global to
the entire Web site.
• Should NOT use to maintain state on a user-
by-user basis
• Can drain your server’s resources
• Can’t use to store anything you need to keep
63/1
Application Demo
chap6\Application folder
Caching
• Caching is the process of storing frequently
used data on the server to fulfill subsequent
requests.
• Caching is extremely important for performance
boosting in ASP.NET, as the pages and controls
are dynamically generated
• Caching places frequently used data in quickly
accessed media such as the random access
memory (RAM)
65/1
Caching
• Three types of caching
Output caching / Page output caching
Fragment caching / Partial page caching
Data caching [Not covered]
66/1
Output Caching
• Allows the entire contents of a page to be
persisted to memory and used to fulfill client
requests.
• This type of cache saves post-rendered content
so it won‘t have to be regenerated again the
next time it’s requested.
• After a page is cached, it can be served up again
when any subsequent requests are made to the
server.
67/1
Without Cache
68/1
With Cache
69/1
With Cache
70/1
Output Caching
71/1
Output Caching
• <%@ OutputCache Duration=“60”
VaryByParam=“None” %>
• Duration attribute - defines the number of seconds a page is stored in the
cache.
• You must include either the VaryByParam attribute or the VaryByControl
attribute.
• However, if you do not need to vary your cached output by control or
parameters, define VaryByParam =“None”.
72/1
Cache multiple versions of the same page in output cache
VaryByParam attribute :
allows you to vary the cached output depending
on the query string.
The VaryByControl attribute :
allows you to vary the cached output
depending on a control value.
73/1
Cache multiple versions of the same page in output cache
VaryByHeader attribute :
allows you to vary the cached output depending
on the request's HTTP header.
VaryByCustom attribute :
allows you to vary the cached output by
browser type or by a custom string that you
define.
74/1
Cache attribute and values
75/1
Cache attribute and values
76/1
Fragment Caching
• Partial page caching allows parts of a page to
be cached and other parts to be dynamic.
• Achieved with using of user control(caching of
user control ) (chapter 8)
• By enabling the Shared = "true" attribute, the
UserControl’s output can be shared among
multiple pages .
<%@ OutputCache Duration="10" VaryByParam="*" shared="true"%>
77/1
When to use output caching?
• The generated page changes every few hours
as information is loaded into a database.
78/1
Caching Demo
chap6\Caching folder