380 likes | 572 Views
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
E N D
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 • Relies on hidden input field (__VIEWSTATE) • Accessed through ViewState property • Tamper-proof; optionally encryptable
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"];
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
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
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");
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 );
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));
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"));
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
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");
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
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)
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
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 }
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>
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
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
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>
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;
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
Profile Groups • Properties can be grouped • <group> element defines groups <profile> <properties> <add ... /> ... <group name="..."> <add ... /> ... </group> </properties> </profile>
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>
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;
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
Using a Custom Data Type <configuration> <system.web> <profile> <properties> <add name="Cart" type="ShoppingCart" serializeAs="Binary" /> </properties> </profile> </system.web> </configuration>
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
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>
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
Using the SQL Server Provider <configuration> <system.web> <profile defaultProvider="AspNetSqlProvider" /> </system.web> </configuration>
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
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
Creating a Cookie HttpCookie cookie = new HttpCookie ("UserName", "Jeffpro"); Response.Cookies.Add (cookie); Cookie name Cookie value
Reading a Cookie HttpCookie cookie = Request.Cookies["UserName"]; if (cookie != null) { string username = cookie.Value; // "Jeffpro" ... }
© 2003-2004 Microsoft Corporation. All rights reserved. This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.