private ISessionFactory GetNHibernateSessionFactory()
        {
            var connString = ConfigurationManager.ConnectionStrings["IdSvr3Config"];

            var sessionFactory = Fluently.Configure()
                                 .Database(MsSqlConfiguration.MsSql2012.ConnectionString(connString.ToString())
                                           .ShowSql()
                                           .FormatSql()
                                           .AdoNetBatchSize(20)
                                           )
                                 .Mappings(
                m => m.AutoMappings.Add(MappingHelper.GetNhibernateServicesMappings(true, true))
                )
                                 .ExposeConfiguration(cfg =>
            {
                SchemaMetadataUpdater.QuoteTableAndColumns(cfg);
                BuildSchema(cfg);
            })
                                 .BuildSessionFactory();

            return(sessionFactory);
        }
コード例 #2
0
        public NhHelper(IDictionary <string, string> configParameters, bool allowInstall, List <string> mappingFiles)
        {
            configParameters.ToList()
            .ForEach(x => Console.WriteLine("{0}:{1}", x.Key, x.Value));

            _configuration = new Configuration().DataBaseIntegration(
                x =>
            {
#if DEBUG
                x.LogSqlInConsole = true;
                x.LogFormattedSql = true;
#endif
            });


            var cfg         = _configuration.SetProperties(configParameters);
            var modelMapper = new ModelMapper();
            mappingFiles.ToList().ForEach(
                assebmlyFile => modelMapper.AddMappings(Assembly.Load(assebmlyFile).GetExportedTypes()));

            var mp = modelMapper.CompileMappingForAllExplicitlyAddedEntities();
            // For Duplicate mapping
            mp.autoimport = false;
            cfg.AddDeserializedMapping(mp, null);

#pragma warning disable CS0618 // Type or member is obsolete
            SchemaMetadataUpdater.QuoteTableAndColumns(cfg);
#pragma warning restore CS0618 // Type or member is obsolete

            if (!Directory.Exists(ScriptFolder))
            {
                Directory.CreateDirectory(ScriptFolder);
            }

            if (allowInstall && !File.Exists(ScriptFile))
            {
                new SchemaExport(cfg).SetOutputFile(ScriptFile).Create(false, true);
            }
        }
コード例 #3
0
        public static ISessionFactory CreateNhSessionFactory <TRootEntity>(string connectionString)
        {
            var mapper   = new ConventionModelMapper();
            var mappings = NhHelper.CreateConventionalMappings <TRootEntity>(mapper);
            var config   = NhHelper.CreateConfig(mappings, cfg =>
            {
                cfg.DataBaseIntegration(db =>
                {
                    db.ConnectionString = connectionString;
                    db.ConnectionProvider <DriverConnectionProvider>();
                    db.Driver <SqlClientDriver>();
                    db.Dialect <MsSql2012Dialect>();
                    db.KeywordsAutoImport = Hbm2DDLKeyWords.None;
                });
            });

            SchemaMetadataUpdater.QuoteTableAndColumns(config, new MsSql2012Dialect());

            var sessionFactory = config.BuildSessionFactory();

            return(sessionFactory);
        }
コード例 #4
0
        public async Task WhenConfiguredOnlyExplicitAutoQuoteAsync()
        {
            var configuration = TestConfigurationHelper.GetDefaultConfiguration();
            var driverClass   = ReflectHelper.ClassForName(configuration.GetProperty(Environment.ConnectionDriver));

            // Test uses the default dialect driver, which will not accept Odbc or OleDb connection strings.
            if (typeof(OdbcDriver).IsAssignableFrom(driverClass) || typeof(OleDbDriver).IsAssignableFrom(driverClass))
            {
                Assert.Ignore("Test is not compatible with OleDb or ODBC driver connection strings");
            }

            var configuredDialect = Dialect.Dialect.GetDialect();

            if (!configuredDialect.DefaultProperties.ContainsKey(Environment.ConnectionDriver))
            {
                Assert.Ignore(GetType() + " does not apply to " + configuredDialect);
            }
            configuration.Properties.Remove(Environment.ConnectionDriver);
            configuration.AddResource("NHibernate.Test.Tools.hbm2ddl.SchemaMetadataUpdaterTest.HeavyEntity.hbm.xml",
                                      GetType().Assembly);

            var dialect = Dialect.Dialect.GetDialect(configuration.GetDerivedProperties());

            dialect.Keywords.Add("Abracadabra");

            await(SchemaMetadataUpdater.UpdateAsync(configuration, dialect, CancellationToken.None));
            SchemaMetadataUpdater.QuoteTableAndColumns(configuration, dialect);

            var cm = configuration.GetClassMapping(typeof(Order));

            Assert.That(cm.Table.IsQuoted);
            var culs = new List <Column>(cm.Table.ColumnIterator);

            Assert.That(GetColumnByName(culs, "From").IsQuoted);
            Assert.That(GetColumnByName(culs, "And").IsQuoted);
            Assert.That(GetColumnByName(culs, "Select").IsQuoted);
            Assert.That(GetColumnByName(culs, "Abracadabra").IsQuoted);
            Assert.That(!GetColumnByName(culs, "Name").IsQuoted);
        }
コード例 #5
0
        public Configuration BuildConfiguration(string connectionString, string sessionFactoryName)
        {
            Contract.Requires(!string.IsNullOrEmpty(connectionString), "ConnectionString is null or empty");
            Contract.Requires(!string.IsNullOrEmpty(sessionFactoryName), "SessionFactory name is null or empty");
            Contract.Requires(!string.IsNullOrEmpty(_databaseSchema), "Database Schema is null or empty");
            Contract.Requires(_configurator != null, "Configurator is null");

            return(CatchExceptionHelper.TryCatchFunction(
                       () =>
            {
                DomainTypes = GetTypeOfEntities(_assemblies);

                if (DomainTypes == null)
                {
                    throw new Exception("Type of domains is null");
                }

                var configure = new Configuration();
                configure.SessionFactoryName(sessionFactoryName);

                configure.Proxy(p => p.ProxyFactoryFactory <ProxyFactoryFactory>());
                configure.DataBaseIntegration(db => GetDatabaseIntegration(db, connectionString));

                if (_configurator.GetAppSettingString("IsCreateNewDatabase").ConvertToBoolean())
                {
                    configure.SetProperty("hbm2ddl.auto", "create-drop");
                }

                configure.Properties.Add("default_schema", _databaseSchema);
                configure.AddDeserializedMapping(GetMapping(),
                                                 _configurator.GetAppSettingString("DocumentFileName"));

                SchemaMetadataUpdater.QuoteTableAndColumns(configure);

                return configure;
            }, Logger));
        }
コード例 #6
0
        public Configuration Build()
        {
            var configuration = new Configuration();

            // initialize database configuration
            configuration.DataBaseIntegration(cfg =>
            {
                cfg.ConnectionStringName = ConnectionStringName;
                cfg.Driver <Sql2008ClientDriver>();
                cfg.Dialect <MsSql2008Dialect>();
                cfg.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
            });

            // initialize mappers
            var mapper = new ModelMapper();

            mapper.AddMappings(GetType().Assembly.GetExportedTypes());
            configuration.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());

            // Auto Quote all table and column names
            SchemaMetadataUpdater.QuoteTableAndColumns(configuration);

            return(configuration);
        }
コード例 #7
0
ファイル: ORMManger.cs プロジェクト: Woody-Hu/NoneMapORM
        /// <summary>
        /// 创建数据库架构
        /// </summary>
        private void CreatSchema()
        {
            SchemaMetadataUpdater.QuoteTableAndColumns(m_hibernateConfig, m_useConfiguartionPacker.GetUseDialect());

            new SchemaExport(m_hibernateConfig).Create(false, true);
        }
コード例 #8
0
        /// <summary>
        /// Execute the schema updates
        /// </summary>
        /// <param name="scriptAction">The action to write the each schema line.</param>
        /// <param name="doUpdate">Commit the script to DB</param>
        public void Execute(Action <string> scriptAction, bool doUpdate)
        {
            log.Info("Running hbm2ddl schema update");

            var autoKeyWordsImport = PropertiesHelper.GetString(Environment.Hbm2ddlKeyWords, configuration.Properties, "not-defined");

            autoKeyWordsImport = autoKeyWordsImport.ToLowerInvariant();
            if (autoKeyWordsImport == Hbm2DDLKeyWords.AutoQuote)
            {
                SchemaMetadataUpdater.QuoteTableAndColumns(configuration);
            }

            IDbCommand stmt = null;

            exceptions.Clear();

            try
            {
                DatabaseMetadata meta;
                try
                {
                    log.Info("fetching database metadata");
                    connectionHelper.Prepare();
                    var connection = connectionHelper.Connection;
                    meta = new DatabaseMetadata(connection, dialect);
                    stmt = connection.CreateCommand();
                }
                catch (Exception sqlException)
                {
                    exceptions.Add(sqlException);
                    log.Error("could not get database metadata", sqlException);
                    throw;
                }

                log.Info("updating schema");

                var updateSQL = configuration.GenerateSchemaUpdateScript(dialect, meta);

                foreach (var item in updateSQL)
                {
                    var updateSqlStatement = fixUpHelper.FixUp(item);
                    var formatted          = formatter.Format(updateSqlStatement);

                    try
                    {
                        scriptAction?.Invoke(formatted);
                        if (doUpdate)
                        {
                            log.Debug(updateSqlStatement);
                            stmt.CommandText = updateSqlStatement;
                            stmt.ExecuteNonQuery();
                        }
                    }
                    catch (Exception e)
                    {
                        exceptions.Add(e);
                        log.Error("Unsuccessful: " + updateSqlStatement, e);
                    }
                }

                log.Info("schema update complete");
            }
            catch (Exception e)
            {
                exceptions.Add(e);
                log.Error("could not complete schema update", e);
            }
            finally
            {
                try
                {
                    stmt?.Dispose();
                    connectionHelper.Release();
                }
                catch (Exception e)
                {
                    exceptions.Add(e);
                    log.Error("Error closing connection", e);
                }
            }
        }
コード例 #9
0
        public void JustForFun()
        {
            Configuration conf = ConfigureNHibernate();

            conf.AddDeserializedMapping(GetMapping(), "Animals_Domain");
            SchemaMetadataUpdater.QuoteTableAndColumns(conf);
            new SchemaExport(conf).Create(false, true);
            ISessionFactory factory = conf.BuildSessionFactory();

            using (ISession s = factory.OpenSession())
            {
                using (ITransaction tx = s.BeginTransaction())
                {
                    var polliwog = new Animal {
                        BodyWeight = 12, Description = "Polliwog"
                    };

                    var catepillar = new Animal {
                        BodyWeight = 10, Description = "Catepillar"
                    };

                    var frog = new Animal {
                        BodyWeight = 34, Description = "Frog"
                    };

                    polliwog.Father = frog;
                    frog.AddOffspring(polliwog);

                    var butterfly = new Animal {
                        BodyWeight = 9, Description = "Butterfly"
                    };

                    catepillar.Mother = butterfly;
                    butterfly.AddOffspring(catepillar);

                    s.Save(frog);
                    s.Save(polliwog);
                    s.Save(butterfly);
                    s.Save(catepillar);

                    var dog = new Dog {
                        BodyWeight = 200, Description = "dog"
                    };
                    s.Save(dog);

                    var cat = new Cat {
                        BodyWeight = 100, Description = "cat"
                    };
                    s.Save(cat);

                    var zoo = new Zoo {
                        Name = "Zoo"
                    };
                    var add = new Address {
                        City = "MEL", Country = "AU", Street = "Main st", PostalCode = "3000"
                    };
                    zoo.Address = add;

                    Zoo pettingZoo = new PettingZoo {
                        Name = "Petting Zoo"
                    };
                    var addr = new Address {
                        City = "Sydney", Country = "AU", Street = "High st", PostalCode = "2000"
                    };
                    pettingZoo.Address = addr;

                    s.Save(zoo);
                    s.Save(pettingZoo);
                    tx.Commit();
                }
            }

            using (ISession s = factory.OpenSession())
            {
                using (ITransaction tx = s.BeginTransaction())
                {
                    s.CreateQuery("delete from Animal where mother is not null or father is not null").ExecuteUpdate();
                    s.CreateQuery("delete from Animal").ExecuteUpdate();
                    s.CreateQuery("delete from Zoo").ExecuteUpdate();
                    tx.Commit();
                }
            }

            new SchemaExport(conf).Drop(false, true);
        }
