Pages

Men

rh

4/25/2013

ASP.Net State Management

ASP.Net State Management
Introduction:
State management is the process by which you maintain state and page information over multiple requests for the same or different pages. As is true for any HTTP-based technology, A Web application is stateless. A new instance of the Web page is created each time the page is requested from the server.

This would ordinarily mean that all information associated with the page and its controls would be lost with each round trip. Furthermore, pages are destroyed and re-created with each round trip to the server; therefore, page information will not exist beyond the life cycle of a single page.

For example, if a user enters information into a text box on an HTML Web page, that information is sent to the server, but is not returned to the client. To overcome this limitation of Web programming, the ASP.NET page framework includes several state-management features.
Asp.Net State Management:

ASP.NET provides multiple ways to maintain state between server round trips. Which of these options you choose depends heavily upon your application, and it should be based on the following criteria:

How much information do you need to store?
Does the client accept persistent or in-memory cookies?

Do you want to store the information on the client or on the server?

Is the information sensitive?
What performance and bandwidth criteria do you have for your application?

What are the capabilities of the browsers and devices that you are targeting?

Do you need to store information per user?
How long do you need to store the information?
Do you have a Web farm (multiple servers), a Web garden (multiple processes on one machine), or a single process that serves the application?

Asp.Net State Management options can be divided into two categories:
I. Client-Side Management
II. Server-Side Management

Client-Side State Management Options
Storing page information using client-side options doesn't use server resources. These options typically have minimal security but fast server performance because the demand on server resources is modest. However, because you must send information to the client for it to be stored, there is a practical limit on how much information you can store this way.
The following are the client-side state management options that ASP.NET supports:
View state
Hidden fields
Cookies
Query strings
Server-Side State Management Options
Server-side options for storing page information typically have higher security than client-side options, but they can use more Web server resources, which can lead to scalability issues when the size of the information store is large. ASP.NET provides several options to implement server-side state management.
The following are the server-side state management options that ASP.NET supports:
Application state
Session state
Profile properties
Database support
Client Side State Management:
View State:
The ViewState property provides a dictionary object for retaining values between multiple requests for the same page. This is the default method that the page uses to preserve page and control property values between round trips.

When the page is processed, the current state of the page and controls is hashed into a string and saved in the page as a hidden field, or multiple hidden fields if the amount of data stored in the ViewState property exceeds the specified value in the MaxPageStateFieldLength property. When the page is posted back to the server, the page parses the view-state string at page initialization and restores property information in the page.
You can use view state to store your own page-specific values across round trips when the page posts back to itself. For example, if your application is maintaining user-specific information — that is, information that is used in the page but is not necessarily part of any control — you can store it in view state.

Data Types You Can Store in View State
You can store objects of Strings, Integers, Boolean values, Array objects, ArrayList objects, Hash tables, and Custom type converters in view state:
You can store other types of data as well, but the class must be compiled with the Serializable attribute so that view state can serialize them into XML.

Advantages of using view state are:
No server resources are required: The view state is contained in a structure within the page code.
Simple implementation: View state does not require any custom programming to use. It is on by default to maintain state data on controls.
Enhanced security features: The values in view state are hashed, compressed, and encoded for Unicode implementations, which provides more security than using hidden fields.

Disadvantages of using view state are:
Performance considerations: Because the view state is stored in the page itself, storing large values can cause the page to slow down when users display it and when they post it. This is especially relevant for mobile devices, where bandwidth is often a limitation.
Device limitations: Mobile devices might not have the memory capacity to store a large amount of view-state data.

Potential security risks: The view state is stored in one or more hidden fields on the page. Although view state stores data in a hashed format, it can still be tampered with. The information in the hidden field can be seen if the page output source is viewed directly, creating a potential security issue.
Hidden Fields:
In Asp.Net, you can use the HTML standard hidden fields in a Web form to store page specific information. A hidden field does not render in a web browser. However, you can set the properties of the hidden field. When a page is submitted to server, the content of a hidden field is sent in the HTTPForm collection along with the values or other controls
A hidden field stores a single variable in its value property and must be explicitly added to the page. In ASP.Net, the HtmlInputHidden control provides the hidden field functionality.
Advantages of using Hidden Form fields:
The hidden filed can store page-specific information without accessing any Web server or Web browser resource.
The hidden field can be easily implemented in an ASP.Net web form page.
Disadvantages of using Hidden Form fields:
You can view the information stored in hidden fields by accessing the source of the Web page. Therefore, the values stored in hidden form fields are not very secure.
The hidden filed does not support more than a single value field to store information.
The hidden fields are stored in a page. Therefore, storing large values in hidden form fields can slow down the processing of the page.
Cookies
A cookie is a small amount of data that is stored either in a text file on the client file system or in-memory in the client browser session. It contains site-specific information that the server sends to the client along with page output. Cookies can be temporary (with specific expiration times and dates) or persistent.

You can use cookies to store information about a particular client, session, or application. The cookies are saved on the client device, and when the browser requests a page, the client sends the information in the cookie along with the request information. The server can read the cookie and extract its value. A typical use is to store a token (perhaps encrypted) indicating that the user has already been authenticated in your application.

The browser is responsible for managing cookies on a user system. Cookies are sent to the browser via the HttpResponse object that exposes a collection called Cookies. You can access the HttpResponse object as the Response property of your Page class. Any cookies that you want to send to the browser must be added to this collection.

When creating a cookie, you specify a Name and Value. Each cookie must have a unique name so that it can be identified later when reading it from the browser. Because cookies are stored by name, naming two cookies the same will cause one to be overwritten.

You can also set a cookie's date and time expiration. Expired cookies are deleted by the browser when a user visits the site that wrote the cookies. The expiration of a cookie should be set for as long as your application considers the cookie value to be valid. For a cookie to effectively never expire, you can set the expiration date to be 50 years from now.

If you do not set the cookie's expiration, the cookie is created but it is not stored on the user's hard disk. Instead, the cookie is maintained as part of the user's session information. When the user closes the browser, the cookie is discarded. A non-persistent cookie like this is useful for information that needs to be stored for only a short time or that for security reasons should not be written to disk on the client computer.

For example, non-persistent cookies are useful if the user is working on a public computer, where you do not want to write the cookie to disk.
You can add cookies to the Cookies collection in a number of ways. The following example shows two methods to write cookies:
Visual Basic
Response.Cookies ("userName").Value = "patrick"
Response.Cookies ("userName").Expires = DateTime.Now.AddDays (1)

Dim aCookie As New HttpCookie ("lastVisit")
aCookie.Value = DateTime.Now.ToString()
aCookie.Expires = DateTime.Now.AddDays(1)
Response.Cookies.Add (aCookie)
C#
Response.Cookies["userName"].Value = "patrick";
Response.Cookies["userName"].Expires = DateTime.Now.AddDays(1);
HttpCookie aCookie = new HttpCookie("lastVisit");
aCookie.Value = DateTime.Now.ToString();
aCookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(aCookie);
The example adds two cookies to the Cookies collection, one named userName and the other named lastVisit. For the first cookie, the values of the Cookies collection are set directly. You can add values to the collection this way because Cookies derives from a specialized collection of type NameObjectCollectionBase.
For the second cookie, the code creates an instance of an object of type HttpCookie, sets its properties, and then adds it to the Cookies collection via the Add method. When you instantiate an HttpCookie object, you must pass the cookie name as part of the constructor.
Both examples accomplish the same task, writing a cookie to the browser. In both methods, the expiration value must be of type DateTime. However, the lastVisited value is also a date-time value. Because all cookie values are stored as strings, the date-time value has to be converted to a String.

Cookies with More Than One Value:
You can also store multiple name-value pairs in a single cookie. The name-value pairs are referred to as subkeys. For example, instead of creating two separate cookies named userName and lastVisit, you can create a single cookie named userInfo that has the subkeys userName and lastVisit.

A cookie with subkeys also helps you limit the size of cookie files. Cookies are usually limited to 4096 bytes and you can't store more than 20 cookies per site. By using a single cookie with subkeys, you use fewer of those 20 cookies that your site is allotted. In addition, a single cookie takes up about 50 characters for overhead (expiration information, and so on), plus the length of the value that you store in it, all of which counts toward the 4096-byte limit. If you store five subkeys instead of five separate cookies, you save the overhead of the separate cookies and can save around 200 bytes.

