public void CanBeSerialized() { TestsContext.AssumeSystemTypeIsSerializable(); ValidatorEngine ve = new ValidatorEngine(); NHAssert.IsSerializable(ve); }
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"); }
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)); }
/// <summary> /// Metodo responsavel por executar o mapeamento das classes com o banco de dados /// </summary> /// <param name="databaseConfigurer"></param> /// <param name="validatorEngine"></param> /// <returns></returns> private static ISessionFactory ConfigureNHibernate(IPersistenceConfigurer databaseConfigurer, out ValidatorEngine validatorEngine) { ValidatorEngine ve = null; ISessionFactory factory = Fluently.Configure() .Database(databaseConfigurer) .Mappings(m => m.FluentMappings.AddFromAssemblyOf<UsuarioMap>() .Conventions.Add(typeof(CascadeAll)) ) .Cache(x => x.UseQueryCache() .UseSecondLevelCache() .ProviderClass<SysCacheProvider>() ) .ExposeConfiguration(c => { ve = ConfigureValidator(c); c.SetProperty("adonet.batch_size", "5"); c.SetProperty("generate_statistics", "false"); //c.SetProperty("cache.use_second_level_cache", "true"); }) .BuildConfiguration().BuildSessionFactory(); validatorEngine = ve; return factory; }
private static void InjectValidationAndFieldLengths(Configuration nhConfig, string validationDefinitionsNamespace, Assembly mappingsAssembly) { if (string.IsNullOrWhiteSpace(validationDefinitionsNamespace)) { return; } var mappingsValidatorEngine = new ValidatorEngine(); var configuration = new global::NHibernate.Validator.Cfg.Loquacious.FluentConfiguration(); var validationDefinitions = mappingsAssembly.GetTypes() .Where(t => t.Namespace == validationDefinitionsNamespace) .ValidationDefinitions(); configuration .Register(validationDefinitions) .SetDefaultValidatorMode(ValidatorMode.OverrideExternalWithAttribute) .IntegrateWithNHibernate .ApplyingDDLConstraints() .And .RegisteringListeners(); mappingsValidatorEngine.Configure(configuration); //Registering of Listeners and DDL-applying here nhConfig.Initialize(mappingsValidatorEngine); }
public void IntegrationWithValidation() { ValidatorEngine ve = new ValidatorEngine(); ve.AssertValid(new Foo(1)); Assert.IsFalse(ve.IsValid(new Foo(3))); }
/// <summary> /// Instructs the builder that there are assemblies containing NHibernate.Validator /// definitions whose DDL constraints are to be used when creating the database schema /// </summary> public void AddValidationDatabaseContraints(IEnumerable <string> validationAssemblies) { var assembliesNames = validationAssemblies.Safe().Where(name => !String.IsNullOrEmpty(name)); var assemblies = assembliesNames.Select(n => Assembly.Load(n)); List <Type> validationDefinitionTypes = assemblies.SelectMany(assembly => assembly.ValidationDefinitions()).ToList(); if (validationDefinitionTypes.Count == 0) { return; } var validatorConfiguration = new FluentConfiguration(); validatorConfiguration .Register(validationDefinitionTypes) .SetDefaultValidatorMode(ValidatorMode.UseExternal) .IntegrateWithNHibernate.ApplyingDDLConstraints(); var validatorEngine = new ValidatorEngine(); validatorEngine.Configure(validatorConfiguration); NHibernateConfiguration.Initialize(validatorEngine); }
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); } }
private void injectValidationAndFieldLengths(Configuration nhConfig) { if (string.IsNullOrWhiteSpace(ValidationDefinitionsNamespace)) { return; } MappingsValidatorEngine = new ValidatorEngine(); var configuration = new FluentConfiguration(); var validationDefinitions = MappingsAssembly.GetTypes() .Where(t => t.Namespace == ValidationDefinitionsNamespace) .ValidationDefinitions(); configuration .Register(validationDefinitions) .SetDefaultValidatorMode(ValidatorMode.OverrideExternalWithAttribute) .IntegrateWithNHibernate .ApplyingDDLConstraints() .And .RegisteringListeners(); MappingsValidatorEngine.Configure(configuration); //Registering of Listeners and DDL-applying here nhConfig.Initialize(MappingsValidatorEngine); }
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); }
/// <summary> /// Initialize NHibernate's events and/or DLL. /// </summary> /// <param name="cfg">The NHibernate.Cfg.Configuration before build the session factory.</param> /// <param name="ve">A configured ValidatorEngine (after call <see cref="ValidatorEngine.Configure()"/>)</param> /// <remarks> /// <para> /// To have DDL-integration you must set the configuration property "apply_to_ddl" to true /// </para> /// <para> /// To have events-integration you must set the configuration property "autoregister_listeners" to true /// </para> /// </remarks> public static void Initialize(this Configuration cfg, ValidatorEngine ve) { if (ve.AutoGenerateFromMapping || ve.ApplyToDDL) { cfg.BuildMappings(); } if (ve.AutoGenerateFromMapping) { foreach (PersistentClass persistentClazz in cfg.ClassMappings) { ConfigureValidatorFromDDL(persistentClazz, ve); } } //Apply To DDL if (ve.ApplyToDDL) { foreach (PersistentClass persistentClazz in cfg.ClassMappings) { ApplyValidatorToDDL(persistentClazz, ve); } } //Autoregister Listeners if (ve.AutoRegisterListeners) { cfg.SetListeners(ListenerType.PreInsert, cfg.EventListeners.PreInsertEventListeners.Concat(new[] { new ValidatePreInsertEventListener() }).ToArray()); cfg.SetListeners(ListenerType.PreUpdate, cfg.EventListeners.PreUpdateEventListeners.Concat(new[] { new ValidatePreUpdateEventListener() }).ToArray()); cfg.SetListeners(ListenerType.PreCollectionUpdate, cfg.EventListeners.PreCollectionUpdateEventListeners.Concat(new[] { new ValidatePreCollectionUpdateEventListener() }).ToArray()); } }
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 AddValidatorWithoutUseIt() { ValidatorEngine ve = new ValidatorEngine(); ve.AddValidator <Boo>(); Assert.IsNotNull(ve.GetValidator <Boo>()); }
/// <summary> /// Metodo responsavel por executar o mapeamento das classes com o banco de dados /// </summary> /// <param name="databaseConfigurer"></param> /// <param name="validatorEngine"></param> /// <returns></returns> private static ISessionFactory ConfigureNHibernate(IPersistenceConfigurer databaseConfigurer, out ValidatorEngine validatorEngine) { ValidatorEngine ve = null; ISessionFactory factory = Fluently.Configure() .Database(databaseConfigurer) .Mappings(m => m.FluentMappings.AddFromAssemblyOf <FornecedorMap>() .Conventions.Add(typeof(CascadeAll)) ) .Cache(x => x.UseQueryCache() .UseSecondLevelCache() .ProviderClass <SysCacheProvider>() ) .ExposeConfiguration(c => { ve = ConfigureValidator(c); c.SetProperty("adonet.batch_size", "5"); c.SetProperty("generate_statistics", "false"); //c.SetProperty("cache.use_second_level_cache", "true"); }) .BuildConfiguration().BuildSessionFactory(); validatorEngine = ve; return(factory); }
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); }
///<remarks> /// The output of this function should be either put into your IoC container or cached somewhere to prevent /// re-reading of the config files. ///</remarks> public static ValidatorEngine CreateValidationEngine() { var validator = new ValidatorEngine(); validator.Configure(); return validator; }
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_")); }
public void ValidatePropertyValue() { var ve = new ValidatorEngine(); Assert.AreEqual(1, ve.ValidatePropertyValue <BaseClass>("A", null).Length); Assert.AreEqual(1, ve.ValidatePropertyValue <DerivatedClass>("A", null).Length); Assert.AreEqual(1, ve.ValidatePropertyValue <BaseClass>("A", "1234").Length); Assert.AreEqual(1, ve.ValidatePropertyValue <DerivatedClass>("A", "1234").Length); Assert.AreEqual(1, ve.ValidatePropertyValue <DerivatedClass>("B", "123456").Length); Assert.AreEqual(0, ve.ValidatePropertyValue <DerivatedClass>("B", null).Length); Assert.AreEqual(1, ve.ValidatePropertyValue <BaseClass, string>(x => x.A, null).Length); Assert.AreEqual(1, ve.ValidatePropertyValue <DerivatedClass, string>(x => x.A, null).Length); Assert.AreEqual(1, ve.ValidatePropertyValue <BaseClass, string>(x => x.A, "1234").Length); Assert.AreEqual(1, ve.ValidatePropertyValue <DerivatedClass, string>(x => x.A, "1234").Length); Assert.AreEqual(1, ve.ValidatePropertyValue <DerivatedClass, string>(x => x.B, "123456").Length); Assert.AreEqual(0, ve.ValidatePropertyValue <DerivatedClass, string>(x => x.B, null).Length); try { ve.ValidatePropertyValue <DerivatedClass>("WrongName", null); Assert.Fail("Intent to validate a wrong property don't throw any exception."); } catch (TargetException) { //ok } }
public override ValidatorEngine GetValidatorEngine() { Environment.ConstraintValidatorFactory = new TestConstraintValidatorFactory(); var ve = new ValidatorEngine(); return(ve); }
private static IValidatorEngine ManuallyBuildValidatorSources() { var scanSource = new ModelScanValidatorSource(); var customerValidatorSource = new CustomerValidatorSource(); var engine = new ValidatorEngine(new IValidatorSource[] { scanSource, customerValidatorSource }); return engine; }
public ViewValidator() { if (validatorEngine == null) { validatorEngine = new ValidatorEngine(); } }
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 ConfigureFile() { // This test is for .Configure(XmlReader) too string tmpf = Path.GetTempFileName(); using (StreamWriter sw = new StreamWriter(tmpf)) { sw.WriteLine("<?xml version='1.0' encoding='utf-8' ?>"); sw.WriteLine("<nhv-configuration xmlns='urn:nhv-configuration-1.0'>"); sw.WriteLine("<property name='apply_to_ddl'>false</property>"); sw.WriteLine("<property name='autoregister_listeners'>false</property>"); sw.WriteLine("<property name='default_validator_mode'>OverrideAttributeWithExternal</property>"); sw.WriteLine("<property name='message_interpolator_class'>" + typeof(PrefixMessageInterpolator).AssemblyQualifiedName + "</property>"); sw.WriteLine("</nhv-configuration>"); sw.Flush(); } ValidatorEngine ve = new ValidatorEngine(); ve.Configure(tmpf); Assert.AreEqual(false, ve.ApplyToDDL); Assert.AreEqual(false, ve.AutoRegisterListeners); Assert.AreEqual(ValidatorMode.OverrideAttributeWithExternal, ve.DefaultMode); Assert.IsNotNull(ve.Interpolator); Assert.AreEqual(typeof(PrefixMessageInterpolator), ve.Interpolator.GetType()); }
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); } } }
public NHibernateValidatorClientModelValidator(ModelMetadata metadata, ControllerContext controllerContext, IClassValidator validator, ValidatorEngine engine) : base(metadata, controllerContext) { _engine = engine; _validator = validator; this.PropertyName = metadata.PropertyName; }
public void ValidateDecimal() { var configure = new FluentConfiguration(); var validationDef = new ValidationDef <EntityWithFloats <decimal> >(); validationDef.Define(e => e.Value).Satisfy(v => v > 0).WithMessage("Value > 0"); 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 EntityWithFloats <decimal> { Value = 1, NullValue = 1 })); Assert.That(!ve.IsValid(new EntityWithFloats <decimal>())); Assert.That(!ve.IsValid(new EntityWithFloats <decimal> { Value = 1 })); Assert.That(!ve.IsValid(new EntityWithFloats <decimal> { NullValue = 1 })); }
public void Configure(IWindsorContainer container) { var ve = new ValidatorEngine(); container.Register(Component.For<IEntityValidator>() .ImplementedBy<EntityValidator>()); container.Register(Component.For<ValidatorEngine>() .Instance(ve) .LifeStyle.Singleton); //Register the service for ISharedEngineProvider container.Register(Component.For<ISharedEngineProvider>() .ImplementedBy<NHVSharedEngineProvider>()); //Assign the shared engine provider for NHV. Environment.SharedEngineProvider = container.Resolve<ISharedEngineProvider>(); //Configure validation framework fluently var configure = new FluentConfiguration(); configure.Register(typeof (WorkerValidationDefenition).Assembly.ValidationDefinitions()) .SetDefaultValidatorMode(ValidatorMode.OverrideAttributeWithExternal) .AddEntityTypeInspector<NHVTypeInspector>() .IntegrateWithNHibernate.ApplyingDDLConstraints().And.RegisteringListeners(); ve.Configure(configure); }
private static ValidatorEngine GetValidatorEngine() { var cfg = GetNhvConfiguration(); var validatorEngine = new ValidatorEngine(); validatorEngine.Configure(cfg); return validatorEngine; }
protected override void Configure(NHibernate.Cfg.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; var enversConf = new FluentConfiguration(); enversConf.Audit <Address>(); configuration.IntegrateWithEnvers(enversConf); ve.Configure(nhvc); ValidatorInitializer.Initialize(configuration); }
public void Install(IWindsorContainer container, IConfigurationStore store) { var ve = new ValidatorEngine(); container.Register(Component.For <IEntityValidator>() .ImplementedBy <EntityValidator>()); container.Register(Component.For <ValidatorEngine>() .Instance(ve) .LifeStyle.Singleton); //Register the service for ISharedEngineProvider container.Register(Component.For <ISharedEngineProvider>() .ImplementedBy <SharedEngineProvider>()); //Assign the shared engine provider for NHV. Environment.SharedEngineProvider = container.Resolve <ISharedEngineProvider>(); //Configure validation framework fluently var configure = new FluentConfiguration(); configure.Register(typeof(AlbumValidationDef).Assembly.ValidationDefinitions()) .SetDefaultValidatorMode(ValidatorMode.OverrideAttributeWithExternal) .IntegrateWithNHibernate.ApplyingDDLConstraints().And.RegisteringListeners(); ve.Configure(configure); }
public UserService(ICapRedV2UserManager <CapRedV2User> userManager, ICapRedV2SignInManager <CapRedV2User> signInManager, ValidatorEngine <CapRedV2UserSignUpDTO> signUpValidatorEngine, ValidatorEngine <CapRedV2UserLoginDTO> loginValidatorEngine) { _userManager = userManager ?? throw new ArgumentNullException(nameof(userManager)); _signInManager = signInManager ?? throw new ArgumentNullException(nameof(signInManager)); _signUpValidatorEngine = signUpValidatorEngine ?? throw new ArgumentNullException(nameof(signUpValidatorEngine)); _loginValidatorEngine = loginValidatorEngine ?? throw new ArgumentNullException(nameof(loginValidatorEngine)); }
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 CreateEngine() { var conf = new XmlConfiguration(); conf.Properties[Environment.ValidatorMode] = "UseExternal"; conf.Mappings.Add(new MappingConfiguration("NHibernate.Validator.Tests", "NHibernate.Validator.Tests.Engine.Tagging.EntityXml.nhv.xml")); ve = new ValidatorEngine(); ve.Configure(conf); }
///<remarks> /// The output of this function should be either put into your IoC container or cached somewhere to prevent /// re-reading of the config files. ///</remarks> public static ValidatorEngine CreateValidationEngine() { var validator = new ValidatorEngine(); validator.Configure(); return(validator); }
public void IntegrationWithValidation() { var ve = new ValidatorEngine(); ve.AssertValid(new Foo(1)); Assert.IsFalse(ve.IsValid(new Foo(3))); }
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)); }
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 }
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); }
private static void ConfigureNHibernateValidator(Configuration configuration) { INHVConfiguration nhvc = (INHVConfiguration)new NHibernate.Validator.Cfg.Loquacious.FluentConfiguration() .SetDefaultValidatorMode(ValidatorMode.UseAttribute); var validator = new ValidatorEngine(); validator.Configure(nhvc); configuration.Initialize(validator); }
public void CreateValidatorEngine() { var configure = new FluentConfiguration(); configure.Register(new[] {typeof (UserValidation), typeof (GroupValidation)}) .SetDefaultValidatorMode(ValidatorMode.UseExternal); validatorEngine = new ValidatorEngine(); validatorEngine.Configure(configure); }
public void CreateEngine() { var conf = new FluentConfiguration(); conf.SetDefaultValidatorMode(ValidatorMode.UseExternal); conf.Register <EntityLoqValidation, EntityLoq>(); ve = new ValidatorEngine(); ve.Configure(conf); }
public ViewValidator(ValidatorEngine validatorEngine, ErrorProvider errorProvider) : this(errorProvider) { Check.NotNull( validatorEngine, "ve", "The ValidatorEngine is null"); this.validatorEngine = validatorEngine; }
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 })); }
protected override void Configure(NHibernate.Cfg.Configuration configuration) { base.Configure(configuration); var nhvc = new FluentConfiguration(); nhvc.SetDefaultValidatorMode(ValidatorMode.UseAttribute).IntegrateWithNHibernate.ApplyingDDLConstraints().And. RegisteringListeners(); var onlyToUseToInitializeNh_Engine = new ValidatorEngine(); onlyToUseToInitializeNh_Engine.Configure(nhvc); configuration.Initialize(onlyToUseToInitializeNh_Engine); }
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 ValidatorEngine GetValidatorEngine() { var vtor = new ValidatorEngine(); var cfg = new XmlConfiguration(); cfg.Properties[Environment.ValidatorMode] = "UseExternal"; string an = Assembly.GetExecutingAssembly().FullName; cfg.Mappings.Add(new MappingConfiguration(an, "NHibernate.Validator.Tests.Specifics.NHV29.Mappings.nhv.xml")); vtor.Configure(cfg); return vtor; }
public static void Validate(this IValidatable model, ModelStateDictionary state) { InvalidValue[] invalidValues = new ValidatorEngine().Validate(model); foreach (var error in invalidValues) { var errorMessage = error.PropertyName + " " + error.Message; state.AddModelError(errorMessage, errorMessage); } }
protected ValidatorEngine ConfigureValidator(NHibernate.Cfg.Configuration configuration) { var nhvc = new FluentConfiguration(); nhvc.SetDefaultValidatorMode(ValidatorMode.UseExternal).IntegrateWithNHibernate.ApplyingDDLConstraints(); nhvc.Register<PersonValidation, Person>(); nhvc.Register<NameValidation, Name>(); var engine = new ValidatorEngine(); engine.Configure(nhvc); return engine; }
public override ValidatorEngine GetValidatorEngine() { var ve = new ValidatorEngine(); var cfg = new XmlConfiguration(); cfg.Properties[Environment.ValidatorMode] = "UseExternal"; cfg.Properties[Environment.ConstraintValidatorFactoryClass] = typeof (TestConstraintValidatorFactory).AssemblyQualifiedName; ve.Configure(cfg); return ve; }
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(); }
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 static ValidatorEngine Get_Engine_Configured_for_Fluent() { var vtor = new ValidatorEngine(); var configuration = new FluentConfiguration(); configuration .Register(Assembly.GetExecutingAssembly().GetTypes().Where(t => t.Namespace.Equals("NHibernate.Validator.Demo.Ev.Validators")) .ValidationDefinitions()) .SetDefaultValidatorMode(ValidatorMode.UseExternal); vtor.Configure(configuration); return vtor; }
public static ValidatorEngine Get_Engine_Configured_for_Xml() { var vtor = new ValidatorEngine(); var nhvc = new XmlConfiguration(); nhvc.Properties[Environment.ApplyToDDL] = "false"; nhvc.Properties[Environment.AutoregisterListeners] = "false"; nhvc.Properties[Environment.ValidatorMode] = "UseExternal"; nhvc.Mappings.Add(new MappingConfiguration("NHibernate.Validator.Demo.Ev", null)); vtor.Configure(nhvc); return vtor; }
public void Configure() { ValidatorEngine ve = new ValidatorEngine(); ve.Configure(); Assert.AreEqual(true, ve.ApplyToDDL); Assert.AreEqual(true, ve.AutoRegisterListeners); Assert.AreEqual(ValidatorMode.UseAttribute, ve.DefaultMode); Assert.IsNotNull(ve.Interpolator); Assert.AreEqual(typeof(PrefixMessageInterpolator), ve.Interpolator.GetType()); }
public void CanInitialezeValidatorEngine() { var fc = new FluentConfiguration(); fc.SetDefaultValidatorMode(ValidatorMode.UseExternal) .Register<AddressValidationDef, Address>().Register<BooValidationDef, Boo>() .IntegrateWithNHibernate.AvoidingDDLConstraints().And.AvoidingListenersRegister(); var ve = new ValidatorEngine(); ve.Configure(fc); Assert.That(ve.GetValidator<Address>(), Is.Not.Null); Assert.That(ve.GetValidator<Boo>(), Is.Not.Null); }
public ValidatorFixtureLoquacious() { var configure = new FluentConfiguration(); configure.Register( Assembly.GetExecutingAssembly().GetTypes() .Where(t => t.Namespace.Equals("NHibernate.Validator.Tests.Base")) .ValidationDefinitions()) .SetDefaultValidatorMode(ValidatorMode.UseExternal); ve = new ValidatorEngine(); ve.Configure(configure); }