private FluentConfiguration buildFluentConfiguration()
 {
     return(Fluently.Configure()
            .Database(_persistenceConfigurer)
            .Mappings(_mappingConfig.GetMappings()));
 }
Esempio n. 2
0
 public static void PerformDefaultConfiguration()
 {
     Fluently.Configure()
     .WithConnectionFactory(new TempDbConnectionFactory(_db))
     .WithEntitiesFrom(typeof(TestQueryExecution).Assembly);
 }
Esempio n. 3
0
        static ISessionFactory CreateSessionFactory(
            IConfiguration configuration,
            IEnumerable <Assembly> assemblies)
        {
            var database = new Database();

            configuration.GetSection("database").Bind(database);
            var db = Fluently.Configure();

            switch (database.Type)
            {
            case "MSSQL":
                // Notice, version 2012
                db = db.Database(MsSqlConfiguration.MsSql2012.ConnectionString(database.Connection));
                break;

            case "MySQL":
                db = db.Database(MySQLConfiguration.Standard.ConnectionString(database.Connection));
                break;

            case "SQLIte":
                db = db.Database(SQLiteConfiguration.Standard.ConnectionString(database.Connection));
                break;

            // Specific versions of MS SQL
            case "MsSql7":
                db = db.Database(MsSqlConfiguration.MsSql7.ConnectionString(database.Connection));
                break;

            case "MsSql2008":
                db = db.Database(MsSqlConfiguration.MsSql2008.ConnectionString(database.Connection));
                break;

            case "MsSql2005":
                db = db.Database(MsSqlConfiguration.MsSql2005.ConnectionString(database.Connection));
                break;

            case "MsSql2000":
                db = db.Database(MsSqlConfiguration.MsSql2000.ConnectionString(database.Connection));
                break;

            default:
                throw new ConfigurationErrorsException($"The database type of '{database.Type}' is unsupported.");
            }
            return(db.Mappings((m) =>
            {
                foreach (var idxAsm in assemblies)
                {
                    m.FluentMappings.AddFromAssembly(idxAsm);
                }
            }).ExposeConfiguration(cfg => new SchemaUpdate(cfg).Execute(true, true)).BuildSessionFactory());
            // WARNING: The above line of code will automatically generate your database schema. This is probably NOT something you want in a production environment!

            /*
             * The above "ExposeConfiguration(cfg => new SchemaUpdate(cfg).Execute(true, true))" code will automatically create your database schema.
             * In a production environment, you would probably not want your code to automatically do this, since it modifies your database schema,
             * and might have dangerous side-effects if not done correctly.
             *
             * NOTICE!
             * If you build the project in "Release" configuration, the database schema will NOT be automatically modified!
             */
        }
Esempio n. 4
0
        private static ISessionFactory InitializeSessionFactory(string dbType, string dbVersion, string connString, bool showSql, IList <Type> mappings,
                                                                Action <NHibernate.Cfg.Configuration> configuration)
        {
            var fluentConfiguration = Fluently.Configure();

            IPersistenceConfigurer dbConfig = null;

            switch (dbType.ToLowerInvariant())
            {
            case "mssql":
                if (showSql)
                {
                    dbConfig = MsSqlConfiguration.MsSql2012.ConnectionString(connString).ShowSql();
                }
                else
                {
                    dbConfig = MsSqlConfiguration.MsSql2012.ConnectionString(connString);
                }
                break;

            case "oracle10":
                if (showSql)
                {
                    dbConfig = OracleDataClientConfiguration.Oracle10.ConnectionString(connString).ShowSql();
                }
                else
                {
                    dbConfig = OracleDataClientConfiguration.Oracle10.ConnectionString(connString);
                }
                break;

            case "oracle9":
                if (showSql)
                {
                    dbConfig = OracleDataClientConfiguration.Oracle9.ConnectionString(connString).ShowSql();
                }
                else
                {
                    dbConfig = OracleDataClientConfiguration.Oracle9.ConnectionString(connString);
                }
                break;
            }

            fluentConfiguration.Mappings(m =>
            {
                foreach (var sessionOptionsMapping in mappings)
                {
                    m.FluentMappings.Add(sessionOptionsMapping);
                }
            });

            fluentConfiguration.Database(dbConfig);
            fluentConfiguration.CurrentSessionContext("web");

            if (configuration != null)
            {
                fluentConfiguration.ExposeConfiguration(configuration);
            }

            ConfigureAssemblies(ref fluentConfiguration);

            return(fluentConfiguration.BuildSessionFactory());
        }
 protected override global::NHibernate.ISessionFactory InitializeFactory()
 {
     return(Fluently.Configure().Database(MsSqlConfiguration.MsSql2012
                                          .ConnectionString(p => p.FromConnectionStringWithKey("NorthwindContext")))
            .Mappings(p => p.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly())).BuildSessionFactory());
 }
 private static FluentConfiguration CreateConfiguration()
 {
     return(Fluently.Configure()
            .InitializeFromConfigSqLite("Test.sqlite", true)
            .AddMappingsFromAssemblyOf <UserMap>(PrimaryKey.Name.Is(x => "ID"), ForeignKeyConstraintNameConvention.WithConstraintNameConvention()));
 }
Esempio n. 7
0
        public static void InitializeStorage()
        {
            if (!string.IsNullOrEmpty(Preferences.StorageUsername))
            {
                // if (null != Preferences.StorageUsername && string.Empty != Preferences.StorageUsername) {
                Preferences.StorageConnectionString =
                    //@"Data Source=" +
                    @"Server=" +
                    Preferences.StorageServer +
                    //";Initial Catalog=" +
                    ";Database=" +
                    Preferences.StorageDatabase +
                    ";Username="******";Password="******";";
            }
            else
            {
                Preferences.StorageConnectionString =
                    //@"Data Source=" +
                    @"Server=" +
                    Preferences.StorageServer +
                    //";Initial Catalog=" +
                    ";Database=" +
                    Preferences.StorageDatabase +
                    ";Integrated Security=SSPI;";
            }

            try {
//                cmdlet.WriteVerbose("building configuration...");

                if (null == Fluently.Configure())
                {
                    Console.WriteLine("Fluently == null");
                }
                Console.WriteLine("Fluently != null");
                Fluently.Configure();
//                    .Database(MsSqlConfiguration
//                              .MsSql2008
//                              //.ConnectionString(Preferences.StorageConnectionString))
//                              //.ConnectionString(x => x.Is(connString)))
//                              .ConnectionString(x => x.Is(Preferences.StorageConnectionString)))
//                    //.Mappings(m => m.FluentMappings.AddFromAssemblyOf<ProductMap>())
//                    .Mappings(m => m.FluentMappings
//                              .AddFromAssemblyOf<TestSuiteMap>())
//                              //.AddFromAssemblyOf<System.Object>())
//                    .ExposeConfiguration(CreateSchema)
//                    .BuildConfiguration();

//                cmdlet.WriteVerbose("creating session factory...");

                SessionFactory = Fluently.Configure()
                                 .Database(MsSqlConfiguration
                                           .MsSql2008
                                           .ConnectionString(Preferences.StorageConnectionString))
                                 .Mappings(m => m.FluentMappings
                                 //.AddFromAssembly(Assembly.GetExecutingAssembly()))
                                           .AddFromAssemblyOf <TestSuiteMap>())
                                 //.AddFromAssemblyOf<System.Object>())
                                 .BuildSessionFactory();

//                cmdlet.WriteVerbose("session factory has been created...");
            }
            catch (Exception eSession) {
                // 20140720
//                cmdlet.WriteError(
//                    cmdlet,
//                    eSession.InnerException.Message,
//                    "SessionFailed",
//                    ErrorCategory.InvalidOperation,
//                    true);
                throw new Exception(
                          eSession.InnerException.Message);
            }
        }