The following example shows two ways to write the same cookie, each with two subkeys:
Visual Basic
Response.Cookies("userInfo")("userName") = "patrick"
Response.Cookies("userInfo")("lastVisit") = DateTime.Now.ToString()
Response.Cookies("userInfo").Expires = DateTime.Now.AddDays(1)
Dim aCookie As New HttpCookie("userInfo")
aCookie.Values("userName") = "patrick"
aCookie.Values("lastVisit") = DateTime.Now.ToString()
aCookie.Expires = DateTime.Now.AddDays(1)
Response.Cookies.Add(aCookie)

C#
Response.Cookies["userInfo"]["userName"] = "patrick";
Response.Cookies["userInfo"]["lastVisit"] = DateTime.Now.ToString();
Response.Cookies["userInfo"].Expires = DateTime.Now.AddDays(1);
HttpCookie aCookie = new HttpCookie("userInfo");
aCookie.Values["userName"] = "patrick";
aCookie.Values["lastVisit"] = DateTime.Now.ToString();
aCookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(aCookie);
Reading Cookies:
When a browser makes a request to the server, it sends the cookies for that server along with the request. In your ASP.NET applications, you can read the cookies using the HttpRequest object, which is available as the Request property of your Page class.

The structure of the HttpRequest object is essentially the same as that of the HttpResponse object, so you can read cookies out of the HttpRequest object much the same way you wrote cookies into the HttpResponse object. The following code example shows two ways to get the value of a cookie named username and display its value in a Label control:
Visual Basic
If Not Request.Cookies("userName") Is Nothing Then
Label1.Text = Server.HtmlEncode(Request.Cookies("userName").Value)
End If
If Not Request.Cookies("userName") Is Nothing Then
Dim aCookie As HttpCookie = Request.Cookies("userName")
Label1.Text = Server.HtmlEncode(aCookie.Value)
End If
C#

if(Request.Cookies["userName"] != null)
Label1.Text = Server.HtmlEncode(Request.Cookies["userName"].Value);

if(Request.Cookies["userName"] != null)
{
HttpCookie aCookie = Request.Cookies["userName"];
Label1.Text = Server.HtmlEncode(aCookie.Value);
}
Before trying to get the value of a cookie, you should make sure that the cookie exists; if the cookie does not exist, you will get a NullReferenceException exception.

Advantages of using cookies are:
Configurable expiration rules: The cookie can expire when the browser session ends, or it can exist indefinitely on the client computer, subject to the expiration rules on the client.
No server resources are required: The cookie is stored on the client and read by the server after a post.

Simplicity: The cookie is a lightweight, text-based structure with simple key-value pairs.
Data persistence: Although the durability of the cookie on a client computer is subject to cookie expiration processes on the client and user intervention, cookies are generally the most durable form of data persistence on the client.
Disadvantages of using cookies are:
Size limitations: Most browsers place a 4096-byte limit on the size of a cookie, although support for 8192-byte cookies is becoming more common in newer browser and client-device versions.

User-configured refusal: Some users disable their browser or client device's ability to receive cookies, thereby limiting this functionality.

Potential security risks: Cookies are subject to tampering. Users can manipulate cookies on their computer, which can potentially cause a security risk or cause the application that is dependent on the cookie to fail. Also, although cookies are only accessible by the domain that sent them to the client, hackers have historically found ways to access cookies from other domains on a user's computer. You can manually encrypt and decrypt cookies, but it requires extra coding and can affect application performance because of the time that is required for encryption and decryption.

Query Strings
A query string is information that is appended to the end of a page URL.
You can use a query string to submit data back to your page or to another page through the URL. Query strings provide a simple but limited way of maintaining some state information. For example, query strings are an easy way to pass information from one page to another, such as passing a product number to another page where it will be processed.

Advantages of using query strings are:

No server resources are required: The query string is contained in the HTTP request for a specific URL.
Widespread support: Almost all browsers and client devices support using query strings to pass values.
Simple implementation: ASP.NET provides full support for the query-string method, including methods of reading query strings using the Params property of the HttpRequest object.

Disadvantages of using query strings are:
Potential security risks: The information in the query string is directly visible to the user via the browser's user interface. A user can bookmark the URL or send the URL to other users, thereby passing the information in the query string along with it. If you are concerned about any sensitive data in the query string, consider using hidden fields in a form that uses POST instead of using query strings.
Limited capacity: Some browsers and client devices impose a 2083-character limit on the length of URLs.

Client-Side State Management Summary
The following table lists the client-side state management options that are available with ASP.NET, and provides recommendations about when you should use each option.
State Management
Recommended usage
View state
Use when you need to store small amounts of information for a page that will post back to itself. Using the ViewState property provides functionality with basic security.
Hidden fields
Use when you need to store small amounts of information for a page that will post back to itself or to another page, and when security is not an issue.
Cookies
Use when you need to store small amounts of information on the client and security is not an issue.
Query string
Use when you are transferring small amounts of information from one page to another and security is not an issue.
Server Side State Management

Application State:
Application state is a data repository available to all classes in an ASP.NET application. Application state is stored in memory on the server and is faster than storing and retrieving information in a database. Unlike session state, which is specific to a single user session, application state applies to all users and sessions. Therefore, application state is a useful place to store small amounts of often-used data that does not change from one user to another.

ASP.NET provides application state via the HttpApplicationState class as a method of storing global application-specific information that is visible to the entire application. Application-state variables are global variables for an ASP.NET application. You can store your application-specific values in application state, which is then managed by the server. Data that is shared by multiple sessions and does not change often is the ideal type of data to insert into application-state variables.

Advantages of using application state are:
Simple implementation Application state is easy to use, familiar to ASP developers, and consistent with other .NET Framework classes.
Application scope Because application state is accessible to all pages in an application, storing information in application state can mean keeping only a single copy of the information (for instance, as opposed to keeping copies of information in session state or in individual pages).

Disadvantages of using application state are:
Application scope: The scope of application state can also be a disadvantage. Variables stored in application state are global only to the particular process the application is running in, and each application process can have different values. Therefore, you cannot rely on application state to store unique values or update global counters in Web-garden and Web-farm server configurations.

Limited durability of data: Because global data that is stored in application state is volatile, it will be lost if the Web server process containing it is destroyed, such as from a server crash, upgrade, or shutdown.

Resource requirements: Application state requires server memory, which can affect the performance of the server as well as the scalability of the application.

Session State:
ASP.NET provides a session state, which is available as the HttpSessionState class, as a method of storing session-specific information that is visible only within the session. ASP.NET session state identifies requests from the same browser during a limited time window as a session, and provides the ability to persist variable values for the duration of that session.
You can store your session-specific values and objects in session state, which is then managed by the server and available to the browser or client device. The ideal data to store in session-state variables is short-lived, sensitive data that is specific to an individual session.

The following example shows two methods to store data in session:

Visual Basic
Session("FirstName") = FirstNameTextBox.Text
Session("LastName") = LastNameTextBox.Text

C#
Session["FirstName"] = FirstNameTextBox.Text;
Session["LastName"] = LastNameTextBox.Text;

Reading data from Session:

Visual Basic
‘When retrieving an object from session state, cast it to the appropriate type.
Dim strStockPicks As String = CType(Session("StockPicks"), String)

' Write the modified stock picks list back to session state.
Session("StockPicks") = stockPicks

C#
// When retrieving an object from session state, cast it to the appropriate type.
String stockPicks = (String) Session ["StockPicks"];

// Write the modified stock picks list back to session state.
Session ["StockPicks"] = stockPicks;

Cookieless SessionIDs:

By default, the SessionID value is stored in a non-expiring session cookie in the browser. However, you can specify that session identifiers should not be stored in a cookie by setting the cookieless attribute to true in the sessionState section of the Web.config file.

The following example shows a Web.config file that configures an ASP.NET application to use cookieless session identifiers.



regenerateExpiredSessionId="true" />

ASP.NET maintains cookieless session state by automatically inserting a unique session ID into the page's URL. For example, the following URL has been modified by ASP.NET to include the unique session ID lit3py55t21z5v55vlm25s55:

http://www.example.com/(S(lit3py55t21z5v55vlm25s55))/orderform.aspx

When ASP.NET sends a page to the browser, it modifies any links in the page that use an application-relative path by embedding a session ID value in the links. (Links with absolute paths are not modified.) Session state is maintained as long as the user clicks links that have been modified in this manner. However, if the client rewrites a URL that is supplied by the application, ASP.NET may not be able to resolve the session ID and associate the request with an existing session. In that case, a new session is started for the request.

The session ID is embedded in the URL after the slash that follows the application name and before any remaining file or virtual directory identifier. This enables ASP.NET to resolve the application name before involving the SessionStateModule in the request.

Advantages of using session state are:
Simple implementation: The session-state facility is easy to use, familiar to ASP developers, and consistent with other .NET Framework classes.
Session-specific events: Session management events can be raised and used by your application.

Data persistence: Data placed in session-state variables can be preserved through Internet Information Services (IIS) restarts and worker-process restarts without losing session data because the data is stored in another process space. Additionally, session-state data can be persisted across multiple processes, such as in a Web farm or a Web garden.
Platform scalability: Session state can be used in both multi-computer and multi-process configurations, therefore optimizing scalability scenarios.

Cookieless support: Session state works with browsers that do not support HTTP cookies, although session state is most commonly used with cookies to provide user identification facilities to a Web application. Using session state without cookies, however, requires that the session identifier be placed in the query string, which is subject to the security issues stated in the query string section of this topic.
Extensibility: You can customize and extend session state by writing your own session-state provider. Session state data can then be stored in a custom data format in a variety of data storage mechanisms, such as a database, an XML file, or even to a Web service.

Disadvantage of using session state are:
 Performance considerations: Session-state variables stay in memory until they are either removed or replaced, and therefore can degrade server performance. Session-state variables that contain blocks of information, such as large datasets, can adversely affect Web-server performance as server load increases.
profile
A SP.NET provides a feature called profile properties, which allows you to store user-specific data. It is similar to session state, except that unlike session state, the profile data is not lost when a user's session expires. The profile properties feature uses an ASP.NET profile, which is stored in a persistent format and associated with an individual user.

The ASP.NET profile allows you to easily manage user information without requiring you to create and maintain your own database. In addition, the profile makes the user information available using a strongly typed API that you can access from anywhere in your application. You can store objects of any type in the profile. The ASP.NET profile feature provides a generic storage system that allows you to define and maintain almost any kind of data while still making the data available in a type-safe manner.

Advantages of using profile properties are:
Data persistence: Data placed in profile properties is preserved through IIS restarts and worker-process restarts without losing data because the data is stored in an external mechanism. Additionally, profile properties can be persisted across multiple processes, such as in a Web farm or a Web garden.

Platform scalability: Profile properties can be used in both multi-computer and multi-process configurations, therefore optimizing scalability scenarios.

Extensibility: In order to use profile properties, you must configure a profile provider. ASP.NET includes a SqlProfileProvider class that allows you to store profile data in a SQL database, but you can also create your own profile provider class that stores profile data in a custom format and to a custom storage mechanism, such as an XML file, or even to a Web service. For more information, see ASP.NET Profile Providers and Implementing a Profile Provider.

Disadvantages of using profile properties are:
Performance considerations: Profile properties are generally slower than using session state because instead of storing data in memory, the data is persisted to a data store.
Additional configuration requirements: Unlike session state, the profile properties feature requires a considerable amount of configuration to use. To use profile properties, you must not only configure a profile provider, but you must pre-configure all of the profile properties that you want to store. For more information, see ASP.NET Profile Properties Overview and Defining ASP.NET Profile Properties.

Data maintenance: Profile properties require a certain amount of maintenance. Because profile data is persisted to non-volatile storage, you must make sure that your application calls the appropriate cleanup mechanisms, which are provided by the profile provider, when data becomes stale.

Database Support:
In some cases, you might want to use database support to maintain state on your Web site. Typically, database support is used in conjunction with cookies or session state. For example, it is common for an e-commerce Web site to maintain state information by using a relational database for the following reasons:
Security
Personalization
Consistency
Data mining

