Пример #1
0
        private static Validator CreateValidator(Type targetType, string ruleset, IConfigurationSource configurationSource, bool cacheValidator)
        {
            Validator wrapperValidator = null;

            if (cacheValidator)
            {
                lock (attributeAndDefaultConfigurationValidatorsCacheLock)
                {
                    ValidatorCacheKey key = new ValidatorCacheKey(targetType, ruleset, false);

                    Validator cachedValidator;
                    if (attributeAndDefaultConfigurationValidatorsCache.TryGetValue(key, out cachedValidator))
                    {
                        return(cachedValidator);
                    }

                    Validator validator = new AndCompositeValidator(InnerCreateValidatorFromAttributes(targetType, ruleset),
                                                                    InnerCreateValidatorFromConfiguration(targetType, ruleset, configurationSource));
                    wrapperValidator = WrapAndInstrumentValidator(validator, configurationSource);

                    attributeAndDefaultConfigurationValidatorsCache[key] = wrapperValidator;
                }
            }
            else
            {
                Validator validator = new AndCompositeValidator(InnerCreateValidatorFromAttributes(targetType, ruleset),
                                                                InnerCreateValidatorFromConfiguration(targetType, ruleset, configurationSource));
                wrapperValidator = WrapAndInstrumentValidator(validator, configurationSource);
            }

            return(wrapperValidator);
        }
        public void ValidationRequestWithNullSuppliedValidationResultsThrows()
        {
            Validator validator = new AndCompositeValidator();
            string    target    = new string('a', 10); // just any string, but a new one

            validator.Validate(target, null);
        }
        protected virtual Validator DoGetValidator()
        {
            Validator validator;

            if (this.valueValidators.Count == 1)
            {
                validator = this.valueValidators[0];
            }
            else if (this.validatedElement.CompositionType == CompositionType.And)
            {
                validator = new AndCompositeValidator(this.valueValidators.ToArray());
            }
            else
            {
                validator = new OrCompositeValidator(this.valueValidators.ToArray())
                {
                    MessageTemplate = this.validatedElement.CompositionMessageTemplate,
                    Tag             = this.validatedElement.CompositionTag
                };
            }
            if (this.validatedElement.IgnoreNulls)
            {
                return(new OrCompositeValidator(new Validator[] { new NotNullValidator(true), validator })
                {
                    MessageTemplate = (this.validatedElement.IgnoreNullsMessageTemplate != null) ? this.validatedElement.IgnoreNullsMessageTemplate : Resources.IgnoreNullsDefaultMessageTemplate, Tag = this.validatedElement.IgnoreNullsTag
                });
            }
            return(validator);
        }
Пример #4
0
        /// <summary>
        /// Creates the composite validator built by the builder.
        /// </summary>
        protected virtual Validator DoGetValidator()
        {
            // create appropriate composite validator
            Validator compositeValidator;

            if (CompositionType.And == this.validatedElement.CompositionType)
            {
                compositeValidator = new AndCompositeValidator(this.valueValidators.ToArray());
            }
            else
            {
                compositeValidator = new OrCompositeValidator(this.valueValidators.ToArray());
                compositeValidator.MessageTemplate = this.validatedElement.CompositionMessageTemplate;
                compositeValidator.Tag             = this.validatedElement.CompositionTag;
            }
            // add support for ignoring nulls
            Validator valueValidator;

            if (this.validatedElement.IgnoreNulls)
            {
                valueValidator = new OrCompositeValidator(new NotNullValidator(true), compositeValidator);
                valueValidator.MessageTemplate = this.validatedElement.IgnoreNullsMessageTemplate != null
                                        ? this.validatedElement.IgnoreNullsMessageTemplate
                                        : Resources.IgnoreNullsDefaultMessageTemplate;
                valueValidator.Tag = this.validatedElement.IgnoreNullsTag;
            }
            else
            {
                valueValidator = compositeValidator;
            }

            return(valueValidator);
        }
Пример #5
0
        internal static Validator GetPropertyValidator(Type type, PropertyInfo propertyInfo,
                                                       string ruleset, MemberAccessValidatorBuilderFactory memberAccessValidatorBuilderFactory)
        {
            Validator validator = null;

            lock (attributeAndDefaultConfigurationPropertyValidatorsCacheLock)
            {
                PropertyValidatorCacheKey key = new PropertyValidatorCacheKey(type, propertyInfo.Name, ruleset);

                if (!attributeAndDefaultConfigurationPropertyValidatorsCache.TryGetValue(key, out validator))
                {
                    Validator attributesValidator    = GetPropertyValidatorFromAttributes(type, propertyInfo, ruleset, memberAccessValidatorBuilderFactory);
                    Validator configurationValidator = GetPropertyValidatorFromConfiguration(type, propertyInfo, ruleset, memberAccessValidatorBuilderFactory);

                    if (null != attributesValidator && null != configurationValidator)
                    {
                        validator = new AndCompositeValidator(attributesValidator, configurationValidator);
                    }
                    else if (null != attributesValidator)
                    {
                        validator = attributesValidator;
                    }
                    else
                    {
                        validator = configurationValidator;
                    }

                    attributeAndDefaultConfigurationPropertyValidatorsCache[key] = validator;
                }
            }

            return(validator);
        }
        public void ReturnsSuccessIfAllValidatorsReturnSuccess()
        {
            MockValidator <string> subValidator1 = new MockValidator <string>(false, "validator1");
            MockValidator <string> subValidator2 = new MockValidator <string>(false, "validator2");
            MockValidator <string> subValidator3 = new MockValidator <string>(false, "validator3");
            Validator validator = new AndCompositeValidator(subValidator1, subValidator2, subValidator3);
            string    target    = new string('a', 10); // just any string, but a new one

            ValidationResults validationResults = validator.Validate(target);

            Assert.IsTrue(validationResults.IsValid);
            Assert.AreSame(target, subValidator1.ValidatedTargets[0]);
            Assert.AreSame(target, subValidator2.ValidatedTargets[0]);
            Assert.AreSame(target, subValidator3.ValidatedTargets[0]);
        }
Пример #7
0
        public void GetValidatorTest()
        {
            Type      type         = typeof(Person);
            string    propertyName = "Name";                                            // TODO: Initialize to an appropriate value
            Validator expected     = new AndCompositeValidator(new NotNullValidator()); // TODO: Initialize to an appropriate value
            Validator actual;

            actual = ReflcationClassProperty.GetValidator(type, propertyName);
            Assert.IsTrue(actual is AndCompositeValidator);
            var actualValidator = actual as AndCompositeValidator;
            var children        = new List <Validator>(actualValidator.ListValidator);

            Assert.IsTrue(children.Count == 1);
            Assert.IsTrue(children[0] is NotNullValidator);
        }
Пример #8
0
        public void TestMethod1()
        {
            Customer myCustomer = new Customer()
            {
                firstName = " A Name tat is too long for the validation"
            };

            Validator shortStringValidator = new AndCompositeValidator(new NotNullValidator(), new StringLengthValidator(1, 50));

            ValidationResults r = shortStringValidator.Validate(myCustomer.firstName);

            //ValidationResults r = Validation.Validate<Customer>(myCustomer);
            if (!r.IsValid)
            {
                throw new InvalidOperationException("Validation error found.");
            }
        }
