Introduction:
In this article,i am going to explain about the available state management techniques in asp.net 2.0 and above versions.
Main:
State Management Techniques,
View state
Application cache
Session state
Profiles
Cookies
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
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"];
// Write the price of an item to view state ViewState["Price"] = price; // Read the price back following a postback decimal price = (decimal) ViewState["Price"]; |
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,
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
In-Process Session State:-
<!-- Web.config -->
<configuration>
<system.web>
<sessionState mode="InProc" />
...
</system.web>
</configuration>
<!-- Web.config --> <configuration> <system.web> <sessionState mode="InProc" /> ... </system.web> </configuration> |
Session state store Inside the worker process,
Types stored in session state using this model do NOT have to be serializable,
State Server Session State:-
<!-- Web.config -->
<configuration>
<system.web>
<sessionState mode="StateServer"
stateConnectionString="tcpip=24.159.185.213:42424" />
...
</system.web>
</configuration>
<!-- Web.config --> <configuration> <system.web> <sessionState mode="StateServer" stateConnectionString="tcpip=24.159.185.213:42424" /> ... </system.web> </configuration> |
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.
ASP.NET state service (aspnet_-state.exe),
SQL Server Session State
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.
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
}
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 } |
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>
<!-- Web.config --> <configuration> <system.web> <sessionState timeout="60" /> ... </system.web> </configuration> |
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,
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");
// 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"); |
Cache.Insert:-
public void Insert (
string key, // Key that identifies item
object value, // The item itself
CacheDependency dependencies, // Cache dependencies (if any)
DateTime absoluteExpiration, // When should item expire (absolute)?
TimeSpan slidingExpiration, // When should item expire (sliding)?
CacheItemPriority priority, // Item's priority relative to other items
CacheItemRemovedCallback onRemoveCallback // Removal callback delegate
);
public void Insert ( string key, // Key that identifies item object value, // The item itself CacheDependency dependencies, // Cache dependencies (if any) DateTime absoluteExpiration, // When should item expire (absolute)? TimeSpan slidingExpiration, // When should item expire (sliding)? CacheItemPriority priority, // Item's priority relative to other items CacheItemRemovedCallback onRemoveCallback // Removal callback delegate ); |
Temporal Expiration:-
Cache.Insert ("Stocks", stocks, null,
DateTime.Now.AddMinutes (5), Cache.NoSlidingExpiration); //Will Expire After 5 Mins,
Cache.Insert ("Stocks", stocks, null,
Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes (5)); //Expire if 5 minutes elapse without the item being retrieved from the cache
<strong>Cache Dependencies</strong>:-
Cache.Insert ("Stocks", stocks,
new CacheDependency (Server.MapPath ("Stocks.xml"))); //Expire if and when Stocks.xml changes
Cache.Insert ("Stocks", stocks,
new SqlCacheDependency ("Stocks", "Prices")); //Expire if and when the "Stocks" database's "Prices" table changes
Cache.Insert ("Stocks", stocks, null, DateTime.Now.AddMinutes (5), Cache.NoSlidingExpiration); //Will Expire After 5 Mins, Cache.Insert ("Stocks", stocks, null, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes (5)); //Expire if 5 minutes elapse without the item being retrieved from the cache <strong>Cache Dependencies</strong>:- Cache.Insert ("Stocks", stocks, new CacheDependency (Server.MapPath ("Stocks.xml"))); //Expire if and when Stocks.xml changes Cache.Insert ("Stocks", stocks, new SqlCacheDependency ("Stocks", "Prices")); //Expire if and when the "Stocks" database's "Prices" table changes |
Profile Service:-
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.
Some Important points about profiles are,
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
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.
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.
<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>
<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> |
How to use profile?
// Increment the current user's post count
Profile.Posts = Profile.Posts + 1;
// Update the current user's last post date
Profile.LastPost = DateTime.Now;
// Increment the current user's post count Profile.Posts = Profile.Posts + 1; // Update the current user's last post date Profile.LastPost = DateTime.Now; |
“Profile” is a property of the page that refers to an instance of the dynamically compiled HttpProfile class that ASP.NET derives from HttpProfileBase. Included in
HttpProfile are the properties declared in the profile,
Profile Groups:-
Properties can be grouped
<profile>
<properties>
<add ... />
...
<group name="...">
<add ... />
...
</group>
</properties>
</profile>
<profile> <properties> <add ... /> ... <group name="..."> <add ... /> ... </group> </properties> </profile> |
A single profile can contain any number of groups, but groups can’t be nested.
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
Creating a Cookie
HttpCookie cookie = new HttpCookie (“UserName”, “Jeffpro”);
Response.Cookies.Add (cookie);
Reading a Cookie:-
HttpCookie cookie = Request.Cookies["UserName"];
if (cookie != null) {
string username = cookie.Value; // "Jeffpro"
...
}
HttpCookie cookie = Request.Cookies["UserName"]; if (cookie != null) { string username = cookie.Value; // "Jeffpro" ... } |
Conclusion:
Hope this helps,
Happy coding.