The following are typical features of a cookie-supported database Web site:

Security: The visitor types an account name and password into a site logon page. The site infrastructure queries the database with the logon values to determine whether the user has rights to utilize your site. If the database validates the user information, the Web site will distribute a valid cookie containing a unique ID for that user on that client computer. The site grants access to the user.

Personalization: With security information in place, your site can distinguish each user by reading the cookie on the client computer. Typically, sites have information in the database that describes the preferences of a user (identified by a unique ID). This relationship is known as personalization. The site can research the user's preferences using the unique ID contained in the cookie, and then place content and information in front of the user that pertains to the user's specific wishes, reacting to the user's preferences over time.

Consistency: If you have created a commerce Web site, you might want to keep transactional records of purchases made for goods and services on your site. This information can be reliably saved in your database and referenced by the user's unique ID. It can be used to determine whether a purchase transaction has been completed, and to determine the course of action if a purchase transaction fails. The information can also be used to inform the user of the status of an order placed using your site.

Data mining: Information about your site usage, your visitors, or your product transactions can be reliably stored in a database. For example, your business development department might want to use the data collected from your site to determine next year's product line or distribution policy. Your marketing department might want to examine demographic information about users on your site. Your engineering and support departments might want to look at transactions and note areas where your purchasing process could be improved. Most enterprise-level relational databases, such as Microsoft SQL Server, contain an expansive toolset for most data mining projects.

By designing the Web site to repeatedly query the database by using the unique ID during each general stage in the above scenario, the site maintains state. In this way, the user perceives that the site is remembering and reacting to him or her personally.

Advantages of using a database to maintain state are:
Security: Access to databases requires rigorous authentication and authorization.

Storage capacity: You can store as much information as you like in a database.

Data persistence: Database information can be stored as long as you like, and it is not subject to the availability of the Web server.

Robustness and data integrity: Databases include various facilities for maintaining good data, including triggers and referential integrity, transactions, and so on. By keeping information about transactions in a database (rather than in session state, for example), you can recover from errors more readily.

Accessibility: The data stored in your database is accessible to a wide variety of information-processing tools.

Widespread support: There is a large range of database tools available, and many custom configurations are available.

Disadvantages of using a database to maintain state are:
Complexity: Using a database to support state management requires that the hardware and software configurations be more complex.

Performance considerations: Poor construction of the relational data model can lead to scalability issues. Also, leveraging too many queries to the database can adversely affect server performance.

Server-Side Method State Management Summary

The following table lists the server-side state management options that are available with ASP.NET, and provides recommendations about when you should use each option.
State management option
Recommended usage

Application state
Use when you are storing infrequently changed, global information that is used by many users, and security is not an issue. Do not store large quantities of information in application state.
Session state

Use when you are storing short-lived information that is specific to an individual session and security is an issue. Do not store large quantities of information in session state. Be aware that a session-state object will be created and maintained for the lifetime of every session in your application. In applications hosting many users, this can occupy significant server resources and affect scalability.

Profile properties
Use when you are storing user-specific information that needs to be persisted after the user session is expired and needs to be retrieved again on subsequent visits to your application.
Database support

Use when you are storing large amounts of information, managing transactions, or the information must survive application and session restarts. Data mining is a concern, and security is an issue.

Conclusion
State management influences almost every aspect of a Web application’s design, and it is important to understand all the options available for state management as well as their implications for usability, performance, and scalability.

ASP.NET provides four types of state, each of which may be the best choice in different parts of your application. State that is global to an application may be stored in the application state bag, although it is typically preferable to use the new data cache instead of application state in ASP.NET. Client-specific state can be stored either in the session state bag, as client-side cookies, or as view state.

Session state is most commonly used for storing data that should not be sent back and forth with each request, either because it is too large or because the information should not be visible on the Internet. Cookie state is useful for small client-specific pieces of information such as preferences, authentication keys, and session keys.

View state is a useful alternative to session state for information that needs to be retained across posts back to the same page. Finally, enhancements to the session state model in ASP.NET give developers the flexibility to rely on session state even for applications that are deployed on Web farms or Web gardens through remote session storage.

No comments :

Post a Comment