Monday, September 14, 2009

ASP.NET - Session time

To record the session time, two variables are initialised in the global application class Global.asax to hold the name of user and time of session.



<%@ Application Language="C#" %>

<script runat="server">

void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup

}

void Application_End(object sender, EventArgs e)
{
// Code that runs on application shutdown

}

void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs

}

void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
Session.Add("Name", null);
Session.Add("Time", null);

}

void Session_End(object sender, EventArgs e)
{
// 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.

}

</script>


Now, in the first page (Default.aspx) which holds the textbox for the user name and the login button, the following code is written for the Click event of the login button. The variable Time in the Session object will store the date and time of the click.



protected void btnLogin_Click(object sender, EventArgs e)
{
Session["Name"] = txtName.Text;
Session["Time"] = DateTime.Now;
Response.Redirect("~/Default2.aspx");

}


In Default2.aspx, the name is displayed in the Form_Load event.
The button for logout will display the Session time.



protected void Page_Load(object sender, EventArgs e)
{
lblInfo.Text = Session["Name"].ToString();
}
protected void btnLogout_Click(object sender, EventArgs e)
{

lblInfo.Text = (DateTime.Now.Subtract(DateTime.Parse( Session["Time"].ToString()) )).Seconds.ToString();
}


Note: This code was written in class and has limitations. It will only display seconds. That is, 1 minute and 5 seconds will display as 5 seconds. I believe there are many ways to solve this problem. Please feel free to share your code.

No comments:

Post a Comment