コード例 #1
0
        public void ValidateWithMultipleConditions()
        {
            var configure = new FluentConfiguration();

            var validationDef = new ValidationDef<EntityWithString>();
            validationDef.Define(e => e.Name)
                .Satisfy(name => name != null && name.StartsWith("ab")).WithMessage("Name should start with 'ab'")
                .And
                .Satisfy(name => name != null && name.EndsWith("zz")).WithMessage("Name should end with 'zz'");

            configure.Register(validationDef).SetDefaultValidatorMode(ValidatorMode.UseExternal);
            var ve = new ValidatorEngine();

            ve.Configure(configure);

            Assert.That(ve.IsValid(new EntityWithString { Name = "abczz" }));
            Assert.That(!ve.IsValid(new EntityWithString { Name = "bc" }));
            var iv = ve.Validate(new EntityWithString {Name = "abc"});
            Assert.That(iv.Length, Is.EqualTo(1));
            Assert.That(iv.Select(i => i.Message).First(), Is.EqualTo("Name should end with 'zz'"));

            iv = ve.Validate(new EntityWithString { Name = "zz" });
            Assert.That(iv.Length, Is.EqualTo(1));
            Assert.That(iv.Select(i => i.Message).First(), Is.EqualTo("Name should start with 'ab'"));

            iv = ve.Validate(new EntityWithString { Name = "bc" });
            Assert.That(iv.Length, Is.EqualTo(2));
            var messages = iv.Select(i => i.Message);
            Assert.That(messages, Has.Member("Name should start with 'ab'") & Has.Member("Name should end with 'zz'"));
        }
コード例 #2
0
        public void NoEndlessLoop()
        {
            var john = new User("John", null);
            john.Knows(john);

            var validator = new ValidatorEngine();

            InvalidValue[] constraintViolations = validator.Validate(john);
            Assert.AreEqual(constraintViolations.Length, 1, "Wrong number of constraints");
            Assert.AreEqual("LastName", constraintViolations.ElementAt(0).PropertyName);

            var jane = new User("Jane", "Doe");
            jane.Knows(john);
            john.Knows(jane);

            constraintViolations = validator.Validate(john);
            Assert.AreEqual(constraintViolations.Length, 1, "Wrong number of constraints");
            Assert.AreEqual("LastName", constraintViolations.ElementAt(0).PropertyName);

            constraintViolations = validator.Validate(jane);
            Assert.AreEqual(1, constraintViolations.Length, "Wrong number of constraints");
            Assert.AreEqual(constraintViolations.ElementAt(0).PropertyPath, "knowsUser[0].LastName");

            john.LastName = "Doe";
            constraintViolations = validator.Validate(john);
            Assert.AreEqual(0, constraintViolations.Length, "Wrong number of constraints");
        }
コード例 #3
0
ファイル: Validator.cs プロジェクト: galehouse5/TreesDb
 protected override IEnumerable <IValidationError> InternalValidate(object source)
 {
     foreach (var iv in m_E.Validate(source))
     {
         yield return(new InvalidValueValidationError(iv));
     }
 }
コード例 #4
0
        public void NoEndlessLoop()
        {
            var john = new User("John", null);

            john.Knows(john);

            var validator = new ValidatorEngine();

            InvalidValue[] constraintViolations = validator.Validate(john);
            Assert.AreEqual(constraintViolations.Length, 1, "Wrong number of constraints");
            Assert.AreEqual("LastName", constraintViolations.ElementAt(0).PropertyName);

            var jane = new User("Jane", "Doe");

            jane.Knows(john);
            john.Knows(jane);

            constraintViolations = validator.Validate(john);
            Assert.AreEqual(constraintViolations.Length, 1, "Wrong number of constraints");
            Assert.AreEqual("LastName", constraintViolations.ElementAt(0).PropertyName);

            constraintViolations = validator.Validate(jane);
            Assert.AreEqual(1, constraintViolations.Length, "Wrong number of constraints");
            Assert.AreEqual(constraintViolations.ElementAt(0).PropertyPath, "knowsUser[0].LastName");

            john.LastName        = "Doe";
            constraintViolations = validator.Validate(john);
            Assert.AreEqual(0, constraintViolations.Length, "Wrong number of constraints");
        }
コード例 #5
0
 public void ValidateEntityWithTags()
 {
     ve.Validate(new EntityLoq {
         ValueUsingTags = new string('A', 21)
     }, Tags.Warning).Should().Be.Empty();
     ve.Validate(new EntityLoq {
         ValueUsingTags = ""
     }, Tags.Error).Should().Have.Count.EqualTo(1);
 }
コード例 #6
0
        public void NoInitializeAfterFetch()
        {
            // Saved object are valid and don't need to initialize it for validation matters

            Person parent = CreateGrandparent();

            SavePerson(parent);
            int savedId = parent.Id;

            using (ISession s = OpenSession())
            {
                Person p = s.CreateQuery("from Person p where p.Name = 'GP'")
                           .UniqueResult <Person>();

                // This two lines are not needed for tests because is a NH matter
                // we use it only to check where the problem really is
                Assert.IsFalse(NHibernateHelper.IsInitialized(p.Children));
                Assert.IsFalse(NHibernateHelper.IsInitialized(p.Friends));

                vengine.Validate(p);

                Assert.IsFalse(NHibernateHelper.IsInitialized(p.Children));
                Assert.IsFalse(NHibernateHelper.IsInitialized(p.Friends));
            }

            // No initialized many-to-one
            using (ISession s = OpenSession())
            {
                Person p = s.CreateQuery("from Person p where p.Name = 'C1'")
                           .UniqueResult <Person>();

                // This line are not needed for tests because is a NH matter
                // we use it only to check where the problem really is
                Assert.IsFalse(NHibernateHelper.IsInitialized(p.Parent));

                vengine.Validate(p);

                Assert.IsFalse(NHibernateHelper.IsInitialized(p.Parent));
            }

            // No initialized the proxie it self
            using (ISession s = OpenSession())
            {
                Person p = s.Load <Person>(savedId);

                Assert.IsFalse(NHibernateHelper.IsInitialized(p));

                vengine.Validate(p);

                Assert.IsFalse(NHibernateHelper.IsInitialized(p));
            }

            CleanUp();
        }
コード例 #7
0
        public void ValidateAnyClass()
        {
            ValidatorEngine ve = new ValidatorEngine();

            Assert.IsTrue(ve.IsValid(new AnyClass()));
            Assert.IsNotNull(ve.GetValidator <AnyClass>());
            ve.AssertValid(new AnyClass());             // not cause exception
            Assert.AreEqual(0, ve.Validate(new AnyClass()).Length);
            Assert.AreEqual(0, ve.ValidatePropertyValue <AnyClass>("aprop", new AnyClass()).Length);
            Assert.AreEqual(0, ve.ValidatePropertyValue(new AnyClass(), "aprop").Length);

            Assert.AreEqual(0, ve.Validate("always valid").Length);
            Assert.AreEqual(0, ve.ValidatePropertyValue("always valid", "Length").Length);
        }
コード例 #8
0
        public void can_validate_legs()
        {
            var validationDef = new ValidationDef<Cat>();
            validationDef.Define(c => c.Legs).GreaterThanOrEqualTo(2);

            var vc = new FluentConfiguration();
            vc.SetDefaultValidatorMode(ValidatorMode.UseExternal);
            vc.Register(validationDef);

            var ve = new ValidatorEngine();
            ve.Configure(vc);

            ve.Validate(new Cat {Legs = 0}).Should().Have.Count.EqualTo(1);
            ve.Validate(new Cat {Legs = 3}).Should().Be.Empty();
        }
コード例 #9
0
 public IList <IInvalidValueInfo> Validate(object entityInstance)
 {
     return
         (validatorEngine.Validate(entityInstance)
          .Select(iv => new InvalidValueInfo(iv))
          .Cast <IInvalidValueInfo>().ToList());
 }
コード例 #10
0
        public void Validate_TestingTwoValidatorsThatReturnFalseAndMessage_ThrowsExceptionWithMessagesFromBothValidators()
        {
            const string errorMessage1 = "Error message validator 1";
            const string errorMessage2 = "Error message validator 2";

            //Arrange
            _validatorTest1.Validate(Arg.Any <CapRedV2UserSignUpDTO>()).Returns(new Tuple <bool, string>(false, errorMessage1));
            _validatorTest2.Validate(Arg.Any <CapRedV2UserSignUpDTO>()).Returns(new Tuple <bool, string>(false, errorMessage2));

            IList <IDomainEntitiesValidator <CapRedV2UserSignUpDTO> > domainEntityValidators = new List
                                                                                               <IDomainEntitiesValidator <CapRedV2UserSignUpDTO> >
            {
                _validatorTest1,
                _validatorTest2
            };

            var validatorEngine = new ValidatorEngine <CapRedV2UserSignUpDTO>(domainEntityValidators);

            //Act
            var exception = Assert.Throws <BusinessValidationException>(() => validatorEngine.Validate(new CapRedV2UserSignUpDTO()));

            //Assert
            _validatorTest1.Received().Validate(Arg.Any <CapRedV2UserSignUpDTO>());
            _validatorTest2.Received().Validate(Arg.Any <CapRedV2UserSignUpDTO>());
            StringAssert.Contains(errorMessage1, exception.Message);
            StringAssert.Contains(errorMessage2, exception.Message);
        }
コード例 #11
0
        private static void Run_Example_With_Invalid_Entity(ValidatorEngine vtor)
        {
            Console.WriteLine("==Entity with Invalid values==");
            var m = new Meeting
            {
                Name        = "NHibernate Validator virtual meeting",
                Description = "How to configure NHibernate Validator in different ways.",
                Start       = DateTime.Now.AddHours(2),                           //Invalid: the Start date is minor than End.
                End         = DateTime.Now
            };

            var invalidValues = vtor.Validate(m);

            if (invalidValues.Length == 0)
            {
                throw new Exception("Something was wrong in the NHV configuration, the entity should be invalid.");
            }
            else
            {
                Console.WriteLine("The entity is invalid.");
                foreach (var value in invalidValues)
                {
                    Console.WriteLine(" - " + value.Message);
                }
            }
        }
コード例 #12
0
        private static void RunSerializationTest(ValidatorEngine ve)
        {
            Address a = new Address();

            Address.blacklistedZipCode = null;
            a.Country = "Australia";
            a.Zip     = "1221341234123";
            a.State   = "Vic";
            a.Line1   = "Karbarook Ave";
            a.Id      = 3;
            InvalidValue[] validationMessages = ve.Validate(a);

            // All work before serialization
            Assert.AreEqual(2, validationMessages.Length);             //static field is tested also
            Assert.IsTrue(validationMessages[0].Message.StartsWith("prefix_"));
            Assert.IsTrue(validationMessages[1].Message.StartsWith("prefix_"));

            // Serialize and deserialize
            ValidatorEngine cvAfter = (ValidatorEngine)SerializationHelper.Deserialize(SerializationHelper.Serialize(ve));

            validationMessages = cvAfter.Validate(a);
            // Now test after
            Assert.AreEqual(2, validationMessages.Length);             //static field is tested also
            Assert.IsTrue(validationMessages[0].Message.StartsWith("prefix_"));
            Assert.IsTrue(validationMessages[1].Message.StartsWith("prefix_"));
        }
コード例 #13
0
        public void InterpolatingMemberAndSubMembers()
        {
            var c = new Contractor
            {
                SubcontractorHourEntries = new List <SubcontractorHourEntry>
                {
                    new SubcontractorHourEntry
                    {
                        Contrator = new SubContractor(1),
                        Hour      = 9
                    },
                    new SubcontractorHourEntry
                    {
                        Contrator = new SubContractor(2),
                        Hour      = 8
                    }
                }
            };

            var vtor   = new ValidatorEngine();
            var values = vtor.Validate(c);

            Assert.AreEqual(2, values.Length);
            Assert.AreEqual("The min value in the SubContractor Id: 1 is invalid. Instead was found: 9", values[0].Message);
            Assert.AreEqual("The min value in the SubContractor Id: 2 is invalid. Instead was found: 8", values[1].Message);
        }
コード例 #14
0
        private void btnSend_Click(object sender, EventArgs e)
        {
            //NOTE...IMPORTANT!:
            //This is an example of how-to-change-the-configuration.
            //You should maintain in your code just 1 (one) ValidatorEngine,
            //see SharedEngine: http://nhibernate.info/blog/2009/02/26/diving-in-nhibernate-validator.html

            ValidatorEngine ve = vvtor.ValidatorEngine;

            ve.Clear();

            //Configuration of NHV. You can also configure this stuff using xml, outside of the code
            XmlConfiguration nhvc = new XmlConfiguration();

            nhvc.Properties[Environment.ApplyToDDL]            = "false";
            nhvc.Properties[Environment.AutoregisterListeners] = "false";
            nhvc.Properties[Environment.ValidatorMode]         = GetMode();
            nhvc.Mappings.Add(new MappingConfiguration("NHibernate.Validator.Demo.Winforms", null));
            ve.Configure(nhvc);

            Customer customer = GetCustomerFromUI();

            if (ve.IsValid(customer))
            {
                listBox1.Items.Clear();
                Send();
            }
            else
            {
                InvalidValue[] values = ve.Validate(customer);
                FillErrorsOnListBox(values);
            }
        }
コード例 #15
0
        public void InterpolatingMemberAndSubMembers()
        {
            var c = new Contractor
            {
                SubcontractorHourEntries = new List<SubcontractorHourEntry>
                                                       	{
                                                       		new SubcontractorHourEntry
                                                       			{
                                                       				Contrator = new SubContractor(1),
                                                       				Hour = 9
                                                       			},
                                                       		new SubcontractorHourEntry
                                                       			{
                                                       				Contrator = new SubContractor(2),
                                                       				Hour = 10
                                                       			}
                                                       	}
            };

            var vtor = new ValidatorEngine();
            Assert.IsFalse(vtor.IsValid(c));
            var values = vtor.Validate(c);
            Assert.AreEqual(1, values.Length);
            Assert.AreEqual("The min value in the SubContractor Id: 1 is invalid. Instead was found: 9", values[0].Message);
        }
コード例 #16
0
        public void when_validate_customer_with_invalid_name_and_email_should_return_two_invalid_values()
        {
            var validatorEngine = new ValidatorEngine();
            var notValidCustomer = GetNotValidCustomer();
            validatorEngine.Configure();

            validatorEngine.Validate(notValidCustomer).Should().Have.Count.EqualTo(2);
        }
コード例 #17
0
        public OperationResult Validate <T>(T entity) where T : class
        {
            var result = EngineContext.Current.Resolve <OperationResult>();

            result += _validatorEngine.Validate(entity).ToList();

            return(result);
        }
コード例 #18
0
        public void NullIsAllwaysValid()
        {
            ValidatorEngine ve = new ValidatorEngine();

            Assert.IsTrue(ve.IsValid(null));
            Assert.AreEqual(0, ve.Validate(null).Length);
            ve.AssertValid(null);             // not cause exception
        }
コード例 #19
0
        public ICollection <IValidationResult> ValidationResultsFor(object value)
        {
            Check.Require(value != null, "value to ValidationResultsFor may not be null");

            InvalidValue[] invalidValues = ValidatorEngine.Validate(value);

            return(ParseValidationResultsFrom(invalidValues));
        }
コード例 #20
0
        public void when_validate_customer_with_invalid_name_and_email_should_return_two_invalid_values()
        {
            var validatorEngine  = new ValidatorEngine();
            var notValidCustomer = GetNotValidCustomer();

            validatorEngine.Configure();

            validatorEngine.Validate(notValidCustomer).Should().Have.Count.EqualTo(2);
        }
コード例 #21
0
ファイル: Fixture.cs プロジェクト: stuartcarnie/nhcontrib
        public void Should_Be_Able_To_Validate_A_Invalid_Entity_With_Custom_Validator()
        {
            ValidatorEngine vtor = GetValidatorEngine();

            InvalidValue[] invalids = vtor.Validate(new Foo
            {
                Name = null
            });
            Assert.AreEqual(1, invalids.Length);
        }
コード例 #22
0
        public void InterpolatingMemberAndSubMembers()
        {
            var animal = new Animal {Legs = 1, Name = "Horse"};

            var vtor = new ValidatorEngine();
            var values = vtor.Validate(animal);
            Assert.AreEqual(1, values.Length);
            //The legs validator add a error message for the property Legs.
            Assert.AreEqual("Legs", values[0].PropertyName);
        }
コード例 #23
0
        public static void Validate(this Controller controller, object Entity)
        {
            ValidatorEngine vtor = Environment.SharedEngineProvider.GetEngine();

            InvalidValue[] errors = vtor.Validate(Entity);
            foreach (InvalidValue error in errors)
            {
                controller.ModelState.AddModelError(error.PropertyName, error.Message);
            }
        }
コード例 #24
0
        public void ValidateWithMultipleConditions()
        {
            var configure = new FluentConfiguration();

            var validationDef = new ValidationDef <EntityWithString>();

            validationDef.Define(e => e.Name)
            .Satisfy(name => name != null && name.StartsWith("ab")).WithMessage("Name should start with 'ab'")
            .And
            .Satisfy(name => name != null && name.EndsWith("zz")).WithMessage("Name should end with 'zz'");

            configure.Register(validationDef).SetDefaultValidatorMode(ValidatorMode.UseExternal);
            var ve = new ValidatorEngine();

            ve.Configure(configure);

            Assert.That(ve.IsValid(new EntityWithString {
                Name = "abczz"
            }));
            Assert.That(!ve.IsValid(new EntityWithString {
                Name = "bc"
            }));
            var iv = ve.Validate(new EntityWithString {
                Name = "abc"
            });

            Assert.That(iv.Length, Is.EqualTo(1));
            Assert.That(iv.Select(i => i.Message).First(), Is.EqualTo("Name should end with 'zz'"));

            iv = ve.Validate(new EntityWithString {
                Name = "zz"
            });
            Assert.That(iv.Length, Is.EqualTo(1));
            Assert.That(iv.Select(i => i.Message).First(), Is.EqualTo("Name should start with 'ab'"));

            iv = ve.Validate(new EntityWithString {
                Name = "bc"
            });
            Assert.That(iv.Length, Is.EqualTo(2));
            var messages = iv.Select(i => i.Message);

            Assert.That(messages, Has.Member("Name should start with 'ab'") & Has.Member("Name should end with 'zz'"));
        }
コード例 #25
0
        public void Should_Create_Constraints_With_Custom_Factory()
        {
            TestConstraintValidatorFactory.ClearCounter();

            ValidatorEngine ve = GetValidatorEngine();

            ve.Validate(new Foo());

            Assert.AreEqual(3, TestConstraintValidatorFactory.ValidatorsCreated);
        }
コード例 #26
0
		public static List<string> ItensInvalidos(this Entidade entidade)
		{
			var engine = new ValidatorEngine();
			var mensagens = new List<string>();

			foreach (var item in engine.Validate(entidade))
				mensagens.Add(item.PropertyName + ": " + item.Message);

			return mensagens;
		}
コード例 #27
0
        public void CopositionUsingEngine()
        {
            DerivatedClass dFullBroken = new DerivatedClass();

            dFullBroken.A = "1234";
            dFullBroken.B = "1234";

            DerivatedClass dPartialBroken = new DerivatedClass();

            dPartialBroken.A = "1234";

            BaseClass bOk = new BaseClass();

            bOk.A = "123";

            BaseClass bBroken = new BaseClass();

            bBroken.A = "1234";

            ValidatorEngine ve = new ValidatorEngine();

            InvalidValue[] ivalues;
            Composition    c = new Composition();

            c.Any   = bBroken;
            ivalues = ve.Validate(c);
            Assert.AreEqual(1, ivalues.Length);

            c.Any   = dFullBroken;
            ivalues = ve.Validate(c);
            Assert.AreEqual(2, ivalues.Length);

            c.Any   = bOk;
            ivalues = ve.Validate(c);
            Assert.AreEqual(0, ivalues.Length);

            c.Any = dPartialBroken;
            var ivalue = ve.Validate(c);

            ivalue.Should().Not.Be.Empty();
            ivalue.Single().PropertyName.Should().Be.EqualTo("A");
        }
コード例 #28
0
        public void DelegatedValidate_WithoutMessageHasInvalidValue()
        {
            var configure = new FluentConfiguration();
            configure.Register(new[] { typeof(RangeDefWithoutCustomMessage) })
                .SetDefaultValidatorMode(ValidatorMode.UseExternal);
            var ve = new ValidatorEngine();

            ve.Configure(configure);
            var iv = ve.Validate(new Range {Start = 5, End = 4});
            iv.Should().Not.Be.Empty();
        }
