C# || How To Add Simple Object Change Tracking To Track Changes Using C#
The following is a module with functions which demonstrates how to add simple object change tracking to track changes made to an object using C#.
Contents
1. Overview
2. Basic Usage
3. Accept Changes
4. Reject Changes
5. Ignore Tracking For Property
6. Notify Property Changed
7. Utils Namespace
8. More Examples
1. Overview
The following is a simple abstract change tracker class which implements INotifyPropertyChanged and IRevertibleChangeTracking which provides functionality to track object changes, and to ‘accept’ or ‘revert’ changes.
To use this class, simply inherit the abstract class, and your all set!
Note: Don’t forget to include the ‘Utils Namespace‘ before running the examples!
2. Basic Usage
The example below demonstrates the use of ChangeTracker.BeginChanges to start tracking object changes, as well as ChangeTracker.GetChanges to get the changes made to an object.
The following example demonstrates the basic usage of adding change tracking to an object, and making and getting changes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
// Basic Usage using Utils; // Declare class and inherit ChangeTracker public class Person : ChangeTracker { public string FirstName { get; set; } public string LastName { get; set; } public int? Age { get; set; } } // Declare data var person = new Person { FirstName = "Kenneth", LastName = "Perkins", Age = 31 }; // Required: Changes made to this object will start being // tracked the moment this function is called person.BeginChanges(); // Make changes to the object person.FirstName = "Jennifer"; person.LastName = "Nguyen"; person.Age = 28; // Get changes made to the object var changes = person.GetChanges(); // Display the changes Console.WriteLine($"Changes: {changes.Count}"); foreach (var change in changes) { Console.WriteLine($" PropertyName: {change.PropertyName}, OriginalValue: {change.OriginalValue}, CurrentValue: {change.CurrentValue}"); } // expected output: /* Changes: 3 PropertyName: FirstName, OriginalValue: Kenneth, CurrentValue: Jennifer PropertyName: LastName, OriginalValue: Perkins, CurrentValue: Nguyen PropertyName: Age, OriginalValue: 31, CurrentValue: 28 */ |
3. Accept Changes
The example below demonstrates the use of ChangeTracker.AcceptChanges to accept modification changes made to an object.
This function commits all the changes made to the object since either ChangeTracker.BeginChanges was called, or since ChangeTracker.AcceptChanges was last called.
When the accept function is called, all the changes made to the object up to that point will be marked as the current ‘source of truth’ for change tracking.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
// Accept Changes using Utils; // Declare class and inherit ChangeTracker public class Person : ChangeTracker { public string FirstName { get; set; } public string LastName { get; set; } public int? Age { get; set; } } // Declare data var person = new Person { FirstName = "Kenneth", LastName = "Perkins", Age = 31 }; // Required: Changes made to this object will start being // tracked the moment this function is called person.BeginChanges(); // Make changes to the object person.FirstName = "Lynn"; person.LastName = "P"; person.Age = 10; // Accept all the changes made to the object up to // this point as the source of truth for change tracking person.AcceptChanges(); // Get changes made to the object var changes = person.GetChanges(); // Display the changes // Note: No changes will display because the most recent modifications has been accepted Console.WriteLine($"Changes: {changes.Count}"); foreach (var change in changes) { Console.WriteLine($" PropertyName: {change.PropertyName}, OriginalValue: {change.OriginalValue}, CurrentValue: {change.CurrentValue}"); } // expected output: /* Changes: 0 */ |
4. Reject Changes
The example below demonstrates the use of ChangeTracker.RejectChanges to reject modification changes made to an object.
This function rejects all the changes made to the object since either ChangeTracker.BeginChanges was called, or since ChangeTracker.AcceptChanges was last called.
When the reject function is called, all the changes made to the object up to that point reverts back to the objects state before modifications initially began or modifications was last accepted.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
// Reject Changes using Utils; // Declare class and inherit ChangeTracker public class Person : ChangeTracker { public string FirstName { get; set; } public string LastName { get; set; } public int? Age { get; set; } } // Declare data var person = new Person { FirstName = "Kenneth", LastName = "Perkins", Age = 31 }; // Required: Changes made to this object will start being // tracked the moment this function is called person.BeginChanges(); // Make changes to the object person.FirstName = "Sole"; person.LastName = "P"; person.Age = 19; // Rejects all the changes made to the object up to // this point and reverts back to the objects state // before modifications were made person.RejectChanges(); // Get changes made to the object var changes = person.GetChanges(); // Display the changes // Note: No changes will display because the most recent modifications has been rejected Console.WriteLine($"Changes: {changes.Count}"); foreach (var change in changes) { Console.WriteLine($" PropertyName: {change.PropertyName}, OriginalValue: {change.OriginalValue}, CurrentValue: {change.CurrentValue}"); } // expected output: /* Changes: 0 */ |
5. Ignore Tracking For Property
The example below demonstrates the use of ChangeTracker.ChangeTrackerIgnore attribute to mark a specific property to be ignored from change tracking.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
// Ignore Tracking For Property using Utils; // Declare class and inherit ChangeTracker public class Person : ChangeTracker { public string FirstName { get; set; } public string LastName { get; set; } [ChangeTrackerIgnore] public int? Age { get; set; } } // Declare data var person = new Person { FirstName = "Kenneth", LastName = "Perkins", Age = 31 }; // Required: Changes made to this object will start being // tracked the moment this function is called person.BeginChanges(); // Make changes to the object person.FirstName = "Jennifer"; person.LastName = "Nguyen"; person.Age = 28; // Get changes made to the object var changes = person.GetChanges(); // Display the changes Console.WriteLine($"Changes: {changes.Count}"); foreach (var change in changes) { Console.WriteLine($" PropertyName: {change.PropertyName}, OriginalValue: {change.OriginalValue}, CurrentValue: {change.CurrentValue}"); } // expected output: /* Changes: 2 PropertyName: FirstName, OriginalValue: Kenneth, CurrentValue: Jennifer PropertyName: LastName, OriginalValue: Perkins, CurrentValue: Nguyen */ |
6. Notify Property Changed
The example below demonstrates the use of ChangeTracker.NotifyPropertyChanged to fire the PropertyChanged event notifying that the specified property value has changed.
In the class declaration, simply add ChangeTracker.NotifyPropertyChanged to the properties you wish to notify changes, and add a PropertyChanged event handler function to receive the notifications.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
// Notify Property Changed using Utils; // Declare class and inherit ChangeTracker // Modify the properties you wish to notify changes public class Person : ChangeTracker { string _firstName; public string FirstName { get { return _firstName; } set { _firstName = value; NotifyPropertyChanged(value); } } string _lastName; public string LastName { get { return _lastName; } set { _lastName = value; NotifyPropertyChanged(value); } } int? _age; public int? Age { get { return _age; } set { _age = value; NotifyPropertyChanged(value); } } } // Declare data var person = new Person { FirstName = "Kenneth", LastName = "Perkins", Age = 31 }; // Set custom event handler function for property changed event person.PropertyChanged += Person_PropertyChanged; // Required: Changes made to this object will start being // tracked the moment this function is called person.BeginChanges(); // Make changes to the object person.FirstName = "Jennifer"; person.LastName = "Nguyen"; person.Age = 28; // Declare Custom event handler function for the PropertyChanged event public static void Person_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { var eventArgs = (ChangeTracker.PropertyChangedTrackedEventArgs)e; Console.WriteLine($"Event Handler Changes:"); Console.WriteLine($" PropertyName: {eventArgs.PropertyName}, OriginalValue: {eventArgs.OriginalValue}, CurrentValue: {eventArgs.CurrentValue}"); } // expected output: /* Event Handler Changes: PropertyName: FirstName, OriginalValue: Kenneth, CurrentValue: Jennifer Event Handler Changes: PropertyName: LastName, OriginalValue: Perkins, CurrentValue: Nguyen Event Handler Changes: PropertyName: Age, OriginalValue: 31, CurrentValue: 28 */ |
7. Utils Namespace
The following is the Utils Namespace. Include this in your project to start using!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 |
// ============================================================================ // Author: Kenneth Perkins // Date: Apr 10, 2022 // Taken From: http://programmingnotes.org/ // File: Utils.cs // Description: Handles general utility functions // ============================================================================ using System; using System.Linq; using System.Reflection; using System.Collections.Generic; using System.Runtime.CompilerServices; namespace Utils { public abstract class ChangeTracker : System.ComponentModel.INotifyPropertyChanged, System.ComponentModel.IRevertibleChangeTracking { protected Dictionary<string, ITrackedChange> Tracked { get; set; } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; public bool IsTracking { get { return Tracked.Count > 0; } } /// <summary> /// Gets the objects changed status /// </summary> /// <returns><see langword="true"/> if the objects content has changed since either <see cref="BeginChanges"/> /// was called, or since <see cref="AcceptChanges"/> was last called; <see langword="false"/> otherwise</returns> public bool IsChanged { get { if (!_isChanged && IsTracking) { var trackedChanges = GetTrackedChanges(); if (trackedChanges.Any(x => x.DetectChange(GetValue(x.Property)))) { _isChanged = true; } } return _isChanged; } protected set { _isChanged = value; } } private bool _isChanged = false; protected ChangeTracker() { Tracked = new Dictionary<string, ITrackedChange>(); } /// <summary> /// Fires the PropertyChanged event notifying that the specified property value changed /// </summary> /// <param name="currentValue">The current value</param> /// <param name="originalValue">The original value</param> /// <param name="propertyName">The corresponding property name</param> protected void NotifyPropertyChanged(object currentValue, object originalValue, [CallerMemberName] string propertyName = "") { this.PropertyChanged?.Invoke(this, new PropertyChangedTrackedEventArgs(propertyName, originalValue, currentValue)); } /// <summary> /// Fires the PropertyChanged event notifying that the specified property value changed /// </summary> /// <param name="currentValue">The current value</param> /// <param name="propertyName">The corresponding property name</param> protected virtual void NotifyPropertyChanged(object currentValue, [CallerMemberName] string propertyName = "") { NotifyPropertyChanged(currentValue, GetTrackedChange(propertyName)?.OriginalValue, propertyName); } /// <summary> /// Starts the tracking operation on the object. Changes made to the /// object will start being tracked the moment this function is called /// </summary> /// <exception cref="InvalidOperationException">Changes have already begun</exception> public virtual void BeginChanges() { ThrowIfTrackingStarted(); Track(GetTrackableProperties()); IsChanged = false; } /// <summary> /// Ends the tracking operation on the object. Any pending tracked changes made to the /// object since either <see cref="BeginChanges"/> was called, or since <see cref="AcceptChanges"/> /// was last called will be lost the moment this function is called /// </summary> /// <exception cref="InvalidOperationException">Change tracking has not started</exception> public virtual void EndChanges() { ThrowIfTrackingNotStarted(); Tracked.Clear(); IsChanged = false; } /// <summary> /// Sets the current object state as its default state by accepting the modifications. /// Commits all the changes made to this object since either <see cref="BeginChanges"/> /// was called, or since <see cref="AcceptChanges"/> was last called /// </summary> /// <exception cref="InvalidOperationException">Change tracking has not started</exception> public virtual void AcceptChanges() { ThrowIfTrackingNotStarted(); var trackedChanges = UpdateTracked(); foreach (var change in trackedChanges) { change.AcceptChange(); } IsChanged = false; } /// <summary> /// Resets the current objects state by rejecting the modifications. Rejects /// all changes made to the object since either <see cref="BeginChanges"/> /// was called, or since <see cref="AcceptChanges"/> was last called /// </summary> /// <exception cref="InvalidOperationException">Change tracking has not started</exception> public virtual void RejectChanges() { ThrowIfTrackingNotStarted(); var trackedChanges = GetTrackedChanges(); foreach (var change in trackedChanges) { SetValue(change.Property, change.OriginalValue); change.RejectChange(); } IsChanged = false; } /// <summary> /// Returns a list containing information of all the properties with changes /// applied to it since either <see cref="BeginChanges"/> was called, or /// since <see cref="AcceptChanges"/> was last called /// </summary> /// <returns>A list containing the changes made to the object</returns> /// <exception cref="InvalidOperationException">Change tracking has not started</exception> public virtual List<ITrackedChange> GetChanges() { ThrowIfTrackingNotStarted(); var result = new List<ITrackedChange>(); var trackedChanges = UpdateTracked(); foreach (var change in trackedChanges) { if (change.HasChanges) { result.Add(change); } } return result; } /// <summary> /// Returns a list containing information of all the properties being tracked /// </summary> /// <returns>A list containing property tracking information</returns> /// <exception cref="InvalidOperationException">Change tracking has not started</exception> public List<ITrackedChange> GetTracked() { ThrowIfTrackingNotStarted(); return Tracked.Values.ToList(); } /// <summary> /// Updates the tracking status of all the properties being tracked /// </summary> /// <returns>A list containing properties being tracked</returns> protected IEnumerable<TrackedChange> UpdateTracked() { var trackedChanges = GetTrackedChanges(); Track(trackedChanges.Select(x => x.Property)); return trackedChanges; } /// <summary> /// Keeps track of the original and current values of the provided properties /// </summary> /// <param name="properties">The properties to track</param> protected void Track(IEnumerable<PropertyInfo> properties) { if (properties != null) { foreach (var prop in properties) { Track(prop, GetValue(prop)); } } } /// <summary> /// Keeps track of the original and current value of the provided property /// </summary> /// <param name="property">The property to track</param> /// <param name="currentValue">The current value of the property</param> protected void Track(PropertyInfo property, object currentValue) { TrackedChange currentChange = null; if (!IsTrackedChange(property.Name)) { Func<object, object, bool> hasChangedFunc = (original, current) => { return HasValuesChanged(original, current); }; currentChange = new TrackedChange { Property = property, OriginalValue = currentValue, HasChangedFunc = hasChangedFunc }; Tracked.Add(property.Name, currentChange); } else { currentChange = GetTrackedChange(property.Name); currentChange.CurrentValue = currentValue; currentChange.Status = TrackedChange.TrackingStatus.Checked; currentChange.LastChecked = DateTime.Now; } if (currentChange.HasChanges) { IsChanged = true; } } /// <summary> /// Class which contains property tracking information /// </summary> protected class TrackedChange : ITrackedChange { public enum TrackingStatus { Unchecked, Checked } public PropertyInfo Property { get; set; } public string PropertyName { get { return Property?.Name; } } public object OriginalValue { get; set; } public object CurrentValue { get; set; } public TrackingStatus Status { get; set; } = TrackingStatus.Unchecked; public bool HasChanges { get { return Status == TrackingStatus.Checked && DetectChange(CurrentValue); } } public DateTime? LastChecked { get; set; } = null; public Func<object, object, bool> HasChangedFunc { get; set; } public bool DetectChange(object currentValue) { return HasChangedFunc(OriginalValue, currentValue); } public void AcceptChange() { OriginalValue = CurrentValue; RejectChange(); } public void RejectChange() { CurrentValue = null; Status = TrackingStatus.Unchecked; LastChecked = null; } } /// <summary> /// Provides support for object change tracking /// </summary> public interface ITrackedChange { string PropertyName { get; } object OriginalValue { get; } object CurrentValue { get; } } /// <summary> /// Provides data for the <see cref=" System.ComponentModel.PropertyChangedEventArgs"/> event /// </summary> public class PropertyChangedTrackedEventArgs : System.ComponentModel.PropertyChangedEventArgs { public object OriginalValue{ get; private set; } public object CurrentValue { get; private set; } public PropertyChangedTrackedEventArgs(string propertyName, object originalValue, object currentValue) : base(propertyName) { OriginalValue = originalValue; CurrentValue = currentValue; } } /// <summary> /// Attribute which allows a property to be ignored from being tracked /// </summary> public class ChangeTrackerIgnoreAttribute : System.Attribute {} #region "Helpers" protected bool IsTrackedChange(string propertyName) { return Tracked.ContainsKey(propertyName); } protected TrackedChange GetTrackedChange(string propertyName) { return IsTrackedChange(propertyName) ? (TrackedChange)Tracked[propertyName] : null; } protected IEnumerable<TrackedChange> GetTrackedChanges() { return Tracked.Select(pair => (TrackedChange)pair.Value); } protected virtual IEnumerable<PropertyInfo> GetTrackableProperties() { return this.GetType().GetProperties() .Where(p => !p.DeclaringType.Equals(typeof(ChangeTracker)) && p.CanRead && p.CanWrite && !p.GetCustomAttributes<ChangeTrackerIgnoreAttribute>(false).Any() ); } protected virtual object GetValue(PropertyInfo property) { return property?.GetValue(this, property.GetIndexParameters() .Count() == 1 ? new object[] { null } : null); } protected virtual void SetValue(PropertyInfo property, object value) { if (property != null && property.CanWrite) { property.SetValue(this, value); } } protected virtual bool HasValuesChanged<T>(T originalValue, T currentValue) { return !EqualityComparer<T>.Default.Equals(originalValue, currentValue); } protected void ThrowIfTrackingNotStarted() { if (!IsTracking) { throw new InvalidOperationException("Change tracking has not started. Call 'BeginChanges' to start change tracking"); } } protected void ThrowIfTrackingStarted() { if (IsTracking) { throw new InvalidOperationException("Change tracking has already started"); } } #endregion } }// http://programmingnotes.org/ |
8. More Examples
Below are more examples demonstrating the use of the ‘Utils‘ Namespace. Don’t forget to include the module when running the examples!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 |
// ============================================================================ // Author: Kenneth Perkins // Date: Apr 10, 2022 // Taken From: http://programmingnotes.org/ // File: Program.cs // Description: The following demonstrates the use of the Utils Namespace // ============================================================================ using System; using System.Diagnostics; using System.Collections.Generic; using System.Threading.Tasks; using Utils; public class Program { // Declare class and inherit ChangeTracker // Modify the properties you wish to notify changes public class Person : ChangeTracker { string _firstName; public string FirstName { get { return _firstName; } set { _firstName = value; NotifyPropertyChanged(value); } } string _lastName; public string LastName { get { return _lastName; } set { _lastName = value; NotifyPropertyChanged(value); } } int? _age; //[ChangeTrackerIgnore] public int? Age { get { return _age; } set { _age = value; NotifyPropertyChanged(value); } } } static void Main(string[] args) { try { // Declare data var person = new Person { FirstName = "Kenneth", LastName = "Perkins", Age = 31 }; // Set custom event handler function for property changed event person.PropertyChanged += Person_PropertyChanged; // Required: Changes made to this object will start being // tracked the moment this function is called person.BeginChanges(); var changes1 = person.GetChanges(); // Make changes to the object person.FirstName = "Jennifer"; person.LastName = "Nguyen"; person.Age = 28; // Get changes made to the object var changes2 = person.GetChanges(); // Display the changes DisplayChanges(changes2); // --- Accept changes --- // Make changes to the object person.FirstName = "Lynn"; person.LastName = "P"; person.Age = 10; var changes3 = person.GetChanges(); // Accept all the changes made to the object up to // this point as the source of truth for change tracking person.AcceptChanges(); // Get changes made to the object var changes4 = person.GetChanges(); // Display the changes // Note: No changes will display because the most recent modifications has been accepted DisplayChanges(changes4); // --- Reject changes --- // Make changes to the object person.FirstName = "Sole"; person.LastName = "P"; person.Age = 19; // Rejects all the changes made to the object up to // this point and reverts back to the objects state // before modifications were made person.RejectChanges(); // Get changes made to the object var changes5 = person.GetChanges(); // Display the changes // Note: No changes will display because the most recent modifications has been rejected DisplayChanges(changes5); } catch (Exception ex) { Display(ex.ToString()); } finally { Console.ReadLine(); } } // Declare Custom event handler function for the PropertyChanged event public static void Person_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { var eventArgs = (ChangeTracker.PropertyChangedTrackedEventArgs)e; Display($"Event Handler Changes:"); Display($" PropertyName: {eventArgs.PropertyName}, OriginalValue: {eventArgs.OriginalValue}, CurrentValue: {eventArgs.CurrentValue}"); } public static void DisplayChanges(List<ChangeTracker.ITrackedChange> changes) { Display($"Changes: {changes.Count}"); foreach (var change in changes) { Display($" PropertyName: {change.PropertyName}, OriginalValue: {change.OriginalValue}, CurrentValue: {change.CurrentValue}"); } Display("============"); } static void Display(string message) { Console.WriteLine(message); Debug.Print(message); } }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
Leave a Reply