Пример #1
0
        private static void ValidateContext(WebServerConfiguration context)
        {
            var validator = new ValidatorRunner(true, new CachedValidationRegistry());

            if (!validator.IsValid(context))
            {
                string[] errorList      = validator.GetErrorSummary(context).ErrorMessages;
                var      messageBuilder = new StringBuilder("The CassisniContext contained invalid data. ");
                foreach (string item in errorList)
                {
                    messageBuilder.AppendLine(item);
                }

                throw new ValidationException(messageBuilder.ToString());
            }

            if (context.PortNumber == 0)
            {
                string message =
                    "You must specify a port number. Auto-configured port numbers are not supported untill I figure out how to return the selected port number.";
                throw new NotImplementedException(message);
            }

            if (!File.Exists(Path.Combine(context.WebSiteRootFolder, context.DefaultWebPageFileName)))
            {
                string message = string.Format("Could not find the default page '{0}'",
                                               Path.Combine(context.WebSiteRootFolder, context.DefaultWebPageFileName));
                throw new FileNotFoundException(message);
            }
        }
Пример #2
0
        static void Main(string[] args)
        {
            var order = new Order
            {
                Product = new Product {
                    Name = "Widget", MinQuantity = 5, MaxQuantity = 100
                },
                Quantity = 50
            };

            var runner = new ValidatorRunner(new CachedValidationRegistry());

            if (runner.IsValid(order))
            {
                Console.WriteLine("The order is valid!");
            }
            else
            {
                ErrorSummary summary = runner.GetErrorSummary(order);
                foreach (var invalidProperty in summary.InvalidProperties)
                {
                    Console.WriteLine("{0} is invalid because:", invalidProperty);
                    foreach (var error in summary.GetErrorsForProperty(invalidProperty))
                    {
                        Console.WriteLine("\t * {0}", error);
                    }
                }
            }

            Console.ReadLine();
        }
Пример #3
0
        /// <summary>
        /// Validates the current MainModel
        /// </summary>
        /// <param name="model"></param>
        /// <param name="throwException">Determine if it should fire a MVPValidationException on validation error</param>
        /// <returns>True if sucessfully validated</returns>
        protected virtual bool DoValidate(T model, bool throwException)
        {
#if FRAMEWORK_3
            IValidatorRunner runner = new ValidatorRunner(new CachedValidationRegistry());
            if (runner.IsValid(model))
            {
                return(true);
            }

            ErrorSummary errors = runner.GetErrorSummary(model);

            for (int i = 0; i < errors.ErrorsCount; i++)
            {
                ErrorList.Add(new ValidationError(errors.InvalidProperties[i], errors.ErrorMessages[i]));
            }

            if (throwException)
            {
                // TODO: Colocar a string em um resource
                throw new MVPValidationException(
                          string.Format("Validation has failed with {0} errors. See inner exceptions for details.",
                                        errors.ErrorsCount),
                          ErrorList);
            }
#endif
            return(false);
        }
Пример #4
0
        public void COMP87_Invalid()
        {
            Admin admin = new Admin();

            admin.Password             = string.Empty;
            admin.PasswordConfirmation = "test";

            Assert.IsFalse(runner.IsValid(admin));
            Assert.AreEqual(2, runner.GetErrorSummary(admin).ErrorsCount);
            Assert.AreEqual(1, runner.GetErrorSummary(admin).GetErrorsForProperty("Password").Length);
            Assert.AreEqual(1, runner.GetErrorSummary(admin).GetErrorsForProperty("PasswordConfirmation").Length);

            admin.Password             = "******";
            admin.PasswordConfirmation = string.Empty;

            Assert.IsFalse(runner.IsValid(admin));
            Assert.AreEqual(1, runner.GetErrorSummary(admin).ErrorsCount);
            Assert.AreEqual(1, runner.GetErrorSummary(admin).GetErrorsForProperty("PasswordConfirmation").Length);
        }
Пример #5
0
        /// <errorSummary>
        /// Determines whether the specified instance is valid.
        /// </errorSummary>
        /// <param name="instance">The instance.</param>
        /// <param name="fieldValue">The field value.</param>
        /// <returns>
        ///     <c>true</c> if the specified instance is valid; otherwise, <c>false</c>.
        /// </returns>
        public override bool IsValid(object instance, object fieldValue)
        {
            ValidatorRunner runner = new ValidatorRunner(validationRegistry.BaseRegistry);
            bool            valid  = runner.IsValid(instance);

            if (!valid)
            {
                errorSummary = runner.GetErrorSummary(instance);
            }

            return(valid);
        }
Пример #6
0
        public ErrorSummary Validate()
        {
            ValidatorRunner vr = new ValidatorRunner(true, new CachedValidationRegistry());

            if (!vr.IsValid(this))
            {
                return(vr.GetErrorSummary(this));
            }
            else
            {
                return(null);
            }
        }
Пример #7
0
        public void SummaryBasicFunctionality()
        {
            Person person = new Person();

            Assert.IsFalse(runner.IsValid(person));

            Assert.IsTrue(runner.HasErrors(person));

            ErrorSummary errorSummary = runner.GetErrorSummary(person);

            Assert.IsNotNull(errorSummary);
            Assert.AreEqual(2, errorSummary.ErrorsCount);
            Assert.AreEqual(2, errorSummary.InvalidPropertiesCount);
        }
        public IEnumerable <ErrorInfo> GetErrors <ENTITY>(ENTITY entity) where ENTITY : DomainEntity
        {
            var result = new List <ErrorInfo>();
            var runner = new ValidatorRunner(registry);

            if (entity != null && !runner.IsValid(entity))
            {
                var errorSummary = runner.GetErrorSummary(entity);
                var errorInfos   = errorSummary.InvalidProperties.SelectMany(
                    prop => errorSummary.GetErrorsForProperty(prop),
                    (prop, err) => new ErrorInfo(prop, err));
                result.AddRange(errorInfos);
            }
            return(result);
        }
