public void RegisterSpecificDefinitions()
 {
     var fc = new FluentConfiguration();
     fc.Register<AddressValidationDef, Address>().Register<BooValidationDef, Boo>();
     var ml = (IMappingLoader) fc;
     Assert.That(ml.GetMappings().Count(), Is.EqualTo(2));
 }
 public void ConfigureCustomResourceManager()
 {
     var fc = new FluentConfiguration();
     fc.SetCustomResourceManager("NHibernate.Validator.Tests.Resource.Messages", Assembly.GetExecutingAssembly());
     var cfg = (INHVConfiguration)fc;
     Assert.That(cfg.Properties[Environment.CustomResourceManager], Is.EqualTo("NHibernate.Validator.Tests.Resource.Messages, " + Assembly.GetExecutingAssembly().FullName));
 }
Exemplo n.º 3
0
        static void Main(string[] args)
        {
#if DEBUG      
            IConfiguration configuration; // = new JsonConfiguration("test.json");
            if (args.Length == 1)
            {
                configuration = new JsonConfiguration(args[0]);
            }
            else
            {
                configuration = new FluentConfiguration(@".\db")
                    //.AddInput("MongoDb", "logs", "mongodb://*****:*****@"C:\PerfLogs\log-file.txt")
                    .AddInput("WindowsEventLog", "Application")
                    //.AddInput("File", "2", @"D:\log-file.txt")
                    //.AddFilter("RegExTimeStamp", "Type==\"File\" && Id==\"2\"", @"^[\d]{4}-[\d]{2}-[\d]{2} [\d]{2}:[\d]{2}:[\d]{2}", @"Message")
                    //.AddInput("SqlServer", "ServerName", "DatabaseName", "TableName", "TableId", "CurrentDate", "UserName", "Password")
                    .AddOutput("Console");
            }
#else
            IConfiguration configuration = new JsonConfiguration(args[0]);
#endif

            using (EventHerder eventHerder = new EventHerder(configuration))
            {
                

                Console.WriteLine("Press ENTER to exit...");
                Console.ReadLine();
            }
        }
        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);
        }
Exemplo n.º 5
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'"));
        }
Exemplo n.º 6
0
        public void CreateValidatorEngine()
        {
            var configure = new FluentConfiguration();
            configure.Register(new[] {typeof (UserValidation), typeof (GroupValidation)})
                .SetDefaultValidatorMode(ValidatorMode.UseExternal);
            validatorEngine = new ValidatorEngine();

            validatorEngine.Configure(configure);
        }
Exemplo n.º 7
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 }));
        }
 public void RegisterDefinitions()
 {
     var fc = new FluentConfiguration();
     fc.Register(
         Assembly.GetExecutingAssembly().ValidationDefinitions()
         .Where(x => x.Namespace.Equals("NHibernate.Validator.Tests.Configuration.Loquacious") &&
         (x.Name.StartsWith("Address") || x.Name.StartsWith("Boo"))));
     var ml = (IMappingLoader)fc;
     Assert.That(ml.GetMappings().Count(), Is.EqualTo(2));
 }
 public TypeMappingConfig(FluentConfiguration fluentConfiguration, Type type)
 {
     if (fluentConfiguration == null)
         throw new ArgumentNullException("fluentConfiguration");
     if (type == null)
         throw new ArgumentNullException("type");
     _configuration = fluentConfiguration;
     _type = type;
     _mapping = new TypeMappingInfo { Type = type, IdentityField = fluentConfiguration.IdPropertyName };
 }
 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;
 }
Exemplo n.º 11
0
 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);
 }
Exemplo n.º 12
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();
        }
Exemplo n.º 13
0
        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 }));
        }
Exemplo n.º 14
0
 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;
 }
Exemplo n.º 15
0
        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);
        }
        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);
        }
Exemplo n.º 17
0
        public override ValidatorEngine GetValidatorEngine()
        {
            var ve = new ValidatorEngine();
            var configuration = new FluentConfiguration();
            configuration
                .SetConstraintValidatorFactory<TestConstraintValidatorFactory>()
                .SetDefaultValidatorMode(ValidatorMode.UseExternal)
                .Register(new [] { typeof(Foo) }) ;

            ve.Configure(configuration);
            return ve;
        }
Exemplo n.º 18
0
 private static FluentConfiguration GetNhvConfiguration()
 {
     var nhvConfiguration = new FluentConfiguration();
       nhvConfiguration
     .SetDefaultValidatorMode(ValidatorMode.UseExternal)
     .Register(Assembly.Load("Eg.ClassValidation")
             .ValidationDefinitions())
     .IntegrateWithNHibernate
     .ApplyingDDLConstraints()
     .And
     .RegisteringListeners();
       return nhvConfiguration;
 }
        public LoquaciousInheritanceFixture()
        {
            var configure = new FluentConfiguration();
            configure.Register(
                Assembly.Load("NHibernate.Validator.Tests")
                .ValidationDefinitions()
                .Where(t => t.Namespace.Equals("NHibernate.Validator.Tests.Inheritance"))
                )
            .SetDefaultValidatorMode(ValidatorMode.UseExternal);

            ve = new ValidatorEngine();
            ve.Configure(configure);
        }
Exemplo n.º 20
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();
        }
Exemplo n.º 21
0
        private static void ConfigurarStringConexao <TThisConfiguration, TConnectionString>(
            this FluentConfiguration configFluente,
            PersistenceConfiguration <TThisConfiguration, TConnectionString> persistenceConfiguration,
            bool showSql)
            where TThisConfiguration : PersistenceConfiguration <TThisConfiguration, TConnectionString>
            where TConnectionString : ConnectionStringBuilder, new()
        {
            const string connectionStringKey = "ExemploConexao";

            if (showSql)
            {
                persistenceConfiguration.ShowSql();
            }
            persistenceConfiguration.ConnectionString(c => c.FromConnectionStringWithKey(connectionStringKey));
            configFluente.Database(persistenceConfiguration);
        }
        public static FluentConfiguration CreateSQLServerSchemas(this FluentConfiguration fluentConfiguration)
        {
            return(fluentConfiguration.ExposeDbCommand((command, cfg) =>
            {
                var schemas = cfg.ClassMappings.Select(x => x.Table.Schema).Where(x => !string.IsNullOrEmpty(x))
                              .Distinct()
                              .Select(x => cfg.NamingStrategy.TableName(x))
                              .ToList();

                foreach (var schema in schemas)
                {
                    command.CommandText = $"IF NOT EXISTS(SELECT * FROM sys.schemas  WHERE name = N'{schema}') EXEC('CREATE SCHEMA [{schema}]');";
                    command.ExecuteNonQuery();
                }
            }));
        }
Exemplo n.º 23
0
 private static void CreateMappings(FluentConfiguration fmc)
 {
     (from a in AppDomain.CurrentDomain.GetAssemblies() select a into assemblies select assemblies).ToList().ForEach(a =>
     {
         if (a.FullName.StartsWith("_DAO"))
         {
             foreach (var type in a.DefinedTypes)
             {
                 if (type.FullName.StartsWith("_DAO.Maps") && !type.FullName.StartsWith("_DAO.Maps.BaseEntityMap"))
                 {
                     fmc.Mappings(m => m.FluentMappings.Add(type));
                 }
             }
         }
     });
 }
Exemplo n.º 24
0
        private static void InitializeFromConfigMsSql(FluentConfiguration fluentConfiguration,
                                                      DbConnectionSettings settings,
                                                      Action <MsSqlConfiguration> additionalClientConfiguration = null)
        {
            var clientConfiguration = MsSqlConfiguration.MsSql2008.ConnectionString(c => c
                                                                                    .Server(settings.ServerName)
                                                                                    .Database(settings.DataBaseName)
                                                                                    .Username(settings.UserName)
                                                                                    .Password(settings.UserPassword));

            additionalClientConfiguration?.Invoke(clientConfiguration);

            fluentConfiguration.Database(clientConfiguration);

            PerformCommonInitialization(fluentConfiguration, settings.ShowSql);
        }
