state management in asp.net

28
State State Management Management in ASP.NET in ASP.NET

Upload: om-vikram-thapa

Post on 16-Jan-2015

11.440 views

Category:

Technology


0 download

DESCRIPTION

Full credit to Microsoft but i have modified and updated the presentation to increase readability and simplicity. Hope you will enjoy knowing about Session Mgmt.

TRANSCRIPT

Page 1: State management in ASP.NET

State State ManagementManagement

in ASP.NETin ASP.NET

Page 2: State management in ASP.NET

AgendaAgenda

View stateView state

Application cacheApplication cache

Session stateSession state

ProfilesProfiles

CookiesCookies

Page 3: State management in ASP.NET

1. View State1. View 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 in ASP.NET

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 postbackdecimal price = (decimal) ViewState["Price"];

Page 5: State management in ASP.NET

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 in ASP.NET

2. Application Cache2. Application 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 in ASP.NET

Using the Application Using the Application CacheCache// Write a Hashtable containing stock prices to the cache// Write a Hashtable containing stock prices to the cacheHashtable 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 stockHashtable stocks = (Hashtable) Cache["Stocks"];if (stocks != null) // Important! decimal msft = (decimal) stocks["MSFT"]; . . .// Remove the Hashtable from the cacheCache.Remove ("Stocks");

Page 8: State management in ASP.NET

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 9: State management in ASP.NET

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 10: State management in ASP.NET

3. Session State3. Session 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 11: State management in ASP.NET

Using Session StateUsing Session State

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

Page 12: State management in ASP.NET

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 13: State management in ASP.NET

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 14: State management in ASP.NET

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 15: State management in ASP.NET

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.asaxvoid 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}

Page 16: State management in ASP.NET

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 17: State management in ASP.NET

4. Profile Service4. Profile 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 18: State management in ASP.NET

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 19: State management in ASP.NET

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>

// Increment the current user's post countProfile.Posts = Profile.Posts + 1;

// Update the current user's last post dateProfile.LastPost = DateTime.Now;

UsageUsage

Page 20: State management in ASP.NET

How Profiles WorkHow Profiles Work

public partial class page_aspx : System.Web.UI.Page{ ... protected ASP.HttpProfile Profile { get { return ((ASP.HttpProfile)(this.Context.Profile)); } } ...}

Autogenerated classrepresenting the page

Autogenerated class derivedfrom HttpProfileBase

Profile property included inautogenerated page class

Page 21: State management in ASP.NET

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>

// 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;

UsageUsage

Page 22: State management in ASP.NET

Anonymous User ProfilesAnonymous User Profiles

By default, profiles aren't available By default, profiles aren't available for for anonymousanonymous (unauthenticated) (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 23: State management in ASP.NET

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 24: State management in ASP.NET

5. Cookies5. Cookies

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 25: State management in ASP.NET

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 26: State management in ASP.NET

Creating a CookieCreating a Cookie

HttpCookie cookie = new HttpCookie ("UserName", "Jeffpro");Response.Cookies.Add (cookie);

Cookie name

Cookie value

Page 27: State management in ASP.NET

Reading a CookieReading a Cookie

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

Page 28: State management in ASP.NET

Thank YouThank You