In this article, we will implement the ability to revert the object to the last-accepted version. The .NET Framework exposes this ability as the IRevertibleChangeTracking interface. It adds a new RejectChanges method. This method must revert any changes performed since the last call to the AcceptChanges method.
We need to duplicate each field or automatic property: one copy will contain the current value, and the second will contain the accepted value. The AcceptChanges method copies the current values to the accepted ones, while the RejectChanges method copies the accepted values to the current ones.
Let's see this pattern in action:
1#pragma warning disable CS8618
2
3[TrackChanges]
4[NotifyPropertyChanged]
5public partial class Comment
6{
7 public Comment( Guid id, string author, string content )
8 {
9 this.Id = id;
10 this.Author = author;
11 this.Content = content;
12 }
13
14 public Guid Id { get; }
15 public string Author { get; set; }
16 public string Content { get; set; }
17}
1#pragma warning disable CS8618
2
3using System;
4using System.ComponentModel;
5
6[TrackChanges]
7[NotifyPropertyChanged]
8public partial class Comment
9: INotifyPropertyChanged, ISwitchableChangeTracking, IRevertibleChangeTracking, IChangeTracking
10{
11 public Comment( Guid id, string author, string content )
12 {
13 this.Id = id;
14 this.Author = author;
15 this.Content = content;
16 }
17
18 public Guid Id { get; }
19private string _author = default!;
20
21 public string Author { get { return this._author; } set { if (value != this._author) { this._author = value; OnPropertyChanged("Author"); } return; } }
22 private string _content = default!;
23
24 public string Content { get { return this._content; } set { if (value != this._content) { this._content = value; OnPropertyChanged("Content"); } return; } }
25 private string _acceptedAuthor;
26 private string _acceptedContent;
27 private bool _isTrackingChanges;
28
29 public bool IsChanged { get; private set; }
30
31 public bool IsTrackingChanges
32 {
33 get
34 {
35 return _isTrackingChanges;
36 }
37 set
38 {
39 if (this._isTrackingChanges != value)
40 {
41 this._isTrackingChanges = value;
42 this.OnPropertyChanged("IsTrackingChanges");
43 if (value)
44 {
45 AcceptChanges();
46 }
47 }
48 }
49 }
50
51 public virtual void AcceptChanges()
52 {
53 IsChanged = false;
54 this._acceptedAuthor = this.Author;
55 this._acceptedContent = this.Content;
56 }
57 protected void OnChange()
58 {
59 if (IsChanged == false)
60 {
61 IsChanged = true;
62 this.OnPropertyChanged("IsChanged");
63 }
64 }
65 protected virtual void OnPropertyChanged(string name)
66 {
67 PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
68 if (name is not ("IsChanged" or "IsTrackingChanges"))
69 {
70 OnChange();
71 }
72 }
73 public virtual void RejectChanges()
74 {
75 IsChanged = false;
76 this.Author = this._acceptedAuthor;
77 this.Content = this._acceptedContent;
78 }
79 public event PropertyChangedEventHandler? PropertyChanged;
80}
1[TrackChanges]
2public class ModeratedComment : Comment
3{
4 public ModeratedComment( Guid id, string author, string content ) : base( id, author, content )
5 {
6 }
7
8 public bool? IsApproved { get; set; }
9}
1using System;
2
3[TrackChanges]
4public class ModeratedComment : Comment
5{
6 public ModeratedComment( Guid id, string author, string content ) : base( id, author, content )
7 {
8 }
9private bool? _isApproved;
10
11 public bool? IsApproved { get { return this._isApproved; } set { if (value != this._isApproved) { this._isApproved = value; OnPropertyChanged("IsApproved"); } return; } }
12 private bool? _acceptedIsApproved;
13}
Aspect implementation
Here is the complete code of the new version of the TrackChanges
aspect:
1using Metalama.Framework.Advising;
2using Metalama.Framework.Aspects;
3using Metalama.Framework.Code;
4using Metalama.Framework.Diagnostics;
5using System.Globalization;
6
7#pragma warning disable IDE0031, IDE1005
8
9[Inheritable]
10public class TrackChangesAttribute : TypeAspect
11{
12 private static readonly DiagnosticDefinition<INamedType> _mustHaveOnChangeMethod = new(
13 "MY001",
14 Severity.Error,
15 $"The '{nameof(ISwitchableChangeTracking)}' interface is implemented manually on type '{{0}}', but the type does not have an '{nameof(OnChange)}()' method.");
16
17 private static readonly DiagnosticDefinition _onChangeMethodMustBeProtected = new(
18 "MY002",
19 Severity.Error,
20 $"The '{nameof(OnChange)}()' method must be have the 'protected' accessibility.");
21
22 private static readonly DiagnosticDefinition<IMethod> _onPropertyChangedMustBeVirtual = new(
23 "MY003",
24 Severity.Error,
25 "The '{0}' method must be virtual.");
26
27 [InterfaceMember( WhenExists = InterfaceMemberOverrideStrategy.Ignore )]
28 public bool IsChanged { get; private set; }
29
30 [InterfaceMember( WhenExists = InterfaceMemberOverrideStrategy.Ignore )]
31 public bool IsTrackingChanges
32 {
33 get => meta.This._isTrackingChanges;
34 set
35 {
36 if ( meta.This._isTrackingChanges != value )
37 {
38 meta.This._isTrackingChanges = value;
39
40 var onPropertyChanged = this.GetOnPropertyChangedMethod( meta.Target.Type );
41
42 if ( onPropertyChanged != null )
43 {
44 onPropertyChanged.Invoke( nameof(this.IsTrackingChanges) );
45 }
46
47 if ( value )
48 {
49 this.AcceptChanges();
50 }
51 }
52 }
53 }
54
55 public override void BuildAspect( IAspectBuilder<INamedType> builder )
56 {
57 // Select fields and automatic properties that can be changed.
58 var fieldsOrProperties = builder.Target.FieldsAndProperties
59 .Where( f =>
60 !f.IsImplicitlyDeclared && f.Writeability == Writeability.All &&
61 f.IsAutoPropertyOrField == true )
62 .ToArray();
63
64 var introducedFields = new Dictionary<IFieldOrProperty, IField>();
65
66 // Create a field for each mutable field or property. These fields
67 // will contain the accepted values.
68 foreach ( var fieldOrProperty in fieldsOrProperties )
69 {
70 var upperCaseName = fieldOrProperty.Name.TrimStart( '_' );
71 upperCaseName =
72 upperCaseName.Substring( 0, 1 ).ToUpper( CultureInfo.InvariantCulture ) +
73 upperCaseName.Substring( 1 );
74 var acceptedField =
75 builder.Advice.IntroduceField( builder.Target, "_accepted" + upperCaseName,
76 fieldOrProperty.Type );
77 introducedFields[fieldOrProperty] = acceptedField.Declaration;
78 }
79
80 // Implement the ISwitchableChangeTracking interface.
81 var implementInterfaceResult = builder.Advice.ImplementInterface( builder.Target,
82 typeof(ISwitchableChangeTracking), OverrideStrategy.Ignore,
83 new { IntroducedFields = introducedFields } );
84
85 // If the type already implements ISwitchableChangeTracking, it must have a protected method called OnChanged, without parameters, otherwise
86 // this is a contract violation, so we report an error.
87 if ( implementInterfaceResult.Outcome == AdviceOutcome.Ignore )
88 {
89 var onChangeMethod = builder.Target.AllMethods.OfName( nameof(this.OnChange) )
90 .SingleOrDefault( m => m.Parameters.Count == 0 );
91
92 if ( onChangeMethod == null )
93 {
94 builder.Diagnostics.Report(
95 _mustHaveOnChangeMethod.WithArguments( builder.Target ) );
96 }
97 else if ( onChangeMethod.Accessibility != Accessibility.Protected )
98 {
99 builder.Diagnostics.Report( _onChangeMethodMustBeProtected );
100 }
101 }
102 else
103 {
104 builder.Advice.IntroduceField( builder.Target, "_isTrackingChanges", typeof(bool) );
105 }
106
107 // Override all writable fields and automatic properties.
108 // If the type has an OnPropertyChanged method, we assume that all properties
109 // and fields already call it, and we hook into OnPropertyChanged instead of
110 // overriding each setter.
111 var onPropertyChanged = this.GetOnPropertyChangedMethod( builder.Target );
112
113 if ( onPropertyChanged == null )
114 {
115 // If the type has an OnPropertyChanged method, we assume that all properties
116 // and fields already call it, and we hook into OnPropertyChanged instead of
117 // overriding each setter.
118 foreach ( var fieldOrProperty in fieldsOrProperties )
119 {
120 builder.Advice.OverrideAccessors( fieldOrProperty, null,
121 nameof(this.OverrideSetter) );
122 }
123 }
124 else if ( onPropertyChanged.DeclaringType.Equals( builder.Target ) )
125 {
126 builder.Advice.Override( onPropertyChanged, nameof(this.OnPropertyChanged) );
127 }
128 else if ( implementInterfaceResult.Outcome == AdviceOutcome.Ignore )
129 {
130 // If we have an OnPropertyChanged method but the type already implements ISwitchableChangeTracking,
131 // we assume that the type already hooked the OnPropertyChanged method, and
132 // there is nothing else to do.
133 }
134 else
135 {
136 // If the OnPropertyChanged method was defined in a base class, but not overridden
137 // in the current class, and if we implement ISwitchableChangeTracking ourselves,
138 // then we need to override OnPropertyChanged.
139
140 if ( !onPropertyChanged.IsVirtual )
141 {
142 builder.Diagnostics.Report(
143 _onPropertyChangedMustBeVirtual.WithArguments( onPropertyChanged ) );
144 }
145 else
146 {
147 builder.Advice.IntroduceMethod( builder.Target, nameof(this.OnPropertyChanged),
148 whenExists: OverrideStrategy.Override );
149 }
150 }
151 }
152
153 private IMethod? GetOnPropertyChangedMethod( INamedType type )
154 => type.AllMethods
155 .OfName( "OnPropertyChanged" )
156 .SingleOrDefault( m => m.Parameters.Count == 1 );
157
158 [InterfaceMember]
159 public virtual void AcceptChanges()
160 {
161 if ( meta.Target.Method.IsOverride )
162 {
163 meta.Proceed();
164 }
165 else
166 {
167 this.IsChanged = false;
168 }
169
170 var introducedFields =
171 (Dictionary<IFieldOrProperty, IField>) meta.Tags["IntroducedFields"]!;
172
173 foreach ( var field in introducedFields )
174 {
175 field.Value.Value = field.Key.Value;
176 }
177 }
178
179 [InterfaceMember]
180 public virtual void RejectChanges()
181 {
182 if ( meta.Target.Method.IsOverride )
183 {
184 meta.Proceed();
185 }
186 else
187 {
188 this.IsChanged = false;
189 }
190
191
192 var introducedFields =
193 (Dictionary<IFieldOrProperty, IField>) meta.Tags["IntroducedFields"]!;
194
195 foreach ( var field in introducedFields )
196 {
197 field.Key.Value = field.Value.Value;
198 }
199 }
200
201
202 [Introduce( WhenExists = OverrideStrategy.Ignore )]
203 protected void OnChange()
204 {
205 if ( this.IsChanged == false )
206 {
207 this.IsChanged = true;
208
209 var onPropertyChanged = this.GetOnPropertyChangedMethod( meta.Target.Type );
210
211 if ( onPropertyChanged != null )
212 {
213 onPropertyChanged.Invoke( nameof(this.IsChanged) );
214 }
215 }
216 }
217
218 [Template]
219 private void OverrideSetter( dynamic? value )
220 {
221 meta.Proceed();
222
223 if ( value != meta.Target.Property.Value )
224 {
225 this.OnChange();
226 }
227 }
228
229 [Template]
230 protected virtual void OnPropertyChanged( string name )
231 {
232 meta.Proceed();
233
234 if ( name is not (nameof(this.IsChanged) or nameof(this.IsTrackingChanges)) )
235 {
236 this.OnChange();
237 }
238 }
239}
Let's focus on the following part of the BuildAspect
method for the moment.
64 var introducedFields = new Dictionary<IFieldOrProperty, IField>();
65
66 // Create a field for each mutable field or property. These fields
67 // will contain the accepted values.
68 foreach ( var fieldOrProperty in fieldsOrProperties )
69 {
70 var upperCaseName = fieldOrProperty.Name.TrimStart( '_' );
71 upperCaseName =
72 upperCaseName.Substring( 0, 1 ).ToUpper( CultureInfo.InvariantCulture ) +
73 upperCaseName.Substring( 1 );
74 var acceptedField =
75 builder.Advice.IntroduceField( builder.Target, "_accepted" + upperCaseName,
76 fieldOrProperty.Type );
77 introducedFields[fieldOrProperty] = acceptedField.Declaration;
78 }
79
80 // Implement the ISwitchableChangeTracking interface.
81 var implementInterfaceResult = builder.Advice.ImplementInterface( builder.Target,
82 typeof(ISwitchableChangeTracking), OverrideStrategy.Ignore,
83 new { IntroducedFields = introducedFields } );
First, the method introduces new fields into the type for each mutable field or automatic property using the IntroduceField method. For details about this practice, see Introducing members.
Note that we are building the introducedFields
dictionary, which maps the current-value field or property to the
accepted-value field. This dictionary will be passed to
the ImplementInterface call as a tag. The collection of tags is
an
anonymous object. For more details about this technique, see Sharing state with advice.
The field dictionary is read from the implementation of AcceptChanges
and RejectChanges
:
158 [InterfaceMember]
159 public virtual void AcceptChanges()
160 {
161 if ( meta.Target.Method.IsOverride )
162 {
163 meta.Proceed();
164 }
165 else
166 {
167 this.IsChanged = false;
168 }
169
170 var introducedFields =
171 (Dictionary<IFieldOrProperty, IField>) meta.Tags["IntroducedFields"]!;
172
173 foreach ( var field in introducedFields )
174 {
175 field.Value.Value = field.Key.Value;
176 }
177 }
179 [InterfaceMember]
180 public virtual void RejectChanges()
181 {
182 if ( meta.Target.Method.IsOverride )
183 {
184 meta.Proceed();
185 }
186 else
187 {
188 this.IsChanged = false;
189 }
190
191
192 var introducedFields =
193 (Dictionary<IFieldOrProperty, IField>) meta.Tags["IntroducedFields"]!;
194
195 foreach ( var field in introducedFields )
196 {
197 field.Key.Value = field.Value.Value;
198 }
199 }
As you can see, the (Dictionary<IFieldOrProperty, IField>) meta.Tags["IntroducedFields"]
expression gets
the IntroducedFields
tag, which was passed to
the ImplementInterface method. We cast it back to its original
type
and iterate it. We use the Value property to generate the run-time expression
that represents the field or property. In the AcceptChanges
method, we copy the current values to the accepted ones
and do the opposite in the RejectChanges
method.