0

I want to execute a code that will insert in the DB something like "Session expire" to track the users. However, my session timeout is in the Web.config.

<system.web>
    <compilation debug="true" targetFramework="4.0" />
    <sessionState timeout="20" mode="InProc" />
</system.web>
<defaultDocument>
      <files>
        <add value="Login.aspx" />
      </files>
</defaultDocument>

Then I want to execute this code.

 if (HttpContext.Current.Session["usersId"] == null && HttpContext.Current.Session["usersRole"] == null && HttpContext.Current.Session["usersDivision"] == null && HttpContext.Current.Session["notification"] == null)
  {
      string connstr = ConfigurationManager.ConnectionStrings["dbConn"].ConnectionString;
        SqlConnection conn = new SqlConnection(connstr);
        conn.Open();
        SqlCommand cmdlog = new SqlCommand("INSERT INTO Logs (logs_info,logs_date,users_id) VALUES (@info,@date,@id)", conn);
        cmdlog.Parameters.AddWithValue("@info", "User " +sessionName+ " session timed out.");
        cmdlog.Parameters.AddWithValue("@date", DateTime.Now);
        cmdlog.Parameters.AddWithValue("@id", HttpContext.Current.Session["usersId"].ToString());
        cmdlog.ExecuteNonQuery();
        conn.Close();
        HttpContext.Current.Response.Redirect("../Login.aspx");
}

How can I execute that code before the timeout?

Wowie
  • 23
  • 9

1 Answers1

0

You can use the following event in the Global.asax file

void Session_End(Object sender, EventArgs E) {
    // Do processing here
}

However this event will only trigger if the session timeout is reached.

To access the session variables you can use this.Session instead of HttpContext.Current.

Hope it helps.

Wail
  • 137
  • 8
  • Hi, I'm following what you said, but an error said `The type or namespace name 'SqlConnection' could not be found (are you missing a using directive or an assembly reference?)` – Wowie Jul 11 '17 at 03:43
  • This is due to the namespace that is missing. Try [this solution](https://stackoverflow.com/a/29733842/1600909) for that. – Wail Jul 12 '17 at 13:56