ObservableValidator.cs 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. // See the LICENSE file in the project root for more information.
  4. using System;
  5. using System.Collections;
  6. using System.Collections.Generic;
  7. using System.ComponentModel;
  8. using System.ComponentModel.DataAnnotations;
  9. using System.Diagnostics.CodeAnalysis;
  10. using System.Linq;
  11. using System.Linq.Expressions;
  12. using System.Reflection;
  13. using System.Runtime.CompilerServices;
  14. namespace CommunityToolkit.Mvvm.ComponentModel;
  15. /// <summary>
  16. /// A base class for objects implementing the <see cref="INotifyDataErrorInfo"/> interface. This class
  17. /// also inherits from <see cref="ObservableObject"/>, so it can be used for observable items too.
  18. /// </summary>
  19. public abstract class ObservableValidator : ObservableObject, INotifyDataErrorInfo
  20. {
  21. /// <summary>
  22. /// The <see cref="ConditionalWeakTable{TKey,TValue}"/> instance used to track compiled delegates to validate entities.
  23. /// </summary>
  24. private static readonly ConditionalWeakTable<Type, Action<object>> EntityValidatorMap = new();
  25. /// <summary>
  26. /// The <see cref="ConditionalWeakTable{TKey, TValue}"/> instance used to track display names for properties to validate.
  27. /// </summary>
  28. /// <remarks>
  29. /// This is necessary because we want to reuse the same <see cref="ValidationContext"/> instance for all validations, but
  30. /// with the same behavior with respect to formatted names that new instances would have provided. The issue is that the
  31. /// <see cref="ValidationContext.DisplayName"/> property is not refreshed when we set <see cref="ValidationContext.MemberName"/>,
  32. /// so we need to replicate the same logic to retrieve the right display name for properties to validate and update that
  33. /// property manually right before passing the context to <see cref="Validator"/> and proceed with the normal functionality.
  34. /// </remarks>
  35. private static readonly ConditionalWeakTable<Type, Dictionary<string, string>> DisplayNamesMap = new();
  36. /// <summary>
  37. /// The cached <see cref="PropertyChangedEventArgs"/> for <see cref="HasErrors"/>.
  38. /// </summary>
  39. private static readonly PropertyChangedEventArgs HasErrorsChangedEventArgs = new(nameof(HasErrors));
  40. /// <summary>
  41. /// The <see cref="ValidationContext"/> instance currently in use.
  42. /// </summary>
  43. private readonly ValidationContext validationContext;
  44. /// <summary>
  45. /// The <see cref="Dictionary{TKey,TValue}"/> instance used to store previous validation results.
  46. /// </summary>
  47. private readonly Dictionary<string, List<ValidationResult>> errors = new();
  48. /// <summary>
  49. /// Indicates the total number of properties with errors (not total errors).
  50. /// This is used to allow <see cref="HasErrors"/> to operate in O(1) time, as it can just
  51. /// check whether this value is not 0 instead of having to traverse <see cref="errors"/>.
  52. /// </summary>
  53. private int totalErrors;
  54. /// <inheritdoc/>
  55. public event EventHandler<DataErrorsChangedEventArgs>? ErrorsChanged;
  56. /// <summary>
  57. /// Initializes a new instance of the <see cref="ObservableValidator"/> class.
  58. /// This constructor will create a new <see cref="ValidationContext"/> that will
  59. /// be used to validate all properties, which will reference the current instance
  60. /// and no additional services or validation properties and settings.
  61. /// </summary>
  62. [RequiresUnreferencedCode("The type of the current instance cannot be statically discovered.")]
  63. protected ObservableValidator()
  64. {
  65. this.validationContext = new ValidationContext(this);
  66. }
  67. /// <summary>
  68. /// Initializes a new instance of the <see cref="ObservableValidator"/> class.
  69. /// This constructor will create a new <see cref="ValidationContext"/> that will
  70. /// be used to validate all properties, which will reference the current instance.
  71. /// </summary>
  72. /// <param name="items">A set of key/value pairs to make available to consumers.</param>
  73. [RequiresUnreferencedCode("The type of the current instance cannot be statically discovered.")]
  74. protected ObservableValidator(IDictionary<object, object?>? items)
  75. {
  76. this.validationContext = new ValidationContext(this, items);
  77. }
  78. /// <summary>
  79. /// Initializes a new instance of the <see cref="ObservableValidator"/> class.
  80. /// This constructor will create a new <see cref="ValidationContext"/> that will
  81. /// be used to validate all properties, which will reference the current instance.
  82. /// </summary>
  83. /// <param name="serviceProvider">An <see cref="IServiceProvider"/> instance to make available during validation.</param>
  84. /// <param name="items">A set of key/value pairs to make available to consumers.</param>
  85. [RequiresUnreferencedCode("The type of the current instance cannot be statically discovered.")]
  86. protected ObservableValidator(IServiceProvider? serviceProvider, IDictionary<object, object?>? items)
  87. {
  88. this.validationContext = new ValidationContext(this, serviceProvider, items);
  89. }
  90. /// <summary>
  91. /// Initializes a new instance of the <see cref="ObservableValidator"/> class.
  92. /// This constructor will store the input <see cref="ValidationContext"/> instance,
  93. /// and it will use it to validate all properties for the current viewmodel.
  94. /// </summary>
  95. /// <param name="validationContext">
  96. /// The <see cref="ValidationContext"/> instance to use to validate properties.
  97. /// <para>
  98. /// This instance will be passed to all <see cref="Validator.TryValidateObject(object, ValidationContext, ICollection{ValidationResult})"/>
  99. /// calls executed by the current viewmodel, and its <see cref="ValidationContext.MemberName"/> property will be updated every time
  100. /// before the call is made to set the name of the property being validated. The property name will not be reset after that, so the
  101. /// value of <see cref="ValidationContext.MemberName"/> will always indicate the name of the last property that was validated, if any.
  102. /// </para>
  103. /// </param>
  104. /// <exception cref="System.ArgumentNullException">Thrown if <paramref name="validationContext"/> is <see langword="null"/>.</exception>
  105. protected ObservableValidator(ValidationContext validationContext)
  106. {
  107. ArgumentNullException.ThrowIfNull(validationContext);
  108. this.validationContext = validationContext;
  109. }
  110. /// <inheritdoc/>
  111. [Display(AutoGenerateField = false)]
  112. public bool HasErrors => this.totalErrors > 0;
  113. /// <summary>
  114. /// Compares the current and new values for a given property. If the value has changed,
  115. /// raises the <see cref="ObservableObject.PropertyChanging"/> event, updates the property with
  116. /// the new value, then raises the <see cref="ObservableObject.PropertyChanged"/> event.
  117. /// </summary>
  118. /// <typeparam name="T">The type of the property that changed.</typeparam>
  119. /// <param name="field">The field storing the property's value.</param>
  120. /// <param name="newValue">The property's value after the change occurred.</param>
  121. /// <param name="validate">If <see langword="true"/>, <paramref name="newValue"/> will also be validated.</param>
  122. /// <param name="propertyName">(optional) The name of the property that changed.</param>
  123. /// <returns><see langword="true"/> if the property was changed, <see langword="false"/> otherwise.</returns>
  124. /// <remarks>
  125. /// This method is just like <see cref="ObservableObject.SetProperty{T}(ref T,T,string)"/>, just with the addition
  126. /// of the <paramref name="validate"/> parameter. If that is set to <see langword="true"/>, the new value will be
  127. /// validated and <see cref="ErrorsChanged"/> will be raised if needed. Following the behavior of the base method,
  128. /// the <see cref="ObservableObject.PropertyChanging"/> and <see cref="ObservableObject.PropertyChanged"/> events
  129. /// are not raised if the current and new value for the target property are the same.
  130. /// </remarks>
  131. /// <exception cref="System.ArgumentNullException">Thrown if <paramref name="propertyName"/> is <see langword="null"/>.</exception>
  132. [RequiresUnreferencedCode("The type of the current instance cannot be statically discovered.")]
  133. protected bool SetProperty<T>([NotNullIfNotNull(nameof(newValue))] ref T field, T newValue, bool validate, [CallerMemberName] string propertyName = null!)
  134. {
  135. ArgumentNullException.ThrowIfNull(propertyName);
  136. bool propertyChanged = SetProperty(ref field, newValue, propertyName);
  137. if (propertyChanged && validate)
  138. {
  139. ValidateProperty(newValue, propertyName);
  140. }
  141. return propertyChanged;
  142. }
  143. /// <summary>
  144. /// Compares the current and new values for a given property. If the value has changed,
  145. /// raises the <see cref="ObservableObject.PropertyChanging"/> event, updates the property with
  146. /// the new value, then raises the <see cref="ObservableObject.PropertyChanged"/> event.
  147. /// See additional notes about this overload in <see cref="SetProperty{T}(ref T,T,bool,string)"/>.
  148. /// </summary>
  149. /// <typeparam name="T">The type of the property that changed.</typeparam>
  150. /// <param name="field">The field storing the property's value.</param>
  151. /// <param name="newValue">The property's value after the change occurred.</param>
  152. /// <param name="comparer">The <see cref="IEqualityComparer{T}"/> instance to use to compare the input values.</param>
  153. /// <param name="validate">If <see langword="true"/>, <paramref name="newValue"/> will also be validated.</param>
  154. /// <param name="propertyName">(optional) The name of the property that changed.</param>
  155. /// <returns><see langword="true"/> if the property was changed, <see langword="false"/> otherwise.</returns>
  156. /// <exception cref="System.ArgumentNullException">Thrown if <paramref name="comparer"/> or <paramref name="propertyName"/> are <see langword="null"/>.</exception>
  157. [RequiresUnreferencedCode("The type of the current instance cannot be statically discovered.")]
  158. protected bool SetProperty<T>([NotNullIfNotNull(nameof(newValue))] ref T field, T newValue, IEqualityComparer<T> comparer, bool validate, [CallerMemberName] string propertyName = null!)
  159. {
  160. ArgumentNullException.ThrowIfNull(comparer);
  161. ArgumentNullException.ThrowIfNull(propertyName);
  162. bool propertyChanged = SetProperty(ref field, newValue, comparer, propertyName);
  163. if (propertyChanged && validate)
  164. {
  165. ValidateProperty(newValue, propertyName);
  166. }
  167. return propertyChanged;
  168. }
  169. /// <summary>
  170. /// Compares the current and new values for a given property. If the value has changed,
  171. /// raises the <see cref="ObservableObject.PropertyChanging"/> event, updates the property with
  172. /// the new value, then raises the <see cref="ObservableObject.PropertyChanged"/> event. Similarly to
  173. /// the <see cref="ObservableObject.SetProperty{T}(T,T,Action{T},string)"/> method, this overload should only be
  174. /// used when <see cref="ObservableObject.SetProperty{T}(ref T,T,string)"/> can't be used directly.
  175. /// </summary>
  176. /// <typeparam name="T">The type of the property that changed.</typeparam>
  177. /// <param name="oldValue">The current property value.</param>
  178. /// <param name="newValue">The property's value after the change occurred.</param>
  179. /// <param name="callback">A callback to invoke to update the property value.</param>
  180. /// <param name="validate">If <see langword="true"/>, <paramref name="newValue"/> will also be validated.</param>
  181. /// <param name="propertyName">(optional) The name of the property that changed.</param>
  182. /// <returns><see langword="true"/> if the property was changed, <see langword="false"/> otherwise.</returns>
  183. /// <remarks>
  184. /// This method is just like <see cref="ObservableObject.SetProperty{T}(T,T,Action{T},string)"/>, just with the addition
  185. /// of the <paramref name="validate"/> parameter. As such, following the behavior of the base method,
  186. /// the <see cref="ObservableObject.PropertyChanging"/> and <see cref="ObservableObject.PropertyChanged"/> events
  187. /// are not raised if the current and new value for the target property are the same.
  188. /// </remarks>
  189. /// <exception cref="System.ArgumentNullException">Thrown if <paramref name="callback"/> or <paramref name="propertyName"/> are <see langword="null"/>.</exception>
  190. [RequiresUnreferencedCode("The type of the current instance cannot be statically discovered.")]
  191. protected bool SetProperty<T>(T oldValue, T newValue, Action<T> callback, bool validate, [CallerMemberName] string propertyName = null!)
  192. {
  193. ArgumentNullException.ThrowIfNull(callback);
  194. ArgumentNullException.ThrowIfNull(propertyName);
  195. bool propertyChanged = SetProperty(oldValue, newValue, callback, propertyName);
  196. if (propertyChanged && validate)
  197. {
  198. ValidateProperty(newValue, propertyName);
  199. }
  200. return propertyChanged;
  201. }
  202. /// <summary>
  203. /// Compares the current and new values for a given property. If the value has changed,
  204. /// raises the <see cref="ObservableObject.PropertyChanging"/> event, updates the property with
  205. /// the new value, then raises the <see cref="ObservableObject.PropertyChanged"/> event.
  206. /// See additional notes about this overload in <see cref="SetProperty{T}(T,T,Action{T},bool,string)"/>.
  207. /// </summary>
  208. /// <typeparam name="T">The type of the property that changed.</typeparam>
  209. /// <param name="oldValue">The current property value.</param>
  210. /// <param name="newValue">The property's value after the change occurred.</param>
  211. /// <param name="comparer">The <see cref="IEqualityComparer{T}"/> instance to use to compare the input values.</param>
  212. /// <param name="callback">A callback to invoke to update the property value.</param>
  213. /// <param name="validate">If <see langword="true"/>, <paramref name="newValue"/> will also be validated.</param>
  214. /// <param name="propertyName">(optional) The name of the property that changed.</param>
  215. /// <returns><see langword="true"/> if the property was changed, <see langword="false"/> otherwise.</returns>
  216. /// <exception cref="System.ArgumentNullException">Thrown if <paramref name="comparer"/>, <paramref name="callback"/> or <paramref name="propertyName"/> are <see langword="null"/>.</exception>
  217. [RequiresUnreferencedCode("The type of the current instance cannot be statically discovered.")]
  218. protected bool SetProperty<T>(T oldValue, T newValue, IEqualityComparer<T> comparer, Action<T> callback, bool validate, [CallerMemberName] string propertyName = null!)
  219. {
  220. ArgumentNullException.ThrowIfNull(comparer);
  221. ArgumentNullException.ThrowIfNull(callback);
  222. ArgumentNullException.ThrowIfNull(propertyName);
  223. bool propertyChanged = SetProperty(oldValue, newValue, comparer, callback, propertyName);
  224. if (propertyChanged && validate)
  225. {
  226. ValidateProperty(newValue, propertyName);
  227. }
  228. return propertyChanged;
  229. }
  230. /// <summary>
  231. /// Compares the current and new values for a given nested property. If the value has changed,
  232. /// raises the <see cref="ObservableObject.PropertyChanging"/> event, updates the property and then raises the
  233. /// <see cref="ObservableObject.PropertyChanged"/> event. The behavior mirrors that of
  234. /// <see cref="ObservableObject.SetProperty{TModel,T}(T,T,TModel,Action{TModel,T},string)"/>, with the difference being that this
  235. /// method is used to relay properties from a wrapped model in the current instance. For more info, see the docs for
  236. /// <see cref="ObservableObject.SetProperty{TModel,T}(T,T,TModel,Action{TModel,T},string)"/>.
  237. /// </summary>
  238. /// <typeparam name="TModel">The type of model whose property (or field) to set.</typeparam>
  239. /// <typeparam name="T">The type of property (or field) to set.</typeparam>
  240. /// <param name="oldValue">The current property value.</param>
  241. /// <param name="newValue">The property's value after the change occurred.</param>
  242. /// <param name="model">The model </param>
  243. /// <param name="callback">The callback to invoke to set the target property value, if a change has occurred.</param>
  244. /// <param name="validate">If <see langword="true"/>, <paramref name="newValue"/> will also be validated.</param>
  245. /// <param name="propertyName">(optional) The name of the property that changed.</param>
  246. /// <returns><see langword="true"/> if the property was changed, <see langword="false"/> otherwise.</returns>
  247. /// <exception cref="System.ArgumentNullException">Thrown if <paramref name="model"/>, <paramref name="callback"/> or <paramref name="propertyName"/> are <see langword="null"/>.</exception>
  248. [RequiresUnreferencedCode("The type of the current instance cannot be statically discovered.")]
  249. protected bool SetProperty<TModel, T>(T oldValue, T newValue, TModel model, Action<TModel, T> callback, bool validate, [CallerMemberName] string propertyName = null!)
  250. where TModel : class
  251. {
  252. ArgumentNullException.ThrowIfNull(model);
  253. ArgumentNullException.ThrowIfNull(callback);
  254. ArgumentNullException.ThrowIfNull(propertyName);
  255. bool propertyChanged = SetProperty(oldValue, newValue, model, callback, propertyName);
  256. if (propertyChanged && validate)
  257. {
  258. ValidateProperty(newValue, propertyName);
  259. }
  260. return propertyChanged;
  261. }
  262. /// <summary>
  263. /// Compares the current and new values for a given nested property. If the value has changed,
  264. /// raises the <see cref="ObservableObject.PropertyChanging"/> event, updates the property and then raises the
  265. /// <see cref="ObservableObject.PropertyChanged"/> event. The behavior mirrors that of
  266. /// <see cref="ObservableObject.SetProperty{TModel,T}(T,T,IEqualityComparer{T},TModel,Action{TModel,T},string)"/>,
  267. /// with the difference being that this method is used to relay properties from a wrapped model in the
  268. /// current instance. For more info, see the docs for
  269. /// <see cref="ObservableObject.SetProperty{TModel,T}(T,T,IEqualityComparer{T},TModel,Action{TModel,T},string)"/>.
  270. /// </summary>
  271. /// <typeparam name="TModel">The type of model whose property (or field) to set.</typeparam>
  272. /// <typeparam name="T">The type of property (or field) to set.</typeparam>
  273. /// <param name="oldValue">The current property value.</param>
  274. /// <param name="newValue">The property's value after the change occurred.</param>
  275. /// <param name="comparer">The <see cref="IEqualityComparer{T}"/> instance to use to compare the input values.</param>
  276. /// <param name="model">The model </param>
  277. /// <param name="callback">The callback to invoke to set the target property value, if a change has occurred.</param>
  278. /// <param name="validate">If <see langword="true"/>, <paramref name="newValue"/> will also be validated.</param>
  279. /// <param name="propertyName">(optional) The name of the property that changed.</param>
  280. /// <returns><see langword="true"/> if the property was changed, <see langword="false"/> otherwise.</returns>
  281. /// <exception cref="System.ArgumentNullException">Thrown if <paramref name="comparer"/>, <paramref name="model"/>, <paramref name="callback"/> or <paramref name="propertyName"/> are <see langword="null"/>.</exception>
  282. [RequiresUnreferencedCode("The type of the current instance cannot be statically discovered.")]
  283. protected bool SetProperty<TModel, T>(T oldValue, T newValue, IEqualityComparer<T> comparer, TModel model, Action<TModel, T> callback, bool validate, [CallerMemberName] string propertyName = null!)
  284. where TModel : class
  285. {
  286. ArgumentNullException.ThrowIfNull(comparer);
  287. ArgumentNullException.ThrowIfNull(model);
  288. ArgumentNullException.ThrowIfNull(callback);
  289. ArgumentNullException.ThrowIfNull(propertyName);
  290. bool propertyChanged = SetProperty(oldValue, newValue, comparer, model, callback, propertyName);
  291. if (propertyChanged && validate)
  292. {
  293. ValidateProperty(newValue, propertyName);
  294. }
  295. return propertyChanged;
  296. }
  297. /// <summary>
  298. /// Tries to validate a new value for a specified property. If the validation is successful,
  299. /// <see cref="ObservableObject.SetProperty{T}(ref T,T,string?)"/> is called, otherwise no state change is performed.
  300. /// </summary>
  301. /// <typeparam name="T">The type of the property that changed.</typeparam>
  302. /// <param name="field">The field storing the property's value.</param>
  303. /// <param name="newValue">The property's value after the change occurred.</param>
  304. /// <param name="errors">The resulting validation errors, if any.</param>
  305. /// <param name="propertyName">(optional) The name of the property that changed.</param>
  306. /// <returns>Whether the validation was successful and the property value changed as well.</returns>
  307. /// <exception cref="System.ArgumentNullException">Thrown if <paramref name="propertyName"/> is <see langword="null"/>.</exception>
  308. [RequiresUnreferencedCode("The type of the current instance cannot be statically discovered.")]
  309. protected bool TrySetProperty<T>(ref T field, T newValue, out IReadOnlyCollection<ValidationResult> errors, [CallerMemberName] string propertyName = null!)
  310. {
  311. ArgumentNullException.ThrowIfNull(propertyName);
  312. return TryValidateProperty(newValue, propertyName, out errors) &&
  313. SetProperty(ref field, newValue, propertyName);
  314. }
  315. /// <summary>
  316. /// Tries to validate a new value for a specified property. If the validation is successful,
  317. /// <see cref="ObservableObject.SetProperty{T}(ref T,T,IEqualityComparer{T},string?)"/> is called, otherwise no state change is performed.
  318. /// </summary>
  319. /// <typeparam name="T">The type of the property that changed.</typeparam>
  320. /// <param name="field">The field storing the property's value.</param>
  321. /// <param name="newValue">The property's value after the change occurred.</param>
  322. /// <param name="comparer">The <see cref="IEqualityComparer{T}"/> instance to use to compare the input values.</param>
  323. /// <param name="errors">The resulting validation errors, if any.</param>
  324. /// <param name="propertyName">(optional) The name of the property that changed.</param>
  325. /// <returns>Whether the validation was successful and the property value changed as well.</returns>
  326. /// <exception cref="System.ArgumentNullException">Thrown if <paramref name="comparer"/> or <paramref name="propertyName"/> are <see langword="null"/>.</exception>
  327. [RequiresUnreferencedCode("The type of the current instance cannot be statically discovered.")]
  328. protected bool TrySetProperty<T>(ref T field, T newValue, IEqualityComparer<T> comparer, out IReadOnlyCollection<ValidationResult> errors, [CallerMemberName] string propertyName = null!)
  329. {
  330. ArgumentNullException.ThrowIfNull(comparer);
  331. ArgumentNullException.ThrowIfNull(propertyName);
  332. return TryValidateProperty(newValue, propertyName, out errors) &&
  333. SetProperty(ref field, newValue, comparer, propertyName);
  334. }
  335. /// <summary>
  336. /// Tries to validate a new value for a specified property. If the validation is successful,
  337. /// <see cref="ObservableObject.SetProperty{T}(T,T,Action{T},string?)"/> is called, otherwise no state change is performed.
  338. /// </summary>
  339. /// <typeparam name="T">The type of the property that changed.</typeparam>
  340. /// <param name="oldValue">The current property value.</param>
  341. /// <param name="newValue">The property's value after the change occurred.</param>
  342. /// <param name="callback">A callback to invoke to update the property value.</param>
  343. /// <param name="errors">The resulting validation errors, if any.</param>
  344. /// <param name="propertyName">(optional) The name of the property that changed.</param>
  345. /// <returns>Whether the validation was successful and the property value changed as well.</returns>
  346. /// <exception cref="System.ArgumentNullException">Thrown if <paramref name="callback"/> or <paramref name="propertyName"/> are <see langword="null"/>.</exception>
  347. [RequiresUnreferencedCode("The type of the current instance cannot be statically discovered.")]
  348. protected bool TrySetProperty<T>(T oldValue, T newValue, Action<T> callback, out IReadOnlyCollection<ValidationResult> errors, [CallerMemberName] string propertyName = null!)
  349. {
  350. ArgumentNullException.ThrowIfNull(callback);
  351. ArgumentNullException.ThrowIfNull(propertyName);
  352. return TryValidateProperty(newValue, propertyName, out errors) &&
  353. SetProperty(oldValue, newValue, callback, propertyName);
  354. }
  355. /// <summary>
  356. /// Tries to validate a new value for a specified property. If the validation is successful,
  357. /// <see cref="ObservableObject.SetProperty{T}(T,T,IEqualityComparer{T},Action{T},string?)"/> is called, otherwise no state change is performed.
  358. /// </summary>
  359. /// <typeparam name="T">The type of the property that changed.</typeparam>
  360. /// <param name="oldValue">The current property value.</param>
  361. /// <param name="newValue">The property's value after the change occurred.</param>
  362. /// <param name="comparer">The <see cref="IEqualityComparer{T}"/> instance to use to compare the input values.</param>
  363. /// <param name="callback">A callback to invoke to update the property value.</param>
  364. /// <param name="errors">The resulting validation errors, if any.</param>
  365. /// <param name="propertyName">(optional) The name of the property that changed.</param>
  366. /// <returns>Whether the validation was successful and the property value changed as well.</returns>
  367. /// <exception cref="System.ArgumentNullException">Thrown if <paramref name="comparer"/>, <paramref name="callback"/> or <paramref name="propertyName"/> are <see langword="null"/>.</exception>
  368. [RequiresUnreferencedCode("The type of the current instance cannot be statically discovered.")]
  369. protected bool TrySetProperty<T>(T oldValue, T newValue, IEqualityComparer<T> comparer, Action<T> callback, out IReadOnlyCollection<ValidationResult> errors, [CallerMemberName] string propertyName = null!)
  370. {
  371. ArgumentNullException.ThrowIfNull(comparer);
  372. ArgumentNullException.ThrowIfNull(callback);
  373. ArgumentNullException.ThrowIfNull(propertyName);
  374. return TryValidateProperty(newValue, propertyName, out errors) &&
  375. SetProperty(oldValue, newValue, comparer, callback, propertyName);
  376. }
  377. /// <summary>
  378. /// Tries to validate a new value for a specified property. If the validation is successful,
  379. /// <see cref="ObservableObject.SetProperty{TModel,T}(T,T,TModel,Action{TModel,T},string?)"/> is called, otherwise no state change is performed.
  380. /// </summary>
  381. /// <typeparam name="TModel">The type of model whose property (or field) to set.</typeparam>
  382. /// <typeparam name="T">The type of property (or field) to set.</typeparam>
  383. /// <param name="oldValue">The current property value.</param>
  384. /// <param name="newValue">The property's value after the change occurred.</param>
  385. /// <param name="model">The model </param>
  386. /// <param name="callback">The callback to invoke to set the target property value, if a change has occurred.</param>
  387. /// <param name="errors">The resulting validation errors, if any.</param>
  388. /// <param name="propertyName">(optional) The name of the property that changed.</param>
  389. /// <returns>Whether the validation was successful and the property value changed as well.</returns>
  390. /// <exception cref="System.ArgumentNullException">Thrown if <paramref name="model"/>, <paramref name="callback"/> or <paramref name="propertyName"/> are <see langword="null"/>.</exception>
  391. [RequiresUnreferencedCode("The type of the current instance cannot be statically discovered.")]
  392. protected bool TrySetProperty<TModel, T>(T oldValue, T newValue, TModel model, Action<TModel, T> callback, out IReadOnlyCollection<ValidationResult> errors, [CallerMemberName] string propertyName = null!)
  393. where TModel : class
  394. {
  395. ArgumentNullException.ThrowIfNull(model);
  396. ArgumentNullException.ThrowIfNull(callback);
  397. ArgumentNullException.ThrowIfNull(propertyName);
  398. return TryValidateProperty(newValue, propertyName, out errors) &&
  399. SetProperty(oldValue, newValue, model, callback, propertyName);
  400. }
  401. /// <summary>
  402. /// Tries to validate a new value for a specified property. If the validation is successful,
  403. /// <see cref="ObservableObject.SetProperty{TModel,T}(T,T,IEqualityComparer{T},TModel,Action{TModel,T},string?)"/> is called, otherwise no state change is performed.
  404. /// </summary>
  405. /// <typeparam name="TModel">The type of model whose property (or field) to set.</typeparam>
  406. /// <typeparam name="T">The type of property (or field) to set.</typeparam>
  407. /// <param name="oldValue">The current property value.</param>
  408. /// <param name="newValue">The property's value after the change occurred.</param>
  409. /// <param name="comparer">The <see cref="IEqualityComparer{T}"/> instance to use to compare the input values.</param>
  410. /// <param name="model">The model </param>
  411. /// <param name="callback">The callback to invoke to set the target property value, if a change has occurred.</param>
  412. /// <param name="errors">The resulting validation errors, if any.</param>
  413. /// <param name="propertyName">(optional) The name of the property that changed.</param>
  414. /// <returns>Whether the validation was successful and the property value changed as well.</returns>
  415. /// <exception cref="System.ArgumentNullException">Thrown if <paramref name="comparer"/>, <paramref name="model"/>, <paramref name="callback"/> or <paramref name="propertyName"/> are <see langword="null"/>.</exception>
  416. [RequiresUnreferencedCode("The type of the current instance cannot be statically discovered.")]
  417. protected bool TrySetProperty<TModel, T>(T oldValue, T newValue, IEqualityComparer<T> comparer, TModel model, Action<TModel, T> callback, out IReadOnlyCollection<ValidationResult> errors, [CallerMemberName] string propertyName = null!)
  418. where TModel : class
  419. {
  420. ArgumentNullException.ThrowIfNull(comparer);
  421. ArgumentNullException.ThrowIfNull(model);
  422. ArgumentNullException.ThrowIfNull(callback);
  423. ArgumentNullException.ThrowIfNull(propertyName);
  424. return TryValidateProperty(newValue, propertyName, out errors) &&
  425. SetProperty(oldValue, newValue, comparer, model, callback, propertyName);
  426. }
  427. /// <summary>
  428. /// Clears the validation errors for a specified property or for the entire entity.
  429. /// </summary>
  430. /// <param name="propertyName">
  431. /// The name of the property to clear validation errors for.
  432. /// If a <see langword="null"/> or empty name is used, all entity-level errors will be cleared.
  433. /// </param>
  434. protected void ClearErrors(string? propertyName = null)
  435. {
  436. // Clear entity-level errors when the target property is null or empty
  437. if (string.IsNullOrEmpty(propertyName))
  438. {
  439. ClearAllErrors();
  440. }
  441. else
  442. {
  443. ClearErrorsForProperty(propertyName!);
  444. }
  445. }
  446. /// <inheritdoc cref="INotifyDataErrorInfo.GetErrors(string)"/>
  447. public IEnumerable<ValidationResult> GetErrors(string? propertyName = null)
  448. {
  449. // Get entity-level errors when the target property is null or empty
  450. if (string.IsNullOrEmpty(propertyName))
  451. {
  452. // Local function to gather all the entity-level errors
  453. [MethodImpl(MethodImplOptions.NoInlining)]
  454. IEnumerable<ValidationResult> GetAllErrors()
  455. {
  456. return this.errors.Values.SelectMany(static errors => errors);
  457. }
  458. return GetAllErrors();
  459. }
  460. // Property-level errors, if any
  461. if (this.errors.TryGetValue(propertyName!, out List<ValidationResult>? errors))
  462. {
  463. return errors;
  464. }
  465. // The INotifyDataErrorInfo.GetErrors method doesn't specify exactly what to
  466. // return when the input property name is invalid, but given that the return
  467. // type is marked as a non-nullable reference type, here we're returning an
  468. // empty array to respect the contract. This also matches the behavior of
  469. // this method whenever errors for a valid properties are retrieved.
  470. return Array.Empty<ValidationResult>();
  471. }
  472. /// <inheritdoc/>
  473. IEnumerable INotifyDataErrorInfo.GetErrors(string? propertyName) => GetErrors(propertyName);
  474. /// <summary>
  475. /// Validates all the properties in the current instance and updates all the tracked errors.
  476. /// If any changes are detected, the <see cref="ErrorsChanged"/> event will be raised.
  477. /// </summary>
  478. /// <remarks>
  479. /// Only public instance properties (excluding custom indexers) that have at least one
  480. /// <see cref="ValidationAttribute"/> applied to them will be validated. All other
  481. /// members in the current instance will be ignored. None of the processed properties
  482. /// will be modified - they will only be used to retrieve their values and validate them.
  483. /// </remarks>
  484. [RequiresUnreferencedCode(
  485. "This method requires the generated CommunityToolkit.Mvvm.ComponentModel.__Internals.__ObservableValidatorExtensions type not to be removed to use the fast path. " +
  486. "If this type is removed by the linker, or if the target recipient was created dynamically and was missed by the source generator, a slower fallback " +
  487. "path using a compiled LINQ expression will be used. This will have more overhead in the first invocation of this method for any given recipient type. " +
  488. "Additionally, due to the usage of validation APIs, the type of the current instance cannot be statically discovered.")]
  489. protected void ValidateAllProperties()
  490. {
  491. // Fast path that tries to create a delegate from a generated type-specific method. This
  492. // is used to make this method more AOT-friendly and faster, as there is no dynamic code.
  493. [RequiresUnreferencedCode("The type of the current instance cannot be statically discovered.")]
  494. static Action<object> GetValidationAction(Type type)
  495. {
  496. if (type.Assembly.GetType("CommunityToolkit.Mvvm.ComponentModel.__Internals.__ObservableValidatorExtensions") is Type extensionsType &&
  497. extensionsType.GetMethod("CreateAllPropertiesValidator", new[] { type }) is MethodInfo methodInfo)
  498. {
  499. return (Action<object>)methodInfo.Invoke(null, new object?[] { null })!;
  500. }
  501. return GetValidationActionFallback(type);
  502. }
  503. // Fallback method to create the delegate with a compiled LINQ expression
  504. static Action<object> GetValidationActionFallback(Type type)
  505. {
  506. // Get the collection of all properties to validate
  507. (string Name, MethodInfo GetMethod)[] validatableProperties = (
  508. from property in type.GetProperties(BindingFlags.Instance | BindingFlags.Public)
  509. where property.GetIndexParameters().Length == 0 &&
  510. property.GetCustomAttributes<ValidationAttribute>(true).Any()
  511. let getMethod = property.GetMethod
  512. where getMethod is not null
  513. select (property.Name, getMethod)).ToArray();
  514. // Short path if there are no properties to validate
  515. if (validatableProperties.Length == 0)
  516. {
  517. return static _ => { };
  518. }
  519. // MyViewModel inst0 = (MyViewModel)arg0;
  520. ParameterExpression arg0 = Expression.Parameter(typeof(object));
  521. UnaryExpression inst0 = Expression.Convert(arg0, type);
  522. // Get a reference to ValidateProperty(object, string)
  523. MethodInfo validateMethod = typeof(ObservableValidator).GetMethod(nameof(ValidateProperty), BindingFlags.Instance | BindingFlags.NonPublic)!;
  524. // We want a single compiled LINQ expression that validates all properties in the
  525. // actual type of the executing viewmodel at once. We do this by creating a block
  526. // expression with the unrolled invocations of all properties to validate.
  527. // Essentially, the body will contain the following code:
  528. // ===============================================================================
  529. // {
  530. // inst0.ValidateProperty(inst0.Property0, nameof(MyViewModel.Property0));
  531. // inst0.ValidateProperty(inst0.Property1, nameof(MyViewModel.Property1));
  532. // ...
  533. // inst0.ValidateProperty(inst0.PropertyN, nameof(MyViewModel.PropertyN));
  534. // }
  535. // ===============================================================================
  536. // We also add an explicit object conversion to represent boxing, if a given property
  537. // is a value type. It will just be a no-op if the value is a reference type already.
  538. // Note that this generated code is technically accessing a protected method from
  539. // ObservableValidator externally, but that is fine because IL doesn't really have
  540. // a concept of member visibility, that's purely a C# build-time feature.
  541. BlockExpression body = Expression.Block(
  542. from property in validatableProperties
  543. select Expression.Call(inst0, validateMethod, new Expression[]
  544. {
  545. Expression.Convert(Expression.Call(inst0, property.GetMethod), typeof(object)),
  546. Expression.Constant(property.Name)
  547. }));
  548. return Expression.Lambda<Action<object>>(body, arg0).Compile();
  549. }
  550. // Get or compute the cached list of properties to validate. Here we're using a static lambda to ensure the
  551. // delegate is cached by the C# compiler, see the related issue at https://github.com/dotnet/roslyn/issues/5835.
  552. EntityValidatorMap.GetValue(
  553. GetType(),
  554. [RequiresUnreferencedCode("The type of the current instance cannot be statically discovered.")] static (t) => GetValidationAction(t))(this);
  555. }
  556. /// <summary>
  557. /// Validates a property with a specified name and a given input value.
  558. /// If any changes are detected, the <see cref="ErrorsChanged"/> event will be raised.
  559. /// </summary>
  560. /// <param name="value">The value to test for the specified property.</param>
  561. /// <param name="propertyName">The name of the property to validate.</param>
  562. /// <exception cref="ArgumentNullException">Thrown when <paramref name="propertyName"/> is <see langword="null"/>.</exception>
  563. [RequiresUnreferencedCode("The type of the current instance cannot be statically discovered.")]
  564. protected internal void ValidateProperty(object? value, [CallerMemberName] string propertyName = null!)
  565. {
  566. ArgumentNullException.ThrowIfNull(propertyName);
  567. // Check if the property had already been previously validated, and if so retrieve
  568. // the reusable list of validation errors from the errors dictionary. This list is
  569. // used to add new validation errors below, if any are produced by the validator.
  570. // If the property isn't present in the dictionary, add it now to avoid allocations.
  571. if (!this.errors.TryGetValue(propertyName, out List<ValidationResult>? propertyErrors))
  572. {
  573. propertyErrors = new List<ValidationResult>();
  574. this.errors.Add(propertyName, propertyErrors);
  575. }
  576. bool errorsChanged = false;
  577. // Clear the errors for the specified property, if any
  578. if (propertyErrors.Count > 0)
  579. {
  580. propertyErrors.Clear();
  581. errorsChanged = true;
  582. }
  583. // Validate the property, by adding new errors to the existing list
  584. this.validationContext.MemberName = propertyName;
  585. this.validationContext.DisplayName = GetDisplayNameForProperty(propertyName);
  586. bool isValid = Validator.TryValidateProperty(value, this.validationContext, propertyErrors);
  587. // Update the shared counter for the number of errors, and raise the
  588. // property changed event if necessary. We decrement the number of total
  589. // errors if the current property is valid but it wasn't so before this
  590. // validation, and we increment it if the validation failed after being
  591. // correct before. The property changed event is raised whenever the
  592. // number of total errors is either decremented to 0, or incremented to 1.
  593. if (isValid)
  594. {
  595. if (errorsChanged)
  596. {
  597. this.totalErrors--;
  598. if (this.totalErrors == 0)
  599. {
  600. OnPropertyChanged(HasErrorsChangedEventArgs);
  601. }
  602. }
  603. }
  604. else if (!errorsChanged)
  605. {
  606. this.totalErrors++;
  607. if (this.totalErrors == 1)
  608. {
  609. OnPropertyChanged(HasErrorsChangedEventArgs);
  610. }
  611. }
  612. // Only raise the event once if needed. This happens either when the target property
  613. // had existing errors and is now valid, or if the validation has failed and there are
  614. // new errors to broadcast, regardless of the previous validation state for the property.
  615. if (errorsChanged || !isValid)
  616. {
  617. ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(propertyName));
  618. }
  619. }
  620. /// <summary>
  621. /// Tries to validate a property with a specified name and a given input value, and returns
  622. /// the computed errors, if any. If the property is valid, it is assumed that its value is
  623. /// about to be set in the current object. Otherwise, no observable local state is modified.
  624. /// </summary>
  625. /// <param name="value">The value to test for the specified property.</param>
  626. /// <param name="propertyName">The name of the property to validate.</param>
  627. /// <param name="errors">The resulting validation errors, if any.</param>
  628. [RequiresUnreferencedCode("The type of the current instance cannot be statically discovered.")]
  629. private bool TryValidateProperty(object? value, string propertyName, out IReadOnlyCollection<ValidationResult> errors)
  630. {
  631. // Add the cached errors list for later use.
  632. if (!this.errors.TryGetValue(propertyName!, out List<ValidationResult>? propertyErrors))
  633. {
  634. propertyErrors = new List<ValidationResult>();
  635. this.errors.Add(propertyName!, propertyErrors);
  636. }
  637. bool hasErrors = propertyErrors.Count > 0;
  638. List<ValidationResult> localErrors = new();
  639. // Validate the property, by adding new errors to the local list
  640. this.validationContext.MemberName = propertyName;
  641. this.validationContext.DisplayName = GetDisplayNameForProperty(propertyName!);
  642. bool isValid = Validator.TryValidateProperty(value, this.validationContext, localErrors);
  643. // We only modify the state if the property is valid and it wasn't so before. In this case, we
  644. // clear the cached list of errors (which is visible to consumers) and raise the necessary events.
  645. if (isValid && hasErrors)
  646. {
  647. propertyErrors.Clear();
  648. this.totalErrors--;
  649. if (this.totalErrors == 0)
  650. {
  651. OnPropertyChanged(HasErrorsChangedEventArgs);
  652. }
  653. ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(propertyName));
  654. }
  655. errors = localErrors;
  656. return isValid;
  657. }
  658. /// <summary>
  659. /// Clears all the current errors for the entire entity.
  660. /// </summary>
  661. private void ClearAllErrors()
  662. {
  663. if (this.totalErrors == 0)
  664. {
  665. return;
  666. }
  667. // Clear the errors for all properties with at least one error, and raise the
  668. // ErrorsChanged event for those properties. Other properties will be ignored.
  669. foreach (KeyValuePair<string, List<ValidationResult>> propertyInfo in this.errors)
  670. {
  671. bool hasErrors = propertyInfo.Value.Count > 0;
  672. propertyInfo.Value.Clear();
  673. if (hasErrors)
  674. {
  675. ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(propertyInfo.Key));
  676. }
  677. }
  678. this.totalErrors = 0;
  679. OnPropertyChanged(HasErrorsChangedEventArgs);
  680. }
  681. /// <summary>
  682. /// Clears all the current errors for a target property.
  683. /// </summary>
  684. /// <param name="propertyName">The name of the property to clear errors for.</param>
  685. private void ClearErrorsForProperty(string propertyName)
  686. {
  687. if (!this.errors.TryGetValue(propertyName!, out List<ValidationResult>? propertyErrors) ||
  688. propertyErrors.Count == 0)
  689. {
  690. return;
  691. }
  692. propertyErrors.Clear();
  693. this.totalErrors--;
  694. if (this.totalErrors == 0)
  695. {
  696. OnPropertyChanged(HasErrorsChangedEventArgs);
  697. }
  698. ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(propertyName));
  699. }
  700. /// <summary>
  701. /// Gets the display name for a given property. It could be a custom name or just the property name.
  702. /// </summary>
  703. /// <param name="propertyName">The target property name being validated.</param>
  704. /// <returns>The display name for the property.</returns>
  705. [RequiresUnreferencedCode("The type of the current instance cannot be statically discovered.")]
  706. private string GetDisplayNameForProperty(string propertyName)
  707. {
  708. static Dictionary<string, string> GetDisplayNames(Type type)
  709. {
  710. Dictionary<string, string> displayNames = new();
  711. foreach (PropertyInfo property in type.GetProperties(BindingFlags.Instance | BindingFlags.Public))
  712. {
  713. if (property.GetCustomAttribute<DisplayAttribute>() is DisplayAttribute attribute &&
  714. attribute.GetName() is string displayName)
  715. {
  716. displayNames.Add(property.Name, displayName);
  717. }
  718. }
  719. return displayNames;
  720. }
  721. // This method replicates the logic of DisplayName and GetDisplayName from the
  722. // ValidationContext class. See the original source in the BCL for more details.
  723. _ = DisplayNamesMap.GetValue(GetType(), static t => GetDisplayNames(t)).TryGetValue(propertyName, out string? displayName);
  724. return displayName ?? propertyName;
  725. }
  726. }