Пример #1
0
        static void Main(string[] args)
        {
            NLogAudit.Register(AuditType.Debug, AuditTarget.Console, AuditTarget.File);

            Audit.Message("Lit.Db.Test");

            try
            {
                Audit.Message("\n\n*** NAMING TEST ***");
                Naming.Execute();

                //Audit.Message("\n\n*** STORED PROCEDURE TEST ***");
                //StoredProcedure.Execute(db);

                Audit.Message("\n\n*** INFORMATION SCHEMA TEST ***");
                MySql.InformationSchema.Load(db);

                Audit.Message("\n\n*** SCHEMA UPDATE TEST ***");
                SchemaUpdate.Execute(tdb);

                Audit.Message("\n\n*** DATA ACCESS TEST ***");
                DataAccess.Execute(db);

                Audit.Message("\n\n*** TEST FINISHED OK ***");
            }
            catch (Exception x)
            {
                Audit.Error($"Error: {x.Message}.");
            }
        }
Пример #2
0
        /// <summary>
        /// Update the Database Schema
        /// </summary>
        /// <param name="configuration">
        /// The configuration.
        /// </param>
        public static void UpdateSchema(this Configuration configuration)
        {
            // configuration.CreateIndexesForForeignKeys();
            var schema = new SchemaUpdate(configuration);

            schema.Execute(false, true);
        }
        public static ISessionFactory GetSessionFactoryGeral()
        {
            if (SessionGeralFactory == null)
            {
                var _session = Fluently.Configure()
                               .Database(MySQLConfiguration.Standard.ConnectionString(connectionGeral))
                               .Mappings(m => m.FluentMappings
                                         .Add <UsuarioMap>()
                                         .Add <EnderecoMap>()
                                         .Add <VeiculoMap>()
                                         .Add <EmpresaMap>()
                                         .Add <EstacaoMap>()
                                         );


                #if DEBUG
                var updater = new SchemaUpdate(_session.BuildConfiguration());
                updater.Execute(true, true);
                var ex = updater.Exceptions;
                #endif

                SessionGeralFactory = _session.BuildSessionFactory();
            }
            return(SessionGeralFactory);
        }
Пример #4
0
        public void TestMethod1()
        {
            var config = new NH.Configuration().Configure();

            var mapper = new ModelMapper();

            mapper.AddMappings(typeof(SessionFactory).Assembly.GetTypes());
            config.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());
            SchemaUpdate su = new SchemaUpdate(config);

            //se.Execute(false, false, true);
            su.Execute(true, true);

            var factory = config.BuildSessionFactory();

            using (var session = factory.OpenSession())
            {
                using (var tran = session.BeginTransaction())
                {
                    session.Save(new Brand {
                        Name = "Brand 2", UtcCreationDate = DateTime.UtcNow, UtcUpdateDate = DateTime.UtcNow
                    });
                    tran.Commit();
                }
            }

            factory.Dispose();
        }
Пример #5
0
        private static void BuildSchema(Configuration config)
        {
            var update = new SchemaUpdate(config);

            //update.Drop(false,true)
            update.Execute(false, true);
        }
        public static void ValidateOrCreateSchema(string connString, string mapAssemblyName)
        {
            Configuration configuration = CreateConfiguration(connString, mapAssemblyName);

            try
            {
                SchemaValidator validator = new SchemaValidator(configuration);
                validator.Validate();
            }
            catch (HibernateException)
            {
                SchemaUpdate schema = new SchemaUpdate(configuration);
                schema.Execute(true, true);
            }
            catch (Exception)
            {
                try
                {
                    SchemaUpdate schema = new SchemaUpdate(configuration);
                    schema.Execute(true, true);
                }
                catch (Exception)
                {
                    throw;
                }

                throw;
            }
        }
Пример #7
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);
        }
        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());
        }
Пример #9
0
        public static ISession AbreSession()
        {
            var teste = new SchemaUpdate(RecuperaConfiguracao());

            teste.Execute(true, true);
            return(fabrica.OpenSession());
        }
        public ISessionFactory CreateSqLite()
        {
            string databaseFilePath = Path.Combine(Path.GetTempPath(), "Lab.ExchangeNet45.sqlite");

            return(CreateConfiguration()
                   .Database
                   (
                       SQLiteConfiguration.Standard
                       .ConnectionString($"data source={databaseFilePath};Version=3;New=True;BinaryGuid=False;PRAGMA synchronous=off;")
                       .Driver <SQLite20Driver>()
                       .Dialect <SQLiteDialect>()
                       .Provider <DriverConnectionProvider>()
                       .QuerySubstitutions("true 1, false 0")
                       .ShowSql()
                       .FormatSql()
                       .AdoNetBatchSize(250)
                       .IsolationLevel(IsolationLevel.ReadCommitted)
                   )
                   .ExposeConfiguration(config =>
            {
                config.Properties.Add("hbm2ddl.keywords", "none");

                var schemaUpdate = new SchemaUpdate(config);
                schemaUpdate.Execute(true, true);
            })
                   .BuildSessionFactory());
        }
Пример #11
0
        private static void ExportarEsquema(Configuration cfg)
        {
            var lol = new SchemaUpdate(cfg);

            lol.Execute(false, true);
            //lol.Execute(true, false);
        }
        public void UpdateExistingDatabase(SchemaDefinition definition)
        {
            CheckDefinitionIsValid(definition);

            var schemaUpdate = new SchemaUpdate(definition.Configuration);

            if (definition.FileDefinition != null && !string.IsNullOrWhiteSpace(definition.FileDefinition.FileName))
            {
                //output the sql to create the db to a file.
                string filename = Path.Combine(string.IsNullOrWhiteSpace(definition.FileDefinition.OutputFolder) ? "" : definition.FileDefinition.OutputFolder, definition.FileDefinition.FileName);

                Action <string> updateExport = x =>
                {
                    using (var file = new FileStream(filename, FileMode.Append, FileAccess.Write))
                        using (var sw = new StreamWriter(file))
                        {
                            sw.Write(x);
                            sw.Close();
                        }
                };

                schemaUpdate.Execute(updateExport, true);
            }
            else
            {
                schemaUpdate.Execute(false, true);
            }
        }
Пример #13
0
        public static ISessionFactory CreateSessionFactory(string connectionName, IEnumerable <Type> types, ILogger logger)
        {
            var conf = new Configuration();

            conf.DataBaseIntegration(c =>
            {
//                c.
//                c.Dialect<SQLiteDialect>();
//                c.ConnectionStringName = connectionName;
                c.ConnectionStringName = connectionName;
                c.Driver <SQLite20Driver>();
                c.Dialect <SQLiteDialect>();
                c.ConnectionReleaseMode = ConnectionReleaseMode.OnClose;
            });
            var mapper = new ModelMapper();

            mapper.AddMappings(types);
            conf.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());

            conf.CurrentSessionContext <TContext>();

            var shemaUpdate = new SchemaUpdate(conf);

            shemaUpdate.Execute(true, true);
            if (shemaUpdate.Exceptions.Any())
            {
                foreach (var exception in shemaUpdate.Exceptions)
                {
                    logger.Error(exception);
                }
                throw new AggregateException(shemaUpdate.Exceptions);
            }

            return(conf.BuildSessionFactory());
        }
