?
Solved

Sharing session state between asp .net and asp  -- advice needed pleas

Posted on 2006-04-21
2
Medium Priority
?
691 Views
Last Modified: 2008-01-09
Hi There,

I recently read an article that explained how to share session information between asp and asp .net. I tested it on my dev server and it seems to be working fine except that if I start another browser session it gives me access to the information I had from the previous session, for example if I have 2 browser windows open then it shows me the same information in both windows. I was just wondering if this is a design flaw or this is supposed to happen when accessing the website from the same machine using 2 different browser sessions.

article: http://www.asp101.com/articles/sidney/sharingsessionstate/default.asp

ASP >NET CODE -------------------

Imports System
Imports System.Collections
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Web
Imports System.Web.SessionState
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.HtmlControls
Imports System.Data.SqlClient
Namespace pcf_solution_cs

    Public Class SessionTransfer
        Inherits System.Web.UI.Page

        Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            Dim guidSave As String
            If Request.QueryString("dir") = "2asp" Then
                guidSave = AddSessionToDatabase()
                Response.Redirect("SessionTransfer.asp?dir=2asp&guid=" + guidSave + "&url=" + Server.UrlEncode(Request.QueryString("url")))
            Else
                GetSessionFromDatabase(Request.QueryString("guid"))
                ClearSessionFromDatabase(Request.QueryString("guid"))
                Response.Redirect(Request.QueryString("url"))
            End If
        End Sub

        Private Function AddSessionToDatabase() As String
            Dim strConnStr As String = (ConfigurationSettings.AppSettings("connectionString"))
            Dim con As SqlConnection = New SqlConnection(strConnStr)
            Dim cmd As SqlCommand = New SqlCommand
            con.Open()
            cmd.Connection = con
            Dim i As Integer = 0
            Dim strSql As String
            Dim guidTemp As String = GetGuid()
            While i < Session.Contents.Count
                strSql = "INSERT INTO ASPSessionState (GUID, SessionKey, SessionValue) " + "VALUES ('" + guidTemp + "', '" + Session.Contents.Keys(i).ToString + "', '" + Session.Contents(i).ToString + "')"
                cmd.CommandText = strSql
                cmd.ExecuteNonQuery()
                System.Math.Min(System.Threading.Interlocked.Increment(i), i - 1)
            End While
            con.Close()
            cmd.Dispose()
            con.Dispose()
            Return guidTemp
        End Function

        Private Sub GetSessionFromDatabase(ByVal guidIn As String)
            Dim strConnStr As String = (ConfigurationSettings.AppSettings("connectionString"))
            Dim con As SqlConnection = New SqlConnection(strConnStr)
            Dim cmd As SqlCommand = New SqlCommand
            Dim dr As SqlDataReader
            con.Open()
            cmd.Connection = con
            Dim strSql As String
            Dim guidTemp As String = GetGuid()
            strSql = "SELECT * FROM ASPSessionState WHERE GUID = '" + guidIn + "'"
            cmd.CommandText = strSql
            dr = cmd.ExecuteReader
            While dr.Read
                Session(dr("SessionKey").ToString) = dr("SessionValue").ToString
            End While
            dr.Close()
            con.Close()
            cmd.Dispose()
            con.Dispose()
        End Sub

        Private Sub ClearSessionFromDatabase(ByVal guidIn As String)
            Dim strConnStr As String = (ConfigurationSettings.AppSettings("connectionString"))
            Dim con As SqlConnection = New SqlConnection(strConnStr)
            Dim cmd As SqlCommand = New SqlCommand
            con.Open()
            cmd.Connection = con
            Dim strSql As String
            strSql = "DELETE FROM ASPSessionState WHERE GUID = '" + guidIn + "'"
            cmd.CommandText = strSql
            cmd.ExecuteNonQuery()
            con.Close()
            cmd.Dispose()
            con.Dispose()
        End Sub

        Private Function GetGuid() As String
            Return System.Guid.NewGuid.ToString
        End Function

        Protected Overloads Overrides Sub OnInit(ByVal e As EventArgs)
            InitializeComponent()
            MyBase.OnInit(e)
        End Sub

        Private Sub InitializeComponent()

        End Sub
    End Class
End Namespace

asp code

<%@ LANGUAGE="VBScript" %>
<%Option Explicit%>

<%
 dim DbConnectionStr
'***********************************
'Functions
'***********************************
 DbConnectionStr = "Provider=SQLOLEDB.1;" & _
                       "Password=pass;" & _
                       "Persist Security Info=True;" & _
                       "User ID=user;" & _
                       "Initial Catalog=dev;" & _
                       "Data Source=datasource;"


'Function returns a valid Globally Unique ID (GUID) for identifying a session.
Function GetGuid()
      Dim TypeLib, guid_temp
      
      Set TypeLib = Server.CreateObject("Scriptlet.TypeLib")
      
      'A true GUID contains a unicode null termination, that needs to be stripped to behave like
      '  a string.
      guid_temp = TypeLib.Guid
      GetGuid = Left(guid_temp, Len(guid_temp) - 2)
            
      Set TypeLib = Nothing
End Function