コード例 #29
0
        public void ShouldAddAnothersMessages()
        {
            var vtor = new ValidatorEngine();
            var mi   = new MembershipInfo
            {
                Username = null,
                Password = "******"
            };

            InvalidValue[] invalidValues = vtor.Validate(mi);
            Assert.AreEqual(3, invalidValues.Length);
        }
        public void ShouldAddAnothersMessages()
        {
            var vtor = new ValidatorEngine();
            var mi = new MembershipInfo
                     	{
                     		Username = null,
                     		Password = "******"
                     	};

            InvalidValue[] invalidValues = vtor.Validate(mi);
            Assert.AreEqual(3, invalidValues.Length);
        }
コード例 #31
0
        public async Task <IdentityResult> RegisterAsync(CapRedV2UserSignUpDTO capRedV2UserSignUpDTO)
        {
            _signUpValidatorEngine.Validate(capRedV2UserSignUpDTO);

            var user = new CapRedV2User
            {
                UserName = capRedV2UserSignUpDTO.Email,
                Email    = capRedV2UserSignUpDTO.Email
            };

            return(await _userManager.CreateAsync(user, capRedV2UserSignUpDTO.Password));
        }
コード例 #32
0
        public void can_validate_legs()
        {
            var validationDef = new ValidationDef <Cat>();

            validationDef.Define(c => c.Legs).GreaterThanOrEqualTo(2);

            var vc = new FluentConfiguration();

            vc.SetDefaultValidatorMode(ValidatorMode.UseExternal);
            vc.Register(validationDef);

            var ve = new ValidatorEngine();

            ve.Configure(vc);

            ve.Validate(new Cat {
                Legs = 0
            }).Should().Have.Count.EqualTo(1);
            ve.Validate(new Cat {
                Legs = 3
            }).Should().Be.Empty();
        }
コード例 #33
0
        public void InterpolatingMemberAndSubMembers()
        {
            var animal = new Animal {
                Legs = 1, Name = "Horse"
            };

            var vtor   = new ValidatorEngine();
            var values = vtor.Validate(animal);

            Assert.AreEqual(1, values.Length);
            //The legs validator add a error message for the property Legs.
            Assert.AreEqual("Legs", values[0].PropertyName);
        }
        public void Validating_root_entity_should_report_error_from_attribute_validators_and_fluent_validators()
        {
            var engine = new ValidatorEngine();
            var cfg    = new FluentConfiguration();

            cfg.Register(new[] { typeof(SubEntityValidation) });
            cfg.SetDefaultValidatorMode(ValidatorMode.OverrideExternalWithAttribute);
            engine.Configure(cfg);

            InvalidValue[] errors = engine.Validate(_entity);

            Assert.That(errors.Length, Is.EqualTo(3));             // FAIL! validators defined in SubEntityValidation are not considered
        }
コード例 #35
0
        /// <summary>
        /// Filter implementation to validate input data
        /// </summary>
        /// <param name="actionContext">http action context</param>
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            string rawRequest;

            using (var stream = new StreamReader(actionContext.Request.Content.ReadAsStreamAsync().Result))
            {
                stream.BaseStream.Position = 0;
                rawRequest = stream.ReadToEnd();
            }
            string errors = "";

            if (null != rawRequest)
            {
                if (!ValidateJson(rawRequest))
                {
                    string jsonexample = @"{'FirstName': {'type':'string','required': true},'LastName': {'type':'string','required': true},'Address': {'type':'string','required': true},'Phonenumber': {'type':'string','required': true}}";
                    errors += "Invalid Json! It should have the following structure: " + jsonexample;
                }
                else
                {
                    Customer customer = JsonConvert.DeserializeObject <Customer>(rawRequest);
                    ConfigureValidator();
                    if (!actionContext.Request.Headers.Contains("transactionID"))
                    {
                        errors += "transactionID is required in the header! ";
                    }
                    if (!actionContext.Request.Headers.Contains("agentID"))
                    {
                        errors += "agentID is required in the header! ";
                    }
                    if (!_ve.IsValid(customer))
                    {
                        var results = _ve.Validate(customer);
                        foreach (InvalidValue error in results)
                        {
                            errors += error.Message + ". ";
                        }
                    }
                }
            }
            else
            {
                errors += "Customer data missing in body of request!";
            }
            if (errors != "")
            {
                actionContext.Response = actionContext.Request.CreateErrorResponse(System.Net.HttpStatusCode.BadRequest, errors);
                return;
            }
            base.OnActionExecuting(actionContext);
        }
コード例 #36
0
        public void ValidateOnBaseClasses()
        {
            var configure = new FluentConfiguration();

            configure.Register(new[] { typeof(BaseEntityValidationDef) })
            .SetDefaultValidatorMode(ValidatorMode.UseExternal);

            var ve = new ValidatorEngine();

            ve.Configure(configure);

            ve.Validate(new Entity()).Any().Should().Be.True();
            //ve.GetClassValidator(typeof (Entity)).GetInvalidValues(new Entity()).Any().Should().Be.True();
        }
コード例 #37
0
ファイル: ThreadSafeFixture.cs プロジェクト: spib/nhcontrib
        public void Validate()
        {
            ve = new ValidatorEngine();

            Run(delegate
            {
                for (int i = 0; i < ITERATIONS; i++)
                {
                    Thread t = new Thread(delegate() { ve.Validate(new Foo()); });

                    t.Start();
                }
            });
        }
コード例 #38
0
        public void Validate()
        {
            ve = new ValidatorEngine();

            Run(delegate
            {
                for (int i = 0; i < ITERATIONS; i++)
                {
                    Thread t = new Thread(delegate() { ve.Validate(new Foo()); });

                    t.Start();
                }
            });
        }
コード例 #39
0
        public void GraphNavigationDeterminism()
        {
            // build the test object graph
            var user = new User("John", "Doe");

            var address1 = new Address(null, "11122", "Stockholm");

            address1.SetInhabitant(user);

            var address2 = new Address("Kungsgatan 5", "11122", "Stockholm");

            address2.SetInhabitant(user);

            user.AddAddress(address1);
            user.AddAddress(address2);

            var order = new Order(1);

            order.ShippingAddress = address1;
            order.BillingAddress  = address2;
            order.Customer        = user;

            var line1 = new OrderLine(order, 42);
            var line2 = new OrderLine(order, 101);

            order.AddOrderLine(line1);
            order.AddOrderLine(line2);

            var vtor = new ValidatorEngine();

            InvalidValue[] constraintViolations = vtor.Validate(order);
            Assert.AreEqual(3, constraintViolations.Length, "Wrong number of constraints");

            var expectedErrorMessages = new List <string>();

            expectedErrorMessages.Add("shippingAddress.addressline1");
            expectedErrorMessages.Add("customer.addresses[0].addressline1");
            expectedErrorMessages.Add("billingAddress.inhabitant.addresses[0].addressline1");

            foreach (InvalidValue violation in constraintViolations)
            {
                if (expectedErrorMessages.Contains(violation.PropertyPath))
                {
                    expectedErrorMessages.Remove(violation.PropertyPath);
                }
            }

            Assert.IsTrue(expectedErrorMessages.Count == 0, "All error messages should have occured once");
        }
コード例 #40
0
        public void CopositionUsingEngine()
        {
            DerivatedClass dFullBroken = new DerivatedClass();
            dFullBroken.A = "1234";
            dFullBroken.B = "1234";

            DerivatedClass dPartialBroken = new DerivatedClass();
            dPartialBroken.A = "1234";

            BaseClass bOk = new BaseClass();
            bOk.A = "123";

            BaseClass bBroken = new BaseClass();
            bBroken.A = "1234";

            ValidatorEngine ve = new ValidatorEngine();
            InvalidValue[] ivalues;
            Composition c = new Composition();

            c.Any = bBroken;
            ivalues = ve.Validate(c);
            Assert.AreEqual(1, ivalues.Length);

            c.Any = dFullBroken;
            ivalues = ve.Validate(c);
            Assert.AreEqual(2, ivalues.Length);

            c.Any = bOk;
            ivalues = ve.Validate(c);
            Assert.AreEqual(0, ivalues.Length);

            c.Any = dPartialBroken;
            ivalues = ve.Validate(c);
            Assert.AreEqual(1, ivalues.Length);
            Assert.AreEqual("A", ivalues[0].PropertyName);
        }
        public void ShouldDisableTheDefaultMessageAndAddAnothers()
        {
            var vtor = new ValidatorEngine();
            var mi = new MembershipInfo
                     	{
                     		Username = "******",
                            Password = "******"
                     	};

            InvalidValue[] invalidValues = vtor.Validate(mi);

            Assert.AreEqual(2, invalidValues.Length);
            Assert.AreEqual(Messages.PasswordLength, invalidValues.ElementAt(0).Message);
            Assert.AreEqual(Messages.PasswordContent, invalidValues.ElementAt(1).Message);
        }
        public void ShouldAddAnothersMessagesUsingEntityValidation()
        {
            var vtor = new ValidatorEngine();
            var mi = new MembershipInfo2
                     	{
                     		Username = null,
                     		Password = "******"
                     	};

            InvalidValue[] invalidValues = vtor.Validate(mi);
            Assert.AreEqual(3, invalidValues.Length);

            Assert.AreEqual(Messages.PasswordLength, invalidValues.ElementAt(1).Message);
            Assert.AreEqual(Messages.PasswordContent, invalidValues.ElementAt(2).Message);
        }
コード例 #43
0
        public void GraphNavigationDeterminism()
        {
            // build the test object graph
            var user = new User("John", "Doe");

            var address1 = new Address(null, "11122", "Stockholm");
            address1.SetInhabitant(user);

            var address2 = new Address("Kungsgatan 5", "11122", "Stockholm");
            address2.SetInhabitant(user);

            user.AddAddress(address1);
            user.AddAddress(address2);

            var order = new Order(1);
            order.ShippingAddress = address1;
            order.BillingAddress = address2;
            order.Customer = user;

            var line1 = new OrderLine(order, 42);
            var line2 = new OrderLine(order, 101);
            order.AddOrderLine(line1);
            order.AddOrderLine(line2);

            var vtor = new ValidatorEngine();

            InvalidValue[] constraintViolations = vtor.Validate(order);
            Assert.AreEqual(3, constraintViolations.Length, "Wrong number of constraints");

            var expectedErrorMessages = new List<string>();
            expectedErrorMessages.Add("shippingAddress.addressline1");
            expectedErrorMessages.Add("customer.addresses[0].addressline1");
            expectedErrorMessages.Add("billingAddress.inhabitant.addresses[0].addressline1");

            foreach (InvalidValue violation in constraintViolations)
            {
                if (expectedErrorMessages.Contains(violation.PropertyPath))
                {
                    expectedErrorMessages.Remove(violation.PropertyPath);
                }
            }

            Assert.IsTrue(expectedErrorMessages.Count == 0, "All error messages should have occured once");
        }
