示例#1
0
        private static ISessionFactory ConfigureDatabase()
        {
            IPersistenceConfigurer persistenceConfigurer = MsSqlConfiguration.MsSql2008.ConnectionString(c => c.FromConnectionStringWithKey("DefaultConnection"));

            return(Database.CreateConfiguration(persistenceConfigurer, c =>
            {
                var u = new SchemaUpdate(c);
                u.Execute(true, true);
            }));
        }
示例#2
0
        public static void Configuration(IAppBuilder app)
        {
            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);

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

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


            var containerBuilder = new ContainerBuilder();

            containerBuilder.Register(x => {
                var cfg = Fluently.Configure()
                          .Database(MsSqlConfiguration.MsSql2012
                                    .ConnectionString(connectionString.ConnectionString)
                                    .Dialect <MsSql2012Dialect>())
                          .Mappings(m => m.FluentMappings.AddFromAssemblyOf <Person>())
                          //.ExposeConfiguration(m =>{
                          //    SchemaMetadataUpdater.QuoteTableAndColumns(m); //не совсеми БД это хорошо, лучше использовать не совпадающие ключевые слова с названиями колонок в БД
                          //})
                          .CurrentSessionContext("call");
                var conf         = cfg.BuildConfiguration();
                var schemeExport = new SchemaUpdate(conf);
                schemeExport.Execute(true, true);
                return(cfg.BuildSessionFactory());
            }).As <ISessionFactory>().SingleInstance();
            containerBuilder
            .Register(x => x.Resolve <ISessionFactory>().OpenSession())
            .As <ISession>()
            .InstancePerRequest();

            containerBuilder.RegisterControllers(Assembly.GetAssembly(typeof(HomeController)));
            containerBuilder.RegisterModule(new AutofacWebTypesModule());
            // регистрация репозитория
            var types = typeof(Person).Assembly.GetTypes();

            foreach (var type in types)
            {
                var repositoriesAtribut = type.GetCustomAttribute <RepositoryAttribute>();
                if (repositoriesAtribut == null)
                {
                    continue;
                }
                containerBuilder.RegisterType(type);
            }

            var container = containerBuilder.Build();

            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
            app.UseAutofacMiddleware(container);
        }
 public static void UpdateSchema(global::NHibernate.Cfg.Configuration configuration)
 {
     using (new WriteLockDisposable(SchemaValidationLocker))
     {
         using (DisposableTimer.TraceDuration <ProviderBootstrapper>("Begin db schema update", "End db schema update"))
         {
             var schema = new SchemaUpdate(configuration);
             schema.Execute(x => LogHelper.TraceIfEnabled <ProviderBootstrapper>("NHibernate generated the following update Sql: \n" + x), true);
         }
     }
 }
示例#4
0
        public static void CreateDatabase()
        {
            var configuration = Fluently.Configure()
                                .Database(MsSqlConfiguration.MsSql2008.ConnectionString(connectionString).ShowSql)
                                .Mappings(m => m.FluentMappings.AddFromAssemblyOf <CustomerMap>())
                                .BuildConfiguration();

            var exporter = new SchemaUpdate(configuration);

            exporter.Execute(true, true);
        }
示例#5
0
        public static void UpdateSchema()
        {
            string pathDatabase = Path.GetDirectoryName(RegistryHelper.CheckDBFile());
            string pathName     = Path.Combine(pathDatabase, @"update.database");

            Utilities.CreateIfMissing(pathDatabase);
            Utilities.CreateIfMissing(pathName);
            var update = new SchemaUpdate(_configuration);

            update.Execute(false, true);
        }
        private static void UpdateDatabaseSchema(NHibernate.Cfg.Configuration cfg, string connectionString)
        {
            var updateCode   = new System.Text.StringBuilder();
            var schemaUpdate = new SchemaUpdate(cfg);

            schemaUpdate.Execute(row =>
            {
                updateCode.AppendLine(row);
                updateCode.AppendLine();
            }, true);
        }
示例#7
0
        public static void Migrate(IMigrationLogger MigrationLogger = null, bool update_database = false)
        {
            SchemaUpdate schemaUpdate = new SchemaUpdate(_configuration);

            if (MigrationLogger == null)
            {
                schemaUpdate.Execute(false, update_database);
            }

            Migrator.Migrate(schemaUpdate, MigrationLogger, update_database);
        }
示例#8
0
 protected NHibernateFixture()
 {
     _configuration = new Lazy <Configuration>(() => {
         var config = new Configuration();
         Configure(config);
         var schemaExport = new SchemaUpdate(config);
         schemaExport.Execute(true, true);
         return(config);
     });
     _sessionFactory = new Lazy <ISessionFactory>(() => _configuration.Value.BuildSessionFactory());
 }
示例#9
0
        public void SchemaUpdateAddsIndexesThatWerentPresentYet()
        {
            Configuration cfg = TestConfigurationHelper.GetDefaultConfiguration();

            cfg.AddResource("NHibernate.Test.NHSpecificTest.NH1593.TestIndex.hbm.xml", GetType().Assembly);
            var su = new SchemaUpdate(cfg);
            var sb = new StringBuilder(500);

            su.Execute(x => sb.AppendLine(x), false);
            Assert.That(sb.ToString(), Is.StringContaining("create index test_index_name on TestIndex (Name)"));
        }
示例#10
0
        public string Update()
        {
            var schemaExport = new SchemaUpdate(configuration);

            var stringBuilder = new StringBuilder();

            schemaExport.Execute(x => stringBuilder.Append(x), false);

            var script = stringBuilder.ToString();

            return(string.IsNullOrWhiteSpace(script) ? null : script);
        }
