Quản lý nhà nước trong ứng dụng Web ppt

32 116 0
Quản lý nhà nước trong ứng dụng Web ppt

Đ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

Managing State in Web Applications Chapter 5 Web pages and ASP.NET Framework use HTTP protocol to communicate between a Web browser and a Web server. HTTP is a stateless protocol and cannot automatically indicate whether the sequential requests are coming from the same or different clients. Therefore, when a Web page is posted to the server, a new instance of the Web page class is created. This results in the loss of all the information associated with the page and the controls placed on it. To overcome this limitation, ASP.NET provides the state management feature. In addition, it provides a feature called caching that helps you improve the performance of your Web application. This chapter discusses the various client-side and server-side state management options provided by ASP.NET. In addition, it discusses how to improve the performance of a Web application by using caching. In this chapter, you will learn to:  Implement client-side state management  Implement server-side state management  Manage state by using cross-page posting  Implement caching Objectives NIIT Managing State in Web Applications 5.3 N ot e A new instance of the Web page class is created each time the page is posted to the server. In traditional Web programming, this would typically mean that all information associated with the page and the controls on the page would be lost with each round trip. Consider an example. Suppose a user fills up some personal information on a Web form. While filling up this information, the user selects a country from a drop-down list on the Web page. As soon as the user selects a country, the page needs to be posted back to the server to retrieve a list of state names, which need to be populated in another drop-down list on the same Web page. When the page is posted to the server, a new instance of the Web page class will be created, and therefore, all information previously entered on the Web page will be lost. This problem can be solved by using client-side state management. Client-side state management allows you to store information either on a Web page or on a client computer. Such state management improves the performance of a Web application because it reduces the load on the server. The various options available to implement client-side state management are:  Hidden fields  View state  Control state  Cookies  Query strings You can store only a limited amount of information by using client-side state management. A hidden field is a control similar to a TextBox control. However, unlike a TextBox control, it does not render in a Web browser. As a result, a user cannot type anything in it. Hidden fields can be used to store information that needs to be submitted along with the Web page, but should not be displayed on the page. For example, when the details of a product are displayed on a Web page, the ID of the product can be stored in a hidden field. If the user orders the product, the information stored in the hidden field will be sent to the server and the corresponding product will be added to the shopping cart. Implementing Client-Side State Management Hidden Fields 5.4 Managing State in Web Applications NIIT N ot e Hidden fields can also be used to pass session information to and from forms, transparently. Consider an example. Suppose the home page of your website asks a user to specify his or her favorite color. When the user clicks the submit button to move to another page, say Page1.aspx, the information about the favorite color can be passed on to a hidden field on Page1.aspx and the information can be used to change the background color of the page to the specified color. Similarly, when the user moves from Page1.aspx to another page, say Page2.aspx, the information in the hidden field on Page1.aspx can be passed on to a hidden field on Page2.aspx. This information, again, can be used to change the background color of Page2.aspx to the specified color. To pass the information from one page to another, you can invoke the Server.Transfer method on the Click event of a Button control, as shown in the following example: protected void Button1_Click(object sender, EventArgs e) { Server.Transfer("Page2.aspx"); } The target page can access the passed information by referring to individual controls on the source page, as shown in the following example: String name = Request.Form["TextBox1"]; String color = Request.Form["HiddenField1"]; To ensure that the passed values are available to the target page, you must submit the page by using the HTTP Post method. A hidden field acts as a repository for any page-specific information that you want to store directly in a page. The advantages of using hidden form fields are:  A hidden field can store page-specific information without accessing any Web server or Web browser resource.  A hidden field can be easily implemented in an ASP.NET Web form page. You just need to add the HiddenField control to a Web page and use the Value property of the control to set its value. Some limitations of using hidden form fields are:  You can view the information stored in the hidden field by accessing the source of the Web page. Therefore, the values stored in hidden form fields are not very secure.  A hidden field does not support more than a single value field to store information.  The hidden fields are stored in a page. Therefore, storing large values in hidden form fields can slow down the processing of the page. NIIT Managing State in Web Applications 5.5  If you use hidden fields, you must submit your pages to the server using the HTTP POST method instead of requesting the page using the page URL. You cannot take advantage of hidden fields if a page is processed in response to a link or the HTTP GET method. Each Web page and controls on the page have a property called ViewState. This property is used to automatically save the values of the Web page and each control on the Web page prior to rendering the page. This, in turn, enables you to retain the page and control-specific values between round trips to the server. The view state is implemented with the help of a hidden form field called __VIEWSTATE. This hidden form field is automatically created in every Web page. When ASP.NET executes a Web page on the Web server, the values stored in the ViewState property of the page and controls on it are collected and formatted into a single encoded string. This encoded string is then assigned to the Value attribute of the hidden form field, __VIEWSTATE, and is sent to the client as part of the Web page. During postback of a Web page to itself, one of the tasks performed by ASP.NET is to restore the values in __VIEWSTATE. When the page is initialized during postback, ASP.NET Framework parses the view state string to restore the information displayed on the page. The view state of a Web page or a control consists of the cumulative property values of the page or the control. To preserve these values across stateless HTTP requests, Web pages and controls in ASP.NET use an instance of the StateBag class. The StateBag class is the primary storage mechanism for HTML and server controls. This class works like a dictionary object and allows you to store items as a key/value pair in it. It accepts a string as a key and an object as its value. Items added to this class are automatically added to the hidden __VIEWSTATE form variable. Storing Information in View State Information in the form fields on a Web page is automatically added to the view state. In addition to the information contained in form fields, the view state can be used to store some additional information. For example, you can store a key-value pair, Counter=1, in the view state by using the following code: ViewState["Counter"] = 1; V iew State 5.6 Managing State in Web Applications NIIT In the preceding code snippet, a key by the name Counter is stored in the view state and the value 1 is assigned to the key. If currently no key has the name Counter, a new key will be added automatically. If a key with the name Counter already exists, it will be replaced. Retrieving Information from View State A value stored in view state can be retrieved by using code. For example, you can retrieve the value of the key, Counter, from view state by using the following code snippet: int counter; counter = (int) ViewState["Counter"]; In the preceding code snippet, the value stored in the key, Counter is converted to an integer before storing it into an integer variable. Enabling and Disabling View State By default, the ViewState property of a Web page and the controls on the Web page is enabled. However, you can disable this property for a Web page or any particular control on the Web page. This is required when you have a large volume of information to maintain. However, maintaining large volume of information leads to a significantly slower rendering of a Web page. Therefore, disabling the ViewState property is important when users are accessing a Web page with limited bandwidth. You also need to disable the ViewState property for users using mobile devices. This is because mobile devices may not have enough storage space for storing large volumes of information. You can enable or disable the ViewState property of a Web page or an individual control by setting the EnableViewState property of the Web page or the control to True or False. You can set the EnableViewState property of a Web page by using the @Page directive, as shown in the following example: <%@ Page Language="C#" AutoEventWireup="true" EnableViewState="false" CodeFile="Page1.aspx.cs" Inherits="Page1" %> To determine the effect of enabling and disabling the ViewState property of a control, consider an example. Add a Label and a Button control to a Web page and type the following code in the Page_Load event handler: if(!IsPostBack) { Label1.Text="Hello World"; } NIIT Managing State in Web Applications 5.7 N ot e N ot e By default, a Button Web server control submits a page back to itself. When this page is loaded for the first time, the message, Hello World, is displayed in the Label control. When the user clicks the button, the message is still displayed on the Label control. This is because the default value of the EnableViewState property of the Label control is True. To see the effect of disabling the ViewState property, set the EnableViewState property of the Label control to False and execute the application. When this page is loaded for the first time, the message, Hello World, is displayed in the Label control. However, when the button is clicked, the Label control displays the default text, Label. This is because the Label control does not maintain its state when its EnableViewState property is set to False. If the EnableViewState property of a Web page is set to False, viewstate is not maintained for any control on that Web page, even if the EnableViewState property of a control on the Web page is set to True. The advantages of using view state are:  The values in view state are stored in a standard HTML format as part of a Web page. Therefore, no Web server resource is required to maintain it.  The view state can be easily implemented on the ASP.NET Web page. You just need to set the EnableViewState property of a Web page and server controls.  The values in view state are hashed, compressed, and encoded for Unicode implementations. Therefore, values in view state are more secure than the values stored in hidden fields. View state also has the following limitations:  Storing large values can cause a page to slow down when users display it or post it because view state is stored in the Web page.  View state is stored in a hidden field on a Web page. Although view state stores data in a hashed format, it can be tampered with. The information in the hidden field can be seen if the page output source is viewed directly, creating a potential security issue. 5.8 Managing State in Web Applications NIIT You can use the ViewState property to preserve page and control values between round trips to the Web server. If you disable the ViewState property of a page, the ViewState of the controls on that page is not maintained. This can lead to improper functioning of some controls on the page. For example, the state of the selected node in a TreeView control needs to be maintained for the control to function properly across postbacks. To enable persistence of property information that is specific to a control, ASP.NET allows you to store the state of a control by using a client-side state maintenance mechanism called control state. Unlike view state, the control state cannot be disabled at the page level. Therefore, if your Web page contains controls whose state must be maintained, you can use the control state mechanism to store their state. You can implement control state on a custom Web control by overriding the following methods of the base class:  OnInit: This method should contain the following lines of code: Page.RegisterRequiresControlState(this); base.OnInit(e);  SaveControlState : This method should return a public property of the control (whose state needs to be saved) or an object array containing the values of all the public properties of the control.  LoadControlState: This method should set the value of the public properties to the values contained in the object passed to the LoadControlState method as an argument. Task 5.1: Implementing control state on a Custom Web control Cookies are used to store small pieces of information related to a user’s computer, such as its IP address, browser type, operating system, and Web pages last visited. The purpose of storing this information is to offer a personalized experience to the user. For example, if a user has logged on to your website for the first time, the name of the user can be stored in a cookie. This information can be retrieved later on when the same user visits the website again to greet the user with his/her name. Cookies are sent to a client computer along with the page output. These Cookies are stored on the client’s computer. When a browser requests the same page the next time, it sends the cookie along with the request information. The Web server reads the cookie and Cookies Control State NIIT Managing State in Web Applications 5.9 extracts its value. It then process the Web page according to the information contained in the cookie and renders it on the Web browser. Types of Cookies Cookies can either be temporary or persistent. Temporary cookies exist in the memory space of a browser. When the browser is closed, all temporary cookies added to the browser are lost. Temporary cookies are also known as session cookies. A temporary cookie is useful for storing information required for only a short time or that should not be written to disk on the client computer for security reasons. For example, a temporary cookie can be created to store the user name. The user name stored in the cookie can be retrieved and displayed on every page of the website. A persistent cookie is saved as a text file in the file system of the client computer. Persistent cookies are used when you want to store information for a longer period. For example, persistent cookies can be used to store customized user settings for a website. This helps in customizing the website when the user visits the website again. While creating a persistent cookie, you can set the expiration date of the cookie, which defines the duration for which the cookie will be stored on the client computer. If you do not set the expiration date of a cookie, the cookie is maintained as a temporary cookie, as part of the user's session information. Once the user session is finished, the cookie is discarded. Persistent cookies can be created as shown in the following example: Response.Cookies["userName"].Value = "Peter"; Response.Cookies["userName"].Expires = DateTime.Now.AddDays(2); Response.Cookies["lastVisited"].Value = DateTime.Now.ToString(); Response.Cookies["lastVisited"].Expires = DateTime.Now.AddDays(2); In the preceding example, two cookies, username and lastVisited, are created. The user name Peter is stored in the first cookie and the date and time when the user, Peter, last visited the site is stored in the second cookie. The expiry period for both the cookies is set as 2 days. If you do not set the expiry period for the cookies, the cookies will be created as temporary cookies. You can also store multiple values in a single cookie. For example, instead of creating separate cookies for storing the user name and last visited information, you can create a single cookie that can hold both the values. Such a cookie can be created as shown in the following example: Response.Cookies["userInfo"]["userName"] = "Peter"; Response.Cookies["userInfo"]["lastVisited"] = DateTime.Now.ToString(); Response.Cookies["userInfo"].Expires = DateTime.Now.AddDays(2); 5.10 Managing State in Web Applications NIIT In the preceding example, the cookie, userInfo, with two subkeys, userName and lastVisited, is created. Reading Cookies You can access the value of a cookie by using the Request built-in object. However, if you want to modify a cookie, you need to use the Response built-in object of ASP.NET. The following example reads the value of a cookie that stores a single value: if (Request.Cookies["userName"].Value != null) { Label1.Text = Request.Cookies["userName"].Value; } In the preceding example, the value in the cookie, userName, is checked for null. If the value is not null, the value is assigned to the Text property of the Label control. Similarly, you can read the values from a cookie that stores multiple values. The following example reads values from a cookie that stores multiple values: if (Request.Cookies["userInfo"] != null) { Label1.Text = Request.Cookies["userInfo"]["userName"]); Label2.Text = Request.Cookies["userInfo"]["lastVisited"]); } In the preceding example, the value in the cookie, userInfo, is checked for null. If the value is not null, the value of the subkeys, userName and lastVisited, is assigned to the Text properties of the Label controls. Advantages and Disadvantages of Cookies Cookies provide several advantages. Some advantages of using cookies are:  A cookie is stored on the client computer and can be read by the server after a request for a page is posted. Therefore, no server resource is involved in maintaining the cookie.  A cookie is a text-based data structure that contains key-value pairs. Therefore, it is easy to create and manipulate cookies.  A cookie can either expire when the browser session ends or exist indefinitely on the client computer, subject to the expiration rules on the client. [...]... application state 5.14 Managing State in Web Applications NIIT Handling Application Events Application state has the following events that you can capture to manipulate an ASP.NET Web application: Application.Start: This event is raised when the application receives the first request for a Web page It is also raised on the next request after the server, Web service, or website has been restarted The event... in a Web application If you need to improve the performance of the Web application, you can disable session state for Web pages This can be done by using the EnableSessionState attribute in the page directive, as shown in the following code: You can also disable session state for all pages of a Web application by setting the mode attribute to Off in the web. config... 5.26 Managing State in Web Applications NIIT Implementing Caching Speed is a critical factor that judges the success or failure of any website When multiple users access a website simultaneously, slow access to Web pages is a common problem that arises The problem of slow access can be solved by using a technique called caching This technique improves the performance of any Web application by temporarily... shared among all the pages of the Web application Session state is used to store session-specific information for a Web application The scope of session state is limited to the current browser session The profiles feature is used to implement personalization in Web applications Caching improves the performance of a Web application by temporarily storing frequently used Web objects on local hard disks... each user profile for an application can be configured in the web. config file You can configure the profile properties by using the markup shown in the following example: NIIT Managing State in Web Applications 5.23 In the preceding example, two profile properties,... can be configured through the web. config file for the application The web. config file allows you to set advanced options such as the timeout and the session state mode The following markup shows some important options that can be set for the element: . Managing State in Web Applications Chapter 5 Web pages and ASP.NET Framework use HTTP protocol to communicate between a Web browser and a Web server. HTTP is a stateless. without accessing any Web server or Web browser resource.  A hidden field can be easily implemented in an ASP.NET Web form page. You just need to add the HiddenField control to a Web page and use. ViewState property of a Web page and the controls on the Web page is enabled. However, you can disable this property for a Web page or any particular control on the Web page. This is required

Ngày đăng: 12/08/2014, 17:21

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