Пример #9
0
        public void ExecutesCustomContributors()
        {
            ValidatorRunner runnerWithContributor = new ValidatorRunner(true, new CachedValidationRegistry(),
                                                                        new IValidationContributor[] { new AlwaysErrorContributor() });

            object target = new object();

            Assert.IsFalse(runnerWithContributor.IsValid(target));
            ErrorSummary errors = runnerWithContributor.GetErrorSummary(target);

            Assert.IsTrue(errors.HasError);
            Assert.AreEqual(1, errors.ErrorsCount);
            string[] errorsForKey = errors.GetErrorsForProperty("someKey");
            Assert.AreEqual(1, errorsForKey.Length);
            Assert.AreEqual("error", errorsForKey[0]);
        }
		public void ValidationOrderTest()
		{
			ValidatorRunner runner = new ValidatorRunner(new CachedValidationRegistry());

			Supplier supplier = new Supplier();
			supplier.Password = "******";

			runner.IsValid(supplier);

			ErrorSummary summary = runner.GetErrorSummary(supplier);
			Assert.IsNotNull(summary);

			Assert.AreEqual("This is a required field", summary.ErrorMessages[0]);
			Assert.AreEqual("Fields do not match", summary.ErrorMessages[1]);
			Assert.AreEqual("This is a required field", summary.ErrorMessages[2]);
		}
        internal static void AddNestedPropertyValidationErrorMessages(List <string> errorMessages, object instance, ValidatorRunner runner)
        {
            foreach (PropertyInfo propinfo in GetNestedPropertiesToValidate(instance))
            {
                object propval = propinfo.GetValue(instance, null);
                if (propval != null)
                {
                    ErrorSummary summary = runner.GetErrorSummary(propval);

                    if (summary != null)
                    {
                        errorMessages.AddRange(summary.ErrorMessages);
                    }
                }
            }
        }
        public void ValidationOrderTest()
        {
            ValidatorRunner runner = new ValidatorRunner(new CachedValidationRegistry());

            Supplier supplier = new Supplier();

            supplier.Password = "******";

            runner.IsValid(supplier);

            ErrorSummary summary = runner.GetErrorSummary(supplier);

            Assert.IsNotNull(summary);

            Assert.AreEqual("This is a required field", summary.ErrorMessages[0]);
            Assert.AreEqual("Fields do not match", summary.ErrorMessages[1]);
            Assert.AreEqual("This is a required field", summary.ErrorMessages[2]);
        }
Пример #13
0
 private void CheckForValidationFailures(object instance, string prefix, ErrorSummary summary)
 {
     if (validator == null)
     {
         return;
     }
     if (!validator.IsValid(instance))
     {
         summary.RegisterErrorsFrom(validator.GetErrorSummary(instance));
         foreach (string invalidProperty in summary.InvalidProperties)
         {
             foreach (string errorMessage in summary.GetErrorsForProperty(invalidProperty))
             {
                 errors.Add(new DataBindError(prefix, invalidProperty, errorMessage));
             }
         }
     }
 }
Пример #14
0
        public void LocalizedValidation_Uses_CurrentUICultureLocalization()
        {
            var bar = new OnlyLocalizedForLithuaniaBar();

            using (SwitchUICulture(CultureInfo.CreateSpecificCulture("lt-LT")))
            {
                runner.IsValid(bar);
                ErrorSummary summary = runner.GetErrorSummary(bar);

                Assert.IsNotNull(summary);
                Assert.AreEqual("lt-Bar_BazNonEmpty", summary.ErrorMessages[0]);
                Assert.AreEqual("lt-Bar_Baz", summary.InvalidProperties[0]);
            }
        }
Пример #15
0
        private void CheckForValidationFailures(object instance, string prefix, Node node, ErrorSummary summary)
        {
            if (validator == null)
            {
                return;
            }
            if (!validator.IsValid(instance))
            {
                ErrorSummary errorSummaryFromValidator = validator.GetErrorSummary(instance);
                foreach (string invalidProperty in errorSummaryFromValidator.InvalidProperties)
                {
                    if (ShouldIgnoreProperty(string.Format("{0}.{1}", node.FullName, invalidProperty)))
                    {
                        continue;
                    }

                    foreach (string errorMessage in errorSummaryFromValidator.GetErrorsForProperty(invalidProperty))
                    {
                        summary.RegisterErrorMessage(invalidProperty, errorMessage);
                        errors.Add(new DataBindError(prefix, invalidProperty, errorMessage));
                    }
                }
            }
        }
		public void ExecutesCustomContributors()
		{
			ValidatorRunner runnerWithContributor = new ValidatorRunner(true, new CachedValidationRegistry(),
				new IValidationContributor[] {new AlwaysErrorContributor()});

			object target = new object();
			Assert.IsFalse(runnerWithContributor.IsValid(target));
			ErrorSummary errors = runnerWithContributor.GetErrorSummary(target);
			Assert.IsTrue(errors.HasError);
			Assert.AreEqual(1, errors.ErrorsCount);
			string[] errorsForKey = errors.GetErrorsForProperty("someKey");
			Assert.AreEqual(1, errorsForKey.Length);
			Assert.AreEqual("error", errorsForKey[0]);
		}