Exemplo n.º 25
0
        private void InitMapping(FluentConfiguration fluentConfiguration)
        {
            fluentConfiguration.Mappings(
                x =>
            {
                x.AutoMappings.Add(PersistenceModelGenerator.Generate(new string[] { "NHibernateTest.exe" },
                                                                      new string[] { "NHibernateTest.exe" }));
                x.FluentMappings.Add <IsDeletedFilter>();

                x.AutoMappings.ExportTo(@"D:\Temp");
            });

            //fluentConfiguration.Mappings(m => m.FluentMappings.Add<ClassesMap>());
            //fluentConfiguration.Mappings(m => m.FluentMappings.Add<StudentMap>());
            //fluentConfiguration.Mappings(m => m.FluentMappings.Add<CourseMap>());
        }
Exemplo n.º 26
0
        public static FluentConfiguration RegisterDateTimeGenerators(this FluentConfiguration fluentConfiguration)
        {
            fluentConfiguration.ExposeConfiguration(config =>
            {
                config.AddSqlFunction("AddSeconds", new SQLFunctionTemplate(NHibernateUtil.DateTime, "DATEADD(second, ?2, ?1)"));
                config.AddSqlFunction("AddMinutes", new SQLFunctionTemplate(NHibernateUtil.DateTime, "DATEADD(minute, ?2, ?1)"));
                config.AddSqlFunction("AddHours", new SQLFunctionTemplate(NHibernateUtil.DateTime, "DATEADD(hour, ?2, ?1)"));
                config.AddSqlFunction("AddDays", new SQLFunctionTemplate(NHibernateUtil.DateTime, "DATEADD(day, ?2, ?1)"));
                config.AddSqlFunction("AddMonths", new SQLFunctionTemplate(NHibernateUtil.DateTime, "DATEADD(month, ?2, ?1)"));
                config.AddSqlFunction("AddYears", new SQLFunctionTemplate(NHibernateUtil.DateTime, "DATEADD(year, ?2, ?1)"));

                config.LinqToHqlGeneratorsRegistry <CoreSharpLinqToHqlGeneratorsRegistry>();
            });

            return(fluentConfiguration);
        }
Exemplo n.º 27
0
        public void Workaround()
        {
            var engine = new ValidatorEngine();
            var cfg    = new FluentConfiguration();

            cfg.Register(new[] {
                typeof(SubEntityValidation),
                typeof(EntityValidation) // Here is the workaround
            });
            cfg.SetDefaultValidatorMode(ValidatorMode.OverrideExternalWithAttribute);
            engine.Configure(cfg);

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

            Assert.That(errors.Length, Is.EqualTo(3));
        }
Exemplo n.º 28
0
        public static void IniciarNHibernate()
        {
            if (!Directory.Exists("C:\\temp"))
            {
                Directory.CreateDirectory("C:\\temp");
            }
            FluentConfiguration dbConfig = Fluently.Configure()
                                           .Database(SQLiteConfiguration.Standard.UsingFile("C:\\temp\\Cadastro.db"));


            NHIBERNATE_CONFIGURATION =
                dbConfig.Mappings(x => x.FluentMappings.AddFromAssemblyOf <EmpresaMap>())
                .Mappings(x => x.FluentMappings.AddFromAssemblyOf <FornecedorMap>())
                .Mappings(x => x.FluentMappings.AddFromAssemblyOf <TelefoneMap>())
                .BuildConfiguration();
        }
Exemplo n.º 29
0
        private static void ConfigureAssemblies(ref FluentConfiguration configuration)
        {
            foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
            {
                foreach (var attribute in assembly.GetCustomAttributes(true))
                {
                    if (attribute is HibernatePersistenceAttribute)
                    {
                        Assembly bgmAssembly = assembly;
                        configuration.Mappings(m => m.FluentMappings.AddFromAssembly(bgmAssembly));
                    }
                }
            }

            //configuration.Mappings(m => m.FluentMappings.AddFromAssemblyOf<Praxio.Tools.Authorization.Infra.Data.NHibernateDataAccess.Repositories.UsersRepository>());
        }
