public void VerifyThatMigrationVersionsWork()
        {
            MigrationEngine.Reset();

            MigrationEngine.Migrate(excludes: new List <string>()
            {
                "BadMigration", "BadSeed", "BadSave", "BadReverse"
            });

            Assert.IsTrue(DatabaseSession.Instance.Connector.CheckTableExists(new MigrationRecord()));
            Assert.AreEqual(4, MigrationRecord.All().Count);

            MigrationEngine.ResetTo(new Version(1, 0, 0));

            Assert.AreEqual(3, MigrationRecord.All().Count);

            MigrationEngine.Reset();

            MigrationEngine.Migrate(excludes: new List <string>()
            {
                "BadMigration", "BadSeed", "BadSave"
            });

            Assert.IsTrue(DatabaseSession.Instance.Connector.CheckTableExists(new MigrationRecord()));
            Assert.AreEqual(5, MigrationRecord.All().Count);

            var migrationDeleteBase = new BadMigration();

            Assert.Throws <InvalidDataException>(() => migrationDeleteBase.Delete());

            Assert.Throws <Exception>(() => MigrationEngine.ResetTo(new Version(0, 0, 0)));

            MigrationEngine.Reset(hard: true);
            Assert.IsFalse(DatabaseSession.Instance.Connector.CheckTableExists(new MigrationRecord()));
        }
Example #2
0
 /// <summary>
 /// The on upgraded.
 /// </summary>
 /// <param name="record">
 /// The record.
 /// </param>
 private void OnUpgraded(MigrationRecord record)
 {
     if (Upgraded != null)
     {
         Upgraded(this, new MerchelloMigrationEventArgs(record));
     }
 }
Example #3
0
        /// <summary>
        /// The post analytic info.
        /// </summary>
        /// <param name="record">
        /// The record.
        /// </param>
        public async void PostAnalyticInfo(MigrationRecord record)
        {
            if (!MerchelloConfiguration.Current.Section.EnableInstallTracking)
            {
                return;
            }
            var client = new HttpClient();

            try
            {
                var data = JsonConvert.SerializeObject(record);
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                await client.PostAsync(PostUrl, new StringContent(data, Encoding.UTF8, "application/json"));
            }
            catch (Exception ex)
            {
                LogHelper.Error <WebMigrationManager>("Migration record post exception", ex);
            }
            finally
            {
                if (client != null)
                {
                    client.Dispose();
                    client = null;
                }
            }
        }
Example #4
0
        /// <summary>
        /// The method that executes to apply a migration.
        /// </summary>
        public override void Migrate()
        {
            var migrationTableTemplate = new MigrationRecord();

            DatabaseSession.Instance.Connector.CreateTable(migrationTableTemplate);

            foreach (var property in migrationTableTemplate.GetType().GetProperties().Where(p => !CustomAttributeExtensions.IsDefined(p, typeof(IgnoreDataMemberAttribute))).ToList())
            {
                DatabaseSession.Instance.Connector.CreateColumn(property, migrationTableTemplate);
            }

            DatabaseSession.Instance.Connector.CreatePrimaryKeyConstraint(migrationTableTemplate);
        }
 public MigrationNode(MigrationRootNode root, VM target, Server reciever, bool turnOnNew = false)
 {
     _root   = root;
     Changes = new MigrationRecord[1] {
         new MigrationRecord(target, reciever, _root.TargetServer)
     };
     IsValid = CalculateValidity();
     if (turnOnNew)
     {
         _turnOnCount = 1;
     }
     _value = CalculateValue(root, turnOnNew);
 }
