Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save codeprogression/1068888 to your computer and use it in GitHub Desktop.

Select an option

Save codeprogression/1068888 to your computer and use it in GitHub Desktop.
RoundhousE RefreshDatabase.fnh with Automapping
<?xml version="1.0"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
<appSettings>
<add key="IsInitialDevelopment" value="true"/>
<add key="RepositoryPath" value=""/>
<add key="VersionFile" value=""/>
<add key="RestoreDuringMaintenance" value="false"/>
<add key="RestoreFromPath" value=""/>
<!-- <add key="NameOfInitialScript" value=""/>-->
<!-- <add key="NameOfUpdateScript" value=""/>-->
<!-- <add key="SqlFilesDirctory" value=""/>-->
</appSettings>
<connectionStrings configSource="connectionStrings.config" />
</configuration>
<connectionStrings>
<add name="LOCAL" connectionString="data source=(local);Integrated Security=SSPI;Initial Catalog=[Local Database]"/>
<add name="PROD" connectionString="Server=[server];Database=[database];User ID=[userid];Password=[password];"/>
</connectionStrings>
<!-- Set "Copy to Output Directory" to "Copy Always" -->
// ==============================================================================
//
// Fervent Coder Copyright © 2011 - Released under the Apache 2.0 License
//
// Adaption by Code Progression Copyright © 2011 - Released under the Apache 2.0 License
//
// Copyright 2007-2008 The Apache Software Foundation.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
// ==============================================================================
using CP.Infrastructure.Persistence.Configuration;
namespace CP.Migrations
{
using System.IO;
using System.Text;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;
using roundhouse;
using roundhouse.infrastructure.app;
public class DifferenceWithFluentNHibernate
{
private static string path_to_sql_scripts_up_folder;
private static string name_of_script_to_create;
readonly RoundhousESessionFactory _sessionFactory = new RoundhousESessionFactory(new[] { new EntityAutoPersistenceModelConfiguration() });
/// <summary>
/// Set up your migrator and call this to generate a diff file. Known limitations - will not detect size changes or renames. In other words, destructive changes will need to be done by hand.
/// </summary>
/// <param name="diffingType">Are you in greenfield development or have you went to production (maintenance)? Do you want it to restore during maintenance mode?</param>
/// <param name="nameOfOutputScriptToCreateOrReplace">This is something like 0001_CreateTables.sql. This will end up in your up folder, assuming you have set up your migrator configuration correctly.</param>
/// <param name="databaseMigrator">The Migrator to use when running.</param>
/// <param name="mappingsAssembly">This is the assembly that contains your mapping files.</param>
/// <param name="conventionsAssembly">This is the assembly that contains your conventions. If you do not have conventions set up, just pass null. It will use the mappingsAssembly</param>
public void Run(RoundhousEFluentNHDiffingType diffingType, string nameOfOutputScriptToCreateOrReplace, Migrate databaseMigrator)
{
name_of_script_to_create = nameOfOutputScriptToCreateOrReplace;
var configuration = databaseMigrator.GetConfiguration();
configuration.Silent = true;
configuration.Restore = false;
ApplicationConfiguraton.set_defaults_if_properties_are_not_set(configuration);
path_to_sql_scripts_up_folder = Path.Combine(configuration.SqlFilesDirectory, configuration.UpFolderName);
switch (diffingType)
{
case RoundhousEFluentNHDiffingType.InitialDevelopment:
run_initial_database_setup(databaseMigrator, configuration);
break;
case RoundhousEFluentNHDiffingType.Maintenance:
run_maintenance_database_setup(false, databaseMigrator, configuration);
break;
case RoundhousEFluentNHDiffingType.MaintenanceWithRestore:
run_maintenance_database_setup(true, databaseMigrator, configuration);
break;
}
}
private void run_initial_database_setup(Migrate migrator, ConfigurationPropertyHolder configuration)
{
var files_directory = configuration.SqlFilesDirectory;
configuration.SqlFilesDirectory = ".";
migrator.Run();
generate_database_schema(configuration);
configuration.SqlFilesDirectory = files_directory;
migrator.RunDropCreate();
}
private void generate_database_schema(ConfigurationPropertyHolder configuration)
{
_sessionFactory.CreateSessionFactory(configuration, generate_the_schema);
}
private void generate_the_schema(Configuration cfg)
{
var s = new SchemaExport(cfg);
s.SetOutputFile(Path.Combine(path_to_sql_scripts_up_folder, name_of_script_to_create));
s.Create(true, false);
}
private void run_maintenance_database_setup(bool restoring_the_database, Migrate migrator, ConfigurationPropertyHolder configuration)
{
if (restoring_the_database)
{
configuration.Restore = true;
migrator.RunRestore();
}
upgrade_database_schema(configuration);
configuration.Restore = false;
migrator.Run();
}
private void upgrade_database_schema(ConfigurationPropertyHolder configuration)
{
_sessionFactory.CreateSessionFactory(configuration, update_the_schema);
}
private void update_the_schema(Configuration cfg)
{
var s = new SchemaUpdate(cfg);
var sb = new StringBuilder();
s.Execute(x => sb.Append(x), false);
var updateScriptFileName = Path.Combine(path_to_sql_scripts_up_folder, name_of_script_to_create);
if (File.Exists(updateScriptFileName))
{
File.Delete(updateScriptFileName);
}
File.WriteAllText(updateScriptFileName, sb.ToString());
}
}
}
// ==============================================================================
//
// Code Progression Copyright © 2011 - Released under the Apache 2.0 License
//
// Copyright 2007-2008 The Apache Software Foundation.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
// ==============================================================================
using CP.Infrastructure.Types;
using FluentNHibernate.Automapping;
namespace CP.Infrastructure.Persistence.Configuration
{
public class EntityAutoPersistenceModelConfiguration : IAutoPersistenceModelConfiguration
{
public AutoPersistenceModel GetModel()
{
return AutoMap
.AssemblyOf<Entity>(new EntityAutoMappingConfiguration())
.IgnoreBase<Entity>()
.UseOverridesFromAssemblyOf<Entity>()
.Conventions.AddFromAssemblyOf<Entity>()
.OverrideAll(x => x.IgnoreProperties(p => !p.CanWrite));
}
}
public class EntityAutoMappingConfiguration : DefaultAutomappingConfiguration
{
public override bool ShouldMap(Type type)
{
return type.GetInterfaces().Contains(typeof (IPersistable));
}
public override bool IsComponent(Type type)
{
return type.GetInterfaces().Contains(typeof (IComponent));
}
public override string GetComponentColumnPrefix(FluentNHibernate.Member member)
{
return member.Name.Replace(member.PropertyType.Name, "") + "";
}
}
public interface IAutoPersistenceModelConfiguration
{
AutoPersistenceModel GetModel();
}
public interface IFluentMappingConfiguration
{
FluentMappingsContainer Configure(FluentMappingsContainer fluentMappings);
}
public interface IHbmMappingConfiguration
{
HbmMappingsContainer Configure(HbmMappingsContainer hbmMappings);
}
}
// ==============================================================================
//
// Code Progression Copyright © 2011 - Released under the Apache 2.0 License
//
// Copyright 2007-2008 The Apache Software Foundation.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
// ==============================================================================
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Tool.hbm2ddl;
namespace CP.Infrastructure.Persistence.Configuration
{
public class NHibernateConfiguration
{
readonly IEnumerable<IAutoPersistenceModelConfiguration> _models;
readonly IEnumerable<IFluentMappingConfiguration> _fluentMappings;
readonly IEnumerable<IHbmMappingConfiguration> _hbmMappings;
public NHibernateConfiguration() : this(null,null,null) {}
public NHibernateConfiguration(IEnumerable<IAutoPersistenceModelConfiguration> models) : this(models,null,null) {}
public NHibernateConfiguration(IEnumerable<IAutoPersistenceModelConfiguration> models, IEnumerable<IFluentMappingConfiguration> fluentMappings, IEnumerable<IHbmMappingConfiguration> hbmMappings)
{
_models = models??new List<IAutoPersistenceModelConfiguration>();
_fluentMappings = fluentMappings ?? new List<IFluentMappingConfiguration>();
_hbmMappings = hbmMappings ?? new List<IHbmMappingConfiguration>();
}
protected ISessionFactory SessionFactory;
protected NHibernate.Cfg.Configuration SchemaConfig;
public ISessionFactory CreateSessionFactory()
{
SessionFactory = CreateSessionFactory(GetSqlConfiguration(), BuildSchema);
return SessionFactory;
}
protected virtual Func<IPersistenceConfigurer> GetSqlConfiguration()
{
var msSql2005 = MsSqlConfiguration.MsSql2008;
Action<MsSqlConnectionStringBuilder> expression =
c => c.FromConnectionStringWithKey(DatabaseConstants.SettlersConnectionStringKey);
return () => msSql2005.ConnectionString(expression)
.UseReflectionOptimizer()
.IsolationLevel(IsolationLevel.ReadUncommitted)
.ShowSql();
}
public virtual ISessionFactory CreateSessionFactory(Func<IPersistenceConfigurer> configuration,
Action<NHibernate.Cfg.Configuration> schema)
{
try
{
var configure = Fluently.Configure();
var database = configure.Database(configuration);
var mappings = database.Mappings(CreateMappings());
var fluentConfiguration = mappings.ExposeConfiguration(c =>
{
// c.SetProperty("generate_statistics", "true");
SchemaConfig = c;
schema.Invoke(c);
});
return fluentConfiguration.BuildSessionFactory();
}
catch (Exception ex)
{
Log.Fatal(this, "Failed to create session factory", ex);
throw;
}
}
protected virtual Action<MappingConfiguration> CreateMappings()
{
return m =>
{
foreach (var model in _models ?? new Collection<IAutoPersistenceModelConfiguration>())
{
m.AutoMappings.Add(model.GetModel());
}
foreach (var mapping in _fluentMappings ?? new Collection<IFluentMappingConfiguration>())
{
mapping.Configure(m.FluentMappings);
}
foreach (var mapping in _hbmMappings ?? new Collection<IHbmMappingConfiguration>())
{
mapping.Configure(m.HbmMappings);
}
};
}
protected virtual void BuildSchema(NHibernate.Cfg.Configuration config)
{
new SchemaExport(config).Create(false, false);
}
}
}
# ==============================================================================
#
# Code Progression Copyright © 2011 - Released under the Apache 2.0 License
#
# Copyright 2007-2008 The Apache Software Foundation.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use
# this file except in compliance with the License. You may obtain a copy of the
# License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed
# under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
# CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.
# ==============================================================================
require 'albacore'
BUILD_NUMBER_BASE = '0.0.0'
PRODUCT = 'Irrigation District Management (Custom - Settlers Irrigation District)'
COPYRIGHT = 'Copyright 2011 Code Progression LLC '
COMMON_ASSEMBLY_INFO = 'src/CommonAssemblyInfo.cs'
MIGRATIONS_PROJECT = 'CP.Settlers.Migrations'
desc "Displays a list of tasks"
task :help do
task_hash = Hash[* (`rake -T`.split(/\n/).collect { |l| l.match(/rake (\S+)\s+\#\s(.+)/).to_a }.collect { |l| [l[1], l[2]] }).flatten]
indent = " "
puts "rake #{indent} Runs the 'default' task"
task_hash.each_pair do |key, value|
if key.nil?
next
end
puts "rake #{key}#{indent.slice(0, indent.length - key.length+2)} #{value}"
end
end
desc "Compiles the solution"
task :default => [:compile]
desc "Compiles the solution"
msbuild :compile do |msb|
msb.solution = 'src/CP.Settlers.sln'
end
desc "Update the version information"
assemblyinfo :version do |asm|
asm_version = BUILD_NUMBER_BASE + ".0"
begin
gittag = `git describe --tags --long`.chomp # looks something like v0.1.0-63-g92228f4
gitnumberpart = /-(\d+)-/.match(gittag)
gitnumber = gitnumberpart.nil? ? '0' : gitnumberpart[1]
commit = (ENV["BUILD_VCS_NUMBER"].nil? ? `git log -1 --pretty=format:%H` : ENV["BUILD_VCS_NUMBER"])
rescue
commit = "git unavailable"
gitnumber = "0"
end
build_number = "#{BUILD_NUMBER_BASE}.#{gitnumber}"
tc_build_number = ENV["BUILD_NUMBER"]
puts "##teamcity[buildNumber '#{build_number}-#{tc_build_number}']" unless tc_build_number.nil?
asm.trademark = commit
asm.product_name = "#{PRODUCT} #{gittag}"
asm.company_name = 'Code Progression LLC'
asm.description = build_number
asm.version = asm_version
asm.file_version = build_number
asm.namespaces 'System.Runtime.CompilerServices'
asm.custom_attributes :AssemblyInformationalVersion => asm_version, :InternalsVisibleTo => 'CP.Settlers.Specs'
asm.copyright = COPYRIGHT
asm.output_file = COMMON_ASSEMBLY_INFO
end
desc "Run database migrations"
task :migrate, :environment do |t, args|
environment = args[:environment] || "LOCAL"
FileUtils.cd("src/#{MIGRATIONS_PROJECT}/bin/Debug/") do
sh "#{MIGRATIONS_PROJECT}.exe #{environment}"
end
end
desc "Run database migrations"
task :migrateForce, :environment do |t, args|
environment = args[:environment] || "LOCAL"
FileUtils.cd("src/#{MIGRATIONS_PROJECT}/bin/Debug/") do
sh "#{MIGRATIONS_PROJECT}.exe #{environment} --force"
end
end
// ==============================================================================
//
// Fervent Coder Copyright © 2011 - Released under the Apache 2.0 License
//
// Adaption by Code Progression Copyright © 2011 - Released under the Apache 2.0 License
//
// Copyright 2007-2008 The Apache Software Foundation.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
// ==============================================================================
using System.Reflection;
using NDesk.Options;
using log4net;
using log4net.Core;
using log4net.Repository;
using roundhouse.infrastructure;
using roundhouse.infrastructure.app;
namespace CP.Migrations
{
using System;
using roundhouse;
public class RefreshDatabase
{
internal void Run(string[] args)
{
try
{
RunRoundhouseNhibernate(args);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
void RunRoundhouseNhibernate(string[] args)
{
GetMigrationSettings();
var migrator = new Migrate().Set(c =>
{
var environmentName = args.Any() ? args[0] : "LOCAL";
c.Logger = new roundhouse.infrastructure.logging.custom.ConsoleLogger();
c.SqlFilesDirectory = _sqlFilesDirectory;
c.ConnectionString = _connectionStrings[environmentName].ConnectionString;
c.EnvironmentName = environmentName;
c.VersionFile = _versionFile;
c.RepositoryPath = _repositoryPath;
c.RestoreFromPath = _restoreFromPath;
c.RecoveryModeSimple = true;
c.Silent = true;
c.WarnOnOneTimeScriptChanges = args.Select(x => x.ToLower()).Contains("--force");
});
RunMigration(migrator);
}
void GetMigrationSettings()
{
_connectionStrings = ConfigurationManager.ConnectionStrings;
_settings = ConfigurationManager.AppSettings;
_assemblyName = Assembly.GetAssembly(typeof (RefreshDatabase)).GetName();
_isInitialDevelopment = bool.Parse(_settings["IsInitialDevelopment"] ?? "false");
_restoreDuringMaintenance = bool.Parse(_settings["RestoreDuringMaintenance"] ?? "false");
_nameOfInitialScript = _settings["NameOfInitialScript"] ?? "0001_CreateTables_NH.sql";
_nameOfUpdateScript = _settings["NameOfUpdateScript"] ?? "0002_AlterTables_NH.sql";
_repositoryPath = _settings["RepositoryPath"];
_versionFile = _settings["VersionFile"];
_restoreFromPath = _settings["RestoreFromPath"];
_sqlFilesDirectory = _settings["SqlFilesDirctory"] ?? @"..\..\..\" + _assemblyName.Name;
}
void RunMigration(Migrate migrator)
{
var diffType = _restoreDuringMaintenance
? RoundhousEFluentNHDiffingType.MaintenanceWithRestore
: RoundhousEFluentNHDiffingType.Maintenance;
var scriptName = _nameOfUpdateScript;
if (_isInitialDevelopment)
{
scriptName = _nameOfInitialScript;
diffType = RoundhousEFluentNHDiffingType.InitialDevelopment;
}
new DifferenceWithFluentNHibernate().Run(diffType, scriptName, migrator);
}
static readonly ILog Logger = LogManager.GetLogger(typeof (Program));
ConnectionStringSettingsCollection _connectionStrings;
NameValueCollection _settings;
AssemblyName _assemblyName;
bool _isInitialDevelopment;
string _nameOfInitialScript;
string _nameOfUpdateScript;
bool _restoreDuringMaintenance;
string _pathToSqlScripts;
string _versionFile;
string _sqlFilesDirectory;
string _repositoryPath;
string _restoreFromPath;
}
}
// ==============================================================================
//
// Fervent Coder Copyright ? 2011 - Released under the Apache 2.0 License
//
// Adaption by Code Progression Copyright © 2011 - Released under the Apache 2.0 License
//
// Copyright 2007-2008 The Apache Software Foundation.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
// ==============================================================================
using System.Collections.Generic;
using System.Reflection;
using CP.Infrastructure;
using CP.Infrastructure.Persistence.Configuration;
using roundhouse.databases.sqlserver.orm;
using roundhouse.infrastructure;
using roundhouse.infrastructure.app;
using roundhouse.infrastructure.loaders;
namespace CP.Migrations
{
using System;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Cfg;
using Environment = NHibernate.Cfg.Environment;
public class RoundhousESessionFactory : NHibernateConfiguration
{
string _dbName;
public RoundhousESessionFactory (IEnumerable<IAutoPersistenceModelConfiguration> configs)
: base(configs, new[] {new RoundhousEFluentMappingConfiguration()}, null)
{
}
const string ProxyFactory = Environment.ProxyFactoryFactoryClass;
const string ProxyFactoryName = "NHibernate.ByteCode.Castle.ProxyFactoryFactory";
static ConfigurationPropertyHolder _configurationPropertyHolder;
public ISessionFactory CreateSessionFactory(ConfigurationPropertyHolder configurationPropertyHolder,
Action<Configuration> additionalFunction)
{
_configurationPropertyHolder = configurationPropertyHolder;
return CreateSessionFactory(GetSqlConfiguration(), additionalFunction);
}
protected override Func<IPersistenceConfigurer> GetSqlConfiguration()
{
var msSql2005 = MsSqlConfiguration.MsSql2008;
Action<MsSqlConnectionStringBuilder> expression = c =>
{
if (!string.IsNullOrEmpty(_configurationPropertyHolder.ConnectionStringAdmin))
{
c.Is(_configurationPropertyHolder.ConnectionStringAdmin);
}
else if (!string.IsNullOrEmpty(_configurationPropertyHolder.ConnectionString))
{
c.Is(
_configurationPropertyHolder.
ConnectionString);
}
else
c.Server(_configurationPropertyHolder.ServerName).Database(
_configurationPropertyHolder.DatabaseName).TrustedConnection();
};
return () => msSql2005.ConnectionString(expression);
}
public override ISessionFactory CreateSessionFactory(Func<IPersistenceConfigurer> configuration,
Action<Configuration> schema)
{
try
{
var configure = Fluently.Configure();
var database = configure.Database(configuration);
var mappings = database.Mappings(CreateMappings());
var fluentConfiguration = mappings.ExposeConfiguration(cfg =>
{
const string proxyFactoryLocation = ProxyFactoryName + ", NHibernate.ByteCode.Castle";
if (cfg.Properties.ContainsKey(ProxyFactory))
{
cfg.Properties[ProxyFactory] = proxyFactoryLocation;
}
else
{
cfg.Properties.Add(ProxyFactory, proxyFactoryLocation);
}
})
.ExposeConfiguration(schema.Invoke);
return fluentConfiguration.BuildSessionFactory();
}
catch (Exception ex)
{
Log.Fatal(this, "Failed to create session factory", ex);
throw;
}
}
public class RoundhousEFluentMappingConfiguration : IFluentMappingConfiguration
{
public FluentMappingsContainer Configure(FluentMappingsContainer fluentMappings)
{
var databaseType = _configurationPropertyHolder.DatabaseType;
string top_namespace = databaseType.Substring(0, databaseType.IndexOf(','));
top_namespace = top_namespace.Substring(0, top_namespace.LastIndexOf('.'));
string assembly_name = databaseType.Substring(0, databaseType.IndexOf(',') + 1);
var assembly = DefaultAssemblyLoader.load_assembly(ApplicationParameters.get_merged_assembly_name());
return fluentMappings.Add(
assembly.GetType(top_namespace + ".orm.VersionMapping", true, true))
.Add(assembly.GetType(top_namespace + ".orm.ScriptsRunMapping", true, true))
.Add(assembly.GetType(top_namespace + ".orm.ScriptsRunErrorMapping", true, true));
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment