Home > Articles

  • Print
  • + Share This
This chapter is from the book

Apply Your Knowledge

Exercises

3.1 Using Session State to Create a Shopping Cart

Online stores often use session state to maintain information about a user's shopping cart. This allows the site to keep track of users' selections as they explore the store rather than requiring the users to add all the items at the same time.

In this exercise, you'll use a similar technique to manage a shopping cart. To keep the emphasis on session state, you'll keep the catalog smaller than you'll generally find at most stores.

Estimated time: 20 minutes

  1. Create a new Visual C# ASP.NET Web Application project at the location http://localhost/315C03Exercises.

  2. Add a Web form to the project. Name it ShoppingPage.aspx.

  3. Add three Label controls, three Textbox controls (txtNK, txtCF, and txtHA) and three Button controls (btnNK, btnCF, and btnHA) in to the table on the Web form (see Figure 3.16).

  4. Switch to code view and add the following code to add selected items and their quantities to the session:

  5. // Add the selected item to 
    // the session state
    private void AddToSession(
      String strProduct, int intQty)
    {
      if(Session[strProduct] != null)
      {
        // If the product already exists, 
        // increase its quantity
        Session[strProduct] = (int) 
         Session[strProduct] + intQty;
      }
      else
      {
        Session[strProduct] = intQty;
      }
    }
  6. Double-click the three button controls and add the following code to their Click event handlers:

  7. private void btnNK_Click(
      object sender, System.EventArgs e)
    {
      // Add the selected item 
      // to the shopping cart
      AddToSession("NK", Int32.Parse(
        txtNK.Text));
      // Display shopping cart
      Server.Transfer("ShoppingCart.aspx");
    }
    
    private void btnCF_Click(
      object sender, System.EventArgs e)
    {
      // Add the selected item 
      // to the shopping cart 
      AddToSession("CF", 
        Int32.Parse(txtCF.Text));
      // Display shopping cart
      Server.Transfer("ShoppingCart.aspx");
    }
    
    private void btnHA_Click(
      object sender, System.EventArgs e)
    {
      // Add the selected item 
      // to the shopping cart 
      AddToSession("HA", 
        Int32.Parse(txtHA.Text));
      // Display shopping cart
      Server.Transfer("ShoppingCart.aspx");
    }
  8. Add a new Web form to the project. Name the Web form ShoppingCart.aspx.

  9. Drag a Hyperlink control (hlShopping) to the Web form. Set its NavigateUrl property to ShoppingPage.aspx.

  10. Switch to code view and add the following code in the Page_Load() event handler:

  11. private void Page_Load(
      object sender, System.EventArgs e)
    {
      Response.Write(
       "The shopping cart contains" +
       " the following items: <br>");
      // Display the contents of 
      // the shopping cart
      for(int intI=0; intI < Session.Count; 
        intI++)
      {
        switch (Session.Keys[intI])
        {
          case "NK":
            Response.Write(
              "Nestle KitKat (" +
              Session[intI]+ ")" +
              "<br>");
            break;
          case "CF":
            Response.Write(
              "Cadbury's Fingers (" +
              Session[intI]+ ")"+ 
              "<br>");
            break;
          case "HA":
            Response.Write(
              "Hersheys Almonds (" + 
              Session[intI] + ")" +
              "<br>");
            break;
        }
      }
    }
  12. Set ShoppingPage.aspx as the start page in the project.

  13. Run the project. You'll see a shopping page as shown in Figure 3.16. Enter a quantity for a product and click on the Add to Cart button. You'll be taken to the shopping cart as shown in Figure 3.17. Add a few more items to the cart; you'll note that the shopping cart remembers your selections.

Figure3.16Figure 3.16 The Add to Cart button updates the session state with the corresponding item and its quantity.

Figure3.17Figure 3.17 The shopping cart page summarizes the user's selections by retrieving the information from the session state.

3.2 Creating a Wizard-like User Interface

When creating a wizard-like user interface, you need to access the information entered in one page from another page in the wizard.

When you use the Server.Transfer() method to navigate from one page to another, both the pages share the same HTTP context. From the first page, you can add items to the HTTP context and then retrieve these items in the second page.

The HttpContext object gives access to all the information about the current HTTP request. It exposes a key-value collection via the Items property in which you can add values that will be available for the life of the current request.

