Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

State management in ASP.NET

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.

Related Books

Free with a 30 day trial from Scribd

See all
  • Be the first to comment

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=24.159.185.213:42424" /> ... </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

×