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.
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. Reading and Writing View State
// Write the price of an item to view state
ViewState["Price"] = price;
// Read the price back following a postback
decimal price = (decimal) ViewState["Price"];
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. 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. Using the Application Cache
// Write a Hashtable containing stock prices to the cache
Hashtable 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 stock
Hashtable stocks = (Hashtable) Cache["Stocks"];
if (stocks != null) // Important!
decimal msft = (decimal) stocks["MSFT"];
.
.
.
// Remove the Hashtable from the cache
Cache.Remove ("Stocks");
8. Temporal Expiration
Cache.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 cache
Cache.Insert ("Stocks", stocks, null,
Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes (5));
9. Cache Dependencies
Cache.Insert ("Stocks", stocks,
new CacheDependency (Server.MapPath ("Stocks.xml")));
Expire if and when Stocks.xml changes
Expire if and when the "Stocks"
database's "Prices" table changes
Cache.Insert ("Stocks", stocks,
new SqlCacheDependency ("Stocks", "Prices"));
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. Using Session State
// Write a ShoppingCart object to session state
ShoppingCart cart = new ShoppingCart ();
Session["Cart"] = cart;
.
.
.
// Read this user's ShoppingCart from session state
ShoppingCart cart = (ShoppingCart) Session["Cart"];
.
.
.
// Remove this user's ShoppingCart from session state
Session.Remove ("Cart");
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.NET's worker process
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. 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. Session Events
Session_Start event signals new session
Session_End event signals end of session
Process with handlers in Global.asax
void 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. 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
<!-- Web.config -->
<configuration>
<system.web>
<sessionState timeout="60" />
...
</system.web>
</configuration>
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. Profile Schema
Profiles
HttpProfileBase
HttpProfile (Autogenerated HttpProfile (Autogenerated
HttpProfileBase-Derivative) HttpProfileBase-Derivative)
Profile Providers
AccessProfileProvider SqlProfileProvider Other Providers
Profile Data Stores
Other
Access SQL Server
Data Stores
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 user's post count
Profile.Posts = Profile.Posts + 1;
// Update the current user's last post date
Profile.LastPost = DateTime.Now;
20. How Profiles Work
Autogenerated class
representing the page
public 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 in
from HttpProfileBase autogenerated page class
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 user's post count
Profile.Forums.Posts = Profile.Forums.Posts + 1;
// Update the current user's last post date
Profile.Forums.LastPost = DateTime.Now;
22. 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
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. 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 Cookie's expiration date and time
Secure True if cookie should only be transmitted over HTTPS
Path Path to transmit cookie to
26. Creating a Cookie
HttpCookie cookie = new HttpCookie ("UserName", "Jeffpro");
Response.Cookies.Add (cookie);
Cookie name
Cookie value