Session State

Session state exists on a per-user basis for as long as that user's session persists. Sessions begin when the user first visits a site and last depending on how they are managed on the site: timeout, logout, or never. With a per-user state bag, one user doesn't have access to another user's session state. Additionally, session state may be made to persist across Web gardens and Web farms.

A classic example of when session state helps out is the shopping cart analogy. If a given user adds an item to the shopping cart, it stays with them until checkout. Behind the scenes, the shopping cart is really session-state. Listings 12.3 through 12.8 show a shopping cart application that uses session state to manage a user's items.

Listing 12.3 is a Web Form for displaying a list of grocery items for the user to select. It is simply a user interface for this application.

Listing 12.3 Shopping Cart Application in the Vegetables and Fruits Aisle Web Form (VegetablesAndFruits.aspx)
 <%@ Page language="c#" Debug="true" Codebehind="VegtablesAndFruits.aspx.cs" AutoEventWireup="false" Inherits="SessionState.VegetablesAndFruits" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html>   <head>     <title></title>     <meta name="GENERATOR" content= "Borland ASP.NET Designer for c# Package Library 7.1">   </head>   <body ms_positioning="FlowLayout">     <form runat="server">       <h2 align="left">         Some Corner Grocery Store       </h2>       <p align="left">         Vegetables and Fruits       </p>       <p align="left">         &nbsp;       </p>       <asp:checkboxlist  runat="server">         <asp:listitem value="Lettuce">Lettuce</asp:listitem>         <asp:listitem value="Potatoes">Potatoes</asp:listitem>         <asp:listitem value="Oranges">Oranges</asp:listitem>         <asp:listitem value="Bananas">Bananas</asp:listitem>       </asp:checkboxlist><br>       <br>       <asp:button  runat="server" text="Go To Meats">       </asp:button><br>       <br>       <p align="left">         &nbsp;       </p>     </form>   </body>  </html> 

Listing 12.4 is the code-behind file for the shopping cart application. This is where session state is used to keep track of the user's selection.

