Wednesday, August 11, 2004 - Posts

How do you create an audit trail of changes made to an object

I have been working on a C# WinForms project which has a requirement of logging to a database, all of the changes made to an object/form to allow the users to produce a report on who/when/what was done within the application.

My question is... What is the best way to do this?

Currently, the way it has been implemented (by another engineer) is, the original data (before any updates) is kept within the object itself as a member variable and then compared with the current data when the object  is saved, logging the differences in each member to the database.

Here is a basic example of how the current implementation works.

1public class MySample
2{
3   public int var1;
4   public string var2;
5 
6   private MySample original;
7 
8   public void Read()
9   {
10     // Open database and populate fields
11 
12     original = new MySample();
13     original.ReadFrom( this );
14   }
15 
16   public void ReadFrom( MySample source )
17   {
18     var1 = source.var1;
19     var2 = source.var2;
20   }
21 
22   public void Write()
23   {
24     if ( original.var1 != var1 )
25     {
26        // Add to list of changed fields
27     }
28 
29     if ( ! original.var2.Equals( var2 ) )
30     {
31       // Add to list of changed fields
32     }
33
34     // Write change log to DB
35 
36     // Update original
37     original.ReadFrom( this );
38 
39     // Write fields to DB (excluding original field)
40   }
41}

This code just feels wrong to me. My first thought to fix this is to implement something utilizing reflection. I am looking for other people's experiences to help me come up with a better way.

The other thing that seems odd to me is, how is it possible to have an instance of MyObject inside itself?

Update: I have updated the sample code to be correct. That is what you get when trying to write something from memory late at night.

First Post

Welcome to my blog, Learning .NET. I will be using this blog to talk about some of the things I have learned and are still learning about developing with .NET using C#.

My name is Christopher Steen, and I am a Lead Software Engineer for company producing solutions for the hospitality and retail industries. 

More to come. Thanks for listening.