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
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)
[Link] 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
[Link] - ASPX [Link] - [Link]
Great tool for enhancing performance
Using the Application Cache
// Write a Hashtable containing stock prices to the cache Hashtable stocks = new Hashtable (); [Link] ("AMZN", 10.00m); [Link] ("INTC", 20.00m); [Link] ("MSFT", 30.00m); [Link] ("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 [Link] ("Stocks");
[Link]
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
[Link] ("Stocks", stocks, null, [Link] (5), [Link]);
Expire after 5 minutes Expire if 5 minutes elapse without the item being retrieved from the cache
[Link] ("Stocks", stocks, null, [Link], [Link] (5));
Cache Dependencies
[Link] ("Stocks", stocks, new CacheDependency ([Link] ("[Link]")));
Expire if and when [Link] changes Expire if and when the "Stocks" database's "Prices" table changes
[Link] ("Stocks", stocks, new SqlCacheDependency ("Stocks", "Prices"));
Application Cache
Session State
Read/write per-user data store Accessed through Session property
[Link] - ASPX [Link] - [Link]
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 [Link] ("Cart");
In-Process Session State
<!-- [Link] --> <configuration> <[Link]> <sessionState mode="InProc" /> ... </[Link]> </configuration>
Web Server
[Link] Session State
Session state stored inside [Link]'s worker process
State Server Session State
<!-- [Link] --> <configuration> <[Link]> <sessionState mode="StateServer" stateConnectionString="tcpip=[Link]:42424" /> ... </[Link]> </configuration>
Web Server
[Link]
State Server
aspnet_state Process
[Link] state service (aspnet_state.exe)
SQL Server Session State
<!-- [Link] --> <configuration> <[Link]> <sessionState mode="SQLServer" sqlConnectionString="server=orion;integrated security=true" /> ... </[Link]> </configuration>
Web Server
[Link]
Database Server
ASPState Database
Created with [Link] or [Link]
Session Events
Session_Start event signals new session Session_End event signals end of session Process with handlers in [Link]
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 [Link]
<!-- [Link] --> <configuration> <[Link]> <sessionState timeout="60" /> ... </[Link]> </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
Other Data Stores
Access
SQL Server
Defining a Profile
<configuration> <[Link]> <profile> <properties> <add name="ScreenName" /> <add name="Posts" type="System.Int32" defaultValue="0" /> <add name="LastPost" type="[Link]" /> </properties> </profile> </[Link]> </configuration>
Using a Profile
// Increment the current user's post count [Link] = [Link] + 1; // Update the current user's last post date [Link] = [Link];
How Profiles Work
Autogenerated class representing the page
public partial class page_aspx : [Link] { ... protected [Link] Profile { get { return (([Link])([Link])); } } ... }
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> <[Link]> <profile> <properties> <add name="ScreenName" /> <group name="Forums"> <add name="Posts" type="System.Int32" defaultValue="0" /> <add name="LastPost" type="[Link]" /> </group> </properties> </profile> </[Link]> </configuration>
Accessing a Profile Group
// Increment the current user's post count [Link] = [Link] + 1; // Update the current user's last post date [Link] = [Link];
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> <[Link]> <profile> <properties> <add name="Cart" type="ShoppingCart" serializeAs="Binary" /> </properties> </profile> </[Link]> </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> <[Link]> <anonymousIdentification enabled="true" /> <profile> <properties> <add name="ScreenName" allowAnonymous="true" /> <add name="Posts" type="System.Int32" defaultValue="0 /> <add name="LastPost" type="[Link]" /> </properties> </profile> </[Link]> </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> <[Link]> <profile defaultProvider="AspNetSqlProvider" /> </[Link]> </configuration>
Profiles
Cookies
Mechanism for persisting textual data
Described in RFC 2109 For relatively small pieces of data
HttpCookie class encapsulates cookies [Link] collection enables cookies to be read from requests [Link] collection enables cookies to be written to responses
HttpCookie Properties
Name
Name Value Values HasKeys Domain
Description
Cookie name (e.g., "UserName=Jeffpro") Cookie value (e.g., "UserName=Jeffpro") Collection of cookie values (multivalue cookies only) True if cookie contains multiple values Domain to transmit cookie to
Expires
Secure Path
Cookie's expiration date and time
True if cookie should only be transmitted over HTTPS Path to transmit cookie to
Creating a Cookie
HttpCookie cookie = new HttpCookie ("UserName", "Jeffpro"); [Link] (cookie);
Cookie name Cookie value
Reading a Cookie
HttpCookie cookie = [Link]["UserName"]; if (cookie != null) { string username = [Link]; // "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.