State Management. Agenda View state Application cache Session state ProfilesCookies.
-
Upload
gregory-haynes -
Category
Documents
-
view
214 -
download
1
Transcript of State Management. Agenda View state Application cache Session state ProfilesCookies.
![Page 1: State Management. Agenda View state Application cache Session state ProfilesCookies.](https://reader035.fdocuments.us/reader035/viewer/2022070403/56649f275503460f94c3f77e/html5/thumbnails/1.jpg)
State State ManagementManagement
![Page 2: State Management. Agenda View state Application cache Session state ProfilesCookies.](https://reader035.fdocuments.us/reader035/viewer/2022070403/56649f275503460f94c3f77e/html5/thumbnails/2.jpg)
AgendaAgenda
View stateView state
Application cacheApplication cache
Session stateSession state
ProfilesProfiles
CookiesCookies
![Page 3: State Management. Agenda View state Application cache Session state ProfilesCookies.](https://reader035.fdocuments.us/reader035/viewer/2022070403/56649f275503460f94c3f77e/html5/thumbnails/3.jpg)
View StateView State
Mechanism for persisting relatively Mechanism for persisting relatively small pieces of data across postbackssmall pieces of data across postbacks
Used by pages and controls to persist Used by pages and controls to persist statestate
Also available to you for persisting stateAlso available to you for persisting state
Relies on hidden input field Relies on hidden input field (__VIEWSTATE)(__VIEWSTATE)
Accessed through ViewState propertyAccessed through ViewState property
Tamper-proof; optionally encryptableTamper-proof; optionally encryptable
![Page 4: State Management. Agenda View state Application cache Session state ProfilesCookies.](https://reader035.fdocuments.us/reader035/viewer/2022070403/56649f275503460f94c3f77e/html5/thumbnails/4.jpg)
Reading and Writing View Reading and Writing View StateState ' Write the price of an item to view stateViewState("Price") = price
' Read the price back following a postbackDim price As Decimal = CType (ViewState ("Price"), Decimal)
![Page 5: State Management. Agenda View state Application cache Session state ProfilesCookies.](https://reader035.fdocuments.us/reader035/viewer/2022070403/56649f275503460f94c3f77e/html5/thumbnails/5.jpg)
View State and Data TypesView State and Data Types
What data types can you store in What data types can you store in view state?view state?
Primitive types (strings, integers, etc.)Primitive types (strings, integers, etc.)
Types accompanied by type convertersTypes accompanied by type converters
Serializable types (types compatible with Serializable types (types compatible with BinaryFormatter)BinaryFormatter)
System.Web.UI.LosFormatter System.Web.UI.LosFormatter performs serialization and performs serialization and deserializationdeserialization
Optimized for compact storage of Optimized for compact storage of strings, integers, booleans, arrays, and strings, integers, booleans, arrays, and hash tableshash tables
![Page 6: State Management. Agenda View state Application cache Session state ProfilesCookies.](https://reader035.fdocuments.us/reader035/viewer/2022070403/56649f275503460f94c3f77e/html5/thumbnails/6.jpg)
Application CacheApplication Cache
Intelligent in-memory data storeIntelligent in-memory data storeItem prioritization and automatic evictionItem prioritization and automatic eviction
Time-based expiration and cache Time-based expiration and cache dependenciesdependencies
Cache removal callbacksCache removal callbacks
Application scope (available to all Application scope (available to all users)users)
Accessed through Cache propertyAccessed through Cache propertyPage.Cache - ASPXPage.Cache - ASPX
HttpContext.Cache - Global.asaxHttpContext.Cache - Global.asax
Great tool for enhancing performanceGreat tool for enhancing performance
![Page 7: State Management. Agenda View state Application cache Session state ProfilesCookies.](https://reader035.fdocuments.us/reader035/viewer/2022070403/56649f275503460f94c3f77e/html5/thumbnails/7.jpg)
Using the Application Using the Application CacheCache' Write a Hashtable containing stock prices to the cache' Write a Hashtable containing stock prices to the cacheDim stocks As Hashtable = New Hashtable () Dim stocks As Hashtable = New Hashtable () stocks.Add ("AMZN", 10.00m)stocks.Add ("AMZN", 10.00m)stocks.Add ("INTC", 20.00m)stocks.Add ("INTC", 20.00m)stocks.Add ("MSFT", 30.00m)stocks.Add ("MSFT", 30.00m)Cache.Insert ("Stocks", stocks)Cache.Insert ("Stocks", stocks) .. .. ..' Fetch the price of Microsoft stock' Fetch the price of Microsoft stockDim stocks As Hashtable = CType (Cache ("Stocks"), Hashtable)Dim stocks As Hashtable = CType (Cache ("Stocks"), Hashtable)If Not stocks Is Nothing ThenIf Not stocks Is Nothing Then Dim msft As Decimal = CType (stocks("MSFT"), Decimal)Dim msft As Decimal = CType (stocks("MSFT"), Decimal)End IfEnd If .. .. ..' Remove the Hashtable from the cache' Remove the Hashtable from the cacheCache.Remove ("Stocks")Cache.Remove ("Stocks")
![Page 8: State Management. Agenda View state Application cache Session state ProfilesCookies.](https://reader035.fdocuments.us/reader035/viewer/2022070403/56649f275503460f94c3f77e/html5/thumbnails/8.jpg)
Cache.InsertCache.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 _)
![Page 9: State Management. Agenda View state Application cache Session state ProfilesCookies.](https://reader035.fdocuments.us/reader035/viewer/2022070403/56649f275503460f94c3f77e/html5/thumbnails/9.jpg)
Temporal ExpirationTemporal 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
![Page 10: State Management. Agenda View state Application cache Session state ProfilesCookies.](https://reader035.fdocuments.us/reader035/viewer/2022070403/56649f275503460f94c3f77e/html5/thumbnails/10.jpg)
Cache DependenciesCache 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
![Page 11: State Management. Agenda View state Application cache Session state ProfilesCookies.](https://reader035.fdocuments.us/reader035/viewer/2022070403/56649f275503460f94c3f77e/html5/thumbnails/11.jpg)
Application CacheApplication Cache
![Page 12: State Management. Agenda View state Application cache Session state ProfilesCookies.](https://reader035.fdocuments.us/reader035/viewer/2022070403/56649f275503460f94c3f77e/html5/thumbnails/12.jpg)
Session StateSession State
Read/write per-user data storeRead/write per-user data store
Accessed through Session propertyAccessed through Session propertyPage.Session - ASPXPage.Session - ASPX
HttpApplication.Session - Global.asaxHttpApplication.Session - Global.asax
Provider-based for flexible data Provider-based for flexible data storagestorage
In-process (default)In-process (default)
State server processState server process
SQL ServerSQL Server
Cookied or cookielessCookied or cookieless
![Page 13: State Management. Agenda View state Application cache Session state ProfilesCookies.](https://reader035.fdocuments.us/reader035/viewer/2022070403/56649f275503460f94c3f77e/html5/thumbnails/13.jpg)
Using Session StateUsing Session State
' Write a ShoppingCart object to session stateDim cart As ShoppingCart = New ShoppingCart () Session ("Cart") = cart . . . ' Read this user's ShoppingCart from session stateDim cart As ShoppingCart = CType (Session ("Cart"), ShoppingCart) . . .' Remove this user's ShoppingCart from session stateSession.Remove ("Cart")
![Page 14: State Management. Agenda View state Application cache Session state ProfilesCookies.](https://reader035.fdocuments.us/reader035/viewer/2022070403/56649f275503460f94c3f77e/html5/thumbnails/14.jpg)
In-Process Session StateIn-Process Session State
<!-- Web.config --><configuration> <system.web> <sessionState mode="InProc" /> ... </system.web></configuration>
Web Server
ASP.NET ASP.NET Session StateSession StateSession state stored insideASP.NET's worker process
![Page 15: State Management. Agenda View state Application cache Session state ProfilesCookies.](https://reader035.fdocuments.us/reader035/viewer/2022070403/56649f275503460f94c3f77e/html5/thumbnails/15.jpg)
State Server Session StateState Server Session State
<!-- Web.config --><configuration> <system.web> <sessionState mode="StateServer" stateConnectionString="tcpip=24.159.185.213:42424" /> ... </system.web></configuration>
Web Server
ASP.NETASP.NET
State Server
ASP.NET state service (aspnet_-state.exe)
aspnet_stateProcess
aspnet_stateProcess
![Page 16: State Management. Agenda View state Application cache Session state ProfilesCookies.](https://reader035.fdocuments.us/reader035/viewer/2022070403/56649f275503460f94c3f77e/html5/thumbnails/16.jpg)
SQL Server Session StateSQL Server Session State
<!-- Web.config --><configuration> <system.web> <sessionState mode="SQLServer" sqlConnectionString="server=orion;integrated security=true" /> ... </system.web></configuration>
Web Server
ASP.NETASP.NET
Database Server
ASPStateDatabase
ASPStateDatabase
Created withInstallSqlState.sql orInstallPersistSql-State.sql
![Page 17: State Management. Agenda View state Application cache Session state ProfilesCookies.](https://reader035.fdocuments.us/reader035/viewer/2022070403/56649f275503460f94c3f77e/html5/thumbnails/17.jpg)
Session EventsSession Events
Session_Start event signals new Session_Start event signals new sessionsession
Session_End event signals end of Session_End event signals end of sessionsession
Process with handlers in Global.asaxProcess with handlers in Global.asaxSub 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 endsEnd Sub
![Page 18: State Management. Agenda View state Application cache Session state ProfilesCookies.](https://reader035.fdocuments.us/reader035/viewer/2022070403/56649f275503460f94c3f77e/html5/thumbnails/18.jpg)
Session Time-OutsSession Time-Outs
Sessions end when predetermined Sessions end when predetermined time period elapses without any time period elapses without any requests from session's ownerrequests from session's owner
Default time-out = 20 minutesDefault time-out = 20 minutes
Time-out can be changed in Time-out can be changed in Web.configWeb.config
<!-- Web.config --><configuration> <system.web> <sessionState timeout="60" /> ... </system.web></configuration>
![Page 19: State Management. Agenda View state Application cache Session state ProfilesCookies.](https://reader035.fdocuments.us/reader035/viewer/2022070403/56649f275503460f94c3f77e/html5/thumbnails/19.jpg)
Profile ServiceProfile Service
Stores per-user data Stores per-user data persistentlypersistentlyStrongly typed access (unlike session Strongly typed access (unlike session state)state)
On-demand lookup (unlike session state)On-demand lookup (unlike session state)
Long-lived (unlike session state)Long-lived (unlike session state)
Supports authenticated and anonymous Supports authenticated and anonymous usersusers
Accessed through dynamically Accessed through dynamically compiled HttpProfileBase derivatives compiled HttpProfileBase derivatives (HttpProfile)(HttpProfile)
Provider-based for flexible data Provider-based for flexible data storagestorage
![Page 20: State Management. Agenda View state Application cache Session state ProfilesCookies.](https://reader035.fdocuments.us/reader035/viewer/2022070403/56649f275503460f94c3f77e/html5/thumbnails/20.jpg)
Profile SchemaProfile SchemaProfiles
Profile Data Stores
SQL Server OtherData Stores
HttpProfileBaseHttpProfileBase
HttpProfile (AutogeneratedHttpProfileBase-Derivative)HttpProfile (AutogeneratedHttpProfileBase-Derivative)
AccessProfileProviderAccessProfileProvider Other ProvidersOther Providers
Profile Providers
SqlProfileProviderSqlProfileProvider
Access
HttpProfile (AutogeneratedHttpProfileBase-Derivative)HttpProfile (AutogeneratedHttpProfileBase-Derivative)
![Page 21: State Management. Agenda View state Application cache Session state ProfilesCookies.](https://reader035.fdocuments.us/reader035/viewer/2022070403/56649f275503460f94c3f77e/html5/thumbnails/21.jpg)
Defining a ProfileDefining 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>
![Page 22: State Management. Agenda View state Application cache Session state ProfilesCookies.](https://reader035.fdocuments.us/reader035/viewer/2022070403/56649f275503460f94c3f77e/html5/thumbnails/22.jpg)
Using a ProfileUsing a Profile
' Increment the current user's post countProfile.Posts = Profile.Posts + 1 ' Update the current user's last post dateProfile.LastPost = DateTime.Now
![Page 23: State Management. Agenda View state Application cache Session state ProfilesCookies.](https://reader035.fdocuments.us/reader035/viewer/2022070403/56649f275503460f94c3f77e/html5/thumbnails/23.jpg)
How Profiles WorkHow 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 classrepresenting the page
Autogenerated class derivedfrom HttpProfileBase
Profile property included inautogenerated page class
![Page 24: State Management. Agenda View state Application cache Session state ProfilesCookies.](https://reader035.fdocuments.us/reader035/viewer/2022070403/56649f275503460f94c3f77e/html5/thumbnails/24.jpg)
Profile GroupsProfile Groups
Properties can be groupedProperties can be grouped
<group> element defines groups<group> element defines groups
<profile> <properties> <add ... /> ... <group name="..."> <add ... /> ... </group> </properties></profile>
![Page 25: State Management. Agenda View state Application cache Session state ProfilesCookies.](https://reader035.fdocuments.us/reader035/viewer/2022070403/56649f275503460f94c3f77e/html5/thumbnails/25.jpg)
Defining a Profile GroupDefining 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>
![Page 26: State Management. Agenda View state Application cache Session state ProfilesCookies.](https://reader035.fdocuments.us/reader035/viewer/2022070403/56649f275503460f94c3f77e/html5/thumbnails/26.jpg)
Accessing a Profile GroupAccessing a Profile Group
' Increment the current user's post countProfile.Forums.Posts = Profile.Forums.Posts + 1 ' Update the current user's last post dateProfile.Forums.LastPost = DateTime.Now
![Page 27: State Management. Agenda View state Application cache Session state ProfilesCookies.](https://reader035.fdocuments.us/reader035/viewer/2022070403/56649f275503460f94c3f77e/html5/thumbnails/27.jpg)
Custom Data TypesCustom Data Types
Profiles support base typesProfiles support base typesString, Int32, Int64, DateTime, Decimal, String, Int32, Int64, DateTime, Decimal, etc.etc.
Profiles also support custom typesProfiles also support custom typesUse type attribute to specify typeUse type attribute to specify type
Use serializeAs attribute to specify Use serializeAs attribute to specify serialization mode: Binary, Xml (default), serialization mode: Binary, Xml (default), or Stringor String
serializeAs="Binary" types must be serializeAs="Binary" types must be serializableserializable
serializeAs="String" types need type serializeAs="String" types need type convertersconverters
![Page 28: State Management. Agenda View state Application cache Session state ProfilesCookies.](https://reader035.fdocuments.us/reader035/viewer/2022070403/56649f275503460f94c3f77e/html5/thumbnails/28.jpg)
Using a Custom Data TypeUsing a Custom Data Type
<configuration> <system.web> <profile> <properties> <add name="Cart" type="ShoppingCart" serializeAs="Binary" /> </properties> </profile> </system.web></configuration>
![Page 29: State Management. Agenda View state Application cache Session state ProfilesCookies.](https://reader035.fdocuments.us/reader035/viewer/2022070403/56649f275503460f94c3f77e/html5/thumbnails/29.jpg)
Anonymous User ProfilesAnonymous User Profiles
By default, profiles aren't available By default, profiles aren't available for anonymous (unauthenticated) for anonymous (unauthenticated) usersusers
Data keyed by authenticated user IDsData keyed by authenticated user IDs
Anonymous profiles can be enabledAnonymous profiles can be enabledStep 1Step 1: Enable anonymous identification: Enable anonymous identification
Step 2Step 2: Specify which profile properties : Specify which profile properties are available to anonymous usersare available to anonymous users
Data keyed by user anonymous IDsData keyed by user anonymous IDs
![Page 30: State Management. Agenda View state Application cache Session state ProfilesCookies.](https://reader035.fdocuments.us/reader035/viewer/2022070403/56649f275503460f94c3f77e/html5/thumbnails/30.jpg)
Profiles for Anonymous Profiles for Anonymous UsersUsers<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>
![Page 31: State Management. Agenda View state Application cache Session state ProfilesCookies.](https://reader035.fdocuments.us/reader035/viewer/2022070403/56649f275503460f94c3f77e/html5/thumbnails/31.jpg)
Profile ProvidersProfile Providers
Profile service is provider-basedProfile service is provider-based
Beta 1 ships with two providersBeta 1 ships with two providersAccessProfileProvider (Access)*AccessProfileProvider (Access)*
SqlProfileProvider (SQL Server)SqlProfileProvider (SQL Server)
Use custom providers to add support Use custom providers to add support for other data storesfor other data stores
* Will be replaced by SQL Express provider in beta 2
![Page 32: State Management. Agenda View state Application cache Session state ProfilesCookies.](https://reader035.fdocuments.us/reader035/viewer/2022070403/56649f275503460f94c3f77e/html5/thumbnails/32.jpg)
Using the SQL Server Using the SQL Server ProviderProvider<configuration> <system.web> <profile defaultProvider="AspNetSqlProvider" /> </system.web></configuration>
![Page 33: State Management. Agenda View state Application cache Session state ProfilesCookies.](https://reader035.fdocuments.us/reader035/viewer/2022070403/56649f275503460f94c3f77e/html5/thumbnails/33.jpg)
ProfilesProfiles
![Page 34: State Management. Agenda View state Application cache Session state ProfilesCookies.](https://reader035.fdocuments.us/reader035/viewer/2022070403/56649f275503460f94c3f77e/html5/thumbnails/34.jpg)
CookiesCookies
Mechanism for persisting textual dataMechanism for persisting textual dataDescribed in RFC 2109Described in RFC 2109
For relatively small pieces of dataFor relatively small pieces of data
HttpCookie class encapsulates HttpCookie class encapsulates cookiescookies
HttpRequest.Cookies collection HttpRequest.Cookies collection enables cookies to be read from enables cookies to be read from requestsrequests
HttpResponse.Cookies collection HttpResponse.Cookies collection enables cookies to be written to enables cookies to be written to responsesresponses
![Page 35: State Management. Agenda View state Application cache Session state ProfilesCookies.](https://reader035.fdocuments.us/reader035/viewer/2022070403/56649f275503460f94c3f77e/html5/thumbnails/35.jpg)
HttpCookie PropertiesHttpCookie 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
![Page 36: State Management. Agenda View state Application cache Session state ProfilesCookies.](https://reader035.fdocuments.us/reader035/viewer/2022070403/56649f275503460f94c3f77e/html5/thumbnails/36.jpg)
Creating a CookieCreating a Cookie
Dim cookie As HttpCookie = New HttpCookie ("UserName", "Jeffpro")Response.Cookies.Add (cookie)
Cookie name
Cookie value
![Page 37: State Management. Agenda View state Application cache Session state ProfilesCookies.](https://reader035.fdocuments.us/reader035/viewer/2022070403/56649f275503460f94c3f77e/html5/thumbnails/37.jpg)
Reading a CookieReading a Cookie
Dim cookie As HttpCookie = Request.Cookies ("UserName")If Not cookie Is Nothing Then Dim username As String = cookie.Value End If ...}
![Page 38: State Management. Agenda View state Application cache Session state ProfilesCookies.](https://reader035.fdocuments.us/reader035/viewer/2022070403/56649f275503460f94c3f77e/html5/thumbnails/38.jpg)
© 2003-2004 Microsoft Corporation. All rights reserved.This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.