The project I'm working on needs some simple audit logging for when a user changes their email, billing address, etc. The objects we're working with are coming from different sources, one a WCF service, the other a web service.
I've implemented the following method using reflection to find changes to the properties on two different objects. This generates a list of the properties that have differences along with their old and new values.
public static IList GenerateAuditLogMessages(T originalObject, T changedObject)
{
IList list = new List();
string className = string.Concat("[", originalObject.GetType().Name, "] ");
foreach (PropertyInfo property in originalObject.GetType().GetProperties())
{
Type comparable =
property.PropertyType.GetInterface("System.IComparable");
if (comparable != null)
{
string originalPropertyValue =
property.GetValue(originalObject, null) as string;
string newPropertyValue =
property.GetValue(changedObject, null) as string;
if (originalPropertyValue != newPropertyValue)
{
list.Add(string.Concat(className, property.Name,
" changed from '", originalPropertyValue,
"' to '", newPropertyValue, "'"));
}
}
}
return list;
}
I'm looking for System.IComparable because "All numeric types (such as Int32 and Double) implement IComparable, as do String, Char, and DateTime." This seemed the best way to find any property that's not a custom class.
Tapping into the PropertyChanged event that's generated by the WCF or web service proxy code sounded good but doesn't give me enough info for my audit logs (old and new values).
Looking for input as to if there is a better way to do this, thanks!
@Aaronaught, here is some example code that is generating a positive match based on doing object.Equals:
Address address1 = new Address();
address1.StateProvince = new StateProvince();
Address address2 = new Address();
address2.StateProvince = new StateProvince();
IList list = Utility.GenerateAuditLogMessages(address1, address2);
"[Address] StateProvince changed from 'MyAccountService.StateProvince' to 'MyAccountService.StateProvince'"
It's two different instances of the StateProvince class, but the values of the properties are the same (all null in this case). We're not overriding the equals method.
The my way of
Expression
tree compile version. It should faster thanPropertyInfo.GetValue
.This project on codeplex checks nearly any type of property and can be customized as you need.
You might want to look at Microsoft's Testapi It has an object comparison api that does deep comparisons. It might be overkill for you but it could be worth a look.
IComparable
is for ordering comparisons. Either useIEquatable
instead, or just use the staticSystem.Object.Equals
method. The latter has the benefit of also working if the object is not a primitive type but still defines its own equality comparison by overridingEquals
.This obviously isn't perfect, but if you're only doing it with classes that you control, then you can make sure it always works for your particular needs.
There are other methods to compare objects (such as checksums, serialization, etc.) but this is probably the most reliable if the classes don't consistently implement
IPropertyChanged
and you want to actually know the differences.Update for new example code:
The reason that using
object.Equals
in your audit method results in a "hit" is because the instances are actually not equal!Sure, the
StateProvince
may be empty in both cases, butaddress1
andaddress2
still have non-null values for theStateProvince
property and each instance is different. Therefore,address1
andaddress2
have different properties.Let's flip this around, take this code as an example:
Should these be considered equal? Well, they will be, using your method, because
StateProvince
does not implementIComparable
. That's the only reason why your method reported that the two objects were the same in the original case. Since theStateProvince
class does not implementIComparable
, the tracker just skips that property entirely. But these two addresses are clearly not equal!This is why I originally suggested using
object.Equals
, because then you can override it in theStateProvince
method to get better results:Once you've done this, the
object.Equals
code will work perfectly. Instead of naïvely checking whether or notaddress1
andaddress2
literally have the sameStateProvince
reference, it will actually check for semantic equality.The other way around this is to extend the tracking code to actually descend into sub-objects. In other words, for each property, check the
Type.IsClass
and optionally theType.IsInterface
property, and iftrue
, then recursively invoke the change-tracking method on the property itself, prefixing any audit results returned recursively with the property name. So you'd end up with a change forStateProvinceCode
.I use the above approach sometimes too, but it's easier to just override
Equals
on the objects for which you want to compare semantic equality (i.e. audit) and provide an appropriateToString
override that makes it clear what changed. It doesn't scale for deep nesting but I think it's unusual to want to audit that way.The last trick is to define your own interface, say
IAuditable<T>
, which takes a second instance of the same type as a parameter and actually returns a list (or enumerable) of all of the differences. It's similar to our overriddenobject.Equals
method above but gives back more information. This is useful for when the object graph is really complicated and you know you can't rely on Reflection orEquals
. You can combine this with the above approach; really all you have to do is substituteIComparable
for yourIAuditable
and invoke theAudit
method if it implements that interface.You never want to implement GetHashCode on mutable properties (properties that could be changed by someone) - i.e. non-private setters.
Imagine this scenario:
Guess what...your object is permanently lost in the collection since the collection uses GetHashCode() to find it! You've effectively changed the hashcode value from what was originally placed in the collection. Probably not what you wanted.
Liviu Trifoi solution: Using CompareNETObjects library. GitHub - NuGet package - Tutorial.