Example #6
0
        public void Save_InsertsNewRecord_IfItDidNotExist()
        {
            var record = new MigrationRecord {
                Version      = Guid.NewGuid().ToString("N"),
                Name         = "Test",
                DateExecuted = DateTime.Now
            };

            MigrationRecords.Save(new[] { record });

            var found = MigrationRecords.GetAll().SingleOrDefault(r => r.Version == record.Version);

            Assert.IsNotNull(found);
        }
        /// <summary>
        /// Posts the migration analytic record.
        /// </summary>
        /// <param name="record">
        /// The record.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        public async Task <HttpResponseMessage> PostAnalyticInfo(MigrationRecord record)
        {
            if (!MerchelloConfiguration.Current.Section.EnableInstallTracking)
            {
                return(new HttpResponseMessage(HttpStatusCode.OK));
            }

            // reset the domain analytic
            if (MerchelloContext.HasCurrent)
            {
                var storeSettingService = MerchelloContext.Current.Services.StoreSettingService;

                var setting = storeSettingService.GetByKey(Constants.StoreSetting.HasDomainRecordKey);
                if (setting != null)
                {
                    setting.Value = false.ToString();
                }

                storeSettingService.Save(setting);
            }

            var data = JsonConvert.SerializeObject(record);

            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                HttpResponseMessage responseMessage = null;
                try
                {
                    responseMessage = await client.PostAsync(PostUrl, new StringContent(data, Encoding.UTF8, "application/json"));
                }
                catch (Exception ex)
                {
                    if (responseMessage == null)
                    {
                        responseMessage = new HttpResponseMessage();
                    }

                    responseMessage.StatusCode   = HttpStatusCode.InternalServerError;
                    responseMessage.ReasonPhrase = string.Format("PostAnalyticInfo failed: {0}", ex);
                }

                return(responseMessage);
            }
        }
Example #8
0
        protected void DoUpdateMigrationRecord(IDataMigration dataMigration)
        {
            MigrationRecord record = _migrationRecordRepository.Get(m => m.TableName == dataMigration.TableName);

            if (record == null)
            {
                record = new MigrationRecord
                {
                    TableName = dataMigration.TableName
                };
            }

            record.Version = dataMigration.Version;

            Logger.Debug("DataMigrationManager", "Migrate {0} to version:{1}", record.TableName, record.Version);
            _migrationRecordRepository.CreateOrUpdate(record);
        }
Example #9
0
        public void Save_UpdatesExistingRecord()
        {
            var record = new MigrationRecord {
                Version      = Guid.NewGuid().ToString("N"),
                Name         = "Old",
                DateExecuted = DateTime.Now
            };

            MigrationRecords.SaveNew(record);

            record.Name = "New";
            MigrationRecords.Save(new[] { record });

            var reloaded = MigrationRecords.GetAll().Single(r => r.Version == record.Version);

            Assert.AreEqual("New", reloaded.Name);
        }