'This function adds all Session information to the database and returns the GUID used to
'  identify the Session information.
Function AddSessionToDatabase()
      'Declare Variables
      Dim con, cmd, strSql, guidTemp, i

      'Initialize Variables
      Set con = Server.CreateObject("ADODB.Connection")

'******************
      con.Open dbConnectionStr
'******************

      Set cmd = Server.CreateObject("ADODB.Command")
      cmd.ActiveConnection = con
      i = 1

      'Iterate through all Session variables and add them to the database with the
      '  same GUID as an identifier.
      guidTemp = GetGuid()
            
      Do While (i <= Session.Contents.Count)
            strSql = "INSERT INTO ASPSessionState (GUID, SessionKey, SessionValue) " + _
                  "VALUES ('" + guidTemp + "', '" + Session.Contents.Key(i) + "', '" + cstr(Session.Contents.Item(i)) + "')"
            cmd.CommandText = strSql
            cmd.Execute
            i = i + 1
            
            'response.Write Session.Contents.Key(i) & " " & Session.Contents.Item(i)
      Loop

      'Return the GUID used to identify the Session information
      AddSessionToDatabase = guidTemp

      'Clean up database objects
      con.Close
      Set cmd = Nothing
      Set con = Nothing
End Function

'This function retrieves the Session information identified by the parameter guidIn. The
'  resulting Session information is loaded into the Session object, it is not returned.
Sub GetSessionFromDatabase(guidIn)
      'Declare Variables
      Dim con, cmd, rs, strSql, guidTemp, i

      'Initialize Variables
      Set con = Server.CreateObject("ADODB.Connection")

'******************
      con.Open dbConnectionStr
'******************

      Set cmd = Server.CreateObject("ADODB.Command")
      cmd.ActiveConnection = con
      i = 1

      strSql = "SELECT * FROM ASPSessionState WHERE GUID = '" + guidIn + "'"
      Set rs = Server.CreateObject("ADODB.Recordset")
      rs.Open strSql, con

      While Not(rs.EOF)
            Session(rs("SessionKey")) = rs("SessionValue")
            rs.MoveNext
      Wend


      i = 1
      Do While (i <= Session.Contents.Count)
            Response.Write "Session(""" + Session.Contents.Key(i) + """) - " + Session.Contents.Item(i) + "<BR>"
            i = i + 1
      Loop
      
      'Clean up database objects
      rs.Close
      con.Close

      Set rs = Nothing
      Set cmd = Nothing
      Set con = Nothing
End Sub

'This performs cleanup of the Session information identified by the parameter guidIn. All Session
'  information in the database with the specified GUID is deleted.
Sub ClearSessionFromDatabase(guidIn)
      'Declare Variables
      Dim con, cmd, strSql

      'Initialize Variables
      Set con = Server.CreateObject("ADODB.Connection")

'******************
      con.Open dbConnectionStr
'******************

      Set cmd = Server.CreateObject("ADODB.Command")
      cmd.ActiveConnection = con
      
      'Remove all session variables from the database
      strSql = "DELETE FROM ASPSessionState WHERE GUID = '" + guidIn + "'"
      'Response.Write strSql + "<BR>"
      cmd.CommandText = strSql
      cmd.Execute

      'Clean up database objects
      con.Close
      Set cmd = Nothing
      Set con = Nothing
End Sub

'***********************************
'Main code execution
'***********************************

Dim guidSave

If Request.QueryString("dir") = "2aspx" Then
      'Store the session information in the database, and switch to ASP.NET
      guidSave = AddSessionToDatabase()
      Response.Redirect("SessionTransfer.aspx?dir=2aspx&guid=" + guidSave + "&url=" & Server.URLEncode(Request.QueryString("url")))
Else
      'Retrieve the session information and redirect to the specified URL
      Call GetSessionFromDatabase(Request.QueryString("guid"))

      'Clean up the database
      Call ClearSessionFromDatabase(Request.QueryString("guid"))
      Response.Redirect(Request.QueryString("url"))
End If
%>
0
Comment
Question by:bullrout
2 Comments
 
LVL 6

Accepted Solution

by:
the_paab earned 1500 total points
ID: 16515951
When you create New Page in IE then it is created really only new window in the same session. New session is created when you run another IE process.
0
 
LVL 5

Author Comment

by:bullrout
ID: 16559429
Hi paab,

Thanks for the answer. I did a little more testing and it seemed to work fine.

Sean
0

Featured Post

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

One of the pain points with developing AJAX, JavaScript, JQuery, and other client-side behaviors is that JavaScript doesn’t allow for cross domain request for pulling content. For example, JavaScript code on www.johnchapman.name could not pull conte…
IntroductionWhile developing web applications, a single page might contain many regions and each region might contain many number of controls with the capability to perform  postback. Many times you might need to perform some action on an ASP.NET po…
Is your data getting by on basic protection measures? In today’s climate of debilitating malware and ransomware—like WannaCry—that may not be enough. You need to establish more than basics, like a recovery plan that protects both data and endpoints.…
Despite its rising prevalence in the business world, "the cloud" is still misunderstood. Some companies still believe common misconceptions about lack of security in cloud solutions and many misuses of cloud storage options still occur every day. …
Suggested Courses

840 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question