Track LastLogin of WebSite Visitor


Introduction

Some website admin needs to track user’s last login date and time. There may be many concepts for this like updating database through lading page or user’s profile page even any other page where user lands first.

Even I have used couple of ways for this but finally come time mechanism. Maybe this is not too good but best for me.

If we write some code in code-behind for this, then query will execute each time user comes or say navigates website, this will increase the site execution time. So, what’s now? Let’s take a look at my one.

Sample Database

Look at the sample database table named ‘users’ having user account details like username, password, joining_date, last_login_date etc.


Follow the steps:-

Step 1

Add a Global.asax File in your web project.

Step 2

Add following namespaces in Global.asax.

<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.Data" %>

Step 3

Place the following code in ‘Session_Start()’ event.

using (SqlConnection connection = new SqlConnection(GetConnectionString()))
        {
            string dateandtime = DateTime.Now.ToString();
            string loggedusername = HttpContext.Current.User.Identity.Name;
            string sql = "UPDATE users SET last_login_date=@dateandtime WHERE username=@loggedusername";
            connection.Open();
            SqlCommand cmd = new SqlCommand(sql, connection);
            SqlParameter[] pram = new SqlParameter[2];
            pram[0] = new SqlParameter("@dateandtime", SqlDbType.VarChar, 49);
            pram[1] = new SqlParameter("@loggedusername", SqlDbType.VarChar, 49);
            
            pram[0].Value = dateandtime;
            pram[1].Value = loggedusername;
            for (int i = 0; i < pram.Length; i++)
            {
                cmd.Parameters.Add(pram[i]);
            }
            cmd.ExecuteNonQuery();
        }

Step 4

Define the ‘GetConnectionString()’ function.

public string GetConnectionString()
    {
        return System.Configuration.ConfigurationManager.ConnectionStrings["ConnStrName"].ConnectionString;
    }
That's all about the update sample last login date and time of user in database without effecting speed of website.

Comments

Popular posts from this blog

Customize User's Profile in ASP.NET Identity System

Lambda two tables and three tables inner join code samples