Link to home
Start Free TrialLog in
Avatar of ksfok
ksfok

asked on

User logout time

The closing of the browser is not trapped by session_end in global.asax, right? Then what's the event for trapping when a user closes the browser or leaves a site in code behind? Is there such an event as session terminate and/or session abandon? If yes, where? What's the best way to detect the logout time of a user from a site by clicking logout, closing the browser, leaving the site, or letting session time expire?
The logout time needs to be logged in a table.
Avatar of samtran0331
samtran0331
Flag of United States of America image

>>The closing of the browser is not trapped by session_end in global.asax, right?
Yes it is, if you're using InProc.
But you still have to wait for the timeout to be reached even if the user closes the browser.
You can put the code to log the user out of the database in the session_end event

If you're using SQLServer or StateServer (instead of the default InProc) for state management, Session_end does *not* fire.
Avatar of ksfok
ksfok

ASKER

Please elaborate in more detail on "If you're using SQLServer or StateServer (instead of the default InProc) for state management, Session_end does *not* fire." What's SQLServer doing here? Can only Session_End be used alone?
A user's session can be maintained 3 ways:
InProc (IIS), StateServer, or SQLServer

The default is InProc.
If you use either of the other 2 methods, the Session_End event in global.asax is ignored and any code inside that event does not get executed.

Here's an article on the 3 different ways to maintain sessions:
http://www.codeproject.com/aspnet/ASPNETSession.asp
Avatar of ksfok

ASKER

OK.
Can Session() be invoked in a class file with logout time sub used in global.asax and other pages? What is the namespace to which Session() belong? I got blue wriggly line under "Session" in the class code below :

    Public Sub UserLogoutTime()
        Dim queryString As String = _
"UPDATE UserLoginHistory SET LogoutTime = getdate() WHERE Username='" & ("UserName") & "' AND SessionID='" & Session.SessionID() & "';"
        Using connection As New SqlConnection(ConfigurationManager.ConnectionStrings("LocalSqlServer").ConnectionString)
            Try
                Dim command As New SqlCommand(queryString, connection)
                connection.Open()
                command.ExecuteNonQuery()
            Finally
                connection.Close()
            End Try
        End Using

    End Sub

Avatar of ksfok

ASKER

How can global.asax call sub UserLogoutTime() from AdminSubs.vb (class file)?
the actual filename isn't important...it's the name of the class that is important...so
in "AdminSubs.vb "...if the class begins like this:

public class adminsubs
     public sub userlogouttime
....

then in global.asax, you would:
(at top of page:)
import adminsubs

(in code:)
dim myAdmin as new adminsubs
myAdmin.userlogouttime


if you don't want to dim a new instance of the class, you need to make it a public shared function; then you can skip the declaration...
>>I got blue wriggly line under "Session" in the class code below :
well...quickest way would be to change your sub to accept one param:

 Public Sub UserLogoutTime(byval theSessionID as string)
        Dim queryString As String = _
"UPDATE UserLoginHistory SET LogoutTime = getdate() WHERE Username='" & ("UserName") & "' AND SessionID='" & theSessionID & "';"
        Using connection As New SqlConnection(ConfigurationManager.ConnectionStrings("LocalSqlServer").ConnectionString)
            Try
                Dim command As New SqlCommand(queryString, connection)
                connection.Open()
                command.ExecuteNonQuery()
            Finally
                connection.Close()
            End Try
        End Using

    End Sub

and then in global.asax:
dim myAdmin as new adminsubs
myAdmin.userlogouttime(session.sessionid)
Avatar of ksfok

ASKER

Is it possible that when Sub Session_End fires any session variable filled previously will have a value =  nothing? I tested with a session variable that captures a user's name upon login. That session variable is found to be nothing in Sub Session_End.  Please advise a more reliable way to record a user's departure time.
How are you testing?

I'm using this exact same logic to log users out of a db to maintain licensing, my function to delete the users session from the db is in session_end and accepts a session variable as a parameter and the user gets logged out of the db as expected...
Avatar of ksfok

ASKER

I  tested with Sub Session_End in which sub UserLogoutTime() is called but so far not a single time the user logout time is updated. Seems the only thing that works is user clicking logout button but not closing the browser, leaving the site, or letting session time expire?
can you post the relevant code?
session_end works fine for me to log a user out of the database...
this is a working session end from my app:

    Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)
        If CStr(Session("ConnString")) <> "" Or CStr(Session("UserCode")) <> "" Then
            Dim oSecurity As cSecurity = New cSecurity(CStr(Session("ConnString")))
            If oSecurity.LogOut(CStr(Session("UserCode"))) = True Then
                Session("EmployeeName") = ""
                Session("UserCode") = ""
                Session("EmpCode") = ""
                Session("ConnString") = ""
                Session("admin") = False
                Session("TaskCalAccess") = False
                Session.Clear()
                Session.Abandon()
                FormsAuthentication.SignOut()

            End If
        End If

    End Sub

and here's my logout function in my cSecurity class:
    Public Function LogOut(ByVal UserID As String) As Boolean

        ' Add Parameters to SPROC
        Dim parameterUserID As New SqlParameter("@UserID", SqlDbType.VarChar, 100)
        parameterUserID.Value = UserID

        Try
            oSql.ExecuteNonQuery(mConnString, CommandType.StoredProcedure, "usp_wv_User_Logout", parameterUserID)
        Catch
            Return False
        End Try

        Return True

    End Function
Avatar of ksfok

ASKER

I tested and found UserLogoutTime() works OK with a Logout button click event, but somehow doesn't get called in Session_End() of global.asax. Here's my code:

   Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)
        ' Code that runs when a session ends.
        ' Note: The Session_End event is raised only when the sessionstate mode
        ' is set to InProc in the Web.config file. If session mode is set to StateServer
        ' or SQLServer, the event is not raised.
       
        Dim adc As New AdminClass
        adc.UserLogoutTime()
       
    End Sub

=================================================
Imports Microsoft.VisualBasic
Imports System.Data.SqlClient
Imports System.Web.HttpContext


Public Class AdminClass

    Public Sub New()
    End Sub

    Public Sub UserLogoutTime()
        Dim queryString As String = _
"UPDATE UserLoginHistory SET LogoutTime = getdate() WHERE Username='" & Current.Session("UserName") & "' AND SessionID='" & Current.Session.SessionID() & "';"
        Using connection As New SqlConnection(ConfigurationManager.ConnectionStrings("LocalSqlServer").ConnectionString)
            Try
                Dim command As New SqlCommand(queryString, connection)
                connection.Open()
                command.ExecuteNonQuery()
            Finally
                connection.Close()
            End Try
        End Using

    End Sub

End Class
ASKER CERTIFIED SOLUTION
Avatar of samtran0331
samtran0331
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ksfok

ASKER

Would State Server Mode or SQL Server Mode be better alternatives?
Avatar of ksfok

ASKER

samtran0331,
I tested your code with leaving site and letting time out. It works! Thanks! I haven't tested with closing browser yet because I'm working on localhost. When I close the browser, the app stops. By the way, can  I set cookieless="false" in <sessionState mode="InProc"  cookieless="true"  timeout="20" />? What would be the impact of cookie on the site if we want to have sessionState mode="InProc"  and users want to use cookie to remember their credentials?