Example #10
0
        /// <summary>
        /// Executes the Migration runner.
        /// </summary>
        /// <param name="database">
        /// The database.
        /// </param>
        /// <returns>
        /// A value indicating whether or not the migration was successful.
        /// </returns>
        private bool UpgradeMerchello(Database database)
        {
            var databaseSchemaCreation = new DatabaseSchemaCreation(database);
            var schemaResult           = databaseSchemaCreation.ValidateSchema();
            var dbVersion = schemaResult.DetermineInstalledVersion();

            if (dbVersion != MerchelloVersion.Current)
            {
                try
                {
                    LogHelper.Info <CoreMigrationManager>("Merchello database upgraded required.  Initializing Upgrade.");
                    var runner = new MigrationRunner(
                        MerchelloConfiguration.ConfigurationStatusVersion,
                        MerchelloVersion.Current,
                        MerchelloConfiguration.MerchelloMigrationName);
                    var upgraded = runner.Execute(database);
                    if (upgraded)
                    {
                        var migrationKey = this.EnsureMigrationKey(schemaResult);

                        var record = new MigrationRecord()
                        {
                            MigrationKey   = migrationKey,
                            CurrentVersion = dbVersion.ToString(),
                            TargetVersion  = MerchelloVersion.Current.ToString(),
                            DbProvider     = database.GetDatabaseProvider().ToString(),
                            InstallDate    = DateTime.Now,
                            IsUpgrade      = true
                        };

                        this.OnUpgraded(record);

                        LogHelper.Info <CoreMigrationManager>("Merchello Schema Migration completed successfully");
                    }

                    LogHelper.Debug <CoreMigrationManager>("Merchello migration runner returned false.");
                }
                catch (Exception ex)
                {
                    LogHelper.Error <CoreMigrationManager>("Merchello Database Schema Upgrade Failed", ex);
                    throw;
                }
            }
            else
            {
                // this is a new install
                var migrationKey = this.EnsureMigrationKey(schemaResult);

                var record = new MigrationRecord()
                {
                    MigrationKey   = migrationKey,
                    CurrentVersion = MerchelloConfiguration.ConfigurationStatus,
                    TargetVersion  = MerchelloVersion.Current.ToString(),
                    DbProvider     = database.GetDatabaseProvider().ToString(),
                    InstallDate    = DateTime.Now,
                    IsUpgrade      = !MerchelloConfiguration.ConfigurationStatus.Equals("0.0.0")
                };
                this.OnUpgraded(record);
            }

            MerchelloConfiguration.ConfigurationStatus = MerchelloVersion.Current.ToString();

            return(true);
        }
        /// <summary>
        /// Executes the Migration runner.
        /// </summary>
        /// <param name="database">
        /// The database.
        /// </param>
        /// <returns>
        /// A value indicating whether or not the migration was successful.
        /// </returns>
        private bool UpgradeMerchello(Database database)
        {
            var databaseSchemaCreation = new DatabaseSchemaCreation(_database, _logger, new DatabaseSchemaHelper(_database, _logger, _sqlSyntaxProvider), _sqlSyntaxProvider);
            var schemaResult           = databaseSchemaCreation.ValidateSchema();
            var dbVersion = schemaResult.DetermineInstalledVersion();

            var upgraded = false;

            if (dbVersion != MerchelloVersion.Current)
            {
                try
                {
                    _logger.Info <CoreMigrationManager>("Merchello database upgraded required.  Initializing Upgrade.");

                    var resolver = new MigrationResolver(_logger, PluginManager.Current.ResolveMerchelloMigrations());

                    var migrations = resolver.OrderedUpgradeMigrations(
                        MerchelloConfiguration.ConfigurationStatusVersion,
                        MerchelloVersion.Current).ToList();

                    var context = InitializeMigrations(migrations, _database, _database.GetDatabaseProvider());

                    try
                    {
                        ExecuteMigrations(context, _database);

                        upgraded = true;
                    }
                    catch (Exception ex)
                    {
                        _logger.Error <CoreMigrationManager>("Merchello migration failed", ex);
                        upgraded = false;
                    }


                    _logger.Debug <CoreMigrationManager>("Merchello migration runner returned false.");
                }
                catch (Exception ex)
                {
                    _logger.Error <CoreMigrationManager>("Merchello Database Schema Upgrade Failed", ex);
                    throw;
                }
            }

            var currentVersion = dbVersion.ToString();

            if (!upgraded)
            {
                currentVersion = MerchelloConfiguration.ConfigurationStatusVersion.ToString();
            }

            var migrationKey = this.EnsureMigrationKey(schemaResult);

            var record = new MigrationRecord()
            {
                MigrationKey   = migrationKey,
                CurrentVersion = currentVersion,
                TargetVersion  = MerchelloVersion.Current.ToString(),
                DbProvider     = database.GetDatabaseProvider().ToString(),
                InstallDate    = DateTime.Now,
                IsUpgrade      = currentVersion != "0.0.0"
            };

            this.OnUpgraded(record);

            _logger.Info <CoreMigrationManager>("Merchello Schema Migration completed successfully");

            MerchelloConfiguration.ConfigurationStatus = MerchelloVersion.Current.ToString();

            return(true);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="MerchelloMigrationEventArgs"/> class.
 /// </summary>
 /// <param name="record">
 /// The record.
 /// </param>
 public MerchelloMigrationEventArgs(MigrationRecord record)
 {
     MigrationRecord = record;
 }
Example #13
0
        /// <summary>
        /// Checks whether the migration should execute.
        /// </summary>
        /// <returns>True if the migration should run.</returns>
        public override bool ShouldMigrate()
        {
            var migrationTableTemplate = new MigrationRecord();

            return(!DatabaseSession.Instance.Connector.CheckTableExists(migrationTableTemplate));
        }
Example #14
0
        /// <summary>
        /// The method that executes if a migration needs to be rolled back.
        /// </summary>
        public override void Reverse()
        {
            var migrationTableTemplate = new MigrationRecord();

            DatabaseSession.Instance.Connector.DeleteTable(migrationTableTemplate);
        }
Example #15
0
        //[Test]
        public void Can_CreateAMigrationRecord()
        {
            var record = new MigrationRecord();

            Assert.NotNull(record);
        }
Example #16
0
        /// <summary>
        /// Executes the Migration runner.
        /// </summary>
        /// <param name="database">
        /// The database.
        /// </param>
        /// <returns>
        /// A value indicating whether or not the migration was successful.
        /// </returns>
        private bool UpgradeMerchello(Database database)
        {
            var databaseSchemaCreation = new DatabaseSchemaCreation(_database, _logger, new DatabaseSchemaHelper(_database, _logger, _sqlSyntaxProvider), _sqlSyntaxProvider);
            var schemaResult           = databaseSchemaCreation.ValidateSchema();
            var dbVersion = schemaResult.DetermineInstalledVersion();

            if (dbVersion != MerchelloVersion.Current)
            {
                try
                {
                    _logger.Info <CoreMigrationManager>("Merchello database upgraded required.  Initializing Upgrade.");

                    var resolver = new MigrationResolver(_logger, PluginManager.Current.ResolveMerchelloMigrations());

                    var migrations = resolver.OrderedUpgradeMigrations(
                        MerchelloConfiguration.ConfigurationStatusVersion,
                        MerchelloVersion.Current);

                    bool upgraded;
                    try
                    {
                        foreach (var m in migrations)
                        {
                            m.Up();
                        }

                        upgraded = true;
                    }
                    catch (Exception ex)
                    {
                        _logger.Error <CoreMigrationManager>("Merchello migration failed", ex);
                        upgraded = false;
                    }


                    //var entryService = ApplicationContext.Current.Services.MigrationEntryService;


                    //var runner = new MigrationRunner(
                    //    entryService,
                    //    _logger,
                    //    new SemVersion(MerchelloConfiguration.ConfigurationStatusVersion),
                    //    new SemVersion(MerchelloVersion.Current),
                    //    MerchelloConfiguration.MerchelloMigrationName);

                    //var upgraded = runner.Execute(database);

                    if (upgraded)
                    {
                        var migrationKey = this.EnsureMigrationKey(schemaResult);

                        var record = new MigrationRecord()
                        {
                            MigrationKey   = migrationKey,
                            CurrentVersion = dbVersion.ToString(),
                            TargetVersion  = MerchelloVersion.Current.ToString(),
                            DbProvider     = database.GetDatabaseProvider().ToString(),
                            InstallDate    = DateTime.Now,
                            IsUpgrade      = true
                        };

                        this.OnUpgraded(record);

                        _logger.Info <CoreMigrationManager>("Merchello Schema Migration completed successfully");
                    }

                    _logger.Debug <CoreMigrationManager>("Merchello migration runner returned false.");
                }
                catch (Exception ex)
                {
                    _logger.Error <CoreMigrationManager>("Merchello Database Schema Upgrade Failed", ex);
                    throw;
                }
            }
            else
            {
                // this is a new install
                var migrationKey = this.EnsureMigrationKey(schemaResult);

                var record = new MigrationRecord()
                {
                    MigrationKey   = migrationKey,
                    CurrentVersion = MerchelloConfiguration.ConfigurationStatus,
                    TargetVersion  = MerchelloVersion.Current.ToString(),
                    DbProvider     = database.GetDatabaseProvider().ToString(),
                    InstallDate    = DateTime.Now,
                    IsUpgrade      = !MerchelloConfiguration.ConfigurationStatus.Equals("0.0.0")
                };
                this.OnUpgraded(record);
            }

            MerchelloConfiguration.ConfigurationStatus = MerchelloVersion.Current.ToString();

            return(true);
        }