Advertisement
Guest User

Untitled

a guest
Apr 26th, 2017
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.77 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Linq;
  5. using System.Runtime.CompilerServices;
  6. using FluentValidation;
  7. using FluentValidation.Attributes;
  8. using FluentValidation.Results;
  9.  
  10.  
  11. namespace aluTransport.App
  12. {
  13. public class ValidatableBindableBase : BindableBase, INotifyDataErrorInfo
  14. {
  15. private IValidator Validator => new AttributedValidatorFactory().GetValidator(GetType());
  16.  
  17. private readonly Dictionary<string, List<string>> _errors = new Dictionary<string, List<string>>();
  18.  
  19. public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged = delegate { };
  20.  
  21. public System.Collections.IEnumerable GetErrors(string propertyName)
  22. {
  23. if (propertyName == null) return null;
  24. if (_errors.ContainsKey(propertyName))
  25. return _errors[propertyName];
  26. else
  27. return null;
  28. }
  29.  
  30. //public IList<string> GetAllErrors()
  31. //{
  32. // return _errors.SelectMany(err=> err.Value).ToList();
  33. //}
  34.  
  35. public bool HasErrors => _errors.Count > 0;
  36.  
  37. protected override void SetProperty<T>(ref T member, T val, [CallerMemberName] string propertyName = null)
  38. {
  39. //
  40. base.SetProperty<T>(ref member, val, propertyName);
  41. ValidateProperty(propertyName, val);
  42. }
  43.  
  44. private void ValidateProperty<T>(string propertyName, T value)
  45. {
  46. ValidationResult results = Validator?.Validate(this);
  47.  
  48. if (results == null) return;
  49.  
  50. bool validationSucceeded = results.IsValid;
  51. IList<ValidationFailure> failures = results.Errors;
  52.  
  53. if (!validationSucceeded)
  54. {
  55.  
  56. _errors[propertyName] = failures.Where(p=>p.PropertyName == propertyName).Select(c => c.ErrorMessage).ToList();
  57. }
  58. else
  59. {
  60. _errors.Remove(propertyName);
  61. }
  62. ErrorsChanged(this, new DataErrorsChangedEventArgs(propertyName));
  63. }
  64.  
  65. public void ValidateAll()
  66. {
  67. ValidationResult results = Validator?.Validate(this);
  68.  
  69. if (results == null) return;
  70.  
  71. bool validationSucceeded = results.IsValid;
  72. IList<ValidationFailure> failures = results.Errors;
  73.  
  74. if (!validationSucceeded)
  75. {
  76. _errors.Clear();
  77. foreach (var validationFailure in failures)
  78. {
  79. _errors[validationFailure.PropertyName] = failures.Where(p => p.PropertyName == validationFailure.PropertyName).Select(c => c.ErrorMessage).ToList();
  80. ErrorsChanged(this, new DataErrorsChangedEventArgs(validationFailure.PropertyName));
  81. }
  82. }
  83. }
  84.  
  85. }
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement