1 / 38

State Management

State Management. Agenda. View state Application cache Session state Profiles Cookies. View State. Mechanism for persisting relatively small pieces of data across postbacks Used by pages and controls to persist state Also available to you for persisting state

guenevere
Download Presentation

State Management

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. State Management

  2. Agenda • View state • Application cache • Session state • Profiles • Cookies

  3. View State • Mechanism for persisting relatively small pieces of data across postbacks • Used by pages and controls to persist state • Also available to you for persisting state • Relies on hidden input field (__VIEWSTATE) • Accessed through ViewState property • Tamper-proof; optionally encryptable

  4. Reading and Writing View State // Write the price of an item to view state ViewState["Price"] = price; // Read the price back following a postback decimal price = (decimal) ViewState["Price"];

  5. View State and Data Types • What data types can you store in view state? • Primitive types (strings, integers, etc.) • Types accompanied by type converters • Serializable types (types compatible with BinaryFormatter) • System.Web.UI.LosFormatter performs serialization and deserialization • Optimized for compact storage of strings, integers, booleans, arrays, and hash tables

  6. Application Cache • Intelligent in-memory data store • Item prioritization and automatic eviction • Time-based expiration and cache dependencies • Cache removal callbacks • Application scope (available to all users) • Accessed through Cache property • Page.Cache - ASPX • HttpContext.Cache - Global.asax • Great tool for enhancing performance

  7. Using the Application Cache // Write a Hashtable containing stock prices to the cache Hashtable stocks = new Hashtable (); stocks.Add ("AMZN", 10.00m); stocks.Add ("INTC", 20.00m); stocks.Add ("MSFT", 30.00m); Cache.Insert ("Stocks", stocks); . . . // Fetch the price of Microsoft stock Hashtable stocks = (Hashtable) Cache["Stocks"]; if (stocks != null) // Important! decimal msft = (decimal) stocks["MSFT"]; . . . // Remove the Hashtable from the cache Cache.Remove ("Stocks");

  8. Cache.Insert public void Insert ( string key, // Key that identifies item object value, // The item itself CacheDependency dependencies, // Cache dependencies (if any) DateTime absoluteExpiration, // When should item expire (absolute)? TimeSpan slidingExpiration, // When should item expire (sliding)? CacheItemPriority priority, // Item's priority relative to other items CacheItemRemovedCallback onRemoveCallback // Removal callback delegate );

  9. Temporal Expiration Cache.Insert ("Stocks", stocks, null, DateTime.Now.AddMinutes (5), Cache.NoSlidingExpiration); Expire after 5 minutes Expire if 5 minutes elapse without the item being retrieved from the cache Cache.Insert ("Stocks", stocks, null, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes (5));

  10. Cache Dependencies Cache.Insert ("Stocks", stocks, new CacheDependency (Server.MapPath ("Stocks.xml"))); Expire if and when Stocks.xml changes Expire if and when the "Stocks" database's "Prices" table changes Cache.Insert ("Stocks", stocks, new SqlCacheDependency ("Stocks", "Prices"));

  11. Application Cache

  12. Session State • Read/write per-user data store • Accessed through Session property • Page.Session - ASPX • HttpApplication.Session - Global.asax • Provider-based for flexible data storage • In-process (default) • State server process • SQL Server • Cookied or cookieless

  13. Using Session State // Write a ShoppingCart object to session state ShoppingCart cart = new ShoppingCart (); Session["Cart"] = cart; . . . // Read this user's ShoppingCart from session state ShoppingCart cart = (ShoppingCart) Session["Cart"]; . . . // Remove this user's ShoppingCart from session state Session.Remove ("Cart");

  14. In-Process Session State <!-- Web.config --> <configuration> <system.web> <sessionState mode="InProc" /> ... </system.web> </configuration> Web Server ASP.NET Session state stored inside ASP.NET's worker process Session State

  15. State Server Session State <!-- Web.config --> <configuration> <system.web> <sessionState mode="StateServer" stateConnectionString="tcpip=24.159.185.213:42424" /> ... </system.web> </configuration> Web Server State Server ASP.NET aspnet_state Process ASP.NET state service (aspnet_- state.exe)

  16. SQL Server Session State <!-- Web.config --> <configuration> <system.web> <sessionState mode="SQLServer" sqlConnectionString="server=orion;integrated security=true" /> ... </system.web> </configuration> Web Server Database Server ASP.NET ASPState Database Created with InstallSqlState.sql or InstallPersistSql- State.sql

  17. Session Events • Session_Start event signals new session • Session_End event signals end of session • Process with handlers in Global.asax void Session_Start () { // Create a shopping cart and store it in session state // each time a new session is started Session["Cart"] = new ShoppingCart (); } void Session_End () { // Do any cleanup here when session ends }

  18. Session Time-Outs • Sessions end when predetermined time period elapses without any requests from session's owner • Default time-out = 20 minutes • Time-out can be changed in Web.config <!-- Web.config --> <configuration> <system.web> <sessionState timeout="60" /> ... </system.web> </configuration>

  19. Profile Service • Stores per-user data persistently • Strongly typed access (unlike session state) • On-demand lookup (unlike session state) • Long-lived (unlike session state) • Supports authenticated and anonymous users • Accessed through dynamically compiled HttpProfileBase derivatives (HttpProfile) • Provider-based for flexible data storage

  20. Profile Schema Profiles HttpProfileBase HttpProfile (Autogenerated HttpProfileBase-Derivative) HttpProfile (Autogenerated HttpProfileBase-Derivative) Profile Providers AccessProfileProvider SqlProfileProvider Other Providers Profile Data Stores Access SQL Server Other Data Stores

  21. Defining a Profile <configuration> <system.web> <profile> <properties> <add name="ScreenName" /> <add name="Posts" type="System.Int32" defaultValue="0" /> <add name="LastPost" type="System.DateTime" /> </properties> </profile> </system.web> </configuration>

  22. Using a Profile // Increment the current user's post count Profile.Posts = Profile.Posts + 1; // Update the current user's last post date Profile.LastPost = DateTime.Now;

  23. How Profiles Work Autogenerated class representing the page public partial class page_aspx : System.Web.UI.Page { ... protected ASP.HttpProfile Profile { get { return ((ASP.HttpProfile)(this.Context.Profile)); } } ... } Autogenerated class derived from HttpProfileBase Profile property included in autogenerated page class

  24. Profile Groups • Properties can be grouped • <group> element defines groups <profile> <properties> <add ... /> ... <group name="..."> <add ... /> ... </group> </properties> </profile>

  25. Defining a Profile Group <configuration> <system.web> <profile> <properties> <add name="ScreenName" /> <group name="Forums"> <add name="Posts" type="System.Int32" defaultValue="0" /> <add name="LastPost" type="System.DateTime" /> </group> </properties> </profile> </system.web> </configuration>

  26. Accessing a Profile Group // Increment the current user's post count Profile.Forums.Posts = Profile.Forums.Posts + 1; // Update the current user's last post date Profile.Forums.LastPost = DateTime.Now;

  27. Custom Data Types • Profiles support base types • String, Int32, Int64, DateTime, Decimal, etc. • Profiles also support custom types • Use type attribute to specify type • Use serializeAs attribute to specify serialization mode: Binary, Xml (default), or String • serializeAs="Binary" types must be serializable • serializeAs="String" types need type converters

  28. Using a Custom Data Type <configuration> <system.web> <profile> <properties> <add name="Cart" type="ShoppingCart" serializeAs="Binary" /> </properties> </profile> </system.web> </configuration>

  29. Anonymous User Profiles • By default, profiles aren't available for anonymous (unauthenticated) users • Data keyed by authenticated user IDs • Anonymous profiles can be enabled • Step 1: Enable anonymous identification • Step 2: Specify which profile properties are available to anonymous users • Data keyed by user anonymous IDs

  30. Profiles for Anonymous Users <configuration> <system.web> <anonymousIdentification enabled="true" /> <profile> <properties> <add name="ScreenName" allowAnonymous="true" /> <add name="Posts" type="System.Int32" defaultValue="0 /> <add name="LastPost" type="System.DateTime" /> </properties> </profile> </system.web> </configuration>

  31. Profile Providers • Profile service is provider-based • Beta 1 ships with two providers • AccessProfileProvider (Access)* • SqlProfileProvider (SQL Server) • Use custom providers to add support for other data stores * Will be replaced by SQL Express provider in beta 2

  32. Using the SQL Server Provider <configuration> <system.web> <profile defaultProvider="AspNetSqlProvider" /> </system.web> </configuration>

  33. Profiles

  34. Cookies • Mechanism for persisting textual data • Described in RFC 2109 • For relatively small pieces of data • HttpCookie class encapsulates cookies • HttpRequest.Cookies collection enables cookies to be read from requests • HttpResponse.Cookies collection enables cookies to be written to responses

  35. HttpCookie Properties Name Description Name Cookie name (e.g., "UserName=Jeffpro") Value Cookie value (e.g., "UserName=Jeffpro") Values Collection of cookie values (multivalue cookies only) HasKeys True if cookie contains multiple values Domain Domain to transmit cookie to Expires Cookie's expiration date and time Secure True if cookie should only be transmitted over HTTPS Path Path to transmit cookie to

  36. Creating a Cookie HttpCookie cookie = new HttpCookie ("UserName", "Jeffpro"); Response.Cookies.Add (cookie); Cookie name Cookie value

  37. Reading a Cookie HttpCookie cookie = Request.Cookies["UserName"]; if (cookie != null) { string username = cookie.Value; // "Jeffpro" ... }

  38. © 2003-2004 Microsoft Corporation. All rights reserved. This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.

More Related