Beispiel #1
0
        public static void LoadNHibernateCfg()
        {
            var cfg = new Configuration();

            cfg.Configure();
            cfg.AddAssembly(typeof(Program).Assembly);
            SchemaExport schemaExport = new SchemaExport(cfg);

            schemaExport.SetDelimiter(";");
            schemaExport.Execute(true, false, false);
        }
Beispiel #2
0
        private static SchemaExport CreateSchemaExport(Configuration cfg)
        {
            SchemaExport export = new SchemaExport(cfg);

            // set the delimiter, but only if it is not the default delimiter
            if (schemaDelimiter != defaultSchemaDelimiter)
            {
                export.SetDelimiter(schemaDelimiter);
            }

            return(export);
        }
        SchemaExport GetExporter(Configuration configuration)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }

            var output = new SchemaExport(configuration);

            output.SetDelimiter(";");
            return(output);
        }
Beispiel #4
0
        public static bool ExportSchema(Configuration configuration, FileInfo outputFile)
        {
            try
            {
                if (outputFile == null)
                {
                    throw new ArgumentNullException("outputFile");
                }

                var schemaExport = new SchemaExport(configuration);

                if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["SchemaExportDelimiter"]))
                {
                    schemaExport.SetDelimiter(ConfigurationManager.AppSettings["SchemaExportDelimiter"]);
                }

                var schemaBuilder = new StringBuilder();
                using (var textWriter = new StringWriter(schemaBuilder, CultureInfo.InvariantCulture))
                {
                    schemaExport.Execute(false, false, false, null, textWriter);
                }

                var schema = schemaBuilder.ToString();

                // remove drop tables/constraints statements
                schema = schema.Substring(schema.IndexOf("create table", StringComparison.OrdinalIgnoreCase));

                // cleanup generated script
                schema = schema.Replace("\r\n", "\n").Replace("\r", "\n");
                schema = Regex.Replace(schema, "^ +(create table|\\)|alter table|add constraint|foreign key|references|on delete|on update|on insert)(.*)$", "$1$2", RegexOptions.Multiline);
                schema = Regex.Replace(schema, "^ +", "\t", RegexOptions.Multiline);

                schema = schema.Replace("\n", System.Environment.NewLine);

                File.WriteAllText(outputFile.FullName, schema, Encoding.UTF8);

                return(true);
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine("ERROR GENERATING DATABASE SCHEMA SCRIPT");
                Console.Error.WriteLine("=======================================");

                for (Exception ex1 = ex; ex1 != null; ex1 = ex1.InnerException)
                {
                    Console.Error.WriteLine(ex.Message ?? "no message");
                }

                return(false);
            }
        }
        private SchemaExport CreateSchemaExport(Configuration config)
        {
            var result = new SchemaExport(config);

            if (!string.IsNullOrEmpty(this.delimiter))
            {
                result.SetDelimiter(this.delimiter);
            }
            if (!string.IsNullOrEmpty(this.outputFile))
            {
                result.SetOutputFile(this.outputFile);
            }
            return(result);
        }
Beispiel #6
0
        // GET: /Admin/
        public ActionResult Index()
        {
            var se = new SchemaExport((new Configuration()).Configure());

            se.SetDelimiter(";\n");
            TextWriter oldOut         = Console.Out;
            var        creationSchema = new StringWriter();

            Console.SetOut(creationSchema);
            se.Create(true, false);
            Console.SetOut(oldOut);
            ViewBag.SchemaExport = creationSchema.ToString();
            return(View());
        }
Beispiel #7
0
        public void TestExportSchemaByXml()
        {
            var config = new Configuration();

            config.Configure("MySql.cfg.xml");

            config.AddXmlFile("Hbm\\Test.hbm.xml");

            // test build schema
            var schemaExport = new SchemaExport(config);

            schemaExport.SetDelimiter(";");
            //schemaExport.SetOutputFile("R:\\test.sql");
            schemaExport.Execute(true, true, false);
        }
Beispiel #8
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="cfg"></param>
        /// <param name="outputFileName"></param>
        /// <param name="script"></param>
        /// <param name="export"></param>
        /// <param name="justDrop"></param>
        public static void ExportSchema(Configuration cfg, string outputFileName, bool script, bool export, bool justDrop)
        {
            SchemaExport exporter = new SchemaExport(cfg);

            //exporter.SetOutputFile(outputFileName);
            exporter.SetDelimiter(";");

            using (System.IO.StreamWriter sw = new System.IO.StreamWriter(outputFileName, false, Encoding.UTF8))
            {
                Console.SetOut(sw);
                exporter.Execute(script, export, justDrop);
            }

            //exporter.Drop(true, false);  ==  == exporter.Execute(true, false, true, true)
            //exporter.Create(true, false); == exporter.Execute(true, false, false, true)
        }
