I added a new .Net project to GitHub. It contains a base class you can use to easily see if a property was changed on your object.
You can get it at https://github.com/ScottLilly/PropertyChangeLogger.
To use it, have your business class inherit from PropertyChangeLoggingClass. If you instantiate your class with the empty constructor, the “original” values will be set to the defaults for the property types. If you use a constructor that receives parameters you use to set the values of the properties, you just need to call SetInitialPropertyValues() when you’ve got all your values set.
Here a sample of it:
using PropertyChangeLogger; namespace TestPropertyChangeLogger { public class Customer : PropertyChangeLoggingClass { public string Name { get; set; } [DoNotLogValuesWhenThisPropertyChanges] public string Password { get; set; } [DoNotLogChangesToThisProperty] public double ComputedValue { get; set; } public Customer() { } public Customer(string name, string password, double computedValue) { Name = name; Password = password; ComputedValue = computedValue; SetInitialPropertyValues(); } } }
There are two property attributes available, so you can let the library know to ignore changes to specified properties or to recognize the changes, without showing the values (for properties like passwords).
To see how you’d check for changes, here’s one of the unit tests from the solution:
[TestMethod] public void EmptyConstructor_OneLoggedOneLoggedWithoutValuesPropertyChanged() { Customer customer = new Customer(); customer.Name = CUSTOMER_ORIGINAL_NAME; customer.Password = CUSTOMER_ORIGINAL_PASSWORD; Assert.IsTrue(customer.HasChangedProperties); Assert.AreEqual(2, customer.ChangedProperties.Count); Assert.AreEqual(null, customer.ChangedProperties.First(x => x.PropertyName == "Name").OriginalValue); Assert.AreEqual(CUSTOMER_ORIGINAL_NAME, customer.ChangedProperties.First(x => x.PropertyName == "Name").CurrentValue); Assert.AreEqual(null, customer.ChangedProperties.First(x => x.PropertyName == "Password").OriginalValue); Assert.AreEqual(null, customer.ChangedProperties.First(x => x.PropertyName == "Password").CurrentValue); }
If your class has properties that are a class of yours which also inherits from PropertyChangeLoggingClass, you’ll see changes to the property’s child properties (and any other descendants that have PropertyChangeLoggingClass as a base).
There is one noticeable limit; this library doesn’t check for changes of properties that are lists. I may look for a way to do that in the future.
Check it out and let me know if you have any ideas to improve it.
Leave a Comment