Esempio n. 8
0
 //var listOfEntityMap = typeof(M).Assembly.GetTypes().Where(t => t.GetInterfaces().Contains(typeof(M))).ToList();
 //var sessionFactory = SessionFactoryBuilder.BuildSessionFactory(dbmsTypeAsString, connectionStringName, listOfEntityMap, withLog, create, update);
 public static ISessionFactory BuildSessionFactory(string connectionString, bool create = false, bool update = false)
 {
     return(Fluently.Configure().Database(MsSqlConfiguration.MsSql2012.ConnectionString(connectionString))
            //.Mappings(m => entityMappingTypes.ForEach(e => { m.FluentMappings.Add(e); }))
            .Mappings(m => m.FluentMappings.AddFromAssemblyOf <NHibernate.Cfg.Mappings>()).CurrentSessionContext("call").ExposeConfiguration(cfg => BuildSchema(cfg, create, update)).BuildSessionFactory());
 }
Esempio n. 9
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Register the Swagger generator, defining 1 or more Swagger documents
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info
                {
                    Title   = "GRID 3.0 API",
                    Version = "v1",
                    License = new License
                    {
                        Name = "Simpat Tech",
                        Url  = "https://simpat.tech/"
                    }
                });
                var security = new Dictionary <string, IEnumerable <string> >
                {
                    { "Bearer", new string[] { } },
                };
                c.AddSecurityDefinition("Bearer", new ApiKeyScheme
                {
                    Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                    Name        = "Authorization",
                    In          = "header",
                    Type        = "apiKey"
                });
                c.AddSecurityRequirement(security);
            });

            services.Configure <JwtSettings>(Configuration.GetSection("JwtSettings"));

            services.AddMediatR();
            services.AddAutoMapper();

            services.AddSingleton(provider =>
            {
                return(Fluently
                       .Configure()
                       .Database(() =>
                {
                    return FluentNHibernate.Cfg.Db.MsSqlConfiguration
                    .MsSql2012
                    .ShowSql()
                    .ConnectionString(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
                })
                       .Mappings(m => m.FluentMappings.AddFromAssemblyOf <PersistentObjectMap>())
                       .BuildSessionFactory());
            });

            services.AddScoped(provider =>
                               provider
                               .GetService <NHibernate.ISessionFactory>()
                               .OpenSession()
                               );

            var sharedKey      = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration.GetSection("JwtSettings")["JwtKey"]));
            var issuerAudience = Configuration.GetSection("JwtSettings")["Domain"];

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateLifetime         = true,
                    ValidateIssuerSigningKey = true,
                    ValidateIssuer           = true,
                    ValidateAudience         = true,
                    ValidIssuer      = issuerAudience,
                    ValidAudience    = issuerAudience,
                    IssuerSigningKey = sharedKey
                };
            });

            services.AddHttpContextAccessor();
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }
Esempio n. 10
0
 protected override ISessionFactory InitializeFactory()
 {
     return(Fluently.Configure().Database(MsSqlConfiguration.MsSql2012
                                          .ConnectionString(c => c.Username("NorthwindContext")))
            .Mappings(t => t.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly())).BuildSessionFactory());
 }
 public FluentConfiguration GetFluentConfiguration()
 {
     return(Fluently.Configure()
            .Database(MsSqlConfiguration.MsSql2008.ConnectionString(GetConnectionString())));
 }
Esempio n. 12
0
 private static FluentConfiguration CreateConfiguration()
 {
     return(Fluently.Configure()
            .Database(SQLiteConfiguration.Standard.ConnectionString(c => c.Is("Data Source=WeatherStation.db")))
            .Mappings(x => x.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly())));
 }
