programming for the web and programming for the desktop is state management how you store information over the lifetime of your application.
This information can be as simple as a users name, or as complex as a stuffed-full shopping cart for an e-commerce store.
In a web application, Thousands of users can simultaneously run the same application on the same computer (the web server). In this section Youll explore different storage options, including view state, session state, and custom cookies
Youll also learn how to transfer information from page to page using cross-page posting and the query string. In a typical web request, the client connects to the web server and requests a page.
When the page is delivered, the connection is closed, and the web server clears any information it has about the client.
View State One of the most common ways to store information is in view state.
View state uses a hidden field that ASP.NET automatically inserts in the final, rendered HTML of a web page.
ViewState.Add ("Name", Dipti");
String strName = ViewState ["Name"];
The ViewState Collection
Advantages : Easy to implement. No server resources are required
Disadvantages : Its tightly bound to a specific page. If the user navigates to another page, this information is lost.
It does not have any support on mobile devices. - Client Side or Server Side ?
- Use Server Resource ?
- Easy to implement ?
- Support Encryption Decryption?
- Timeout
Client Side
No
Yes
Yes
No Cross-Page Posting (Transferring Information Between Pages) The infrastructure that supports cross-page postbacks is a new property named PostBackUrl
To use cross-posting, you simply set PostBackUrl to the name of another web form
When the user clicks the button, the page will be posted to that new URL with the values from all the input controls on the current page.
Now if you load this page and click the button, the page will be posted back to CrossPage2.aspx.
At this point, the CrossPage2.aspx page can interact with CrossPage1.aspx using the Page.PreviousPage property an event handler that grabs the title from the previous page and displays it: Note that this page checks for a null reference before attempting to access the PreviousPage object.
If its a null reference, no cross-page postback took place.
Getting More Information from the Source Page To get more specific details, such as control values.
you need to cast the PreviousPage reference to the appropriate page class. Crosspage 1.aspx
} } } The Query String Another common approach is to pass information using a query string in the URL.
This approach is commonly found in search engines.
For example, if you perform a search on the Google website, youll be redirected to a new URL that incorporates your search parameters.
http://www.google.com/search?q=organic+gardenin g
The query string is the portion of the URL after the question mark.
The receiving page has an easier way to with the query string.
Note : Information is always retrieved as a string, which can then be converted to another simple data type.
If you attempt to retrieve a value that isnt present in the query string, youll get a null reference.
Second page which receive the query string Limitations of QueryString Information is limited. Many browsers impose a limit on the length of a URL (usually from 1KB to 2KB).
Information is clearly visible to the user and to anyone.
URL Encoding With URL encoding, special characters are replaced by escaped character sequences starting with the percent sign (%), followed by a two-digit hexadecimal representation. For example, the & character becomes %26
Cookies Cookies provide another way that you can store information for later use.
Cookies are small files that are created on the clients hard drive
Advantage of cookies One advantage of cookies is that they work transparently without the user being aware that information needs to be stored.
They also can be easily used by any page in your application.
Before you can use cookies, you should import the System.Net namespace
We retrieve cookies from the Request object, and you set cookies using the Response object.
To set a cookie, just create a new HttpCookie object. You can then fill it with string information
A Cookie Example HttpCookie mycookie = new HttpCookie(lname"); mycookie.Value = patil"; Or HttpCookie mycookie = new HttpCookie(); myCookie.Values.Add(lname", patil");
// Setting cookie path myCookie.Path = "/forums";
// Deleting a cookie myCookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(mycookie);
// Retrive the cookie Label1.Text= Request.Cookies[lname"].ToString();
Drawback of cookies Store simple string information.
Easily accessible and readable if the user finds and opens the corresponding file.
Poor choice for complex or private information or large amounts of data.
Some users disable cookies on their browsers, which will cause problems for web applications that require them.
Session State Allows you to store any type of data in memory on the server.
The information is protected, because it is never transmitted to the client, and its uniquely bound to a specific session
Every client that accesses the application has a different session and a distinct collection of information
Session Tracking ASP.NET tracks each session using a unique 120-bit identifier
ASP.NET uses a proprietary algorithm to generate this value, thereby guaranteeing that the number is unique and its random enough that a malicious user cant reverse-engineer or guess what session ID a given client will be using This ID is the only piece of session-related information that is transmitted between the web server and the client.
For this system to work, the client must present the appropriate session ID with each request. You can accomplish this in two ways:
Using cookies
Using modified URL
Using cookies: In this case, the session ID is transmitted in a special cookie (named ASP.NET_SessionId), which ASP.NET creates automatically when the session collection is used. This is the default, and its also the same approach that was used in earlier versions of ASP.
Using modified URLs: In this case, the session ID is transmitted in a specially modified URL. This allows you to create applications that use session state with clients that dont support cookies.
Using Session State You can interact with session state using the System.Web.SessionState.HttpSessionState class, which is provided in an ASP.NET web page as the built-in Session object
The syntax for adding items to the collection and retrieving them is basically the same as for adding items to a pages view state. 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 due to inactivity.
If your web page code ends the session by calling the Session.Abandon() method.
HttpSessionState Members
Session Example //Storing informaton in session state
Label1.Text = "Session ID: " + Session.SessionID; Label1.Text += "<br />Number of Objects:"+ Session.Count.ToString(); Label1.Text += "<br />Mode: " + Session.Mode.ToString(); Label1.Text += "<br />Is Cookieless: "+ Session.IsCookieless.ToString(); Label1.Text += "<br />Is New: "+ Session.IsNewSession.ToString(); Label1.Text += "<br />Timeout (minutes): "+ Session.Timeout.ToString(); } Session Example Application State Application state allows you to store global objects that can be accessed by any client.
Application object will not have any default expiration period.
Whenever the web server has been restarted or stopped then the information maintained by the application object will be lost.
If any data is stored on the application object then that information will be shared upon all the users accessing the web server.
Since the information is shared among all the users, it is advisable to lock and unlock the application object as per requirement. Application State Example protected void Page_Load(object sender, EventArgs e) { string x, y; Application.Lock(); x = Application["A"].ToString(); y = Application["B"].ToString(); Application.UnLock(); TextBox1.Text = x; TextBox2.Text = y; } protected void Button1_Click(object sender, EventArgs e) { Session.Abandon(); } Global.asax <%@ Application Language="C#" %> <script runat="server"> void Application_Start(object sender, EventArgs e) { Application.Lock(); Application["A"] = 0; Application["B"] = 0; Application.UnLock(); } void Application_End(object sender, EventArgs e) { // Code that runs on application shutdown }
void Session_Start(object sender, EventArgs e) { int x, y; Application.Lock(); x = int.Parse(Application["A"].ToString()) + 1; y = int.Parse(Application["B"].ToString()) + 1; Application["A"] = x; Application["B"] = y; Application.UnLock(); } void Session_End(object sender, EventArgs e) { int c; Application.Lock(); c = int.Parse(Application["B"].ToString()) - 1; Application["B"] = c; Application.UnLock(); } </script>