05 ASP - Net Session07
05 ASP - Net Session07
NET
Objectives
Ver. 1.0
Slide 1 of 33
A new instance of the Web page class is created each time the page is posted to the server. In traditional Web programming, all information that is associated with the page, along with the controls on the page, would be lost with each roundtrip. Microsoft ASP.NET framework includes several options to help you preserve data on both a per-page basis and an application-wide basis. These options can be broadly divided into two categories:
Client-Based State Management Options Server-Based State Management Options
Ver. 1.0
Slide 2 of 33
Client-based options involve storing information either in the page or on the client computer. Some client-based state management options are:
View state Control state Hidden form fields Cookies Query strings
Ver. 1.0
Slide 3 of 33
View State:
The ViewState property provides a dictionary object for retaining values between multiple requests for the same page. When the page is processed, the current state of the page and controls is hashed into a string and saved in the page as a hidden field. When the page is posted back to the server, the page parses the view-state string at page initialization and restores property information in the page. To specify the maximum size allowed in a single view-state field, you can use the property, System.Web.UI.Page.MaxPageStateFieldLength. In addition to the contents of controls, the ViewState property can also contain some additional information: ViewState[color] = Yellow ;
Ver. 1.0
Slide 4 of 33
Control State:
The ControlState property allows you to persist property information that is specific to a control. This property cannot be turned off at a page level as can the ViewState property.
Ver. 1.0
Slide 5 of 33
Cookies:
Cookies are stored either in a text file on the client file system or in memory in the client browser session. They contain site-specific information that a server sends to the client along with the page output. When the browser requests a page, the client sends the information in the cookie along with the request information. The server can read the cookie and extract its value.
Query Strings:
Query string is a piece of information that is appended to the end of a page URL. You must submit the page by using an HTTP GET command to ensure availability of these values.
Ver. 1.0
Slide 6 of 33
Server-based options maintain state information on the server. Some server-based state management options are:
Application state Session state
Ver. 1.0
Slide 7 of 33
Application State:
Application state is an instance of the System.Web.HttpApplicationState class. It allows you to save values for each active Web application. Application state is stored in a key/value dictionary that is created during each request to a specific URL. It is a global storage mechanism that is accessible from all pages in the Web application. It supports the following events:
Application.Start Application.End Application.Error
The handlers for the preceding events can be defined in the Global.asax file.
Ver. 1.0
Slide 8 of 33
Ver. 1.0
Slide 9 of 33
Session State:
Session state is an instance of the System.Web.SessionState.HttpSessionState class. It allows you to save values for each active Web application session. It is similar to application state, except that it is scoped to the current browser session. It supports the following events:
Session.Start Session.End
The handlers for the preceding events can be defined in the Global.asax file.
Ver. 1.0
Slide 10 of 33
Values can be saved in the Session state as: string name = Jeff; Session[Name] = name; Values can be retrieved from the Session state as: if(Session[Name]!=null) { string name=(string)Session[Name]; }
Ver. 1.0
Slide 11 of 33
Session state information can be stored in several locations. Location can be configured by setting the mode attribute of the SessionState element in Web.config file. Three possible storage modes can be used:
InProc Mode State Server Mode SQL Server Mode
Ver. 1.0
Slide 12 of 33
InProc Mode:
This is the default mode. Session state data is stored in memory on the Web server within the process that is running the Web application. This is the only mode that supports the Session.End event. Session state information will be lost if application is restarted. Session state cannot be shared between multiple servers in a Web farm. To enable InProc mode, the following markup can be added within the <system.web> tags in the Web.config file: <sessionState mode=InProc></sessionState>
Ver. 1.0
Slide 13 of 33
Following Diagram shows how Session state information is managed in InProc mode, when Cookies are enabled.
Client Server
Ver. 1.0
Slide 14 of 33
Ver. 1.0
Slide 15 of 33
You need to configure each Web server in the Web farm to connect to the ASP.NET state service by modifying the Web.config file as:
<configuration> <system.web> <sessionState mode="StateServer stateConnectionString= "tcpip=MyStateServer:42424" cookieless="AutoDetect" timeout="20"/> </system.web> </configuration>
Ver. 1.0
Slide 16 of 33
Status of ASP.NET State Service can be checked from the Services window on the server on which the service is running.
Ver. 1.0
Slide 17 of 33
Ver. 1.0
Slide 18 of 33
After database has been installed, you need to specify SQLServer mode in Web.config file as:
<configuration> <system.web> <sessionState mode="SQLServer" sqlConnectionString=" Integrated Security=SSPI;data source=MySqlServer;" /> </system.web> </configuration>
Ver. 1.0
Slide 19 of 33
An object can be stored in cache if it consumes a lot of server resources during creation and is being used frequently. This caching system can be used to improve the response time of an application. This caching system automatically removes items when system memory becomes scarce, in a process called scavenging.
Ver. 1.0
Slide 20 of 33
Insert method:
Specify the key name as the first argument and the value being cached as the second argument. The following code performs the same task as the previous example by using the Insert method of the Cache object: Cache.Insert(key", value);
Ver. 1.0
Slide 21 of 33
If you try to access an object from the cache that has been removed because of scarcity of memory, the cache will return a Null reference.
Ver. 1.0
Slide 22 of 33
Expiration time of a cached object can be specified during the object addition into the cache. Expiration time can be:
Absolute Sliding
Absolute Expiration:
This method specifies a date and time when the object will be removed. To add an item to the cache with an absolute expiration of two minutes, the following code snippet can be used:
Cache.Insert("CacheItem", "Cached Item Value", null, DateTime.Now.AddMinutes(2), System.Web.Caching.Cache.NoSlidingExpiration);
Ver. 1.0
Slide 23 of 33
Sliding Expiration:
This method specifies a duration for which an item can lie unused in the cache. The caching system can scavenge the item if it has not been used for a duration that exceeds this value. To add an item to the cache with a sliding expiration of 10 minutes, the following code snippet can be used:
Cache.Insert("CacheItem", "Cached Item Value", null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0, 10, 0));
Ver. 1.0
Slide 24 of 33
Policy for removing objects from the cache can be influenced by specifying CacheItemPriority value. The caching system will scavenge low-priority items before high-priority items when system memory becomes scarce. To set the priority of ac cached object to high at the time of creation, the following code snippet can be used:
Cache.Insert("CacheItem", "Cached Item Value", null, System.Web.Caching.Cache.NoAbsoluteExpiration, System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.High, null);
Ver. 1.0
Slide 25 of 33
Cached items can become invalid because the source of the data has changed. Cached items may be dependent on files, directories, and other cached items. At the time of adding an item to the cache, you can specify the object on which the cached item depends. If any object (on which a cached item depends) changes, the cached item is automatically removed from the cache.
Ver. 1.0
Slide 26 of 33
You can add an item with a dependency to the cache by using the dependencies parameter in the Cache.Insert method, as:
Cache.Insert(Key", value, new CacheDependency Server.MapPath("~\myConfig.xml")));
You can also add an item that depends on another cached item to the cache, as:
string[] sDependencies = new string[1]; sDependencies[0] = key_original"; CacheDependency dependency = new CacheDependency(null, sDependencies); Cache.Insert(key_dependent", "This item depends on OriginalItem", dependency);
Ver. 1.0
Slide 27 of 33
Ver. 1.0
Slide 28 of 33
Ver. 1.0
Slide 29 of 33
Create an event handler to respond when the item is removed from the cache as:
static bool itemRemoved = false; static CacheItemRemovedReason reason; public void RemovedCallback(string key, object value, CacheItemRemovedReason callbackreason) { itemRemoved = true; reason = callbackreason; }
Ver. 1.0
Slide 30 of 33
Add the item to the cache by using the Cache.Insert method as:
Cache.Insert("MyData1", Source, null, DateTime.Now.AddMinutes(2), NoSlidingExpiration, CacheItemPriority.High, onRemove);
Ver. 1.0
Slide 31 of 33
Ver. 1.0
Slide 32 of 33
The possible storage modes for storing session state information are:
InProc StateServer SQLServer
ASP.NET has a powerful caching system that you can use to improve the response time of your application. The ASP.NET caching system automatically removes items from the cache when system memory becomes scarce.
Ver. 1.0
Slide 33 of 33