Share Session state Between Classic ASP and ASP. NET (1)

Source: Internet
Author: User
Tags datetime dsn serialization sessions trim classic asp
Asp.net|session applies To:
Microsoft®asp.net

Summary:discusses to share sessions state between classic ASP and Microsoft asp.net using Microsoft. NET Framework CLA SSEs and the serialization feature the. NET Framework. Sharing session state allows converting existing ASP applications to asp.net applications at stages while running the APPL Ications side by side. (Printed pages)

Download The source code for this article.

Contents
Introduction
Conceptual Overview
asp.net implementation
ASP implementation
Demo Program
Incorporating the COM Object in an Existing ASP application
Limitation/improvement
Conclusion

Introduction
Microsoft®asp.net is the latest Microsoft technology for developing web-based applications. It offers a number of advantages over the classic ASP script technology, INCLUDING:1) a better development structure by s Eparating the UI presentation from business logic; 2 its code is fully compiled instead the interpreted as in classic ASP; and 3) Its compile feature into conjunction with it caching support means significantly better performance for sites Writte N in asp.net over equivalent sites written in classic ASP.

Despite the potential benefit of converting existing ASP applications to ASP.net, many existing ASP applications are Missi On critical and complex. The conversion process could is resource intensive and induce additional to the risk existing. One approach to address these issues are to run the ASP and ASP.net side by side, and convert one section of the Applicatio N at a time to asp.net. In order to run the new and old application side by side, a mechanism are needed to share the sessions state between classic ASP and asp.net. In this article, I'll discuss how the sessions state can is shared by using several classes and the serialization feature O f the Microsoft®.net Framework.

Conceptual Overview
Cookies are the most common way for WEB applications to identify the user session, and can is used to identify session STA Te for both classic ASP and asp.net. Session state information are stored in memory in ASP script and can ' t being shared with the other applications, such as asp.net. If the session ' is stored in a common format into Microsoft®sql Server, the session state can be accessible by both CL Assic ASP and asp.net.

In this example, a cookie named mysession are used to identify the user session. When a user makes a request to the WEB application, the user would be issued a unique cookie to identify session. On subsequent request, the browser'll send the unique cookie to the "server to identify" session. Before the requested Web page is loaded, a custom object would reload the user session data from SQL Server using the Uniqu e cookies. The session's accessible in the Web page through the custom object. After the WEB request are finished, the session data would be persisted the SQL Server as the request terminates (SE e Figure 1).



Figure 1. Sample Data Flow

