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'"));
        }
        public void Engine_Validate()
        {
            var configure = new FluentConfiguration();
            configure.Register(new[] {typeof (RangeDef)}).SetDefaultValidatorMode(ValidatorMode.UseExternal);
            var ve = new ValidatorEngine();

            ve.Configure(configure);

            Assert.That(!ve.IsValid(new Range { Start = 5, End = 4 }));
            Assert.That(ve.IsValid(new Range { Start = 1, End = 4 }));
        }
        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);
        }
        public void ValidateWithSingleCondition()
        {
            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'");

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

            ve.Configure(configure);

            Assert.That(ve.IsValid(new EntityWithString {Name = "abc"}));
            Assert.That(!ve.IsValid(new EntityWithString { Name = "bc" }));
        }
        public void IntegrationWithValidation()
        {
            ValidatorEngine ve = new ValidatorEngine();
            ve.AssertValid(new Foo(1));

            Assert.IsFalse(ve.IsValid(new Foo(3)));
        }
        public void Validate()
        {
            var configure = new FluentConfiguration();

            var validationDef = new ValidationDef<EntityWithCollection>();
            validationDef.Define(e => e.Value).Satisfy(v => v != null && v.Any(e => e == "something")).WithMessage("Should contain 'something'");

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

            ve.Configure(configure);

            Assert.That(ve.IsValid(new EntityWithCollection { Value = new[]{"b", "something"} }));
            Assert.That(!ve.IsValid(new EntityWithCollection()));
            Assert.That(!ve.IsValid(new EntityWithCollection { Value = new[] { "b" } }));
        }
        public void Validate()
        {
            var configure = new FluentConfiguration();

            var validationDef = new ValidationDef<EntityWithDate>();
            validationDef.Define(e => e.Value).Satisfy(v => v.Year == DateTime.Today.Year).WithMessage("In this year");
            validationDef.Define(e => e.NullValue).Satisfy(v => v.HasValue).WithMessage("HasValue");

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

            ve.Configure(configure);

            Assert.That(ve.IsValid(new EntityWithDate { Value = DateTime.Today, NullValue = DateTime.Today }));
            Assert.That(!ve.IsValid(new EntityWithDate()));
            Assert.That(!ve.IsValid(new EntityWithDate { Value = DateTime.Today }));
            Assert.That(!ve.IsValid(new EntityWithDate { NullValue = DateTime.Today }));
        }
        public void DelegatedValidate_WithoutMessageNotThrow()
        {
            var configure = new FluentConfiguration();
            configure.Register(new[] { typeof(RangeDefWithoutCustomMessage) })
                .SetDefaultValidatorMode(ValidatorMode.UseExternal);
            var ve = new ValidatorEngine();

            ve.Configure(configure);
            ActionAssert.NotThrow(()=>ve.IsValid(new Range { Start = 1, End = 4 }));
        }
        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'"));
        }
Exemple #10
0
 public void LoadMappingsSpecific()
 {
     var nhvc = new XmlConfiguration();
     nhvc.Properties[Environment.ValidatorMode] = "useExternal";
     nhvc.Properties[Environment.MappingLoaderClass] = "NHibernate.Validator.Cfg.Loquacious.FluentMappingLoader, NHibernate.Validator";
     nhvc.Mappings.Add(new MappingConfiguration("NHibernate.Validator.Tests",
                                                "NHibernate.Validator.Tests.Configuration.Loquacious.AddressValidationDef"));
     nhvc.Mappings.Add(new MappingConfiguration("NHibernate.Validator.Tests",
                                                                                          "NHibernate.Validator.Tests.Configuration.Loquacious.BooValidationDef"));
     var ve = new ValidatorEngine();
     ve.Configure(nhvc);
     var a = new Address {Country = string.Empty};
     var b = new Boo();
     Assert.That(ve.IsValid(a));
     Assert.That(!ve.IsValid(b));
     a.Country = "bigThan5Chars";
     Assert.That(!ve.IsValid(a));
     b.field = "whatever";
     Assert.That(ve.IsValid(b));
 }
        public void Validate()
        {
            var configure = new FluentConfiguration();

            var validationDef = new ValidationDef <EntityWithCollection>();

            validationDef.Define(e => e.Value).Satisfy(v => v != null && v.Any(e => e == "something")).WithMessage("Should contain 'something'");

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

            ve.Configure(configure);

            Assert.That(ve.IsValid(new EntityWithCollection {
                Value = new[] { "b", "something" }
            }));
            Assert.That(!ve.IsValid(new EntityWithCollection()));
            Assert.That(!ve.IsValid(new EntityWithCollection {
                Value = new[] { "b" }
            }));
        }
        public void ValidateWithSingleCondition()
        {
            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'");

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

            ve.Configure(configure);

            Assert.That(ve.IsValid(new EntityWithString {
                Name = "abc"
            }));
            Assert.That(!ve.IsValid(new EntityWithString {
                Name = "bc"
            }));
        }
