Home > Articles > Programming > User Interface (UI)

  • 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 a user's selection as he explores the store rather than requiring the user 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: 10 minutes

  1. Create a new Visual Basic ASP.NET Web Application project at the location http:// localhost/305C03Exercises.

  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) to a table on the Web Form. Figure 3.16 shows a design for this Web Form.

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

    ' Add the selected item to
    ' the session state
    Private Sub AddToSession( _
     ByVal strProduct As String, _
     ByVal intQty As Integer)
      If Not Session(strProduct) _
       Is Nothing Then
        ' If the product already exist,
        ' increase its quantity
        Session(strProduct) = _
         CInt(Session(strProduct)) + intQty
      Else
        Session(strProduct) = intQty
      End If
    End Sub
  5. Double-click the three button controls and add the following code to their Click event handlers:

    Private Sub btnNK_Click( _
     ByVal sender As System.Object, _
     ByVal e As System.EventArgs) _
     Handles btnNK.Click
      ' Add the selected item
      ' to the shopping cart
      AddToSession("NK", _
       Int32.Parse(txtNK.Text))
      ' Display shopping cart
      Server.Transfer("ShoppingCart.aspx")
    End Sub
    
    Private Sub btnCF_Click( _
     ByVal sender As System.Object, _
     ByVal e As System.EventArgs) _
     Handles btnCF.Click
      ' Add the selected item
      ' to the shopping cart
      AddToSession("CF", _
       Int32.Parse(txtCF.Text))
      ' Display shopping cart
      Server.Transfer("ShoppingCart.aspx")
    End Sub
    
    Private Sub btnHA_Click(
     ByVal sender As System.Object, _
     ByVal e As System.EventArgs) _
     Handles btnHA.Click
      ' Add the selected item
      ' to the shopping cart
      AddToSession("HA", _
       Int32.Parse(txtHA.Text))
      ' Display shopping cart
      Server.Transfer("ShoppingCart.aspx")
    End Sub
  6. Add a new Web Form to the project. Name the Web Form ShoppingCart.aspx.

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

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

    Private Sub Page_Load( _
     ByVal sender As System.Object, _
     ByVal e As System.EventArgs) _
     Handles MyBase.Load
      Response.Write( _
       "The shopping cart contains " & _
       "the following items: <br>")
      ' Display the contents
      ' of the shopping cart
      Dim intI As Integer
      For intI = 0 To Session.Count -
        Select Case Session.Keys(intI)
          Case "NK"
            Response.Write( _
             "New Kandy (" & _
             Session(intI) & ")" _
             & "<br>")
          Case "CF"
            Response.Write( _
             "Chixen Fingerz (" _
             & Session(intI) & _
             ")" & "<br>")
          Case "HA"
            Response.Write( _
             "Hairy Apples (" & _
             Session(intI) & ")" _
             & "<br>")
        End Select
      Next
    End Sub
  9. Set ShoppingPage.aspx as the start page for the project.

  10. Run the project. You'll see a shopping page as shown in Figure 3.16. Enter quantity for a product and click 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 this cart, and you'll note that shopping cart remembers your selections.

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

Figure 3.17Figure 3.17 The shopping cart page summarizse user's selection by retrieving the information from the session state.

3.2 - Creating a Wizardlike User Interface

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

In a wizardlike interface, all the Web Forms that make up the wizard are accessed in the same HTTP context. You can access this context in any page using the Context property of the Page class. The Context property provides access to the HttpContext object for the current request.

The HttpContext object gives access to all the information about the current HTTP request. It exposes an Items collection, in which you can add values that will be available for the life of the current request. The Page class contains a property called Context that provides access to the HttpContext object for the current request.

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

Estimated time: 10 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) to the Web Form.

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

    ' Declaring a Code property to expose
    ' the txtCode control's value
    Public ReadOnly Property Code() As String
      Get
        Code = txtCode.Text
      End Get
    End Property
  4. Double-click the Button control and add the following code in the Click event handler:

    Private Sub btnCode_Click( _
     ByVal sender As System.Object, _
     ByVal e As System.EventArgs) _
     Handles btnCode.Click
      ' 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")
    End Sub
  5. Add another Web Form to the project. Name it Magazine2.aspx.

  6. Drag two Label controls, two TextBox controls (txtName and txtAddress) and a Button control (btnFinish) to the Web Form (see Figure 3.19).

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

    Private Sub Page_Load( _
     ByVal sender As System.Object, _
     ByVal e As System.EventArgs) _
     Handles MyBase.Load
      If Not IsPostBack Then
        ' Fetch the Code value from the
        ' HttpContext object
        ' of the current request
        Dim strCode As String = _
         Context.Items("Code").ToString()
        Response.Write( _
         "Priority Code: " & strCode)
      End If
    End Sub
  8. Set the Magazine1.aspx page as the start page of the project.

  9. 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).

Figure 3.18Figure 3.18 The first page of the wizard publishes its properties to another page by adding it to the HttpContext.Items collection.

Figure 3.19Figure 3.19 The second page of the wizard fetches the value of the first page in the wizard through the HttpContext.Items collection.

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 ViewState in ASP.NET?

  6. What can you achieve by 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 of data can be stored in session state and in 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. Where should you put the code? (Select two.)

    1. In the Page_Init() method.

    2. In the Page_Load() method.

    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 about the application, you found that users complain that they receive an annoying flash when they submit forms. They also complain that the data entry form sometimes does not remember the active controls and because of this, they 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.5 or above to access your application. What should you do to eliminate the problems reported by the users?

    1. Set SmartNavigation to true.

    2. Set AutoEventWireup to true.

    3. Set EnableViewState to true.

    4. Set ClientTarget 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 appropriate content. You want to write the minimum code to achieve this task; which of the following techniques will you use?

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

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

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

    4. Use the Application_Start() method 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, they should 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. Session_Start() method of the global.asax file

    2. Begin_Request() method of the global.asax file

    3. Page_Load() method of the default.aspx file

    4. Application_Start()method of the global.asax file

  5. Your ASP.NET page contains a page-level ArrayList variable. 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 you the best way to achieve this?

    1. Query strings

    2. Cookies

    3. Session

    4. ViewState

  6. You are developing a Web application for an online bank. Your application allows users to access 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?

    1. Cookies

    2. ViewState

    3. ViewState 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 the shopping cart. Users are only required to log on to the Web site when they are ready to check out. However, you want to remember users' names and greet the users on their future visits to the retail store. Which of the following state management techniques helps you accomplish this?

    1. Hidden fields

    2. ViewState

    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 ViewState of all the pages. The bank business rapidly increased and the management decided to upgrade the single Web server to a Web Farm of Web servers. When you were testing the application for the Web Form, sometimes the application worked fine while other times it generated a ViewState error. What should you do to resolve this problem?

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

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

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

    4. Set 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 in the United States, and from several countries 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. Your manager recommended that you disable ViewState where ever it is not needed in the application. In which of the following cases can you safely disable ViewState in your application? (Select three.)

    1. Those pages that do not post back.

    2. Those pages that post back.

    3. Those controls that are not dynamically changed.

    4. Those controls that are dynamically changed.

    5. Those controls 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, and several countries in 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 ViewState. You want to do minimum modification to the code. How would you disable ViewState 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 finished making selections, you want to transfer them 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. HyperLink control

    2. Response.Redirect() method

    3. Server.Transfer() method

    4. 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" which returns the data to be displayed in the DataGrid control. Which of the following method would you use to invoke "GetData.aspx" from "ShowData.aspx"?

    1. HyperLink control

    2. Response.Redirect() method

    3. Server.Transfer() method

    4. 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 user name 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. HyperLink control

    2. Response.Redirect() method

    3. Server.Transfer() method

    4. 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" which returns the data to be displayed in the DataGrid control. You are using Server.Execute() method to invoke "GetData.aspx" from "ShowData.aspx" page. When you run the application, you get an Invalid ViewState error. Which option 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 a 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 four ASPX files. You want all the data entered by a user in the first three ASPX files to be available in the fourth file. For security reasons, you are not allowed to disable the ViewState 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 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 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 ViewState for managing state at the client-side.

  5. ViewState 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 ViewState as long as it is serializable.

    • You can customize ViewState to enable protection and encryption.

  6. When the EnableViewStateMac property is set to True, ASP.NET performs a machine authentication check (MAC) on the ViewState during postback to verify that the ViewState has not been tampered with at the client-side.

  7. The client-side state management techniques consume client resources to manage state where as 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 or application state.

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

  10. Server.Transfer() and Server.Execute().

