Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Blogs | Beginners
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » ASP.NET and Web » Session State Management in Application having ASP and ASP. Net Pages in VB.NET

Session State Management in Application having ASP and ASP. Net Pages in VB.NET


If we are developing a web application in which both ASP and ASP.NET pages resides, then passing session information from ASP to ASP.NET page or vice versa becomes a critical issue. To share session state between ASP and ASP.NET pages, session state need to be stored in some common format like in database.

Total page views :  11851
Total downloads : 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Become a Sponsor

If we are developing a web application in which both ASP and ASP.NET pages resides, then passing session information from ASP to ASP.NET page or vice versa becomes a critical issue.

To share session state between ASP and ASP.NET pages, session state need to be stored in some common format like in database.

In the following example, ASP and ASP.NET session states are stored in Microsoft SQL Server database.

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 is derived from the System.Web.UI.Page to offer all the same features as the Page class. The only difference with the derived page is that the default HttpSession is overridden with a custom session object. (Using the new modifier for the instance variable, VB.Net allows the derived class to hide members of the base class.)

<Serializable> _
Public Class mySession
Private dic As HybridDictionary = New HybridDictionary()
Public Sub mySession()
End Sub

Public Default Property Item(ByVal name As String) As String
Get
Return
CStr(dic(name.ToLower()))
End Get
Set
dic(name.ToLower()) = Value
End Set

End Property
End
Class

The Page class exposes different events and methods for customization. In particular, the OnInit method is used to set the initialize state of the Page object. If the request does not have the mySession cookie, a new mySession cookie will be issued to the requester. Otherwise, the session data will be retrieved from SQL Server using a custom data access object, SessionPersistence. The dsn and SessionExpiration values are retrieved from the web.config.

Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
InitializeComponent()
End Sub

Private Sub InitializeComponent()
cookie =
Me.Request.Cookies(sessionPersistence.SessionID)
If cookie Is Nothing Then
   Session = New mySession()
   CreateNewSessionCookie()
   IsNewSession =
True
Else
   Session = sessionPersistence.LoadSession(Server.UrlDecode(cookie.Value).ToLower().Trim(), dsn, SessionExpiration)
End If
Me
.Unload += New EventHandler(Me.PersistSession)
End Sub

Private Sub CreateNewSessionCookie()
cookie =
New HttpCookie(sessionPersistence.SessionID, sessionPersistence.GenerateKey())
Me.Response.Cookies.Add(cookie)
End Sub

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

Public Function LoadSession(ByVal key As String, ByVal dsn As String, ByVal SessionExpiration As Integer) As mySession
Dim conn As SqlConnection = New SqlConnection(dsn)
Dim LoadCmd As SqlCommand = New SqlCommand()
LoadCmd.CommandText = command
LoadCmd.Connection = conn
Dim reader As SqlDataReader = Nothing
Dim
Session As mySession = Nothing
Try
LoadCmd.Parameters.Add("@ID", New Guid(key))
conn.Open()
reader = LoadCmd.ExecuteReader()
If reader.Read() Then
Dim
LastAccessed As DateTime =reader.GetDateTime(1).AddMinutes(SessionExpiration)
If LastAccessed >= DateTime.Now Then
Session = Deserialize(CType(reader("Data"), Byte()))
End If
End
If
Finally
If
Not reader Is Nothing Then
reader.Close()
End If
If
Not conn Is Nothing Then
conn.Close()
End If
End
Try
Return
Session
End Function

Private Function Deserialize(ByVal state As Byte()) As mySession
If state Is Nothing Then
Return
Nothing
End
If
Dim
Session As mySession = Nothing
Dim
stream As Stream = Nothing
Try
stream = New MemoryStream()
stream.Write(state, 0, state.Length)
stream.Position = 0
Dim formatter As IFormatter = New BinaryFormatter()
Session =
CType(formatter.Deserialize(stream), mySession)
Finally
If
Not stream Is Nothing Then
stream.Close()
End If
End
Try
Return
Session
End Function

At the end of the request, the Page class Unload event is fired, and an event handler registered with the Unload event will serialize the session data into binary format and save the resulting binary data into SQL Server.

Private Sub PersistSession(ByVal obj As Object, ByVal arg As System.EventArgs)
sessionPersistence.SaveSession(Server.UrlDecode(cookie.Value).ToLower().Trim(), dsn, Session, IsNewSession)
End Sub

