Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jamiepollock/f1eac7cf5bae615d8746d97246757b83 to your computer and use it in GitHub Desktop.
Save jamiepollock/f1eac7cf5bae615d8746d97246757b83 to your computer and use it in GitHub Desktop.
Code to represent using custom Umbraco Migrations with Umbraco v7.3.0
using System;
using Umbraco.Core.Logging;
using Umbraco.Core.Persistence;
using Umbraco.Core.Persistence.Migrations;
using Umbraco.Core.Persistence.SqlSyntax;
namespace MyApp.Migrations
{
[Migration("1.1.0", 1, MyCustomSectionMigrationConstants.ProductName)]
public class AddCustomPropertyToBeAddedLaterToMyPocoTable : MigrationBase
{
protected readonly Database _database;
protected readonly DatabaseSchemaHelper _schemaHelper;
protected readonly ILogger _logger;
public AddCustomPropertyToBeAddedLaterToMyPocoTable(ISqlSyntaxProvider sqlSyntax, ILogger logger) : base(sqlSyntax, logger)
{
_database = new Database(MyCustomSectionApplicationContext.Instance.DatabaseSettings.ConnectionString,
MyCustomSectionApplicationContext.Instance.DatabaseSettings.ProviderName);
_schemaHelper = new DatabaseSchemaHelper(_database, logger, sqlSyntax);
_logger = logger;
}
public override void Up()
{
//Check to make code environment proof. Some environments which do not have the property will evaluate false
if (CheckIfColumnExists(MyCustomSectionDatabaseTableNames.MyPoco, "CustomPropertyToBeAddedLater") == false)
{
Alter.Table(MyCustomSectionDatabaseTableNames.MyPoco).AddColumn("CustomPropertyToBeAddedLater").AsString().WithDefaultValue("Default Text");
}
}
public override void Down()
{
Delete.Column("CustomPropertyToBeAddedLater").FromTable(MyCustomSectionDatabaseTableNames.MyPoco);
}
protected bool CheckIfColumnExists(string tableName, string columnName)
{
var columns = SqlSyntax.GetColumnsInSchema(_database);
var doesColumnExist =
columns.Any(
x =>
string.Equals(x.TableName, tableName) &&
string.Equals(x.ColumnName, columnName)
);
return doesColumnExist;
}
}
}
using MyApp.Models;
using Umbraco.Core.Logging;
using Umbraco.Core.Persistence.Migrations;
using Umbraco.Core.Persistence.SqlSyntax;
namespace MyApp.Migrations
{
[Migration("1.0.0", 1, MyCustomSectionMigrationConstants.ProductName)]
public class CreateMyPocoTable : MigrationBase
{
protected readonly Database _database;
protected readonly DatabaseSchemaHelper _schemaHelper;
protected readonly ILogger _logger;
protected CreateMyPocoTable(ISqlSyntaxProvider sqlSyntax, ILogger logger) : base(sqlSyntax, logger)
{
_database = new Database(MyCustomSectionApplicationContext.Instance.DatabaseSettings.ConnectionString,
MyCustomSectionApplicationContext.Instance.DatabaseSettings.ProviderName);
_schemaHelper = new DatabaseSchemaHelper(_database, logger, sqlSyntax);
_logger = logger;
}
public override void Up()
{
if (CheckTableExists() == false)
{
_schemaHelper.CreateTable<MyPoco>(false);
var message = string.Format("Created table for {0}.", typeof(MyPoco));
_logger.Info<CreateMyPocoTable>(message);
}
else
{
var message = string.Format("Skipped creating table for {0}. It already exists", typeof(MyPoco));
_logger.Info<CreateMyPocoTable>(message);
}
}
public override void Down()
{
if (CheckTableExists())
{
_schemaHelper.DropTable<MyPoco>();
var message = string.Format("Dropped table for {0}.", typeof(MyPoco));
_logger.Info<CreateMyPocoTable>(message);
}
else
{
var message = string.Format("Skipped dropping table for {0}. It does not exist.", typeof(MyPoco));
_logger.Info<CreateMyPocoTable>(message);
}
}
protected bool CheckTableExists()
{
var type = typeof(MyPoco);
var tableNameAttribute = type.GetCustomAttribute<TableNameAttribute>(false);
if (tableNameAttribute != null)
{
return _schemaHelper.TableExist(tableNameAttribute.Value);
}
return false;
}
}
}
using System;
using System.Configuration;
using System.Linq;
using System.Web;
using Semver;
using MyApp.Migrations;
using MyApp.Models;
using MyApp.Services;
using Umbraco.Core;
using Umbraco.Core.Logging;
using Umbraco.Core.Persistence;
using Umbraco.Core.Persistence.Migrations;
using Umbraco.Web;
namespace MyApp.Events
{
public class MyCustomSectionAppBootManager : ApplicationEventHandler
{
protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
{
var connectionString = ConfigurationManager.ConnectionStrings["MyCustomSectionDbDSN"];
MyCustomSectionApplicationContext.Instance = new MyCustomSectionApplicationContext(connectionString, applicationContext.ProfilingLogger.Logger);
var rawTargetVersion = ConfigurationManager.AppSettings["MyCustomSectionApplication:MigrationVersion"] ?? "1.0.0";
var targetVersion = SemVersion.Parse(rawTargetVersion);
if (targetVersion != null)
{
HandleMigrations(targetVersion);
}
base.ApplicationStarted(umbracoApplication, applicationContext);
}
private static void HandleMigrations(SemVersion targetVersion)
{
var currentVersion = new SemVersion(0, 0, 0);
var migrations = ApplicationContext.Current.Services.MigrationEntryService.GetAll(MigrationConstants.ProductName);
var latestMigration = migrations.OrderByDescending(x => x.Version).FirstOrDefault();
if (latestMigration != null)
{
currentVersion = latestMigration.Version;
}
if (targetVersion == currentVersion)
{
return;
}
var migrationsRunner = new MigrationRunner(
ApplicationContext.Current.Services.MigrationEntryService,
ApplicationContext.Current.ProfilingLogger.Logger,
currentVersion,
targetVersion,
MyCustomSectionMigrationConstants.ProductName);
try
{
using (
var db = new Database(MyCustomSectionApplicationContext.Instance.DatabaseSettings.ConnectionString,
MyCustomSectionApplicationContext.Instance.DatabaseSettings.ProviderName))
{
migrationsRunner.Execute(db);
}
}
catch (HttpException httpex)
{
LogHelper.Error<MyCustomSectionAppBootManager>("HttpException Error running MyCustomSectionAppBootManager migration", httpex);
}
catch (Exception e)
{
LogHelper.Error<MyCustomSectionAppBootManager>("Exception Error running MyCustomSectionAppBootManager migration", e);
}
}
}
}
using Newtonsoft.Json;
using System;
using Umbraco.Core.Persistence;
using Umbraco.Core.Persistence.DatabaseAnnotations;
namespace MyApp.Models
{
//Note: DB table may or may not exist depending on environment
[TableName(MyCustomSectionDatabaseTableNames.MyPoco)]
[PrimaryKey("Id", autoIncrement = true)]
public class MyPoco
{
[PrimaryKeyColumn(AutoIncrement = true)]
public int Id { get; set; }
//Note: Poco property stored in code but until 1.1.0 Migration has run the property may not exist in the DB table
public string CustomPropertyToBeAddedLater { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment