Пример #1
0
        /// <summary>
        ///     The create database.
        /// </summary>
        public void CreateSchema()
        {
            if (Configuration == null)
            {
                return;
            }

            var export = new SchemaExport(Configuration);

#if DEBUG
            CreateLogDir();

            using (var file = new FileStream(
                       @"C:\TestOutput\NHibernate\CreateSchema.sql",
                       FileMode.Create,
                       FileAccess.Write))
            {
                using (var sw = new StreamWriter(file))
                {
                    export.Execute(true, true, false, CurrentSession?.Connection, sw);
                }
            }
#else
            export.Execute(true, true, false, this.CurrentSession?.Connection, null);
#endif
        }
        public void BuildSchema(DbConnection connection = null)
        {
            var path = Path.Combine(
                AppDomain.CurrentDomain.BaseDirectory,
                $@"schema{connection?.DataSource}.sql");

            // this NHibernate tool takes a configuration (with mapping info in)
            // and exports a database schema from it
            var schemaExport = new SchemaExport(this._configuration);

            schemaExport.SetOutputFile(path);
            schemaExport.Create(
                useStdOut: true,
                execute: false);

            if (connection != null)
            {
                schemaExport.Execute(
                    useStdOut: false,
                    execute: true,
                    justDrop: false,
                    connection: connection,
                    exportOutput: null);
            }
            else
            {
                schemaExport.Execute(
                    useStdOut: false,
                    execute: true,
                    justDrop: false);
            }
        }
Пример #3
0
        public string Create()
        {
            var schemaExport = new SchemaExport(configuration);

            databaseProvider.CreateIfNotExists();

            var stringBuilder = new StringBuilder();

            schemaExport.Create(x => stringBuilder.Append(x), false);
            var statement = stringBuilder.ToString();

            statement = string.IsNullOrWhiteSpace(statement) ? null : statement;

            if (!databaseProvider.Exists())
            {
                databaseProvider.Create();
                schemaExport.Execute(false, true, false);
            }
            else
            {
                try
                {
                    new SchemaValidator(configuration).Validate();
                }
                catch
                {
                    schemaExport.Execute(false, true, false);
                }
            }

            return(statement);
        }
Пример #4
0
        // Drop old database if any, create new schema
        private void RecreateSchema(NHibernate.Cfg.Configuration cfg, string connectionStringName)
        {
                        #if !DEBUG
            return;
                        #endif

            bool writeOutput = false;

            RunSql(connectionStringName, connection => {
                // NH schema export does not correctly drop all constraints
                // SQL from http://stackoverflow.com/a/26348027
                new SqlCommand(@"
					exec sp_MSforeachtable ""declare @name nvarchar(max); set @name = parsename('?', 1); exec sp_MSdropconstraints @name"";
				"                , connection).ExecuteNonQuery();

                var export = new SchemaExport(cfg);
                if (writeOutput)
                {
                    using (var writer = new StreamWriter(@"C:\Temp\vdb.sql")) {
                        export.Execute(false, true, false, connection, writer);
                    }
                }
                else
                {
                    export.Execute(false, true, false, connection, null);
                }
            });
        }
Пример #5
0
        private static void ExportSchema(Configuration configuration)
        {
            var schemaExport = new SchemaExport(configuration);

            schemaExport.SetOutputFile(SchemaOutputPath);
            schemaExport.Execute(false, false, false);
        }
Пример #6
0
        /// <summary>
        /// Only development phase usage do not use production code
        /// </summary>
        /// <param name="factoryKey"></param>
        private void BuildSchemaByDroping(string factoryKey)
        {
            var filePath = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, factoryKey + ".NHibernate.config")?.FirstOrDefault();

            if (string.IsNullOrEmpty(filePath))
            {
                Console.WriteLine(factoryKey + ".NHibernate.config file not found for BuildSchemaDroping!");
                return;
            }
            var nHibernateMappingAssembly = GetAssemblyName(filePath);

            var cfg = new global::NHibernate.Cfg.Configuration();

            cfg.Configure(filePath);
            FluentConfiguration a = Fluently.Configure(cfg).Mappings(m =>
            {
                var assembly = Assembly.Load(nHibernateMappingAssembly);
                m.HbmMappings.AddFromAssembly(assembly);
                m.FluentMappings.AddFromAssembly(assembly).Conventions.AddAssembly(assembly);
            });

            SchemaExport schema = new SchemaExport(a.BuildConfiguration());

            if (schema != null)
            {
                schema.Execute(true, true, false);
            }
        }
Пример #7
0
        public static void CreateDatabase()
        {
            Configuration config   = CreateNHibernateConfiguration().BuildConfiguration();
            var           exporter = new SchemaExport(config);

            exporter.Execute(true, true, false);
        }
Пример #8
0
        public void TestCleanup()
        {
            //Reset database data after every run
            SchemaExport exp = new SchemaExport(_cfg);

            exp.Execute(true, true, false);
        }
Пример #9
0
        public static IAuthenticationService AuthenticationService()
        {
            if (configured == false)
            {
                string applicationName = "sops";

                IPersistenceConfigurer persistenceConfigurer =
                    MsSqlConfiguration.MsSql2008.ConnectionString(c => c.FromConnectionStringWithKey("DefaultConnection"));

                service = new FormsAuthenticationService(applicationName,
                                                         new BCryptStrategy(),
                                                         new ConsoleLogger(),
                                                         persistenceConfigurer,
                                                         configuration =>
                {
                    var se = new SchemaExport(configuration);
                    se.Drop(true, true);
                    se.Execute(true, true, true);

                    var su = new SchemaUpdate(configuration);
                    su.Execute(true, true);
                });
                service.Configure();
                configured = true;
            }

            return(service);
        }
Пример #10
0
        public void Script()
        {
            var automapper = new AutoMapper
            {
                EntityBaseType = typeof(AutoMapperTestEntityBase)
            };

            automapper.MapAssemblyOf <SchemaTests>();

            var compiled = automapper.Complete();

            var configuration = new Configuration();

            configuration.DataBaseIntegration(db =>
            {
                db.Dialect <SQLiteDialect>();
                db.ConnectionString = "Data Source=:memory:;Version=3;New=True";
            });

            configuration.AddDeserializedMapping(compiled.First(), string.Empty);

            var export = new SchemaExport(configuration);

            export.Execute(true, false, false);
        }
Пример #11
0
        public void TestInitizlize()
        {
            var config = new Configuration();

            config.DataBaseIntegration(
                db =>
            {
                db.Dialect <SQLiteDialect>();
                db.Driver <SQLite20Driver>();
                db.ConnectionString = ConnectionString;
                db.LogSqlInConsole  = false;
                db.LogFormattedSql  = true;
                db.AutoCommentSql   = true;
            }
                );
            config.SetProperty(Environment.CurrentSessionContextClass, "thread_static");

            var mapper = new ModelMapper();

            mapper.WithMappings(config);

            ContextSessionFactory = config.BuildSessionFactory();

            ContextSession = ContextSessionFactory.OpenSession();

            var schemaExport = new SchemaExport(config);

            schemaExport.Execute(false, true, false, ContextSession.Connection, TextWriter.Null);

            Context();
            BecauseOf();
        }
Пример #12
0
        void SetupQueryIntegrationTest(ISession session)
        {
            using (var tran = session.BeginTransaction())
            {
                var exporter = new SchemaExport(config);
                exporter.Execute(false, true, false, session.Connection, null);
                tran.Commit();
            }

            using (var tran = session.BeginTransaction())
            {
                var pet = new Pet
                {
                    Identity = 1,
                    Owner    = new Person {
                        Identity = 1, Name = "Jane Doe"
                    }
                };
                session.Save(pet);
                session.Save(pet.Owner);
                session.Flush();

                tran.Commit();
            }

            session.Clear();
        }
        public static ISessionFactory CreateSessionGeral()
        {
            var _session = Fluently.Configure()
                           .Database(MySQLConfiguration.Standard.ConnectionString(connectionGeral))
                           .Mappings(m => m.FluentMappings
                                     .Add <UsuarioMap>()
                                     .Add <EnderecoMap>()
                                     .Add <EstacaoService>()
                                     .Add <VeiculoMap>()
                                     .Add <EmpresaMap>()
                                     );
            var session = _session.BuildConfiguration();

            if (!initGeral)
            {
                var schemaExport = new SchemaExport(session);
                schemaExport.Execute(false, true, true);
                schemaExport.Drop(false, true);
                schemaExport.Create(false, true);

                var updater = new SchemaUpdate(session);
                updater.Execute(true, true);
                var ex = updater.Exceptions;

                initGeral = true;
            }

            return(_session.BuildSessionFactory());
        }
Пример #14
0
        public void Throwing_IsIntercepted_InMediumTrust()
        {
            IEngine engine = new ContentEngine(new MediumTrustServiceContainer(), new EventBroker(), new ContainerConfigurer());

            engine.Initialize();

            var schemaCreator = new SchemaExport(engine.Resolve <IConfigurationBuilder>().BuildConfiguration());
            var conn          = engine.Resolve <ISessionProvider>().OpenSession.Session.Connection;

            schemaCreator.Execute(false, true, false, conn, null);

            engine.SecurityManager.Enabled = false;

            ContentItem root = new ThrowableItem();

            root.Name = "root_mediumtrust";

            ContentItem item = new ThrowableItem();

            item.Name = "bin's destiny";
            item.AddTo(root);

            engine.Persister.Save(root);
            engine.Resolve <IHost>().DefaultSite.RootItemID  = root.ID;
            engine.Resolve <IHost>().DefaultSite.StartPageID = root.ID;

            engine.Persister.Delete(item);

            Assert.That(root.Children.Count, Is.EqualTo(1));
            Assert.That(root.Children[0], Is.TypeOf(typeof(TrashContainerItem)));
            Assert.That(root.Children[0].Children[0], Is.EqualTo(item));
        }
Пример #15
0
        protected static void ResetDB()
        {
            Configuration config       = GetNHibernateConfig();
            var           schemaExport = new SchemaExport(config);

            schemaExport.Execute(true, true, false);
        }
        public static ISessionFactory CreateSessionPacote()
        {
            var _session = Fluently.Configure()
                           .Database(MySQLConfiguration.Standard.ConnectionString(connectionPacote))
                           .Mappings(m => m.FluentMappings
                                     .Add <PacoteMap>()
                                     .Add <RotaMap>()
                                     .Add <LocalizacaoMap>()
                                     );
            var session = _session.BuildConfiguration();

            if (!initPacote)
            {
                var schemaExport = new SchemaExport(session);
                schemaExport.Execute(false, true, true);
                schemaExport.Drop(false, true);
                schemaExport.Create(false, true);

                var updater = new SchemaUpdate(session);
                updater.Execute(true, true);
                var ex = updater.Exceptions;

                initPacote = true;
            }

            return(_session.BuildSessionFactory());
        }
Пример #17
0
        private static void BuildSchema(NHibernate.Cfg.Configuration config)
        {
            var export = new SchemaExport(config);

            export.SetOutputFile(@"c:\output.sql");
            export.Execute(true, false, false);
        }
Пример #18
0
        public void CanCreate_FromScratch()
        {
            SchemaExport schemaCreator = new SchemaExport(CreateConfiguration(xml1));

            schemaCreator.Execute((s) =>
            {
                Debug.WriteLine(" === Create === ");
                Debug.WriteLine(s);
            }, true, false);

            schemaCreator.Execute((s) =>
            {
                Debug.WriteLine(" === Drop === ");
                Debug.WriteLine(s);
            }, true, true);
        }
Пример #19
0
        public void ShouldExportSchema()
        {
            schemaExport.SetOutputFile("../../../sqloutput/ddl.sql");
            schemaExport.Execute(false, true, false);

            dropDatabase = true;
        }
Пример #20
0
        public static bool RebuildSchema(string dud = null)
        {
            var configuration = new Configuration();

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

            using (var connection = new SQLiteConnection(configuration.GetProperty("connection.connection_string")))
            {
                connection.Open();
                try
                {
                    var export = new SchemaExport(configuration);
                    export.Execute(false, true, false, connection, null);
                    WriteBaselineData();
                }
                catch (Exception ex)
                {
                    _Logger.Error("Unable to rebuild the database schema", ex);
                    throw;
                }
                finally
                {
                    connection.Close();
                }
            }

            return(false);
        }
Пример #21
0
        private static Task BugAsync(Configuration cfg, CancellationToken cancellationToken = default(CancellationToken))
        {
            try
            {
                var su = new SchemaExport(cfg);
                var sb = new StringBuilder(500);
                su.Execute(x => sb.AppendLine(x), false, false);
                string script = sb.ToString();


                if (Dialect.Dialect.GetDialect(cfg.Properties).SupportsIfExistsBeforeTableName)
                {
                    Assert.That(script, Does.Match("drop table if exists nhibernate.dbo.Aclass"));
                }
                else
                {
                    Assert.That(script, Does.Match("drop table nhibernate.dbo.Aclass"));
                }

                Assert.That(script, Does.Match("create table nhibernate.dbo.Aclass"));
                return(Task.CompletedTask);
            }
            catch (System.Exception ex)
            {
                return(Task.FromException <object>(ex));
            }
        }
Пример #22
0
        private void EnsureMasterDatabaseExistence()
        {
            if (configuration == null)
            {
                lock (masterDatabaseSync)
                {
                    if (configuration == null)
                    {
                        string connectionString = BuildConnectionString(masterDatabaseFileName);

                        if (File.Exists(masterDatabaseFileName))
                        {
                            File.Delete(masterDatabaseFileName);
                        }

                        using (var engine = new SqlCeEngine(connectionString))
                        {
                            engine.CreateDatabase();
                        }

                        configuration  = BuildConfigurationInternal(masterDatabaseFileName);
                        sessionFactory = configuration.BuildSessionFactory();

                        using (var masterConnection = new SqlCeConnection(connectionString))
                        {
                            masterConnection.Open();

                            SchemaExport schemaExport = new SchemaExport(configuration);
                            schemaExport.Execute(false, true, false, masterConnection, TextWriter.Null);
                        }
                    }
                }
            }
        }
Пример #23
0
        private static Configuration Configure()
        {
            var config = Fluently.Configure()
                         .Database(
                SQLiteConfiguration.Standard.UsingFile("database").ShowSql()
                //MsSqlConfiguration.MsSql2008.ConnectionString(b => b.FromConnectionStringWithKey("db"))
                )
                         .Mappings(m =>
            {
                var model = AutoMap.Assemblies(new AutomappingConfiguration(), GetAssemblies());
                model.Conventions.Add(new SetEnumTypeConvention());
                model.Conventions.Add(new UseNewSqlDateTime2TypeConvention());
                model.Conventions.Add(new CollectionAccessConvention());
                model.Conventions.Add(new SqlTimestampConvention());
                model.Conventions.Add(new SetTableNameConvention());

                model.Conventions.Add(DefaultLazy.Never());
                m.AutoMappings.Add(model);
                m.AutoMappings.ExportTo("c:\\mapping");
                m.FluentMappings.ExportTo("c:\\mapping");
            })
                         .BuildConfiguration();

            // Generatre schema before each start
            var e = new SchemaExport(config);

            e.SetOutputFile(@"c:\mapping\a.sql");
            e.Execute(true, true, false);

            return(config);
        }
Пример #24
0
        static ISessionFactory CreateSessionFactoryForDdl()
        {
            FluentConfiguration cfg = Fluently.Configure()
                                      .Database(MsSqlConfiguration.MsSql2008
                                                .ConnectionString(c => c.FromConnectionStringWithKey("MSSQL2012"))
                                                .Dialect <MsSql2012Dialect>()
                                                );

            cfg.Mappings(m => m
                         .FluentMappings
                         .AddFromAssemblyOf <NHibernateHelper>()
                         );

            cfg.ExposeConfiguration(config =>
            {
                SchemaExport schemaExport = new SchemaExport(config);
                schemaExport.SetOutputFile(AppDomain.CurrentDomain.BaseDirectory + @"\LedgerLinkDbScript.sql");
                schemaExport.Drop(true, true);
                schemaExport.Create(true, true);
                schemaExport.Execute(false, false, false);
            });
            SessionFactory = cfg.BuildSessionFactory();


            return(SessionFactory);
        }