Пример #14
0
        public void PersistTestObject()
        {
            var schemaUpdate = new SchemaUpdate(_container.Resolve <IConfigurationFactory>().Build());

            schemaUpdate.Execute(
                scriptAction => Trace.WriteLine(scriptAction),
                true);

            var temporalTestObject = new TemporalTestObject(Guid.NewGuid());
            var versions           = Enumerable.Range(0, 3).Select(
                i => new TestObjectVersion(
                    Guid.NewGuid(),
                    temporalTestObject)).ToList();

            foreach (var index in Enumerable.Range(0, temporalTestObject.Versions.Count))
            {
                Assert.That(temporalTestObject.Versions[index].Number, Is.EqualTo(index + 1));
            }

            using (var scope = _container.BeginLifetimeScope())
            {
                var session = scope.Resolve <ISession>();
                session.Save(temporalTestObject);
                temporalTestObject.Versions.ForEach(version => session.Save(version));
                session.Flush();
            }

            using (var scope = _container.BeginLifetimeScope())
            {
                var session = scope.Resolve <ISession>();
                var retrievedTemporalTestObject = session.Get <TemporalTestObject>(temporalTestObject.Id);
                Assert.That(temporalTestObject, Is.Not.Null);
                Assert.That(temporalTestObject.Versions.SequenceEqual(retrievedTemporalTestObject.Versions), Is.True);
            }
        }
Пример #15
0
        private static ISessionFactory OpenSessionFactory()
        {
            ISessionFactory sessionFactory = null;

            try
            {
                var nhConfig = Fluently.Configure()
                               .Database(SQLiteConfiguration.Standard
                                         .ConnectionString("data source=|DataDirectory|test.db;")
                                         .AdoNetBatchSize(100))
                               .Mappings(mappings => mappings.FluentMappings.AddFromAssemblyOf <UserMap>())
                               .BuildConfiguration();

                sessionFactory = nhConfig.BuildSessionFactory();
                var schemaExport = new SchemaUpdate(nhConfig);
                schemaExport.Execute(true, true);
            }
            catch (Exception e)
            {
                Logger.Log(e);
                Console.WriteLine(e.Message);
                Console.ReadLine();
            }

            return(sessionFactory);
        }
Пример #16
0
        static void Main(string[] args)
        {
            try
            {
                var container = new WindsorContainer();
                container.Install(FromAssembly.Containing <NHibernateConfigurationInstaller>());


                Info("Creating tables...");
                var cfg = container.Resolve <NHibernate.Cfg.Configuration>();
                cfg.SetInterceptor(new ConsoleInterceptor());
                var se = new SchemaUpdate(cfg);
                se.Execute(sql =>
                {
                    File.WriteAllText("update-database.sql", sql);
                }, doUpdate: true);

                RunMigration();

                Success(" Success\r\n");
                ExecuteSqlScripts();
            }
            catch (Exception exc)
            {
                Error(exc.ToString());
            }
            Console.Read();
        }
        public static void AddNHibernate(this IServiceCollection serviceCollection, IConfigurationRoot configurationRoot)
        {
            var nhibernateConfiguration = Fluently.Configure()
                                          .Database(MsSqlConfiguration.MsSql2012.ConnectionString(c => c.Is(configurationRoot["Nhibernate:Con"])).Dialect <MsSql2012Dialect>())
                                          .Mappings(m => m.FluentMappings.AddFromAssemblyOf <IMap>())
                                          .ExposeConfiguration(c =>
            {
                c.SetProperty(NHibernate.Cfg.Environment.GenerateStatistics, "true");
                c.SetProperty(NHibernate.Cfg.Environment.PrepareSql, "true");
                c.SetProperty("use_sql_comments", "false");


                var update = new SchemaUpdate(c);
                update.Execute(true, true);
            })
                                          .Cache(c => c
                                                 .UseQueryCache()
                                                 .UseSecondLevelCache()
                                                 .ProviderClass <HashtableCacheProvider>())
                                          .BuildConfiguration();
            var sessionFactory = nhibernateConfiguration.BuildSessionFactory();

            serviceCollection.AddSingleton <Configuration>((sp) => nhibernateConfiguration);
            serviceCollection.AddSingleton <ISessionFactory>(sp => sessionFactory);
            serviceCollection.AddScoped <ISession>(sp =>
            {
                var session = sessionFactory.OpenSession();
                session.BeginTransaction();
                return(session);
            });
        }
Пример #18
0
        static void Main(string[] args)
        {
            log4net.Config.XmlConfigurator.Configure();

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

            nhConfig.AddAssembly(typeof(Product).Assembly);

            var sessionFactory = nhConfig.BuildSessionFactory();

            var update = new SchemaUpdate(nhConfig);

            update.Execute(false, true);

            using (var session = sessionFactory.OpenSession())
            {
                using (var tr = session.BeginTransaction())
                {
                    var prod = new Product()
                    {
                        Name        = "Pepsi4",
                        Description = "Beverage",
                        UnitPrice   = 1.15M
                    };

                    session.Save(prod);

                    tr.Commit();
                }
            }


            Console.WriteLine("Finished!");
            Console.ReadLine();
        }
        public InMemoryNHibernateSessionSource(IEnumerable <Assembly> mappingAssemblies)
        {
            _configuration = Fluently.Configure()
                             .Database(SQLiteConfiguration.Standard.ConnectionString("FullUri=file:memorydb.db?mode=memory&cache=shared"))
                             .ExposeConfiguration(
                c =>
            {
                c.SetProperty(NHibernate.Cfg.Environment.CommandTimeout,
                              TimeSpan.FromMinutes(3).TotalSeconds.ToString(CultureInfo.InvariantCulture));
            })
                             .Mappings(x =>
            {
                foreach (var mappingAssembly in mappingAssemblies)
                {
                    x.FluentMappings.AddFromAssembly(mappingAssembly);
                }
            }).BuildConfiguration();

            _factory = _configuration.BuildSessionFactory();
            _connectionCreatingSession = _factory.OpenSession();
            var connection = _connectionCreatingSession.Connection;

            new SchemaExport(_configuration).Execute(
                false,
                true,
                justDrop: false,
                connection: connection,
                exportOutput: null);
            var export = new SchemaUpdate(_configuration);

            export.Execute(true, true);
        }
Пример #20
0
        private static Configuration AddSchemaValidationAndMigration(this Configuration config)
        {
            var logger = NHibernateLogger.For(typeof(SessionFactory));

            System.Action <string> updateExport = x =>
            {
                if (logger != null)
                {
                    logger.Info(x);
                }
            };

            var update = new SchemaUpdate(config);

            try
            {
                update.Execute(updateExport, true);
                if (update.Exceptions != null && update.Exceptions.Count > 0)
                {
                    throw new AggregateException("Multiple exceptions occurred while executing database migrations. Check the inner list of exceptions.", update.Exceptions.ToArray());
                }
            }
            catch (Exception)
            {
                throw;
            }

            return(config);
        }
        public static IEnumerable <Exception> UpdateSchema(this Configuration config)
        {
            var schema = new SchemaUpdate(config);

            schema.Execute(false, true);
            return(schema.Exceptions);
        }
Пример #22
0
        // configure nhibernate
        static ISessionFactory BuildSessionFactory()
        {
            Configuration cfg = new Configuration();

            cfg.Proxy(p => p.ProxyFactoryFactory <ProxyFactoryFactory>());

            // this is important - specify the desired session context storage
            cfg.CurrentSessionContext <WcfOperationSessionContext>();

            cfg.DataBaseIntegration(db =>
            {
                db.Dialect <NHibernate.Dialect.MsSql2008Dialect>();
                db.Driver <NHibernate.Driver.SqlClientDriver>();
                db.ConnectionString = @"Data Source=.\sqlexpress;Initial Catalog=sample;Integrated Security=True;Pooling=False";
            });

            cfg.AddAssembly(typeof(Program).Assembly);

            // remove this in production
            SchemaUpdate updater = new SchemaUpdate(cfg);

            updater.Execute(true, true);

            // do actual configuration
            return(cfg.BuildSessionFactory());
        }
        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());
        }
Пример #24
0
        public void TryGenerateUpdateScript()
        {
            // Tables must not exists for it to output!!
            var schemaUpdate = new SchemaUpdate(NhibernateHelper.Configuration);

            schemaUpdate.Execute(Console.WriteLine, true);
        }
