Session State

   

As I mentioned at the beginning of this chapter, there were several ways to handle the state information of a user's visit or session on your web site. All the methods had an inherent problem in one factor or another. Let's look at a few of the problems that some of the solutions used in the past have faced.

Session Object

  • Lost data if web services were stopped and restarted

  • Not very scalable; server resources required

  • Won't work in a web farm

  • Won't work with user's cookies disabled

Cookies

  • Won't work with user's cookies disabled

  • Hidden text boxes

  • Information is exposed to anyone that knows how to view source

  • Can be tampered with if a malicious visitor wants to

  • Work only if a user submits a form

QueryString

  • Exposed in the browser's address bar and can be tampered with, making it less than reliable

Now don't get ridiculously excited because ASP.NET doesn't provide any miraculous answers for these problems, but it does supply reasonable remedies and tools to overcome these problems. Are they foolproof? No. Is there any perfect solution? If there were it would be the only one available in ASP.NET, but there are still a bunch of different methods you can use. So you will still be left with some choices, but they are a bit more solid than they used to be, and if you run a SQL Server there is a totally new option available that is quite interesting. Let's address them one by one and see how .NET addresses the individual problems associated with the different methods.

Sessions

By default, sessions in ASP.NET are just like their counterparts in traditional ASP. When a user visits your web site for the first time, ASP.NET generates a 120-bit unique ID for that user, assigns a piece of the server's memory to that ID, and sets a temporary cookie with that ID on the user's machine to maintain the association between the partition of memory and the visitor.

How to Use Sessions

Using session variables isn't much different than using the StateBag that was discussed earlier, except you use the word Session rather than ViewState to address the object.

Visual Basic .NET session_standard_vb.aspx
<%@ page language="vb" runat="server"%>  <script runat=server>  Sub Page_Load()      Session("OurSession") = "Sessions hold stuff"      OurLabel.Text = Session("OurSession")  End Sub  </script>  <html>  <head>  <title>Session State - Set Get</title>  </head>  <body bgcolor="#FFFFFF" text="#000000">  <asp:label  runat="server" />  </body>  </html> 
C# session_standard_cs.aspx
<%@ page language="c#" runat="server"%>  <script runat=server>  void Page_Load(){     Session["OurSession"] = "Sessions hold stuff";      OurLabel.Text = Session["OurSession"].ToString();  }  </script>  <html>  <head>  <title>Session State - Set Get</title>  </head>  <body bgcolor="#FFFFFF" text="#000000">  <asp:label  runat="server" />  </body>  </html> 

Pretty simple. One thing to take note of is that C# requires you to use the ToString() method to set the label's text property because C# generally doesn't convert data types on the fly, as Visual Basic .NET will do gracefully.

By default, a session has a lifetime of 20 minutes of inactivity. The server releases the memory set aside for that session and discards the data it contains. The timeout of a session is flexible, though. The Session object is really an instance of the HttpSessionState object, which has a property of Timeout.

This timeout property is valued in minutes, so if you want your session to time out after 10 minutes of inactivity, you need to insert the following code on your page in both Visual Basic .NET and C#.

 Session.Timeout = 10 

You can also set the session's timeout property across the application by placing the <sessionstate/> tag inside the <system.web> section of the web.config file.

 <configuration>      <system.web>          <sessionState timeout="10" />      </system.web>  </configuration> 

Pretty simple either way. Again, the first example of setting the timeout is page-specific. In other words, only people that load a page with that code on it will have the timeout property set, whereas setting it in the web.config file sets the timeout application-wide.

As I've implied, each session has a beginning and an end as far as your application is concerned, and ASP.NET gives you a way to use those events in your applications. These events are called Session_Start and Session_End, and they can be referenced in your global.asax file in your application's root folder.

Visual Basic .NET global.asax
<script language="vb" runat=server>  Sub Application_OnStart()      Application("SessionNum") = 0  End Sub  Sub Session_Start()      dim NumSessions as Integer = Application("SessionNum")      Application("SessionNum") = NumSessions + 1  End Sub  Sub Session_End()      dim NumSessions as Integer = Application("SessionNum")      Application("SessionNum") = NumSessions - 1  End Sub  </script> 
C# global.asax
<script language="c#" runat=server>  void Application_OnStart(){     Application["SessionNum"] = 0;  }  void Session_Start(){      int NumSessions = int.Parse(Application["SessionNum"].ToString());      Application["SessionNum"] = NumSessions + 1;  }  void Session_End(){      int NumSessions = int.Parse(Application["SessionNum"].ToString());      Application["SessionNum"] = NumSessions - 1;  }  </script> 

