Click here to Skip to main content
Click here to Skip to main content

Creating Audit Functionality Using ASP.NET 2.0

By , 8 Jun 2007
 
Sample image

Introduction

This updated article describes how to create an audit tool that tracks and records the changes of any fields with their old and new values using an ASP.NET web page. To see the project in action, you can download the code. However, you must change your connection properties for the database interaction.

Background

When posed with this issue, I found various solutions that range from SQL Server Triggers to more custom solutions that require additional knowledge of web controls. However, my solution has the following benefits:

  • Records and tracks only the changes made to the field or fields that are changed. One solution, for example, used a trigger that would populate the audit changes, but this included ALL fields that were in the UPDATE SQL statement. What this means it that it would populate the Audit table with fields that were also not changed, which filled my audit table exponentially.
  • Plays on events already part of the .NET Framework. In this example, I use key event objects that allow us to record and compare data changes consistently, whether using GridView or DetailsView.
  • Uses existing properties that allow audit tracking to work. There are event properties already nicely built into the .NET Framework that is part of the GridView and DetialsView control. This allows us to see the new values and old values via a returned collection object.

Using the Code

The pattern implementations are the same for both the GridView and DetailsView. It is just a matter of simply passing in the appropriate event object as a parameter. Here is an example of the overload methods for the GridView and DetailsView:

// GridView Method overload
public static void updateFieldAudits(GridViewUpdatedEventArgs e)
{
    foreach (DictionaryEntry newValues in e.NewValues)
    {
        int i = 0;

        string newKeyCol = newValues.Key.ToString();
        foreach (DictionaryEntry oldVals in e.OldValues)
        {
            string oldKeyCol = oldVals.Key.ToString();

            if (oldKeyCol == newKeyCol)
            {
                break;
            }
            i++;
        }
        string oldVal = (string)e.OldValues[i];

        if (newValues.Value != null)
        {
            string newVal = newValues.Value.ToString();

            if (oldVal != newVal)
            {
                MyDBDAL.insertAuditChanges(newKeyCol, oldVal, newVal);
            }
        }
        else
        {
            if (!String.IsNullOrEmpty(oldVal))
            {
                MyDBDAL.insertAuditChanges(newKeyCol, oldVal, "");
            }
        }
    }
}
// DetailsView Method overload
public static void updateFieldAudits(DetailsViewUpdatedEventArgs e)
{
    foreach (DictionaryEntry newValues in e.NewValues)
    {
        int i = 0;

        string newKeyCol = newValues.Key.ToString();
        foreach (DictionaryEntry oldVals in e.OldValues)
        {
            string oldKeyCol = oldVals.Key.ToString();
            if (oldKeyCol == newKeyCol)
            {
                break;
            }
                i++;
            }
            string oldVal = (string)e.OldValues[i];

            if (newValues.Value != null)
            {
                string newVal = newValues.Value.ToString();

                if (oldVal != newVal)
                {
                MyDBDAL.insertAuditChanges(newKeyCol, oldVal, newVal);
            }
        }
        else
        {
            if (!String.IsNullOrEmpty(oldVal))
            {
                MyDBDAL.insertAuditChanges(newKeyCol, oldVal, "");
            }
        }
    }
}

In order to record the changes, the event of interest on the GridView is the RowUpdated method. The example below traps this event and allows you to pass in the GridViewUpdatedEventArgs event object parameter to the updateFieldAudits method.

protected void GridView1_RowUpdated(object sender, 
    GridViewUpdatedEventArgs e)
{
    AuditFields.updateFieldAudits(e);
}

For the DetailsView code-behind, we capture the ItemUpdated event method:

protected void DetailsView1_ItemUpdated(object sender, 
    DetailsViewUpdatedEventArgs e)
{ 
    AuditFields.updateFieldAudits(e);
}

Finally, we have to wire up the web control events for the GridView and DetailsView with the following:

OnRowUpdated="GridView1_RowUpdated" 
OnItemUpdating="DetailsView1_ItemUpdating"

That's it! It is portable for web controls and you can add your own database update functions to record your audit data changes, or create a custom business object.

History

  • 8 January, 2007 -- Original version posted
  • 8 June, 2007 -- Article updated

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

harryteck
Web Developer
United States United States
Member
Harry is a .NET Developer for a major financial institution building web and stand alone applications and class libraries. He also has experience teaching courses on ASP.NET and Microsoft databases. He holds a graduate degree in Information Science.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralSQL AuditingmemberRyanHilton10 Jan '07 - 7:04 
I know you mentioned the SQL triggers and how they placed all of the fields in the audit table. I modified one of those projects with only a few lines of code to compare the old and new values and only update the values that have changed. The only limitation to this is that it will throw an exception if the type is text or image, as these are not support in the "updated" table.
 
Creating a generic audit trigger with SQL 2005 CLR This is the project I based my modifications on. I converted to C#, added a table to capture the hostname, and added the following additional code:
 

if (Context.IsUpdatedColumn(Column.Ordinal))
{
// Begin my code
if (DeletedRow[Column.Ordinal].ToString() == InsertedRow[Column.Ordinal].ToString())
{
// An update was performed but the data did not change
Triggers.EmitDebugMessage("Update occurred but data is the same.");
}
else
{
// End My Code
// An update occurred and data changed

GeneralRe: SQL Auditing Pinmemberharryteck12 Jan '07 - 3:30 
Thanks for that tip Ryan!
 
I did read and also convert the code written by David Ziffer from that article. One thing that I did not mention was that our application also needed to know the logged in user making the change. We ran into some issues with the "dbo" populating as the "PerformedBy" value, since we needed to drill down further as to what userID made the change. We did not want to make separate SQL logins for many users because it would be more difficult to manage when users left or new users needed added. I tried ASP.NET identity impersonation and also tried a domain account in SQL Server, but they didn't provide what we were looking for. So I played on the .NET security membership, which allowed me to drill down to that level while also being able to leverage the .NET framework for auditing as well.
 
--Harry

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130516.1 | Last Updated 8 Jun 2007
Article Copyright 2007 by harryteck
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid