Session State Management

Snoops

   

 
Migrating to .NET: A Pragmatic Path to Visual Basic .NET, Visual C++ .NET, and ASP.NET
By Dhananjay Katre, Prashant Halari, Narayana Rao Surapaneni, Manu Gupta, Meghana Deshpande

Table of Contents
Chapter 7.  Migrating to ASP.NET II


We have seen in Chapter 5 that state management using the session object in ASP.NET is different than that in ASP. All of the pages in the application using the session object should be migrated because it is not possible to share session state across ASP and ASP.NET pages within the same Web application.

Most of the properties of the ASP session object are supported by the ASP.NET session object, as we will see a little later. Hence, the part of code using an ASP session object can be simply replaced with an ASP.NET session object.

In this section, we first list the differences in ASP and ASP.NET session state management and then take a look at ways in which we can use the ASP.NET session object in the existing code.

Table 7-1 compares ASP session state with ASP.NET session state and Table 7-2 lists features of the ASP session object that are supported by the ASP.NET session object.

Table 7-1. Comparison between ASP and ASP.NET Session States

ASP Session State

ASP.NET Session State

Process dependent. ASP session state exists in the process that hosts ASP; thus the actions that affect the process also affect session state. When the process is recycled or fails, session state is lost.

Process independent. ASP.NET session state is able to run in a separate process from the ASP.NET host process. If session state is in a separate process, the ASP.NET process can come and go while the session state process remains available. Of course, you can still use session state in a process similar to classic ASP, too.

Server farm limitations. As users move from server to server in a Web server farm, their session state does not follow them. ASP session state is machine specific. Each ASP server provides its own session state, and unless the user returns to the same server, the session state is inaccessible. Although network IP-level routing solutions can solve such problems, by ensuring that client IPs are routed to the originating server, some ISPs choose to use a proxy load-balancing solution for their clients .

Support for server farm configurations. By moving to an out-of-process model, ASP.NET also solves the server farm problem. The new out-of-process model allows all servers in the farm to share a session state process. You can implement this by changing the ASP.NET configuration to point to a common server.

Cookie dependent. Clients that don't accept HTTP cookies can't take advantage of session state. Some clients believe that cookies compromise security and/or privacy and thus disable them, which disables session state on the server.

Cookie independent. Although solutions to the problem of cookieless state management do exist for classic ASP, they're not trivial to implement. ASP.NET, on the other hand, reduces the complexities of cookieless session state to a simple configuration setting.

Session handling in ASP.NET can be managed by setting parameters in the configuration file called web.config . The web.config is an XML file containing configuration settings for the application and is present in the root directory of the Web application. The configuration section < sessionState > present in the web.config is shown in the following example. The Web application CodeSamples contains web.config in the root directory.

 graphics/icon01.gif <configuration>     <sessionState         mode="InProc"         cookieless="false"         timeout="20"         sqlconnectionstring="data _         source=127.0.01;uid=sa;pwd=;"        stateConnectionString="tcpip=127.0.0.1:42424"/>  </configuration> 
Table 7-2. ASP Session Object Features Supported by ASP.NET

Session Object Properties

ASP

ASP.NET

Collections

   

Contents(Key)

Collection of data and object with session scope not declared using <OBJECT> tag

Supported.

StaticObjects(Key)

Collection of objects with session scope declared using <OBJECT> tag

Supported.

Methods

   

Abandon

Cancels the current session

Supported.

Properties

   

CodePage

Gets and sets the CodePage for the current session

Supported.

LCID

Location identifier

Supported.

SessionID

Gets the unique session ID to identify the session; returns Long

Supported, returns String.

TimeOut

Gets and sets the time in minutes allowed between requests before the session state provider terminates the session

Supported.

Events

   

OnEnd

Specified in the global.asa file as Session_OnEnd

Specified in the global.asax file as Session_End .

OnStart

Specified in the global.asa file as Session_OnStart

Specified in the global.asax file as Session_Start .

Modes

When the mode is Off , the session state management is off and is almost like disabling the feature of session handling:

 <sessionstate      mode="Off"/> 

Session state management can be turned off at both the application and page level. Web.Config , as shown can be used to turn it off at the application level. This can also be done through the Internet Services Manager console as follows :

  • Open the Internet Services Manager console.

  • Select Properties of the site for which the session needs to be disabled.

  • Click the Configuration Button from the Home Directory Flap.

  • Select the App Options flap and UnCheck the Enable Session State CheckBox.

To turn it off at the page level, an attribute EnableSessionState is added to the Page directive:

 <%@ Page Language="vb" EnableSessionState="false" %> 

The default mode is InProc when the ASP.NET session state is used in a manner similar to the classic ASP session state. That is, session state is managed within the process and if the process is recycled, state is lost. With this setting, the only other settings made in web.config are cookieless and then time out. In-process session state management gives the best performance because the session state memory is kept within the ASP.NET process:

 graphics/icon01.gif <sessionstate      mode="InProc"      cookieless="false"      timeout="20"  /> 

When the mode is StateServer , session state is maintained out of process, for which ASP.NET uses a Windows service. This is a Windows NT service called ASPNet_State and is included with the .NET SDK. To use this state manager, you first need to start the service from the services control panel. This mode is best suited for a Web farm kind of configuration. In such a case, one of the servers in the Web farm is made to run the state service and the rest are configured to point to that server for state management:

 graphics/icon01.gif <sessionstate      mode="StateServer"      stateConnectionString="tcpip=127.0.0.1:42424"  /> 

In these settings, tcpip specifies the IP address of the state server followed by the listener port number. By default, the port number is 42424. The default port can be changed by making changes in the server registry under the Parameters section of aspnet_state. Thus, it can be seen that the StateServer mode of session management can be implemented without making any specific changes in the network configuration.

When the mode is SqlServer , session state is again maintained out of process, but this time ASP.NET makes use of a SQL Server database to store the session state of the user:

 graphics/icon01.gif <sessionstate      mode="SqlServer"      sqlConnection _      String="datasource=127.0.0.1;user_id=sa;password="  /> 

.NET Framework can also provide a cookieless state management. This feature essentially allows sites whose clients choose not to use cookies to take advantage of ASP.NET session state:

 graphics/icon01.gif <sessionstate      mode="InProc"      cookieless="true"      timeout="20"  /> 

This is done by modifying the URL with an ID that uniquely identifies the session. In the following example, the session ID is sent along with the URL:

 http://localhost/(lit3py55t21z5v55vlm25s55)/Application/SessionState.aspx 

When ASP.NET encounters a URL like this, it modifies relative links found within the page and embeds this ID. Thus, as long as the user follows the path of links that the site provides, session state can be maintained. However, if the end user rewrites the URL or restarts the process, session state instance will most likely be lost.

Using the ASP.NET session object is similar to using the ASP session object. We will take a look at few examples where the ASP session object can be replaced with the ASP.NET session object.

The following examples in ASP demonstrate the use of the session object. To add a username to a session object, we use the following syntax. This is demonstrated in the ASP file sessionStateadd.asp in Web application CodeSamples .

 <% Session("Name") = "Patni" %> 

We read from the session object in the ASP file sessionStateread.asp as follows:

 User Name is : <%=Session("Name")%> 

The output for the above shows as:

 User Name is : Patni 

The same code can be used in ASP.NET to add to and retrieve from a session object. ASP.NET provides the Add method for the session object; the syntax for adding to the session object is as follows:

 Session.Add("Name", "Patni") 

The syntax for reading from the session object remains the same.

The global.asa provides methods for handling session start and end events. These can be made use of by, say, providing a connection string and opening a connection during the start of the session and closing it during the session end. The following example demonstrates the use of Session_OnStart and Session_OnEnd events in the global.asa :

 graphics/icon01.gif <Script language="VBScript" RunAt="Server">  Sub Session_OnStart     Set objConnection = _     Server.CreateObject("ADODB.Connection")     objConnection.CursorLocation = 3     objConnection.Open "SampleDSN","sa",""     Set Session("objconn") = objConnection  End Sub  Sub Session_OnEnd()     Set objConn = Session("objconn")     objConn.Close()     Set objconn = nothing     Set Session("objconn") = nothing  End Sub  </Script> 

In the Session_OnStart method we have defined an ADO Connection object. The connection is opened and the object is placed in Session so that it can be accessed across the pages in the application. In the Session_OnEnd method, we close the connection and destroy the object references.

In ASP.NET, the method names are slightly different: Session_Start and Session_End in the global.asax . Using ADO.NET, the preceding code will be changed as follows:

 graphics/icon01.gif Dim connString As String  Public Shared objOLEConnection As OleDbConnection  Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)     connString =     "server=localhost;uid=sa;pwd=;database=Samples;     Provider=SQLOLEDB"     objOLEConnection = New OleDbConnection(connString)     objOLEConnection.Open()  End Sub  Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)     objOLEConnection.Close()     objOLEConnection = Nothing  End Sub 

In this example, we have declared the connection object as a public variable so that it is available across the application. This eliminates the need to keep the object in session. The connection is opened in the Session_Start and closed in Session_End as before.

Cache Control

Caching is the process of storing frequently used data, usually data that is costly to generate, for reuse. Typically this data is stored in memory because retrieving data from memory is much more efficient than retrieving the data from other locations, such as a database. In traditional ASP, caching is enabled by default. Web pages are cached on the client browser by making use of cookies. If cookies are disabled, the caching feature does not work.

ASP.NET offers distinct caching features such as page output caching and the cache object.

PAGE OUTPUT CACHING

Page output caching is a feature of ASP.NET that allows for the entire contents of a given page to be stored in the cache. We used the cache API in the preceding example to store datasets in the cache. What if, rather than simply storing the dataset, we determine that the entire page (that displays the results of the dataset) can be cached? The benefit here is that rather than dynamically executing the ASP.NET page on each request, we serve it statically from memory. This can be a huge performance enhancement.

Page output caching can be divided into high-level and low-level APIs. The high-level API comprises the OutputCache directive written at the start of the page:

 <%@Page Language="VB" %>  <%@OutputCache Duration="15" VaryByParam="none" %> 

The attributes Duration and VaryByParam are required attributes; a parser error occurs if any one of them is not present.

The low-level APIs consist of accessing properties of the HttpCachePolicy class through HttpResponse.Cache :

 Response.Cache.SetExpires (DateTime.Now.AddSeconds (60)) 
CACHE OBJECT

Cache is an instance of the Cache class found in the System.Web.Cache namespace. Its lifetime is the same as that of the application; if the application restarts, the instance of the cache object is lost. In addition to simply storing key and value pairs, Cache adds additional functionality specifically designed to store transient data:

  • Dependency-based expiration . The supported dependencies include a key, file, or timestamp. When one of the dependencies changes or expires (in the case of a timestamp), the cache item is removed from cache.

  • Automatic expiration . Items in the cache unused for a long time and not having dependencies will expire automatically.

  • Lock management . Concurrent users attempting to modify the cache can pose a problem. This is resolved by the internal lock management of the Cache class.

  • Callback support . This allows us to run code when items are removed from the cache.

Adding items to the cache object is similar to the way we use session or application objects:

 Dim dsCash as new dataset()  Cache("cash")=dsCash 

Another way of adding items to the cache object is by using the Insert method of the object:

 Dim dsCash as new dataset()  Cache.Insert("cash", dsCash, nothing) 

The Insert method allows us to set up dependencies.

PREVENTING CACHING

Unless specified otherwise , the browser will always cache pages according to the browser settings made. To prevent the browser from caching pages, we can use the following piece of code in our ASP page:

 graphics/icon01.gif <%  Response.Cachecontrol="private"  Response.Expires=0  Response.AddHeader("pragma", "no-cache")  %> 

This code is valid in ASP.NET also.

In ASP, browser caching is enabled by default. In ASP.NET, caching is enabled by the OutputCache directive at the start of the page. To prevent the browser from caching, we can access the HttpResponse.Cache properties.

PARTIAL CACHING

Additionally, ASP.NET facilitates fragment caching. Sometimes it is not feasible to cache the entire page when certain portions of the page are created dynamically. In these cases, it can be worthwhile for you to identify the objects or data associated with the page request that require significant server resources to construct. Once you identify these items, you can isolate them from the rest of the page by creating them in Web Forms user controls and caching them for a period of time that you specify to save server resources. This is also known as fragment caching.

To use fragment caching, you must develop a Web Forms user control for the portion of the page that you want to cache and include an OutputCache directive in the user control ( .ascx file) with the duration and any of the optional attributes that vary the user control output. For example, if you include the following directive at the top of a user control file, a version of the control is stored in the output cache for 120 seconds:

 <%@ OutputCache Duration="120" %> 

In the following example, the ASP.NET page partialCaching.aspx contains a user control. This code is available in the Web application CodeSamples .

 graphics/icon01.gif <%@ Page Language="vb" %>  <%@ Register TagPrefix="UserControl" TagName="DataDisplay"_    Src="userControl.ascx" %>     <script runat=server>     sub page_load(Sender as object, e as eventargs)         Dim strTime as String         strTime = now()         lblTime.text = "This page was last viewed on " & _   strTime     end sub     </script>     <html>         <head>               <title>partialCaching</title>         </head>         <body>               <UserControl:DataDisplay id="usrControl1" _               runat=server></UserControl:DataDisplay>               <asp:Label ID="lblTime" Runat=server _                ></asp:Label>         </body>     </html> 

The @ Register directive registers the user control with the aspx page using it. The path of the user control is mentioned in the src attribute of the directive. The following code is written in the user control file userControl.ascx in Web application CodeSamples .

 graphics/icon01.gif <%@ Control Language="vb" Target_ Schema="http://schemas.    microsoft.com/intellisense/ie5" %>  <%@ Import Namespace="System.Data"%>  <%@ Import Namespace="System.Data.SQLClient"%>  <%@ OutputCache Duration="120" VaryByParam="none"%>  <%     Dim objConn as SQLConnection     Dim strConn as String     Dim objCommand as SQLCommand     Dim objDataReader as SQLDataReader     Dim strSQL as String     strConn = _     "server=localhost;uid=sa;pwd=;database=Samples"     strSQL = "select * from Login"     objConn  = new SQLConnection(strConn)     objCommand  = new SQLCommand(strSQL, objConn)     objConn.open()     objDataReader  = objCommand.ExecuteReader()     Display.DataSource = objDataReader     Display.DataBind()     objDataReader.close()     objConn.close()  %>     <asp:DataGrid ID=Display Runat=server ></asp:DataGrid> 

Note the @ OutputCache directive in this code. It enables caching only for the user control for the specified duration. Thus, partial caching of the user control can be achieved without caching the aspx page using it.


Snoops

   
Top


Migrating to. NET. A Pragmatic Path to Visual Basic. NET, Visual C++. NET, and ASP. NET
Migrating to. NET. A Pragmatic Path to Visual Basic. NET, Visual C++. NET, and ASP. NET
ISBN: 131009621
EAN: N/A
Year: 2001
Pages: 149

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net