As you can see, whenever a new session starts, an application variable called SessionNum is incremented by one. Whenever a session ends, this application variable is decremented by one. There are other applications for using the Session_Start and Session_End events in your applications, so keep this in your pocket for those occasions.

What you've seen so far is a use of the session in a way that parallels a traditional ASP Session object. ASP.NET provides some methods to overcome some of the session's trouble spots that I mentioned earlier.

In traditional ASP, if the Web Service decides to take a vacation and you need to restart Web Services, all the data that were stored in memory for the people with a current session on the web site would lose their state information. That's too bad if someone is scoping out a $5,000 diamond ring on your jewelry web site and is ready to buy, but the shopping cart has just gotten dumped because of a Web Service restart.

This is how sessions run by default and this is called an InProc session. InProc sessions are "In the same process" in which ASP.NET is running and is the default mode of the SessionState, but there are three alternatives to running InProc. One doesn't take any explanation at all. It is Off, which means that SessionState is disabled.

 <configuration>      <system.web>          <sessionState mode="Off" />      </system.web>  </configuration> 

This information isn't very useful for the discussion here, but for the sake of being thorough I had to mention it. The other two options for SessionState are StateServer and SQLServer. Look first at the StateServer mode and see what problems it helps you overcome.

StateServer

With the StateServer mode, you can cause sessions to be processed either in a separate process on the same web server where you are running your ASP.NET pages, or you can have these sessions processed on a totally different server.

This addresses to one degree or another three of the four issues that session variables have had in traditional ASP. First, because they run in a totally separate process, either on your web server or a server dedicated to handling session information, if there's a problem with the Web Service and you need to stop and restart this service, a user won't lose session information.

Second, it provides a greater path for scalability because you can utilize a machine that is dedicated to handling session information, thus taking the load and responsibility for maintaining this data off your web server. The scalability issues are also coupled with the third issue that StateServer addresses.

Finally, sessions can reach across web farms when you have a machine dedicated to state management. All the machines in your web farm can utilize the same StateServer for their state information.

These possibilities make storing session state information in memory a more viable option. In traditional ASP this type of system for maintaining state was largely frowned upon because of scalability issues.

There are certain things you must do to use StateServer that either runs out of process on your web server or runs on a different server all together.

First, whatever machine you want to run as your StateServer must have a service called ASP.NET State Service. To start that service, go to Start Menu, Settings, Control Panel, Administrative Tools, Services. There you can see the service with that title, and it probably has a Startup Type of Manual. Double-click ASP.NET State Service and set the Startup Type to Automatic. This starts this service immediately and assures that it starts every time the server is rebooted.

Second, you must set up the web.config file so that the mode of SessionState and another attribute of SessionState, called stateConnectionString, are set properly.

Web.config
<configuration>      <system.web>          <sessionState mode="StateServer"              stateConnectionString="tcpip=server:port" />      </system.web>  </configuration> 

The mode attribute needs to be set to StateServer. The stateConnectionString attribute needs to be set to the server name or IP address and port separated by a colon (:). This is required if the mode is set to StateServer.

SQL Server

Another alternative to running session data in the memory of either the web server or a SessionState server is using Microsoft SQL Server to store it in a database.

The reality in using sessions, just like with the StateServer, is that there is absolutely no difference. You set them and get them exactly the same way. The only thing that's different is how the .NET Framework handles the data from there, which depends on the mode that is set in the web.config file.

When you run in SQLServer mode, all your sets and gets of Session variables will cause the information to be written or read from the database rather than from the web server or StateServer's memory. This is another scalable way to handle session information out-of-process, but is not without its drawbacks, either.

First, there is a small performance sacrifice. The benchmarks, articles, and whatever other data I could find all state that using SQLServer for storing session data will result in approximately 75%-80% of the performance of session data being stored in process. The plus side to this is that as the number of users grows, the SQLServer method will scale much better because its limitations for holding and delivering data are much less than those of a web server's memory.

Second, this system was designed with enterprises in mind, and it therefore assumes that you run a dedicated Microsoft SQL Server database server to which you have administrative access. I assume that many readers of this book use Microsoft SQL Server in a shared environment, where this type of access wouldn't be available. Unfortunately, this system wasn't designed for that type of environment.

If you want to enable Microsoft SQL Server as the location where session data is managed, there are a few things that you must do.

You must properly set the mode of sessionState in the web.config file, as follows:

 <configuration>       <system.web>         <sessionState             mode="SQLServer"             sqlConnectionString="data source=server;userid=username;password=password"             timeout="10" />       </system.web>  </configuration> 

Set the mode attribute of the sessionState tag in the web.config file to SQLServer. The other attribute you must provide is sqlConnectionString, which is simply a connection string to your database server with the server path, hostname or IP address, user ID, and password. This provides the .NET Framework with the necessary information to use your database as the session storage unit. But wait…there's more! Your database needs to be prepared, also.

Microsoft has written a nifty little SQL script that you can run from Query Analyzer in SQL Server's Enterprise Manager. Enterprise Manager is the utility that Microsoft provides with SQL Server so you can administer the database server.

The necessary SQL script for preparing your SQL Server to handle sessions is called InstallSQLState.sql and was placed on the server in the <Drive>:\ WINNT\Microsoft.NET\Framework\<version> directory when you installed the .NET Framework. What this script does is create a new database on the server called ASPState and create a bunch of stored procedures that are necessary for managing session data. It also adds two tables to the system database called tempdb.

Let's proceed by opening Enterprise Manager and then selecting and opening the proper database server from the tree menu on the left. After you've done this, go to the Tools menu and select SQL Query Analyzer. From there you can either copy and paste the contents of the InstallSQLState.sql file or open it using File, Open.

After you have the file open or pasted in the window, you must execute it by either pressing the green arrow in the tool bar, through the Query, Execute Query menu option or Pressing F5. This process will take more than an instant to process, so wait until you see the results appear in a second window, as shown in Figure 11.2.

Figure 11.2. Executing the InstallSQLState.sql query in Query Analyzer.
graphics/11fig02.gif

Now you are ready to start using SQL Server for your session information. Let's run the files that I created earlier, called either session_standard_vb.aspx or session_standard_cs.aspx, for Visual Basic .NET and C# respectively.

Visual Basic .NET session_standard_vb.aspx
<%@ page language="vb" runat="server"%>  <script runat=server>  Sub Page_Load()      Session("OurSession") = "Sessions hold stuff"      OurLabel.Text = Session("OurSession")  End Sub  </script>  <html>  <head>  <title>Session State - Set Get</title>  </head>  <body bgcolor="#FFFFFF" text="#000000">  <asp:label  runat="server" />  </body>  </html> 
C# session_standard_cs.aspx
<%@ page language="c#" runat="server"%>  <script runat=server>  void Page_Load(){     Session["OurSession"] = "Sessions hold stuff";      OurLabel.Text = Session["OurSession"].ToString();  }  </script>  <html>  <head>  <title>Session State - Set Get</title>  </head>  <body bgcolor="#FFFFFF" text="#000000">  <asp:label  runat="server" />  </body>  </html> 

The results of this can be seen in Figure 11.3 and they are displayed just as you'd expect. Again, setting and getting session variables when using SQL Server for session storage is not different than using sessions on a web server or a StateServer. You create the session, and then the Text property of the Label server control is set to that session's value. Now take a look at SQL Server and see whether anything happened.

Figure 11.3. To store session data with SQL Server, use the same method of getting and setting session variables as you do when you use in-memory sessions.
graphics/11fig03.gif

In Figure 11.4 you can see that I've opened up a table called ASPStateTempSessions that resides in the tempdb database and was created when I ran the InstallSQLState.sql in Query Analyzer. This table stores SessionID, created and expired date information, timeout length, and the session info, which is stored in <binary> form in the last two columns. For each variable a row is created and affected by your session gets and sets in your ASP.NET pages.

Figure 11.4. SQL Server stores session information in a table called ASPStateTempSessions in the tempdb database.
graphics/11fig04.gif
Going Cookieless

Although this may seem like it's a cookie issue and that it should go in the section where I cover cookies, this is really a session issue. All the mentioned methods of in-process and out-of-process session management use a single in-memory (meaning it isn't written to the user's hard drive) cookie to hold the SessionID so the server knows who is making the request. This is how it associates session data with that user.

What happens with users who have an older (much older) browser that doesn't support cookies, or those who have opted to turn cookie functionality off in their browsers? That person is alienated from using your web site if you use session variables to store session information.

The .NET Framework provides a way around that using a technique called URL munging. Now I forewarn you that I will not use that word again simply because I hate it. I don't know who coined the phrase but I just want to let them I think it's dumb. To me, that word represents the stuff you step in at the bottom of a lake that squishes between you toes and makes you run back to the shore. Yuck!!! From now on I'll use words like embed and such. Thanks for understanding.

To let the .NET Framework know you want to run your application cookieless, you must set another attribute in the sessionState tag in the web.config file named, oddly enough, cookieless.

 <configuration>      <system.web>          <sessionState              cookieless="true"              mode="InProc" />      </system.web>  </configuration> 

Now let's run the session_standard_vb.aspx or session_standard_cs.aspx for Visual Basic .NET and C# respectively and see what happens to our page.

Figure 11.5. The .NET Framework embeds the SessionID information in the URL when running session state with cookieless equal to true.
graphics/11fig05.gif

If you look at the URL in the address bar, you can see that (xxirqxydq33onl55new20u45) is embedded in there between the root address and the ch11 directory. This is how the .NET Framework deals with this issue. It embeds the SessionID at the root of the application for uniformity. This provides the necessary information for ASP.NET to identify the user and properly associate session data.

Again, this method isn't without problems. The first problem is a security issue. A malicious person (idiot) could easily capture the URL and subsequently the person's SessionID and masquerade as them and potentially access sensitive data. The second problem is that the user can mung (okay, one small exception, but I mean it in a totally different way) their own URL. This can cause a loss of association with the session data if the user alters the SessionID.

One more problem is losing the SessionID in certain linking situations. ASP.NET handles embedding the SessionID into hyperlinks with relative paths, but it doesn't embed it into fully qualified paths. A solution for that might be to use an HTMLAnchor server control on your page and set the control's href property during Page_Load so you can retrieve the session's SessionID property and construct the link.

Visual Basic .NET session_url_vb.aspx
<%@ page language="vb" runat="server"%>  <script runat=server>  Sub Page_Load()      OurHref.HRef = "http://aspdotnet/(" + Session.SessionID + ")/ch11/dotnet_page_state. graphics/ccc.gifaspx"  End Sub  </script>  <html>  <head>  <title>Session State - Set Get</title>  </head>  <body bgcolor="#FFFFFF" text="#000000">  <a href="dotnet_page_state.aspx">relative</a><br>  <a  runat="server">full</a>  </body>  </html> 
C# session_url_cs.aspx
<%@ page language="c#" runat="server"%>  <script runat=server>  void Page_Load(){     OurHref.HRef = "http://aspdotnet/(" + Session.SessionID + ")/ch11/dotnet_page_state. graphics/ccc.gifaspx";  }  </script>  <html>  <head>  <title>Session State - Set Get</title>  </head>  <body bgcolor="#FFFFFF" text="#000000">  <a href="dotnet_page_state.aspx">relative</a><br>  <a  runat="server">full</a>  </body>  </html> 

If you plan on using a cookieless session environment, this is something that you need to be mindful of. Make sure that on any link other than those that are relative, you will be responsible for maintaining this ID.

Using Cookies to Maintain Session State

The previous section discussed using session variables to store session state information. Session variables are stored server-side, on the web server, a state server, or Microsoft SQL Server, and they use a single cookie that holds the SessionID to maintain an association between the client machine and the session information stored server-side.

Now we are going to talk about storing much of the information that would be stored in session variables in cookies. For clarity, a cookie is a text file that resides on the client's machine that can be used from the server-side to store and retrieve information. It is a domain-specific mechanism that allows a web server to set and get information in a cookie associated with its own domain.

Because of this layer of security, it is a safe way to store data such as a login, password information, or a customer ID. Cookies are really a great alternative to using server-side session variables because they utilize the client's resources as opposed to server-side resources. The only downfall is that visitors to your web site aren't guaranteed to support them or to have them enabled.

Cookies are controlled and manipulated through the HttpCookie object located in the System.Web namespace. The easiest way to manipulate cookies with .NET is through the HttpRequest and HttpResponse objects. The HttpCookieCollection is a property of each of these objects and is referenced as a property called Cookies. And as you saw in Chapter 4, you reference the Request and Response objects as properties of the page. So to reference the HttpCookieCollection from within your ASP.NET pages you would simply use:

  • Request.Cookies

  • Response.Cookies

From there you address the individual cookies as items of the collection like anything else. Take a look.

Visual Basic .NET cookies_simple_vb.aspx
<%@ page language="vb" runat="server"%>  <script runat=server>  Sub Page_Load()      If Not IsPostBack then          Response.Cookies("Test").Value = "CookieValue"      Else          OurLabel.Text=Request.Cookies("Test").Value      End If  End Sub  </script>  <html>  <head>  <title>Cookie - Simple</title>  </head>  <body bgcolor="#FFFFFF" text="#000000">  <form runat="server">  <asp:Label  runat="server" /><br>  <asp:Button Text="test" runat="server" />  </form>  </body>  </html> 
C# cookies_simple_cs.aspx
<%@ page language="c#" runat="server"%>  <script runat=server>  void Page_Load(){     if (!IsPostBack){         Response.Cookies["Test"].Value = "CookieValue";      }else{         OurLabel.Text=Request.Cookies["Test"].Value;      }  }  </script>  <html>  <head>  <title>Cookie - Simple</title>  </head>  <body bgcolor="#FFFFFF" text="#000000">  <form runat="server">  <asp:Label  runat="server" /><br>  <asp:Button Text="test" runat="server" />  </form>  </body>  </html> 

In Figure 11.6, you can see that the cookie was set to CookieValue during the initial load, and it was retrieved during postback and the value of OurLabel's text property was set to the value of the cookie. Not very difficult. If you come from a traditional ASP background this doesn't look too different from what you're used to, with the exception of the .Value at the end of the Response and Request of the cookies.

Figure 11.6. Setting the value of a cookie with the HttpResponse object and retrieving a cookie with the HttpRequest object is very simple.
graphics/11fig06.gif

This cookie type is one that resides in the memory of the client's machine but doesn't persist after the user closes his browser down and returns. You can control how long a cookie lasts through the Expires property of the HttpCookie object.

Visual Basic .NET cookies_expires_vb.aspx
<%@ page language="vb" runat="server"%>  <script runat=server>  Sub Page_Load()      If Not IsPostBack then          Dim ExpDate as DateTime = Now.AddDays(1)          Response.Cookies("Test").Value = "CookieValue"          Response.Cookies("Test").Expires = ExpDate      Else          OurLabel.Text=Request.Cookies("Test").Value      End If  End Sub  </script>  <html>  <head>  <title>Cookie - Expires</title>  </head>  <body bgcolor="#FFFFFF" text="#000000">  <form runat="server">  <asp:Label  runat="server" /><br>  <asp:Button Text="test" runat="server" />  </form>  </body>  </html> 
C# cookies_expires_cs.aspx
<%@ page language="c#" runat="server"%>  <script runat=server>  void Page_Load(){     if (!IsPostBack){         DateTime ExpDate = DateTime.Now.AddDays(1);          Response.Cookies["Test"].Value = "CookieValue";          Response.Cookies["Test"].Expires = ExpDate;      }else{         OurLabel.Text=Request.Cookies["Test"].Value;      }  }  </script>  <html>  <head>  <title>Cookie - Expires</title>  </head>  <body bgcolor="#FFFFFF" text="#000000">  <form runat="server">  <asp:Label  runat="server" /><br>  <asp:Button Text="test" runat="server" />  </form>  </body>  </html> 

You can use that function and operate just fine. But ASP.NET also provides a deeper level of cookies in that each cookie can have a collection of name-value pairs in addition to a value itself. ASP.NET hasn't changed the way cookies work any more than it has changed the way HTML works. It simply has given additional functions to cookies that aren't inherent without ASP.NET.