Exemple #13
0
        public void DelegatedValidate_WithoutMessageNotThrow()
        {
            var configure = new FluentConfiguration();

            configure.Register(new[] { typeof(RangeDefWithoutCustomMessage) })
            .SetDefaultValidatorMode(ValidatorMode.UseExternal);
            var ve = new ValidatorEngine();

            ve.Configure(configure);
            ActionAssert.NotThrow(() => ve.IsValid(new Range {
                Start = 1, End = 4
            }));
        }
        /// <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);
        }
        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);
        }
Exemple #16
0
        public void IsValid()
        {
            ve = new ValidatorEngine();

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

                    t.Start();
                }
            });
        }
Exemple #17
0
        public void IsValid()
        {
            ve = new ValidatorEngine();

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

                    t.Start();
                }
            });
        }
        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();
        }
        public void ValidateInitializedProxyAtDeepLevel()
        {
            var validatorConf = new FluentConfiguration();

            validatorConf.SetDefaultValidatorMode(ValidatorMode.UseExternal);

            var vDefSimple = new ValidationDef <SimpleWithRelation>();

            vDefSimple.Define(s => s.Name).MatchWith("OK");
            vDefSimple.Define(s => s.Relation).IsValid();
            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);
                NHibernateUtil.Initialize(proxy);
                Assert.That(engine.IsValid(new SimpleWithRelation {
                    Name = "OK", Relation = proxy
                }));
                Assert.DoesNotThrow(() => engine.AssertValid(new SimpleWithRelation {
                    Name = "OK", Relation = proxy
                }));
            }

            CleanDb();
        }
        private static void Run_Example_With_Valid_Entity(ValidatorEngine vtor)
        {
            Console.WriteLine("==Entity with valid values==");
            var m = new Meeting
                        {
                            Name = "NHibernate Validator virtual meeting",
                            Description = "How to configure NHibernate Validator in different ways.",
                            Start = DateTime.Now,
                            End = DateTime.Now.AddHours(2) // 2 hours of meeting.
                        };

            if(vtor.IsValid(m))
                Console.WriteLine("The entity is valid.");
            else
                throw new Exception("Something was wrong in the NHV configuration, the entity should be invalid.");
        }
        /// <summary>
        /// Filter implementation to validate input data
        /// </summary>
        /// <param name="actionContext">http action context</param>
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            InputLead input = new InputLead();

            input.LeadID = (string)actionContext.ActionArguments["leadID"];
            ConfigureValidator();
            if (!_ve.IsValid(input))
            {
                var    results = _ve.Validate(input);
                string errors  = "";
                foreach (InvalidValue error in results)
                {
                    errors += error.Message + ". ";
                }
                actionContext.Response = actionContext.Request.CreateErrorResponse(System.Net.HttpStatusCode.BadRequest, errors);
                return;
            }
            base.OnActionExecuting(actionContext);
        }
Exemple #22
0
        private static void Run_Example_With_Valid_Entity(ValidatorEngine vtor)
        {
            Console.WriteLine("==Entity with valid values==");
            var m = new Meeting
            {
                Name        = "NHibernate Validator virtual meeting",
                Description = "How to configure NHibernate Validator in different ways.",
                Start       = DateTime.Now,
                End         = DateTime.Now.AddHours(2)                         // 2 hours of meeting.
            };

            if (vtor.IsValid(m))
            {
                Console.WriteLine("The entity is valid.");
            }
            else
            {
                throw new Exception("Something was wrong in the NHV configuration, the entity should be invalid.");
            }
        }
Exemple #23
0
        protected override void Configure(Configuration configuration)
        {
            // The ValidatorInitializer and the ValidateEventListener share the same engine

            // Initialize the SharedEngine
            fortest = new NHibernateSharedEngineProvider();
            Cfg.Environment.SharedEngineProvider = fortest;
            ValidatorEngine ve = Cfg.Environment.SharedEngineProvider.GetEngine();

            ve.Clear();
            XmlConfiguration nhvc = new XmlConfiguration();

            nhvc.Properties[Cfg.Environment.ApplyToDDL]               = "true";
            nhvc.Properties[Cfg.Environment.AutoregisterListeners]    = "true";
            nhvc.Properties[Cfg.Environment.ValidatorMode]            = "UseAttribute";
            nhvc.Properties[Cfg.Environment.MessageInterpolatorClass] = typeof(PrefixMessageInterpolator).AssemblyQualifiedName;
            ve.Configure(nhvc);
            ve.IsValid(new AnyClass());            // add the element to engine for test

            ValidatorInitializer.Initialize(configuration);
        }
        public void InitializeValidators()
        {
            ValidatorEngine  ve   = new ValidatorEngine();
            XmlConfiguration nhvc = new XmlConfiguration();

            nhvc.Properties[Environment.ApplyToDDL]               = "false";
            nhvc.Properties[Environment.AutoregisterListeners]    = "false";
            nhvc.Properties[Environment.ValidatorMode]            = "overrideattributewithExternal";
            nhvc.Properties[Environment.MessageInterpolatorClass] = typeof(PrefixMessageInterpolator).AssemblyQualifiedName;
            string an = Assembly.GetExecutingAssembly().FullName;

            nhvc.Mappings.Add(new MappingConfiguration(an, "NHibernate.Validator.Tests.Base.Address.nhv.xml"));
            ve.Configure(nhvc);
            Assert.IsNotNull(ve.GetValidator <Address>());

            Assert.IsNull(ve.GetValidator <Boo>());
            // Validate something and then its validator is initialized
            Boo b = new Boo();

            ve.IsValid(b);
            Assert.IsNotNull(ve.GetValidator <Boo>());
        }
        public void ValidateNotInitializeProxyAtFirstLevel()
        {
            var validatorConf = new FluentConfiguration();

            validatorConf.SetDefaultValidatorMode(ValidatorMode.UseExternal);

            var vDefSimple = new ValidationDef <SimpleWithRelation>();

            vDefSimple.Define(s => s.Name).MatchWith("OK");
            validatorConf.Register(vDefSimple);

            var engine = new ValidatorEngine();

            engine.Configure(validatorConf);

            object savedId;

            // fill DB
            using (ISession s = OpenSession())
                using (ITransaction tx = s.BeginTransaction())
                {
                    savedId = s.Save(new SimpleWithRelation {
                        Name = "OK"
                    });
                    tx.Commit();
                }

            using (ISession s = OpenSession())
            {
                var proxy = s.Load <SimpleWithRelation>(savedId);
                Assert.That(engine.IsValid(proxy));
                Assert.DoesNotThrow(() => engine.AssertValid(proxy));
                Assert.That(!NHibernateHelper.IsInitialized(proxy), "should not initialize the proxy");
            }

            CleanDb();
        }
 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
 }
Exemple #27
0
		public static bool Valido(this Entidade entidade)
		{
			ValidatorEngine engine = new ValidatorEngine();

			return engine.IsValid(entidade);
		}
Exemple #28
0
 public bool IsValid(object entityInstance)
 {
     return(validatorEngine.IsValid(entityInstance));
 }
        public bool IsValid(object value)
        {
            Check.Require(value != null, "value to IsValid may not be null");

            return(ValidatorEngine.IsValid(value));
        }
        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();
        }
        public void ValidateNotInitializeProxyAtFirstLevel()
        {
            var validatorConf = new FluentConfiguration();
            validatorConf.SetDefaultValidatorMode(ValidatorMode.UseExternal);

            var vDefSimple = new ValidationDef<SimpleWithRelation>();
            vDefSimple.Define(s => s.Name).MatchWith("OK");
            validatorConf.Register(vDefSimple);

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

            object savedId;
            // fill DB
            using (ISession s = OpenSession())
            using (ITransaction tx = s.BeginTransaction())
            {
                savedId = s.Save(new SimpleWithRelation { Name = "OK" });
                tx.Commit();
            }

            using (ISession s = OpenSession())
            {
                var proxy = s.Load<SimpleWithRelation>(savedId);
                Assert.That(engine.IsValid(proxy));
                Assert.DoesNotThrow(() => engine.AssertValid(proxy));
                Assert.That(!NHibernateUtil.IsInitialized(proxy), "should not initialize the proxy");
            }

            CleanDb();
        }
        public void ValidateInitializedProxyAtDeepLevel()
        {
            var validatorConf = new FluentConfiguration();
            validatorConf.SetDefaultValidatorMode(ValidatorMode.UseExternal);

            var vDefSimple = new ValidationDef<SimpleWithRelation>();
            vDefSimple.Define(s => s.Name).MatchWith("OK");
            vDefSimple.Define(s => s.Relation).IsValid();
            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);
                NHibernateUtil.Initialize(proxy);
                Assert.That(engine.IsValid(new SimpleWithRelation { Name = "OK", Relation = proxy }));
                Assert.DoesNotThrow(() => engine.AssertValid(new SimpleWithRelation { Name = "OK", Relation = proxy }));
            }

            CleanDb();
        }
        public void InitializeValidators()
        {
            ValidatorEngine ve = new ValidatorEngine();
            XmlConfiguration nhvc = new XmlConfiguration();
            nhvc.Properties[Environment.ApplyToDDL] = "false";
            nhvc.Properties[Environment.AutoregisterListeners] = "false";
            nhvc.Properties[Environment.ValidatorMode] = "overrideattributewithExternal";
            nhvc.Properties[Environment.MessageInterpolatorClass] = typeof(PrefixMessageInterpolator).AssemblyQualifiedName;
            string an = Assembly.GetExecutingAssembly().FullName;
            nhvc.Mappings.Add(new MappingConfiguration(an, "NHibernate.Validator.Tests.Base.Address.nhv.xml"));
            ve.Configure(nhvc);
            Assert.IsNotNull(ve.GetValidator<Address>());

            Assert.IsNull(ve.GetValidator<Boo>());
            // Validate something and then its validator is initialized
            Boo b = new Boo();
            ve.IsValid(b);
            Assert.IsNotNull(ve.GetValidator<Boo>());
        }
        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);
        }
Exemple #35
0
        public void InvalidValuesInCollections()
        {
            // we are testing it using proxies created by NH
            Person parent = CreateGrandparent();

            SavePerson(parent);

            // Generic collection
            using (ISession s = OpenSession())
                using (ITransaction tx = s.BeginTransaction())
                {
                    Person p = s.CreateQuery("from Person p where p.Name = 'GP'")
                               .UniqueResult <Person>();
                    IEnumerator <Person> ep = p.Children.GetEnumerator();
                    ep.MoveNext();
                    Person aChildren         = ep.Current;
                    IEnumerator <Person> ep1 = aChildren.Children.GetEnumerator();
                    ep1.MoveNext();
                    Person aCh11 = ep1.Current;

                    Assert.IsTrue(vengine.IsValid(p));

                    aCh11.Name = null;

                    Assert.IsFalse(vengine.IsValid(p));

                    tx.Rollback();
                }

            // No generic collection
            using (ISession s = OpenSession())
                using (ITransaction tx = s.BeginTransaction())
                {
                    Person p = s.CreateQuery("from Person p where p.Name = 'GP'")
                               .UniqueResult <Person>();
                    IEnumerator ep = p.Friends.GetEnumerator();
                    ep.MoveNext();
                    Person aFriend = (Person)ep.Current;
                    Assert.IsTrue(vengine.IsValid(p));

                    aFriend.Name = "A";

                    Assert.IsFalse(vengine.IsValid(p));

                    tx.Rollback();
                }

            // Many-to-one
            using (ISession s = OpenSession())
                using (ITransaction tx = s.BeginTransaction())
                {
                    Person p = s.CreateQuery("from Person p where p.Name = 'C1'")
                               .UniqueResult <Person>();
                    NHibernateUtil.Initialize(p.Parent);

                    Assert.IsTrue(vengine.IsValid(p));

                    p.Parent.Name = "A";

                    Assert.IsFalse(vengine.IsValid(p));

                    tx.Rollback();
                }
            CleanUp();
        }