1. STATE MANAGEMENT
No web application framework, no matter how
advanced, can change the fact that HTTP is a stateless
protocol.
After every web request, the client disconnects from the
server, and the ASP.NET engine discards the objects that
were created for the page.
Stateless architecture ensures that web applications can
fetch serve thousands of simultaneous requests without
running out of server memory.
The drawback is that your code needs to use other
techniques to store information between web requests and
retrieve it when needed. 1
2. ASP.NET MANAGEMENT
ASP.NET includes a variety of options for state management.
Can choose the right option depending on the data you need
to store, the length of time you want to store it, the scope of
your data, and additional security and performance
considerations.
State Management Options
View State
Query String
Custom Cookies
Session State
Application State
Profiles
Caching 2
3. VIEW STATE
View state should be your first choice for storing information
within the bounds of a single page.
You can add your own data to the view state collection using a
built-in page property called ViewState.
Like most types of state management in ASP.NET, view state
relies on a dictionary collection, where each item is indexed with
a unique string name
ViewState["Counter"] = 1;
When retrieving a value, you use the key name.
int counter;
if (ViewState["Counter"] != null)
{
counter = (int)ViewState["Counter"];
}
3
4. VIEW STATE EXAMPLE
• The Example (ViewStateTest.aspx) demonstrates
a page that uses view state.
• It allows the user to save a set of values (all the
text that’s displayed in all the text boxes of a table)
and restore it later.
•Refer to example given in textbook
4
5. STORING OBJECTS IN VIEW STATE
Can store your own objects in view state just as easily as you store
numeric and string types.
However, to store an item in view state, ASP.NET must be able to
convert it into a stream of bytes so that it can be added to the hidden
input field in the page. (called serialization)
For your classes to be serializable, you must meet these
requirements:
• Your class must have the Serializable attribute.
• Any classes it derives from must have the Serializable
attribute.
• All the member variables of the class must use
serializable data types.
5
6. VIEW STATE SECURITY
View state information is stored in a single Base64-encoded string that looks like
this:
<input type="hidden" name="__VIEWSTATE“
id="__VIEWSTATE" value="dDw3NDg2NTI5MDg7Oz4="/>
Many ASP.NET programmers assume that their view state data is encrypted. It
isn’t
If you want to make view state secure, you have two choices.:-
First, you can make sure that the view state information is tamper-proof by
using a hash code.
enableViewStateMac attribute of the <pages> element in the web.config or
machine.config
Hash code is cryptographically checksum
ASP.Net calculates checksum based on current view state content and adds it to
hidden field when it returns the page
When page is posted back ASP.NET recalculates the checksum and ensures for 6
7. VIEW STATE SECURITY CONT…
Hash codes are enabled by default.
<%@ Page EnableViewStateMAC="false" ... %>
Can set the enableViewStateMac attribute of the <pages> element in the
web.config or machine.config file, as shown below:
<configuration>
<system.web>
<pages enableViewStateMac="false" />
…
</system.web>
</configuration>
The view state data will still be readable. To prevent users from getting
any view state information, you can enable view state encryption for an
individual page – %<@PageViewStateEncryptionMode=“Always”… >%
Can set the same attribute in the web.config configuration file:
<pages viewStateEncryptionMode="Always" /> 7
8. TRANSFERRING INFORMATION BETWEEN PAGES
One of the most significant limitations with view
state is that it’s tightly bound to a specific page.
If the user navigates to another page, this
information is lost.
This problem has several solutions, and the best
approach depends on your requirements.
Passing information from one page to another:-
The Query String
Cookies
Application State
8
9. QUERY STRING
One common approach is to pass information
using a query string in the URL.
Find this approach in search engines.
For example
http://www.google.ca/search?q=organic+gardening
The advantage of the query string is that it’s
lightweight and doesn’t exert any kind of burden on
the server.
9
10. QUERY STRING CONT…
It has some limitations:
Information is limited to simple strings, which
must contain URL-legal characters.
Information is clearly visible to the user and to
anyone else who cares to eavesdrop on the
Internet
The enterprising user might decide to modify
the query string and supply new values,
Many browsers impose a limit on the length of
a URL (usually from 1 to 2 KB).
10
11. QUERY STRING CONT…
Using the Query String:
// Go to newpage.aspx. Submit a single query string
argument named recordID and set to 10.
int recordID = 10;
Response.Redirect("newpage.aspx?recordID=" +
recordID.ToString());
The receiving page has an easier time working with the query
string.
string ID = Request.QueryString["recordID"];
11
12. URL ENCODING
One potential problem with the query string is using
characters that aren’t allowed in a URL.
& is used to separate multiple query strings
+ used to denote space
#points to specific bookmark on page
Can use the methods of the HttpServerUtility class to
encode your data automatically
string productName = "Flying Carpet";
Response.Redirect("newpage.aspx?productName="
Server.UrlEncode(productName));
12
13. CROSS PAGE POSTING
ASP.NET pages post back to themselves.
When a page is posted back, it sends the current
content of all the controls in the form for that page.
To transfer information from one page to another,
you can use the same postback mechanism, but send
the information to a different page.
The infrastructure that supports cross-page
postbacks is a property named PostBackUrl
To use cross-page posting, you simply set
PostBackUrl to the name of another web form. 13
14. CROSSdefines a form with two text boxes and a button that posts to a page
Example below
PAGE POSTING CONT..
named CrossPage2.aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CrossPage1.aspx.cs"
Inherits="CrossPage1" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>CrossPage1</title>
</head>
<body>
<form id="form1" runat="server" >
<asp:TextBox runat="server" ID="txtFirstName"></asp:TextBox>
<asp:TextBox runat="server" ID="txtLastName"></asp:TextBox>
<asp:Button runat="server" ID="cmdSubmit” PostBackUrl="CrossPage2.aspx"
Text="Submit" />
</form>
</body>
</html> 14
15. CROSS PAGE POSTING CONT…
In CrossPage2.aspx, the page can interact with the CrossPage1.aspx objects using
the Page.PreviousPage property.
protected void Page_Load(object sender, EventArgs e)
{
if (PreviousPage != null)
{
lblInfo.Text = "You came from a page titled " +
PreviousPage.Header.Title;
}
}
Note that this page checks for a null reference before attempting to access
the PreviousPage object.
If there’s no PreviousPage object, there’s no cross-page postback.
ASP.NET uses some interesting idea - The first time the second page
accesses Page.PreviousPage, ASP.NET creates the previous page object by
starting the page processing life cycle, but interrupts it just before the
PreRender stage.
15
16. CROSS PAGE POSTING CONT…
If you want to get more specific details, such as control values, you need to
cast the PreviousPage reference to the appropriate type.
protected void Page_Load(object sender, EventArgs e)
{
CrossPage1 prevPage = PreviousPage as CrossPage1;
if (prevPage != null)
{
// (Read some information from the previous page.)
}
}
You can solve this problem in another way.
<%@ PreviousPageType VirtualPath="CrossPage1.aspx" %>
Don’t have flexibility to deal with situations where more than one page
trigger cross-page postback 16
17. COOKIES
Custom cookies provide another way you can store information for
later use.
Cookies are small files that are created on the client’s hard drive
(or, if they’re temporary, in the web browser’s memory).
Advantage of cookies is that they work transparently without the
user being aware that information needs to be stored.
Limitations:
can store only simple string information, and
easily accessible and readable if the user finds and opens the
corresponding file.
Some users disable cookies on their browsers.
Before you can use cookies, you should import the System.Net
namespace-
using System.Net; 17
18. COOKIES CONT…
Both the Request and Response objects provide a Cookies
collection
To set a cookie, just create a new System.Net.HttpCookie
object
// Create the cookie object.
HttpCookie cookie = new HttpCookie("Preferences");
// Set a value in it.
cookie["LanguagePref"] = "English";
// Add another value.
cookie["Country"] = "US";
// Add it to the current web response.
Response.Cookies.Add(cookie);
// This cookie lives for one year.
cookie.Expires = DateTime.Now.AddYears(1); 18
19. COOKIES CONT…
Cookies are retrieved by cookie name using the Request.Cookies
collection
// Check to see whether a cookie was found with this name. This is a
// good precaution to take, because the user could disable cookies,in
// which case the cookie would not exist.
string language;
if (cookie != null)
{
language = cookie["LanguagePref"];
}
The only way to remove a cookie is by replacing it with a cookie that has
an expiration date that has already passed:
HttpCookie cookie = new HttpCookie("LanguagePref");
cookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(cookie);
19
20. SESSION STATE
Session state is the heavyweight of state management.
It allows information to be stored in one page and accessed in
another.
It supports any type of object, including your own custom data
types.
Session state uses the same collection syntax as view state.
The only difference is the name of the built-in page property, which
is Session.
Every client that accesses the application has a different session
and a distinct collection of information.
Drawbacks:
forces the web server to store additional information in memory
Extra memory requirement, can quickly grow to performance-
destroying levels as thousands of clients access the site. 20
21. SESSION ARCHITECTURE
Session management is not part of the HTTP standard.
ASP.NET needs to do some extra work to track session
information and bind it to the appropriate response.
ASP.NET tracks each session using a unique 120-bit
identifier.
The ID is the only piece of information that is transmitted
between the web server and the client.
When the client presents the session ID
ASP.NET looks up the corresponding session,
retrieves the serialized data from the state server,
converts it to live objects, and
places these objects into a special collection so they can
be accessed in code. 21
22. SESSION ARCHITECTURE CONT…
The SessionStateModule doesn’t actually store the session data. Instead,
the session state is persisted in external components, which are named
state providers.
22
23. USING SESSION STATE
User session state using the
System.Web.SessionState.HttpSessionState class,
which is provided in an ASP.NET web page as the
built-in Session object.
Session["ProductsDataSet"] = dsProducts;
Can then retrieve it with an appropriate conversion
operation:
dsProducts = (DataSet)Session["ProductsDataSet“]
23
24. USING SESSION STATE CONT…
Session state is global to your entire application for the current
user. Session state can be lost in several ways:
If the user closes and restarts the browser.
If the user accesses the same page through a different
browser window, although the session will still exist if a web
page is accessed through the original browser window.
Browsers differ on how they handle this situation.
If the session times out because of inactivity. By default, a
session times out after 20 idle minutes.
If the programmer ends the session by calling
Session.Abandon().
24
25. KEY METHODS AND PROPERTIES OF THE
HTTPSESSIONSTATE
Member Description
Count The number of items in the current session collection.
IsCookieless Identifies whether this session is tracked with a cookie or with
modified URLs
IsNewSession Identifies whether this session was just created for the current
request.
Mode Provides an enumerated value that explains how ASP.NET
stores session state information.(determined based on the
web.config)
SessionID Provides a string with the unique session identifier for the
current client.
Timeout The current number of minutes that must elapse before the
current session will be abandoned.
Abandon() Cancels the current session immediately and releases all the
memory it occupied.
Clear() Removes all the session items but doesn’t change the current
25
session identifier
26. CONFIGURING SESSION STATE
can configure session state through the <sessionState> element in the web.config
file for your application.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.web>
<!-- Other settings omitted. -->
<sessionState
mode="InProc"
stateConnectionString="tcpip=127.0.0.1:42424"
stateNetworkTimeout="10"
sqlConnectionString="data source=127.0.0.1;Integrated Security=SSPI"
sqlCommandTimeout="30" allowCustomSqlDatabase="false"
useHostingIdentity="true"
cookieless="UseCookies" cookieName="ASP.NET_SessionId"
regenerateExpiredSessionId="false"
timeout="20"
customProvider=“” />
</system.web>
</configuration>
26
27. CONFIGURING SESSION STATE CONT…
Mode
Off This setting disables session state management for every
page in the application
InProc InProc is similar to how session state was stored in classic
ASP, stores information in the current application domain
StateServer With this setting, ASP.NET will use a separate Windows
service for state management.
Use Admin. Tools to start ASP.Net State Service.
SQLServer This setting instructs ASP.NET to use a SQL Server database
to store session information, as identified by the
sqlConnectionString attribute in web.config.
Required to have a server with SQL Server installed.
Custom When using custom mode, you need to indicate what session
state store provider to use by supplying the customProvider
attribute.
27
28. CONFIGURING SESSION STATE CONT..
Cookieless
UseCookies Cookies are always used, even if the browser
or device doesn’t support
cookies or they are disabled.
UseUri The session ID is stored in the URL
UseDeviceProfi ASP.NET chooses whether to use cookieless
le sessions by examining the
BrowserCapabilities object.
AutoDetect ASP.NET attempts to determine whether the
browser supports cookies by
attempting to set and retrieve a cookie
28
29. CONFIGURING SESSION STATE CONT..
Timeout
This specifies the number of minutes that ASP.NET will wait,
without receiving a request, before it abandons the session.
<sessionState timeout="20" ... />
This setting represents one of the most important compromises
of session state.
Here’s a sample line of code that changes the time-out to ten
minutes:
Session.Timeout = 10;
29
30. SECURING SESSION STATE
An eavesdropper could steal the cookie and assume the
session on another computer.
One common approach is to use a custom session module
that checks for changes in the client’s IP address.
However, the only truly secure approach is to restrict session
cookies to portions of your website that use SSL.
To use this approach, it also makes sense to mark the
session cookie as a secure cookie so that it will be sent only
over SSL connections.
Request.Cookies["ASP.NET_SessionId"].Secure = true;
Use above this code immediately after the user is 30
31. APPLICATION STATE
Applicationstate allows you to store global objects
that can be accessed by any client.
Application state is based on the
System.Web.HttpApplicationState class, which is
provided in all web pages through the built-in
Application object.
Application state is similar to session state.
Common examples: How many users visited site
OR how many page visited.
31
32. APPLICATION STATE CONT..
Here’s an example of number of page visits:
protected void Page_Load(Object sender, EventArgs e)
{
int count = 0;
if (Application["HitCounterForOrderPage"] != null)
count =
(int)Application["HitCounterForOrderPage"];
count++;
Application["HitCounterForOrderPage"] = count;
lblCounter.Text = count.ToString();
}
32
33. APPLICATION STATE CONT..
To prevent problem of concurrent access use the Lock() and UnLock()
methods.
protected void Page_Load(Object sender, EventArgs e)
{
// Acquire exclusive access.
Application.Lock();
int count = 0;
if (Application["HitCounterForOrderPage"] != null)
count = (int)Application["HitCounterForOrderPage"];
count++;
Application["HitCounterForOrderPage"] = count;
// Release exclusive access.
Application.UnLock();
lblCounter.Text = count.ToString();
}
33
34. APPLICATION STATE CONT..
Application state is rarely used in the .NET world
because its two most common uses have been
replaced by easier, more efficient methods.
In the past, application state was used to store
application-wide constants, such as a database
connection string. (use web.config)
Many uses of application state can be replaced
more efficiently with caching.
34