コード例 #10
0
        public void Configure()
        {
            Configuration = new Configuration().DataBaseIntegration(
                x =>
            {
                    #if DEBUG
                x.LogSqlInConsole = true;
                x.LogFormattedSql = true;
                    #endif
            });

            var filePath = ConfigFile;
            filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, filePath);

            var cfg = Configuration.Configure(filePath);

            Action <IEnumerable <string> > funcCreateInitialScripts =
                scriptFileNames =>
            {
                var scriptBuilder = new StringBuilder();
                scriptFileNames
                .ToList().ForEach(
                    scriptFile =>
                {
                    using (var streamReader = new StreamReader(scriptFile, Encoding.GetEncoding("iso-8859-9")))
                    {
                        scriptBuilder.AppendLine(streamReader.ReadToEnd());
                    }
                }
                    );
                cfg.AddAuxiliaryDatabaseObject(new SimpleAuxiliaryDatabaseObject(scriptBuilder.ToString(), null));
            };

            Action <IEnumerable <string> > actCodeMappings =
                assemblyFileNames =>
            {
                var modelMapper = new ModelMapper();
                assemblyFileNames.ToList().ForEach(
                    assebmlyFile => modelMapper.AddMappings(Assembly.Load(assebmlyFile).GetExportedTypes()));

                var mp = modelMapper.CompileMappingForAllExplicitlyAddedEntities();
                // For Duplicate mapping
                mp.autoimport = false;
                cfg.AddDeserializedMapping(mp, null);
            };

            Action <IEnumerable <string> > actXmlMappings = assemblyFileNames => assemblyFileNames.ToList().ForEach(
                assebmlyFile => cfg.AddAssembly(assebmlyFile));

            if (_databaseConfiguration.AllowInstall)
            {
                funcCreateInitialScripts(_databaseConfiguration.GetScriptFiles());
            }

            var codeMappings = _databaseConfiguration.GetMappings(MappingType.Code);

            if (codeMappings.Any())
            {
                actCodeMappings(codeMappings);
            }

            var xmlMappings = _databaseConfiguration.GetMappings(MappingType.Xml);
            if (xmlMappings.Any())
            {
                actXmlMappings(xmlMappings);
            }

            SchemaMetadataUpdater.QuoteTableAndColumns(cfg);

            if (_databaseConfiguration.AllowInstall)
            {
                new SchemaExport(cfg).SetOutputFile(_databaseConfiguration.ScriptFilePath).Create(false, true);
            }

            Configured = true;
        }
コード例 #11
0
        public static void Configuration(IAppBuilder app)
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            ModelBinders.Binders.Add(typeof(BinaryFile), new BinaryFileModelBinder());

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

            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().InstancePerLifetimeScope();


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

            var fileProviderInterfaceName = typeof(IFileProvider).FullName;

            foreach (var type in Assembly.GetAssembly(typeof(Startup)).GetTypes())
            {
                var inter = type.GetInterface(fileProviderInterfaceName);
                if (inter != null)
                {
                    builder.RegisterType(type).As <IFileProvider>();
                }
            }

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

            NHibernate.Cfg.Environment.BytecodeProvider =
                new AutofacBytecodeProvider(container, new DefaultProxyFactoryFactory(), new DefaultCollectionTypeFactory());
            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()
            });
        }
コード例 #12
0
 public void Finished(Configuration cfg)
 {
     SchemaMetadataUpdater.QuoteTableAndColumns(cfg);
 }
コード例 #13
0
ファイル: Startup.cs プロジェクト: danil99152/NoteApp
        public static void Configuration(IAppBuilder app)
        {
            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);

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

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

            var assembly = Assembly.GetAssembly(typeof(User));
            var builder  = new ContainerBuilder();

            foreach (var type in assembly.GetTypes())
            {
                var attr = (ListenerAttribute)type.GetCustomAttribute(typeof(ListenerAttribute));
                if (attr != null)
                {
                    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);
                ISessionFactory session = conf.BuildSessionFactory();
                InitialData(session);
                return(session);
            }).As <ISessionFactory>().SingleInstance();
            builder.Register(x => x.Resolve <ISessionFactory>().OpenSession())
            .As <ISession>()
            .InstancePerRequest();
            builder.RegisterControllers(Assembly.GetAssembly(typeof(BaseController)));
            builder.RegisterModule(new AutofacWebTypesModule());
            foreach (var type in assembly.GetTypes())
            {
                var attr = type.GetCustomAttribute(typeof(RepositoryAttribute));
                if (attr != null)
                {
                    builder.RegisterType(type);
                }
            }
            var container = builder.Build();

            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
            app.UseAutofacMiddleware(container);

            app.CreatePerOwinContext(() =>
                                     new UserManager(new IdentityStore(DependencyResolver.Current.GetServices <ISession>().FirstOrDefault())));
            app.CreatePerOwinContext(() =>
                                     new RoleManager(new RoleStore(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/Signin"),
                Provider           = new CookieAuthenticationProvider()
            });
        }
コード例 #14
0
ファイル: PersistenceFacility.cs プロジェクト: adst2016/elite
 protected virtual void ConfigurePersistence(NHibernate.Cfg.Configuration config)
 {
     SchemaMetadataUpdater.QuoteTableAndColumns(config);
 }
コード例 #15
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();
                }
            }
        }
コード例 #16
0
        /// <summary>
        ///     Execute the schema updates
        /// </summary>
        /// <param name="scriptAction">The action to write the each schema line.</param>
        /// <param name="doUpdate">Commit the script to DB</param>
        public void Execute(Action <string> scriptAction, bool doUpdate)
        {
            log.Info("Running hbm2ddl schema update");

            var autoKeyWordsImport = PropertiesHelper.GetString(Environment.Hbm2ddlKeyWords, configuration.Properties, "not-defined");

            autoKeyWordsImport = autoKeyWordsImport.ToLowerInvariant();
            if (autoKeyWordsImport == Hbm2DDLKeyWords.AutoQuote)
            {
                SchemaMetadataUpdater.QuoteTableAndColumns(configuration);
            }

            IDbCommand stmt = null;

            exceptions.Clear();

            try
            {
                DatabaseMetadata meta;
                try
                {
                    log.Info("fetching database metadata");
                    connectionHelper.Prepare();
                    var connection = connectionHelper.Connection;
                    meta = new DatabaseMetadata(connection, dialect);
                    stmt = connection.CreateCommand();
                }
                catch (Exception sqlException)
                {
                    exceptions.Add(sqlException);
                    log.Error("could not get database metadata", sqlException);
                    throw;
                }

                log.Info("updating schema");

                var updateSQL = configuration.GenerateSchemaUpdateScript(dialect, meta);

                var dialectScopes = new List <string>
                {
                    typeof(MsSql2005Dialect).FullName,
                    typeof(MsSql2008Dialect).FullName,
                    typeof(MsSql2012Dialect).FullName,
                };

                for (var j = 0; j < updateSQL.Length; j++)
                {
                    var sql = updateSQL[j];

                    if (dialectScopes.Contains(dialect.GetType().FullName))
                    {
                        sql = sql.Replace("primary key (Id)", "primary key nonclustered (Id)");
                        sql = sql.Replace("create index TimeoutEntity_EndpointIdx on TimeoutEntity (Time, Endpoint)", "create clustered index TimeoutEntity_EndpointIdx on TimeoutEntity (Endpoint, Time)");
                    }

                    var formatted = formatter.Format(sql);

                    try
                    {
                        if (scriptAction != null)
                        {
                            scriptAction(formatted);
                        }
                        if (doUpdate)
                        {
                            log.Debug(sql);
                            stmt.CommandText = sql;
                            stmt.ExecuteNonQuery();
                        }
                    }
                    catch (Exception e)
                    {
                        exceptions.Add(e);
                        log.Error("Unsuccessful: " + sql, e);
                    }
                }

                log.Info("schema update complete");
            }
            catch (Exception e)
            {
                exceptions.Add(e);
                log.Error("could not complete schema update", e);
            }
            finally
            {
                try
                {
                    if (stmt != null)
                    {
                        stmt.Dispose();
                    }
                    connectionHelper.Release();
                }
                catch (Exception e)
                {
                    exceptions.Add(e);
                    log.Error("Error closing connection", e);
                }
            }
        }
コード例 #17
0
 protected virtual void ConfigurePersistence(Configuration config)
 {
     config.AppendListeners(ListenerType.PreUpdate, new[] { new AuditEventListener() });
     config.AppendListeners(ListenerType.PreInsert, new[] { new AuditEventListener() });
     SchemaMetadataUpdater.QuoteTableAndColumns(config);
 }
コード例 #18
0
 public virtual void Create()
 {
     CreateEmptyDatabase();
     SchemaMetadataUpdater.QuoteTableAndColumns(DbConfig, Dialect.GetDialect(DbConfig.Properties));
     SessionFactory = DbConfig.BuildSessionFactory();
 }
コード例 #19
0
ファイル: SessionFactoryImpl.cs プロジェクト: PeterJee/vtms
        public SessionFactoryImpl(Configuration cfg, IMapping mapping, Settings settings, EventListeners listeners)
        {
            Init();
            log.Info("building session factory");

            properties          = new Dictionary <string, string>(cfg.Properties);
            interceptor         = cfg.Interceptor;
            this.settings       = settings;
            sqlFunctionRegistry = new SQLFunctionRegistry(settings.Dialect, cfg.SqlFunctions);
            eventListeners      = listeners;
            filters             = new Dictionary <string, FilterDefinition>(cfg.FilterDefinitions);
            if (log.IsDebugEnabled)
            {
                log.Debug("Session factory constructed with filter configurations : " + CollectionPrinter.ToString(filters));
            }

            if (log.IsDebugEnabled)
            {
                log.Debug("instantiating session factory with properties: " + CollectionPrinter.ToString(properties));
            }

            try
            {
                if (settings.IsKeywordsImportEnabled)
                {
                    SchemaMetadataUpdater.Update(this);
                }
                if (settings.IsAutoQuoteEnabled)
                {
                    SchemaMetadataUpdater.QuoteTableAndColumns(cfg);
                }
            }
            catch (NotSupportedException)
            {
                // Ignore if the Dialect does not provide DataBaseSchema
            }

            #region Caches
            settings.CacheProvider.Start(properties);
            #endregion

            #region Generators
            identifierGenerators = new Dictionary <string, IIdentifierGenerator>();
            foreach (PersistentClass model in cfg.ClassMappings)
            {
                if (!model.IsInherited)
                {
                    IIdentifierGenerator generator =
                        model.Identifier.CreateIdentifierGenerator(settings.Dialect, settings.DefaultCatalogName,
                                                                   settings.DefaultSchemaName, (RootClass)model);

                    identifierGenerators[model.EntityName] = generator;
                }
            }
            #endregion

            #region Persisters

            Dictionary <string, ICacheConcurrencyStrategy> caches = new Dictionary <string, ICacheConcurrencyStrategy>();
            entityPersisters        = new Dictionary <string, IEntityPersister>();
            implementorToEntityName = new Dictionary <System.Type, string>();

            Dictionary <string, IClassMetadata> classMeta = new Dictionary <string, IClassMetadata>();

            foreach (PersistentClass model in cfg.ClassMappings)
            {
                model.PrepareTemporaryTables(mapping, settings.Dialect);
                string cacheRegion = model.RootClazz.CacheRegionName;
                ICacheConcurrencyStrategy cache;
                if (!caches.TryGetValue(cacheRegion, out cache))
                {
                    cache =
                        CacheFactory.CreateCache(model.CacheConcurrencyStrategy, cacheRegion, model.IsMutable, settings, properties);
                    if (cache != null)
                    {
                        caches.Add(cacheRegion, cache);
                        allCacheRegions.Add(cache.RegionName, cache.Cache);
                    }
                }
                IEntityPersister cp = PersisterFactory.CreateClassPersister(model, cache, this, mapping);
                entityPersisters[model.EntityName] = cp;
                classMeta[model.EntityName]        = cp.ClassMetadata;

                if (model.HasPocoRepresentation)
                {
                    implementorToEntityName[model.MappedClass] = model.EntityName;
                }
            }
            classMetadata = new UnmodifiableDictionary <string, IClassMetadata>(classMeta);

            Dictionary <string, ISet <string> > tmpEntityToCollectionRoleMap = new Dictionary <string, ISet <string> >();
            collectionPersisters = new Dictionary <string, ICollectionPersister>();
            foreach (Mapping.Collection model in cfg.CollectionMappings)
            {
                ICacheConcurrencyStrategy cache =
                    CacheFactory.CreateCache(model.CacheConcurrencyStrategy, model.CacheRegionName, model.Owner.IsMutable, settings,
                                             properties);
                if (cache != null)
                {
                    allCacheRegions[cache.RegionName] = cache.Cache;
                }
                ICollectionPersister persister = PersisterFactory.CreateCollectionPersister(cfg, model, cache, this);
                collectionPersisters[model.Role] = persister;
                IType indexType = persister.IndexType;
                if (indexType != null && indexType.IsAssociationType && !indexType.IsAnyType)
                {
                    string        entityName = ((IAssociationType)indexType).GetAssociatedEntityName(this);
                    ISet <string> roles;
                    if (!tmpEntityToCollectionRoleMap.TryGetValue(entityName, out roles))
                    {
                        roles = new HashSet <string>();
                        tmpEntityToCollectionRoleMap[entityName] = roles;
                    }
                    roles.Add(persister.Role);
                }
                IType elementType = persister.ElementType;
                if (elementType.IsAssociationType && !elementType.IsAnyType)
                {
                    string        entityName = ((IAssociationType)elementType).GetAssociatedEntityName(this);
                    ISet <string> roles;
                    if (!tmpEntityToCollectionRoleMap.TryGetValue(entityName, out roles))
                    {
                        roles = new HashSet <string>();
                        tmpEntityToCollectionRoleMap[entityName] = roles;
                    }
                    roles.Add(persister.Role);
                }
            }
            Dictionary <string, ICollectionMetadata> tmpcollectionMetadata = new Dictionary <string, ICollectionMetadata>(collectionPersisters.Count);
            foreach (KeyValuePair <string, ICollectionPersister> collectionPersister in collectionPersisters)
            {
                tmpcollectionMetadata.Add(collectionPersister.Key, collectionPersister.Value.CollectionMetadata);
            }
            collectionMetadata = new UnmodifiableDictionary <string, ICollectionMetadata>(tmpcollectionMetadata);
            collectionRolesByEntityParticipant = new UnmodifiableDictionary <string, ISet <string> >(tmpEntityToCollectionRoleMap);
            #endregion

            #region Named Queries
            namedQueries         = new Dictionary <string, NamedQueryDefinition>(cfg.NamedQueries);
            namedSqlQueries      = new Dictionary <string, NamedSQLQueryDefinition>(cfg.NamedSQLQueries);
            sqlResultSetMappings = new Dictionary <string, ResultSetMappingDefinition>(cfg.SqlResultSetMappings);
            #endregion

            imports = new Dictionary <string, string>(cfg.Imports);

            #region after *all* persisters and named queries are registered
            foreach (IEntityPersister persister in entityPersisters.Values)
            {
                persister.PostInstantiate();
            }
            foreach (ICollectionPersister persister in collectionPersisters.Values)
            {
                persister.PostInstantiate();
            }
            #endregion

            #region Serialization info

            name = settings.SessionFactoryName;
            try
            {
                uuid = (string)UuidGenerator.Generate(null, null);
            }
            catch (Exception)
            {
                throw new AssertionFailure("Could not generate UUID");
            }

            SessionFactoryObjectFactory.AddInstance(uuid, name, this, properties);

            #endregion

            log.Debug("Instantiated session factory");

            #region Schema management
            if (settings.IsAutoCreateSchema)
            {
                new SchemaExport(cfg).Create(false, true);
            }

            if (settings.IsAutoUpdateSchema)
            {
                new SchemaUpdate(cfg).Execute(false, true);
            }
            if (settings.IsAutoValidateSchema)
            {
                new SchemaValidator(cfg, settings).Validate();
            }
            if (settings.IsAutoDropSchema)
            {
                schemaExport = new SchemaExport(cfg);
            }
            #endregion

            #region Obtaining TransactionManager
            // not ported yet
            #endregion

            currentSessionContext = BuildCurrentSessionContext();

            if (settings.IsQueryCacheEnabled)
            {
                updateTimestampsCache = new UpdateTimestampsCache(settings, properties);
                queryCache            = settings.QueryCacheFactory.GetQueryCache(null, updateTimestampsCache, settings, properties);
                queryCaches           = new ThreadSafeDictionary <string, IQueryCache>(new Dictionary <string, IQueryCache>());
            }
            else
            {
                updateTimestampsCache = null;
                queryCache            = null;
                queryCaches           = null;
            }

            #region Checking for named queries
            if (settings.IsNamedQueryStartupCheckingEnabled)
            {
                IDictionary <string, HibernateException> errors = CheckNamedQueries();
                if (errors.Count > 0)
                {
                    StringBuilder failingQueries = new StringBuilder("Errors in named queries: ");
                    foreach (KeyValuePair <string, HibernateException> pair in errors)
                    {
                        failingQueries.Append('{').Append(pair.Key).Append('}');
                        log.Error("Error in named query: " + pair.Key, pair.Value);
                    }
                    throw new HibernateException(failingQueries.ToString());
                }
            }
            #endregion

            Statistics.IsStatisticsEnabled = settings.IsStatisticsEnabled;

            // EntityNotFoundDelegate
            IEntityNotFoundDelegate enfd = cfg.EntityNotFoundDelegate;
            if (enfd == null)
            {
                enfd = new DefaultEntityNotFoundDelegate();
            }
            entityNotFoundDelegate = enfd;
        }