Beispiel #9
0
        public string ExportSchema()
        {
            Configuration configuration = new Configuration();

            configuration.Configure(this._sessionFactoryConfigPath);
            SchemaExport schemaExport = new SchemaExport(configuration);

            schemaExport.SetDelimiter(";");
            StringWriter stringWriter = new StringWriter();

            schemaExport.Execute(true, true, false, this.NHibernateSession.Connection, stringWriter);
            string result = stringWriter.ToString();

            stringWriter.Close();
            return(result);
        }
Beispiel #10
0
        public void CreateSchema([CanBeNull] string outputFile = null,
                                 bool writeToConsole           = false)
        {
            var schemaExport = new SchemaExport(_configuration);

            if (!string.IsNullOrEmpty(outputFile))
            {
                schemaExport.SetOutputFile(outputFile);
            }

            schemaExport.SetDelimiter(Environment.NewLine);

            const bool export = true;

            schemaExport.Create(writeToConsole, export);
        }
Beispiel #11
0
        public static void Create(IApplicationContext ctx)
        {
            DDLGenerator generator = ctx["DDLGenerator"] as DDLGenerator;

            ISessionFactory sessionFactory = ctx["SessionFactory"] as ISessionFactory;

            ISession openSession = sessionFactory.OpenSession();

            IDbConnection connection = openSession.Connection;

            SchemaExport e = new SchemaExport(generator.SessionFactory.Configuration);

            e.SetDelimiter(";");
            e.Create(true, false);  // Write DDL to screen
            //  Create database and create DDL file
            e.Execute(false, true, true);
            e.Execute(true, true, false, connection, new StreamWriter("CreateDataBase.ddl.sql"));
        }
Beispiel #12
0
        public void CreateFor(IDatabase database)
        {
            Configuration configuration = database.GetNHibernateConfiguration();

            var schemaExport = new SchemaExport(configuration);

            schemaExport.SetDelimiter(";");

            var scriptLines = new StringBuilder();

            schemaExport.Create(scriptLine => scriptLines.AppendLine(scriptLine), false);

            string script = scriptLines.ToString();

            //Console.WriteLine(script);

            if (database is ISampleDatabase)
            {
                schemaExport.Drop(useStdOut: true, execute: true);

                this.CreateSqlSchema(database.CurrentSession, SampleDatabase.SchemaName);

//                database.CurrentSession
//                        .CreateSQLQuery(
//                            @"
//DROP TABLE [words].[Word]
//DROP TABLE [words].[WordGroup]
//DROP TABLE [words].[User]
//")
//                        .ExecuteUpdate();

                //database.CurrentSession
                //        .CreateSQLQuery($"DROP SCHEMA {SampleDatabase.SchemaName}")
                //        .ExecuteUpdate();

                //database.CurrentSession
                //        .CreateSQLQuery($"CREATE SCHEMA {SampleDatabase.SchemaName}")
                //        .ExecuteUpdate();
            }

            database.CurrentSession
            .CreateSQLQuery(script)
            .ExecuteUpdate();
        }
Beispiel #13
0
        public static void AddNHibernate(this IServiceCollection serviceCollection,
                                         string type, string connectionString)
        {
            var configuration = Fluently.Configure()
                                .Database(GetDatabaseConfiguration(type, connectionString))
                                .Mappings(m => m.FluentMappings.AddFromAssemblyOf <AccountMap>());

#if DEBUG
            configuration = configuration.ExposeConfiguration(config => {
                var schemaExport = new SchemaExport(config);
                schemaExport.SetDelimiter(";");
                schemaExport.SetOutputFile("schema.sql").Execute(true, false, false);
            });
#endif

            var factory = configuration.BuildSessionFactory();

            serviceCollection.AddSingleton(factory);
            serviceCollection.AddScoped <IScopeFactory, ScopeFactory>();
        }
Beispiel #14
0
        /// <summary>
        /// Executes the task.
        /// </summary>
        protected override void ExecuteTask()
        {
            Configuration config = new Configuration();
            Dictionary <string, string> properties = new Dictionary <string, string>();

            properties[NHibernate.Cfg.Environment.ConnectionProvider] = ConnectionProvider;
            properties[NHibernate.Cfg.Environment.Dialect]            = Dialect;
            properties[NHibernate.Cfg.Environment.ConnectionDriver]   = ConnectionDriverClass;
            properties[NHibernate.Cfg.Environment.ConnectionString]   = ConnectionString;

            config.AddProperties(properties);

            foreach (string filename in Assemblies.FileNames)
            {
                Log(Level.Info, "Adding assembly file {0}", filename);
                try
                {
                    Assembly asm = Assembly.LoadFile(filename);
                    config.AddAssembly(asm);
                }
                catch (Exception e)
                {
                    Log(Level.Error, "Error loading assembly {0}: {1}", filename, e);
                }
            }

            SchemaExport se = new SchemaExport(config);

            if (!IsStringNullOrEmpty(OutputFilename))
            {
                se.SetOutputFile(OutputFilename);
            }
            se.SetDelimiter(Delimiter);
            Log(Level.Debug, "Exporting ddl schema.");
            se.Execute(OutputToConsole, ExportOnly, DropOnly, FormatNice);

            if (!IsStringNullOrEmpty(OutputFilename))
            {
                Log(Level.Info, "Successful DDL schema output: {0}", OutputFilename);
            }
        }
Beispiel #15
0
        static NHibernateSessionFactory()
        {
            Configuration = new Configuration().XConfigure(FactoryName)
                            .SetNamingStrategy(new CdtNamingStrategy())
                            .SetProperty(Environment.UseProxyValidator, "true")
                            .SetProperty(Environment.DefaultSchema, DefaultSchemaName);
            //.SetProperty(Environment.DefaultCatalog, DefaultCatalog);

            // get mappings for identity
            var myEntities = new[] { typeof(ClientPortalUser), typeof(ClientPortalRole) };

            Configuration.AddDeserializedMapping(MappingHelper.GetIdentityMappings(myEntities), null);

            var mapper = new OracleModelMapper();

            var path = Utils.GetExcutablePath();

            var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();

            // fix import of classes with same name in different namespaces http://stackoverflow.com/questions/1290466/fluent-nhibernate-duplicatemappingexception-with-automapping
            mapping.autoimport = false;

            Configuration.AddMapping(mapping);

            SessionFactory = Configuration.BuildSessionFactory();

            // Generate Delete and Create Script
            StringBuilder databaseScript = new StringBuilder();
            var           schemaExporter = new SchemaExport(Configuration);

            schemaExporter.SetDelimiter(";");
            using (StringWriter sw = new StringWriter(databaseScript))
            {
                schemaExporter.Execute(false, false, false, null, sw);
            }
            string scripts = null;

            scripts = databaseScript.ToString();
        }
Beispiel #16
0
        public void TestExportSchemaByCode()
        {
            var config = new Configuration();

            config.Configure("MySql.cfg.xml");
            var mapper = new ConventionModelMapper();

            mapper.AddMapping(new EmployeeMapping());
            mapper.AddMapping(new StoreMapping());
            mapper.AddMapping(new ProductMapping());

            var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();

            Assert.IsNotNull(mapping);
            Console.WriteLine(mapping.AsString());
            config.AddMapping(mapping);

            // test build schema
            var schemaExport = new SchemaExport(config);

            schemaExport.SetDelimiter(";");
            //schemaExport.SetOutputFile("R:\\test.sql");
            schemaExport.Execute(true, true, false);
        }
        public static void GenerateScriptsFile(NHibernate.Cfg.Configuration config, string directoryPath, bool openScriptsFileAfterCreation)
        {
            if (!Directory.Exists(directoryPath))
            {
                Directory.CreateDirectory(directoryPath);
            }

            var fileName     = $"{DateTime.Now:yyyy-MM-dd_HH-mm-ss}.sql";
            var fileFullName = $"{directoryPath}{fileName}";

            var schemaExport = new SchemaExport(config);

            schemaExport.SetDelimiter(";");
            schemaExport.SetOutputFile(fileFullName);
            schemaExport.Execute(false, false, false);

            if (openScriptsFileAfterCreation)
            {
                Process.Start(
                    File.Exists(ConfigurationHelper.SublimeTextPath)
                        ? ConfigurationHelper.SublimeTextPath
                        : ConfigurationHelper.NotepadPath, fileFullName);
            }
        }
Beispiel #18
0
        public void Run(LongOperationBroker longOperationBroker)
        {
            _longOperationBroker = longOperationBroker;
            _targetConfiguration = SessionFactoryFactory.GetConfiguration(DatabaseTypeEnum, 0);
            var schemaExport = new SchemaExport(_targetConfiguration);

            schemaExport.SetOutputFile(Path);
            schemaExport.SetDelimiter(";");
            schemaExport.Create(true, false);
            using (var stream = File.OpenWrite(Path))
            {
                _writer = new StreamWriter(stream);
                foreach (var line in _targetConfiguration.GenerateSchemaCreationScript(Dialect))
                {
                    _writer.Write(line);
                    _writer.WriteLine(";");
                }
                using (var session = Workspace.OpenSession())
                {
                    _sourceConnection = session.Connection;
                    ExportTable <DbWorkspace>();
                    ExportTable <DbMsDataFile>();
                    ExportTable <DbSetting>();
                    ExportTable <DbModification>();
                    ExportTable <DbTracerDef>();
                    ExportTable <DbPeptide>();
                    ExportTable <DbPeptideSpectrumMatch>();
                    ExportTable <DbPeptideAnalysis>();
                    ExportTable <DbPeptideFileAnalysis>();
                    ExportTable <DbChromatogramSet>();
                    ExportTable <DbChromatogram>();
                    ExportTable <DbPeak>();
                }
                _writer.Flush();
            }
        }