Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


ASP.NET Simplifies State Management in Web Applications : Page 4

If you're tired of writing state management code in your Web applications, you'll be happy to know that ASP.NET not only greatly simplifies the process, but also solves some of the classic ASP Session object's problems, such as using Sessions with Web farms, and persisting state data.

Evaluating Other ASP.NET State Maintenance Options
You aren't limited to using ASP.NET Viewstate to maintain state data. In fact, Viewstate automatically stores only control state, and is less useful for persisting other values between pages or sessions even though—as you've seen—you can modify it programatically. In the rest of this article, you'll see how to use these other state maintenance options.

Maintaining State with Cookies.
A cookie is basically a small piece of information sent by the Web server to be written to the Web browser. Subsequent requests by the Web browser will send the cookie back to the server.

The syntax for creating a cookie is:

Response.Cookies(NameOfCookie)(key) = value

The cookie behaves much like Viewstate, with the notable exception that a cookie transcends pages while Viewstate is only valid within a single page.

Consider the following example:.

If IsPostBack Then '---retrieves the cookies value--- Response.Write(Request.Cookies _ ("Page4Cookies")("timeRequested")) Response.Write(Request.Cookies _ ("Page4Cookies")("country")) Else '---sets the cookies--- Response.Cookies("Page4Cookies")("timeRequested") = _ DateTime.Now Response.Cookies("Page4Cookies")("country") = "SINGAPORE" End If

In the preceding code, when a page is loaded for the first time (IsPostBack = False), the server sets two cookies—timeRequested and country. When a postback occurs, the server retrieves the cookie values. Note that the cookies created in this example are called session cookies, which are name/value pairs stored in the client's memory. Session cookies apply to a single browser instance. When the user closes that browser instance, the session cookies are destroyed. To create cookies that retain their values between browser instances, you must create persistent cookies, which reside on the user's hard drive. To create a persistent cookie, add an expiration time to the cookie. For example:

Response.Cookies("Page4Cookies").Expires = _ DateTime.Now.AddMinutes(5) Response.Cookies("Page4Cookies")("timeRequested") = _ Date.Now

The cookies will now expire in five minutes after they have been saved on the Web browser. You can verify this by examining your browser cache as shown in Figure 5.

Figure 5: The cookies are stored in the folder designated as your browser cache.
Maintaining State on the Server with the Session Object
Storing state information on the client side using Viewstate reduces server load at the cost of increasing the network traffic and the client workload, so it's not suitable when you need to maintain a large amount of information between pages. Also, there is a practical limit as to how much information you can store on the client side. Viewstate also poses a security problem. Even though the Viewstate value is hashed, it is nonetheless possible for a malicious user to tamper with it.

In classic ASP, you use the Session object to maintain state between pages. ASP.NET extends the Session object to solve some problems with the classic ASP version. Before discussing the extensions, here's a brief review on how classic ASP establishes a Session.

  1. A browser requests a page from the server for the first time.
  2. The server responds with the requested page and sets a cookie containing the Session ID.
  3. The browser requests additional pages from Web server, passing the cookie containing the Session ID back to the server with each request.
  4. When the requested pages contain code to create Session variables, the ASP engine creates the variables in the Web server's memory using the Session ID as a key.
  5. Subsequent ASP pages can access the Session variables created earlier (based on the Session ID).
A few things to note:

  1. The Session variables are stored in the Web server's memory. If an application uses five session variables on average, 100 concurrent users will require 500 session variables. This increases the memory requirements of the Web server. Hence you should use Session variables sparingly.
  2. Session variables are stored in volatile memory, so if the Web server shuts down or crashes, all the values will be lost.
  3. Sessions are problematic in a Web server farm. The Session variables are stored only on the Web server that created them. Subsequent requests from the same user might be rerouted to another Web server, from which the stored Session variables will be inaccessible.
The ASP.NET Session object solves many of these problems. Figure 6 shows a page with tracing enabled. You can see the Session ID generated when a request is made to the Web server. When you refresh this page, you should see the same Session ID.

Figure 6. Turning Tracing on shows the Session ID generated (or retrieved) for a request.
However, if you remove the Session_Start event in Global.asax file, an interesting thing occurs; the Session ID now changes every time you refresh or postback the page. The ASP.NET framework automatically turns off session support when the event handler is not present. You can also explicitly turn off Session support explicitly by modifying the application's web.config file:

<sessionState mode="Off" ... />

Conversely, to enable session support, you need to:

  • Add the Session_Start event to the global.asx file, and
  • Use the Session object in your code
After enabling Sessions, you can add some code to a Web Form:

Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load Session("requestedTime") = DateTime.Now End Sub

When the browser requests this Web Form, the code saves the time of the request into a Session variable called requestedTime.

To prove that the value was saved correctly, you can add a second Web Form (Webform2.aspx) to the project:

Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load Response.Write("Webform1.aspx was requested at " _ & Session("requestedTime")) End Sub

To run this project, first load Webform1.aspx, and then browse to Webform2.aspx. Webform2.aspx will display the date and time you requested Webform1.aspx. Figure 7 shows the Session variable and its value.

Figure 7: Trace-enabled display shows the value of the Session variable and the SessionID cookie.

Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date