Sharing dialog status between ASP and ASP.net

Source: Internet
Author: User
Tags exit config goto include variables split terminates trim
asp.net


[Foreword:]asp.net is the latest technology for developing web-based applications from Microsoft.] It provides a number of benefits over traditional ASP scripting technologies, including:

(1) A better development structure is established by separating the UI presentation layer (presentation) from the commercial logic (business logic);

2 replaces traditional ASP code translation with fully compiled code;

3 It compiles features in conjunction with each supported method, which means that sites using ASP.net are more performance-efficient than traditional ASP sites.

While there are many potential benefits to converting existing ASP applications to ASP.net, some ASP application tasks are important and complex. The conversion process may require additional resources and pose additional risks to the application. One way to solve these problems is to run both ASP and ASP.net applications and convert a conversation to asp.net at one time. In order to run both old and new programs at the same time, it is necessary to establish a mechanism to share the state of conversation between traditional ASP and asp.net. This article discusses how to use. NET Framework components share state information with the class and serialization attributes.

Overview

Cookies are the most common way for Web applications to identify user conversations and can be used to identify traditional ASP and ASP.net dialog states. In ASP scripts, state information is stored in memory and cannot be shared with other applications, such as asp.net. If the dialog state is saved in a common format in Microsoft SQL Server, it can be accessed by traditional ASP and asp.net.

In this case, a cookie named mysession is used to identify user conversations. When a user makes a request to a Web application, a unique cookie is generated for that user to identify the conversation. In a subsequent request, the browser sends the unique cookie back to the server to identify the conversation. A custom object will use the unique cookie to reload user dialog data from SQL Server before the requested Web page is loaded. The dialog status in the Custom Object Web page is accessible. When the Web request completes, the dialog data is saved back to SQL Server if the request terminates (see Figure 1).

Figure 1. Simple Data Flow Diagram

Asp. NET implementation

Each Web page in asp.net is derived from the System.Web.UI.Page class. The page class sets up an instance of the HttpSession object to process the dialog data. In this case, the custom page class, called Sessionpage, derives from System.Web.UI.Page, providing all the attributes similar to the page class. The only difference is that the default HttpSession uses a custom dialog object overload (using the new modifier for instance variables, C # allows derived classes to hide the members of the base class).


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

The custom dialog class uses the HybridDictionary object to save the dialog state in memory appropriately (HybridDictionary can be used to handle any number of dialog elements). For common use with traditional ASP, the custom Dialog object restricts the dialog data type to a string type (the default httpsession allows dialogs to hold any type of data, not common to 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;
}
}
}


The page class exposes different events and methods for customization. In particular, the OnInit method is used to set the initialization state of the Page object. If the request does not contain a cookie named MySession, a new mysession cookie will be generated for the requester. In addition, the dialog data is retrieved from SQL Server using the 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 component to serialize and parallel the dialog state in binary format to provide optimal performance. The resulting binary dialog data is then stored as an Image field type in SQL Server.


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 Unload event for the page class is started, and an event-handling method registered with the Unload event will serialize the dialog data into binary format and save the resulting binary data to 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 the classes associated with it are encapsulated in the sessionutility component. In a new ASP.net project, you need to make a reference to the Sessionutility component, in order to share the conversation with the traditional ASP code, each page is derived from the sessionpage instead of the page class. Once the porting is complete, the new application can switch back to using the original HttpSession object to display the basic httpsession by stating the dialog variables defined in the Sessionpage class. ASP implementation

The original ASP dialog can only save the conversation data in memory. To save the conversation data to SQL Server, you need to write a custom visual Basic 6.0 COM object instead of the current dialog object to manage the dialog state. The COM object is initialized at the start of each Web request and the dialog data is loaded back from SQL Server. When the ASP script completes, the object terminates and the dialog state is returned to SQL Server.
The primary purpose of the Visual Basic 6 COM Session object is to provide access to the internal objects of Microsoft Internet Information Server (IIS). The Visual Basic 6 com Dialog object uses the MySession class of the sessionutility component to save the dialog state, and the Sessionutility Sessionpersistence class is used to load and save the dialog data to the SQL Server. Use the Regasm.exe tool to expose mysession and Sessionpersistence classes as COM objects. The Regasm.exe tool can register and establish a type library for COM clients to use the framework component classes.

State information is being loaded back into the object's constructor. The constructor (Class_Initialize) first retrieves the dialog cookie, the dialog Timeout setting (sessiontimeout), the database connection string (SESSIONDSN) from the Application object, and establish an instance of the MySession class to hold the dialog data. The constructor then attempts to load the dialog data from SQL Server using the given cookie again. If there is no dialog information in SQL Server, or if the conversation is terminated, a new cookie is generated. If SQL Server returns the dialog state data, the dialog state information is saved in the MySession object.