Exemplo n.º 30
0
        public static FluentConfiguration RegisterDateTimeGenerators(this FluentConfiguration fluentConfiguration)
        {
            fluentConfiguration.ExposeConfiguration(config =>
            {
                config.AddSqlFunction("AddSeconds", new SQLFunctionTemplate(NHibernateUtil.DateTime, "?1 + (?2 * interval '1 second')"));
                config.AddSqlFunction("AddMinutes", new SQLFunctionTemplate(NHibernateUtil.DateTime, "?1 + (?2 * interval '1 minute')"));
                config.AddSqlFunction("AddHours", new SQLFunctionTemplate(NHibernateUtil.DateTime, "?1 + (?2 * interval '1 hour')"));
                config.AddSqlFunction("AddDays", new SQLFunctionTemplate(NHibernateUtil.DateTime, "?1 + (?2 * interval '1 day')"));
                config.AddSqlFunction("AddMonths", new SQLFunctionTemplate(NHibernateUtil.DateTime, "?1 + (?2 * interval '1 month')"));
                config.AddSqlFunction("AddYears", new SQLFunctionTemplate(NHibernateUtil.DateTime, "?1 + (?2 * interval '1 year')"));

                config.LinqToHqlGeneratorsRegistry <CoreSharpLinqToHqlGeneratorsRegistry>();
            });

            return(fluentConfiguration);
        }
Exemplo n.º 31
0
    public static void Configurar()
    {
        string connectionString = "Data Source=SERVIDOR;Initial Catalog=BancoDeDados;User ID=Usuario;Password=Senha";

        MsSqlConfiguration configuracao = MsSqlConfiguration.MsSql2012
                                          .ConnectionString(connectionString);

        FluentConfiguration fluentConfig = Fluently.Configure()
                                           .Database(configuracao)
                                           .Mappings(mappingConfiguration =>
        {
            mappingConfiguration.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly());
        }).ExposeConfiguration(cfg => new SchemaUpdate(cfg).Execute(true, true));

        sessionFactory = fluentConfig.BuildSessionFactory();
    }
Exemplo n.º 32
0
        public static FluentConfiguration AddMySql(this FluentConfiguration fluentConfiguration,
                                                   IConfiguration configuration)
        {
            var dbConfig = configuration.GetSection("DataSources:MySQL");

            fluentConfiguration.Database(MySQLConfiguration.Standard.ConnectionString(csBuilder =>
            {
                csBuilder.Server(dbConfig.GetSection("Host").Value)
                .Database(dbConfig.GetSection("DbName").Value)
                .Username(dbConfig.GetSection("User").Value)
                .Password(dbConfig.GetSection("Password").Value);
            })
                                         .ShowSql()
                                         .Dialect <MySQL5Dialect>());
            return(fluentConfiguration);
        }
Exemplo n.º 33
0
            public WhenCallingCreateSessionFactory_WithNamedConnection_MultipleTimesForTheSameConnection()
            {
                var fluentConfiguration = new FluentConfiguration((ISessionFactory s) =>
                {
                    this.sessionFactoryCreatedCount++;
                    return(s);
                });

                this.sessionFactory1 = fluentConfiguration
                                       .ForConnection("SqlConnection", new Mock <ISqlDialect>().Object, new Mock <IDbDriver>().Object)
                                       .CreateSessionFactory();

                this.sessionFactory2 = fluentConfiguration
                                       .ForConnection("SqlConnection", new Mock <ISqlDialect>().Object, new Mock <IDbDriver>().Object)
                                       .CreateSessionFactory();
            }
Exemplo n.º 34
0
        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
            }));
        }
Exemplo n.º 35
0
        private static ISessionFactory BuildSessionFactory(string connectionString)
        {
            FluentConfiguration configuration = Fluently.Configure()
                                                .Database(MsSqlConfiguration.MsSql2012.ConnectionString(connectionString))
                                                .Mappings(m => m.FluentMappings
                                                          .AddFromAssembly(Assembly.GetExecutingAssembly())
                                                          .Conventions.Add(
                                                              ForeignKey.EndsWith("ID"),
                                                              ConventionBuilder.Property
                                                              .When(criteria => criteria.Expect(x => x.Nullable, Is.Not.Set), x => x.Not.Nullable()))
                                                          .Conventions.Add <TableNameConvention>()
                                                          .Conventions.Add <HiLoConvention>()
                                                          );

            return(configuration.BuildSessionFactory());
        }
Exemplo n.º 36
0
        public static FluentConfiguration CreatePostgreSQLSchemas(this FluentConfiguration fluentConfiguration)
        {
            return(fluentConfiguration.ExposeDbCommand((command, cfg) =>
            {
                var schemas = cfg.ClassMappings.Select(x => x.Table.Schema).Where(x => !string.IsNullOrEmpty(x))
                              .Distinct()
                              .Select(x => cfg.NamingStrategy.TableName(x))
                              .ToList();

                foreach (var schema in schemas)
                {
                    command.CommandText = $"CREATE SCHEMA IF NOT EXISTS {schema};";
                    command.ExecuteNonQuery();
                }
            }));
        }
        /// <summary>
        /// Пооверить структуру таблиц.
        /// </summary>
        /// <returns></returns>
        public virtual DbContext ValidateSchema()
        {
            try
            {
                FluentConfiguration  dbConfig = Configure();
                NH.Cfg.Configuration config   = dbConfig.BuildConfiguration();
                var schema = new SchemaValidator(config);
                schema.Validate();

                return(new DbContext(this, dbConfig.BuildSessionFactory()));
            }
            catch (Exception ex)
            {
                throw new DatabaseException($"Некорректная структура таблиц БД: {this}.", ex);
            }
        }
Exemplo n.º 38
0
        protected override void Configure(NHibernate.Cfg.Configuration configuration)
        {
            var configure = new FluentConfiguration();

            configure
                .SetDefaultValidatorMode(ValidatorMode.UseExternal)
                .IntegrateWithNHibernate
                .ApplyingDDLConstraints()
                .And
                .RegisteringListeners();

            var validatorEngine = new ValidatorEngine();
            validatorEngine.Configure(configure);

            configuration.Initialize(validatorEngine);
        }
        /// <summary>
        /// Create database structure from code
        /// </summary>
        /// <param name="configuration">The configuration.</param>
        public static void ExportSchema(this FluentConfiguration configuration)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }

            Configuration config = null;

            configuration.ExposeConfiguration(c => config = c);
            var factory = configuration.BuildSessionFactory();

            var export = new SchemaExport(config);

            export.Execute(false, true, false, factory.OpenSession().Connection, null);
        }
Exemplo n.º 40
0
        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 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" } }));
        }
Exemplo n.º 42
0
        private static IDictionary <string, ISessionFactory> LoadAllFactories()
        {
            var dictionary = new Dictionary <string, ISessionFactory>(2);

            // Database 100 (Exact)
            FluentConfiguration configuration = Fluently.Configure()
                                                .Database(MsSqlConfiguration.MsSql2012.ConnectionString(cs => cs.FromConnectionStringWithKey("db2")))
                                                .Mappings(m => m.FluentMappings
                                                          .AddFromAssembly(Assembly.Load("DeEekhoorn.Logic"))
                                                          .Conventions.Add(
                                                              ForeignKey.EndsWith("Id"),
                                                              ConventionBuilder.Property
                                                              .When(criteria => criteria.Expect(x => x.Nullable, Is.Not.Set), x => x.Not.Nullable()))

                                                          )
                                                .ExposeConfiguration(x =>
            {
                x.EventListeners.PreInsertEventListeners =
                    new IPreInsertEventListener[] { new EventListener() };
                x.EventListeners.PreUpdateEventListeners =
                    new IPreUpdateEventListener[] { new EventListener() };
            });

            dictionary.Add("db2", configuration.BuildSessionFactory());

            // Database EYEBOARD
            configuration = Fluently.Configure()
                            .Database(MsSqlConfiguration.MsSql2012.ConnectionString(cs => cs.FromConnectionStringWithKey("db1")))
                            .Mappings(m => m.FluentMappings
                                      .AddFromAssembly(Assembly.Load("EyeBoard.Logic"))
                                      .Conventions.Add(
                                          ForeignKey.EndsWith("Id"),
                                          ConventionBuilder.Property
                                          .When(criteria => criteria.Expect(x => x.Nullable, Is.Not.Set), x => x.Not.Nullable()))

                                      )
                            .ExposeConfiguration(x =>
            {
                x.EventListeners.PreInsertEventListeners =
                    new IPreInsertEventListener[] { new EventListener() };
                x.EventListeners.PreUpdateEventListeners =
                    new IPreUpdateEventListener[] { new EventListener() };
            });
            dictionary.Add("db1", configuration.BuildSessionFactory());

            return(dictionary);
        }
Exemplo n.º 43
0
        protected virtual void ConfigureMappings(FluentConfiguration fluentConfig)
        {
            ConfigureFilters();

            fluentConfig.Mappings(mappings =>
            {
                foreach (var assemblyName in options.MappingAssemblies)
                {
                    var assembly = Assembly.Load(assemblyName);

                    var fluentMappingsContainer = mappings.FluentMappings.AddFromAssembly(assembly);

                    AddFilters(fluentMappingsContainer);
                    AddConventions(assembly, fluentMappingsContainer);
                }
            });
        }
Exemplo n.º 44
0
        public void PropertyShouldHaveOneAuditAttributeWithNoAuditedRelation_using_field()
        {
            var cfg = new FluentConfiguration();

            cfg.Audit <NotAuditedOwnerEntity>()
            .ExcludeRelationData("RelationField");
            metas = cfg.CreateMetaData(null);

            var propInfo = typeof(NotAuditedOwnerEntity).GetField("RelationField");
            var entMeta  = metas[typeof(NotAuditedOwnerEntity)];

            entMeta.MemberMetas[propInfo]
            .Should().Have.Count.EqualTo(1);
            var auditAttr = (AuditedAttribute)entMeta.MemberMetas[propInfo].First();

            auditAttr.TargetAuditMode.Should().Be.EqualTo(RelationTargetAuditMode.NotAudited);
        }
Exemplo n.º 45
0
        private static void InitializeFromConfigPostgreSql(FluentConfiguration fluentConfiguration,
                                                           DbConnectionSettings settings,
                                                           Action <PostgreSQLConfiguration>?additionalClientConfiguration = null)
        {
            var clientConfiguration = PostgreSQLConfiguration.PostgreSQL82.ConnectionString(c => c
                                                                                            .Host(settings.ServerName)
                                                                                            .Port(settings.Port ?? 5432)
                                                                                            .Database(settings.DataBaseName)
                                                                                            .Username(settings.UserName)
                                                                                            .Password(settings.UserPassword));

            additionalClientConfiguration?.Invoke(clientConfiguration);

            fluentConfiguration.Database(clientConfiguration);

            PerformCommonInitialization(fluentConfiguration, settings.ShowSql);
        }
Exemplo n.º 46
0
        private static void InitializeFromConfigOracleClient(FluentConfiguration fluentConfiguration,
                                                             DbConnectionSettings settings,
                                                             Action <OracleDataClientConfiguration>?additionalClientConfiguration = null)
        {
            var clientConfiguration = OracleDataClientConfiguration.Oracle10.ConnectionString(c =>
                                                                                              c.Server(settings.ServerName)
                                                                                              .Port(settings.Port ?? 1521)
                                                                                              .Instance(settings.DataBaseName)
                                                                                              .Username(settings.UserName)
                                                                                              .Password(settings.UserPassword));

            additionalClientConfiguration?.Invoke(clientConfiguration);

            fluentConfiguration.Database(clientConfiguration);

            PerformCommonInitialization(fluentConfiguration, settings.ShowSql);
        }
Exemplo n.º 47
0
        public static void StartNhibernate(FluentConfiguration instanceBuilderConfiguration, bool reloadDb = true)
        {
            if (reloadDb)
            {
                IManagerDataBase managerDataBase = new NhibernateManagerDataBase(instanceBuilderConfiguration);
                if (!managerDataBase.IsExist())
                {
                    managerDataBase.Create();
                }

                managerDataBase.Update();
            }

            SessionFactory = new NhibernateSessionFactory(instanceBuilderConfiguration);

            SpecWithRepository.Repository = BuildNhibernateRepository();
        }
Exemplo n.º 48
0
 public static ISessionFactory BuildSessionFactory(FluentConfiguration config)
 {
     try
     {
         return(config.BuildSessionFactory());
     }
     catch (ArgumentException x)
     {
         s_log.Fatal(x, "Error while building session factory");
         throw;
     }
     catch (FluentConfigurationException x)
     {
         s_log.Fatal(x, "Error while building session factory");
         throw;
     }
 }
Exemplo n.º 49
0
        public static FluentConfiguration ExportMappings(this FluentConfiguration fluentConfiguration, string path, bool export = true)
        {
            if (!export)
            {
                return(fluentConfiguration);
            }

            return(fluentConfiguration.Mappings(m =>
            {
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }

                m.AutoMappings.ExportTo(path);
            }));
        }
Exemplo n.º 50
0
        //[Ignore]
        public void GerarSchema()
        {
            FluentConfiguration config = Fluently.Configure()
                                         .Database(MsSqlConfiguration.MsSql2012
                                                   .ConnectionString(c => c.FromAppSetting("connectionString")).ShowSql());

            foreach (var assemblyName in AppSettingsHelper.GetValue("mappingAssemblies").Split(','))
            {
                System.Console.WriteLine("carregando assembly " + assemblyName);
                config.Mappings(x => x.FluentMappings.Conventions
                                .Setup(m => m.Add(AutoImport.Never()))
                                .AddFromAssembly(Assembly.Load(assemblyName)));
            }

            config.ExposeConfiguration(BuildSchema);
            config.BuildSessionFactory();
        }
Exemplo n.º 51
0
 public DbSessionProvider()
 {
     FluentConfiguration = Fluently.Configure();
     FluentConfiguration
     // 配置连接串
     .Database(MySQLConfiguration.Standard.ConnectionString(db =>
                                                            db.Server("192.168.3.121")
                                                            .Database("pay")
                                                            .Username("root")
                                                            .Password("root")
                                                            ))
     // 配置ORM
     .Mappings(m => m.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly()))
     .BuildConfiguration();
     // 生成session factory
     _sessionFactory = FluentConfiguration.BuildSessionFactory();
 }
Exemplo n.º 52
0
    void Initialize(string connectionStringKey)
    {
        IPersistenceConfigurer persistenceConfigurer = null;

        persistenceConfigurer = MsSqlConfiguration.MsSql2008
                                .UseOuterJoin()
                                .ConnectionString(connectionStringKey)
                                .FormatSql()
                                .ShowSql()
        ;
        _fluentConfiguration = Fluently.Configure()
                               .Database(persistenceConfigurer)
                               .ExposeConfiguration(ConfigurePersistence)
                               .ProxyFactoryFactory(typeof(ProxyFactoryFactory))
                               .BuildConfiguration()
        ;
    }
        public void GetMemberConstraintsLoquacious()
        {
            var configure = new FluentConfiguration();

            configure.Register(
                Assembly.GetExecutingAssembly().ValidationDefinitions().Where(x=>x.Equals(typeof(AddressDef))))
            .SetDefaultValidatorMode(ValidatorMode.UseExternal);
            var ve = new ValidatorEngine();

            ve.Configure(configure);

            IClassValidator cv = ve.GetValidator<Address>();
            IEnumerable<Attribute> ma = cv.GetMemberConstraints("Country");
            Assert.That(ma.Count(), Is.EqualTo(2));
            Assert.That(ma.Count(x => x.TypeId == (new NotNullAttribute()).TypeId), Is.EqualTo(1));
            Assert.That(ma.Count(x => x.TypeId == (new LengthAttribute()).TypeId), Is.EqualTo(1));
        }
Exemplo n.º 54
0
        public CloudflareDbSessionConfiguration()
            : base()
        {
            FluentConfiguration = Fluently.Configure();
            // 数据库连接串
            //var connString = "data source=|DataDirectory|Cloudflare.db;";
            var connString = ConfigurationManager.AppSettings["connStr"];

            FluentConfiguration
            // 配置连接串
            //.Database(SQLiteConfiguration.Standard.ConnectionString(connString))
            .Database(MsSqlConfiguration.MsSql2012.ConnectionString(connString))
            // 配置ORM
            .Mappings(m => m.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly()));
            // 生成session factory
            SessionFactory = FluentConfiguration.BuildSessionFactory();
        }
Exemplo n.º 55
0
        private static void AppConfigure()
        {
            #region Configuration Log4Net

            // To see the SQLs run the application inside VisualStudio
            // watching the Output window
            XmlConfigurator.Configure();
            //DOMConfigurator.Configure();

            #endregion

            #region NHibernate configuration

            var conf = new Configuration();
            conf.Configure();

            // Validate the schema: if wrong try to create the new schema
            try
            {
                new SchemaValidator(conf).Validate();

            }
            catch (HibernateException)
            {
                var export = new SchemaExport(conf);
                export.Drop(false, true);
                export.Create(false, true);
            }

            #endregion

            #region NHibernate.Validator configuration

            var validatorConf = new FluentConfiguration();
            validatorConf.SetDefaultValidatorMode(ValidatorMode.UseExternal).Register(
                Assembly.GetExecutingAssembly().GetTypes().Where(t => t.Namespace.Equals("plabel2.Mappings")).
                    ValidationDefinitions());
            var validatorEngine = new ValidatorEngine();
            validatorEngine.Configure(validatorConf);

            #endregion

            ApplicationContext.SessionFactory = conf.BuildSessionFactory();
            ApplicationContext.Validator = 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 }));
        }
Exemplo n.º 57
0
        public static void Initialize(global::NHibernate.Cfg.Configuration configuration)
        {
            XangoConfiguration xangoConfig = XangoConfigurationHelper.Get();

            Configuration = new FluentConfiguration();
            Configuration
                .SetDefaultValidatorMode(ValidatorMode.OverrideAttributeWithExternal)
                .Register(xangoConfig.ValidationAssembly
                .ValidationDefinitions())
                .IntegrateWithNHibernate
                .ApplyingDDLConstraints()
                .And
                .RegisteringListeners();

            var validatorEngine = new ValidatorEngine();
            validatorEngine.Configure(Configuration);

            new BasicSharedEngineProvider(validatorEngine,configuration).UseMe();
        }
        public void ValidateChangedPropertyOfProxy()
        {
            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);
                proxy.Description = "no";

                Assert.AreEqual(1, engine.ValidatePropertyValue(proxy, p => p.Description).Length);
                Assert.DoesNotThrow(() => engine.ValidatePropertyValue(proxy, p => p.Description));

                Assert.AreEqual(1, engine.ValidatePropertyValue(proxy, "Description").Length);
                Assert.DoesNotThrow(() => engine.ValidatePropertyValue(proxy, "Description"));
            }

            CleanDb();
        }
        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 Minimal()
        {
            var fc = new FluentConfiguration();
            fc.SetMessageInterpolator<MessageInterpolatorStub>()
                .SetDefaultValidatorMode(ValidatorMode.OverrideExternalWithAttribute)
                .IntegrateWithNHibernate.ApplyingDDLConstraints().And.RegisteringListeners();
            var cfg = (INHVConfiguration) fc;
            Assert.That(cfg.Properties["apply_to_ddl"], Is.EqualTo("true"));
            Assert.That(cfg.Properties["autoregister_listeners"], Is.EqualTo("true"));
            Assert.That(cfg.Properties["message_interpolator_class"], Is.EqualTo(typeof(MessageInterpolatorStub).AssemblyQualifiedName));
            Assert.That(cfg.Properties["external_mappings_loader_class"], Is.EqualTo(typeof(FluentMappingLoader).AssemblyQualifiedName));
            Assert.That(cfg.Properties["default_validator_mode"], Is.EqualTo("OverrideExternalWithAttribute".ToLowerInvariant()));

            fc = new FluentConfiguration();
            fc.SetMessageInterpolator<MessageInterpolatorStub>()
                .SetDefaultValidatorMode(ValidatorMode.UseExternal)
                .IntegrateWithNHibernate.AvoidingDDLConstraints().And.AvoidingListenersRegister();
            cfg = fc;
            Assert.That(cfg.Properties["apply_to_ddl"], Is.EqualTo("false"));
            Assert.That(cfg.Properties["autoregister_listeners"], Is.EqualTo("false"));
            Assert.That(cfg.Properties["message_interpolator_class"], Is.EqualTo(typeof(MessageInterpolatorStub).AssemblyQualifiedName));
            Assert.That(cfg.Properties["external_mappings_loader_class"], Is.EqualTo(typeof(FluentMappingLoader).AssemblyQualifiedName));
            Assert.That(cfg.Properties["default_validator_mode"], Is.EqualTo("UseExternal".ToLowerInvariant()));
        }