The way you address the collection of name-value pairs within each cookie is to use the .Values("name") property rather than just the .Value property. Notice that the collection has the letter S at the end for a plural of Values. Take a look.

Visual Basic .NET cookies_namevalue_vb.aspx
<%@ page language="vb" runat="server"%>  <script runat=server>  Sub Page_Load()      If Not IsPostBack Then          Response.Cookies("Customer").Values("CustomerID") = "100"          Response.Cookies("Customer").Values("OrderID") = "20"      Else          If Not (Request.Cookies("Customer") Is Nothing) Then              OurLabel.Text = Request.Cookies("Customer").Values("CustomerID")              OurLabel2.Text = Request.Cookies("Customer").Values("OrderID")          End If      End If  End Sub 'Page_Load  </script>  <html>  <head>  <title>Cookie - NameValue</title>  </head>  <body bgcolor="#FFFFFF" text="#000000">  <form runat="server">  CustomerID: <asp:Label  runat="server" /><br>  OrderID: <asp:Label  runat="server" /><br>  <asp:Button Text="test" runat="server" />  </form>  </body>  </html> 
C# cookies_namevalue_cs.aspx
<%@ page language="c#" runat="server"%>  <script runat=server>  void Page_Load(){     if (!IsPostBack){         Response.Cookies["Customer"].Values["CustomerID"] = "100";          Response.Cookies["Customer"].Values["OrderID"] = "20";      }else{         if(Request.Cookies["Customer"] != null){              OurLabel.Text = Request.Cookies["Customer"].Values["CustomerID"];              OurLabel2.Text = Request.Cookies["Customer"].Values["OrderID"];          }      }  }  </script>  <html>  <head>  <title>Cookie - NameValue</title>  </head>  <body bgcolor="#FFFFFF" text="#000000">  <form runat="server">  CustomerID: <asp:Label  runat="server" /><br>  OrderID: <asp:Label  runat="server" /><br>  <asp:Button Text="test" runat="server" />  </form>  </body>  </html> 

You can see that the name-value pair is addressed by the .Values("name") property of the cookie object. As with just about everything in the .NET Framework, this property is an inherited object called the NameValueCollection and is located in the System.Collections.Specialized namespace. As you can see, this specialized collection is used to extend the functionality of cookies to perform things like this name value pair function that cookies don't inherently have.

Also, if you look at the previous code there is something else that is very important to notice. Look at these lines:

Visual Basic .NET
If Not (Request.Cookies("Customer") Is Nothing) Then      OurLabel.Text = Request.Cookies("Customer").Values("CustomerID")      OurLabel2.Text = Request.Cookies("Customer").Values("OrderID")  End If 
C#
if(Request.Cookies["Customer"] != null){      OurLabel.Text = Request.Cookies["Customer"].Values["CustomerID"];      OurLabel2.Text = Request.Cookies["Customer"].Values["OrderID"];  } 

These two if statements are critical to include if you will be checking for cookies that potentially don't exist. For instance, imagine that you have a shopping cart page and you are pulling the OrderID out of a cookie on that page, but someone goes there before this cookie has been set. This generates an error because you are trying to address an HttpCookie object that doesn't exist. ASP.NET can't do that. It cannot check the value of something that doesn't exist, so you must first check to see whether it exists by using the highlighted if statement.

There is also a bit of a shortcut for addressing the Values property of the HttpCookie object by dropping the .Values from your Response and Request. Take a look.