Пример #9
0
        public IValidationResult Validate()
        {
            if (!IsOverriden)
            {
                //MS Validation
                Validator NotNullStringLengthValidator = new AndCompositeValidator(this.msNotNullValidator, this.msStringLengthValidator);

                ValidationResults valResults = NotNullStringLengthValidator.Validate(Customer.customerNumber);

                if (!valResults.IsValid) //if not valid
                {
                    RuleValidationResult = new MyValidationResult();
                    RuleValidationResult.ValidationMessageList.Add(new NullValidationMessage());
                }


                if (Customer.EmailList != null)
                {
                    //Some other Random Test Validation. RegexValidator in this case
                    Validator <string> emailAddresssValidator = new RegexValidator(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
                    valResults = emailAddresssValidator.Validate(Customer.EmailList.First());
                }
                else
                {
                    valResults = this.msNotNullValidator.Validate(Customer.EmailList);
                }

                //Holidays Own Validation

                //RuleValidationResult = valResults;

                if (valResults != null)
                {
                    RuleValidationResult = new MyValidationResult();

                    foreach (var varRes in valResults)
                    {
                        IValidationMessage val = new MSWrapperMessage(MessageTypes.Error, varRes.Message);
                        RuleValidationResult.ValidationMessageList.Add(val);
                    }
                }
            }

            return(RuleValidationResult);
        }
        private static bool CompositeHasValidators(Validator validator)
        {
            AndCompositeValidator andValidator = validator as AndCompositeValidator;

            if (andValidator != null)
            {
                return(((Validator[])andValidator.Validators).Length > 0);
            }

            OrCompositeValidator orValidator = validator as OrCompositeValidator;

            if (orValidator != null)
            {
                return(((Validator[])orValidator.Validators).Length > 0);
            }

            return(false);
        }
        public void ReturnsFailureAfterQueryingAllValidatorsIfOneValidatorReturnFailure()
        {
            MockValidator <string> subValidator1 = new MockValidator <string>(false, "validator1");
            MockValidator <string> subValidator2 = new MockValidator <string>(true, "validator2");
            MockValidator <string> subValidator3 = new MockValidator <string>(false, "validator3");
            Validator validator = new AndCompositeValidator(subValidator1, subValidator2, subValidator3);
            string    target    = new string('a', 10); // just any string, but a new one

            ValidationResults validationResults = validator.Validate(target);

            Assert.IsFalse(validationResults.IsValid);
            IList <ValidationResult> resultsList = ValidationTestHelper.GetResultsList(validationResults);

            Assert.AreEqual(1, resultsList.Count);
            Assert.AreEqual("validator2", resultsList[0].Message);
            Assert.AreSame(target, subValidator1.ValidatedTargets[0]);
            Assert.AreSame(target, subValidator2.ValidatedTargets[0]);
            Assert.AreSame(target, subValidator3.ValidatedTargets[0]);
        }
        public void ReturnsCompositeFailureWhenValidatingNullAfterQueryingAllValidatorsIfManyValidatorsReturnFailure()
        {
            MockValidator <string> subValidator1 = new MockValidator <string>(false, "validator1");
            MockValidator <string> subValidator2 = new MockValidator <string>(true, "validator2");
            MockValidator <string> subValidator3 = new MockValidator <string>(true, "validator3");
            Validator validator = new AndCompositeValidator(subValidator1, subValidator2, subValidator3);
            string    target    = null;

            ValidationResults validationResults = validator.Validate(target);

            Assert.IsFalse(validationResults.IsValid);
            IList <ValidationResult> resultsList = ValidationTestHelper.GetResultsList(validationResults);

            Assert.AreEqual(2, resultsList.Count);
            Assert.AreEqual("validator2", resultsList[0].Message);
            Assert.AreEqual("validator3", resultsList[1].Message);
            Assert.AreSame(target, subValidator1.ValidatedTargets[0]);
            Assert.AreSame(target, subValidator2.ValidatedTargets[0]);
            Assert.AreSame(target, subValidator3.ValidatedTargets[0]);
        }
        public Validator GetValidator()
        {
            Validator valiator = null;

            if (ListValidator.Count == 1)
            {
                valiator = ListValidator[0];
            }
            else
            if (CompositType == CompositaionType.AND)
            {
                valiator = new AndCompositeValidator(ListValidator.ToArray());
            }
            else
            if (CompositType == CompositaionType.OR)
            {
                valiator = new OrCompositeValidator(ListValidator.ToArray());
            }
            return(valiator);
        }
Пример #14
0
        public void CreatedAndCompositeValidatorFromAttributesWithPropertiesAppropiately()
        {
            Validator validator = ValidationFactory.CreateValidator(typeof(MockClassWithValidatorAttributesOnProperties), "");

            Assert.IsNotNull(validator);
            Assert.AreSame(typeof(GenericValidatorWrapper <MockClassWithValidatorAttributesOnProperties>), validator.GetType());

            var validatorWrapper = validator as GenericValidatorWrapper <MockClassWithValidatorAttributesOnProperties>;

            AndCompositeValidator compositeValidator = validatorWrapper.WrappedValidator as AndCompositeValidator;

            Assert.IsNotNull(compositeValidator);

            IList <Validator> allValidators = ValidationTestHelper.CreateListFromEnumerable <Validator>(compositeValidator.Validators);

            Assert.AreEqual(2, allValidators.Count);

            Assert.AreEqual(typeof(ValueAccessValidator), allValidators[0].GetType());
            Assert.AreEqual(typeof(ValueAccessValidator), allValidators[1].GetType());
        }
        public void CanPerformValidationWithSuppliedValidationResults()
        {
            MockValidator <string> subValidator1 = new MockValidator <string>(false, "validator1");
            MockValidator <string> subValidator2 = new MockValidator <string>(true, "validator2");
            MockValidator <string> subValidator3 = new MockValidator <string>(false, "validator3");
            Validator         validator          = new AndCompositeValidator(subValidator1, subValidator2, subValidator3);
            string            target             = new string('a', 10);// just any string, but a new one
            ValidationResults validationResults  = new ValidationResults();

            validator.Validate(target, validationResults);

            Assert.IsFalse(validationResults.IsValid);
            IList <ValidationResult> resultsList = ValidationTestHelper.GetResultsList(validationResults);

            Assert.AreEqual(1, resultsList.Count);
            Assert.AreEqual("validator2", resultsList[0].Message);
            Assert.AreSame(target, subValidator1.ValidatedTargets[0]);
            Assert.AreSame(target, subValidator2.ValidatedTargets[0]);
            Assert.AreSame(target, subValidator3.ValidatedTargets[0]);
        }
Пример #16
0
        public void CreatedAndCompositeValidatorFromConfigAppropiately()
        {
            DictionaryConfigurationSource configurationSource = new DictionaryConfigurationSource();
            ValidationSettings            settings            = new ValidationSettings();

            configurationSource.Add(ValidationSettings.SectionName, settings);
            ValidatedTypeReference typeReference = new ValidatedTypeReference(typeof(BaseTestDomainObject));

            settings.Types.Add(typeReference);
            ValidationRulesetData ruleData = new ValidationRulesetData("RuleA");

            typeReference.Rulesets.Add(ruleData);
            ValidatedPropertyReference propertyReference1 = new ValidatedPropertyReference("Property1");

            ruleData.Properties.Add(propertyReference1);
            MockValidatorData validator11 = new MockValidatorData("validator1", true);

            propertyReference1.Validators.Add(validator11);
            validator11.MessageTemplate = "message-from-config1-RuleA";

            ValidatedPropertyReference propertyReference2 = new ValidatedPropertyReference("Property2");

            ruleData.Properties.Add(propertyReference2);
            propertyReference2.Validators.Add(validator11);

            Validator validator
                = ValidationFactory.CreateValidatorFromConfiguration(typeof(BaseTestDomainObject), "RuleA", (IConfigurationSource)configurationSource);

            var validatorWrapper = validator as GenericValidatorWrapper <BaseTestDomainObject>;

            AndCompositeValidator compositeValidator = validatorWrapper.WrappedValidator as AndCompositeValidator;

            Assert.IsNotNull(compositeValidator);

            IList <Validator> allValidators = ValidationTestHelper.CreateListFromEnumerable <Validator>(compositeValidator.Validators);

            Assert.AreEqual(2, allValidators.Count);

            Assert.AreEqual(typeof(ValueAccessValidator), allValidators[0].GetType());
            Assert.AreEqual(typeof(ValueAccessValidator), allValidators[1].GetType());
        }
Пример #17
0
        public void AndCompositeValidator()
        {
            var v = new AndCompositeValidator(PropertyName, new List <Validator> {
                new RequiredValidator(), new LengthValidator(5)
            });

            Assert.AreEqual(v.PropertyName, PropertyName);

            var o = new SimpleObject {
                SimpleProperty = "12345"
            };

            Assert.IsTrue(v.Validate(o));

            o.SimpleProperty = null;
            Assert.IsFalse(v.Validate(o));
            o.SimpleProperty = "123";
            Assert.IsFalse(v.Validate(o));
            o.SimpleProperty = "123456";
            Assert.IsFalse(v.Validate(o));
        }
Пример #18
0
        /// <summary>
        /// Creates the composite validator built by the builder.
        /// </summary>
        protected virtual Validator DoGetValidator()
        {
            // create the appropriate validator
            Validator validator;

            if (this.valueValidators.Count == 1)
            {
                validator = this.valueValidators[0];
            }
            else
            {
                if (CompositionType.And == this.validatedElement.CompositionType)
                {
                    validator = new AndCompositeValidator(this.valueValidators.ToArray());
                }
                else
                {
                    validator = new OrCompositeValidator(this.valueValidators.ToArray());
                    validator.MessageTemplate = this.validatedElement.CompositionMessageTemplate;
                    validator.Tag             = this.validatedElement.CompositionTag;
                }
            }

            // add support for ignoring nulls
            Validator valueValidator;

            if (this.validatedElement.IgnoreNulls)
            {
                valueValidator = new NullIgnoringValidatorWrapper(validator);
            }
            else
            {
                valueValidator = validator;
            }

            return(valueValidator);
        }