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
-
Create a new Visual Basic ASP.NET Web Application project at the location http:// localhost/305C03Exercises.
-
Add a Web Form to the project. Name it ShoppingPage.aspx.
-
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.
-
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
-
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
-
Add a new Web Form to the project. Name the Web Form ShoppingCart.aspx.
-
Drag a Hyperlink control (hlShopping) to the Web Form. Set its NavigateUrl property to ShoppingPage.aspx.
-
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
-
Set ShoppingPage.aspx as the start page for the project.
-
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.16 The Add to Cart button updates the session state with the corresponding item and its quantity.
Figure 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
-
Add a Web Form to the project. Name it Magazine1.aspx.
-
Drag two Label controls, a TextBox control (txtCode) and a Button control (btnCode) to the Web Form.
-
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
-
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
-
Add another Web Form to the project. Name it Magazine2.aspx.
-
Drag two Label controls, two TextBox controls (txtName and txtAddress) and a Button control (btnFinish) to the Web Form (see Figure 3.19).
-
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
-
Set the Magazine1.aspx page as the start page of the project.
-
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.18 The first page of the wizard publishes its properties to another page by adding it to the HttpContext.Items collection.
Figure 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
What is a postback? How can you determine when a postback occurs in an ASP.NET page?
What file do you use to handle Session and Application level events?
What are the classes mapped to the Response, Request, Server, Application, and Session properties of the Page class?
What are the client-side techniques available for state management?
What are the benefits of using ViewState in ASP.NET?
What can you achieve by setting the EnableViewStateMac property to true?
What is the difference between the client-side and the server-side state management techniques?
What type of data can be stored in session state and in application state?
When would you store an object in the session state instead of the application state?
What methods can be called to perform server-side redirection to an ASPX page?
Exam Questions
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.)
In the Page_Init() method.
In the Page_Load() method.
Execute the initialization code only when the Page.IsPostBack property is true.
Execute the initialization code only when the Page.IsPostBack property is false.
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?
Set SmartNavigation to true.
Set AutoEventWireup to true.
Set EnableViewState to true.
Set ClientTarget to "ie5".
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?
Use the Page_Load() method to increment the usage counter of the page.
Use the Application_BeginRequest() method to increment the usage counter of the page.
Use the Session_Start() method to increment the usage counter of the page.
Use the Application_Start() method to increment the usage counter of the page.
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?
Session_Start() method of the global.asax file
Begin_Request() method of the global.asax file
Page_Load() method of the default.aspx file
Application_Start()method of the global.asax file
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?
Query strings
Cookies
Session
ViewState
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?
Cookies
ViewState
ViewState with encryption
Session
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?
Hidden fields
ViewState
Cookies
Session
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?
Use same validation key for all the Web servers in the Web farm.
Use different validation key for all the Web servers in the Web farm.
Set EnableViewStateMac attribute to True for all the pages in the application.
Set EnableViewStateMac attribute to False for all the pages in the application.
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.)
Those pages that do not post back.
Those pages that post back.
Those controls that are not dynamically changed.
Those controls that are dynamically changed.
Those controls are modified at every page load.
Those controls that are not modified at every page load.
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?
Set the EnableViewState property for all the Web server controls to false.
Set the EnableViewState attribute of the @Page directive to false.
Set the EnableViewStateMac attribute of the @Page directive to false.
Set the EnableViewState attribute to false for the <Pages> element in the web.config file.
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?
HyperLink control
Response.Redirect() method
Server.Transfer() method
Server.Execute() method
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"?
HyperLink control
Response.Redirect() method
Server.Transfer() method
Server.Execute() method
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?
HyperLink control
Response.Redirect() method
Server.Transfer() method
Server.Execute() method
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?
Use the Server.Transfer() method instead of the Server.Execute() method.
Set the EnableViewStateMac attribute to false in the @Page directive of GetData.aspx.
Set the EnableViewStateMac attribute to false in the @Page directive of ShowData.aspx.
Set the EnableViewState attribute to false in the @Page directive of GetData.aspx.
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.)
For each screen add the collected data to Context.Items collection and retrieve the information from this collection in the last ASPX page.
Use the Request.Form collection in the last ASPX page to retrieve the information entered by the user.
Use the Server.Transfer() method to transfer the control from one wizard page to the next wizard page.
Use the Server.Execute() method to transfer the control from one wizard page to the next wizard page.
Answers to Review Questions
-
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.
-
The ASP.NET application file global.asax contains event handlers to handle Session and Application level events.
-
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.
-
You can use Query strings, cookies, hidden fields, and ViewState for managing state at the client-side.
-
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.
-
-
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.
-
The client-side state management techniques consume client resources to manage state where as the server-side techniques consume server resources to manage state.
-
Any object that inherits from System.Object directly or indirectly by chain of its inheritance, can be stored in session state or application state.
-
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.
-
Server.Transfer() and Server.Execute().
Answers to Exam Questions
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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
-
The Visual Studio .NET Combined Help Collection, including the following:
-
Introduction to Web Forms State Management
-
Web Forms Page Processing
-
-
ASP.NET/Visual Studio .NET Tips. http://www.swarren.net
-
Fritz Onion. Essential ASP.NET. Addison-Wesley,
-
Jeff Prosise. Programming Microsoft .NET. Microsoft Press,