示例#11
0
        public static void Configuration(IAppBuilder app)
        {
            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            var connectionSttring = ConfigurationManager.ConnectionStrings["MSSQL"];

            if (connectionSttring == null)
            {
                throw new Exception("not found");
            }
            var builder = new ContainerBuilder();

            builder.Register(x =>
            {
                var cfg = Fluently.Configure()
                          .Database(MsSqlConfiguration.MsSql2012
                                    .ConnectionString(connectionSttring.ConnectionString))
                          .Mappings(m => m.FluentMappings.AddFromAssemblyOf <User>())
                          .CurrentSessionContext("call");
                var schemaExport = new SchemaUpdate(cfg.BuildConfiguration());
                schemaExport.Execute(true, true);
                return(cfg.BuildSessionFactory());
            }).As <ISessionFactory>().SingleInstance();
            builder.Register(x => x.Resolve <ISessionFactory>().OpenSession())
            .As <ISession>()
            .InstancePerRequest();
            builder.RegisterControllers(Assembly.GetAssembly(typeof(AccountController)));
            builder.RegisterModule(new AutofacWebTypesModule());
            var assembly = Assembly.GetAssembly(typeof(User));

            foreach (var type in assembly.GetTypes())
            {
                var at = type.GetCustomAttribute(typeof(RepositoryAttribute));
                if (at != 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 <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 Stream UpdateSchema()
        {
            var output  = new MemoryStream();
            var session = Session;

            if (session != null)
            {
                var update = new SchemaUpdate(CreateSessionFactory(DefaultPrefix).Item2);
                update.Execute(sql => output = new MemoryStream(Encoding.UTF8.GetBytes(sql)), false);
            }
            return(output);
        }
示例#13
0
        private static void BuildSchema(Configuration config)
        {
            SchemaMetadataUpdater.QuoteTableAndColumns(config);

            var update = new SchemaUpdate(config);

            update.Execute(false, true);

            // TODO Wait for FluentMigrator.NHibernate to become more stable
            // (or switch back to internal migrations entirely)
            //RunMigrations ();
        }
示例#14
0
 private void UpdateDatabase()
 {
     foreach (string name in SessionManager.SessionFactoryNames)
     {
         var a = new SchemaUpdate(SessionManager.GetSessionWrapperFactory(name).Configuration);
         a.Execute(true, true);
         foreach (Exception exception in a.Exceptions)
         {
             LogManager.GetLogger(GetType()).Error(exception.Message, exception);
         }
     }
 }
示例#15
0
        public static void ApplySchemaChanges()
        {
            Configuration cfg = GetConfiguration();

            SchemaMetadataUpdater.QuoteTableAndColumns(cfg);
            //NHibernate.Tool.hbm2ddl.SchemaExport schema = new NHibernate.Tool.hbm2ddl.SchemaExport(cfg);

            //schema.Create(false, true);
            var update = new SchemaUpdate(cfg);

            update.Execute(true, true);
        }
示例#16
0
        public ISession OpenSession()
        {
            ISession session = _sessionFactory.OpenSession();

            //var export = new SchemaExport(_configuration);
            //export.Execute(true, true, false, session.Connection, null);

            var export2 = new SchemaUpdate(_configuration);

            export2.Execute(true, true);

            return(session);
        }
示例#17
0
 private static ISessionFactory BuildSessionFactory(bool isUpdateSchema = false)
 {
     if (isUpdateSchema)
     {
         var update = new SchemaUpdate(Configuration);
         update.Execute(false, true);
         return(Configuration.BuildSessionFactory());
     }
     else
     {
         return(Configuration.BuildSessionFactory());
     }
 }
示例#18
0
        internal static void Configuration(Configuration cfg)
        {
            cfg.SetProperty(NHibernate.Cfg.Environment.CommandTimeout, System.TimeSpan.FromMinutes(15).TotalSeconds.ToString());

            if (!ResolveConfiguracoesConexao.GerenciarSchema)
            {
                return;
            }

            var schemaUpdate = new SchemaUpdate(cfg);

            schemaUpdate.Execute(true, true);
        }
示例#19
0
        public void SchemaExport_Update_CreatesUpdateScript()
        {
            Configuration configuration = GetConfiguration();
            SchemaUpdate  update        = new SchemaUpdate(configuration);
            TextWriter    tw            = new StringWriter();

            update.Execute(tw.WriteLine, false);

            string s = tw.ToString();

            Assert.IsTrue(s.Contains("create table Home_Update"));
            Assert.IsTrue(s.Contains("create table Home_All"));
        }
        public void SchemaExport_Update_CreatesUpdateScript()
        {
            Configuration configuration = GetConfiguration();
            SchemaUpdate  update        = new SchemaUpdate(configuration);
            TextWriter    tw            = new StringWriter();

            update.Execute(tw.WriteLine, false);

            string s = tw.ToString();

            Assert.That(s, Does.Match("create ((column|row) )?table Home_Update"));
            Assert.That(s, Does.Match("create ((column|row) )?table Home_All"));
        }
示例#21
0
        static NHibernateFactory()
        {
            Configuration configuration = new Configuration();

            configuration.Configure();
            configuration.AddAssembly(typeof(Project).Assembly);

            SchemaUpdate exporter = new SchemaUpdate(configuration);

            exporter.Execute(true, true);

            SessionFactory = configuration.BuildSessionFactory();
        }
示例#22
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers().AddNewtonsoftJson(options =>
            {
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            });
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "NH.Example.Web", Version = "v1"
                });
            });

            services.AddSingleton <ISessionFactory>(serviceProvider =>
            {
                var configuration = new Configuration();
                configuration.DataBaseIntegration(db =>
                {
                    db.ConnectionString = "Data Source=NHExample.db";
                    db.Driver <SQLite20Driver>();
                    db.Dialect <SQLiteDialect>();
                    db.LogSqlInConsole = true;
                    db.LogFormattedSql = true;
                });

                var modelMapper = new ModelMapper();
                modelMapper.AddMapping <UserMapping>();
                modelMapper.AddMapping <RoleMapping>();
                modelMapper.AddMapping <PhoneMapping>();

                var mappings = modelMapper.CompileMappingForAllExplicitlyAddedEntities();

                configuration.AddMapping(mappings);

                var sessionFactory = configuration.BuildSessionFactory();

                var schemaUpdate = new SchemaUpdate(configuration);
                schemaUpdate.Execute(true, true);

                return(sessionFactory);
            });

            services.AddScoped <ISession>(serviceProvider =>
            {
                var sessionFactory = serviceProvider.GetService <ISessionFactory>();
                var session        = sessionFactory.OpenSession();

                return(session);
            });
        }
示例#23
0
        public static void update_schema(Configuration cfg)
        {
            SchemaUpdate  s  = new SchemaUpdate(cfg);
            StringBuilder sb = new StringBuilder();

            s.Execute(x => sb.Append(x), false);
            string updateScriptFileName = Path.Combine(PATH_TO_SCRIPTS, Path.Combine("Up", NAME_OF_UPDATE_SCRIPT));

            if (File.Exists(updateScriptFileName))
            {
                File.Delete(updateScriptFileName);
            }
            File.WriteAllText(updateScriptFileName, sb.ToString());
        }
