Tài liệu Maintaining State in a Web Application pptx

22 412 0
Tài liệu Maintaining State in a Web Application pptx

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Maintaining State in a Web Application The Hypertext Transport Protocol (HTTP) doesn't maintain state between pages served by your Web server during each round-trip. This means that any information you provided in a form is for-gotten when you get a new page. If you're simply receiving static HTML Web pages, then this isn't a problem. If you're placing an order for a product, however, then the server needs to remember what you ordered. To get the Web server to remember what you did during the last round-trip, you can store information on the server or on the client computer the browser is running on. Storing information on the client means you don't use up any resources on the server to store that information, and your Web application can potentially handle many more users. Storing information on the server gives you more control of the stored information, but since this consumes server resources, you need to be careful not to store too much; otherwise your Web application won't be able to handle many users. Storing Information on the Client To store information on the client, you can use cookies or the Page object's ViewState property. Let's take a look at how you use cookies and the ViewState property. Storing Information using Cookies A cookie is a name and value pair that is stored in a small file that resides on the hard drive of the client computer. You use the name to identify the value being stored; both the name and value are string objects. Warning Cookies are potentially problematic because the user can configure their browser to prevent cookies from being stored. Also, a browser stores only a limited number of cookies: 300 in total and no more than 20 per Web server. You should therefore use cookies sparingly-if at all. The following example creates an int variable named myInt that is set to 1 and creates an HttpCookie object that stores myInt under the name count: int myInt = 1; HttpCookie myHttpCookie = new HttpCookie("count", myInt.ToString()); Because a cookie stores the value as a string, you use the ToString() method to convert myInt to a string before storing it in myHttpCookie. To store the cookie on the client, you call the AppendCookie() method of the Page object's Response: Response.AppendCookie(myHttpCookie); The Response object is the HTTP response sent by the Web server to the browser. When this code is run, it causes the browser to store the cookie on the client computer's hard disk in the directory specified in the settings for the browser. You can retrieve the count value from the Cookies collection of the Request object: myInt = Int32.Parse(Request.Cookies["count"].Value); The Request object is sent by the browser to the Web server and contains the cookie previously set. Because the count value is stored as a string, you use the static Parse() method of the Int32 structure to convert the string to an int. Listing 15.6 shows an example ASP.NET application that uses a cookie to keep track of the number of times the page has been viewed. Listing 15.6: CookieTest.aspx <!-- CookieTest.aspx illustrates the use of a cookie to store information on the client --> <html> <head> <script language="C#" runat="server"> void Page_Load(Object sender, EventArgs e) { int myInt; // check if count is null if (Request.Cookies["count"] == null) { // count is null, so initialize myInt to 1 myInt = 1; // create an HttpCookie object HttpCookie myHttpCookie = new HttpCookie("count", myInt.ToString()); // add HttpCookie object to Response Response.AppendCookie(myHttpCookie); } else { // retrieve count and increment myInt by 1 myInt = Int32.Parse(Request.Cookies["count"].Value) + 1; } // set count value to myInt Response.Cookies["count"].Value = myInt.ToString(); // display myInt in myLabel myLabel.Text = "This page has been viewed "+ myInt.ToString() + " times."; } </script> </head> <body> <asp:Label id="myLabel" runat="server"/> <form runat="server"> <asp:Button text="Press the Button!" runat="server"/> </form> </body> </html> Note Notice that you can embed C# code directly into an .aspx file. The CookieTest.aspx file was created using Microsoft Notepad. To run CookieText.aspx, simply copy this file into your Inetpub\wwwroot directory and point your browser to http://localhost/CookieTest.aspx. Figure 15.23 shows the page generated by CookieTest.aspx-assuming that the button on the page has been repeatedly pressed. Figure 15.23: The running CookieTest.aspx page Storing Information using the ViewState Property You use the Page object's ViewState property to access a StateBag object, which stores a collection of name and value pairs on the client computer. You use the name to identify the value being stored. The name is a string and the value is an object. Unlike a cookie, a user cannot prevent values from being stored using the ViewState property. One use for the ViewState property would be to store a user's name. Tip Since the values are sent back and forth between the client and the server, you should store only a small amount of information using the ViewState property. This is still a better solution than using cookies because the user can always prevent cookies from being stored. The following example stores myInt under the name count: int myInt = 1; ViewState["count"] = myInt; You can then retrieve the count value using the following code: myInt = (int) ViewState["count"]; Because a value is stored as an object, you must cast it to the specific type you want to use. In this example, the count value is cast to an int. Listing 15.7 shows an example ASP.NET page that uses the ViewState property to keep track of the number of times the page has been viewed. Listing 15.7: ViewStateTest.aspx <!-- ViewStateTest.aspx illustrates the use of ViewState to store information on the client --> <html> <head> <script language="C#" runat="server"> void Page_Load(Object sender, EventArgs e) { int myInt; // check if count is null if (ViewState["count"] == null) { // count is null, so initialize myInt to 1 myInt = 1; } else { // retrieve count and increment myInt by 1 myInt = (int) ViewState["count"] + 1; } // set count value to myInt ViewState["count"] = myInt; // display myInt in myLabel myLabel.Text = "This page has been viewed "+ myInt.ToString() + " times."; } </script> </head> <body> <asp:Label id="myLabel" runat="server"/> <form runat="server"> <asp:Button text="Press the Button!" runat="server"/> </form> </body> </html> Storing Information on the Server To store information on the server, you can use the Page object's Session, Application, or Cache object. These objects all store information in the form of name and value pairs, where the name is a string and the value is an object. You can also store information in the database itself, which is the best solution if you need to store a lot of information about a user or the application. Finally, you can of course always store information in static variables or objects. You'll learn about the Session, Application, and Cache objects in the next sections. I'll also discuss storing information about a Web application in the database. Storing Information Using a Session Object A Session object allows you to store separate information for each user. The information stored in the Session object remains on the server up to a default time of 20 minutes, after which the information is thrown away. One use for the Session object might be to store the user's name. Tip Because each Session object stores information for a single user, store the absolute minimum information for each user. Otherwise, your Web server could be swamped with Session objects and run out of memory, and your application wouldn't support large numbers of users. The information is stored in name and value pairs, where the name is a string and the value is an object. The following example stores myInt under the name count: int myInt = 1; Session["count"] = myInt; You can then retrieve the count value using the following code: myInt = (int) Session["count"]; Because a value is stored as an object, you must cast it to the specific type you want to use. In this example, the count value is cast to an int. Listing 15.8 shows an example ASP.NET page that uses the Session object to keep track of the number of times the page has been viewed. This information is specific to each user, and therefore shows the total number of times the page has been viewed by the current user. Listing 15.8: SessionObjectTest.aspx <!-- SessionObjectTest.aspx illustrates the use of the Session object to store information on the server. This information is specific for each user. --> <html> <head> <script language="C#" runat="server"> void Page_Load(Object sender, EventArgs e) { int myInt; // check if count is null if (Session["count"] == null) { // count is null, so initialize myInt to 1 myInt = 1; } else { // retrieve count and increment myInt by 1 myInt = (int) Session["count"] + 1; } // set count value to myInt Session["count"] = myInt; // display myInt in myLabel myLabel.Text = "This page has been viewed "+ myInt.ToString() + " times."; } </script> </head> <body> <asp:Label id="myLabel" runat="server"/> <form runat="server"> <asp:Button text="Press the Button!" runat="server"/> </form> </body> </html> Storing Information using the Application Object The Application object allows you to store information that is shared for all users. One use for the Application object might be to store a DataSet object containing a product catalog. The information is stored in name and value pairs, where the name is a string and the value is an object. The following example stores myInt under the name count: int myInt = 1; Application["count"] = myInt; You can then retrieve the count value using the following code: myInt = (int) Application["count"]; Listing 15.9 shows an example ASP.NET page that uses the Application object to keep track of the number of times the page has been viewed. This information is shared by all users, and therefore shows the total number of times the page has been viewed by all users. Listing 15.9: ApplicationObjectTest.aspx <!-- ApplicationObjectTest.aspx illustrates the use of the Application object to store information on the server. This information is shared for all users. --> <html> <head> <script language="C#" runat="server"> void Page_Load(Object sender, EventArgs e) { int myInt; // check if count is null if (Application["count"] == null) { // count is null, so initialize myInt to 1 myInt = 1; } else { // retrieve count and increment myInt by 1 myInt = (int) Application["count"] + 1; } // set count value to myInt Application["count"] = myInt; // display myInt in myLabel myLabel.Text = "This page has been viewed "+ myInt.ToString() + " times."; } </script> </head> <body> <asp:Label id="myLabel" runat="server"/> <form runat="server"> <asp:Button text="Press the Button!" runat="server"/> </form> </body> </html> Storing Information using the Cache Object Like the Application object, the Cache object is also shared for all users, but it provides more functionality than the Application object. For example, you can control when the stored information is removed. For more information about the Cache object, consult the .NET online documentation as described in Chapter 1 , "Introduction to Database Programming with ADO.NET." Look up "Cache class" in the index of the online documentation. Storing Information using the Database If you have a large amount of information to store about a user, store it in the database rather than the Session object. For example, if you're building a Web site that a user can order products from, store their shopping cart in the database. Using a DataGrid Control to Access a Database A DataGrid allows you to access rows in a database table. In the following sections, you'll learn how to create an ASP.NET Web application that uses a DataGrid control to access the rows in a database table. The DataGrid you'll create will display the rows from the Products table of the Northwind database. Creating the Web Application Perform the following steps: 1. To create the new project, select File ➣ New Project in VS .NET. Select Visual C# Projects from the Project Types area on the left of the New Project dialog box, and select ASP.NET Web Application from the Templates area on the right. Enter http://localhost/DataGrid-WebApplication in the Location field. Click OK to continue. Your new project will contain a blank form. [...]... 15.14: Displaying the DataGrid events Double-click the PageIndexChanged event and set your DataGrid1_PageIndexChanged() method as follows: private void DataGrid1_PageIndexChanged( object source, System .Web. UI.WebControls.DataGridPageChangedEventArgs e) { DataGrid1.CurrentPageIndex = e.NewPageIndex; sqlDataAdapter1.Fill(dataSet11, "Products"); DataGrid1.DataBind(); } The first statement inside the method... DataGrid1.CurrentPageIndex equal to e.NewPageIndex, the navigation to the new page of rows is performed The second statement is as follows: sqlDataAdapter1.Fill(dataSet11, "Products"); This statement calls the Fill() method of sqlDataAdapter1 to populate dataSet11 with the next set of rows from the Products table The third statement is as follows: DataGrid1.DataBind(); This statement calls the DataBind() method... object to a form was discussed in Chapter 6, "Introducing Windows Applications and ADO.NET," and in Chapter 7, "Connecting to a Database.") Note To display Server Explorer, select View ➣ Server Explorer, or press Ctrl+Alt+S on your keyboard 4 After you drag the Products table to your form, VS NET creates a SqlConnection object named sqlConnection1 and a SqlDataAdapter object named sqlDataAdapter1 Click... body is as follows: DataGrid1.CurrentPageIndex = e.NewPageIndex; This statement sets the current page displayed in DataGrid1 to the new page that is selected using the navigation buttons in the running form You set the current page for DataGrid1 using the CurrentPageIndex property, and you get the new page from the NewPageIndex property of the DataGridPageChangedEventArgs object By setting DataGrid1.CurrentPageIndex... button to save your SELECT statement and close Query Builder Next, you need to create a DataSet object You use a DataSet object to store a local copy of the information stored in the database A DataSet object can represent database structures such as tables, rows, and columns In the example in this section, you'll use a DataSet object to store the rows from the Products table 1 Click an area of your... the data source for your DataGrid and whether you want a header and footer to displayed, among other properties Set your General properties as shown in Figure 15.9 Figure 15.9: The General properties The General properties are as follows: • • • • • DataSource The DataSource is the source of the data for your DataGrid In this example, the DataSource is dataSet11 DataMember The DataMember is the name... grid lines in your DataGrid Set this to blue Border Width Controls the width and units of the grid lines in your DataGrid Once you've set your properties, click the OK button to continue Next, you'll code the PageIndexChanged() event handler to allow navigation of the rows in your DataGrid Coding the PageIndexChanged() Event Handler As mentioned earlier, in addition to enabling paging in the Paging... the DataSource property of your DataGrid to your DataSet object This sets the source of the data for your DataGrid and allows the rows from your DataSet to be displayed in your DataGrid To set the DataSource property, click your DataGrid object and set the DataSource property to dataSet11 Also, set the DataMember property to Products; this is the table with rows that are to be displayed by your DataGrid... Select UnitPrice as the Sort expression o Data Field The name of column o Data Formatting Expression Allows you to format a column value You can use a formatting expression to format dates and numbers, among others For example, {0:$##.00} formats a number, adds a dollar sign at the front, and displays two digits after the decimal point; thus, 19 is formatted as $19.00 Set the formatting expression for... to {0:$##.00} Paging Properties Next, click on the Paging link of the Properties dialog box Normally, all the rows retrieved by a SELECT statement are displayed on a single page for the DataGrid You can use the Paging properties to split all the rows into separate pages, with a fixed number of rows on each page in your DataGrid You can then select the buttons to navigate between these pages of rows You'll . Maintaining State in a Web Application The Hypertext Transport Protocol (HTTP) doesn't maintain state between pages served by your Web server during. database. Using a DataGrid Control to Access a Database A DataGrid allows you to access rows in a database table. In the following sections, you'll learn

Ngày đăng: 24/12/2013, 01:17

Từ khóa liên quan

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan