auditlog in asp.net mvc

 Auditlog in asp.net mvc

Audit log is the most important part of  a web application. In this article we will create log for user.

The article contains
  1. Create Table
  2. Store Procedure
  3. Userlog Service
  4. Implementation in controller
auditlog

Table

CREATE TABLE UserLog(
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[UserId] [nvarchar](128) NOT NULL,
	[UserName] [nvarchar](50) NOT NULL,
	[LoginDate] [datetime] NOT NULL,
	[LogoutDate] [datetime] NULL,
	[IpAddress] [nvarchar](50) NOT NULL
)

Store Procedure

CREATE PROCEDURE  usp_InsertUserlogs
(
   @UserId nvarchar(50),
   @Username nvarchar(50),
   @LoginDate datetime,
   @LogoutDate datetime NULL,
   @isLogout bit NULL,
   @logId int = 0,
   @Ipaddress nvarchar(50)
)
AS
BEGIN
 
	if @isLogout IS NOT NULL and @isLogout = 1 and @logId > 0
	BEGIN
	SET NOCOUNT ON;

		UPDATE UserLogs
		SET LogoutDate = @LogoutDate
		WHERE ID = @logId

		    Select returnId = @logId;

	END
	ELSE
	BEGIN
	SET NOCOUNT ON;
          INSERT INTO [dbo].[UserLogs] ([UserId],[UserName],[LoginDate],[IpAddress])

          VALUES (@UserId,@Username,@LoginDate,@Ipaddress)

		    Select returnId = SCOPE_IDENTITY();
	END
END

Userlog Service

public class UserLog
    {
        public int InsertUserLogs(UserLogs UserLogs)
        {
            int result = 0;
            try
            {
                if (UserLogs.IpAddress != "::1" && UserLogs.UserName != "superadmin")
                {
                    using (var dbo = new Data.InventoryDevEntities())
                    {
                        var objectContext = ((IObjectContextAdapter)dbo).ObjectContext;

                        var command = dbo.Database.Connection.CreateCommand();
                        command.CommandType = System.Data.CommandType.StoredProcedure;
                        command.CommandText = "sp_InsertUserlogs";

                        SqlParameter param_UserId = new SqlParameter("@UserId", SqlDbType.NVarChar);
                        param_UserId.Direction = ParameterDirection.Input;
                        param_UserId.Value = UserLogs.UserId;
                        command.Parameters.Add(param_UserId);

                        SqlParameter param_Username = new SqlParameter("@Username", SqlDbType.NVarChar);
                        param_Username.Direction = ParameterDirection.Input;
                        param_Username.Value = UserLogs.UserName;
                        command.Parameters.Add(param_Username);

                        SqlParameter param_LoginDate = new SqlParameter("@LoginDate", SqlDbType.DateTime);
                        param_LoginDate.Direction = ParameterDirection.Input;
                        param_LoginDate.Value = DateTime.Now;
                        command.Parameters.Add(param_LoginDate);

                        SqlParameter param_LogoutDate = new SqlParameter("@LogoutDate", SqlDbType.DateTime);
                        param_LogoutDate.Direction = ParameterDirection.Input;
                        param_LogoutDate.Value = DateTime.Now;
                        command.Parameters.Add(param_LogoutDate);

                        SqlParameter param_isLogout = new SqlParameter("@isLogout", SqlDbType.Bit);
                        param_isLogout.Direction = ParameterDirection.Input;
                        param_isLogout.Value = UserLogs.isLogout;
                        command.Parameters.Add(param_isLogout);

                        SqlParameter param_logId = new SqlParameter("@logId", SqlDbType.Int);
                        param_logId.Direction = ParameterDirection.Input;
                        param_logId.Value = UserLogs.LogId;
                        command.Parameters.Add(param_logId);

                        SqlParameter param_Ipaddress = new SqlParameter("@Ipaddress", SqlDbType.NVarChar);
                        param_Ipaddress.Direction = ParameterDirection.Input;
                        param_Ipaddress.Value = UserLogs.IpAddress;
                        command.Parameters.Add(param_Ipaddress);

                        dbo.Database.Connection.Open();

                        result = Convert.ToInt32(command.ExecuteScalar());

                        // Check Error

                        dbo.Database.Connection.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                return result;
            }
            return result;
        }

}

Controller

public class HomeController : Controller
{
        private UserLog Obj = new UserLog();
		
       [Authorize(Roles = "Admin,SuperAdmin,DefaultAdmin")]
        public ActionResult Index()
        {
            ViewBag.RecordsPerPage = 20;
	var UserName = HttpContext.User.Identity.Name;
            HttpContext.Current.Session["UserName"] = UserName;
	string userRoleName = (string)HttpContext.Current.Session["UserRoleName"];

            if (User.IsInRole("Admin"))
            {
                userRoleName = "Admin";
                AddSessionUserlogs();
            }          

            return View();
        }
		
private void AddSessionUserlogs(bool isLogOut = false)
{
            string ipaddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (ipaddress == "" || ipaddress == null)
                ipaddress = Request.ServerVariables["REMOTE_ADDR"];

            var UserName = HttpContext.User.Identity.Name;

            HttpContext.Current.Session["UserName"] = UserName;

            Userlogmodel.UserName = UserName;

            Userlogmodel.UserId = HttpContext.User.Identity.GetUserId();

            if (isLogOut)
            {
                Userlogmodel.isLogout = true;
                if (HttpContext.Current.Session["LogID"] > 0)
                {
                    Userlogmodel.LogId = HttpContext.Current.Session["LogID"];
} } Userlogmodel.IpAddress = ipaddress; int logID = Obj.InsertUserLogs(Userlogmodel); if (logID > 0) { HttpContext.Current.Session["LogID"] = logID; } } }

Post a Comment

0 Comments