Answers to Exam Questions

  1. B and D. The code for initialization of controls should be placed inside the Page_Load() method. 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 then you must execute the code when the IsPostBack property of the Page class is false.

  2. A. When all users are using Internet Explorer Versions 5.5 or later, you can set the SmartNavigation property to true. This will eliminate the flash and will cause Internet Explorer to focus active control.

  3. B. Options C and D do not work with each page request, so only options A and B are the viable choices. Among these two choices, you should choose to write the code in the Application_BeginRequest() method of the global.asax file because if you use the Page_Load() method, you'll have to write code in each and every ASPX file in the application.

  4. A. When a user visits the site, a browser establishes a new session with the Web server. At that time the Session_Start() method is executed. This method is executed only once for the user session and is an appropriate choice for the case in question. Page_Load() may not work in all cases because users might come to your Web site by clicking a link of some other file. Begin_Request() work for the entire HTTP request and not just the first request. Application_Start() method will only redirect the first user of the application.

  5. D. Because the variable is only required on a single page, you may 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 ViewState.

  6. D. Cookies can be easily accessed and used by malicious users. ViewState 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. Sessions are stored at the server side and cannot be easily tampered with.

  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 small amount of information the user's computer.

  8. A. When you use ViewState 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.

  9. A, C, and E. If the pages don't postback to themselves, they are not using ViewState; in that case, it's a good idea to disable ViewState for the whole of the page. For all other pages, the controls that are not dynamically changed need not have their ViewState enabled. Also, the controls whose value is modified at every page load need not store value in the ViewState.

  10. B. Setting EnableViewState property for all the Web server controls to false does the trick but involves a lot of coding. An option that requires lesser code is to set the EnableViewState attribute of the @Page directive to false. Changing EnableViewState to false in web.config file will affect all the pages in the Web application, not just the one which use ViewState and is not recommended in the given case.

  11. B. Query strings are not automatically passed with the Server.Transfer() and Server.Execute() methods. Hyperlink control does accept query strings but not when they are dynamically created as in the above question therefore the best choice is the use of Response.Redirect() method.

  12. D. Only Server.Execute() method works like a function call. That is invoking the specified page and returns the control back to the original page.

  13. C. Response.Redirect() involves additional round trips and therefore is not a good option when you want the application to be responsive at each level. You should instead use Server.Transfer() method to redirect your user to another ASPX page on the same Web server.

  14. B. You get an error while executing Server.Execute() method because the ViewState of "ShowData.aspx" page is passed to "GetData.aspx" page causing the ASP.NET machine authentication check to fail. You need set EnableViewState attribute of the @Page directive in the "GetData.aspx" page to false in order to resolve this error.

  15. A and C. You should use Context.Items to accumulate data from the previous pages, because neither the Server.Transfer() method nor the Server.Execute() method preserves the form data by default. When choosing between Server.Transfer() and Server.Execute(), you need Server.Transfer() in the case mentioned in the question as you'll progress from one page to another.

Recommended Reading

  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,

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

  • + Share This
  • 🔖 Save To Your Account