Track User Activity While Performing CRUD Operation in Database Using Trigger

Introduction

This article explains how to track user activity while doing CRUD operations in a database using triggers. In this application I will track which user does which action on the following table. For doing this I am passing a user name to trigger but in a real scenario it is not possible to pass front-end data to a normal trigger.

In this article I am creating a simple student table of the following structure:

  1. CREATE TABLE [dbo].[tblStudentInfo](  
  2. [Sid] [int] IDENTITY(1,1) NOT NULL,  
  3. [sName] [varchar](50) NOT NULL,  
  4. [sAdd] [varchar](50) NOT NULL,  
  5. [emailId] [varchar](50) NOT NULL,  
  6. [sRollNo] [varchar](50) NOT NULL,  
  7. CONSTRAINT [PK_tblStudentInfo] PRIMARY KEY CLUSTERED   
  8. (  
  9. [Sid] ASC  
  10. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF
  11. IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  12. ON [PRIMARY]  
We do a simple CRUD operation in this table and I also create another table to track the user activity on this table.
  1. CREATE TABLE [dbo].[TriggerData](  
  2. [RollNo] [varchar](50) NULL,  
  3. [InsertedDate] [datetime] NULL,  
  4. [Command] [varchar](maxNOT NULL,  
  5. [InsertedBy] [nvarchar](256) NULL,  
  6. [Action] [varchar](50) NULL  
  7. ON [PRIMARY]  
Now I have taken a blank ASP.NET webpage and design that page using the following HTML and ASP code.
  1. <table id="tblUser" class="auto-style1" runat="server">  
  2. <tr>  
  3. <td>Enter User Name  </td>  
  4. <td>  
  5. <asp:TextBox ID="txtuserName" runat="server"></asp:TextBox>  
  6. </td>  
  7. <td>  
  8. <asp:Button ID="btnContinue" runat="server" OnClick="btnContinue_Click" Text="Continue" /></td>  
  9. </tr>  
  10. </table>  
  11. <table id="StudentTbl" class="auto-style1" runat="server" visible="false">  
  12. <tr>  
  13. <td colspan="4">  
  14. <center>  
  15. <h2>  
  16. Student Information Entry</h2>  
  17. </center>  
  18. </td>  
  19. </tr>  
  20. <tr>  
  21. <td colspan="2">Student Roll Number  
  22. </td>  
  23. <td>  
  24. <asp:TextBox ID="txtRollNo" runat="server"></asp:TextBox>  
  25. <asp:Label ID="libid" runat="server" Visible="False"></asp:Label>  
  26. <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"  
  27. ControlToValidate="txtRollNo" ErrorMessage="*" ForeColor="Red"></asp:RequiredFieldValidator>  
  28. <br />  
  29. </td>  
  30. <td rowspan="6">  
  31. <asp:GridView ID="gvStudent" runat="server" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" 
  32. BackColor="White" BorderColor="#336666" BorderStyle="Double" BorderWidth="3px" CellPadding="4" 
  33. GridLines="Horizontal" AutoGenerateColumns="False">  
  34. <Columns>  
  35. <asp:ButtonField ButtonType="Button" CommandName="Select" Text="Select" HeaderText="Select" />  
  36. <asp:BoundField DataField="Sid" HeaderText="Id" />  
  37. <asp:BoundField DataField="sRollNo" HeaderText="Roll No" />  
  38. <asp:BoundField DataField="sName" HeaderText="Name" />  
  39. <asp:BoundField DataField="sAdd" HeaderText="Address" />  
  40. <asp:BoundField DataField="emailId" HeaderText="EmailId" />  
  41. </Columns>  
  42. <FooterStyle BackColor="White" ForeColor="#333333" />  
  43. <HeaderStyle BackColor="#336666" Font-Bold="True" ForeColor="White" />  
  44. <PagerStyle BackColor="#336666" ForeColor="White" HorizontalAlign="Center" />  
  45. <RowStyle BackColor="White" ForeColor="#333333" />  
  46. <SelectedRowStyle BackColor="#339966" Font-Bold="True" ForeColor="White" />  
  47. <SortedAscendingCellStyle BackColor="#F7F7F7" />  
  48. <SortedAscendingHeaderStyle BackColor="#487575" />  
  49. <SortedDescendingCellStyle BackColor="#E5E5E5" />  
  50. <SortedDescendingHeaderStyle BackColor="#275353" />  
  51. </asp:GridView>  
  52. </td>  
  53. </tr>  
  54. <tr>  
  55. <td colspan="2">Student Name  
  56. </td>  
  57. <td>  
  58. <asp:TextBox ID="txtSName" runat="server"></asp:TextBox>  
  59. <br />  
  60. </td>  
  61. </tr>  
  62. <tr>  
  63. <td colspan="2">Student Address  
  64. </td>  
  65. <td>  
  66. <asp:TextBox ID="txtSAdd" runat="server"></asp:TextBox>  
  67. <br />  
  68. </td>  
  69. </tr>  
  70. <tr>  
  71. <td colspan="2">Student Email Id  
  72. </td>  
  73. <td>  
  74. <asp:TextBox ID="txtSEId" runat="server"></asp:TextBox>  
  75. <br />  
  76. </td>  
  77. </tr>  
  78. <tr>  
  79. <td colspan="2">   
  80. </td>  
  81. <td>  
  82. <asp:Label ID="libmsg" runat="server" Visible="False"></asp:Label>  
  83. </td>  
  84. </tr>  
  85. <tr>  
  86. <td>  
  87. <asp:Button ID="btnInsert" runat="server" OnClick="btnInsert_Click" Text="Insert" Style="height: 26px" />  
  88. </td>  
  89. <td class="auto-style2">  
  90. <asp:Button ID="btnUpdate" runat="server" Text="Update" OnClick="btnUpdate_Click" />  
  91. </td>  
  92. <td>  
  93. <asp:Button ID="btnDelete" runat="server" Text="Delete" OnClick="btnDelete_Click" />  
  94.    
  95. </td>  
  96. </tr>  
  97. </table>  
  98. <table id="triggerAction" class="auto-style2" runat="server" visible="false">  
  99. <tr>  
  100. <td>  
  101. <center><h2>Action List By <asp:Label ID="lbluser" runat="server"></asp:Label></h2></center>  
  102. </td>  
  103. </tr>  
  104. <tr>  
  105. <td>  
  106. <asp:GridView ID="gvTriggerAction" runat="server" BackColor="White" BorderColor="#336666" 
  107. BorderStyle="Double" BorderWidth="3px" CellPadding="4" GridLines="Horizontal" AutoGenerateColumns="False">  
  108. <Columns>  
  109. <asp:BoundField DataField="RollNo" HeaderText="Roll No" />  
  110. <asp:BoundField DataField="Command" HeaderText="Command" />  
  111. <asp:BoundField DataField="Action" HeaderText="Action" />  
  112. <asp:BoundField DataField="InsertedDate" DataFormatString="{0:dd-MMM-yyyy}" HeaderText="Date" />  
  113. </Columns>  
  114. <FooterStyle BackColor="White" ForeColor="#333333" />  
  115. <HeaderStyle BackColor="#336666" Font-Bold="True" ForeColor="White" />  
  116. <PagerStyle BackColor="#336666" ForeColor="White" HorizontalAlign="Center" />  
  117. <RowStyle BackColor="White" ForeColor="#333333" />  
  118. <SelectedRowStyle BackColor="#339966" Font-Bold="True" ForeColor="White" />  
  119. <SortedAscendingCellStyle BackColor="#F7F7F7" />  
  120. <SortedAscendingHeaderStyle BackColor="#487575" />  
  121. <SortedDescendingCellStyle BackColor="#E5E5E5" />  
  122. <SortedDescendingHeaderStyle BackColor="#275353" />  
  123. </asp:GridView>  
  124. </td>  
  125. </tr>  
  126. </table>  
The page will look like:

student information Entry

Now by using the following 3 functions I simply do the CRUD operations with the database table studentInfo. 
  1. Insert Student Record
    1. void AddRecordToDb()  
    2. {  
    3.       SqlConnection con = new SqlConnection( 
    4.                            System.Configuration
    5.                            .ConfigurationManager
    6.                            .ConnectionStrings["DbCS"]
    7.                            .ConnectionString
    8.                            );  
    9.       SqlCommand cmd = new SqlCommand();  
    10.       con.Open();  
    11.       SetContext(con, txtuserName.Text.Trim());  
    12.       try  
    13.       {  
    14.             cmd.CommandText = "insert into tblStudentInfo (sName,sAdd,emailId,sRollNo)" +  
    15.             "values (@sName,@sAdd,@emailId,@sRollNo); SELECT SCOPE_IDENTITY();";  
    16.             cmd.Connection = con;  
    17.             cmd.Parameters.AddWithValue("@sName", txtSName.Text);  
    18.             cmd.Parameters.AddWithValue("@sAdd", txtSAdd.Text);  
    19.             cmd.Parameters.AddWithValue("@emailId", txtSEId.Text);  
    20.             cmd.Parameters.AddWithValue("@sRollNo", txtRollNo.Text);  
    21.             int id = Convert.ToInt32(cmd.ExecuteScalar());  
    22.             libmsg.Visible = true;  
    23.             libmsg.Text = "Record Inserted At Positon " + id.ToString() + ".";  
    24.       }  
    25.       catch  
    26.       {  
    27.             libmsg.Visible = true;  
    28.             libmsg.Text = "Error..";  
    29.       }  
    30.   
    31. }  
  2. Update Student Record
    1. void UpdateRecordToDb()  
    2. {  
    3.       SqlConnection con = new SqlConnection( 
    4.                           System.Configuration
    5.                           .ConfigurationManager
    6.                            .ConnectionStrings["DbCS"]
    7.                            .ConnectionString
    8.                            );  
    9.       SqlCommand cmd = new SqlCommand();  
    10.       con.Open();  
    11.       SetContext(con, txtuserName.Text.Trim());  
    12.       cmd.CommandText = "UPDATE tblStudentInfo SET sName = @sName, sAdd = @sAdd ," + "emailId = @emailId , sRollNo = @sRollNo WHERE       Sid = @Sid ";  
    13.       cmd.Connection = con;  
    14.       int sid = Convert.ToInt32(libid.Text);  
    15.       string sname = txtSName.Text;  
    16.       string sadd = txtSAdd.Text;  
    17.       string seid = txtSEId.Text;  
    18.       string rol = txtRollNo.Text;  
    19.       cmd.Parameters.AddWithValue("@Sid", sid);  
    20.       cmd.Parameters.AddWithValue("@sName", sname);  
    21.       cmd.Parameters.AddWithValue("@sAdd", sadd);  
    22.       cmd.Parameters.AddWithValue("@emailId", seid);  
    23.       cmd.Parameters.AddWithValue("@sRollNo", rol);  
    24.       cmd.ExecuteNonQuery();  
    25.   
    26. }  
  3. Delete Student Record 
    1. void DeleteRecordToDb()    
    2. {    
    3.       SqlConnection con = new SqlConnection(
    4.                            System.Configuration.ConfigurationManager
    5.                            .ConnectionStrings["DbCS"].ConnectionString);    
    6.       SqlCommand cmd = new SqlCommand();    
    7.       con.Open();    
    8.       SetContext(con, txtuserName.Text.Trim());    
    9.       cmd.CommandText = "DELETE FROM tblStudentInfo WHERE Sid = @Sid ";    
    10.       cmd.Connection = con;    
    11.       int sid = Convert.ToInt32(libid.Text);    
    12.       cmd.Parameters.AddWithValue("@Sid", sid);    
    13.       cmd.ExecuteNonQuery();    
    14. }   

When all the three functions have been created, call those functions from their respective button click events.

Now as I told earlier it is not possible to directly send data to trigger from our front end. So for doing that I am seting a value to the context and writting a Stored Procedure to read that context and make that context available for the trigger.

Stored Procedure

  1. Create PROCEDURE [dbo].[sp_set_context]  
  2. @username nvarchar(256)  
  3. AS  
  4. BEGIN  
  5. -- SET NOCOUNT ON added to prevent extra result sets from  
  6. -- interfering with SELECT statements.  
  7. SET NOCOUNT ON;  
  8. declare @Ctx varbinary(128)   
  9. select @Ctx = convert(varbinary(128), @username)  
  10. set context_info @Ctx  
  11. END 
Now I will use the preceding Stored Procedure to pass a data context value to SQL Server. For that I create the following function and call that function before every CRUD operation.
  1. protected virtual void SetContext(IDbConnection conn, string UserName)  
  2. {  
  3.       string currentUserName = UserName;  
  4.       string spName = "sp_set_context";  
  5.       if (conn != null)  
  6.       {  
  7.             if (conn.State != ConnectionState.Open)  
  8.             conn.Open();  
  9.             IDbCommand cmd = conn.CreateCommand();  
  10.             cmd.CommandType = CommandType.StoredProcedure;  
  11.             cmd.CommandText = spName;  
  12.             IDbDataParameter param = cmd.CreateParameter();  
  13.             param.ParameterName = "@username";  
  14.             param.DbType = DbType.String;  
  15.             param.Size = 255;  
  16.             param.Value = currentUserName;  
  17.             cmd.Parameters.Add(param);  
  18.             cmd.ExecuteNonQuery();  
  19.       }  
  20. }  
IDbConnection conn

conn: pass the connection object while calling that function with username.

Before every CRUD operation I am calling this function and setting the user name to the context of SQL Server.

Now I will create three separate triggers to do insert, update and delete actions and that trigger will read the context value with a user action and store that user name and that action done by the user in another table. 
  1. After Insert Trigger
    1. Create TRIGGER [dbo].[TrackStudentInfo]  
    2. ON [dbo].[tblStudentInfo]  
    3. AFTER INSERT  
    4. AS   
    5. BEGIN  
    6. DECLARE @id uniqueidentifier;  
    7. Declare @sName varchar(50);  
    8. Declare @sAdd varchar(50);  
    9. Declare @emailId varchar(50);  
    10. Declare @RollNo varchar(50);  
    11. Declare @Sid varbinary(128);  
    12. Declare @InsertedBy nvarchar(256);  
    13. Declare @Command varchar(max);  
    14.   
    15. SELECT @InsertedBy = convert(nvarchar(256), CONTEXT_INFO());   
    16. select @RollNo=i.sRollNo from inserted i;   
    17. select @sName=i.sName from inserted i;  
    18. select @sAdd=i.sAdd from inserted i;  
    19. select @emailId=i.emailId from inserted i;  
    20.   
    21. select @Command='INSERT INTO [TrakingInfoDb].[dbo].[tblStudentInfo]([sName],[sAdd],[emailId],[sRollNo]) VALUES('''  
    22. + @sName+ ''','''+@sAdd+''','''+@emailId+''','''+@RollNo+''');';  
    23.   
    24. DECLARE @data datetime;  
    25. select @data =getdate();   
    26. Insert TriggerData values(@RollNo,@data,@Command,@InsertedBy,'Insert')  
    27.   
    28. END  
  2. After Update Trigger
    1. CREATE TRIGGER [dbo].[trgAfterUpdate] ON [dbo].[tblStudentInfo]   
    2. FOR UPDATE  
    3. AS  
    4. BEGIN  
    5. DECLARE @id uniqueidentifier;  
    6. Declare @sName varchar(50);  
    7. Declare @sAdd varchar(50);  
    8. Declare @emailId varchar(50);  
    9. Declare @RollNo varchar(50);  
    10. Declare @Sid int;  
    11. Declare @InsertedBy nvarchar(256);  
    12. Declare @Command varchar(max);  
    13.   
    14. SELECT @InsertedBy = convert(nvarchar(256), CONTEXT_INFO());   
    15. select @RollNo=i.sRollNo from inserted i;   
    16. select @sName=i.sName from inserted i;  
    17. select @sAdd=i.sAdd from inserted i;  
    18. select @emailId=i.emailId from inserted i;  
    19. select @Sid=i.[Sid] from inserted i;  
    20.   
    21. select @Command='UPDATE [TrakingInfoDb].[dbo].[tblStudentInfo] SET [sName]='''  
    22. + @sName+ ''',[sAdd]='''+@sAdd+''',[emailId]='''  
    23. +@emailId+''',[sRollNo]='''+@RollNo  
    24. +'''WHERE [Sid]='''+cast(@Sid as varchar(20))+''');';   
    25. DECLARE @data datetime;  
    26. select @data =getdate();   
    27. Insert TriggerData values(@RollNo,@data,@Command,@InsertedBy,'After Update')  
    28.   
    29. END  
  3. After Delete Trigger
    1. ALTER TRIGGER [dbo].[trgAfterDelete] ON [dbo].[tblStudentInfo]  
    2. AFTER DELETE  
    3. AS  
    4. BEGIN   
    5. Declare @RollNo varchar(50);  
    6. Declare @Sid int;  
    7. Declare @InsertedBy nvarchar(256);  
    8. Declare @Command varchar(max);   
    9.   
    10. select @RollNo=d.sRollNo from deleted d;   
    11. select @Sid=d.[Sid] from deleted d;  
    12. SELECT @InsertedBy = convert(nvarchar(256), CONTEXT_INFO());  
    13. select @Command='DELETE FROM [TrakingInfoDb].[dbo].[tblStudentInfo]'  
    14. +' WHERE [Sid]='''+cast(@Sid as varchar(20))+''';';   
    15. DECLARE @data datetime;  
    16. select @data =getdate();   
    17. Insert TriggerData values(@RollNo,@data,@Command,@InsertedBy,'After Delete')  
    18.   
    19. END  

Once we have done this everything is done; run the web page and you will get output like this:

user name

Enter the user name to do a CRUD operation and click the Continue button.

student information Entry data form

The first grid will show the record in the student info table and all the action down by the user Manish will be listed below in descending order. For organized code please find the attachment.

Summary

This article showed how to track user information using a trigger. Please post your feedback, question, or comments about this article.

Up Next
    Ebook Download
    View all
    Learn
    View all