Ch05 state management


Published on

  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Ch05 state management

  1. 1. STATE MANAGEMENT No web application framework, no matter howadvanced, can change the fact that HTTP is a statelessprotocol. After every web request, the client disconnects from theserver, and the ASP.NET engine discards the objects thatwere created for the page. Stateless architecture ensures that web applications canfetch serve thousands of simultaneous requests withoutrunning out of server memory. The drawback is that your code needs to use othertechniques to store information between web requests andretrieve it when needed. 1
  2. 2. ASP.NET MANAGEMENT ASP.NET includes a variety of options for state management. Can choose the right option depending on the data you needto store, the length of time you want to store it, the scope ofyour data, and additional security and performanceconsiderations. State Management Options  View State  Query String  Custom Cookies  Session State  Application State  Profiles  Caching 2
  3. 3. VIEW STATE View state should be your first choice for storing informationwithin the bounds of a single page. You can add your own data to the view state collection using abuilt-in page property called ViewState. Like most types of state management in ASP.NET, view staterelies on a dictionary collection, where each item is indexed witha unique string name ViewState["Counter"] = 1; When retrieving a value, you use the key name. int counter; if (ViewState["Counter"] != null) { counter = (int)ViewState["Counter"]; } 3
  4. 4. VIEW STATE EXAMPLE• The Example (ViewStateTest.aspx) demonstratesa page that uses view state.• It allows the user to save a set of values (all thetext that’s displayed in all the text boxes of a table)and restore it later.•Refer to example given in textbook 4
  5. 5. STORING OBJECTS IN VIEW STATE Can store your own objects in view state just as easily as you storenumeric and string types. However, to store an item in view state, ASP.NET must be able toconvert it into a stream of bytes so that it can be added to the hiddeninput field in the page. (called serialization) For your classes to be serializable, you must meet theserequirements: • Your class must have the Serializable attribute. • Any classes it derives from must have the Serializableattribute. • All the member variables of the class must use serializable data types. 5
  6. 6. VIEW STATE SECURITY View state information is stored in a single Base64-encoded string that looks likethis: <input type="hidden" name="__VIEWSTATE“ id="__VIEWSTATE" value="dDw3NDg2NTI5MDg7Oz4="/> Many ASP.NET programmers assume that their view state data is encrypted. Itisn’t If you want to make view state secure, you have two choices.:-  First, you can make sure that the view state information is tamper-proof by using a hash code.  enableViewStateMac attribute of the <pages> element in the web.config or machine.config Hash code is cryptographically checksumASP.Net calculates checksum based on current view state content and adds it tohidden field when it returns the pageWhen page is posted back ASP.NET recalculates the checksum and ensures for 6
  7. 7. VIEW STATE SECURITY CONT… Hash codes are enabled by default. <%@ Page EnableViewStateMAC="false" ... %> Can set the enableViewStateMac attribute of the <pages> element in the web.config or machine.config file, as shown below: <configuration> <system.web> <pages enableViewStateMac="false" /> … </system.web> </configuration> The view state data will still be readable. To prevent users from gettingany view state information, you can enable view state encryption for anindividual page – %<@PageViewStateEncryptionMode=“Always”… >% Can set the same attribute in the web.config configuration file: <pages viewStateEncryptionMode="Always" /> 7
  8. 8. TRANSFERRING INFORMATION BETWEEN PAGES One of the most significant limitations with viewstate is that it’s tightly bound to a specific page. If the user navigates to another page, thisinformation is lost. This problem has several solutions, and the bestapproach depends on your requirements. Passing information from one page to another:-  The Query String  Cookies  Application State 8
  9. 9. QUERY STRING One common approach is to pass informationusing a query string in the URL. Find this approach in search engines. For example The advantage of the query string is that it’slightweight and doesn’t exert any kind of burden onthe server. 9
  10. 10. QUERY STRING CONT… It has some limitations:  Information is limited to simple strings, which must contain URL-legal characters.  Information is clearly visible to the user and to anyone else who cares to eavesdrop on the Internet  The enterprising user might decide to modify the query string and supply new values,  Many browsers impose a limit on the length of a URL (usually from 1 to 2 KB). 10
  11. 11. QUERY STRING CONT…Using the Query String: // Go to newpage.aspx. Submit a single query string argument named recordID and set to 10. int recordID = 10; Response.Redirect("newpage.aspx?recordID=" + recordID.ToString()); The receiving page has an easier time working with the querystring. string ID = Request.QueryString["recordID"]; 11
  12. 12. URL ENCODING One potential problem with the query string is usingcharacters that aren’t allowed in a URL.& is used to separate multiple query strings+ used to denote space#points to specific bookmark on page Can use the methods of the HttpServerUtility class toencode your data automatically string productName = "Flying Carpet"; Response.Redirect("newpage.aspx?productName=" Server.UrlEncode(productName)); 12
  13. 13. CROSS PAGE POSTING ASP.NET pages post back to themselves. When a page is posted back, it sends the currentcontent of all the controls in the form for that page. To transfer information from one page to another,you can use the same postback mechanism, but sendthe information to a different page. The infrastructure that supports cross-pagepostbacks is a property named PostBackUrl To use cross-page posting, you simply setPostBackUrl to the name of another web form. 13
  14. 14. CROSSdefines a form with two text boxes and a button that posts to a pageExample below PAGE POSTING CONT..named CrossPage2.aspx:<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CrossPage1.aspx.cs" Inherits="CrossPage1" %><html xmlns=""><head runat="server"><title>CrossPage1</title></head><body><form id="form1" runat="server" ><asp:TextBox runat="server" ID="txtFirstName"></asp:TextBox> &nbsp;<asp:TextBox runat="server" ID="txtLastName"></asp:TextBox><asp:Button runat="server" ID="cmdSubmit” PostBackUrl="CrossPage2.aspx" Text="Submit" /></form></body></html> 14
  15. 15. CROSS PAGE POSTING CONT…In CrossPage2.aspx, the page can interact with the CrossPage1.aspx objects usingthe Page.PreviousPage property.protected void Page_Load(object sender, EventArgs e){ if (PreviousPage != null) { lblInfo.Text = "You came from a page titled " + PreviousPage.Header.Title; }} Note that this page checks for a null reference before attempting to accessthe PreviousPage object. If there’s no PreviousPage object, there’s no cross-page postback. ASP.NET uses some interesting idea - The first time the second pageaccesses Page.PreviousPage, ASP.NET creates the previous page object bystarting the page processing life cycle, but interrupts it just before thePreRender stage. 15
  16. 16. CROSS PAGE POSTING CONT… If you want to get more specific details, such as control values, you need tocast the PreviousPage reference to the appropriate type. protected void Page_Load(object sender, EventArgs e) { CrossPage1 prevPage = PreviousPage as CrossPage1; if (prevPage != null) { // (Read some information from the previous page.) } } You can solve this problem in another way. <%@ PreviousPageType VirtualPath="CrossPage1.aspx" %>Don’t have flexibility to deal with situations where more than one pagetrigger cross-page postback 16
  17. 17. COOKIES Custom cookies provide another way you can store information forlater use. Cookies are small files that are created on the client’s hard drive(or, if they’re temporary, in the web browser’s memory). Advantage of cookies is that they work transparently without theuser being aware that information needs to be stored. Limitations:  can store only simple string information, and  easily accessible and readable if the user finds and opens the corresponding file.  Some users disable cookies on their browsers. Before you can use cookies, you should import the System.Netnamespace- using System.Net; 17
  18. 18. COOKIES CONT… Both the Request and Response objects provide a Cookiescollection To set a cookie, just create a new System.Net.HttpCookieobject // Create the cookie object. HttpCookie cookie = new HttpCookie("Preferences"); // Set a value in it. cookie["LanguagePref"] = "English"; // Add another value. cookie["Country"] = "US"; // Add it to the current web response. Response.Cookies.Add(cookie); // This cookie lives for one year. cookie.Expires = DateTime.Now.AddYears(1); 18
  19. 19. COOKIES CONT… Cookies are retrieved by cookie name using the Request.Cookiescollection // Check to see whether a cookie was found with this name. This is a // good precaution to take, because the user could disable cookies,in // which case the cookie would not exist. string language; if (cookie != null) { language = cookie["LanguagePref"]; } The only way to remove a cookie is by replacing it with a cookie that hasan expiration date that has already passed: HttpCookie cookie = new HttpCookie("LanguagePref"); cookie.Expires = DateTime.Now.AddDays(-1); Response.Cookies.Add(cookie); 19
  20. 20. SESSION STATE Session state is the heavyweight of state management. It allows information to be stored in one page and accessed inanother. It supports any type of object, including your own custom datatypes. Session state uses the same collection syntax as view state. The only difference is the name of the built-in page property, whichis Session. Every client that accesses the application has a different sessionand a distinct collection of information. Drawbacks:  forces the web server to store additional information in memory  Extra memory requirement, can quickly grow to performance- destroying levels as thousands of clients access the site. 20
  21. 21. SESSION ARCHITECTURE Session management is not part of the HTTP standard. ASP.NET needs to do some extra work to track sessioninformation and bind it to the appropriate response. ASP.NET tracks each session using a unique 120-bitidentifier. The ID is the only piece of information that is transmittedbetween the web server and the client. When the client presents the session ID  ASP.NET looks up the corresponding session,  retrieves the serialized data from the state server,  converts it to live objects, and  places these objects into a special collection so they can be accessed in code. 21
  22. 22. SESSION ARCHITECTURE CONT… The SessionStateModule doesn’t actually store the session data. Instead,the session state is persisted in external components, which are namedstate providers. 22
  23. 23. USING SESSION STATEUser session state using theSystem.Web.SessionState.HttpSessionState class,which is provided in an ASP.NET web page as thebuilt-in Session object. Session["ProductsDataSet"] = dsProducts; Can then retrieve it with an appropriate conversionoperation: dsProducts = (DataSet)Session["ProductsDataSet“] 23
  24. 24. USING SESSION STATE CONT…Session state is global to your entire application for the currentuser. Session state can be lost in several ways: If the user closes and restarts the browser. If the user accesses the same page through a differentbrowser window, although the session will still exist if a webpage is accessed through the original browser window.Browsers differ on how they handle this situation. If the session times out because of inactivity. By default, asession times out after 20 idle minutes. If the programmer ends the session by callingSession.Abandon(). 24
  25. 25. KEY METHODS AND PROPERTIES OF THEHTTPSESSIONSTATE Member DescriptionCount The number of items in the current session collection.IsCookieless Identifies whether this session is tracked with a cookie or with modified URLsIsNewSession Identifies whether this session was just created for the current request.Mode Provides an enumerated value that explains how ASP.NET stores session state information.(determined based on the web.config)SessionID Provides a string with the unique session identifier for the current client.Timeout The current number of minutes that must elapse before the current session will be abandoned.Abandon() Cancels the current session immediately and releases all the memory it occupied.Clear() Removes all the session items but doesn’t change the current 25 session identifier
  26. 26. CONFIGURING SESSION STATE can configure session state through the <sessionState> element in the web.configfile for your application. <?xml version="1.0" encoding="utf-8" ?> <configuration> <system.web> <!-- Other settings omitted. --> <sessionState mode="InProc" stateConnectionString="tcpip=" stateNetworkTimeout="10" sqlConnectionString="data source=;Integrated Security=SSPI" sqlCommandTimeout="30" allowCustomSqlDatabase="false" useHostingIdentity="true" cookieless="UseCookies" cookieName="ASP.NET_SessionId" regenerateExpiredSessionId="false" timeout="20" customProvider=“” /> </system.web> </configuration> 26
  27. 27. CONFIGURING SESSION STATE CONT…ModeOff This setting disables session state management for every page in the applicationInProc InProc is similar to how session state was stored in classic ASP, stores information in the current application domainStateServer With this setting, ASP.NET will use a separate Windows service for state management. Use Admin. Tools to start ASP.Net State Service.SQLServer This setting instructs ASP.NET to use a SQL Server database to store session information, as identified by the sqlConnectionString attribute in web.config. Required to have a server with SQL Server installed.Custom When using custom mode, you need to indicate what session state store provider to use by supplying the customProvider attribute. 27
  28. 28. CONFIGURING SESSION STATE CONT..CookielessUseCookies Cookies are always used, even if the browser or device doesn’t support cookies or they are disabled.UseUri The session ID is stored in the URLUseDeviceProfi ASP.NET chooses whether to use cookielessle sessions by examining the BrowserCapabilities object.AutoDetect ASP.NET attempts to determine whether the browser supports cookies by attempting to set and retrieve a cookie 28
  29. 29. CONFIGURING SESSION STATE CONT..TimeoutThis specifies the number of minutes that ASP.NET will wait,without receiving a request, before it abandons the session. <sessionState timeout="20" ... />This setting represents one of the most important compromisesof session state.Here’s a sample line of code that changes the time-out to tenminutes: Session.Timeout = 10; 29
  30. 30. SECURING SESSION STATE An eavesdropper could steal the cookie and assume thesession on another computer. One common approach is to use a custom session modulethat checks for changes in the client’s IP address. However, the only truly secure approach is to restrict sessioncookies to portions of your website that use SSL. To use this approach, it also makes sense to mark thesession cookie as a secure cookie so that it will be sent onlyover SSL connections. Request.Cookies["ASP.NET_SessionId"].Secure = true; Use above this code immediately after the user is 30
  31. 31. APPLICATION STATE Applicationstate allows you to store global objectsthat can be accessed by any client. Application state is based on theSystem.Web.HttpApplicationState class, which isprovided in all web pages through the built-inApplication object. Application state is similar to session state. Common examples: How many users visited siteOR how many page visited. 31
  32. 32. APPLICATION STATE CONT..Here’s an example of number of page visits:protected void Page_Load(Object sender, EventArgs e){ int count = 0; if (Application["HitCounterForOrderPage"] != null) count = (int)Application["HitCounterForOrderPage"]; count++; Application["HitCounterForOrderPage"] = count; lblCounter.Text = count.ToString();} 32
  33. 33. APPLICATION STATE CONT.. To prevent problem of concurrent access use the Lock() and UnLock()methods. protected void Page_Load(Object sender, EventArgs e){ // Acquire exclusive access. Application.Lock(); int count = 0; if (Application["HitCounterForOrderPage"] != null) count = (int)Application["HitCounterForOrderPage"]; count++; Application["HitCounterForOrderPage"] = count; // Release exclusive access. Application.UnLock(); lblCounter.Text = count.ToString();} 33
  34. 34. APPLICATION STATE CONT.. Application state is rarely used in the .NET worldbecause its two most common uses have beenreplaced by easier, more efficient methods.  In the past, application state was used to store application-wide constants, such as a database connection string. (use web.config)  Many uses of application state can be replaced more efficiently with caching. 34