コード例 #20
0
        /// <summary>
        /// Execute the schema updates
        /// </summary>
        /// <param name="scriptAction">The action to write the each schema line.</param>
        /// <param name="doUpdate">Commit the script to DB</param>
        public void Execute(Action <string> scriptAction, bool doUpdate)
        {
            log.Info("Running hbm2ddl schema update");

            var autoKeyWordsImport = PropertiesHelper.GetString(Environment.Hbm2ddlKeyWords, configuration.Properties, "not-defined");

            autoKeyWordsImport = autoKeyWordsImport.ToLowerInvariant();
            if (autoKeyWordsImport == Hbm2DDLKeyWords.AutoQuote)
            {
                SchemaMetadataUpdater.QuoteTableAndColumns(configuration);
            }

            IDbCommand stmt = null;

            exceptions.Clear();

            try
            {
                DatabaseMetadata meta;
                try
                {
                    log.Info("fetching database metadata");
                    connectionHelper.Prepare();
                    var connection = connectionHelper.Connection;
                    meta = new DatabaseMetadata(connection, dialect);
                    stmt = connection.CreateCommand();
                }
                catch (Exception sqlException)
                {
                    exceptions.Add(sqlException);
                    log.Error("could not get database metadata", sqlException);
                    throw;
                }

                log.Info("updating schema");

                var updateSQL = configuration.GenerateSchemaUpdateScript(dialect, meta);

                var dialectScopes = new List <string>
                {
                    typeof(MsSql2005Dialect).FullName,
                    typeof(MsSql2008Dialect).FullName,
                    typeof(MsSql2012Dialect).FullName
                };

                var shouldOptimizeTimeoutEntity = timeoutEntityMapping != null;

                foreach (var item in updateSQL)
                {
                    var updateSqlStatement = item;

                    if (dialectScopes.Contains(dialect.GetType().FullName) && shouldOptimizeTimeoutEntity)
                    {
                        var qualifiedTimeoutEntityTableName = timeoutEntityMapping.Table.GetQualifiedName(dialect);

                        if (updateSqlStatement.StartsWith($"create table {qualifiedTimeoutEntityTableName}"))
                        {
                            updateSqlStatement = updateSqlStatement.Replace("primary key (Id)", "primary key nonclustered (Id)");
                        }
                        else if (updateSqlStatement.StartsWith($"create index {TimeoutEntityMap.EndpointIndexName}"))
                        {
                            updateSqlStatement = updateSqlStatement.Replace($"create index {TimeoutEntityMap.EndpointIndexName}", $"create clustered index {TimeoutEntityMap.EndpointIndexName}");
                        }
                    }

                    var formatted = formatter.Format(updateSqlStatement);

                    try
                    {
                        scriptAction?.Invoke(formatted);
                        if (doUpdate)
                        {
                            log.Debug(updateSqlStatement);
                            stmt.CommandText = updateSqlStatement;
                            stmt.ExecuteNonQuery();
                        }
                    }
                    catch (Exception e)
                    {
                        exceptions.Add(e);
                        log.Error("Unsuccessful: " + updateSqlStatement, e);
                    }
                }

                log.Info("schema update complete");
            }
            catch (Exception e)
            {
                exceptions.Add(e);
                log.Error("could not complete schema update", e);
            }
            finally
            {
                try
                {
                    stmt?.Dispose();
                    connectionHelper.Release();
                }
                catch (Exception e)
                {
                    exceptions.Add(e);
                    log.Error("Error closing connection", e);
                }
            }
        }