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
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
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
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
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
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
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
6
View state information is stored in a single Base64-encoded string that looks like this:
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…
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
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
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…
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…
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
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
14
Example below defines a form with two text boxes and a button that posts to a page named CrossPage2.aspx:
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…
16
If you want to get more specific details, such as control values, you need to cast the PreviousPage reference to the appropriate type.
Don’t have flexibility to deal with situations where more than one page trigger cross-page postback
CROSS PAGE POSTING CONT…
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
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…
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…
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
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
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…
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
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…
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
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. -->
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…
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..
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..
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.