How to share session status between traditional ASP and ASP. NET

Source: Internet
Author: User
How to share session status between traditional ASP and ASP. NET

Release date: 4/1/2004 | Updated on: 4/1/2004

Billy Yuen

Microsoft Corporation

February 2003

Applicable:

Microsoft ASP. NET

Abstract:This article discusses how to utilize the serialization features of the Microsoft. NET Framework class and the. NET Framework to share session statuses between traditional ASP and Microsoft ASP. NET. By sharing session status, you can run existing ASP applications in parallel.ProgramAnd ASP. NET applications, ASP applications are converted into ASP. NET Applications in stages. (12 page printing)

Download the source code of this article.

Content on this page

Introduction
Concept Overview
ASP. NET implementation
ASP implementation
Demo program
Embed COM objects in existing ASP applications
Limitations/improvements
Summary

Introduction

Microsoft ASP. NET is the latest Microsoft technology used to develop web-based applications. Compared with the traditional ASP script technology, it has many advantages, including: 1) separating the UI representation from the business logic to provide a better development structure; 2) itCodeIs fully compiled, and the code in the traditional ASP is interpreted; and 3) its compilation feature is combined with its high-speed cache support, which means that compared with the equivalent site written in the traditional ASP, use ASP.. Net has significantly improved the performance of websites.

Although converting existing ASP applications to ASP. NET has potential benefits, many existing ASP applications have a critical mission and are quite complex. This conversion process may require a large amount of resources and may bring additional risks to existing applications. To solve these problems, you can run ASP and ASP. net at the same time and convert only a part of the application to ASP. NET at a time. To run New and Old applications at the same time, a mechanism is required to share the session state between traditional ASP and ASP. NET. In this article, I will discuss how to share these session states using several classes and serialization features of the Microsoft. NET Framework.

Back to topic Overview

Cookie is the most common method used by web applications to identify user sessions. It can be used by traditional ASP and ASP. NET to identify session statuses. However, session status information is stored in the memory using ASP scripts and cannot be shared with other applications (such as ASP. NET. If the session status is stored in Microsoft SQL server in a common format, the traditional ASP and ASP. NET can access the session status.

In this example, a cookie named mysession is used to identify a user session. When a user sends a request to a web application, the user is assigned a unique cookie to identify the session. In subsequent requests, the browser sends the unique cookie back to the server to identify the session. Before loading the requested web page, a custom object will use this unique cookie to reload user session data from SQL Server. You can access the session status through the custom object on the web page. After a Web Request ends, session data will be stored back to SQL Server as the request ends (see figure 1 ).

Figure 1. Sample Data Stream Back to Top ASP. NET implementation

In ASP. NET, every web page isSystem. Web. UI. PageClass.PageClass containsHttpsessionAn instance of the object for session data. In this exampleSystem. Web. UI. PageDerived fromSessionpageUser-DefinedPageClass to achievePageClass has the same features. The only difference between a derived page is that a custom Session object is used to override the defaultHttpsession. (Using instance variablesNewModifier, C # allows the derived class to hide the members of the base class .)

 
Public class sessionpage: system. Web. UI. Page {... public new mysession session = NULL ;...}

Custom session classes are usedHybriddictionaryThe object stores the session Status in the memory. (HybriddictionaryCan efficiently process any number of session elements .) To achieve interoperability with traditional ASP, this custom session class limits the session data type to only string type. (DefaultHttpsessionAny type of data can be stored in sessions, which cannot interwork with traditional 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 ;}}}

PageClass to expose different events and methods for customization. In particular,OninitMethod for settingPageObject initialization status. If the request does not have a mysession cookie, a new mysession cookie will be issued to the requester. Otherwise, a Custom Data Access Object (Sessionpersistence) Retrieves session data from SQL Server. DSN andSessionexpirationThe value is retrieved from 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;} elsesession = sessionpersistence. loadsession (server. urldecode (cookie. 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 );}

For optimal performance,SessionpersistenceClass using the Microsoft. NET FrameworkBinaryformatterIn binary format. Then, the obtained binary session status data is stored in SQL Server as an art field.

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 = 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 ;}

when the request ends, the unload event of the page class is triggered, register an event handler for the unload event to serialize session data to a binary format and save the binary data to SQL Server.

Private void persistsession (Object OBJ, system. eventargs Arg) {sessionpersistence. savesession (server. urldecode (cookie. 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. commandt EXT = insertstatement; elsesavecmd. 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 = 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 ;}

SessionpageClasses and their related classes are encapsulated in the sessionutility assembly. In the new ASP. NET project, a reference to the sessionutility assembly will be created, and to share sessions with traditional ASP codeSessionpageInsteadPageClass to derive each page. Once the migration process is completed, comment outSessionpageThe session variable declaration in the class can remove the base class.HttpsessionSo that new applications can switch back to use the localHttpsessionObject.

Back to Top ASP implementation

ASP sessions on the local machine can only store session data in the memory. To store session data to SQL Server, we have compiled a custom Microsoft Visual Basic6.0 COM object to manage the session Status, instead of using the local Session object for management. This COM object will be instantiated at the beginning of each Web request and re-load session data from SQL Server. When the ASP script is complete, the object is terminated and the session status is saved back to SQL Server.

Visual Basic 6 comSessionThe main purpose of an object is to provide access to objects in Microsoft Internet Information Server. Visual Basic 6.0 COM session object usesMysessionClass to retain the session status, and useSessionpersistenceClass to load session data from SQL Server or save session data back to SQL Server. Use the regasm.exe utility,MysessionAndSessionpersistenceClass can be exposed as a COM object. The regasm.exe utility can register and create a class library so that the COM Client can use various framework classes.

Session status information can be reloaded during the object construction process. Constructor (Class_initialize)ApplicationSession Cookie retrieval and Session Timeout (Sessiontimeout) And the database connection string (sessiondsn), and createMysessionTo hold the session data. The constructor then tries to reload session data from SQL server using the given cookie. If SQL server does not contain the corresponding session information or the session has expired, a new cookie is issued. If SQL Sever does return session status data, these session statuses will be stored inMysessionObject.

 private sub class_initialize () on error goto errhandler: const method_name as string = "class_initialize" set mysessionpersistence = new custom myobjectcontext = getobjectcontext () mysessionid = readsessionid () mydsnstring = getconnectiondsn () mytimeout = getsessiontimeout () myisnewsession = falsecall initcontentsexit suberrhandler: Err. raise err. number, method_name & ":" & err. source, err. descriptionend subprivate sub initcontents () on error goto errhandler: const method_name as string = "initcontents" If mysessionid = "" thenset mycontentsentity = new feature = mysessionpersistence. generatekeymyisnewsession = trueelseset mycontentsentity = mysessionpersistence. loadsession (mysessionid, mydsnstring, mytimeout) end ifexit suberrhandler: Err. raise err. number, method_name & ":" & err. source, err. descriptionend sub 

When the instance of this object exceeds the scope of the script, the Destructor (Class_terminate) Will be executed. The Destructor will useSessionpersistence. savesession ()Method To maintain session data. If this is a new session, The Destructor returns a new cookie to the browser.

 
Private sub class_terminate () on error goto errhandler: const method_name as string = "class_terminate" Call setdataforsessionidexit suberrhandler: Err. raise err. number, method_name & ":" & err. source, err. description> end subprivate sub setdataforsessionid () on error goto errhandler: const method_name as string = "setdataforsessionid" Call mysessionpersistence. savesession (mysessionid, mydsnstring, timeout, myisnewsession) If myisnewsession then call writesessionid (mysessionid) set timeout = nothingset myobjectcontext = nothingset timeout = nothingexit suberrhandler: Err. raise err. number, method_name & ":" & err. source, err. descriptionend sub

Click the link at the top of this article to downloadSource code-Com session manager and Demo code.

Back to Top demo

This demo program is designed to increase and display a number. No matter which page is loaded, the number will always increase, because the value is stored in SQL Server and shared between traditional ASP and ASP. NET.

Procedure

    • Create a new database named sessiondemodb.

    • Create a sessstate table (osql.exe-e-d sessiondemodb-I session. SQL ).

    • Create a new virtual directory named demo.

    • Close ASP Session on the ASP Configuration tab.

    • Copy web. config, testpage. aspx, global. Asa, testpage. asp, and globalinclude. asp to the virtual directory.

    • Update the DSN string settings in global. Asa and web. config. The Session Timeout setting is optional. The default value is 20 minutes. Listen

    • Install sessionutility. DLL to Global Assembly Cache (gacutil/I sessionutility. dll ).

    • Use regasm.exe to publish sessionutility. dll as a COM Object (regasm.exe sessionutility. dll/TLB: sessionutility. TLB ).

    • Copy sessionmanager. DLL to a local directory and use regsvr32.exe to register the file (regsvr32 sessionmanager. dll ).

    • Grant the IUSR _ <machine_name> account the read and execution permissions on sessionmgr. dll.

Procedure

    • Start Microsoft Internet Explorer.

    • Load testpage. asp of traditional ASP. The number "1" should be displayed on the web page ".

    • Click the refresh button on Internet Explorer to reload the page. This number should increase progressively.

    • Change the URL to testpage. aspx of ASP. NET. This number should continue to increase.

    • If you start the testpage. ASPX page, you can repeat the same process.

Back to header embedding COM objects in an existing ASP Application

When developing an ASP application, it is customary to include a file at the beginning of each script to share public code and constants. To add a custom Session object, the best way is to add the corresponding instantiated code to the Public inclusion file. The last step is to replace all references to the session object with the custom session variable name.

Back to Top limitations/improvements

If an existing ASP application stores a COM Object inSessionThe solution does not support this situation. In this case, a custom mail collector is required to serialize/deserialize various States to use custom session objects. In addition, this solution does not support storing string-type arrays. However, with a little effort, we can use Microsoft Visual Basic6.0JoinThe function combines all array elements into a single string and then stores them in the session object to implement this function. Use Visual Basic 6.0SplitThe function splits the string into an array element to complete reverse operations. In the. NET Framework,JoinAndSplitAll methodsStringClass member.

Back to Top Summary

ASP. NET represents a new programming model and structure, and has more advantages than the traditional ASP. Although migrating from ASP to ASP. NET is not a simple process, ASP. NET's better programming model and higher performance make the conversion process worthwhile. Besides storing COM objects inSessionThe method described in this article provides a solution to simplify the migration process.

About the author

Billy YuenHe works at Microsoft Silicon Valley technology center in North California. This center is dedicated to developing Microsoft. NET Framework solutions. If you want to contact him, you can send an email to the billyy@microsoft.com.

Transfer to original English page

Back to Top
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.