Using the Session_End event in the Global.asax file.
You need to set the Inproc mode in the sessionState so that we can make use of Session_End event. For testing purpose i have set 1 min as the Session timeout time.
SQL
CREATE TABLE [dbo].[UserSessionEndTime](
[UserId] [int] NOT NULL,
[TimeOutTime] [datetime] NULL
) ON [PRIMARY]
GO
Web.config
<system.web>
<sessionState mode="InProc" timeout="1"/>
<compilation debug="true" targetFramework="4.0"/>
</system.web>
At the login page Set the Session with the User's Id. Here its in integer format.
C#
protected void Login(object sender, EventArgs e)
{
// Write some code to authenticate the user.
// Set the Id of User’s table in Session.
//It’s for testing purpose i have set it to 1.
Session["UserName"] = 1;
}
Global.asax
<%@ Application Language="C#" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<script RunAt="server">
void Session_End(object sender, EventArgs e)
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
string sqlStatment = "INSERT INTO UserSessionEndTime VALUES(@UserId,@TimeOutTime)";
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(sqlStatment, con))
{
con.Open();
cmd.Parameters.AddWithValue("@UserId", Convert.ToInt32(Session["UserName"]));
cmd.Parameters.AddWithValue("@TimeOutTime", DateTime.Now);
cmd.ExecuteNonQuery();
con.Close();
}
}
}
</script>
VB.Net
Protected Sub Login(ByVal sender As Object, ByVal e As EventArgs)
' Write some code to authenticate the user.
' Set the Id of User’s table in Session.
' It’s for testing purpose i have set it to 1.
Session("UserName") = 1
End Sub
Global.asax
<%@ Application Language="VB" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<script runat="server">
Private Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Dim sqlStatment As String = "INSERT INTO UserSessionEndTime VALUES(@UserId,@TimeOutTime)"
Using con As SqlConnection = New SqlConnection(constr)
Using cmd As SqlCommand = New SqlCommand(sqlStatment, con)
con.Open()
cmd.Parameters.AddWithValue("@UserId", Convert.ToInt32(Session("UserName")))
cmd.Parameters.AddWithValue("@TimeOutTime", DateTime.Now)
cmd.ExecuteNonQuery()
con.Close()
End Using
End Using
End Sub
</script>