main
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Linq.Expressions;
5using gorilla.utility;
6
7namespace solidware.financials.windows.ui.presenters.validation
8{
9 public class Notification<T> : INotification<T>
10 {
11 public void Register<Severity>(Expression<Func<T, object>> property, Func<bool> failCondition, Func<string> errorMessage) where Severity : validation.Severity, new()
12 {
13 Register(property, new AnonymousRule<Severity>(failCondition, errorMessage));
14 }
15
16 public void Register(Expression<Func<T, object>> property, Rule rule)
17 {
18 EnsureRulesAreInitializeFor(property);
19 validationRules[property.pick_property().Name].Add(rule);
20 }
21
22 public string this[Expression<Func<T, object>> property]
23 {
24 get { return this[property.pick_property().Name]; }
25 }
26
27 public string this[string propertyName]
28 {
29 get
30 {
31 if (!validationRules.ContainsKey(propertyName)) return null;
32 var validationRulesForProperty = validationRules[propertyName];
33 return validationRulesForProperty.Any(x => x.IsViolated())
34 ? BuildErrorsFor(validationRulesForProperty)
35 : null;
36 }
37 }
38
39 public string Error
40 {
41 get { throw new NotImplementedException(); }
42 }
43
44 public bool AreAnyRulesViolatedAndMoreSevereThan<Severity>() where Severity : validation.Severity, new()
45 {
46 return validationRules.Any(validationRule => validationRule.Value.Any(x => x.IsViolatedAndMoreSevereThan<Severity>()));
47 }
48
49 void EnsureRulesAreInitializeFor(Expression<Func<T, object>> property)
50 {
51 if (!validationRules.ContainsKey(property.pick_property().Name))
52 validationRules[property.pick_property().Name] = new List<Rule>();
53 }
54
55 string BuildErrorsFor(IEnumerable<Rule> validationRulesForProperty)
56 {
57 var errors = new List<string>();
58 validationRulesForProperty.each(x =>
59 {
60 if (x.IsViolated()) errors.Add(x.ErrorMessage);
61 });
62 return string.Join(Environment.NewLine, errors.ToArray());
63 }
64
65 IDictionary<string, IList<Rule>> validationRules = new Dictionary<string, IList<Rule>>();
66 }
67}