示例#24
0
        public static void ValidateSchema(NHibernate.Cfg.Configuration config)
        {
            var validator = new SchemaValidator(config);

            try
            {
                validator.Validate();
            }
            catch (HibernateException)
            {
                var update = new SchemaUpdate(config);
                update.Execute(false, true);
            }
        }
示例#25
0
        private ISessionFactory ConfigureDatabase()
        {
            IPersistenceConfigurer persistenceConfigurer = MsSqlConfiguration.MsSql2008.ConnectionString(c => c.FromConnectionStringWithKey("DefaultConnection"));

            return(Database.CreateConfiguration(persistenceConfigurer, c =>
            {
                var se = new SchemaExport(c);
                se.Drop(false, true);
                se.Execute(false, true, true);

                var su = new SchemaUpdate(c);
                su.Execute(false, true);
            }));
        }
示例#26
0
        public void ConfigureHibernateMapping()
        {
            NHibernate.Cfg.Configuration hibernateConfig = (UnitOfWork.UnitOfWorkFactory as NHibernateUnitOfWorkFactory).Configuration;
            var mapper = new ModelMapper();

            mapper.AddMappings(typeof(ProductModelMap).Assembly.GetExportedTypes());
            mapper.AddMappings(typeof(DistributorModelMap).Assembly.GetExportedTypes());
            mapper.AddMappings(typeof(QrCodeModelMap).Assembly.GetExportedTypes());

            hibernateConfig.AddDeserializedMapping(mapper.CompileMappingForAllExplicitlyAddedEntities(), "FertilizerPlantScheme");
            SchemaUpdate schema = new SchemaUpdate(hibernateConfig);

            schema.Execute(true, true);
        }
        protected override void Process(global::NHibernate.Cfg.Configuration configuration)
        {
            SchemaUpdate schemaUpdate = new SchemaUpdate(configuration);
            bool         isUpdated    = false;

            schemaUpdate.Execute(script => { Console.WriteLine(script); isUpdated = true; }, true);

            if (!isUpdated)
            {
                return;
            }

            InsertInitialData(configuration);
        }
        private void update_the_schema(Configuration cfg)
        {
            var s  = new SchemaUpdate(cfg);
            var sb = new StringBuilder();

            s.Execute(x => sb.Append(x), false);
            var updateScriptFileName = Path.Combine(path_to_sql_scripts_up_folder, name_of_script_to_create);

            if (File.Exists(updateScriptFileName))
            {
                File.Delete(updateScriptFileName);
            }
            File.WriteAllText(updateScriptFileName, sb.ToString());
        }
        public static ISessionFactory CreateSessionFactory()
        {
            var config = GetSqliteConfig();

            var sessionFactory = config.BuildSessionFactory();

            // Execute update
            // TODO: Make this optional - check for a flag or something
            var schemaUpdate = new SchemaUpdate(config);

            schemaUpdate.Execute(false, true);

            return(sessionFactory);
        }
示例#30
0
        public static Configuration UpdateSchema(this Configuration cfg, bool export = false)
        {
            if (export)
            {
                var fileName     = "c:\\usr\\create_schema.sql";
                var schemaExport = new SchemaExport(cfg);
                schemaExport.SetOutputFile(fileName);
                schemaExport.Create(true, true);
                return(cfg);
            }
            var update = new SchemaUpdate(cfg);

            update.Execute(LogAutoMigration, true);
            return(cfg);
        }
        public void Install(string identity, Configure config)
        {
            if (RunInstaller)
            {
                var schemaUpdate = new SchemaUpdate(Configuration);
                var sb = new StringBuilder();
                schemaUpdate.Execute(s => sb.AppendLine(s), true);

                if (!schemaUpdate.Exceptions.Any())
                {
                    return;
                }

                var aggregate = new AggregateException(schemaUpdate.Exceptions);

                var errorMessage = @"Schema update failed.
The following exception(s) were thrown:
{0}

TSql Script:
{1}";
                throw new Exception(String.Format(errorMessage, aggregate, sb));
            }
        }