Download presentation
Presentation is loading. Please wait.
Published byGregory Haynes Modified over 9 years ago
1
State Management
2
Agenda View state Application cache Session state ProfilesCookies
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 Dim price As Decimal = CType (ViewState ("Price"), Decimal)
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 Dim stocks As Hashtable = 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 Dim stocks As Hashtable = CType (Cache ("Stocks"), Hashtable) If Not stocks Is Nothing Then Dim msft As Decimal = CType (stocks("MSFT"), Decimal) Dim msft As Decimal = CType (stocks("MSFT"), Decimal) End If... ' Remove the Hashtable from the cache Cache.Remove ("Stocks")
8
Cache.Insert Public Sub Insert ( ByVal key As String, _ ByVal value As Object, _ ByVal dependencies As CacheDependency, _ ByVal absoluteExpiration As DateTime, _ ByVal slidingExpiration As TimeSpan, _ ByVal priority As CacheItemPriority, _ ByVal onRemoveCallback As CacheItemRemovedCallback _ )
9
Temporal Expiration Cache.Insert ("Stocks", stocks, null, DateTime.Now.AddMinutes (5), Cache.NoSlidingExpiration) Cache.Insert ("Stocks", stocks, null, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes (5)) Expire after 5 minutes Expire if 5 minutes elapse without the item being retrieved from the cache
10
Cache Dependencies Cache.Insert ("Stocks", stocks, New CacheDependency (Server.MapPath ("Stocks.xml"))) Cache.Insert ("Stocks", stocks, New SqlCacheDependency ("Stocks", "Prices")) Expire if and when Stocks.xml changes Expire if and when the "Stocks" database's "Prices" table changes
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 Dim cart As ShoppingCart = New ShoppingCart () Session ("Cart") = cart. ' Read this user's ShoppingCart from session state Dim cart As ShoppingCart = CType (Session ("Cart"), ShoppingCart). ' Remove this user's ShoppingCart from session state Session.Remove ("Cart")
14
In-Process Session State... Web Server ASP.NET Session State Session state stored inside ASP.NET's worker process
15
State Server Session State <sessionState mode="StateServer" stateConnectionString="tcpip=24.159.185.213:42424" />... Web Server ASP.NET State Server ASP.NET state service (aspnet_- state.exe) aspnet_state Process aspnet_state Process
16
SQL Server Session State <sessionState mode="SQLServer" sqlConnectionString="server=orion;integrated security=true" />... Web Server ASP.NET Database Server ASPState Database 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 Sub Session_Start () ' Create a shopping cart and store it in session state ' each time a new session is started Session ("Cart") = New ShoppingCart () End Sub Sub Session_End () ' Do any cleanup here when session ends End Sub
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...
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 Profile Data Stores SQL Server Other Data Stores HttpProfileBase HttpProfile (Autogenerated HttpProfileBase-Derivative) HttpProfile (Autogenerated HttpProfileBase-Derivative) AccessProfileProvider Other Providers Profile Providers SqlProfileProvider Access HttpProfile (Autogenerated HttpProfileBase-Derivative) HttpProfile (Autogenerated HttpProfileBase-Derivative)
21
Defining a Profile
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 Partial Public Class page_aspx Inherits System.Web.UI.Page {... Protected ReadOnly Property Profile() As ASP.HttpProfile Get Return CType (Me.Context.Profile, ASP.HttpProfile) End Get End Property... } Autogenerated class representing the page Autogenerated class derived from HttpProfileBase Profile property included in autogenerated page class
24
Profile Groups Properties can be grouped element defines groups element defines groups......
25
Defining a Profile Group
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
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
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
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 NameDescription NameCookie name (e.g., "UserName=Jeffpro") ValueCookie value (e.g., "UserName=Jeffpro") ValuesCollection of cookie values (multivalue cookies only) HasKeysTrue if cookie contains multiple values DomainDomain to transmit cookie to ExpiresCookie's expiration date and time SecureTrue if cookie should only be transmitted over HTTPS PathPath to transmit cookie to
36
Creating a Cookie Dim cookie As HttpCookie = New HttpCookie ("UserName", "Jeffpro") Response.Cookies.Add (cookie) Cookie name Cookie value
37
Reading a Cookie Dim cookie As HttpCookie = Request.Cookies ("UserName") If Not cookie Is Nothing Then Dim username As String = cookie.Value End If... }
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.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.