Private Sub Class_Initialize ()
On Error GoTo ErrHandler:
Const method_name as String = "Class_Initialize"
Set mysessionpersistence = New sessionpersistence
Set Myobjectcontext = GetObjectContext ()
Mysessionid = Readsessionid ()
mydsnstring = Getconnectiondsn ()
Mytimeout = Getsessiontimeout ()
Myisnewsession = False
Call Initcontents

Exit Sub
ErrHandler:
Err.Raise Err.Number, Method_name & ":" & Err.Source, Err.Description
End Sub

Private Sub initcontents ()
On Error GoTo ErrHandler:
Const method_name as String = "Initcontents"
If Mysessionid = "" Then
Set mycontentsentity = New mysession
Mysessionid = Mysessionpersistence.generatekey
Myisnewsession = True
Else
Set mycontentsentity =mysessionpersistence.loadsession (Mysessionid, mydsnstring, Mytimeout)
End If

Exit Sub
ErrHandler:
Err.Raise Err.Number, Method_name & ":" & Err.Source, Err.Description
End Sub


If the object instance is outside the scope of the script, the destructor (Class_Terminate) is executed. The destructor uses the Sessionpersistence.savesession () method to hold the dialog data. If this is a new conversation, the destructor sends the new cookie back to the browser.


Private Sub Class_Terminate ()
On Error GoTo ErrHandler:
Const method_name as String = "Class_Terminate"
Call Setdataforsessionid
Exit Sub
ErrHandler:
Err.Raise Err.Number, Method_name & ":" & Err.Source, Err.Description
End Sub

Private Sub Setdataforsessionid ()
On Error GoTo ErrHandler:
Const method_name as String = "Setdataforsessionid"
Call Mysessionpersistence.savesession (Mysessionid,
Mydsnstring, mycontentsentity, myisnewsession)

If myisnewsession Then Call Writesessionid (Mysessionid)

Set mycontentsentity = Nothing
Set Myobjectcontext = Nothing
Set mysessionpersistence = Nothing
Exit Sub
ErrHandler:
Err.Raise Err.Number, Method_name & ":" & Err.Source, Err.Description
End Sub


Routines

The routines are designed to add and display a number. Regardless of which page is loaded, numbers are increasing as numeric values are stored in SQL Server and shared between ASP and ASP.net.

Steps to establish a routine

1. Create a new database Sessiondemodb.

2. Create a new Table Sessstate (OSQL.EXE-E-D sessiondemodb-i session.sql).

3. Create a new virtual directory demo.

4. Close the ASP dialog in the ASP Configuration page.

5. Copy web.config, testpage.aspx, Global.asa, testpage.asp, and globalinclude.asp to the virtual directory.

6. Updates the DSN string settings in Global.asa and web.config. The dialog timeout setting is optional and defaults to 20 minutes.

7. Installs the SessionUtility.dll to the Global component cache (gacutil/i SessionUtility.dll).

8. Use Regasm.exe to expose SessionUtility.dll as a COM object (Regasm.exe sessionutility.dll/tlb:sessionutility.tlb).

9. Copy the SessionManager.dll to the local directory and use Regsvr32.exe registration (regsvr32 SessionManager.dll).

10. Gives the iusr_< computer name > account permission to read and run Access SessionMgr.dll.

Steps to run a routine

1. Open Microsoft Internet Explorer.

2. Load the testpage.asp for the traditional ASP. The number "1" will appear in the Web page.

3. Click the refresh of Internet Explorer to reload the page. The numbers will increase.

4. Change the URL for asp.net to testpage.aspx. The number is still increasing.

5. If you start with testpage.aspx, the procedure is the same.

Inserting a COM object in an existing ASP application

A common habit of developing ASP applications is to include a file at the beginning of each script to share code and constants. The final way to insert a custom dialog object is to include the sample code in the public inclusion file. The last step simply replaces all references to the dialog object with a custom dialog variable name.

Limitation/Improvement

ASP applications that hold COM objects in the session object are not supported in this scenario. In this case, in order to use a custom dialog object, a custom scheduler is needed to serialize/parallelization the state. Also, this scenario does not support saving arrays of string types. Some additional work can be done with this feature: using the Join function of Visual Basic 6.0 to concatenate an array element into a string before saving it to a dialog object, you can use the Split function of Visual Basic 6.0 to decompose the string into a separate array element. In the. NET Framework component, the join and split methods make the members of the string class.

Conclusion

Asp. NET presents new programming paradigms and architectures, and offers many advantages over traditional ASP. Although the process of porting ASP to asp.net is not simple, asp.net a better programming model and higher performance will make the conversion process worthwhile. In addition to saving a special case of COM objects in the Session object, the approach discussed in this article provides a simple solution for implementing migration.




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.