Пример #25
0
        public void SetupContext()
        {
            _logger.Debug("Setting up context");
            var export = new SchemaExport(_cfg);

            export.Execute(false, true, false, false);
        }
Пример #26
0
        public static void Setup(out ContentPersister persister, ISessionProvider sessionProvider, N2.Persistence.IRepository <ContentItem> itemRepository, INHRepository <ContentDetail> linkRepository, SchemaExport schemaCreator)
        {
            persister = new ContentPersister(itemRepository, linkRepository);
            new BehaviorInvoker(persister, new N2.Definitions.Static.DefinitionMap()).Start();

            schemaCreator.Execute(false, true, false, sessionProvider.OpenSession.Session.Connection, null);
        }
        public void Setup()
        {
            // Create NHibernate DB tables
            _schemaExport.Execute(false, true, false);

            SetupTestData();
        }
        public void CreateDatabaseSchema()
        {
            var export = new SchemaExport(
                DataContext.BuildConfiguration());

            export.Execute(true, true, false);
        }
Пример #29
0
        protected void ReBuildDatabase()
        {
            var export = new SchemaExport(helper.Configuration);

            export.Execute(true, true, false);
            //var query = Session.CreateSQLQuery(hilo);
            //query.ExecuteUpdate();
        }
Пример #30
0
        public void CreateDB()
        {
            SchemaExport schemaExport = new SchemaExport(Common.GetNHibernateConnnectInfo());

            schemaExport.Execute(false, true, false);

            CreateBlog();
        }
Пример #31
0
 public void SetUp()
 {
     cfg = new Configuration();
     cfg.Properties["connection.provider"] = "NHibernate.Connection.DriverConnectionProvider";
     cfg.Properties["connection.driver_class"] = "NHibernate.Driver.SqlClientDriver";
     cfg.Properties["connection.connection_string"] =
         "Data Source=.\\SQLEXPRESS;Initial Catalog=test;Integrated Security=SSPI";
     cfg.Properties["dialect"] = "NHibernate.Dialect.MsSql2000Dialect";
     cfg.Properties["proxyfactory.factory_class"] =
         "NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle";
     cfg.Properties["show_sql"] = "true";
     cfg.AddAssembly("BlogSharp.NHibernate");
     factory = cfg.BuildSessionFactory();
     var export = new SchemaExport(cfg);
     export.Execute( true, false, true);
 }
Пример #32
0
        public void SetUp()
        {
            cfg=Fluently.Configure()
                .Mappings(mappings => mappings.FluentMappings.AddFromAssemblyOf<UserMap>())
                .Database(MsSqlConfiguration.MsSql2008
                            .AdoNetBatchSize(20)
                            .ConnectionString(stringBuilder=>
                                              		stringBuilder.Database("test")
                                              			.TrustedConnection()
                                              			.Server("."))
                            .ShowSql()
                            .Raw("hbm2ddl.keywords", "auto-quote")
                ).BuildConfiguration();

            factory = cfg.BuildSessionFactory();
            var export = new SchemaExport(cfg);
            export.Execute(true, true, false);
        }
        /// <summary>
        /// Gets an NHibernate session for an in-memory database.
        /// </summary>
        /// <returns>
        /// A session for an in-memory database.
        /// </returns>
        private static ISession GetInMemoryDatabaseSession()
        {
            Configuration configuration = null;
            ISessionFactory sessionFactory = Fluently.Configure()
                .Database(
                    SQLiteConfiguration.Standard
                        .InMemory()
                        .ShowSql())
                .Mappings(
                    m => m.FluentMappings.AddFromAssemblyOf<StockMap>())
                .ExposeConfiguration(
                    cfg => configuration = cfg)
                .BuildSessionFactory();
            var session = sessionFactory.OpenSession();

            var schemaExport = new SchemaExport(configuration);
            schemaExport.Execute(true, true, false, session.Connection, null);

            return session;
        }
Пример #34
0
 public void TearDown()
 {
     factory = cfg.BuildSessionFactory();
     var export = new SchemaExport(cfg);
     export.Execute(true, false, true);
 }