In this exercise, I'll show you how to use the Items property of the HttpContext object to retrieve values from previous page of a wizard.

Estimated time: 20 minutes

  1. Add a Web form to the project. Name it Magazine1.aspx.

  2. Drag two Label controls, a TextBox control (txtCode), and a Button control (btnCode) on the Web form. (see Figure 3.18).

  3. Figure3.18Figure 3.18 The first page of the wizard publishes its properties to the other page by adding it to a key-value collection via the HttpContext.Items property.

  4. Switch to the code view of the form. Add the following code in the class definition:

  5. // Declaring Code property to expose
    // the txtCode control's value
    public String Code
    {
      get
      {
        return txtCode.Text;
      }
    }
  6. Double-click the Next button control and add the following code in the Click event handler:

  7. private void btnNext_Click(
      object sender, System.EventArgs e)
    {
      // Adding the Code to the Items 
      // collection of the HttpContext
      // object for the current request
      Context.Items.Add("Code", txtCode.Text);
      // Calling the Server.Transfer method
      Server.Transfer("Magazine2.aspx");
    }
  8. Add another Web form to the project. Name it Magazine2.aspx.

  9. Drag two Label controls, two TextBox controls (txtName and txtAddress), and a Button control (btnCode) to the Web form (see Figure 3.19).

  10. Add the following code in the Page_Load() event handler:

  11. private void Page_Load(
      object sender, System.EventArgs e)
    {
      if(!IsPostBack)
      {
        // Fetch the Code value from the 
        // HttpContext object of the 
        // current request
        string strCode = 
         Context.Items["Code"].ToString();
        lblCode.Text = 
         "Priority Code: " + strCode;
      }
    }
  12. Set Magazine1.aspx as the start page of the project.

  13. Run the project. You will see the first page of the wizard as shown in Figure 3.18. Enter some text in the text box and click the Next button. You can see that the second page can retrieve the information entered in the first page of the wizard (see Figure 3.19) .

Figure3.19Figure 3.19 The second page of the wizard fetches the value of first page in the wizard through a key-value collection via the HttpContext.Items property.

Review Questions

  1. What is a postback? How can you determine when a postback occurs in an ASP.NET page?

  2. What file do you use to handle Session and Application level events?

  3. What are the classes mapped to the Response, Request, Server, Application, and Session properties of the Page class?

  4. What are the client-side techniques available for state management?

  5. What are the benefits of using view state in ASP.NET?

  6. What is the significance of setting the EnableViewStateMac property to true?

  7. What is the difference between the client-side and the server-side state management techniques?

  8. What type(s) of data can be stored in a session state and in an application state?

  9. When would you store an object in the session state instead of the application state?

  10. What methods can be called to perform server-side redirection to an ASPX page?

Exam Questions

  1. You are developing a Web form to display weather information. On the initial requests to the Web form, you need to do some initialization that will change the appearance of the form and assign values to some controls. However, this initialization should not be repeated again when the user submits the Web form. How should you write the code to accomplish this? (Select two)

    1. Write the code inside the Page_Init() event handler.

    2. Write the code inside the Page_Load() event handler.

    3. Execute the initialization code only when the Page.IsPostBack property is true.

    4. Execute the initialization code only when the Page.IsPostBack property is false.

  2. You have used ASP.NET to develop an inventory management system for your organization. Associates can access this application from the company's intranet. When analyzing users' feedback on the applications, you found that users complain that they receive an annoying flash when they submit forms. They also complain that the data entry form does not always remember the active controls and because of this, users have to press the Tab key several times before they can focus again on the desired control. This makes the data entry inconvenient and time- consuming. On analyzing further usage data, you found that all the users in your company use Internet Explorer 5.0 or above to access your application. What should you do to eliminate the problems reported by the users?

    1. Set SmartNavigation attribute of the Page directive to true.

    2. Set AutoEventWireup attribute of the Page directive to true.

    3. Set EnableViewState attribute of the Page directive to true.

    4. Set ClientTarget attribute of the Page directive to "ie5".

  3. You are developing an ASP.NET Web site for a popular Web development magazine. You want to keep track of how many times each page of your Web application is accessed. This data will help your company to analyze the usage pattern and develop most appropriate content. You want to write minimum code to achieve this task; which of the following techniques will you use?

    1. Use the Page_Load() event handler to increment the usage counter of the page.

    2. Use the Application_BeginRequest() event handler to increment the usage counter of the page.

    3. Use the Session_Start() event handler to increment the usage counter of the page.

    4. Use the Application_Start() event handler to increment the usage counter of the page.

  4. You are designing a Web application for a multinational company. When users access the Web site, you want them to be automatically redirected to a page specific to their country. Your colleague has developed a method that determines the user's country from the HTTP Request and does the redirection. Where should you call this method in your application?

    1. The Session_Start() event handler of the global.asax file

    2. The Begin_Request() event handler of the global.asax file

    3. The Page_Load() event handler of the default.aspx file

    4. The Application_Start() event handler of the global.asax file

  5. Your ASP.NET page contains a page-level variable of ArrayList type. You want to preserve the value of this variable across page postbacks. You do not need this variable in any other page in the application. Which of the following state management techniques provides the best way to achieve this?

    1. Query strings

    2. Cookies

    3. Session

    4. View state

  6. You are developing a Web application for an online bank. Your application allows users to access their account information and transactions right from their desktops. When the user logs on to your application, you want to show the username and current balance on all the pages of the application until the user logs off. You want your application to be safe from malicious users. Which of the following state management techniques should you use? (Select the best answer.)

    1. Cookies

    2. View state

    3. View state with encryption

    4. Session

  7. You are developing an online retail store using ASP.NET. Users can freely access the catalogs and add items to their shopping carts. Users are only required to log on to the Web site when they are ready to check out. However, you want to remember each user's name and greet the users on their future visits to the retail store. Which of the following state management techniques helps you accomplish this? (Select the best answer.)

    1. Hidden fields

    2. View state

    3. Cookies

    4. Session

  8. You have developed and deployed a Web application for an online bank. This application allows users to access their account information and transactions right from their desktops. Because the application deals with financial data, you have enabled encryption for the view state of all the pages. The bank business has rapidly increased, and the management has decided to upgrade the single Web server to a Web farm of Web servers. When you were testing the application for the Web farm, sometimes the application worked fine while other times it generated a view state error. What should you do to resolve this problem?

    1. Use the same validation key for all the Web servers in a Web farm.

    2. Use different validation keys for all the Web servers in a Web farm.

    3. Set the EnableViewStateMac attribute to true for all the pages in the application.

    4. Set the EnableViewStateMac attribute to false for all the pages in the application.

  9. You have recently developed and deployed a Web application for a large automotive parts supplier. This application is used by users from the United States, Europe, and Asia. You have received complaints from several users that the Web pages take very long to download. You did some research and found out that an HTML element named __VIEWSTATE in your pages is storing a large amount of data and is responsible for bigger page sizes. Your manager recommended that you to disable view state wherever it is not needed in the application. In which of the following cases would you like to disable view state in your application? (Select all that apply)

    1. Those pages that do not postback.

    2. Those pages that postback.

    3. Those controls that are not dynamically changed.

    4. Those controls that are dynamically changed.

    5. Those controls that are modified at every page load.

    6. Those controls that are not modified at every page load.

  10. You have recently developed and deployed a Web application for a large automotive parts supplier. This application is used by users from the United States, Europe, and Asia. You have received complaints from several users that the Web pages take very long to download. You did some research and found that an HTML element named __VIEWSTATE in your pages is storing a large amount of data and is responsible for bigger page sizes. You have also found that some of your pages do not use view state. You want to do minimum modification to the code. How would you disable view state for such pages?

    1. Set the EnableViewState property for all the Web server controls to false.

    2. Set the EnableViewState attribute of the Page directive to false.

    3. Set the EnableViewStateMac attribute of the Page directive to false.

    4. Set the EnableViewState attribute to false for the <Pages> element in the web.config file.

  11. In a Web page of your application, you allow users to select a product and its quantity. When the user has made her selection, you want to transfer the user to another page named "ShoppingCart.aspx" with the ProductId and Quantity as the query string parameters to the ASPX page. Which of the following methods would you use in your code to accomplish this?

    1. A HyperLink control

    2. The Response.Redirect() method

    3. The Server.Transfer() method

    4. The Server.Execute() method

  12. You are using a DataGrid control in a Web form "ShowData.aspx" of your Web application. You want to invoke another ASP.NET page, "GetData.aspx," that returns the data to be displayed in the DataGrid control. Which of the following methods would you use to invoke "GetData.aspx" from "ShowData.aspx"?

    1. A HyperLink control

    2. The Response.Redirect() method

    3. The Server.Transfer() method

    4. The Server.Execute() method

  13. You are developing an online bill payment system using ASP.NET. When a user logs on to the application by entering her username and password, you want to programmatically redirect the user to a page named "accountdetails.aspx" in the same Web application. You want an application that responds quickly to the users. Which of the following methods would you use to accomplish this?

    1. A HyperLink control

    2. The Response.Redirect() method

    3. The Server.Transfer() method

    4. The Server.Execute() method

  14. You are using a DataGrid control in an ASP.NET page ("ShowData.aspx") of your Web application. You want to invoke another ASP.NET page, "GetData.aspx," that returns the data to be displayed in the DataGrid control. You are using the Server.Execute() method to invoke "GetData.aspx" from the "ShowData.aspx" page. When you run the application, you get an Invalid View state error. Which of the following options would you choose to resolve this error?

    1. Use the Server.Transfer() method instead of the Server.Execute() method.

    2. Set the EnableViewStateMac attribute to false in the Page directive of "GetData.aspx."

    3. Set the EnableViewStateMac attribute to false in the Page directive of "ShowData.aspx."

    4. Set the EnableViewState attribute to false in the Page directive of "GetData.aspx."

  15. You are creating a Web site that allows users to create online communities to interact with their friends and families. The creation of a community requires the user to register with the Web site. You have created a User Registration Wizard that allows users to enter registration information in a step by step manner. The Wizard consists of two ASPX pages. You want all the data entered by the user in the first ASPX page to be available in the second page. For security reasons, you are not allowed to disable the view state machine authentication check in your ASP.NET pages. Which of the following options would you use? (Select two)

    1. For each screen, add the collected data to the Context.Items collection and retrieve the information from this collection in the last ASPX page.

    2. Use the Request.Form collection in the last ASPX page to retrieve the information entered by the user.

    3. Use the Server.Transfer() method to transfer the control from one wizard page to the next wizard page.

    4. Use the Server.Execute() method to transfer the control from one wizard page to the next wizard page.

Answers to Review Questions

  1. When a user submits the form to the Web server, it is called as a postback. The Page.IsPostBack property, when true, indicates that the page is loaded as a result of postback from the client.

  2. The ASP.NET application file, global.asax, contains event handlers to handle Session and Application level events.

  3. The classes that map to the Response, Request, Server, Application, and Session properties of the Page class are HttpResponse, HttpRequest, HttpServerUtility, HttpApplicationState, and HttpSessionState, respectively.

  4. You can use query strings, cookies, hidden fields, and view state for managing state at the client side.

  5. View state provides the following benefits:

    • It maintains the state of non-postback controls in a page across page postbacks.

    • You can store any object in the view state as long as it is serializable.

    • You can customize view state to enable protection and encryption.

  6. The EnableViewStateMac property, when set to true, performs a machine authentication check (MAC) on the view state during postback to verify that the view state has not been tampered with at the client side.

  7. The client-side state management techniques consume client resources to manage state, whereas the server-side techniques consume server resources to manage state.

  8. Any object that inherits from System.Object, directly or indirectly by chain of its inheritance, can be stored in session state and application state.

  9. When you need to store data that does not apply to all the users of the application but only to specific users, you should choose session state instead of the application state.

  10. Server.Transfer() and Server.Execute() methods can perform server-side redirection to an ASPX page.

Answers to Exam Questions

  1. B and D. The code for the initialization of controls should be placed inside the Page_Load() event handler. If you want to execute the initialization code only when the page is first requested and do not want to run that code again at the time of page postback, you must execute the code when the IsPostBack property of the Page class is false. For more information, see the section "The IsPostBack Property" in this chapter.

  2. A. When all users are using Internet Explorer versions 5.0 or later, you can set the SmartNavigation property to true. This will eliminate the flash and will cause Internet Explorer to focus active control. For more information, see the section "The SmartNavigation Property" in this chapter.

  3. B. Options C and D do not work with each page request, so only options A and B are viable choices. Between these two choices, you should choose to write the code in the Application_BeginRequest() event handler of the global.asax file because if you use the Page_Load() event handler, you'll have to write code in each and every ASPX page in the application. For more information, see the section "ASP.NET Application" in this chapter.

  4. A. When a user visits the site, the browser establishes a new session with the Web server. At that time, the Session_Start() event handler is executed. This method is executed only once for the user session and is an appropriate choice for the case in question. Page_Load() event handler might not work in all cases because the user could enter the Web site through a page other than default.aspx. Begin_Request() works for the entire HTTP request and not just the first request. The Application_Start() method will only redirect the first user of the application. For more information, see the section "ASP.NET Application" in this chapter.

  5. D. Because the variable is only required on a single page, you might not want to consume server resources by storing the values in session. You can instead use a client-side technique for state management, but cookies and hidden fields do not allow you to stored structured data. Therefore, the best option is to use view state. For more information, see the section "State Management" in this chapter.

  6. D. Cookies can be easily accessed and used by malicious users. View state with encryption does provide a high level of encryption but is only available on the same page. In the application, you want the name and current balance to be displayed on all the pages, so the correct choice is session. Session data is stored at the server side and cannot be easily tampered with. For more information, see the section "State Management" in this chapter.

  7. C. You want the information to be available across browser restarts. In this case, cookies are the right choice because they allow you to store a small amount of information on the user's computer. For more information, see the section "Client-side Techniques for State Management" in this chapter.

  8. A. When you use view state encryption in a Web farm, you must use the same validation key for all the Web servers. If the validation keys don't match, you will get an error when the user is directed to a different server in the Web farm. For more information, see the section "View State" in this chapter.

  9. A, C, and E. If the pages don't postback to themselves, they are not making use of view state; in that case, it's a good idea to disable view state for the whole page. For all other pages, the controls that are not dynamically changed need not have their view state enabled. Also, the controls whose values are modified on every page load need not store their values in the view state. For more information, see the section "View State" in this chapter.

  10. B. Setting the EnableViewState property for all the Web server controls to false does the trick but involves a lot of coding. An option that requires less code is to set the EnableViewState attribute of the Page directive to false. Changing EnableViewState to false in the web.config file will affect all the pages in the Web application—not just the one that uses view state—and is not recommended in the given case. For more information, see the section "View State" in this chapter.

  11. B. You cannot use query strings with the Server.Transfer() and Server.Execute() methods. The Hyperlink control does accept query strings, but the redirection needs to be performed within code. Therefore, the only choice that works is the use of Response.Redirect() method. For more information, see the section "Navigation Between Pages" in this chapter.

  12. D. Only the Server.Execute() method works like a method call. That is, it invokes the specified page and returns the control back to the original page. For more information, see the section "The Server.Execute() Method" in this chapter.

  13. C. Response.Redirect() involves an additional roundtrip and therefore is not a good option when you want the application to be faster. You should instead use the Server.Transfer() method to redirect your user to another ASPX page on the same Web server. For more information, see the section "The Server.Transfer() Method" in this chapter.

  14. B. You get an error while executing the Server.Execute() method because the view state of the "ShowData.aspx" page is passed to the "GetData.aspx" page along with the form and query string collections, causing the ASP.NET machine authentication check to fail. You need to set the EnableViewState attribute of the Page directive in the "GetData.aspx" page to false in order to resolve this error. For more information, see the section "Navigation Between Pages" in this chapter.

  15. A and C. You should choose Server.Transfer() and Context.Items to accumulate data from the previous page over the Server.Execute() and Request.Form methods because you cannot disable the view state machine authentication check and thus cannot preserve the form data. For more information, see the section "Navigation Between Pages" in this chapter.

Suggested Readings and Resources

  1. The Visual Studio .NET Combined Help Collection, including the following:

    • Introduction to Web Forms State Management

    • Web Forms Page Processing

  2. ASP.NET/Visual Studio .NET Tips. http://www.swarren.net

  3. Fritz Onion. Essential ASP.NET. Addison-Wesley, 2002

  4. Jeff Prosise. Programming Microsoft .NET. Microsoft Press, 2002

 

  • + Share This
  • 🔖 Save To Your Account