Пример #25
0
        /// <summary>
        /// Perform database migration<br/>
        /// 迁移数据库<br/>
        /// </summary>
        protected void MigrateDatabase(
            string database, string connectionString, FluentConfiguration configuration)
        {
            // initialize database scheme
            // flow:
            // - generate ddl script
            // - compare to App_Data\nh_{hash}.ddl
            // - if they are different, upgrade database scheme and write ddl script to file
            // it can make the website startup faster
            var fileStorage = Application.Ioc.Resolve <IFileStorage>();
            var hash        = PasswordUtils.Sha1Sum(
                Encoding.UTF8.GetBytes(database + connectionString)).ToHex();
            var ddlFileEntry = fileStorage.GetStorageFile($"nh_{hash}.ddl");

            configuration.ExposeConfiguration(c =>
            {
                var scriptBuilder = new StringBuilder();
                scriptBuilder.AppendLine("/* this file is for database migration checking, don't execute it */");
                new SchemaExport(c).Create(s => scriptBuilder.AppendLine(s), false);
                var script = scriptBuilder.ToString();
                if (!ddlFileEntry.Exists || script != ddlFileEntry.ReadAllText())
                {
                    var logManager   = Application.Ioc.Resolve <LogManager>();
                    var schemaUpdate = new SchemaUpdate(c);
                    schemaUpdate.Execute(false, true);
                    foreach (var ex in schemaUpdate.Exceptions)
                    {
                        logManager.LogError($"NHibernate schema update error: ({ex.GetType()}) {ex.Message}");
                    }
                    // Write ddl script to file
                    // Since Nhibernate 5.0 ExposeConfiguration is executed on fly
                    ddlFileEntry.WriteAllText(script);
                }
            });
        }
Пример #26
0
        //Retorna a sessão que utilizarei para operações de crud...
        public static ISessionFactory GetSessionFactory()
        {
            //Crio a configuração...
            var configuration = Fluently.Configure()
                                .Database(
                MySQLConfiguration
                .Standard
                .ConnectionString(cs => cs
                                  .Server(server)
                                  .Database(database)
                                  .Username(username)
                                  .Password(password)).ShowSql())
                                .Mappings(m => m.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly()))
                                .BuildConfiguration();



            //Crio a tabela no banco se ela não existir...
            var exporter = new SchemaUpdate(configuration);

            exporter.Execute(false, true);


            //Retorno a sessão...
            return(configuration.BuildSessionFactory());
        }
        public static void BuildSchema(NHibernate.Cfg.Configuration config, BuildSchemaType buildSchemaType)
        {
            switch (buildSchemaType)
            {
            case BuildSchemaType.CreateSchema:
            {
                var schemaExport = new SchemaExport(config);
                schemaExport.Create(false, true);
                break;
            }

            case BuildSchemaType.UpdateSchema:
            {
                var schemaUpdate = new SchemaUpdate(config);
                schemaUpdate.Execute(false, true);
                break;
            }

            case BuildSchemaType.DropSchema:
            {
                var schemaExport = new SchemaExport(config);
                schemaExport.Drop(false, true);
                break;
            }
            }
        }
Пример #28
0
        public ISessionFactory OpenSessionFactoryFor(string dataSource)
        {
            var cfg    = createSqlLiteConfigurationFor(dataSource);
            var update = new SchemaUpdate(cfg);

            update.Execute(useStdOut: false, doUpdate: true);
            return(cfg.BuildSessionFactory());
        }
Пример #29
0
        public ISessionFactory OpenSessionFactoryFor(string dataSource)
        {
            var cfg    = createSqlLiteConfigurationFor(dataSource);
            var update = new SchemaUpdate(cfg);

            update.Execute(true, true);
            return(createSessionFactory(cfg));
        }
Пример #30
0
 public static void UpdateSchema(global::NHibernate.Cfg.Configuration configuration)
 {
     using (new WriteLockDisposable(SchemaValidationLocker))
     {
         var schema = new SchemaUpdate(configuration);
         schema.Execute(false, true);
     }
 }
Пример #31
0
        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));
            }
        }