コード例 #44
0
ファイル: Program.cs プロジェクト: spib/nhcontrib
        private static void Main(string[] args)
        {
            ///Configuration at Application Start-up.
            var container = new WindsorContainer();
            IoC.Container = container;
            //registering NHV out-of-the-box constraint validators
            WindsorConstraintValidatorFactory.RegisteringValidators(container);

            //registering your own constraint validators
            container.AddComponent(typeof (PersonNameValidator).Name.ToLower(), typeof (PersonNameValidator));
            ///End of IoC Configuration.

            var vtor = new ValidatorEngine();
            vtor.Configure();

            //Validating a valid entity 'Contact'
            var validCustomer = new Contact
                                    {
                                        FirstName = "Dario",
                                        LastName = "Quintana",
                                        Address = "2nd Street at 34",
                                        Description = "Some description"
                                    };

            vtor.AssertValid(validCustomer);

            //Validating an invalid entity 'Contact'
            var invalidCustomer = new Contact
                                  	{
                                  		FirstName = "dario" /*INVALID*/,
                                  		LastName = "Quintana",
                                  		Address = "2nd Street at 34",
                                  		Description = "Some description"
                                  	};

            Debug.Assert(vtor.Validate(invalidCustomer).Length == 1);
            Console.WriteLine("Done.");
            Console.ReadKey(true);
        }
コード例 #45
0
        private static void Run_Example_With_Invalid_Entity(ValidatorEngine vtor)
        {
            Console.WriteLine("==Entity with Invalid values==");
            var m = new Meeting
                        {
                            Name = "NHibernate Validator virtual meeting",
                            Description = "How to configure NHibernate Validator in different ways.",
                            Start = DateTime.Now.AddHours(2), //Invalid: the Start date is minor than End.
                            End = DateTime.Now
                        };

            var invalidValues = vtor.Validate(m);
            if (invalidValues.Length == 0)
                throw new Exception("Something was wrong in the NHV configuration, the entity should be invalid.");
            else
            {
                Console.WriteLine("The entity is invalid.");
                foreach (var value in invalidValues)
                {
                    Console.WriteLine(" - " + value.Message);
                }
            }
        }
コード例 #46
0
        private static void RunSerializationTest(ValidatorEngine ve)
        {
            Address a = new Address();
            Address.blacklistedZipCode = null;
            a.Country = "Australia";
            a.Zip = "1221341234123";
            a.State = "Vic";
            a.Line1 = "Karbarook Ave";
            a.Id = 3;
            InvalidValue[] validationMessages = ve.Validate(a);

            // All work before serialization
            Assert.AreEqual(2, validationMessages.Length); //static field is tested also
            Assert.IsTrue(validationMessages[0].Message.StartsWith("prefix_"));
            Assert.IsTrue(validationMessages[1].Message.StartsWith("prefix_"));

            // Serialize and deserialize
            ValidatorEngine cvAfter = (ValidatorEngine)SerializationHelper.Deserialize(SerializationHelper.Serialize(ve));
            validationMessages = cvAfter.Validate(a);
            // Now test after
            Assert.AreEqual(2, validationMessages.Length); //static field is tested also
            Assert.IsTrue(validationMessages[0].Message.StartsWith("prefix_"));
            Assert.IsTrue(validationMessages[1].Message.StartsWith("prefix_"));
        }
コード例 #47
0
        public void DoPolimorphismWithInterfaces()
        {
            Impl obj = new Impl();
            obj.A = "hola";
            obj.B = "hola";

            ClassValidator vtor = new ClassValidator(typeof(Impl));
            vtor.GetInvalidValues(obj).Should().Have.Count.EqualTo(2);

            ClassValidator vtor2 = new ClassValidator(typeof(IContract));
            vtor2.GetInvalidValues(obj).Should("Polimorphic support is no working").Have.Count.EqualTo(1);

            ValidatorEngine ve = new ValidatorEngine();
            ve.Validate(obj).Should().Have.Count.EqualTo(2);
        }
コード例 #48
0
        public void DoPolimorphismWithClasses()
        {
            DerivatedClass d = new DerivatedClass();
            d.A = "hola";
            d.B = "hola";

            ClassValidator vtor = new ClassValidator(typeof(DerivatedClass));
            vtor.GetInvalidValues(d).Should().Have.Count.EqualTo(2);

            ClassValidator vtor2 = new ClassValidator(typeof(BaseClass));
            vtor2.GetInvalidValues(d).Should("Polimorphic support is no working").Have.Count.EqualTo(1);

            ValidatorEngine ve = new ValidatorEngine();
            ve.Validate(d).Should().Have.Count.EqualTo(2);
        }
