protected ValidationContext CreateNewValidationContextForChildValidator(object instanceToValidate, PropertyValidatorContext propertyValidatorContext, IValidatorSelector validatorSelector) { var propertyChain = new PropertyChain(propertyValidatorContext.PropertyChain); propertyChain.Add(propertyValidatorContext.Member); return new ValidationContext(instanceToValidate, propertyChain, validatorSelector); }
public void Should_not_be_subchain() { chain.Add("Foo"); var otherChain = new PropertyChain(); otherChain.Add("Bar"); otherChain.IsChildChainOf(chain).ShouldBeFalse(); }
public void Should_be_subchain() { chain.Add("Parent"); chain.Add("Child"); var childChain = new PropertyChain(chain); childChain.Add("Grandchild"); childChain.IsChildChainOf(chain).ShouldBeTrue(); }
public PropertyChainTester() { PropertyInfo top = ReflectionHelper.GetProperty<Target>(x => x.Child); PropertyInfo second = ReflectionHelper.GetProperty<ChildTarget>(x => x.GrandChild); PropertyInfo birthday = ReflectionHelper.GetProperty<GrandChildTarget>(x => x.BirthDay); _chain = new PropertyChain(new[] { new PropertyValueGetter(top), new PropertyValueGetter(second), new PropertyValueGetter(birthday), }); }
public void ToString_GivenPropertyChain_ReturnsAsExpected() { // Setup var fixture = new Ploeh.AutoFixture.Fixture ().Customize ( new AutoMoqCustomization () ); var parentPropertyName = fixture.CreateAnonymous<string> (); var childPropertyName = fixture.CreateAnonymous<string> (); var propertyChainList = new List<string> { parentPropertyName, childPropertyName }; var sut = new PropertyChain ( propertyChainList ); // Exercise var str = sut.ToString (); // Verify Assert.AreEqual(parentPropertyName+"."+childPropertyName, str); }
public void Enrich(HtmlConventionsPreviewContext context, HtmlConventionsPreviewViewModel model) { var examples = new List<PropertyExample>(); var tagGenerator = _generatorFactory.GeneratorFor(context.ModelType); tagGenerator.SetModel(context.Instance); _populator.PopulateInstance(context.Instance, context.SimpleProperties()); context .SimpleProperties() .Each(prop => { Accessor property; if(context.PropertyChain.Any()) { property = new PropertyChain(context .PropertyChain .Concat<PropertyInfo>(new[] {prop}) .Select(x => new PropertyValueGetter(x)) .ToArray()); } else { property = new SingleProperty(prop); } var propertyExpression = "x => x." + property.PropertyNames.Join("."); var propertySource = _sourceGenerator.SourceFor(prop); var propExamples = new List<Example>(); propExamples.Add(createExample(tagGenerator.LabelFor(tagGenerator.GetRequest(property)), "LabelFor({0})".ToFormat(propertyExpression))); propExamples.Add(createExample( tagGenerator.DisplayFor(tagGenerator.GetRequest(property)), "DisplayFor({0})".ToFormat(propertyExpression))); propExamples.Add(createExample(tagGenerator.InputFor(tagGenerator.GetRequest(property)), "InputFor({0})".ToFormat(propertyExpression))); var propExample = new PropertyExample { Source = propertySource, Examples = propExamples }; examples.Add(propExample); }); model.Examples = examples; }
public override IEnumerable<ValidationFailure> Validate(PropertyValidatorContext context) { if (context.Member == null) { throw new InvalidOperationException(string.Format("Nested validators can only be used with Member Expressions.")); } var collection = context.PropertyValue as IEnumerable; if (collection == null) { yield break; } int count = 0; foreach (var element in collection) { if(element == null) { // If an element in the validator is null then we want to skip it to prevent NullReferenceExceptions in the child validator. // We still need to update the counter to ensure the indexes are correct. count++; continue; } var childPropertyChain = new PropertyChain(context.PropertyChain); childPropertyChain.Add(context.Member); childPropertyChain.AddIndexer(count++); //The ValidatorSelector should not be propogated downwards. //If this collection property has been selected for validation, then all properties on those items should be validated. var newContext = new ValidationContext(element, childPropertyChain, new DefaultValidatorSelector()); var results = childValidator.Validate(newContext).Errors; foreach (var result in results) { yield return result; } } }
public PropertyChainTests() { chain = new PropertyChain(); }
public void SetUp() { PropertyInfo top = ReflectionHelper.GetProperty<Target>(x => x.Child); PropertyInfo second = ReflectionHelper.GetProperty<ChildTarget>(x => x.GrandChild); PropertyInfo birthday = ReflectionHelper.GetProperty<GrandChildTarget>(x => x.BirthDay); _chain = new PropertyChain(new[] {top, second, birthday}); }
public ValidationContext(T instanceToValidate, PropertyChain propertyChain, IValidatorSelector validatorSelector) : base(instanceToValidate, propertyChain, validatorSelector) { InstanceToValidate = instanceToValidate; }
public void Setup() { chain = new PropertyChain(); }
public DateAfterTodayRule(PropertyChain propertyChain) { _propertyChain = propertyChain; }
public EmailAddressRule(PropertyChain propertyChain) { _propertyChain = propertyChain; _validator = new EmailValidator(); }
/// <summary> /// Creates a new validation context with a custom property chain and selector /// </summary> /// <param name="instanceToValidate"></param> /// <param name="propertyChain"></param> /// <param name="validatorSelector"></param> public ValidationContext(T instanceToValidate, PropertyChain propertyChain, IValidatorSelector validatorSelector) { PropertyChain = new PropertyChain(propertyChain); InstanceToValidate = instanceToValidate; Selector = validatorSelector; }
/// <summary> /// Creates a new validation context with a custom property chain and selector /// </summary> /// <param name="instanceToValidate"></param> /// <param name="propertyChain"></param> /// <param name="validatorSelector"></param> public ValidationContext(T instanceToValidate, PropertyChain propertyChain, IValidatorSelector validatorSelector) : this(instanceToValidate, propertyChain, validatorSelector, new List <ValidationFailure>(), ValidatorOptions.Global.MessageFormatterFactory()) { }
public MaximumLengthRequiredRule(PropertyChain propertyChain, int length) { _propertyChain = propertyChain; _length = length; }
private ValidationContext <T> CreateContextForRulesToAplyOnValidate(T instance, PropertyChain propertychain = null) { var selector = new RulesetValidatorSelector(RulesToAplyOnValidate.ToArray()); var context = new ValidationContext <T>(instance, new PropertyChain(), selector); return(context); }
public static ValidationResult For <T> (this ValidationResult validationResult, Expression <Func <T, object?> > property) { return(validationResult.For(PropertyChain.FromExpression(property).ToString( ), true)); }
public static ValidationResult For <T> (this ValidationResult validationResult, params Expression <Func <T, object?> > [] properties) { return(validationResult.For(properties.Select(property => PropertyChain.FromExpression(property).ToString( )).ToArray( ), true)); }
private ScimValidationContext(T instanceToValidate, PropertyChain propertyChain, IValidatorSelector validatorSelector) : base(instanceToValidate, propertyChain, validatorSelector) { }
public PropertyExpressionToken AllButLast(out string lastName) { lastName = PropertyChain.Last().StringValue; return(new PropertyExpressionToken(PropertyChain.Take(PropertyChain.Length - 1).ToArray(), StartIndex)); }
public string ToInternalString() => string.Join(" ", PropertyChain.Select(x => x.ToString()));
private async Task <bool> ValidateInternal <TCustomState>(IDictionary <string, object> arguments, OnValidationErrorDelegate <TCustomState> onError, CancellationToken cancellationToken, bool runAsync, TCustomState state) { if (null == arguments) { throw new ArgumentNullException(nameof(arguments)); } if (null == onError) { throw new ArgumentNullException(nameof(onError)); } bool hasErrors = false; foreach (var arg in arguments.Where(arg => arg.Value != null && !(arg.Value.GetType().IsPrimitive || arg.Value is string))) { var validator = _factory.GetValidator(arg.Value.GetType()); if (null == validator) { continue; } ValidationResult result; try { if (runAsync) { result = await validator.ValidateAsync(arg.Value, cancellationToken); } else { result = validator.Validate(arg.Value); } if (arg.Value != null && arg.Value.GetType().IsArray) { Array array = (Array)arg.Value; for (int i = 0; i < array.Length; ++i) { var obj = array.GetValue(i); if (null != obj) { var itemValidator = _factory.GetValidator(obj.GetType()); var propertyChain = new PropertyChain(new[] { "Item" }); propertyChain.AddIndexer(i); var ctx = new ValidationContext( obj, propertyChain, ValidatorOptions.ValidatorSelectors.DefaultValidatorSelectorFactory()); ValidationResult localResult; if (runAsync) { localResult = await itemValidator.ValidateAsync(ctx, cancellationToken); } else { localResult = itemValidator.Validate(ctx); } if (result == null) { result = localResult; } if (!localResult.IsValid) { foreach (var failure in localResult.Errors) { result.Errors.Add(failure); } } } } } } catch (ValidationException err) { var failures = err.Errors.Select(p => new ValidationFailure(p.PropertyName, p.ErrorMessage)); result = new ValidationResult(failures); } catch (Exception err) { var failures = new[] { new ValidationFailure(arg.Key, err.Message) }; result = new ValidationResult(failures); } if (result.IsValid) { continue; } hasErrors = true; foreach (var group in result.Errors.GroupBy(p => p.PropertyName, StringComparer.OrdinalIgnoreCase)) { onError($"{arg.Key}.{group.Key}", group.ToArray(), state); } } return(hasErrors); }