Updating last login date time in ASP.NET


While developing your own system (website) having feature to keep track the last visit of users. There are many ways but some of them has demerits. 

Look at my suggestion:-

I recommend you to process such tasks from Global.asax file available in ASP.NET environment. You can place Database Updation tasks in Session_Start() or Session_End() methods. 

Take a look, how to use:-

Add a Global.asax file and add following coding, edit it for your use.

void Session_Start(object sender, EventArgs e) 
    {
        // Updating the last visited date and time
        using (SqlConnection connection = new SqlConnection(GetConnectionString()))
        {
            string dt = DateTime.Now.ToString();
            string loggeduser = HttpContext.Current.User.Identity.Name;
            string sql = "UPDATE users SET last_login_date=@dt WHERE username='abhimanyu'";
            connection.Open();
            SqlCommand cmd = new SqlCommand(sql, connection);

            SqlParameter[] pram = new SqlParameter[2];
            pram[0] = new SqlParameter("@dt", SqlDbType.VarChar, 49);
            pram[1] = new SqlParameter("@loggeduser", SqlDbType.VarChar, 49);
            
            pram[0].Value = dt;
            pram[1].Value = loggeduser;

            for (int i = 0; i < pram.Length; i++)
            {
                cmd.Parameters.Add(pram[i]);
            }
            cmd.ExecuteNonQuery();
        }
    }

public string GetConnectionString()
    {
        return System.Configuration.ConfigurationManager.ConnectionStrings["ConnStrName"].ConnectionString;
    }

Comments

Popular posts from this blog

Migrating database from ASP.NET Identity to ASP.NET Core Identity

Customize User's Profile in ASP.NET Identity System

Lambda two tables and three tables inner join code samples