Public Sub SaveSession(ByVal key As String, ByVal dsn As String, ByVal Session As mySession, ByVal IsNewSession As Boolean)
Dim conn As SqlConnection = New SqlConnection(dsn)
Dim SaveCmd As SqlCommand = New SqlCommand()
SaveCmd.Connection = conn
Try
If
IsNewSession Then
SaveCmd.CommandText = InsertStatement
Else
SaveCmd.CommandText = UpdateStatement
End If
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
Not conn Is Nothing Then
conn.Close()
End If
End
Try
End
Sub

Private Function Serialize(ByVal Session As mySession) As Byte()
If Session Is Nothing Then
Return
Nothing
End
If
Dim
stream As Stream = Nothing
Dim
state As Byte() = Nothing
Try
Dim
formatter As IFormatter = New BinaryFormatter()
stream =
New MemoryStream()
formatter.Serialize(stream, Session)
state =
New Byte(stream.Length - 1){}
stream.Position = 0
stream.Read(state, 0,
CInt(stream.Length))
stream.Close()
Finally
If
Not stream Is Nothing Then
stream.Close()
End If
End
Try
Return
state
End Function

The SessionPage class and its associated classes are packaged in the SessionUtility assembly. In a new ASP.NET project, a reference will be made to the SessionUtility assembly, and every page will derive from the SessionPage instead of from the Page class in order to share session 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 in the SessionPage class to unhide the base HttpSession.

Storing ASP Session in Database.

The ASP session can only be stored in memory,so in order to store session data in SQL Server,we need to write a COM object,In this example Visual Basic-6 object is written. instead of using the native session object. This COM object will be instantiated in the beginning of each Web request and reload the session data from SQL Server. When the ASP script is finished, this object will be terminated and the session state will be persisted back to SQL Server.

The primary purpose of the Visual Basic 6 COM Session object is to provide access to the Microsoft Internet Information Server intrinsic objects. The Visual Basic 6.0 COM Session object uses the mySession class of SessionUtility assembly to hold the session state, and the SessionPersistence class of SessionUtility to load and save session data with SQL Server. The mySession and SessionPersistence classes are exposed as COM objects using the regasm.exe utility. The regasm.exe utility can register and create a type library for the COM client to consume Framework classes.

The session state information is reloaded during the construction of the object. The constructor (class_initialize) will first retrieve the session cookie, session timeout (SessionTimeOut), and database connection string (SessionDSN) from the Application object, and create an instance of the class mySession to hold the session data. Then the constructor will try to reload the session data from SQL Server with the given cookie. If the SQL Server does not have the session information, or the session has been expired, a new cookie will be issued. If the SQL Sever does return with the session state data, the session state will be stored 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, yDSNString, myTimeOut)
End If
Exit
Sub
ErrHandler:
Err.Raise Err.Number, METHOD_NAME & ":" & Err.Source, Err.Description
End Sub

When the object instance goes out of scope in the script, the destructor (class_terminate) will execute. The destructor will persist the session data using the SessionPersistence.SaveSession() method. If this is a new session, the destructor will also send 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

NOTE: THIS ARTICLE IS CONVERTED FROM C# TO VB.NET USING A CONVERSION TOOL. ORIGINAL ARTICLE CAN BE FOUND ON C# CORNER (WWW.C-SHARPCORNER.COM).


Login to add your contents and source code to this article
 About the author
 
pinal.dave
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
SQL and .NET performance profiling in one place
Investigate SQL and .NET code side-by-side with ANTS Performance Profiler 6, so you can see which is causing the problem without switching tools.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
60 FREE UI Controls from DevExpress
Register for your FREE copy on over 60 free presentation controls from DevExpress - Absolutely Free-of-Charge without any royalties or distribution costs. Visit Devexpress.com/60 today. Free controls include advanced lists box, dropdown calendar, rich text edit, spin edit, tab control and so much more!

DevExpress engineers feature rich presentation controls and reporting tools for WinForms, ASP.NET, WPF, and Silverlight. Our technologies help you build your best, see complex software with greater clarity and deliver compelling business solutions for Windows and the web in the shortest possible time.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010
Visualize your workspace with new multiple monitor support, powerful Web development, new SharePoint support with tons of templates and Web parts, and more accurate targeting of any version of the .NET Framework. Get set to unleash your creativity.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
Read the Top 10 Books for Microsoft Developers, 15 Days FREE
Read the Top 10 Books for Microsoft Developers, 15 Days FREE
Try Safari Books Online - 15 Days FREE + 15% Off for 1 Year
Try Safari Books Online - 15 Days FREE + 15% Off for 1 Year
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Become a Sponsor
 Comments
ANTS Performance Profiler 6.0
 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2010.8.14
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.