views:

7

answers:

1

I require all changes such as inserts, updates and deletes to a table to be auditted, and I'm using a simple SQLDataSource and GridView with automagically generated INSERT/UPDATE/DELETE statements. Problem is, when a row is updated I want to get the ID (primary key) and put that into the auditting table - but because the only parameters for the UPDATE query is the actual data and not the primary key, I don't know how to access this information. Here is my UPDATE query:

InsertCommand="INSERT INTO [NominalCode] ([VAXCode], [Reference], [CostCentre], [Department], [ReportingCategory]) VALUES (@VAXCode, @Reference, @CostCentre, @Department, @ReportingCategory)" 

And here is the codebehind for auditting:

protected void SqlDataSource1_Updating(object sender, SqlDataSourceCommandEventArgs e)
    {
        string fields = e.Command.Parameters[0].Value.ToString() + "," + e.Command.Parameters[1].Value.ToString() + "," + e.Command.Parameters[2].Value.ToString() + "," + e.Command.Parameters[3].Value.ToString() + "," + e.Command.Parameters[4].Value.ToString();
        System.Security.Principal.  WindowsPrincipal p = System.Threading.Thread.CurrentPrincipal as System.Security.Principal.WindowsPrincipal;
        string[] namearray = p.Identity.Name.Split('\\');
        string name = namearray[1];
        string queryString = "INSERT INTO Audit (source, action, item, userid, timestamp) VALUES (@source, @action, @item, @userid, @timestamp)";
        using (SqlConnection connection = new SqlConnection("con string removed for privacy"))
        {
            SqlCommand command = new SqlCommand(queryString, connection);
            command.Parameters.AddWithValue("@source", "Nominal");
            command.Parameters.AddWithValue("@action", "Update");
            command.Parameters.AddWithValue("@item", fields);
            command.Parameters.AddWithValue("@userid", name);
            command.Parameters.AddWithValue("@timestamp", DateTime.Now);
            connection.Open();
            try
            {
                command.ExecuteNonQuery();
            }
            catch (Exception x)
            {
                Response.Write(x);
            }
            finally
            {
                connection.Close();
            }
        }
    }
A: 

Okay, I feel stupid. The ID was located in the WHERE clause of the SQL query of course! And I pasted in the INSERT command for some reason.

Chris