Visual Basic .NET cookies_namevalue_shortcut_vb.aspx
<%@ page language="vb" runat="server"%>  <script runat=server>  Sub Page_Load()      If Not IsPostBack Then          Response.Cookies("Customer")("CustomerID") = "100"          Response.Cookies("Customer")("OrderID") = "20"      Else          If Not (Request.Cookies("Customer") Is Nothing) Then              OurLabel.Text = Request.Cookies("Customer")("CustomerID")              OurLabel2.Text = Request.Cookies("Customer")("OrderID")          End If      End If  End Sub 'Page_Load  </script>  <html>  <head>  <title>Cookie - NameValue Shortcut</title>  </head>  <body bgcolor="#FFFFFF" text="#000000">  <form runat="server">  CustomerID: <asp:Label  runat="server" /><br>  OrderID: <asp:Label  runat="server" /><br>  <asp:Button Text="test" runat="server" />  </form>  </body>  </html> 
C# cookies_namevalue_shortcut_cs.aspx
<%@ page language="c#" runat="server"%>  <script runat=server>  void Page_Load(){     if (!IsPostBack){         Response.Cookies["Customer"]["CustomerID"] = "100";          Response.Cookies["Customer"]["OrderID"] = "20";      }else{         if(Request.Cookies["Customer"] != null){             OurLabel.Text = Request.Cookies["Customer"]["CustomerID"];              OurLabel2.Text = Request.Cookies["Customer"]["OrderID"];          }      }  }  </script>  <html>  <head>  <title>Cookie - Simple</title>  </head>  <body bgcolor="#FFFFFF" text="#000000">  <form runat="server">  CustomerID: <asp:Label  runat="server" /><br>  OrderID: <asp:Label  runat="server" /><br>  <asp:Button Text="test" runat="server" />  </form>  </body>  </html> 

To use the shortcut, you just eliminate the .Values from the reference and voil…it works the same. Not a big thing, but every little bit helps.

Although cookies provide a great alternative to sessions, the client does have the power to turn them off. It is therefore important that you check to see whether the client has cookies enabled. This is often a difficult subject and many people confuse the issue of a browser's capabilities for handling cookies with the fact that users have the power to disable cookie use if they so desire.

It pays at critical points to run a check to see whether a person has cookies enabled. Now there are a million ways to skin a cat and checking to see whether cookies are enabled is no exception. The following is a simple example of how to check to see whether cookies are enabled. Remember that you must make a round-trip client to truly know whether the user has cookies enabled. Hence the Response.Redirect to push us back to the client so we can set the cookie and then return and check to see whether it's set.

Visual Basic .NET cookies_test_vb.aspx
<%@ page language="vb" runat="server"%>  <script runat=server>  Sub Page_Load()      If Not (Request.Cookies("cookiesenabled") Is Nothing) Then          OurLabel.Text = "Cookies are enabled"      Else          If Request.QueryString("ck") <> "true" Then              Response.Cookies("cookiesenabled").Value = "true"              Response.Redirect("cookies_test_cs.aspx?ck=true")          Else              OurLabel.Text = "Sorry! Cookies are disabled"          End If      End If  End Sub 'Page_Load  </script>  <html>  <head>  <title>Cookie - Test</title>  </head>  <body bgcolor="#FFFFFF" text="#000000">  <asp:Label  runat="server" /><br>  </body>  </html> 
C# cookies_test_cs.aspx
<%@ page language="c#" runat="server"%>  <script runat=server>  void Page_Load(){     if(Request.Cookies["cookiesenabled"] != null){          OurLabel.Text = "Cookies are enabled";      }else{          if(Request.QueryString["ck"]!="true"){              Response.Cookies["cookiesenabled"].Value = "true";              Response.Redirect("cookies_test_cs.aspx?ck=true");          }else{              OurLabel.Text = "Sorry! Cookies are disabled";          }      }  }  </script>  <html>  <head>  <title>Cookie - Simple</title>  </head>    <body bgcolor="#FFFFFF" text="#000000">  <asp:Label  runat="server" /><br>  </body>  </html> 

As I said, this is not the only way to do this, but is only a simple example of how to check to see whether cookies are enabled. Basically, if it's the first time to the page and there is not a cookie called cookiesenabled, you should try to set that cookie and then redirect back to the same page with a querystring value to indicate that you've attempted to set the cookie. If you return to the page and the cookie exists, great! Cookies are enabled. But if the cookie doesn't exist and there is a querystring value of ck=true, you know that you tried to set a cookie and failed. You can conclude that cookies are disabled and act accordingly, possibly by informing the user that she needs to enable cookies to use the site, or by dealing with state issues in a cookieless way.


   
Top


ASP. NET for Web Designers
ASP.NET for Web Designers
ISBN: 073571262X
EAN: 2147483647
Year: 2005
Pages: 94
Authors: Peter Ladka

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net