Esempio n. 13
0
        public static void SetupAutoMapperForEntities(IPersistenceConfigurer database, IDependencyResolver dependencyResolver, params Assembly[] assemblies)
        {
            var config = Fluently.Configure().Database(database)
                         .Cache(cache => cache.UseQueryCache().ProviderClass <SysCacheProvider>().QueryCacheFactory <ProjectionEnabledQueryCacheFactory>())
                         .ProxyFactoryFactory(typeof(DefaultProxyFactoryFactory))
                         .CurrentSessionContext(CurrentSessionContextClass);

            var stringPropertyconvention = ConventionBuilder.Property.When(x => x.Expect(p => p.Property.PropertyType == typeof(string)), a => a.Length(255));

            var cacheConvention = ConventionBuilder.Class.Always(c => c.Cache.ReadWrite());

            var collectionsConventionMany = ConventionBuilder.HasMany.When(
                x => x.Expect(p => !(p.Member is DummyPropertyInfo)),
                instance => { instance.Cascade.SaveUpdate(); instance.Cache.ReadWrite(); });

            var collectionsConventionManyToMany = ConventionBuilder.HasManyToMany.When(
                x => x.Expect(p => !(p.Member is DummyPropertyInfo)),
                instance => { instance.Cascade.SaveUpdate(); instance.Cache.ReadWrite(); });
            var lazyConvention = ConventionBuilder.Reference.Always(c => c.LazyLoad());

            IEnumerable <Assembly> ass;

            if (assemblies == null || assemblies.Length == 0)
            {
                ass = AppDomain.CurrentDomain.GetAssemblies().Where(
                    a => !a.FullName.StartsWith("System.") &&
                    !a.FullName.StartsWith("Microsoft.") &&
                    !a.FullName.Contains("mscorlib") &&
                    a != typeof(ISession).Assembly &&
                    a != typeof(AutoMap).Assembly
                    );
            }
            else
            {
                ass = assemblies;
            }

            var autoPersistenceModel = new AutoPersistenceModel()
                                       .Conventions.Add(cacheConvention, collectionsConventionMany, collectionsConventionManyToMany, stringPropertyconvention, lazyConvention)
                                       .IgnoreBase(typeof(BaseEntity <>))
                                       .IgnoreBase(typeof(IBaseEntity));

            foreach (var assembly in ass)
            {
                try
                {
                    assembly.GetExportedTypes();
                }
                catch (NotSupportedException)
                {
                    continue;//cannot do dynamic assemblies
                }
                if (assembly != null)
                {
                    Assembly automapper = assembly;

                    config.Mappings(m => m.HbmMappings.AddFromAssembly(automapper));
                    autoPersistenceModel
                    .AddEntityAssembly(automapper)
                    .Conventions.AddAssembly(automapper)
                    .Alterations(alterations => alterations.AddFromAssembly(automapper))
                    .Alterations(collection => collection.Add(new AutoMappingOverrideAlteration(automapper)))     //same as: UseOverridesFromAssemblyOf<Tentity>()
                    .Where(t => typeof(IBaseEntity).IsAssignableFrom(t));

                    // MORE Evil hack, since adding to the Alterations does NOT work.
                    //new AutoMappingOverrideAlteration(automapper).Alter(autoPersistenceModel);
                }
            }

            // Evil hack, since adding to the Alterations does NOT work.
            //foreach (var overrideAssembly in ass)
            //{
            //    new AutoMappingOverrideAlteration(overrideAssembly).Alter(autoPersistenceModel);
            //}

            config.Mappings(m => m.AutoMappings.Add(autoPersistenceModel)
#if DEBUG
                            .ExportTo(@"C:\temp\")
#endif
                            );

            var nhconfig       = config.BuildConfiguration();
            var sessionFactory = nhconfig.BuildSessionFactory();
            //dependencyResolver.RegisterInstance<Configuration>(nhconfig);
            dependencyResolver.RegisterInstance <ISessionFactory>(sessionFactory);

            new SchemaUpdate(nhconfig).Execute(true, true);
        }
Esempio n. 14
0
        public static global::NHibernate.Cfg.Configuration CreateConfiguration(SupportedNHDrivers nhDriver, string connectionString, Assembly fluentMappingsAssembly, bool showSql, bool enablePostCommitListener, string sessionContext, bool outputNhMappings, bool useNhProfiler, out NhConfigurationCacheKey configurationCacheKey, string connReleaseMode)
        {
            Mandate.ParameterNotNullOrEmpty(connectionString, "connectionString");
            Mandate.ParameterNotNull(fluentMappingsAssembly, "fluentMappingsAssembly");
            Mandate.ParameterCondition(nhDriver != SupportedNHDrivers.Unknown, "nhDriver");

            configurationCacheKey = new NhConfigurationCacheKey(
                nhDriver,
                connectionString,
                fluentMappingsAssembly,
                showSql,
                enablePostCommitListener,
                sessionContext,
                outputNhMappings);

            return(ConfigurationCache.GetOrAdd(
                       configurationCacheKey,
                       y =>
            {
                using (new WriteLockDisposable(MappingLocker))
                {
                    if (useNhProfiler)
                    {
                        try
                        {
                            NHibernateProfiler.Initialize();
                        }
                        catch (InvalidOperationException ex)
                        {
                            //swallow security exceptions, happens if running in Medium trust
                            if (!(ex.InnerException is SecurityException))
                            {
                                throw ex;
                            }
                        }
                    }

                    // Check if we already have a serialized Configuration object
                    // for this assembly version and assembly last-write date
                    using (new WriteLockDisposable(ConfigCacheLocker))
                        if (ConfigCacheFileExists(connectionString))
                        {
                            var cachedConfig = DeserializeConfig(connectionString);
                            if (cachedConfig != null)
                            {
                                return cachedConfig;
                            }
                        }

                    // We haven't cached config before, or couldn't load it, so dynamically create it

                    // Figure out the FluentNH persistence configurer based on the desired driver
                    var persistenceConfigurer = GetPersistenceConfigurer(nhDriver, connectionString);

                    // Figure out the connection release mode to use, because SqlCe needs "on_close" for perf reasons,
                    // whereas we should use "auto" for everything else to avoid long-running connections
                    var trueConnReleaseMode = connReleaseMode;                            // Could have been set already by a unit test
                    if (connReleaseMode == NHibernateConfigBuilder.CustomConnReleaseMode) // Only modify if it's a value teling us to modify
                    {
                        if (nhDriver == SupportedNHDrivers.MsSqlCe4)
                        {
                            trueConnReleaseMode = "on_close";
                        }
                        else
                        {
                            trueConnReleaseMode = "auto";
                        }
                    }

                    // Configure NH using FluentNH
                    var fluentConfig = Fluently.Configure().Database(persistenceConfigurer)
                                       //.Cache(x =>
                                       //        x.UseMinimalPuts()
                                       //        .UseQueryCache()
                                       //        .UseSecondLevelCache()
                                       //        .ProviderClass(typeof(global::NHibernate.Caches.SysCache2.SysCacheProvider).AssemblyQualifiedName))

                                       // after_transaction does not work for unit tests with Sqlite
                                       .ExposeConfiguration(c => c.SetProperty(Environment.ReleaseConnections, trueConnReleaseMode)
                                                            .SetProperty(Environment.CurrentSessionContextClass, sessionContext)
                                                            .SetProperty(Environment.GenerateStatistics, useNhProfiler.ToString().ToLower())
                                                            .SetProperty(Environment.BatchSize, "20")
                                                            .SetProperty(Environment.ProxyFactoryFactoryClass, typeof(ProxyFactoryFactory).AssemblyQualifiedName))
                                       .Mappings(x =>
                    {
                        // Add named queries from our embedded mappings file
                        x.HbmMappings.AddFromAssembly(fluentMappingsAssembly);

                        // Add class mappings
                        var container = x.FluentMappings.AddFromAssembly(fluentMappingsAssembly);
                        AddConventions(nhDriver, container.Conventions);
                    });

                    if (showSql)
                    {
                        fluentConfig.ExposeConfiguration(c => c.SetProperty(Environment.ShowSql, "true"));
                    }

                    try
                    {
                        // Generate the NHibernate configuration object from FluentNH
                        var nhConfig = fluentConfig.BuildConfiguration();

                        // Add a PostCommitInsert listener which is responsible for passing generated IDs back to the
                        // mapped entities for entity insert scenarios (since the NH mapped objects aren't passed outside
                        // of this provider)
                        if (enablePostCommitListener)
                        {
                            var entitySaveEventListener = new NhEventListeners();
                            nhConfig.SetListener(ListenerType.PostInsert, entitySaveEventListener);
                            nhConfig.SetListener(ListenerType.PostUpdate, entitySaveEventListener);
                            nhConfig.SetListener(ListenerType.PostCommitInsert, entitySaveEventListener);
                            nhConfig.SetListener(ListenerType.PreDelete, entitySaveEventListener);
                            nhConfig.SetListener(ListenerType.Delete, entitySaveEventListener);
                            nhConfig.SetListener(ListenerType.Merge, entitySaveEventListener);
                            nhConfig.SetListener(ListenerType.SaveUpdate, entitySaveEventListener);
                            nhConfig.SetListener(ListenerType.Flush, entitySaveEventListener);
                            nhConfig.SetListener(ListenerType.Evict, entitySaveEventListener);
                            nhConfig.SetListener(ListenerType.PreDelete, entitySaveEventListener);
                        }

                        // Add the Aggregate interceptor for running trigger-like actions that NH can't handle
                        // Disabled, done by event listener instead now: nhConfig.SetInterceptor(new AggregateDataInterceptor());

                        // Add the FluentNH persistence model and configure NH to use it
                        var fluentAutoModel = new AutoPersistenceModel();

                        fluentAutoModel.AddMappingsFromAssembly(fluentMappingsAssembly);
                        fluentAutoModel.BuildMappings();
                        fluentAutoModel.Configure(nhConfig);

                        if (outputNhMappings)
                        {
                            var codeBase = Assembly.GetExecutingAssembly().CodeBase;
                            var uri = new Uri(codeBase);
                            var path = uri.LocalPath;
                            var binFolder = new DirectoryInfo(Path.GetDirectoryName(path));
                            string nhibernateOutputFolder;
                            if (binFolder.Name == "Debug")
                            {
                                nhibernateOutputFolder = Path.Combine(
                                    binFolder.Parent.Parent.FullName, "App_Data", "Logs", "NHibernateConfig");
                            }
                            else
                            {
                                //its just 'bin'
                                nhibernateOutputFolder = Path.Combine(
                                    binFolder.Parent.FullName, "App_Data", "Logs", "NHibernateConfig");
                            }
                            Directory.CreateDirectory(nhibernateOutputFolder);
                            fluentAutoModel.WriteMappingsTo(nhibernateOutputFolder);
                        }

                        SaveConfigurationToFile(nhConfig, connectionString);

                        return nhConfig;
                    }
                    catch (Exception ex)
                    {
                        throw new InvalidOperationException("Cannot build NHibernate configuration", ex);
                    }
                }
            }));
        }
 public void ConfigurationExtensions_InitializeFromConfig_InitializedCorrectly()
 {
     Fluently.Configure().InitializeFromConfigSqLiteInMemory(true);
     Fluently.Configure().InitializeFromConfigSqLiteInMemory(true, c => c.Dialect <SQLiteDialect>());
 }
Esempio n. 16
0
        public static ISession GetConnection <T>(string Server, string DataBase, string Usuario, string Password)
        {
            string _connection_provider          = string.Empty;
            string _dialect                      = string.Empty;
            string _connection_driver            = string.Empty;
            string _connection_connection_string = "Server=[SERVER];DataBase=[DATABASE];uid=[USER];pwd=[PASSWORD]";
            string _show_sql                     = "false";
            string _showSql                      = string.Empty;
            string _generateStatistics           = string.Empty;

            NHibernate.Cfg.Configuration nhibernateConfig = new NHibernate.Cfg.Configuration();

            _connection_connection_string = _connection_connection_string.Replace("[SERVER]", Server);
            _connection_connection_string = _connection_connection_string.Replace("[DATABASE]", DataBase);
            _connection_connection_string = _connection_connection_string.Replace("[USER]", Usuario);
            _connection_connection_string = _connection_connection_string.Replace("[PASSWORD]", Password);

            _dialect            = ConfigurationManager.AppSettings["dialect"];
            _connection_driver  = ConfigurationManager.AppSettings["connectionDriver"];
            _showSql            = ConfigurationManager.AppSettings["showSql"];
            _generateStatistics = ConfigurationManager.AppSettings["generateStatistics"];

            if (!string.IsNullOrEmpty(_showSql))
            {
                _show_sql = _showSql;
            }

            if (string.IsNullOrEmpty(_generateStatistics))
            {
                _generateStatistics = "false";
            }



            if (string.IsNullOrEmpty(_dialect))
            {
                throw new Exception("The dialect has not been established");
            }

            nhibernateConfig.Properties[NHibernate.Cfg.Environment.Dialect]            = _dialect;
            nhibernateConfig.Properties[NHibernate.Cfg.Environment.ConnectionString]   = _connection_connection_string;
            nhibernateConfig.Properties[NHibernate.Cfg.Environment.GenerateStatistics] = _generateStatistics;
            nhibernateConfig.Properties[NHibernate.Cfg.Environment.ShowSql]            = _show_sql;

            if (iSessionFactory == null)
            {
                lock (syncRoot)
                {
                    if (iSessionFactory == null)
                    {
                        iSessionFactory = Fluently.Configure(nhibernateConfig)
                                          .Cache(c => c.UseQueryCache().ProviderClass <HashtableCacheProvider>())
                                          .Mappings(m => m.FluentMappings.AddFromAssemblyOf <T>())
                                          .BuildConfiguration()
                                          .BuildSessionFactory();
                    }
                }
            }

            return(iSessionFactory.OpenSession());
        }
Esempio n. 17
0
        public InMemoryMappingDatabase()
        {
            #region Programmatic Configuration assuming .hbm.xml files are embedded resources
            //var config = new Configuration()
            //    .SetProperty(Environment.ReleaseConnections, "on_close")
            //    .SetProperty(Environment.Dialect, typeof(SQLiteDialect).AssemblyQualifiedName)
            //    .SetProperty(Environment.ConnectionDriver, typeof(SQLite20Driver).AssemblyQualifiedName)
            //    .SetProperty(Environment.ConnectionString, "data source=:memory:")
            //    //.AddFile(@"D:\Dev\AdventuresWithCode\LearnHibernate\LearnHibernate.Persistence\Mappings\Xml\Employee.hbm.xml")
            //    //.AddFile(@"D:\Dev\AdventuresWithCode\LearnHibernate\LearnHibernate.Persistence\Mappings\Xml\Benefit.hbm.xml")
            //    //.AddFile(@"D:\Dev\AdventuresWithCode\LearnHibernate\LearnHibernate.Persistence\Mappings\Xml\Address.hbm.xml")
            //    //.AddFile(@"D:\Dev\AdventuresWithCode\LearnHibernate\LearnHibernate.Persistence\Mappings\Xml\Community.hbm.xml");
            //    .AddAssembly("LearnHibernate.Persistence");

            #endregion


            #region Loquacious Configuration

            //var config = new Configuration();
            //config.DataBaseIntegration(db =>
            //{
            //    db.Dialect<SQLiteDialect>();
            //    db.Driver<SQLite20Driver>();
            //    db.ConnectionReleaseMode = ConnectionReleaseMode.OnClose;
            //    db.ConnectionString = "data source=:memory:";
            //    db.LogFormattedSql = true;
            //    db.LogSqlInConsole = true;
            //})
            //.AddMapping(GetMapping());

            #endregion

            #region Fluent Configuration

            var fnhConfig = Fluently.Configure()
                            .Database(SQLiteConfiguration.Standard
                                      .DefaultSchema("LearnNH")
                                      .ShowSql()
                                      .FormatSql()
                            //.AdoNetBatchSize(50)
                                      .InMemory())
                            //.CurrentSessionContext<AsyncLocalSessionContext>()
                            //.Cache(cacheBuilder => {
                            //    cacheBuilder.UseQueryCache();
                            //    cacheBuilder.UseSecondLevelCache();
                            //})
                            //either of the below is fine. Latter is terse
                            //.Mappings(mapper => mapper.FluentMappings.AddFromAssembly(typeof(EmployeeFNHMapping).Assembly))
                            .Mappings(mapper => mapper.FluentMappings.AddFromAssemblyOf <EmployeeFNHMapping>());

            var config = fnhConfig.BuildConfiguration();
            #endregion


            sessionFactory = config.BuildSessionFactory();
            Session        = sessionFactory.OpenSession();

            new SchemaExport(config)
            .SetOutputFile(@".\ddl.sql")
            //.Create(false, true);
            .Execute(true, true, false, Session.Connection, null);

            //To increment update database
            //new SchemaUpdate(config).Execute(false, true);

            //validate that the schema and mappings are in compliance
            //this is ideal for an integration test?
            //new SchemaValidator(config).Validate();
        }
Esempio n. 18
0
        public static void Configuration(IAppBuilder app)
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            var connectionString = ConfigurationManager.ConnectionStrings["SMW_Base"];

            if (connectionString == null)
            {
                throw new Exception("Не найдена строка соединения");
            }

            var builder = new ContainerBuilder();

            var modelsAssembly = Assembly.GetAssembly(typeof(User));

            foreach (var type in modelsAssembly.GetTypes())
            {
                var attr = type.GetCustomAttribute <ListenerAttribute>();
                if (attr == null)
                {
                    continue;
                }
                var interfaces = type.GetInterfaces();
                var b          = builder.RegisterType(type);
                foreach (var inter in interfaces)
                {
                    b = b.As(inter);
                }
            }

            builder.Register(x =>
            {
                var cfg = Fluently.Configure()
                          .Database(MsSqlConfiguration.MsSql2012
                                    .ConnectionString(connectionString.ConnectionString)
                                    .Dialect <MsSql2012Dialect>())
                          .Mappings(m => m.FluentMappings.AddFromAssemblyOf <User>())
                          .ExposeConfiguration(c => {
                    SchemaMetadataUpdater.QuoteTableAndColumns(c);
                    c.EventListeners.PreInsertEventListeners = x.Resolve <IPreInsertEventListener[]>();
                    c.EventListeners.PreUpdateEventListeners = x.Resolve <IPreUpdateEventListener[]>();
                })
                          .CurrentSessionContext("call");
                var conf         = cfg.BuildConfiguration();
                var schemaExport = new SchemaUpdate(conf);
                schemaExport.Execute(true, true);
                return(cfg.BuildSessionFactory());
            }).As <ISessionFactory>().SingleInstance();
            builder.Register(x => x.Resolve <ISessionFactory>().OpenSession())
            .As <ISession>()
            .InstancePerRequest()
            .InstancePerDependency();

            foreach (var type in modelsAssembly.GetTypes())
            {
                var attr = type.GetCustomAttribute <RepositoryAttribute>();
                if (attr == null)
                {
                    continue;
                }
                builder.RegisterType(type);
            }

            builder.RegisterControllers(Assembly.GetAssembly(typeof(NoteController)));
            builder.RegisterModule(new AutofacWebTypesModule());
            var container = builder.Build();

            Locator.SetImpl(new AutofacLocatorImpl(container));
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
            app.UseAutofacMiddleware(container);

            app.CreatePerOwinContext(() =>
                                     new UserManager(new IdentityStore(DependencyResolver.Current.GetServices <ISession>().FirstOrDefault())));
            app.CreatePerOwinContext <SignInManager>((options, context) =>
                                                     new SignInManager(context.GetUserManager <UserManager>(), context.Authentication));

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/Account/Login"),
                Provider           = new CookieAuthenticationProvider()
            });
        }
Esempio n. 19
0
        private void InitializeNHibernate()
        {
            Configuration cfg = Fluently.Configure()
                                .Database(SQLiteConfiguration.Standard
                                          .ProxyFactoryFactory <ProxyFactoryFactory>()
                                          .CurrentSessionContext <ThreadStaticSessionContext>()
                                          .ShowSql()
                                          .InMemory())
                                .Mappings(m => m.AutoMappings
                                          .Add(AutoMap.AssemblyOf <Location>()
                                               .Where(t => typeof(IEntity).IsAssignableFrom(t))
                                               .Setup(s =>
            {
                s.IsComponentType =
                    type => typeof(ValueObject).IsAssignableFrom(type);
                s.GetComponentColumnPrefix =
                    property => property.PropertyType.Name + "_";
            })
                                               .Conventions.AddFromAssemblyOf <IntraAggregateEntityCollectionConvention>()
                                               ))
                                .ExposeConfiguration(x => x.AddAssembly("DDDSample.Domain.Persistence.NHibernate"))
                                .BuildConfiguration();

            //Configuration cfg = new Configuration()
            //   .AddProperties(new Dictionary<string, string>
            //                     {
            //                        {Environment.ConnectionDriver, typeof (SQLite20Driver).FullName},
            //                        {Environment.Dialect, typeof (SQLiteDialect).FullName},
            //                        {Environment.ConnectionProvider, typeof (DriverConnectionProvider).FullName},
            //                        {Environment.ConnectionString, "Data Source=:memory:;Version=3;New=True;"},
            //                        {
            //                           Environment.ProxyFactoryFactoryClass,
            //                           typeof (ProxyFactoryFactory).AssemblyQualifiedName
            //                           },
            //                        {
            //                           Environment.CurrentSessionContextClass,
            //                           typeof (ThreadStaticSessionContext).AssemblyQualifiedName
            //                           },
            //                        {Environment.ReleaseConnections,"on_close"},
            //                        {Environment.Hbm2ddlAuto, "create"},
            //                        {Environment.ShowSql, true.ToString()}
            //                     });
            //cfg.AddAssembly("DDDSample.Domain.Persistence.NHibernate");

            _sessionFactory = cfg.BuildSessionFactory();
            _ambientContainer.RegisterInstance(_sessionFactory);

            ISession session = _sessionFactory.OpenSession();

            new SchemaExport(cfg).Execute(false, true, false, session.Connection, Console.Out);

            session.Save(new Location(new UnLocode("CNHKG"), "Hongkong"));
            session.Save(new Location(new UnLocode("AUMEL"), "Melbourne"));
            session.Save(new Location(new UnLocode("SESTO"), "Stockholm"));
            session.Save(new Location(new UnLocode("FIHEL"), "Helsinki"));
            session.Save(new Location(new UnLocode("USCHI"), "Chicago"));
            session.Save(new Location(new UnLocode("JNTKO"), "Tokyo"));
            session.Save(new Location(new UnLocode("DEHAM"), "Hamburg"));
            session.Save(new Location(new UnLocode("CNSHA"), "Shanghai"));
            session.Save(new Location(new UnLocode("NLRTM"), "Rotterdam"));
            session.Save(new Location(new UnLocode("SEGOT"), "Göteborg"));
            session.Save(new Location(new UnLocode("CNHGH"), "Hangzhou"));
            session.Save(new Location(new UnLocode("USNYC"), "New York"));
            session.Save(new Location(new UnLocode("USDAL"), "Dallas"));
            session.Flush();

            _currentSession = session;

            CurrentSessionContext.Bind(_currentSession);
        }
Esempio n. 20
0
        public static void BuildConfiguration()
        {
            lock (_nibernateLock)
            {
                ConfigurationManager.RefreshSection("MonahrqConfigurationSectionGroup");

                var database = GetPersistenceConfigurer(_configService.MonahrqSettings.RebuildDatabase);

                var moduleAssemblies = GetModuleAssemblies().ToList();

                if (Configuration == null)
                {
                    Configuration = Fluently.Configure()
                                    .Database(database)
                                    .Mappings(m => moduleAssemblies.ForEach(mappingAssembly => m.FluentMappings.AddFromAssembly(mappingAssembly)))
                                    .Mappings(m => moduleAssemblies.ForEach(mappingAssembly => m.HbmMappings.AddFromAssembly(mappingAssembly)))
                                    //.Cache(c => c.ProviderClass<SysCacheProvider>().UseSecondLevelCache().UseQueryCache())
                                    .Cache(c => c.ProviderClass <HashtableCacheProvider>().UseSecondLevelCache().UseQueryCache())
                                    .ExposeConfiguration(cfg =>
                    {
                        cfg.SetProperty("current_session_context_class", "thread_static")
                        .SetProperty("use_proxy_validator", "false")
                        .SetProperty("connection.isolation", "ReadCommitted")
                        .SetProperty("adonet.batch_size", _configService.MonahrqSettings.BatchSize.ToString(CultureInfo.InvariantCulture))
                        .SetProperty("command_timeout", "5000");

                        //cfg.EventListeners.PostDeleteEventListeners = new IPostDeleteEventListener[] { new AuditEventListener() };
                        //cfg.EventListeners.PostUpdateEventListeners = new IPostUpdateEventListener[] { new AuditEventListener() };
                        //cfg.EventListeners.PostInsertEventListeners = new IPostInsertEventListener[] { new AuditEventListener() };
                        cfg.EventListeners.PreDeleteEventListeners = new IPreDeleteEventListener[] { new AuditPreUpdateEventListener() };
                        cfg.EventListeners.PreUpdateEventListeners = new IPreUpdateEventListener[] { new AuditPreUpdateEventListener() };
                        cfg.EventListeners.PreInsertEventListeners = new IPreInsertEventListener[] { new AuditPreUpdateEventListener() };
                        cfg.SetInterceptor(new SqlCaseSensitivityInterceptor());
                        //cfg.EventListeners.LoadEventListeners = new ILoadEventListener[] { new OrchardLoadEventListener() };
                        // cfg.SetInterceptor(new DataBindingInterceptor());

                        if (MonahrqContext.ForceDbUpGrade)
                        {
                            return;
                        }

                        SchemaMetadataUpdater.QuoteTableAndColumns(cfg);

                        //if (_configService.MonahrqSettings.RebuildDatabase)
                        //{
                        //    var schemaExport = new SchemaExport(cfg);
                        //    schemaExport.Drop(false, true);
                        //    schemaExport.Execute(true, false, false);
                        //}
                        //else
                        //{
                        try
                        {
                            var schemaUpdate = new SchemaUpdate(cfg);

                            schemaUpdate.Execute(false, true);
                        }
                        catch (Exception ex)
                        {
                            ex.GetType();
                        }
                        //}
                    })
                                    .BuildConfiguration();
                }
            }
        }
Esempio n. 21
0
        /// <summary>
        /// Initialize
        /// </summary>
        /// <param name="database">Database type</param>
        /// <param name="connectionString">Connection string</param>
        public NHibernateDatabaseContextFactory(string database, string connectionString)
        {
            // create database configuration
            var pathConfig  = Application.Ioc.Resolve <LocalPathConfig>();
            var fileStorage = Application.Ioc.Resolve <IFileStorage>();
            IPersistenceConfigurer db;

            if (string.Compare(database, "PostgreSQL", true) == 0)
            {
                db = BetterPostgreSQLConfiguration.Better.ConnectionString(connectionString);
            }
            else if (string.Compare(database, "SQLite", true) == 0)
            {
                db = SQLiteConfiguration.Standard.ConnectionString(
                    connectionString.Replace("{{App_Data}}", pathConfig.AppDataDirectory));
            }
            else if (string.Compare(database, "MySQL", true) == 0)
            {
                db = MySQLConfiguration.Standard.ConnectionString(connectionString);
            }
            else if (string.Compare(database, "MSSQL", true) == 0)
            {
                db = MsSqlConfiguration.MsSql2008.ConnectionString(connectionString);
            }
            else
            {
                throw new ArgumentException($"unsupported database type {database}");
            }
            var configuration = Fluently.Configure();

            configuration.Database(db);
            // register entity mappings
            var providers   = Application.Ioc.ResolveMany <IEntityMappingProvider>();
            var entityTypes = providers.Select(p =>
                                               ReflectionUtils.GetGenericArguments(
                                                   p.GetType(), typeof(IEntityMappingProvider <>))[0]).ToList();

            configuration.Mappings(m => entityTypes.ForEach(t => m.FluentMappings.Add(
                                                                typeof(NHibernateEntityMappingBuilder <>).MakeGenericType(t))));
            // call initialize handlers
            var handlers = Application.Ioc.ResolveMany <IDatabaseInitializeHandler>();

            configuration.Mappings(m => {
                m.FluentMappings.Conventions.Add(ConventionBuilder.Class.Always(x => {
                    var tableName = x.EntityType.Name;
                    handlers.ForEach(h => h.ConvertTableName(ref tableName));
                    x.Table(tableName);
                }));
                m.FluentMappings.Conventions.Add(ConventionBuilder.HasManyToMany.Always(x => {
                    var tableName = string.Format(
                        "{0}To{1}", x.EntityType.Name, x.ChildType.Name);
                    handlers.ForEach(h => h.ConvertTableName(ref tableName));
                    x.Table(tableName);
                }));
            });
            // initialize database scheme
            // flow:
            // - generate ddl script
            // - compare to App_Data\nh_{hash}.ddl
            // - if they are different, upgrade database scheme and write ddl script to file
            // it can make the website startup faster
            var hash = PasswordUtils.Sha1Sum(
                Encoding.UTF8.GetBytes(database + connectionString)).ToHex();
            var    ddlFileEntry          = fileStorage.GetStorageFile($"nh_{hash}.ddl");
            Action onBuildFactorySuccess = null;

            configuration.ExposeConfiguration(c => {
                var scriptBuilder = new StringBuilder();
                scriptBuilder.AppendLine("/* this file is for database migration checking, don't execute it */");
                new SchemaExport(c).Create(s => scriptBuilder.AppendLine(s), false);
                var script = scriptBuilder.ToString();
                if (!ddlFileEntry.Exists || script != ddlFileEntry.ReadAllText())
                {
                    var logManager   = Application.Ioc.Resolve <LogManager>();
                    var schemaUpdate = new SchemaUpdate(c);
                    schemaUpdate.Execute(false, true);
                    foreach (var ex in schemaUpdate.Exceptions)
                    {
                        logManager.LogError($"NHibernate schema update error: ({ex.GetType()}) {ex.Message}");
                    }
                    onBuildFactorySuccess = () => ddlFileEntry.WriteAllText(script);
                }
            });
            // create nhibernate session factory and write ddl script to file
            Database       = database;
            SessionFactory = configuration.BuildSessionFactory();
            onBuildFactorySuccess?.Invoke();
        }
Esempio n. 22
0
 public AbpNHibernateModuleConfiguration()
 {
     FluentConfiguration = Fluently.Configure();
 }
Esempio n. 23
0
        public ISessionFactory CreateSessionFactory()
        {
            var sDbUser     = System.Configuration.ConfigurationManager.AppSettings["dbUser"];
            var sDbPassword = System.Configuration.ConfigurationManager.AppSettings["dbPassword"];
            var sDbName     = System.Configuration.ConfigurationManager.AppSettings["dbName"];
            var sDbHost     = System.Configuration.ConfigurationManager.AppSettings["dbHost"];
            var sDbType     = System.Configuration.ConfigurationManager.AppSettings["dbType"];
            var sDbPort     = System.Configuration.ConfigurationManager.AppSettings["dbPort"];

            string sConnectionString;

            global::NHibernate.Cfg.Configuration configuration;

            switch (sDbType)
            {
            case "2":
                sConnectionString = @"Server=" + sDbHost + ";Initial Catalog=" + sDbName + ";User Id=" + sDbUser + ";Password="******"3":
                sConnectionString = @"Server=" + sDbHost + ";Database=" + sDbName + ";User ID=" + sDbUser + ";Password="******";";
                configuration     = Fluently
                                    .Configure()
                                    .Database(PostgreSQLConfiguration
                                              .Standard
                                              .ConnectionString(sConnectionString)
                                              .ShowSql
                                              )
                                    //.Mappings(m => m.FluentMappings.AddFromAssemblyOf<ACCDataStore.Entity.Mapping.Nationality2012Map>())
                                    .BuildConfiguration();
                break;

            case "4":
                sConnectionString = sDbName;
                configuration     = Fluently
                                    .Configure()
                                    .Database(JetDriverConfiguration
                                              .Standard
                                              .ConnectionString(c => c.DatabaseFile(sConnectionString))
                                              .ShowSql
                                              )
                                    .Mappings(m => m.FluentMappings.AddFromAssemblyOf <ACCDataStore.Entity.Mapping.MSAccess.DatahubDataObjMap>())
                                    .BuildConfiguration();
                break;

            default:
                sConnectionString = @"Server =" + sDbHost + ";Port=" + sDbPort + ";Database=" + sDbName + ";User ID=" + sDbUser + ";Password="******";";
                configuration     = Fluently
                                    .Configure()
                                    .Database(MySQLConfiguration
                                              .Standard
                                              .ConnectionString(sConnectionString)
                                              .ShowSql
                                              )
                                    //.Mappings(m => m.FluentMappings.AddFromAssemblyOf<ACCDataStore.Entity.Mapping.MySQL.LA100SchoolsMap>())
                                    .BuildConfiguration();
                break;
            }

            return(configuration.BuildSessionFactory());
        }
Esempio n. 24
0
        static void Main(string[] args)
        {
            WriteLine("Create and configuration database");

            ISessionFactory sessionFactory = Fluently
                                             .Configure()
                                             .Database(MsSqlConfiguration.MsSql2012.ConnectionString(
                                                           @"Data Source=localhost;Initial Catalog=NHTest; User Id=sa;Password=Hello@123"))
                                             .Mappings(m => m.FluentMappings.AddFromAssemblyOf <Program>())
                                             .ExposeConfiguration(config => new SchemaUpdate(config).Execute(true, true))
                                             .BuildSessionFactory();

            WriteLine("Saving Author and Book");

            using (ISession session = sessionFactory.OpenSession())
            {
                var author = new Author
                {
                    Name = "Affonso Solano"
                };

                WriteLine($"Creating Author:{author}");

                session.Save(author);

                var book = new Book
                {
                    Name   = "O Espadachim de Carvão",
                    Author = author
                };

                WriteLine($"Creating Book:{book}");

                session.Save(book);
                session.Flush();
                WriteLine("Saved on database");
                WriteLine($"Author: {author} - Book: {book}");
            }

            using (ISession session = sessionFactory.OpenSession())
            {
                var author = new Author
                {
                    Name = "Eduardo Spohr"
                };

                WriteLine($"Creating Author:{author}");

                session.Save(author);

                var jovemNerd = new Collaborator
                {
                    Name = "Jovem Nerd"
                };

                WriteLine($"Creating Collaborator:{jovemNerd}");
                session.Save(jovemNerd);

                var azaghal = new Collaborator
                {
                    Name = "Azaghal"
                };

                WriteLine($"Creating Collaborator:{azaghal}");
                session.Save(azaghal);

                var book = new Book
                {
                    Name   = "A Batalha do Apocalipse",
                    Author = author,
                };

                book.Collaborators.Add(jovemNerd);
                book.Collaborators.Add(azaghal);

                WriteLine($"Creating Book:{book}");

                session.Save(book);
                session.Flush();
                WriteLine("Saved on database");
                WriteLine($"Author: {author} - Book: {book}");
            }

            using (ISession session = sessionFactory.OpenSession())
            {
                foreach (Book book in session.Query <Book>().Where(x => x.Collaborators.Any()))
                {
                    WriteLine(book);
                }
            }

            ReadLine();
        }
        /// <summary>
        /// Creates a <see cref="FluentConfiguration"/> instance
        /// </summary>
        /// <param name="connectionStringName">The name of the connection string</param>
        /// <param name="persistenceConfiguration">The persistence configuration type name</param>
        /// <param name="dialect">The persistence configuration dialect full type name</param>
        /// <returns>An <see cref="FluentConfiguration"/> instance</returns>
        private FluentConfiguration FluentlyConfigure(string connectionStringName, string persistenceConfiguration, string dialect = null)
        {
            if (connectionStringName == null)
            {
                throw new ArgumentNullException(nameof(connectionStringName));
            }

            if (persistenceConfiguration == null)
            {
                throw new ArgumentNullException(nameof(persistenceConfiguration));
            }

            if (string.IsNullOrWhiteSpace(persistenceConfiguration) || persistenceConfiguration.IndexOf(".", StringComparison.Ordinal) == -1 ||
                persistenceConfiguration.IndexOf(".", StringComparison.Ordinal) < 1)
            {
                throw new FormatException($"Persistence configuration is of invalid format {persistenceConfiguration}");
            }

            var assembly = Assembly.Load("FluentNHibernate");

            if (assembly == null)
            {
                throw new Exception("Assembly FluentNHibernate not found.");
            }

            var configurationType =
                assembly.GetType(
                    $"FluentNHibernate.Cfg.Db.{persistenceConfiguration.Substring(0, persistenceConfiguration.IndexOf(".", StringComparison.Ordinal))}");

            if (configurationType == null)
            {
                throw new Exception($"Type {persistenceConfiguration} not found.");
            }

            var configurationPropertyName =
                persistenceConfiguration.Substring(persistenceConfiguration.IndexOf(".", StringComparison.Ordinal) + 1);

            var configurationProperty = configurationType.GetProperty(configurationPropertyName);

            if (configurationProperty == null)
            {
                throw new Exception(
                          $"Property with name {configurationPropertyName} not found on type {configurationType.Name}.");
            }

            var configurationPropertyValue = configurationProperty.GetValue(configurationType, null);

            if (configurationPropertyValue == null)
            {
                throw new Exception(
                          $"Property with name {configurationProperty} on type {configurationType} has no value.");
            }

            Type dialectType = null;

            if (!string.IsNullOrWhiteSpace(dialect))
            {
                dialectType = Type.GetType(dialect);
                if (dialectType == null)
                {
                    throw new TypeLoadException($"Cannot load dialect type {dialect}");
                }
            }

            if (dialectType != null)
            {
                var dialectMethod = configurationPropertyValue.GetType().GetMethod("Dialect", new Type[] { });

                if (dialectMethod != null)
                {
                    configurationPropertyValue = dialectMethod.MakeGenericMethod(dialectType).Invoke(configurationPropertyValue, new object[] { });
                }
            }

            if (configurationPropertyValue == null)
            {
                throw new Exception($"Cannot load dialect {dialect}");
            }

            var configurationPropertyType = configurationPropertyValue.GetType();
            var connectionStringMethod    = configurationPropertyType.GetMethod("ConnectionString", new[] { typeof(string) });

            if (connectionStringMethod == null)
            {
                throw new Exception($"ConnectionString method not found on type {configurationPropertyType}.");
            }

            var connectionString = RyanPenfold.Configuration.ConnectionStrings.Get(connectionStringName);

            if (string.IsNullOrEmpty(connectionString))
            {
                throw new Exception($"Connection string {connectionStringName} not found in the configuration settings");
            }

            if (string.IsNullOrWhiteSpace(connectionString))
            {
                throw new Exception($"Connection string {connectionStringName} ");
            }

            return(Fluently.Configure().Database((IPersistenceConfigurer)connectionStringMethod.Invoke(configurationPropertyValue, new object[] { connectionString })));
        }
		public static ISessionFactory GetDatabaseSessionFactory(Env? environmentOverride_testOnly = null) {
			Configuration c;
			var env = environmentOverride_testOnly ?? CurrentEnv ?? Config.GetEnv();
			CurrentEnv = env;
			if (factories == null)
				factories = new Dictionary<Env, ISessionFactory>();
			if (!factories.ContainsKey(env)) {
				lock (lck) {
					ChromeExtensionComms.SendCommand("dbStart");
					var config = System.Configuration.ConfigurationManager.AppSettings;
					var connectionStrings =  System.Configuration.ConfigurationManager.ConnectionStrings;

					switch (environmentOverride_testOnly ?? Config.GetEnv()) {
						//case Env.local_mysql: {

						//		var connectionString = connectionStrings["DefaultConnectionMsSql"].ConnectionString;
						//		var file = connectionString.Split(new String[] { "Data Source=" }, StringSplitOptions.RemoveEmptyEntries)[0].Split(';')[0];
						//		DbFile = file;
						//		try {
						//			c = new Configuration();
						//			c.SetInterceptor(new NHSQLInterceptor());
								
						//			factories[env] = Fluently.Configure(c).Database(MsSqlConfiguration.MsSql2012.ConnectionString(connectionString))
						//			.Mappings(m => {
						//				m.FluentMappings.AddFromAssemblyOf<UserModel>();
						//			})
						//		   .CurrentSessionContext("web")
						//		   .ExposeConfiguration(x => BuildMsSqlSchema(x))
						//		   .BuildSessionFactory();
						//		} catch (Exception e) {
						//			throw e;
						//		}
						//		break;
						//	}
						//case Env.mssql: {								
						//		try {
						//			c = new Configuration();
						//			c.SetInterceptor(new NHSQLInterceptor());
									
						//			factories[env] = Fluently.Configure(c).Database(MsSqlConfiguration.MsSql2012.ConnectionString(connectionStrings["DefaultConnectionMsSql"].ConnectionString)/*.ShowSql()*/)
						//			   .Mappings(m => {
						//				   m.FluentMappings.AddFromAssemblyOf<UserModel>();
						//			   })
						//			   .ExposeConfiguration(x => BuildMsSqlSchema(x))
						//			   .BuildSessionFactory();
						//		} catch (Exception e) {
						//			var mbox = e.Message;
						//			if (e.InnerException != null && e.InnerException.Message != null)
						//				mbox = e.InnerException.Message;

						//			ChromeExtensionComms.SendCommand("dbError", mbox);
						//			throw e;
						//		}
						//		break;
						//	}
						case Env.test_server: {
								try {
									c = new Configuration();
									c.SetInterceptor(new NHSQLInterceptor());

									factories[env] = Fluently.Configure(c).Database(MsSqlConfiguration.MsSql2012.ConnectionString(connectionStrings["Test_Server"].ConnectionString)/*.ShowSql()*/)
									   .Mappings(m => {
										   m.FluentMappings.AddFromAssemblyOf<TimeLogs>();
									   })
									   .ExposeConfiguration(x => BuildMsSqlSchema(x))
									   .BuildSessionFactory();
								} catch (Exception e) {
									var mbox = e.Message;
									if (e.InnerException != null && e.InnerException.Message != null)
										mbox = e.InnerException.Message;

									ChromeExtensionComms.SendCommand("dbError", mbox);
									throw e;
								}
								break;
							}

						default:
							throw new Exception("No database type");
					}
					Names = new RuntimeNames(c);
					ChromeExtensionComms.SendCommand("dbComplete");
				}
			}
			return factories[env];
		}
 public void InitializeFromConfigOracleClient_SectionNotFound_DatabaseConnectionConfigurationException()
 {
     // Act
     Assert.Throws <DatabaseConnectionConfigurationException>(() => Fluently.Configure().InitializeFromConfigOracleClient("foo"));
 }
Esempio n. 28
0
        /// <summary>
        /// Initialize<br/>
        /// 初始化<br/>
        /// </summary>
        public NHibernateDatabaseContextFactory(
            string database, string connectionString,
            IEnumerable <IDatabaseInitializeHandler> handlers,
            IEnumerable <IEntityMappingProvider> providers)
        {
            // create database configuration
            var pathConfig = Application.Ioc.Resolve <LocalPathConfig>();
            IPersistenceConfigurer db;

            if (string.Compare(database, "PostgreSQL", true) == 0)
            {
                db = BetterPostgreSQLConfiguration.Better.ConnectionString(connectionString);
            }
            else if (string.Compare(database, "SQLite", true) == 0)
            {
                db = SQLiteConfiguration.Standard.ConnectionString(
                    connectionString.Replace("{{App_Data}}", pathConfig.AppDataDirectory));
            }
            else if (string.Compare(database, "MySQL", true) == 0)
            {
                db = MySQLConfiguration.Standard.ConnectionString(connectionString);
            }
            else if (string.Compare(database, "MSSQL", true) == 0)
            {
                db = MsSqlConfiguration.MsSql2008.ConnectionString(connectionString);
            }
            else
            {
                throw new ArgumentException($"unsupported database type {database}");
            }
            var configuration = Fluently.Configure();

            configuration.Database(db);
            // register entity mappings
            var entityProviders = providers
                                  .GroupBy(p => ReflectionUtils.GetGenericArguments(
                                               p.GetType(), typeof(IEntityMappingProvider <>))[0])
                                  .ToList();

            configuration.Mappings(m => {
                // FIXME: fluent nhibernate doesn't support passing arguments to builder
                // so it still retrieve providers and handers from IoC container
                foreach (var group in entityProviders)
                {
                    var builder = typeof(NHibernateEntityMappingBuilder <>).MakeGenericType(group.Key);
                    m.FluentMappings.Add(builder);
                }
            });
            // set many-to-many table name
            configuration.Mappings(m => {
                m.FluentMappings.Conventions.Add(ConventionBuilder.HasManyToMany.Always(x => {
                    var tableName = string.Format("{0}To{1}", x.EntityType.Name, x.ChildType.Name);
                    foreach (var handler in handlers)
                    {
                        handler.ConvertTableName(ref tableName);
                    }
                    x.Table(tableName);
                }));
            });
            // check if database auto migration is disabled
            var configManager   = Application.Ioc.Resolve <WebsiteConfigManager>();
            var noAutoMigration = configManager.WebsiteConfig.Extra.GetOrDefault <bool?>(
                NHibernateExtraConfigKeys.DisableNHibernateDatabaseAutoMigration) ?? false;

            if (!noAutoMigration)
            {
                MigrateDatabase(database, connectionString, configuration);
            }
            // create nhibernate session
            Database         = database;
            ConnectionString = connectionString;
            SessionFactory   = configuration.BuildSessionFactory();
        }
Esempio n. 29
0
        private static Configuration CreateConfiguration()
        {
            FluentConfiguration fluentConfig = Fluently.Configure();

            switch (DatabaseType)
            {
            case SupportedDatabaseType.SQLEXPRESS_2012:
            {
                // IMPORTANT: The database MUST ALREADY EXIST.
                //fluentConfig.Database(
                //	MsSqlConfiguration.MsSql2012.ConnectionString(x =>
                //		x.Server(@".\SQLEXPRESS")
                //		.Database("teltec_backup")
                //		.TrustedConnection()
                //	).UseReflectionOptimizer()
                //);
                fluentConfig.Database(
                    MsSqlConfiguration.MsSql2012.ConnectionString(x =>
                                                                  x.Server(@".\SQLEXPRESS")
                                                                  .Database("teltec_backup_db")
                                                                  .Username("teltec_backup_user")
                                                                  .Password("p@55w0rd")
                                                                  ).UseReflectionOptimizer()
                    );
                break;
            }

            case SupportedDatabaseType.SQLITE3:
            {
                string dataDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                string dbFilePath    = dataDirectory + @"\database.sqlite3";
                fluentConfig.Database(SQLiteConfiguration.Standard.UsingFile(dbFilePath));
                break;
            }
            }

            //fluentConfig.Diagnostics(diag => diag.Enable().OutputToConsole());

            // Add all mappings from this assembly.
            fluentConfig.Mappings(m => m.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly()));

            Configuration config = fluentConfig.BuildConfiguration();

            //config.SetProperty(NHibernate.Cfg.Environment.Hbm2ddlAuto, "true");

            if (DatabaseType == SupportedDatabaseType.SQLEXPRESS_2012)
            {
                config.DataBaseIntegration(db =>
                {
                    db.BatchSize = NHibernateHelper.BatchSize;
                    db.Dialect <NHibernate.Dialect.MsSql2012Dialect>();
                    db.Driver <NHibernate.Driver.Sql2008ClientDriver>();
                    //db.HqlToSqlSubstitutions = "true 1, false 0, yes 'Y', no 'N'";
                    db.IsolationLevel     = System.Data.IsolationLevel.ReadCommitted;
                    db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
#if DEBUG
                    db.LogFormattedSql = true;
                    db.LogSqlInConsole = true;
#else
                    db.LogFormattedSql = false;
                    db.LogSqlInConsole = false;
#endif
                    //db.OrderInserts = true;
                    //db.PrepareCommands = true;
                    db.SchemaAction = SchemaAutoAction.Update;
                });
            }

            UpdateSchema(config);
            ValidateSchema(config);

            // Register interceptors.
#if DEBUG
            config.SetInterceptor(new NHibernateAuditInterceptor());
#endif

            // Register listeners.
            config.AppendListeners(ListenerType.Load, new ILoadEventListener[] {
                new NHibernateLoadListener(),
            });
            config.AppendListeners(ListenerType.PostLoad, new IPostLoadEventListener[] {
                new NHibernatePersistentEntityListener(),
            });
            config.AppendListeners(ListenerType.Save, new ISaveOrUpdateEventListener[] {
                new NHibernatePersistentEntityListener(),
            });
            config.AppendListeners(ListenerType.Update, new ISaveOrUpdateEventListener[] {
                new NHibernatePersistentEntityListener(),
            });

            return(config);
        }
 public FluentConfiguration BuildFluent()
 {
     return(Fluently.Configure()
            .Database(SQLiteConfiguration.Standard.UsingFile("DataStore.db"))
            .Mappings(m => m.FluentMappings.AddFromAssemblyOf <NHibInstaller>()));
 }