• home
  • forum
  • my
  • kt
  • download
  • Session State

    Author: 2007-07-04 15:38:44 From:

    After completing this tutorial, you will be able to
    • Explain the importance of managing session state in a Web application
    • Use the session state manager (the Session object)
    • Configure session state
    • Store session state on a state server
    • Store session state in a database

    This tutorial covers managing session state within your ASP.NET application. Programming Web applications requires you to be very mindful of how the state of your application is distributed at any moment. One of the most important types of state in a Web application is session state¡ªthe state associated with a single particular session. Because Web applications are distributed by nature, keeping track of any single client has to be done deliberately

    After completing this tutorial, you will be able to

    • Explain the importance of managing session state in a Web application

    • Use the session state manager (the Session object)

    • Configure session state

    • Store session state on a state server

    • Store session state in a database

    This tutorial covers managing session state within your ASP.NET application. Programming Web applications requires you to be very mindful of how the state of your application is distributed at any moment. One of the most important types of state in a Web application is session state¡ªthe state associated with a single particular session. Because Web applications are distributed by nature, keeping track of any single client has to be done deliberately.

    ASP.NET session state support is extensive, reliable, and flexible¡ªoffering many advantages over the session state support available in classic ASP. For starters, ASP.NET session state is handled by the Session object¡ªan object dictionary that's automatically created with each new session (if you have session state enabled). The Session object is easily accessible through the HttpContext object, which you can reference at any point during the request. The process of associating user state with a particular user's session is handled automatically by ASP.NET. Whenever you want to access session state, you just grab it from the context (it's also mapped into a member variable living on the page). You may choose how ASP.NET tracks session state, and you may even tell ASP.NET where to store session state.

    Let's begin with a look at how various pieces of state are managed by ASP.NET, and the gap filled by the session state manager.


    After working with ASP.NET during the previous tutorials, one theme should be emerging. Web-based programming distinguishes itself as a programming idiom in which you're trying to manage an application serving multiple users distributed over a wide area. What's more, you're doing it over a disconnected protocol.

    For example, imagine you're writing some sort of shopping portal. Certain types of the application data can be kept in a central database¡ªthings like inventory and supplier lists. We've seen that System.Web.UI.Page and server-side controls themselves manage view state. However, when you think about the nature of data in a user's shopping cart, you see the data clearly belongs elsewhere.

    You don't really want to store that data in the page's ViewState. While it's possible for simple applications, storing large chunks of data in view state will bog down your users' experience of the site (it'll be much slower) and it poses a security risk by having items travel back and forth with each request. In addition, only serializable types may be stored in view state.

    Unfortunately, a single user's data doesn't really belong in the central database, either. Perhaps if you expected only one user over the lifetime of your application, that might work. However, remember the nature of a Web application is to make your application available to as many clients as possible. Suddenly, it becomes clear that you want to be able to carve out a small data holding area that persists for the lifetime of a single user's session. This type of data is known as session state.

    Since its inception, ASP.NET has supported session state. When session state is turned on, ASP.NET creates a new Session object for each new request. The Session object becomes part of the context (and is available through the page). ASP.NET stamps the Session object with an identifier (more on that later), and the Session object is reconstituted when a request comes through containing a valid session identifier. The Session object follows the page around and becomes a convenient repository for storing information that has to survive throughout the session (and not simply for the duration of the page).

    The Session object is a dictionary of name-value pairs. You can associate any CLR-based object with a key of your choosing and place it in the Session object so it will be there when the next request belonging to that session comes through. Then you may access that piece of data using the key under which it was stored. For example, if you wanted to store some information provided by the user in the Session object, you'd write code like this:

    void StoreInfoInSession()
    {
       String strFromUser = TextBox1.Text;
       Session["strFromUser"] = strFromUser;
    }

    To retrieve the string during the next request, you'd use code like this:

    void GetInfoFromSession()
    {
       String strFromUser = Session["strFromUser"] ;
       TextBox1.Text = strFromUser;
    }

    The square braces on the Session object indicate an indexer. The indexer is a convenient syntax for express keys¡ªboth when inserting data into and retrieving data from the Session object.

    Managing session state in ASP.NET is extraordinarily convenient. In ASP.NET, session state may live in a number of places including (1) in proc¡ªin the ASP.NET worker process, (2) on a separate state server running a daemon process, and (3) in a SQL Server database.

    Let's start by getting a taste of using session state right now.

    To see how session state works, here's an exercise that involves creating a Web site whose page stores a value as a member variable in the page and as an element of session state. It will illustrate the difference between page state during a request and session data that persists beyond a request.

    Trying Session State

    1. Create a new Web site. Name it SessionState. Make sure it's an HTTP site so you may use IIS to configure the session state.

    2. In the default page (Default.aspx), drag a text box (and a label to identify the TextBox if you want) onto the form. Then drag two buttons and another label onto the form like so:

      Graphic
    3. Name the first button Submit String. That is, set the ID to SubmitString. It doesn't matter what you name the second button. The first button will submit the string to the form, and the other button will just perform a post back. That way, you'll be able to see the ephemeral nature of page member variables. Name the label LabelShowString. We'll use it to display the value of the string.

    4. Add a String variable member to the page. In the Page_Load handler, set the text box on the page to the value of the string. Then add a handler for the Submit String button. Have the handler take the Text property from the TextBox1 and store it in the page member variable. Then set the LabelShowString label text to the value of the string like so:

      public partial class _Default : System.Web.UI.Page
      {
      
         String _str;
      
         protected void Page_Load(object sender, EventArgs e)
         {
           this.LabelShowString.Text = this._str;
      
          }
         protected void SubmitString_Click(object sender, EventArgs e)
         {
      
           this._str = this.TextBox1.Text;
           this.LabelShowString.Text = this._str;
         }
      }
    5. Now run the program. Type a string into the text box and click Submit String. When the post goes to the page, the page will show the string in the label.

      Graphic
    6. Now click the Submit String button. What happens? Remember, Page_Load simply looks at the value of the _str member variable and stuffs it into the label. Pages (and HTTP handlers in general) are very short-lived objects. They live for the duration of the request and then are destroyed¡ªalong with all the data they hold. The _str member variable evaporated as soon as the last request finished. A new _str member variable (which was empty) was instantiated as soon as the page was recreated.

      Graphic

      To sum up, we saw in Tutorial 4 that controls manage their own state. But in this case, we're taking the data from the text box and storing it in a member variable in the Page class. The lifetime of the page is very short. The page lives long enough to generate a response, then it disappears. Any state you've stored as data members in the page disappears, too.

    7. Session state is a way to solve this issue. To show this, add a new label to the page. This one will show the data as retrieved from the Session object.

      Graphic
    8. Write code to store the string in session state. Have the SubmitString take the text from the TextBox1 and store it into the Session object. Then update the Page_Load method to display the value as it came from session state as shown below:

      public partial class _Default : System.Web.UI.Page
      {
      
         String _str;
      
         protected void Page_Load(object sender, EventArgs e)
          {
               this.LabelShowString.Text = this._str;
      
               this.LabelShowStringAsSessionState.Text =
                   (String)this.Session["str"];
      
          }
         protected void SubmitString_Click(object sender, EventArgs e)
         {
               this._str = this.TextBox1.Text;
               this.Session["str"] = this.TextBox1.Text;
               this.LabelShowString.Text = this._str;
      
               this.LabelShowStringAsSessionState.Text =
                   (String)this.Session["str"];
      }
      }
    9. Run the program. Type in a string and click the Submit String button. Both labels should contain data. The LabelShowString label will hold data because the SubmitString handler made the assignment. The LabelShowStringAsSessionState label also shows data because the handler set that text.

      Graphic
    10. Now click the Just Submit button and see what happens:

      Graphic

      In this case, the page was simply submitted, causing only the Page_Load to be executed. Page_Load displays both the _str member variable (which is blank because it lives and dies with the page) and the data from the Session object (which lives independently of the page).

    As you can see, session state is pretty convenient. However, we wouldn't get very far if all we could do was store simple strings and scalars. Fortunately, the session dictionary stores all manner of CLR objects.

    ASP.NET's Session object will store any object running within the CLR. That goes for larger data¡ªnot just small strings or other scalar types. One of the most common uses for the object is for implementing features like shopping carts (or any other data that has to go with a particular client). For example, if you're developing a commerce-oriented site for customers to purchase products, you'd probably implement a central database representing your inventory. Then as each user signs on, they will have the opportunity to select items from your inventory and place them in a temporary holding area associated with the session they're running. In ASP.NET that holding area is the Session object.

    A number of different collections are useful for managing shopping cart-like scenarios. Probably the easiest to use is the good ol' ArrayList¡ªan automatically sizing array that supports both random access and the IList interface. However, for other scenarios you might use a DataTable, a DataSet, or some other more complex type.

    We took a quick look at ADO and data access in Tutorial 11¡ªall about databinding. The next example revisits databound controls (the DataList and the GridView. We'll also see the Data[[<img src="images/shy.gif"/>]]Table in depth.

    Session State, ADO.NET Objects, and Databound Controls

    This example illustrates using ADO.NET objects, databound controls, and session state to transfer items from an inventory (represented as a DataList) to a collection of selected items (represented using a GridView).

    1. Create a new page on the SessionState site named UseDataList.aspx.

    2. Drag a DataList onto the page and place it on the right side of the page.

    3. When setting up the DataList, select AutoFormat to give the DataList a sleeker appearance. The style used in the application accompanying this tutorial is the slate style.

      Graphic
    4. Give this DataList a caption of Items in Inventory.

    5. Switch to the Source view in the designer. In the declaration template, add a button as shown in the code highlighted below. The button Text property should be Select Item. The button ID should be ButtonSelectItem.

      <asp:DataList ID="DataList1"
          runat="server" BackColor="White" BorderColor="#E7E7FF"
          BorderStyle="None" BorderWidth="1px" CellPadding="3"
          GridLines="Horizontal"
          Style="z-index: 100; left: 8px; position: absolute; top: 16px"
          OnItemCommand="DataList1_ItemCommand" Caption="Items in Inventory" >
      <FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" />
      <SelectedItemStyle BackColor="#738A9C"
            Font-Bold="True" ForeColor="#F7F7F7" />
      <AlternatingItemStyle BackColor="#F7F7F7" />
      <ItemStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" />
            <ItemTemplate>
            ID:
            <asp:Label ID="IDLabel"
            runat="server" Text='<%# Eval("ID") %>'></asp:Label><br />
            Title:
            <asp:Label ID="TitleLabel"
            runat="server" Text='<%# Eval("Title") %>'></asp:Label><br />
            AuthorLastName:
            <asp:Label ID="AuthorLastNameLabel"
            runat="server" Text='<%# 
      Eval("AuthorLastName")
            %>'></asp:Label><br />
            AuthorFirstName:
            <asp:Label ID="AuthorFirstNameLabel"
            runat="server" Text='<%# 
      Eval("AuthorFirstName")
            %>'></asp:Label><br />
            Topic:
            <asp:Label ID="TopicLabel" runat="server"
            Text='<%# Eval("Topic") %>'></asp:Label><br />
            Publisher:
            <asp:Label ID="PublisherLabel"
            runat="server"
            Text='<%# Eval("Publisher") %>'></asp:Label><br />
            <br />
          <asp:Button ID="SelectItem"
             CommandName="DataList1_ItemCommand"
             runat=server Text="Select Item" />
      
            &nbsp;
            </ItemTemplate>
               <HeaderStyle BackColor="#4A3C8C" Font-
      Bold="True"
                  ForeColor="#F7F7F7" />
      </asp:DataList>
    6. Stub out a shell for the SelectItem button on handler. The button handler should be named DataList1_ItemCommand to match the identifier in the DataList1.We'll use it shortly to move items from the inventory to the selected items table.

      public partial class UseDataList : System.Web.UI.Page
      {
      
         protected void DataList1_ItemCommand(object source,
                  DataListCommandEventArgs e)
         {
         }
      }
    7. Go back to the code for the page and add some code to open a database and populate the DataList. Name the function GetInventory. The examples that come with this tutorial include a database named ASPDotNetStepByStep.mdb that will work. You can use the connection string listed below to connect to the database. Make sure the database path points to the file correctly using your directory structure.

      public partial class UseDataList : System.Web.UI.Page
      {
         protected DataTable GetInventory()
         {
      
            String strConnection =
            @"Provider=Microsoft.Jet.OLEDB.4.0;
            DataSource=
            c:\\inetpub\\wwwroot\\SessionState\\App_Data\\ASPDotNetStepByStep.mdb";
      
            DbProviderFactory f =
                 DbProviderFactories.GetFactory("System.Data.OleDb");
      
            DbConnection connection = f.CreateConnection();
            connection.ConnectionString = strConnection;
      
            connection.Open();
      
            DbCommand command = f.CreateCommand();
            command.CommandText = "Select * from DotNetReferences";
            command.Connection = connection;
      
            IDataReader reader = command.ExecuteReader();
      
            DataTable dt = new DataTable();
            dt.Load(reader);
            reader.Close();
            connection.Close();
            connection.Dispose();
      
            return dt;
         }
      
         protected DataTable BindToinventory()
         {
            DataTable dt;
            dt = this.GetInventory();
            this.DataList1.DataSource = dt;
            this.DataBind();
            return dt;
         }
      
      
      // more goes here¡­
      }
    8. Now add a method named CreateSelectedItemsData. This will be a table into which selected items will be placed. The method will take a DataTable object that will describe the schema of the data in the live database (we'll see how to get that in a minute). You can create an empty DataTable by constructing it and then adding Columns to the column collection. The schema coming from the database will have the column name and the data type.

      public partial class UseDataList : System.Web.UI.Page
      {
        protected DataTable CreateSelectedItemsTable(DataTable tableSchema)
        {
              DataTable tableSelectedItemsData = new DataTable();
      
              foreach(DataColumn dc in tableSchema.Columns)
              {
                    tableSelectedItemsData.Columns.Add(dc.ColumnName,
                          dc.DataType);
              }
              return tableSelectedItemsData;
      
        }
      }
    9. Update the page code to handle Page_Load. When the initial request to a page is made (that is, if the request is not a post back), Page_Load should call BindToInventory (which returns the DataTable snapshot of the DotNetReferences table). Use the DataTable as the schema upon which to base the selected items table. That is, declare an instance of a DataTable and assign it the result of CreateSelectedItemsTable. Then store the (now empty) table in the Session object using the key tableSelectedItems.

      public partial class UseDataList : System.Web.UI.Page
      {
          protected void Page_Load(object sender, EventArgs e)
          {
      
      if (!IsPostBack)
             {
                   DataTable dt = BindToinventory();
                   DataTable tableSelectedItems =
                      this.CreateSelectedItemsTable(dt);
                   Session["tableSelectedItems"] = tableSelectedItems;
             }
      
          }
      }

      Browse to the Web site to make sure that the database connects. It should look something like this:

      Graphic
    10. Now add a GridView to the page. Don't bother to give it a data source. It represents the table of selected items held in session state. We'll add that shortly. Make sure the AutoGenerateColumns property is set to true.

      Graphic
    11. Finally, add a handler for the SelectItem button. This method should move items from the inventory to the selected items table. You can get the selected item index from the DataListCommandEventArgs coming into the handler. Calling BindToInventory will set up the DataList data source so you can fetch the selected item. You may access the columns within the selected row using ordinal indices. From the values in each column, construct a new DataRow and add it to the selected items table. Store the modified table back in session state. Finally, apply the new selected items table to the DataSource in the GridView1 and bind the GridView1.

      public partial class UseDataList : System.Web.UI.Page
      {
         protected void DataList1_ItemCommand(object source,
            DataListCommandEventArgs e)
         {
            int nItemIndex = e.Item.ItemIndex;
            this.DataList1.SelectedIndex = nItemIndex;
      
            BindToinventory();
      
            // Order of the columns is:
            // ID, Title, FirstName, LastName, Topic, Publisher
      
            DataTable dt = (DataTable)DataList1.DataSource;
            String strID = (dt.Rows[nItemIndex][0]).ToString();
            String strTitle = (dt.Rows[nItemIndex][1]).ToString();
            String strAuthorLastName = (dt.Rows[nItemIndex][2]).ToString();
            String strAuthorFirstName = (dt.Rows[nItemIndex][3]).ToString();
            String strTopic = (dt.Rows[nItemIndex][4]).ToString();
            String strPublisher = (dt.Rows[nItemIndex][5]).ToString();
      
            DataTable tableSelectedItems;
            tableSelectedItems = (DataTable)Session["tableSelectedItems"];
      
            DataRow dr = tableSelectedItems.NewRow();
            dr[0] = strID;
            dr[1] = strTitle;
            dr[2] = strAuthorLastName;
            dr[3] = strAuthorFirstName;
            dr[4] = strTopic;
            dr[3] = strPublisher;
      
            tableSelectedItems.Rows.Add(dr);
      
            Session["tableSelectedItems"] = tableSelectedItems;
      
            this.GridView1.DataSource = tableSelectedItems;
            this.GridView1.DataBind();
      
         }
      }
    12. Run the site. When the page first comes up, you should see only the inventory list on the left side of the page. Click the Select Item button on some of the items. You should see your browser post back to the server and render the DataList and the GridView with the newly added selected item.

      Graphic

    Now that you have a working application that uses session state, let's take a look at the different ways in which you may configure ASP.NET session state.

    ASP.NET gives you several choices for managing session state. You can turn it off completely, you may run session state in the ASP.NET worker process, you may run it on a separate state server, or you may run it from a SQL Server database. Here's a rundown of the options available:

    • Don't use it at all.

      By disabling session state, your application performance will increase because the page doesn't need to load the session when starting, nor does it need to store session state when it's going away. On the other hand, you won't be able to associate any data with a particular user.

    • Store session state in proc.

      This is how session state is handled by default. In this case, the session dictionaries (the Session objects) are managed in the same process as the page and handler code. The advantage of using session state in process is that it's very fast and convenient. However, it's not durable. For example, if you restart IIS or somehow knock the server down, all session state is lost. In some cases, this may not be a big deal. However, if your shopping cart represents a shopping cart containing sizeable orders, losing that might be a big deal. In addition, the in process Session manager is confined to a single machine, meaning you can't use it in a Web form.

    • Store session state in a state server.

      This option tells the ASP.NET runtime to direct all session management activities to a separate daemon process running on a particular machine. This option gives you the advantage of running your server in a Web farm. A Web farm is a group of servers tied together to serve Web pages. The ASP.NET Session State facilities support Web farms explicitly. To run in a Web form, you would direct all your applications to go to the same place to retrieve session information. The downside to this approach is that it does impede performance somewhat¡ªapplications need to make a network round-trip to the state server when loading or saving session information.

    • Store session state in a database.

      Configuring your application to use a SQL Server database for state management causes ASP.NET to store session information within a SQL Server database somewhere on your network. Use this option when you want to run your server from within a Web form when you want session state to be durable and safe.

    There are two ways to configure ASP.NET: the hard way and the easy way. As with most other configuration settings, the ASP.NET session state configuration ultimately happens within the Web.Config file. As always, you may configure Web.Config the hard way by using the typing Wizard (that is, typing the settings in by hand). Alternatively, you may use the ASP.NET Configuration Settings dialog box from IIS.

    Graphic

    Turning Off Session State

    The ASP.NET session state configuration tool available through IIS will touch your Web site's Web.Config file and insert the right configuration strings to enforce the settings you choose. To turn off session state completely, select Off from the session state mode control.

    Storing Session State InProc

    To store session state in the ASP.NET worker process, select InProc from the session state mode control. Your application will retrieve and store session information very quickly, but it will be available only to your application (and not on a Web form).

    Storing Session State in a State Server

    To have ASP.NET store session state on another server on your network, select StateServer from the SessionState mode control. When you select this item, the dialog box will enable the Connection String text box and the network timeout text box. Insert the protocol, IP address, and port for the state server in the Connection String text box. For example, the string:

    tcpip=127.0.0.1:42424

    will store the session state on the local machine over port 42424. If you want to store the session state on a machine other than your local server, change the IP address. Before session state is stored on a machine, you need to make sure the ASP.NET state server is running on that machine. You may get to it via the Services panel under the control panel.

    Graphic

    Storing Session State in a Database

    The final option for storing session state is to use a SQL Server database. Select SQLServer from the ASP.NET session state mode combo box. You'll be asked to enter the connection string to the SQL Server state database. Here's the string they provide by default:

    data source=127.0.0.1;Integrated Security=SSPI

    You may point ASP.NET so it references a database on another machine. Of course, you need to have SQL Server installed on the target machine to make this work. In addition, you'll find some SQL scripts to create the state databases in your .NET system directory (C:\WINDOWS\[[<img src="images/shy.gif"/>]]Microsoft.NET\Framework\v2.0.50215 on this machine at the time of this writing). The Aspnet_regsql.exe tool will set up the databases for you.

    Because Web-based applications rely on HTTP to connect browsers to servers and HTML to represent the state of the application, ASP.NET is essentially a disconnected architecture. When an application needs to use session state, the runtime needs a way of tracking the origin of the requests it receives so that it may associate data with a particular client. ASP.NET 2.0 offers three options for tracking the Session ID, via cookies, the URL, or client profiles.

    Tracking Session State with Cookies

    This is the default option for an ASP.NET Web site. In this scenario, ASP.NET generates a hard-to-guess identifier and uses it to store a new Session object. You can see the session identifier come through the cookie collection if you have tracing turned on.

    Graphic

    Tracking Session State with the URL

    The other main option is to track session state by embedding the session ID as part of the request string. This is useful if you think your clients will turn off cookies (thereby disabling cookie-based session state tracking).

    Graphic

    Using AutoDetect

    By selecting AutoDetect, the ASP.NET runtime will determine if the client browser has cookies turned on. If cookies are turned on, then the session identifier is passed around as a cookie. If not, the session identifier will be stored in the URL.

    Applying Device Profiles

    The UseDeviceProfile option tells ASP.NET to determine if the browser supports cookies based on the SupportsRedirectWithCookie property of the HttpBrowserCapabilities object set up for the request. Requests that flip this bit to true cause session identifier values to be passed as cookies. Requests that flip this bit to false cause session identifiers to be passed in the URL.

    Session State Timeouts

    The timeout configuration setting manages the lifetime of the session. The lifetime of the session is the length of time in minutes a session may remain idle before ASP.NET abandons it and makes the session ID invalid. The maximum value is 525,601 minutes (one year), and the default is 20.

    ASP.NET supports some other configuration settings not available through the IIS configuration utility. These are values you need to type into the Web.Config file directly.

    If you don't like the rather obvious name of the session ID cookie made up by ASP.NET (the default is SessionID), you may change it. The cookieName setting lets you change that name. You might want to rename the cookie as a security measure to hamper hackers in their attempts to hijack a session key.

    If you want to replace an expired session ID with a new one, setting the regenerateExpiredSessionId setting to true will perform that task. This is only for cookieless sessions.

    If you don't like the SQL Server database already provided to support ASP.NET's session state, you may apply your own database. The allowCustomSqlDatabase setting turns this feature on.

    When using SQL Server to store session data, ASP.NET has to act as a client of SQL Server. Normally, the ASP.NET process identity is impersonated. You may instruct ASP.NET to use the user credentials supplied to the identity configuration element within Web.Config by setting the mode attribute to Custom. By setting the mode attribute to SQLServer, you tell ASP.NET to use a trusted connection.

    Used when the mode attribute is set to StateServer, the stateNetworkTimeout is for setting the number of seconds for the idle time limits of the TCP/IP network connection between the Web server and the state server. The default is 10.

    Finally, you may instruct ASP.NET to use a custom provider by setting the name of the provider in the custom element. For this to work the provider must be specified elsewhere in Web.Config (specifically in the providers element).

    One of the most common uses for session state is to keep track of information coming from a user even though the information is posted back via several pages. For example, scenarios such as collecting mailing addresses, applying for security credentials, or purchasing something on a Web site introduce this issue.

    Sometimes gathering information is minimal and may be done through only one page. However, when collecting data from users requires several pages of forms, you need to keep track of that information between posts. For example, most commercial Web sites employ a multistage checkout process. After placing a bunch of items into your shopping cart, you click ¡°Check Out¡± and the site redirects you to a checkout page. From there, you are usually required to perform several distinct steps¡ªsetting up a payment method, confirming your order, and getting an order confirmation.

    While you could code something like this in ASP.NET 1.x, ASP.NET 2.0 now includes a Wizard control to deal with this sort of multistage data collection.

    If you were to develop a multistage input sequence, you'd need to build in the navigation logic and keep track of the state of the transaction. The Wizard control provides a template that performs the basic tasks of navigating though multiple input pages while you provide the specifics. The Wizard control logic is built around specific steps, and includes facilities for managing these steps. The Wizard control supports both linear and nonlinear navigation.

    Using the Wizard Control

    This example shows using the Wizard control to gather several different pieces of information from the client: a name and address, what kinds of software he or she uses, and the kind of hardware he or she uses. For example, this might be used to qualify users for entry into a certain part of the Web site or perhaps to qualify them for a subscription.

    1. Create new page in the SessionState project named UseWizard.

    2. Drop a WizardControl onto the page.

    3. When the local menu appears in the designer, select Add Wizard Steps¡­ to show this dialog box:

      Graphic
    4. Add an Intro step, a Name and Address step, a Software step, a Hardware step, and a Submit information step. Make sure Intro is a StartNavigationTemplate.

    5. Make sure the Submit information step is a FinishNavigationTemplate.

    6. Add controls to the steps. The Intro step gets a label that describes what the user is entering:

      Graphic
    7. The Name and Address step should include labels and text boxes to get personal information. Be sure to give useable IDs to the text boxes. You'll need them during the submission step:

      Graphic
    8. The Software step should include a list of check boxes listing common software types:

      Graphic
    9. The Hardware step should include a list of check boxes listing common hardware types:

      Graphic
    10. The summary information step (which you may use to show information before submitting) should include a label that will summarize the information collected. Name the label LabelSummary so you can use it to display the summary.

      Graphic
    11. Finally, edit the Form_Load method to collect the information from each of the controls in the Wizard. The controls are actually available as member variables on the page. This information will be loaded every time the page is loaded. However, it will be hidden from view until the user selects the step. Double-clicking on the Wizard control will add a handler for the Finish button that you may use to harvest the information gathered via the wizard.

          protected void Page_Load(object sender, EventArgs e)
          {
      
               String strSummary =
                     "About to submit. \n ";
               strSummary += " You are: \n";
               strSummary += this.TextBoxName.Text + " ";
               strSummary += this.TextBoxAddress.Text + " ";
               strSummary += this.TextBoxCity.Text + " ";
               strSummary += this.TextBoxState.Text + " ";
               strSummary += this.TextBoxZip.Text + " \n";
      
               strSummary += "Software: ";
               foreach (ListItem listItem in CheckBoxListSoftware.Items)
               {
                     if (listItem.Selected)
                     {
                           strSummary += listItem.Text + " ";
                     }
               }
      
               strSummary += "\nHardware: ";
               foreach (ListItem listItem in CheckBoxListHardware.Items)
               {
                     if (listItem.Selected)
                     {
                           strSummary += listItem.Text + " ";
                     }
               }
      
               this.TextBoxSummary.Text = strSummary;
           }
          protected void Wizard1_FinishButtonClick(object sender,
               WizardNavigationEventArgs e)
          {
               // Do something with the data here
          }
    12. Now run the page and go through the steps. You'll see each step along the way and then finally a summary of the information collected.

      Graphic Graphic Graphic Graphic Graphic


    If anything distinguishes Web-based programming from other types of programming, it's probably the issue of tracking the state of any particular user. Because Web development inherently involves distributing state and managing that state, it needs to be done deliberately.

    Session state is one of the most important pieces of state in any application because it is associated with the particular client making the request. This is most important for applications where you want to have the state associated with a single user available (as in the case of a shopping cart).

    Session state is always available through the Page (and through the HttpContext) via the Session object. It's a name value dictionary that holds any kind of CLR object. Adding and retrieving information is accomplished most easily via indexers. In addition, session state may be configured in its location, in how it's tracked, and in how long it lasts. ASP.NET supports a number of other more advanced settings, too.

    In this tutorial, we also looked at the Wizard control as a way to retain information between several posts without resorting to session state. This is most useful when several kinds of related data need to be collected at once.

    To

    Do This

    Access the current client's session state

    Use the Page.Session property

    Use the current context's HttpContext.Session property

    Access a specific value in the current client's session state

    Session state is a set of key-value pairs. Access the data with the string key originally used to insert the data in the cache

    Store session state in-proc

    Set the <SessionState> attributes in Web.Config. Set mode to InProc

    Store session state in a state server

    Set the <SessionState> attributes in Web.Config. Set mode to StateServer. Be sure to include a stateConnection string

    Store session state in SQL Server

    Set the <SessionState> attributes in Web.Config. Set mode to SQLServer. Be sure to include a sqlConnection string

    Disable session state

    Set the <SessionState> attributes in Web.Config. Set mode to Off

    Use cookies to track session state

    Set the <SessionState> attributes in Web.Config. Set cookieless to false

    Use URL to track session state

    Set the <SessionState> attributes in Web.Config. Set cookieless to true

    Set session state timeout

    Set the <SessionState> attributes in Web.Config. Set timeout to a value (representing minutes)

    discuss this topic to forum

    relation tutorial

    No relevant information

    Category

      NET (110)

    New

    Hot