Listing 12.4 Shopping Cart Application in the Vegetables and Fruits Aisle Code-Behind (VegetablesAndFruits.aspx.cs)
 using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; namespace SessionState {    /// <summary>    /// Summary description for WebForm1.    /// </summary>    public class VegetablesAndFruits : System.Web.UI.Page    {       protected System.Web.UI.WebControls.CheckBoxList cblVegtablesAndFruits;       protected System.Web.UI.WebControls.Button btnGoToMeats;       private void Page_Load(object sender, System.EventArgs e)       {       }       #region Web Form Designer generated code       override protected void OnInit(EventArgs e)       {          //          // CODEGEN: This call is required by the ASP.NET Web Form Designer.          //          InitializeComponent();          base.OnInit(e);       }       /// <summary>       /// Required method for Designer support - do not modify       /// the contents of this method with the code editor.       /// </summary>       private void InitializeComponent()       {          this.btnGoToMeats.Click +=             new System.EventHandler(this.btnGoToMeats_Click);          this.Load += new System.EventHandler(this.Page_Load);       }       #endregion       private void btnGoToMeats_Click(object sender, System.EventArgs e)       {          ArrayList food = new ArrayList();          foreach (ListItem item in cblVegtablesAndFruits.Items)          {             if (item.Selected == true)             {                food.Add(item.Text);             }          }          Session["VegetablesAndFruits"] = food;          Server.Transfer("Meats.aspx");       }    } } 

The btnGoToMeats_Click method in Listing 12.4 uses session state to store the results of the user's selection. Anything typed may be stored in session state. Listing 12.5 is a Web Form that displays the user interface for the meats aisle of the shopping cart application.

Listing 12.5 Shopping Cart Application in the Meats Aisle Web Form (Meats.aspx)
 <%@ Page language="c#" Debug="true" Codebehind="Meats.aspx.cs" AutoEventWireup="false" Inherits="SessionState.Meats" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html>   <head>     <title></title>     <meta name="GENERATOR" content= "Borland ASP.NET Designer for c# Package Library 7.1">   </head>   <body ms_positioning="FlowLayout">     <form runat="server">       <h2 align="left">         Some Corner Grocery Store       </h2>       <p align="left">         Vegetable and Fruits       </p>       <p align="left">         &nbsp;       </p>       <asp:checkboxlist  runat="server">         <asp:listitem value="Beef">Beef</asp:listitem>         <asp:listitem value="Chicken">Chicken</asp:listitem>         <asp:listitem value="Fish">Fish</asp:listitem>         <asp:listitem value="Port">Pork</asp:listitem>       </asp:checkboxlist><br>       <br>       <asp:button  runat="server" text="Go To Check Out">       </asp:button><br>       <br>       <p align="left">         &nbsp;       </p>     </form>   </body>  <html> 

Listing 12.5 contains the HTML for the meats aisle of the shopping cart application. It is simply a user interface file and the real logic is performed by the code-behind file, shown in Listing 12.6.

Listing 12.6 Shopping Cart Application in the Meats Aisle Code-Behind (Meats.aspx.cs)
 using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; namespace SessionState {    /// <summary>    /// Summary description for WebForm1.    /// </summary>    public class Meats : System.Web.UI.Page    {       protected System.Web.UI.WebControls.CheckBoxList cblMeats;       protected System.Web.UI.WebControls.Button btnGoToCheckOut;       private void Page_Load(object sender, System.EventArgs e)       {       }       #region Web Form Designer generated code       override protected void OnInit(EventArgs e)       {          //          // CODEGEN: This call is required by the ASP.NET Web Form Designer.          //          InitializeComponent();          base.OnInit(e);       }       /// <summary>       /// Required method for Designer support - do not modify       /// the contents of this method with the code editor.       /// </summary>       private void InitializeComponent()       {          this.btnGoToCheckOut.Click +=             new System.EventHandler(this.btnGoToCheckOut_Click);          this.Load += new System.EventHandler(this.Page_Load);       }       #endregion       private void btnGoToCheckOut_Click(object sender, System.EventArgs e)       {          ArrayList food = new ArrayList();          foreach (ListItem item in cblMeats.Items)          {             if (item.Selected == true)             {                food.Add(item.Text);             }          }          Session["Meats"] = food;          Server.Transfer("CheckOut.aspx");       }    } } 

The btnGoToCheckOut_Click method in Listing 12.6 uses session state to store the results of the user's selection. Listing 12.7, shown next, is a Web Form that displays the user interface for the checkout counter of the shopping cart application.

Listing 12.7 Shopping Cart Application at the Checkout Counter Web Form (CheckOut.aspx)
 <%@ Page language="c#" Debug="true" Codebehind="CheckOut.aspx.cs" AutoEventWireup="false" Inherits="SessionState.CheckOut" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html>   <head>     <title></title>     <meta name="GENERATOR" content= "Borland ASP.NET Designer for c# Package Library 7.1">   </head>   <body ms_positioning="FlowLayout">     <form runat="server">       <h2 align="left">         Some Corner Grocery Store       </h2>       <h3 align="left">         Here is your order:       </h3>       <p align="left">         &nbsp;       </p>       <asp:label  runat="server"></asp:label>     </form><br>     <p align="left">       &nbsp;     </p><br>   </body> </html> 

Listing 12.7 showed the HTML for the user interface for the checkout counter of the shopping cart application. The code-behind file in Listing 12.8 contains the logic that displays all of the items the user selected while they were shopping.

Listing 12.8 Shopping Cart Application at the Checkout Counter Code-Behind (CheckOut.aspx.cs)
 using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; namespace SessionState {    /// <summary>    /// Summary description for WebForm1.    /// </summary>    public class CheckOut : System.Web.UI.Page    {       protected System.Web.UI.WebControls.Label lblOrder;       private void Page_Load(object sender, System.EventArgs e)       {          StringBuilder order = new StringBuilder();          ArrayList     food  = null;          string        tab   = "&nbsp;&nbsp;&nbsp;&nbsp;";          order.Append("<p><b>Vegetables and Fruits:</b></p>");          food = (ArrayList)Session["VegetablesAndFruits"];          if (food != null)          {             foreach (string item in food)             {                order.AppendFormat("{0}{1}<br>", tab, item);             }          }          else          {             order.Append("None<br>");          }          order.Append("<p><b>Meats:</b></p>");          food = (ArrayList)Session["Meats"];          if (food != null)          {             foreach (string item in food)             {                order.AppendFormat("{0}{1}<br>", tab, item);             }          }          else          {             order.Append("None<br>");          }          lblOrder.Text = order.ToString();       }       #region Web Form Designer generated code       override protected void OnInit(EventArgs e)       {          //          // CODEGEN: This call is required by the ASP.NET Web Form Designer.          //          InitializeComponent();          base.OnInit(e);       }       /// <summary>       /// Required method for Designer support - do not modify       /// the contents of this method with the code editor.       /// </summary>       private void InitializeComponent()       {          this.Load += new System.EventHandler(this.Page_Load);       }       #endregion    } } 

Before executing this page you may want to check Project, Options, Debugger, ASP.NET to make sure that the start page is VegetablesAndFruits.aspx.

The code-behind files in Listing 12.4 and Listing 12.6 capture the ordered items for the current user and place them into the Session state. The following code shows how this is done in the VegetablesAndFruits class in Listing 12.4, but the button-click event in the Meats class in Listing 12.6 does pretty much the same thing:

 private void btnGoToMeats_Click(object sender, System.EventArgs e) {    ArrayList food = new ArrayList();    foreach (ListItem item in cblVegtablesAndFruits.Items)    {       if (item.Selected == true)       {          food.Add(item.Text);       }    }    Session["VegetablesAndFruits"] = food;    Server.Transfer("Meats.aspx"); } 

As shown in Listing 12.3, the grocery items are displayed in a CheckBoxList control. The preceding code iterates through this list, identifying only the selected items and adding them to an ArrayList. When all items are found, the ArrayList is added to Session state and the page is redirected to the Meats page, using the static Transfer method of the Server class. The same logic occurs in the button-click event of the Meats class, except the page transferred to is CheckOut.aspx.

The Page_Load event of the CheckOut class retrieves items out of Session state and builds the output string with a StringBuilder object, which is part of the System.Text namespace. A StringBuilder is the best way to build a string when there are multiple appends like this because it is much more efficient. Notice that the string is built with various HTML formatting tags and that the final string is added to the lblOutput Label. This is to control the rendering in the output page and shows how standard HTML can be added to a Label. In fact, an entire HTML page can be added to the Text property of a label and it will render fine. The output of the CheckOut Web Form is shown in Figure 12.2.

Figure 12.2. The checkout page of a session-state-driven shopping cart.

graphics/12fig02.gif



C# Builder KickStart
C# Builder KickStart
ISBN: 672325896
EAN: N/A
Year: 2003
Pages: 165

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