State management in ASP.NET


Published on

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.

Published in: Technology
1 Comment
No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide
  • Programming ASP.NET Copyright © 2001-2002
  • Programming ASP.NET Copyright © 2001-2002 View state is serialized and deserialized by the System.Web.UI.LosFormatter class ("Los" stands for "Limited Object Serialization"). LosFormatter is capable of serializing any type that is accompanied by a registered type converter or that can be serialized with BinaryFormatter, but it is optimized for storage of certain types.
  • Programming ASP.NET Copyright © 2001-2002 Types stored in session state using this model do NOT have to be serializable.
  • Programming ASP.NET Copyright © 2001-2002 Types stored in session state using this model must be serializable. Moving session state off-machine in this manner is one way to make sessions comaptible with Web farms. The state server process must be started before this model can be used. It can be configured to autostart through Windows' Services control panel applet.
  • Programming ASP.NET Copyright © 2001-2002 Types stored in session state using this model must be serializable. Moving session state off-machine in this manner is another way to make sessions comaptible with Web farms. The ASPState database must be created before SQL Server session state can be used. ASP.NET comes with two SQL scripts for creating the database. InstallSqlState.sql creates a database that stores data in temp tables (memory), meaning that if the database server crashes, session state is lost. InstallPersistSqlState, which was introduced in ASP.NET 1.1, creates a database that stores data in disk-based tables and thus provides a measure of robustness.
  • Programming ASP.NET Copyright © 2001-2002 On the surface, the profile service sounds a lot like session state since both are designed to store per-user data. However, profiles and session state differ in significant ways. Profiles should not be construed as a replacement for session state, but rather as a complement to it. For applications that store shopping carts and other per-user data for a finite period of time, session state is still a viable option.
  • Programming ASP.NET Copyright © 2001-2002 The HttpProfile class, which derives from System.Web.Profile.HttpProfileBase, provides strongly typed access to profile data. You won't find HttpProfile documented in the .NET Framework SDK because it's not part of the .NET Framework Class Library; instead, it is dynamically generated by ASP.NET. Applications read and write profile data by reading and writing HttpProfile properties. HttpProfile, in turn, uses providers to access the underlying data stores.
  • Programming ASP.NET Copyright © 2001-2002 A profile characterizes the data that you wish to store for individual visitors to your site. It's defined in Web.config as shown here and will probably differ in every application. This sample profile uses only .NET Framework data types, but custom data types are supported, too. The type attribute specifies the data type; the default is string if no type is specified. The defaultValue attribute allows you to specify a property's default value. This example might be appropriate for a forums application where you wish to store a screen name, a post count, and the date and time of the last post for each visitor.
  • Programming ASP.NET Copyright © 2001-2002 At first glance, statements that read and write profile properties seem like magic because there is no property named Profile in System.Web.UI.Page. Why, for example, does the code on the previous slide compile? It compiles because ASP.NET inserts a Profile property into classes that it derives from System.Web.UI.Page. This slide shows the property's implementation, which simply returns the HttpProfile reference stored in HttpContext.Profile. ASP.NET also inserts a Profile property into the HttpAplication-derived class that represents the application itself, meaning that you can use the Profile property to access profiles in Global.asax.
  • Programming ASP.NET Copyright © 2001-2002 This example defines a profile containing an ungrouped property named ScreenName and grouped properties named Posts and LastPosts. The grouped properties belong to a group named Forums.
  • Programming ASP.NET Copyright © 2001-2002 Profiles can be used for anonymous users as well as authenticated users, but only if anonymous user profiles are specifically enabled. Enabling anonymous profiles requires two steps. First you use a configuration directive to enable ASP.NET's anonymous identification service. Then you attribute each profile property that you wish to store for anonymous users allowAnonymous="true." For authenticated users, ASP.NET keys profile data with unique user IDs generated by the Membership service. For anonymous users, ASP.NET keys profile data with anonymous user IDs generated by the anonymous identification service. Anonymous user IDs are round-tripped (by default) in cookies. Cookieless operation is also supported for the benefit of users whose browsers don't support cookies (or have cookie support disabled).
  • Programming ASP.NET Copyright © 2001-2002 <anonymousIdentification enabled="true"> enables the anonymous identification service, which is a prerequisite for storing profile values for anonymous users. allowAnonymous="true" tells ASP.NET to store ScreenName values for anonymous users. Since Posts and LastPost lack allowAnonymous="true" attributes, they won't be persisted in profiles for anonymous users.
  • State management in ASP.NET

    1. 1. State Management in ASP.NET
    2. 2. Agenda View state Application cache Session state Profiles Cookies
    3. 3. 1. 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. 4. Reading and Writing View State// Write the price of an item to view stateViewState["Price"] = price;// Read the price back following a postbackdecimal price = (decimal) ViewState["Price"];
    5. 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. 6. 2. 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. 7. Using the Application 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");
    8. 8. Temporal ExpirationCache.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 cacheCache.Insert ("Stocks", stocks, null, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes (5));
    9. 9. Cache DependenciesCache.Insert ("Stocks", stocks, new CacheDependency (Server.MapPath ("Stocks.xml"))); Expire if and when Stocks.xml changes Expire if and when the "Stocks" databases "Prices" table changesCache.Insert ("Stocks", stocks, new SqlCacheDependency ("Stocks", "Prices"));
    10. 10. 3. 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
    11. 11. Using Session State// Write a ShoppingCart object to session stateShoppingCart cart = new ShoppingCart ();Session["Cart"] = cart; . . .// Read this users ShoppingCart from session stateShoppingCart cart = (ShoppingCart) Session["Cart"]; . . .// Remove this users ShoppingCart from session stateSession.Remove ("Cart");
    12. 12. In-Process Session State<!-- Web.config --><configuration> <system.web> <sessionState mode="InProc" /> ... </system.web></configuration>Web Server Session state stored inside ASP.NET Session State ASP.NETs worker process
    13. 13. State Server Session State<!-- Web.config --><configuration> <system.web> <sessionState mode="StateServer" stateConnectionString="tcpip=" /> ... </system.web></configuration>Web Server State Server aspnet_state ASP.NET state ASP.NET service (aspnet_- Process state.exe)
    14. 14. 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 Created with ASP.NET ASPState InstallSqlState.sql or Database InstallPersistSql- State.sql
    15. 15. Session Events Session_Start event signals new session Session_End event signals end of session Process 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}
    16. 16. Session Time-Outs Sessions end when predetermined time period elapses without any requests from sessions 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>
    17. 17. 4. 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
    18. 18. Profile SchemaProfiles HttpProfileBase HttpProfile (Autogenerated HttpProfile (Autogenerated HttpProfileBase-Derivative) HttpProfileBase-Derivative)Profile Providers AccessProfileProvider SqlProfileProvider Other ProvidersProfile Data Stores Other Access SQL Server Data Stores
    19. 19. 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>Usage// Increment the current users post countProfile.Posts = Profile.Posts + 1;// Update the current users last post dateProfile.LastPost = DateTime.Now;
    20. 20. How Profiles Work Autogenerated class representing the pagepublic partial class page_aspx : System.Web.UI.Page{ ... protected ASP.HttpProfile Profile { get { return ((ASP.HttpProfile)(this.Context.Profile)); } } ...}Autogenerated class derived Profile property included infrom HttpProfileBase autogenerated page class
    21. 21. 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>Usage// Increment the current users post countProfile.Forums.Posts = Profile.Forums.Posts + 1;// Update the current users last post dateProfile.Forums.LastPost = DateTime.Now;
    22. 22. Anonymous User Profiles By default, profiles arent 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
    23. 23. 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>
    24. 24. 5. 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
    25. 25. 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 Cookies expiration date and time Secure True if cookie should only be transmitted over HTTPS Path Path to transmit cookie to
    26. 26. Creating a CookieHttpCookie cookie = new HttpCookie ("UserName", "Jeffpro");Response.Cookies.Add (cookie); Cookie name Cookie value
    27. 27. Reading a CookieHttpCookie cookie = Request.Cookies["UserName"];if (cookie != null) { string username = cookie.Value; // "Jeffpro" ...}
    28. 28. Thank You