コード例 #49
0
        public void DoPolimorphismWithInterfaces()
        {
            Impl obj = new Impl();
            obj.A = "hola";
            obj.B = "hola";

            ClassValidator vtor = new ClassValidator(typeof(Impl));
            InvalidValue[] values = vtor.GetInvalidValues(obj);
            Assert.AreEqual(2,values.Length);

            ClassValidator vtor2 = new ClassValidator(typeof(IContract));
            InvalidValue[] values2 = vtor2.GetInvalidValues(obj);
            Assert.AreEqual(1, values2.Length, "Polimorphic support is no working");

            ValidatorEngine ve = new ValidatorEngine();
            values = ve.Validate(obj);
            Assert.AreEqual(2, values.Length);
        }
コード例 #50
0
 public void UseCustomResourceManager()
 {
     var ve = new ValidatorEngine();
     var nhvc = new XmlConfiguration();
     nhvc.Properties[Environment.CustomResourceManager] = "NHibernate.Validator.Tests.Resource.Messages, " + Assembly.GetExecutingAssembly().FullName;
     nhvc.Properties[Environment.ValidatorMode] = "UseAttribute";
     ve.Configure(nhvc);
     var a = new Address {floor = -50};
     var iv = ve.Validate(a);
     Assert.That(iv.Any(x => x.Message.StartsWith("Floor cannot")));
 }
コード例 #51
0
        public void DoPolimorphismWithClasses()
        {
            DerivatedClass d = new DerivatedClass();
            d.A = "hola";
            d.B = "hola";

            ClassValidator vtor = new ClassValidator(typeof(DerivatedClass));
            InvalidValue[] values = vtor.GetInvalidValues(d);
            Assert.AreEqual(2,values.Length);

            ClassValidator vtor2 = new ClassValidator(typeof(BaseClass));
            InvalidValue[] values2 = vtor2.GetInvalidValues(d);
            Assert.AreEqual(1, values2.Length, "Polimorphic support is no working");

            ValidatorEngine ve = new ValidatorEngine();
            values = ve.Validate(d);
            Assert.AreEqual(2, values.Length);
        }
コード例 #52
0
        public void RuleInBothAttributesAndValidationDefsAppliedToChildOfRootEntity()
        {
            var configuration = new FluentConfiguration();
            configuration.SetDefaultValidatorMode(ValidatorMode.OverrideAttributeWithExternal).Register(
                new[] { typeof(ChildEntityWithAttributeRulesDef) });
            var engine = new ValidatorEngine();
            engine.Configure(configuration);

            var child = new ChildEntityWithAttributeRules { NotNullProperty = null, IsWordMonkeyAllowedInName = false, Name = "the monkey, monkey, monkey, monkety monk" };
            var parent = new ParentEntityWithAttributeRules { Child = child };

            var invalidValues = engine.Validate(parent);
            Assert.That(invalidValues.SingleOrDefault(i => i.Message == ChildEntityWithAttributeRulesDef.Message), Is.Not.Null, "Rule in def not applied");
            Assert.That(invalidValues.SingleOrDefault(i => i.PropertyName == "NotNullProperty"), Is.Not.Null, "Rule on attribute not applied");
        }
コード例 #53
0
        public void ValidateHasValidElementsWithProxies()
        {
            var validatorConf = new FluentConfiguration();
            validatorConf.SetDefaultValidatorMode(ValidatorMode.UseExternal);

            var vDefSimple = new ValidationDef<SimpleWithCollection>();
            vDefSimple.Define(s => s.Relations).HasValidElements();
            validatorConf.Register(vDefSimple);

            var vDefRelation = new ValidationDef<Relation>();
            vDefRelation.Define(s => s.Description).MatchWith("OK");
            validatorConf.Register(vDefRelation);

            var engine = new ValidatorEngine();
            engine.Configure(validatorConf);

            object savedIdRelation;
            // fill DB
            using (ISession s = OpenSession())
            using (ITransaction tx = s.BeginTransaction())
            {
                var relation = new Relation { Description = "OK" };
                savedIdRelation = s.Save(relation);
                tx.Commit();
            }

            using (ISession s = OpenSession())
            {
                var proxy = s.Load<Relation>(savedIdRelation);
                var simpleWithCol = new SimpleWithCollection();
                simpleWithCol.Relations = new List<Relation> {proxy};

                Assert.DoesNotThrow(() => engine.Validate(simpleWithCol));

                proxy.Description = "No-o-k";
                Assert.IsFalse(engine.IsValid(simpleWithCol));

            }

            CleanDb();
        }
コード例 #54
0
        public void ValidateAnyClass()
        {
            ValidatorEngine ve = new ValidatorEngine();
            Assert.IsTrue(ve.IsValid(new AnyClass()));
            Assert.IsNotNull(ve.GetValidator<AnyClass>());
            ve.AssertValid(new AnyClass()); // not cause exception
            Assert.AreEqual(0, ve.Validate(new AnyClass()).Length);
            Assert.AreEqual(0, ve.ValidatePropertyValue<AnyClass>("aprop", new AnyClass()).Length);
            Assert.AreEqual(0, ve.ValidatePropertyValue(new AnyClass(), "aprop").Length);

            Assert.AreEqual(0, ve.Validate("always valid").Length);
            Assert.AreEqual(0, ve.ValidatePropertyValue("always valid", "Length").Length);
        }
コード例 #55
0
 public void NullIsAllwaysValid()
 {
     ValidatorEngine ve = new ValidatorEngine();
     Assert.IsTrue(ve.IsValid(null));
     Assert.AreEqual(0, ve.Validate(null).Length);
     ve.AssertValid(null); // not cause exception
 }