/// <summary> /// If EF migrations need to be done, does MF Migrations on the database /// </summary> /// <returns>True if at least one migration was run</returns> public static bool MigrateDatabase(bool hasPendingEFMigrations) { if (!hasPendingEFMigrations) { return(false); } // get the pendingmigrations sorted by name (in the order that they run), then run to the latest migration var migrator = new System.Data.Entity.Migrations.DbMigrator(new Rock.Migrations.Configuration()); var pendingMigrations = migrator.GetPendingMigrations().OrderBy(a => a); // double check if there are migrations to run if (pendingMigrations.Any()) { LogStartupMessage("Migrating Database..."); var lastMigration = pendingMigrations.Last(); // create a logger, but don't enable any of the logs var migrationLogger = new Rock.Migrations.RockMigrationsLogger() { LogVerbose = false, LogInfo = false, LogWarning = false }; var migratorLoggingDecorator = new MigratorLoggingDecorator(migrator, migrationLogger); // NOTE: we need to specify the last migration vs null so it won't detect/complain about pending changes migratorLoggingDecorator.Update(lastMigration); return(true); } return(false); }
/// <summary> /// Migrates the database. /// </summary> /// <returns>True if at least one migration was run</returns> public bool MigrateDatabase(RockContext rockContext) { bool result = false; // default Initializer is CreateDatabaseIfNotExists, so set it to NULL so it doesn't try to do anything special Database.SetInitializer <Rock.Data.RockContext>(null); var fileInfo = new FileInfo(Server.MapPath("~/App_Data/Run.Migration")); if (fileInfo.Exists) { // get the pendingmigrations sorted by name (in the order that they run), then run to the latest migration var migrator = new System.Data.Entity.Migrations.DbMigrator(new Rock.Migrations.Configuration()); var pendingMigrations = migrator.GetPendingMigrations().OrderBy(a => a); if (pendingMigrations.Any()) { LogMessage(APP_LOG_FILENAME, "Migrating Database..."); var lastMigration = pendingMigrations.Last(); // NOTE: we need to specify the last migration vs null so it won't detect/complain about pending changes migrator.Update(lastMigration); result = true; } fileInfo.Delete(); } return(result); }
private static void InitializeDataStore() { System.Data.Entity.Database.SetInitializer(new System.Data.Entity.MigrateDatabaseToLatestVersion <GalleryDb, GalleryDbMigrationConfiguration>()); var configuration = new GalleryDbMigrationConfiguration(); var migrator = new System.Data.Entity.Migrations.DbMigrator(configuration); if (migrator.GetPendingMigrations().Any()) { migrator.Update(); } }
public ApplicationDbContext(string connectionString) : base(connectionString) { _connection = connectionString; Database.SetInitializer(new MigrateDatabaseToLatestVersion <ApplicationDbContext, Configuration>()); var configuration = new Configuration(); var migrator = new System.Data.Entity.Migrations.DbMigrator(configuration); if (migrator.GetPendingMigrations().Any()) { migrator.Update(); } }
public void InitializeDatabase(TContext context) { if (!context.Database.Exists()) { context.Database.CreateIfNotExists(); } else { // this is either // -an old database with no history table, or // -a new table that has a history table //context.Database.CompatibleWithModel(true); // no metadata found in table because there is no history table // "Model compatibility cannot be checked because the database does not contain model metadata. // Model compatibility can only be checked for databases created using Code First or Code First Migrations." if (IsOldDBWithoutHistoryTable(context)) { try { // add the MigrationHistory table and the initial row RunDBTransaction(CON_SQL_Add_MigrationHistory_Table); RunDBTransaction(CON_SQL_Add_InitialRow_MigrationHistory); } catch (Exception ex) { string s = ex.InnerException.Message; throw; } //Initial initialMigration = new Initial(); //initialMigration.IsOldFileWithoutMigrationHistory = true; //initialMigration.Up(); } // see https://galleryserverpro.com/using-entity-framework-code-first-migrations-to-auto-create-and-auto-update-an-application/ // change first the DB conn string to SQL server express // then run the package manager with command: Add-Migration myMigrationName Configuration cf = new Configuration(); var migrator = new System.Data.Entity.Migrations.DbMigrator(cf); if (migrator.GetPendingMigrations().Any()) { migrator.Update(); } } // Do you want to migrate to latest in your initializer? Add code here! // Do you want to seed data in your initializer? Add code here! }
private static void InitData(IUnityContainer container) { Database.SetInitializer( new MigrateDatabaseToLatestVersion <ShortenerContext, MirationConfiguration>() ); var configuration = new MirationConfiguration(); var migrator = new System.Data.Entity.Migrations.DbMigrator(configuration); if (migrator.GetPendingMigrations().Any()) { migrator.Update(); } }
static DataContext() { try { Database.SetInitializer(new MigrateDatabaseToLatestVersion <DataContext, Configuration>()); var migrator = new System.Data.Entity.Migrations.DbMigrator(new Configuration()); if (migrator.GetPendingMigrations().Any()) { migrator.Update(); } } catch (System.Exception ex) { } }
public static void Init() { //configure app domain AppDomain.CurrentDomain.SetData("DataDirectory", AppDomain.CurrentDomain.BaseDirectory); //create or update db with lates migrations Database.SetInitializer(new MigrateDatabaseToLatestVersion <FuhrerContext, Migrations.Configuration>()); var configuration = new Migrations.Configuration(); var migrator = new System.Data.Entity.Migrations.DbMigrator(configuration); if (migrator.GetPendingMigrations().Any()) { migrator.Update(); } }
private void InitializeDataStore() { if (V4SchemaUpdateRequired) { DbManager.ChangeNamespaceForVersion4Upgrade(ProviderDataStore, V4SchemaUpdateRequiredFilePath); } System.Data.Entity.Database.SetInitializer(new System.Data.Entity.MigrateDatabaseToLatestVersion <GalleryDb, GalleryDbMigrationConfiguration>()); var configuration = new GalleryDbMigrationConfiguration(ProviderDataStore); var migrator = new System.Data.Entity.Migrations.DbMigrator(configuration); if (migrator.GetPendingMigrations().Any()) { migrator.Update(); Factory.ValidateGalleries(); } }
private static void InitializeDataStore() { System.Data.Entity.Database.SetInitializer(new System.Data.Entity.MigrateDatabaseToLatestVersion <FlightAvailability.Models.FlightContext, FlightAvailability.Migrations.Configuration>()); var configuration = new FlightAvailability.Migrations.Configuration(); var migrator = new System.Data.Entity.Migrations.DbMigrator(configuration); if (migrator.GetPendingMigrations().Any()) { System.Diagnostics.Debug.WriteLine("Running migrations against database"); migrator.Update(); } else { System.Diagnostics.Debug.WriteLine("There no database schema changes"); } }
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); Database.SetInitializer(new MigrateDatabaseToLatestVersion<DSEntities, MonlithDS.DAL.Migrations.Configuration>()); //Update the DB as required var configuration = new MonlithDS.DAL.Migrations.Configuration(); var migrator = new System.Data.Entity.Migrations.DbMigrator(configuration); if (migrator.GetPendingMigrations().Any()) { migrator.Update(); } //Database.SetInitializer<DSEntities>(null); ModelBinders.Binders.Add(typeof(Cart), new CartModelBinder()); }
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); Database.SetInitializer(new MigrateDatabaseToLatestVersion <DSEntities, MonlithDS.DAL.Migrations.Configuration>()); //Update the DB as required var configuration = new MonlithDS.DAL.Migrations.Configuration(); var migrator = new System.Data.Entity.Migrations.DbMigrator(configuration); if (migrator.GetPendingMigrations().Any()) { migrator.Update(); } //Database.SetInitializer<DSEntities>(null); ModelBinders.Binders.Add(typeof(Cart), new CartModelBinder()); }
/// <summary> /// Migrates the database. /// </summary> /// <returns>True if at least one migration was run</returns> public bool MigrateDatabase(RockContext rockContext) { bool result = false; var fileInfo = new FileInfo(Server.MapPath("~/App_Data/Run.Migration")); if (fileInfo.Exists) { Database.SetInitializer(new MigrateDatabaseToLatestVersion <Rock.Data.RockContext, Rock.Migrations.Configuration>()); // explictly check if the database exists, and force create it if doesn't exist if (!rockContext.Database.Exists()) { // If database did not exist, initialize a database (which runs existing Rock migrations) rockContext.Database.Initialize(true); result = true; } else { // If database does exist, run any pending Rock migrations var migrator = new System.Data.Entity.Migrations.DbMigrator(new Rock.Migrations.Configuration()); if (migrator.GetPendingMigrations().Any()) { LogMessage(APP_LOG_FILENAME, "Migrating Database..."); migrator.Update(); result = true; } } fileInfo.Delete(); } else { // default Initializer is CreateDatabaseIfNotExists, but we don't want that to happen if automigrate is false, so set it to NULL so that nothing happens Database.SetInitializer <Rock.Data.RockContext>(null); } return(result); }
private void InitDatabases() { //debug AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve; var test = Devart.Data.MySql.Entity.MySqlEntityProviderServices.Instance; System.Data.Entity.DbConfiguration.Loaded += (sender, e) => e.ReplaceService <System.Data.Entity.Core.Common.DbProviderServices>( (services, o) => Devart.Data.MySql.Entity.MySqlEntityProviderServices.Instance ); try { LogHelper.Info("Start Code First Upgrade Database to latest......"); //必须留下下面这行,配置使用Devart数据生成MySQL的脚本 System.Data.Entity.Database.SetInitializer( //new System.Data.Entity.DropCreateDatabaseIfModelChanges<AtlanticDXContext>()); new DevartDbMigrationInitializer()); var config = new Migrations.Configuration(); using (AtlanticDXContext context = new AtlanticDXContext()) { System.Data.Entity.Migrations.DbMigrator migrator = new System.Data.Entity.Migrations.DbMigrator(config); config.TargetDatabase = new System.Data.Entity.Infrastructure.DbConnectionInfo( context.Database.Connection.ConnectionString, "Devart.Data.MySql"); var migrationsss = migrator.GetDatabaseMigrations(); var temp11 = migrator.GetLocalMigrations(); var temp22 = migrator.GetPendingMigrations(); temp22 = temp22.Except(migrationsss); if (temp22 != null && temp22.Count() > 0) { LogHelper.Info(string.Format("Start Code First force default migrations......")); migrator.Update(); LogHelper.Info("Finish Code First default migration. "); } else if (this.GetForceExternalSeedingFromConfig()) {//20150120 liangdawen: force to seed! LogHelper.Info(string.Format("Start Code First force Seeding external......")); migrator.Update(); LogHelper.Info("Finish Code First force Seeding external. "); } //20150131 custom migration seeding string[] upgrades = GetUpgradesFromConfig(); if (upgrades != null && upgrades.Length > 0) { LogHelper.Info(string.Format("Start Code First force custom seeds......")); foreach (var key in upgrades) { this.CustomMigration(key, migrator, config, context); LogHelper.Info(string.Format("Finish Code First custom seed: {0} .", key)); } LogHelper.Info("Finish Code First force custom seeds. "); } LogHelper.Info(string.Format("Code First Upgrade Database to latest completed.")); } } catch (Exception e) { string errMsg = "Start Code First Upgrade Database to latest Exception: " + e.Message + "\t\t" + e.StackTrace; if (e.InnerException != null) { errMsg += "\r\nInnerException: " + e.InnerException.Message + "\t\t" + e.InnerException.StackTrace; } LogHelper.Error(errMsg); } }
protected void Application_Start() { //Database.SetInitializer(new DbInitializer()); // new GmailBotDbContext().Database.Initialize(true); Database.SetInitializer(new System.Data.Entity.MigrateDatabaseToLatestVersion <GmailBotDbContext, Configuration>()); var configuration = new Configuration(); var migrator = new System.Data.Entity.Migrations.DbMigrator(configuration); if (migrator.GetPendingMigrations().Any()) { migrator.Update(); } AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); LogMaker.NewMessage += LogMaker_NewMessage; #pragma warning disable 618 #if !DEBUG && !WEBHOOK string clientSecretsStr = Encoding.UTF8.GetString(App_LocalResources.Tokens.client_secret); #else string clientSecretsStr = Encoding.UTF8.GetString(App_LocalResources.TokensTest.client_secret_debug); #endif var botSettings = new BotSettings(); var clienSecretsJtoken = JsonConvert.DeserializeObject <JToken>(clientSecretsStr); var clientSecrets = JsonConvert.DeserializeObject <Secrets>(clienSecretsJtoken["web"].ToString()); #if !DEBUG && !WEBHOOK botSettings.BotName = System.Configuration.ConfigurationSettings.AppSettings["Botname"]; botSettings.Token = App_LocalResources.Tokens.BotToken; botSettings.Topic = App_LocalResources.Tokens.TopicName; botSettings.ClientSecrets = clientSecrets; botSettings.Subscription = App_LocalResources.Tokens.Subscription; botSettings.ImagesPath = System.Configuration.ConfigurationSettings.AppSettings["ImagesPath"]; botSettings.DomainName = App_LocalResources.Tokens.DomainName; botSettings.AttachmentsTempFolder = Path.Combine(HttpRuntime.AppDomainAppPath, System.Configuration.ConfigurationSettings.AppSettings["AttachmentsTemp"]); botSettings.MaxAttachmentSize = int.Parse(System.Configuration.ConfigurationSettings.AppSettings["MaxAttachmentSize"]); botSettings.BotVersion = ReturnBotVersion(); botSettings.GmnbApiKey = App_LocalResources.Tokens.gmnbAPIKey; botSettings.ApplicationName = App_LocalResources.Tokens.ApplicationName; #else botSettings.BotName = System.Configuration.ConfigurationSettings.AppSettings["Botname"]; botSettings.Token = App_LocalResources.TokensTest.BotToken; botSettings.Topic = App_LocalResources.TokensTest.TopicName; botSettings.ClientSecrets = clientSecrets; botSettings.Subscription = App_LocalResources.TokensTest.Subscription; botSettings.ImagesPath = System.Configuration.ConfigurationSettings.AppSettings["ImagesPath"]; botSettings.DomainName = App_LocalResources.TokensTest.DomainName; botSettings.AttachmentsTempFolder = Path.Combine(HttpRuntime.AppDomainAppPath, System.Configuration.ConfigurationSettings.AppSettings["AttachmentsTemp"]); botSettings.MaxAttachmentSize = int.Parse(System.Configuration.ConfigurationSettings.AppSettings["MaxAttachmentSize"]); botSettings.BotVersion = ReturnBotVersion(); botSettings.GmnbApiKey = App_LocalResources.TokensTest.gmnbAPIKey; botSettings.ApplicationName = App_LocalResources.TokensTest.ApplicationName; #endif _botInitializer = BotInitializer.GetInstance(botSettings); #if DEBUG _botInitializer.InitializeUpdates(); #else _botInitializer.InitializeUpdates(true); #endif _botInitializer.InitializeUpdatesHandler(); _botInitializer.InitializeAuthotizer(); _botInitializer.InitializeServiceFactory(); _botInitializer.InitializeMessageHandler(); _botInitializer.InitializeCallbackQueryHandler(); _botInitializer.InitializeInlineQueryHandler(); _botInitializer.InitializeChosenInlineResultHandler(); #if (!WEBHOOK) _botInitializer.InitializeNotifyHandler(); #endif #if !DEBUG && !WEBHOOK _botInitializer.InitializePushNotificationWatchesAsync(initializeDelay); _botInitializer.InitializePushNotificationWatchTimer(_updatePeriod); #endif #pragma warning restore 618 }
/// <summary> /// Migrates the database. /// </summary> /// <returns>True if at least one migration was run</returns> public bool MigrateDatabase( RockContext rockContext ) { bool result = false; // default Initializer is CreateDatabaseIfNotExists, so set it to NULL so it doesn't try to do anything special Database.SetInitializer<Rock.Data.RockContext>( null ); var fileInfo = new FileInfo( Server.MapPath( "~/App_Data/Run.Migration" ) ); if ( fileInfo.Exists ) { // get the pendingmigrations sorted by name (in the order that they run), then run to the latest migration var migrator = new System.Data.Entity.Migrations.DbMigrator( new Rock.Migrations.Configuration() ); var pendingMigrations = migrator.GetPendingMigrations().OrderBy(a => a); if ( pendingMigrations.Any() ) { LogMessage( APP_LOG_FILENAME, "Migrating Database..." ); var lastMigration = pendingMigrations.Last(); // NOTE: we need to specify the last migration vs null so it won't detect/complain about pending changes migrator.Update( lastMigration ); result = true; } fileInfo.Delete(); } return result; }
/// <summary> /// Migrates the database. /// </summary> /// <returns>True if at least one migration was run</returns> public bool MigrateDatabase( RockContext rockContext ) { bool result = false; var fileInfo = new FileInfo( Server.MapPath( "~/App_Data/Run.Migration" ) ); if ( fileInfo.Exists ) { Database.SetInitializer( new MigrateDatabaseToLatestVersion<Rock.Data.RockContext, Rock.Migrations.Configuration>() ); // explictly check if the database exists, and force create it if doesn't exist if ( !rockContext.Database.Exists() ) { // If database did not exist, initialize a database (which runs existing Rock migrations) rockContext.Database.Initialize( true ); result = true; } else { // If database does exist, run any pending Rock migrations var migrator = new System.Data.Entity.Migrations.DbMigrator( new Rock.Migrations.Configuration() ); if ( migrator.GetPendingMigrations().Any() ) { migrator.Update(); result = true; } } fileInfo.Delete(); } else { // default Initializer is CreateDatabaseIfNotExists, but we don't want that to happen if automigrate is false, so set it to NULL so that nothing happens Database.SetInitializer<Rock.Data.RockContext>( null ); } // Migrate any plugins that have pending migrations List<Type> migrationList = Rock.Reflection.FindTypes( typeof( Migration ) ).Select( a => a.Value ).ToList(); // If any plugin migrations types were found if ( migrationList.Any() ) { // Create EF service for plugin migrations var pluginMigrationService = new PluginMigrationService( rockContext ); // Get the current rock version var rockVersion = new Version( Rock.VersionInfo.VersionInfo.GetRockProductVersionNumber() ); // Create dictionary for holding migrations specific to an assembly var assemblies = new Dictionary<string, Dictionary<int, Type>>(); // Iterate plugin migrations foreach ( var migrationType in migrationList ) { // Get the MigrationNumberAttribute for the migration var migrationNumberAttr = System.Attribute.GetCustomAttribute( migrationType, typeof( MigrationNumberAttribute ) ) as MigrationNumberAttribute; if ( migrationNumberAttr != null ) { // If the migration's minimum Rock version is less than or equal to the current rock version, add it to the list var minRockVersion = new Version( migrationNumberAttr.MinimumRockVersion ); if ( minRockVersion.CompareTo( rockVersion ) <= 0 ) { string assemblyName = migrationType.Assembly.GetName().Name; if ( !assemblies.ContainsKey( assemblyName ) ) { assemblies.Add( assemblyName, new Dictionary<int, Type>() ); } assemblies[assemblyName].Add( migrationNumberAttr.Number, migrationType ); } } } var configConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["RockContext"]; if ( configConnectionString != null ) { string connectionString = configConnectionString.ConnectionString; if ( !string.IsNullOrWhiteSpace( connectionString ) ) { using ( SqlConnection con = new SqlConnection( connectionString ) ) { con.Open(); // Iterate each assembly that contains plugin migrations foreach ( var assemblyMigrations in assemblies ) { try { // Get the versions that have already been installed var installedVersions = pluginMigrationService.Queryable() .Where( m => m.PluginAssemblyName == assemblyMigrations.Key ) .ToList(); // Iterate each migration in the assembly in MigrationNumber order foreach ( var migrationType in assemblyMigrations.Value.OrderBy( t => t.Key ) ) { // Check to make sure migration has not already been run if ( !installedVersions.Any( v => v.MigrationNumber == migrationType.Key ) ) { using ( var sqlTxn = con.BeginTransaction() ) { bool transactionActive = true; try { // Create an instance of the migration and run the up migration var migration = Activator.CreateInstance( migrationType.Value ) as Rock.Plugin.Migration; migration.SqlConnection = con; migration.SqlTransaction = sqlTxn; migration.Up(); sqlTxn.Commit(); transactionActive = false; // Save the plugin migration version so that it is not run again var pluginMigration = new PluginMigration(); pluginMigration.PluginAssemblyName = assemblyMigrations.Key; pluginMigration.MigrationNumber = migrationType.Key; pluginMigration.MigrationName = migrationType.Value.Name; pluginMigrationService.Add( pluginMigration ); rockContext.SaveChanges(); result = true; } catch ( Exception ex ) { if ( transactionActive ) { sqlTxn.Rollback(); } throw new Exception( string.Format( "Plugin Migration error occurred in {0}, {1}", assemblyMigrations.Key, migrationType.Value.Name ), ex ); } } } } } catch ( Exception ex ) { // If an exception occurs in an an assembly, log the error, and continue with next assembly LogError( ex, null ); } } } } } } return result; }
/// <summary> /// Migrates the database. /// </summary> /// <returns>True if at least one migration was run</returns> public bool MigrateDatabase( RockContext rockContext ) { bool result = false; var fileInfo = new FileInfo( Server.MapPath( "~/App_Data/Run.Migration" ) ); if ( fileInfo.Exists ) { Database.SetInitializer( new MigrateDatabaseToLatestVersion<Rock.Data.RockContext, Rock.Migrations.Configuration>() ); // explictly check if the database exists, and force create it if doesn't exist if ( !rockContext.Database.Exists() ) { // If database did not exist, initialize a database (which runs existing Rock migrations) rockContext.Database.Initialize( true ); result = true; } else { // If database does exist, run any pending Rock migrations var migrator = new System.Data.Entity.Migrations.DbMigrator( new Rock.Migrations.Configuration() ); if ( migrator.GetPendingMigrations().Any() ) { LogMessage( APP_LOG_FILENAME, "Migrating Database..." ); migrator.Update(); result = true; } } fileInfo.Delete(); } else { // default Initializer is CreateDatabaseIfNotExists, but we don't want that to happen if automigrate is false, so set it to NULL so that nothing happens Database.SetInitializer<Rock.Data.RockContext>( null ); } return result; }
private void InitializeDataStore() { System.Data.Entity.Database.SetInitializer(new System.Data.Entity.MigrateDatabaseToLatestVersion<GalleryDb, GalleryDbMigrationConfiguration>()); var configuration = new GalleryDbMigrationConfiguration(ProviderDataStore); var migrator = new System.Data.Entity.Migrations.DbMigrator(configuration); if (migrator.GetPendingMigrations().Any()) { migrator.Update(); } }