Friday, 19 July 2013

 Many time developer find difficult to handle session on browser close event .
 Today i will explain you the easiest way to handle session on browser close event in asp.net

Please Read..

Code to handle application events (such as the start and end of an application) resides in Global.asax Such event code cannot reside in the ASP.NET page or web service code itself, since during the start or end of the application, its code has not yet been loaded (or unloaded). Global.asax is also used to declare data that is available across different application requests or across different browser sessions. This process is known as application and session state management.

The Global.asax file is an optional file used to declare and handle application and session-level events and objects for an ASP.NET web site running on an IIS Web Server. The file contains ASP.NET program code, and is the .NET counterpart of the Global.asax file used for ASP. The Global.asax file resides in the IIS virtual root of an ASP.NET application.


FIRST STEP :Add Global.asax file in your project 




After Adding   Global.asax You will see (pagedirective Language="C#" ) and Events.






 Global.asax file does not contain it's .cs file ,for this we have to create it.

Right click on Appcode folder an add new item Class file with extention .asax



SECOND STEP : After adding class file We have to map the .cs file to global.asax and remove it's all event of global.asax.




 


THIRD STEP  : Create Session_Start , Session_End Event  (Global.asax.cs)

 public void Session_End(object sender, EventArgs e)
    {
         //Code that runs when a session ends.
        string logindets = Convert.ToString(Session["LoginDetails"]);
        string[] arrLogindets = logindets.Split(',');
        SqlCommand cmd = new SqlCommand("update table set logouttime=@LogoutTime where       UserNm=@usnm and LoginTime=@loginTime", con);
        cmd.Parameters.AddWithValue("@LogoutTime",DateTime.Now);
        cmd.Parameters.AddWithValue("@usnm",arrLogindets[0]);
        cmd.Parameters.AddWithValue("@loginTime", Convert.ToDateTime(arrLogindets[1]));
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();

    }

  public void Session_Start(object sender, EventArgs e)
    {
        // Code that runs when a session Start.



    }

For debuging purpose set session timeout 1 min in web.config file after 1 min you will see after closing browser session_end event calls.


enjoy.........


1 comment: