Wednesday, September 14, 2011

Track User status if user closes the browser window.

This is a sample application of "User Status" tracking in asp.net. When the user is logged in. This will show the user status as online user. If the user click on logout then it automatically logout user and update the user status as off line. But what if the user closes the browser then also you can track the status.
Here in this example I have used SQL server as database. I have created a table [tbluserlogins] in database with a "userstatus" column as bit datatype. Every time I update the "userstatus" when user logged in and logged out.

Sample Table Structure
CREATE TABLE [dbo].[tblUserLogins](
 [sno] [int] IDENTITY(1,1) NOT NULL,
 [username] [nvarchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
 [password] [nvarchar](20) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
 [userStatus] [bit] NOT NULL,
 [lastLogin] [datetime] NOT NULL CONSTRAINT [DF_tblUserLogins_lastLogin]  DEFAULT (getdate()),
 CONSTRAINT [PK_tblUserLogins] PRIMARY KEY CLUSTERED 
(
 [username] ASC
)WITH (PAD_INDEX  = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
1. We have to maintain the session state like this
2. In global.asax there we can update the status.
void Application_End(object sender, EventArgs e)
    {
        //  Code that runs on application shutdown
        //Update the user status if the application is closed

        try
        {
            SqlHelper.ExecuteNonQuery(SqlHelper.mainConnectionString, System.Data.CommandType.Text, "update tblUserLogins set userStatus='false' where sno=" + Session["userid"].ToString(), null);
        }
        catch (Exception ex)
        {

            throw ex;
        }


    }


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.
        //If the user close the browser window or session is end. It will automatically update the staus
        try
        {
            SqlHelper.ExecuteNonQuery(SqlHelper.mainConnectionString, System.Data.CommandType.Text, "update tblUserLogins set userStatus='false' where sno=" + Session["userid"].ToString(), null);
        }
        catch (Exception ex)
        {

            throw ex;
        }

    }


Download the sample code