asp.net implementation
In asp.net, every Web page derives from the System.Web.UI.Page class. The Page class aggregates an instance of the HttpSession object for session data. In this example, a custom Page class called Sessionpage are derived from the System.Web.UI.Page to an offer all same featu Res as the Page class. The only difference and the derived page is this default HttpSession is overridden with a custom session object. (Using the new modifier for the instance variable, C # allows the derived class to hide members of the base class.)

public class SessionPage:System.Web.UI.Page
{
...
Public new MySession session = NULL;
...
}

The custom session class are responsible for storing the session state in memory using the HybridDictionary object. (HybridDictionary can efficiently handle any number of sessions elements.) The custom session class would limit the session data type to is string only as interoperability with the classic ASP. (The default HttpSession allows any type of data to is stored in, which would not interoperate with the classic ASP.)

[Serializable]
public class MySession
{
Private HybridDictionary dic = new HybridDictionary ();

Public MySession ()
{
}

public string This [string name]
{
Get
{
Return (String) dic[name. ToLower ()];
}
Set
{
Dic[name. ToLower ()] = value;
}
}
}

The Page class exposes different events and methods for customization. In particular, the OnInit is used to set the initialize state of the Page object. If the request does not have the MySession cookie, a new mysession cookie is issued to the requester. Otherwise, the session data is retrieved from SQL Server using a custom data Access object, Sessionpersistence. The DSN and sessionexpiration values are retrieved from the web.config.

Override protected void OnInit (EventArgs e)
{
InitializeComponent ();
Base. OnInit (e);
}
private void InitializeComponent ()
{
Cookie = this. Request.cookies[sessionpersistence.sessionid];

if (cookie = null)
{
session = new MySession ();
Createnewsessioncookie ();
Isnewsession = true;
}
Else
Session = Sessionpersistence.loadsession (
Server.urldecode (cookies. Value). ToLower (). Trim (),
Dsn
Sessionexpiration
);

This. Unload + = new EventHandler (this. Persistsession);
}
private void Createnewsessioncookie ()
{
cookie = new HttpCookie (Sessionpersistence.sessionid,
Sessionpersistence.generatekey ());
This. RESPONSE.COOKIES.ADD (cookie);
}

The Sessionpersistence class uses the BinaryFormatter of the Microsoft. NET Framework to serialize and deserialize the SES Sion state in binary format for optimal performance. The resulting binary session state data can then is stored in the SQL Server as an image field type.

Public mysession loadsession (string key, String DSN,
int sessionexpiration)
{
SqlConnection conn = new SqlConnection (DSN);
SqlCommand loadcmd = new SqlCommand ();
loadcmd.commandtext = command;
Loadcmd.connection = conn;
SqlDataReader reader = null;
MySession session = NULL;

Try
{
LOADCMD.PARAMETERS.ADD ("@ID", New Guid (key));
Conn. Open ();
reader = Loadcmd.executereader ();
if (reader. Read ())
{
DateTime lastaccessed =
Reader. GetDateTime (1). AddMinutes (sessionexpiration);
if (lastaccessed >= datetime.now)
Session = Deserialize ((byte[]) reader["Data");
}
}
Finally
{
if (reader!= null)
Reader. Close ();
IF (conn!= null)
Conn. Close ();
}

return session;
}
Private mysession Deserialize (byte[] state)
{
if (state = null) return null;

MySession session = NULL;
Stream stream = null;

Try
{
stream = new MemoryStream ();
Stream. Write (state, 0, state.) Length);
Stream. Position = 0;
IFormatter formatter = new BinaryFormatter ();
Session = (mysession) formatter. Deserialize (stream);
}
Finally
{
if (stream!= null)
Stream. Close ();
}
return session;
}

At the "End of" the request, the Page class Unload event is fired, and a event handler registered with the Unload event wil L SERIALIZE the session data to binary format and save the resulting binary data into SQL Server.

private void Persistsession (Object obj, System.EventArgs arg)
{Sessionpersistence.savesession (
Server.urldecode (cookies. Value). ToLower (). Trim (),
DSN, session, Isnewsession);
}
public void Savesession (string key, String DSN,
MySession session, BOOL Isnewsession)
{
SqlConnection conn = new SqlConnection (DSN);
SqlCommand savecmd = new SqlCommand ();
Savecmd.connection = conn;

Try
{
if (isnewsession)
Savecmd.commandtext = insertstatement;
Else
Savecmd.commandtext = updatestatement;

SAVECMD.PARAMETERS.ADD ("@ID", New Guid (key));
SAVECMD.PARAMETERS.ADD ("@Data", Serialize (session));
SAVECMD.PARAMETERS.ADD ("@LastAccessed", DateTime.Now.ToString ());

Conn. Open ();
Savecmd.executenonquery ();
}
Finally
{
IF (conn!= null)
Conn. Close ();
}
}
Private byte[] Serialize (mysession session)
{
if (session = NULL) return null;

Stream stream = null;
byte[] state = null;

Try
{
IFormatter formatter = new BinaryFormatter ();
stream = new MemoryStream ();
Formatter. Serialize (stream, session);
state = new Byte[stream. Length];
Stream. Position = 0;
Stream. Read (state, 0, (int) stream. Length);
Stream. Close ();
}
Finally
{
if (stream!= null)
Stream. Close ();
}
return state;
}

The Sessionpage class and its associated classes are packaged, sessionutility in the assembly. In a new ASP.net project, a reference would be made to the Sessionutility assembly, and every page would derive from the Ses Sionpage instead of the from the Page class in order to share sessions with classic ASP codes. Once The porting is completed, the new application can switch back to use the native HttpSession object by commenting out The session variable declaration the Sessionpage class to unhide the base HttpSession.



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.