Top Banner
1 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 STATE MANAGEMENT
34
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Ch05 state management

1

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.

STATE MANAGEMENT

Page 2: Ch05 state management

2

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

ASP.NET MANAGEMENT

Page 3: Ch05 state management

3

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"];}

VIEW STATE

Page 4: Ch05 state management

4

• 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

VIEW STATE EXAMPLE

Page 5: Ch05 state management

5

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.

STORING OBJECTS IN VIEW STATE

Page 6: Ch05 state management

6

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 matches

VIEW STATE SECURITY

Page 7: Ch05 state management

7

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" />

VIEW STATE SECURITY CONT…

Page 8: Ch05 state management

8

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

TRANSFERRING INFORMATION BETWEEN PAGES

Page 9: Ch05 state management

9

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.

QUERY STRING

Page 10: Ch05 state management

10

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

QUERY STRING CONT…

Page 11: Ch05 state management

11

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"];

QUERY STRING CONT…

Page 12: Ch05 state management

12

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

URL ENCODING

Page 13: Ch05 state management

13

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.

CROSS PAGE POSTING

Page 14: Ch05 state management

14

Example below defines a form with two text boxes and a button that posts to a page 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> &nbsp;

<asp:TextBox runat="server" ID="txtLastName"></asp:TextBox>

<asp:Button runat="server" ID="cmdSubmit” PostBackUrl="CrossPage2.aspx" Text="Submit" />

</form></body></html>

CROSS PAGE POSTING CONT..

Page 15: Ch05 state management

15

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.

CROSS PAGE POSTING CONT…

Page 16: Ch05 state management

16

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

CROSS PAGE POSTING CONT…

Page 17: Ch05 state management

17

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;

COOKIES

Page 18: Ch05 state management

18

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

COOKIES CONT…

Page 19: Ch05 state management

19

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

COOKIES CONT…

Page 20: Ch05 state management

20

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.

SESSION STATE

Page 21: Ch05 state management

21

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.

SESSION ARCHITECTURE

Page 22: Ch05 state management

22

The SessionStateModule doesn’t actually store the session data. Instead, the session state is persisted in external components, which are named state providers.

SESSION ARCHITECTURE CONT…

Page 23: Ch05 state management

23

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“]

USING SESSION STATE

Page 24: Ch05 state management

24

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

USING SESSION STATE CONT…

Page 25: Ch05 state management

25

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 session identifier

KEY METHODS AND PROPERTIES OF THE HTTPSESSIONSTATE

Page 26: Ch05 state management

26

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

<sessionStatemode="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>

CONFIGURING SESSION STATE

Page 27: Ch05 state management

27

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.

CONFIGURING SESSION STATE CONT…

Page 28: Ch05 state management

28

Cookieless

UseCookies Cookies are always used, even if the browser or device doesn’t supportcookies or they are disabled.

UseUri The session ID is stored in the URL

UseDeviceProfile

ASP.NET chooses whether to use cookieless sessions by examining theBrowserCapabilities object.

AutoDetect ASP.NET attempts to determine whether the browser supports cookies byattempting to set and retrieve a cookie

CONFIGURING SESSION STATE CONT..

Page 29: Ch05 state management

29

TimeoutThis 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;

CONFIGURING SESSION STATE CONT..

Page 30: Ch05 state management

30

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

SECURING SESSION STATE

Page 31: Ch05 state management

31

Application state 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.

APPLICATION STATE

Page 32: Ch05 state management

32

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();

}

APPLICATION STATE CONT..

Page 33: Ch05 state management

33

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();

}

APPLICATION STATE CONT..

Page 34: Ch05 state management

34

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.

APPLICATION STATE CONT..