diff --git a/appveyor.yml b/appveyor.yml index 4806643d..34a5517e 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -1,4 +1,4 @@ -image: Visual Studio 2017 +image: Visual Studio 2019 install: - choco install gitversion.portable -y diff --git a/build.ps1 b/build.ps1 index eeef4418..58232a06 100755 --- a/build.ps1 +++ b/build.ps1 @@ -5,6 +5,7 @@ $MSBUILD=msbuild $root = $PSScriptRoot; $CODEDROP="$($root)/code_drop"; +$PACKAGEDIR="$($CODEDROP)/packages"; $LOGDIR="$($CODEDROP)/log"; $TESTOUTDIR="$($root)/product/roundhouse.tests/bin" @@ -25,12 +26,15 @@ If ($onAppVeyor) { appveyor UpdateBuild -Version "$newVersion" } +" * Updating NuGet to handle newer license metadata" +nuget update -self -Verbosity quiet + " * Restoring nuget packages" nuget restore -NonInteractive -Verbosity quiet # Create output and log dirs if they don't exist (don't know why this is necessary - works on my box...) -If (!(Test-Path $CODEDROP)) { - $null = mkdir $CODEDROP; +If (!(Test-Path $PACKAGEDIR)) { + $null = mkdir $PACKAGEDIR; } If (!(Test-Path $LOGDIR)) { $null = mkdir $LOGDIR; @@ -45,17 +49,24 @@ $file = $(Get-ChildItem -Recurse -Include MySql.Data.dll ~/.nuget/packages/mysql " * Building and packaging" msbuild /t:"Build" /p:DropFolder=$CODEDROP /p:Version="$($gitVersion.FullSemVer)" /p:NoPackageAnalysis=true /nologo /v:q /fl /flp:"LogFile=$LOGDIR/msbuild.log;Verbosity=n" /p:Configuration=Build /p:Platform="Any CPU" -"`n - Packaging net461 packages`n" +" - NuGet libraries" +dotnet pack -nologo --no-build -v q -p:Version="$($gitVersion.FullSemVer)" -p:NoPackageAnalysis=true -p:Configuration=Build -p:Platform="Any CPU" -o ${PACKAGEDIR} + + +" - net461 command-line nuget package" -nuget pack product/roundhouse.console/roundhouse.nuspec -OutputDirectory "$CODEDROP/packages" -Properties "mergedExe=$CODEDROP/merge/rh.exe" -Verbosity quiet -NoPackageAnalysis -Version "$($gitVersion.FullSemVer)" -msbuild /t:"Pack" product/roundhouse.lib.merged/roundhouse.lib.merged.csproj /p:DropFolder=$CODEDROP /p:Version="$($gitVersion.FullSemVer)" /p:NoPackageAnalysis=true /nologo /v:q /fl /flp:"LogFile=$LOGDIR/msbuild.roundhouse.lib.pack.log;Verbosity=n" /p:Configuration=Build /p:Platform="Any CPU" +nuget pack product/roundhouse.console/roundhouse.nuspec -OutputDirectory "$CODEDROP/packages" -Verbosity quiet -NoPackageAnalysis -Version "$($gitVersion.FullSemVer)" msbuild /t:"Pack" product/roundhouse.tasks/roundhouse.tasks.csproj /p:DropFolder=$CODEDROP /p:Version="$($gitVersion.FullSemVer)" /p:NoPackageAnalysis=true /nologo /v:q /fl /flp:"LogFile=$LOGDIR/msbuild.roundhouse.tasks.pack.log;Verbosity=n" /p:Configuration=Build /p:Platform="Any CPU" -"`n - Packaging netcoreapp2.1 global tool dotnet-roundhouse`n" +" - netcoreapp2.1 global tool dotnet-roundhouse" + +dotnet publish -v q -nologo --no-restore product/roundhouse.console -p:NoPackageAnalysis=true -p:TargetFramework=netcoreapp2.1 -p:Version="$($gitVersion.FullSemVer)" -p:Configuration=Build -p:Platform="Any CPU" +dotnet pack -v q -nologo --no-restore --no-build product/roundhouse.console -p:NoPackageAnalysis=true -p:TargetFramework=netcoreapp2.1 -o ${PACKAGEDIR} -p:Version="$($gitVersion.FullSemVer)" -p:Configuration=Build -p:Platform="Any CPU" + -dotnet publish -v q --no-restore product/roundhouse.console -p:Version="$($gitVersion.FullSemVer)" -p:NoPackageAnalysis=true -p:TargetFramework=netcoreapp2.1 -p:Version="$($gitVersion.FullSemVer)" -p:RunILMerge=false -p:Configuration=Build -p:Platform="Any CPU" -dotnet pack -v q --no-restore product/roundhouse.console -p:NoPackageAnalysis=true -p:TargetFramework=netcoreapp2.1 -o $CODEDROP/packages -p:Version="$($gitVersion.FullSemVer)" -p:RunILMerge=false -p:Configuration=Build -p:Platform="Any CPU" +# " * Packaging netcoreapp2.1 global tool dotnet-roundhouse`n" +# nuget pack -Verbosity quiet -outputdirectory ${PACKAGEDIR} .\product\roundhouse.console\roundhouse.tool.nuspec -Properties "Version=$($gitVersion.FullSemVer);NoPackageAnalysis=true" # AppVeyor runs the test automagically, no need to run explicitly with nunit-console.exe. # But we want to run the tests on localhost too. @@ -64,13 +75,10 @@ If (! $onAppVeyor) { "`n * Running unit tests`n" # Find test projects - $testProjects = $(dir -r -i *.tests.csproj) + $testAssemblies = $(dir -r -i *.tests.dll) - $testProjects | % { - Push-Location $_.Directory - dotnet test -v q - Pop-Location + $testAssemblies | ? { $_.FullName -NotLike "*obj*" } | % { + dotnet vstest $_ } } -Pop-Location diff --git a/product/roundhouse.console/roundhouse.console.csproj b/product/roundhouse.console/roundhouse.console.csproj index 4bbe04fb..70b668db 100644 --- a/product/roundhouse.console/roundhouse.console.csproj +++ b/product/roundhouse.console/roundhouse.console.csproj @@ -1,135 +1,111 @@ - - - netcoreapp2.1;net461 - net461 - true - true - Debug - AnyCPU - Exe - bin\ - roundhouse.console - rh - ..\..\ - NU1701 - true - true - 0.8.9 - alpha - $(VersionPrefix) - $(Version)-$(VersionSuffix) - $(Version) - - - - AllRules.ruleset - win7-x86 - - - - true - full - false - DEBUG;TRACE - prompt - 4 - AnyCPU - false - - - TRACE - true - pdbonly - AnyCPU - prompt - false - - - - - - all - runtime; build; native; contentfiles; analyzers - - - - - - - - - - - - - - - - - - - - - - - - - - - - - roundhouse.ico - - - - - $(AssemblyName).keywords.txt - - - - - - - - - - - ..\..\code_drop\merge\ - .dll - - - - .exe - - - - $(MSBuildProjectDirectory)/$(OutputPath)/$(TargetFramework)/$(RuntimeIdentifier)/$(AssemblyName)$(Extension) - $(DropDir)$(AssemblyName)$(Extension) - - - - - - - - - - - roundhouse.nuspec - mergedExe=$(CopyDestination);version=$(NugetVersion) - - - - roundhouse.tool.nuspec - version=$(NugetVersion) - - - - - - - - - - + + + netcoreapp2.1;net461 + net461 + true + true + Debug + AnyCPU + Exe + bin\ + roundhouse.console + rh + ..\..\ + NU1701 + true + true + 1.0.0 + $(Version) + + + + roundhouse.tool.nuspec + + + + win7-x86 + + + + true + full + false + DEBUG;TRACE + prompt + 4 + AnyCPU + false + + + TRACE + true + pdbonly + AnyCPU + prompt + false + + + + + + + + + + all + runtime; build; native; contentfiles; analyzers + + + + + + + + + + + + + + + + + + + + roundhouse.ico + + + + + $(AssemblyName).keywords.txt + + + + + + + + + + + + + roundhouse.nuspec + mergedExe=$(CopyDestination);version=$(NugetVersion) + + + + roundhouse.tool.nuspec + version=$(NugetVersion) + + + + + + + + + + \ No newline at end of file diff --git a/product/roundhouse.console/roundhouse.nuspec b/product/roundhouse.console/roundhouse.nuspec index 4be0799a..0c720dde 100644 --- a/product/roundhouse.console/roundhouse.nuspec +++ b/product/roundhouse.console/roundhouse.nuspec @@ -9,14 +9,14 @@ RoundhousE - Professional Database Change and Versioning Management RoundhousE is a Professional Database Change and Versioning Management tool. Type rh /? for options http://projectroundhouse.org - http://www.apache.org/licenses/LICENSE-2.0 + Apache-2.0 false roundhouse db migration database migrator chucknorris - https://raw.github.com/chucknorris/roundhouse/master/nuget/RoundhousE_Logo.NuGet.jpg + https://raw.github.com/chucknorris/roundhouse/master/nuget/RoundhousE_Logo.NuGet.jpg - + diff --git a/product/roundhouse.console/roundhouse.tool.nuspec b/product/roundhouse.console/roundhouse.tool.nuspec index 0446f5d7..345617e2 100644 --- a/product/roundhouse.console/roundhouse.tool.nuspec +++ b/product/roundhouse.console/roundhouse.tool.nuspec @@ -6,10 +6,10 @@ $version$ Rob Reynolds, Andy Davis, Erik A. Brandstadmoen Rob Reynolds, Andy Davis, Erik A. Brandstadmoen - .NET Core global too for RoundhousE - Professional Database Change and Versioning Management + .NET Core global tool for RoundhousE - Professional Database Change and Versioning Management RoundhousE is a Professional Database Change and Versioning Management tool. Type rh /? for options http://projectroundhouse.org - http://www.apache.org/licenses/LICENSE-2.0 + Apache-2.0 false roundhouse db migration database migrator chucknorris diff --git a/product/roundhouse/DifferenceWithFluentNHibernate.cs b/product/roundhouse.core/DifferenceWithFluentNHibernate.cs similarity index 98% rename from product/roundhouse/DifferenceWithFluentNHibernate.cs rename to product/roundhouse.core/DifferenceWithFluentNHibernate.cs index 99d67389..a665995f 100644 --- a/product/roundhouse/DifferenceWithFluentNHibernate.cs +++ b/product/roundhouse.core/DifferenceWithFluentNHibernate.cs @@ -1,110 +1,110 @@ -//namespace roundhouse -//{ -// using System.IO; -// using System.Reflection; -// using System.Text; -// using infrastructure.app; -// using infrastructure.persistence; -// using NHibernate.Cfg; -// using NHibernate.Tool.hbm2ddl; - -// public class DifferenceWithFluentNHibernate -// { -// private static string path_to_sql_scripts_up_folder; -// private static string name_of_script_to_create; - -// /// -// /// 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. -// /// -// /// Are you in greenfield development or have you went to production (maintenance)? Do you want it to restore during maintenance mode? -// /// This is something like 0001_CreateTables.sql. This will end up in your up folder, assuming you have set up your migrator configuration correctly. -// /// The Migrator to use when running. -// /// This is the assembly that contains your mapping files. -// /// This is the assembly that contains your conventions. If you do not have conventions set up, just pass null. It will use the mappingsAssembly -// public void Run(RoundhousEFluentNHDiffingType diffingType, string nameOfOutputScriptToCreateOrReplace, Migrate databaseMigrator, Assembly mappingsAssembly, Assembly conventionsAssembly) -// { -// 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, mappingsAssembly, conventionsAssembly); -// break; -// case RoundhousEFluentNHDiffingType.Maintenance: -// run_maintenance_database_setup(false, databaseMigrator, configuration, mappingsAssembly, conventionsAssembly); -// break; -// case RoundhousEFluentNHDiffingType.MaintenanceWithRestore: -// run_maintenance_database_setup(true, databaseMigrator, configuration, mappingsAssembly, conventionsAssembly); -// break; -// } -// } - -// // initial database setup - -// private void run_initial_database_setup(Migrate migrator, ConfigurationPropertyHolder configuration, Assembly mappings_assembly, Assembly conventions_assembly) -// { - -// var files_directory = configuration.SqlFilesDirectory; -// configuration.SqlFilesDirectory = "."; - -// migrator.Run(); - -// generate_database_schema(configuration.DatabaseName, mappings_assembly, conventions_assembly); - - -// configuration.SqlFilesDirectory = files_directory; -// migrator.RunDropCreate(); -// } - -// private void generate_database_schema(string database_name,Assembly mappings_assembly,Assembly conventions_assembly) -// { -// DifferencingNHibernateSessionFactory.build_session_factory(database_name, mappings_assembly, conventions_assembly, 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); -// } - -// // maintenance database setup - -// private void run_maintenance_database_setup(bool restoring_the_database, Migrate migrator, ConfigurationPropertyHolder configuration, Assembly mappings_assembly, Assembly conventions_assembly) -// { -// if (restoring_the_database) -// { -// configuration.Restore = true; -// migrator.RunRestore(); -// } - -// upgrade_database_schema(configuration.DatabaseName, mappings_assembly, conventions_assembly); - -// configuration.Restore = false; -// migrator.Run(); -// } - -// private void upgrade_database_schema(string database_name,Assembly mappings_assembly,Assembly conventions_assembly) -// { -// DifferencingNHibernateSessionFactory.build_session_factory(database_name, mappings_assembly, conventions_assembly, 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()); -// } -// } +//namespace roundhouse +//{ +// using System.IO; +// using System.Reflection; +// using System.Text; +// using infrastructure.app; +// using infrastructure.persistence; +// using NHibernate.Cfg; +// using NHibernate.Tool.hbm2ddl; + +// public class DifferenceWithFluentNHibernate +// { +// private static string path_to_sql_scripts_up_folder; +// private static string name_of_script_to_create; + +// /// +// /// 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. +// /// +// /// Are you in greenfield development or have you went to production (maintenance)? Do you want it to restore during maintenance mode? +// /// This is something like 0001_CreateTables.sql. This will end up in your up folder, assuming you have set up your migrator configuration correctly. +// /// The Migrator to use when running. +// /// This is the assembly that contains your mapping files. +// /// This is the assembly that contains your conventions. If you do not have conventions set up, just pass null. It will use the mappingsAssembly +// public void Run(RoundhousEFluentNHDiffingType diffingType, string nameOfOutputScriptToCreateOrReplace, Migrate databaseMigrator, Assembly mappingsAssembly, Assembly conventionsAssembly) +// { +// 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, mappingsAssembly, conventionsAssembly); +// break; +// case RoundhousEFluentNHDiffingType.Maintenance: +// run_maintenance_database_setup(false, databaseMigrator, configuration, mappingsAssembly, conventionsAssembly); +// break; +// case RoundhousEFluentNHDiffingType.MaintenanceWithRestore: +// run_maintenance_database_setup(true, databaseMigrator, configuration, mappingsAssembly, conventionsAssembly); +// break; +// } +// } + +// // initial database setup + +// private void run_initial_database_setup(Migrate migrator, ConfigurationPropertyHolder configuration, Assembly mappings_assembly, Assembly conventions_assembly) +// { + +// var files_directory = configuration.SqlFilesDirectory; +// configuration.SqlFilesDirectory = "."; + +// migrator.Run(); + +// generate_database_schema(configuration.DatabaseName, mappings_assembly, conventions_assembly); + + +// configuration.SqlFilesDirectory = files_directory; +// migrator.RunDropCreate(); +// } + +// private void generate_database_schema(string database_name,Assembly mappings_assembly,Assembly conventions_assembly) +// { +// DifferencingNHibernateSessionFactory.build_session_factory(database_name, mappings_assembly, conventions_assembly, 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); +// } + +// // maintenance database setup + +// private void run_maintenance_database_setup(bool restoring_the_database, Migrate migrator, ConfigurationPropertyHolder configuration, Assembly mappings_assembly, Assembly conventions_assembly) +// { +// if (restoring_the_database) +// { +// configuration.Restore = true; +// migrator.RunRestore(); +// } + +// upgrade_database_schema(configuration.DatabaseName, mappings_assembly, conventions_assembly); + +// configuration.Restore = false; +// migrator.Run(); +// } + +// private void upgrade_database_schema(string database_name,Assembly mappings_assembly,Assembly conventions_assembly) +// { +// DifferencingNHibernateSessionFactory.build_session_factory(database_name, mappings_assembly, conventions_assembly, 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()); +// } +// } //} \ No newline at end of file diff --git a/product/roundhouse/Migrate.cs b/product/roundhouse.core/Migrate.cs similarity index 93% rename from product/roundhouse/Migrate.cs rename to product/roundhouse.core/Migrate.cs index acc907f4..19d9ade6 100644 --- a/product/roundhouse/Migrate.cs +++ b/product/roundhouse.core/Migrate.cs @@ -1,124 +1,133 @@ -namespace roundhouse -{ - using System; - using folders; - using infrastructure.app; - using infrastructure.containers; - using infrastructure.filesystem; - using infrastructure.logging; - using migrators; - using resolvers; - using runners; - - public class Migrate - { - private readonly ConfigurationPropertyHolder configuration; - - public Migrate() - { - configuration = new consoles.DefaultConfiguration(); - } - - /// - /// This is an optional helper to give you the correct settings for a logger. You can still set this in the set by calling propConfig.Logger without having to call this method. - /// - /// This is the logger you want RoundhousE to also use. - /// - public Migrate SetCustomLogging(Logger logger) - { - return Set(c => c.Logger = logger); - } - - /// - /// Set your options for running rh here. It looks like Set(c => {c.DatabaseName = "bob"; c.ServerName = "(local)";}).Run(); - /// - /// The configuration to set - /// Itself so you can chain each of these - public Migrate Set(Action propConfig) - { - propConfig.Invoke(configuration); - return this; - } - - public ConfigurationPropertyHolder GetConfiguration() - { - return configuration; - } - - /// - /// Call this method to run the migrator after you have set the options. - /// - public void Run() - { - RoundhouseMigrationRunner migrator = GetMigrationRunner(); - - - migrator.run(); - } - - /// - /// Call this method to run a drop/create migration (instead of just a normal run) after you have set the options. This does not work in conjunction with the restore. - /// - /// This is usually used during initial development - public void RunDropCreate() - { - if (configuration.Restore) throw new ApplicationException("You cannot use Drop/Create with Restore set to true."); - configuration.Drop = true; - Run(); - configuration.Drop = false; - Run(); - } - - /// - /// Call this method to run a restore migration (instead of just a normal run) after you have set the options. This is a helper method - you can also use the normal Run() with the restore set to true. - /// - /// This is usually used during maintenance development (after production) - public void RunRestore() - { - configuration.Restore = true; - if (string.IsNullOrEmpty(configuration.RestoreFromPath)) throw new ApplicationException("You must set RestoreFromPath in the configuration."); - - Run(); - } - - /// - /// Call this method to find out if there are any new or changed scripts that would be executed when the Run-method is called. - /// - public bool IsDbUpToDate() - { - RoundhouseMigrationRunner migrationRunner = GetMigrationRunner(); - - RoundhouseUpdateCheckRunner updateCheckRunner = new RoundhouseUpdateCheckRunner( - Container.get_an_instance_of(), - Container.get_an_instance_of(), - Container.get_an_instance_of(), - Container.get_an_instance_of(), - configuration, - migrationRunner); - - return updateCheckRunner.is_database_up_to_date(); - } - - - private RoundhouseMigrationRunner GetMigrationRunner() - { - ApplicationConfiguraton.set_defaults_if_properties_are_not_set(this.configuration); - ApplicationConfiguraton.build_the_container(this.configuration); - - return new RoundhouseMigrationRunner( - this.configuration.RepositoryPath, - Container.get_an_instance_of(), - Container.get_an_instance_of(), - Container.get_an_instance_of(), - Container.get_an_instance_of(), - Container.get_an_instance_of(), - this.configuration.Silent, - this.configuration.Drop, - this.configuration.DoNotCreateDatabase, - this.configuration.WithTransaction, - this.configuration); - } - - } - +using roundhouse.infrastructure; + +namespace roundhouse +{ + using System; + using folders; + using infrastructure.app; + using infrastructure.containers; + using infrastructure.filesystem; + using infrastructure.logging; + using migrators; + using resolvers; + using runners; + + public class Migrate + { + private readonly ConfigurationPropertyHolder configuration; + + public Migrate() + { + configuration = new consoles.DefaultConfiguration(); + } + + /// + /// This is an optional helper to give you the correct settings for a logger. You can still set this in the set by calling propConfig.Logger without having to call this method. + /// + /// This is the logger you want RoundhousE to also use. + /// + public Migrate SetCustomLogging(Logger logger) + { + return Set(c => c.Logger = logger); + } + + /// + /// Set your options for running rh here. It looks like Set(c => {c.DatabaseName = "bob"; c.ServerName = "(local)";}).Run(); + /// + /// The configuration to set + /// Itself so you can chain each of these + public Migrate Set(Action propConfig) + { + propConfig.Invoke(configuration); + return this; + } + + public ConfigurationPropertyHolder GetConfiguration() + { + return configuration; + } + + /// + /// Call this method to run the migrator after you have set the options. + /// + public void Run() + { + RoundhouseMigrationRunner migrator = GetMigrationRunner(); + + + migrator.run(); + } + + /// + /// Call this method to run a drop/create migration (instead of just a normal run) after you have set the options. This does not work in conjunction with the restore. + /// + /// This is usually used during initial development + public void RunDropCreate() + { + if (configuration.Restore) + { + throw new ConfigurationException("You cannot use Drop/Create with Restore set to true."); + } + + configuration.Drop = true; + Run(); + configuration.Drop = false; + Run(); + } + + /// + /// Call this method to run a restore migration (instead of just a normal run) after you have set the options. This is a helper method - you can also use the normal Run() with the restore set to true. + /// + /// This is usually used during maintenance development (after production) + public void RunRestore() + { + configuration.Restore = true; + if (string.IsNullOrEmpty(configuration.RestoreFromPath)) + { + throw new ConfigurationException("You must set RestoreFromPath in the configuration."); + } + + Run(); + } + + /// + /// Call this method to find out if there are any new or changed scripts that would be executed when the Run-method is called. + /// + public bool IsDbUpToDate() + { + RoundhouseMigrationRunner migrationRunner = GetMigrationRunner(); + + RoundhouseUpdateCheckRunner updateCheckRunner = new RoundhouseUpdateCheckRunner( + Container.get_an_instance_of(), + Container.get_an_instance_of(), + Container.get_an_instance_of(), + Container.get_an_instance_of(), + configuration, + migrationRunner); + + return updateCheckRunner.is_database_up_to_date(); + } + + + private RoundhouseMigrationRunner GetMigrationRunner() + { + ApplicationConfiguraton.set_defaults_if_properties_are_not_set(this.configuration); + ApplicationConfiguraton.build_the_container(this.configuration); + + return new RoundhouseMigrationRunner( + this.configuration.RepositoryPath, + Container.get_an_instance_of(), + Container.get_an_instance_of(), + Container.get_an_instance_of(), + Container.get_an_instance_of(), + Container.get_an_instance_of(), + this.configuration.Silent, + this.configuration.Drop, + this.configuration.DoNotCreateDatabase, + this.configuration.WithTransaction, + this.configuration); + } + + } + } \ No newline at end of file diff --git a/product/roundhouse/Properties/AssemblyInfo.cs b/product/roundhouse.core/Properties/AssemblyInfo.cs similarity index 100% rename from product/roundhouse/Properties/AssemblyInfo.cs rename to product/roundhouse.core/Properties/AssemblyInfo.cs diff --git a/product/roundhouse/RoundhousEFluentNHibernateDiffingType.cs b/product/roundhouse.core/RoundhousEFluentNHibernateDiffingType.cs similarity index 95% rename from product/roundhouse/RoundhousEFluentNHibernateDiffingType.cs rename to product/roundhouse.core/RoundhousEFluentNHibernateDiffingType.cs index 00e720bc..f38bfbb4 100644 --- a/product/roundhouse/RoundhousEFluentNHibernateDiffingType.cs +++ b/product/roundhouse.core/RoundhousEFluentNHibernateDiffingType.cs @@ -1,12 +1,12 @@ -namespace roundhouse -{ - using System; - - [Obsolete("Use RoundhouseMode",true)] - public enum RoundhousEFluentNHDiffingType - { - InitialDevelopment, - Maintenance, - MaintenanceWithRestore - } +namespace roundhouse +{ + using System; + + [Obsolete("Use RoundhouseMode",true)] + public enum RoundhousEFluentNHDiffingType + { + InitialDevelopment, + Maintenance, + MaintenanceWithRestore + } } \ No newline at end of file diff --git a/product/roundhouse/RoundhouseMode.cs b/product/roundhouse.core/RoundhouseMode.cs similarity index 94% rename from product/roundhouse/RoundhouseMode.cs rename to product/roundhouse.core/RoundhouseMode.cs index 5903d361..7875ceb6 100644 --- a/product/roundhouse/RoundhouseMode.cs +++ b/product/roundhouse.core/RoundhouseMode.cs @@ -1,9 +1,9 @@ -namespace roundhouse -{ - public enum RoundhouseMode - { - InitialDevelopment, - Maintenance, - MaintenanceWithRestore - } +namespace roundhouse +{ + public enum RoundhouseMode + { + InitialDevelopment, + Maintenance, + MaintenanceWithRestore + } } \ No newline at end of file diff --git a/product/roundhouse/connections/AdoNetConnection.cs b/product/roundhouse.core/connections/AdoNetConnection.cs similarity index 77% rename from product/roundhouse/connections/AdoNetConnection.cs rename to product/roundhouse.core/connections/AdoNetConnection.cs index f1f5291c..b28e0aa1 100644 --- a/product/roundhouse/connections/AdoNetConnection.cs +++ b/product/roundhouse.core/connections/AdoNetConnection.cs @@ -1,70 +1,66 @@ -using System; -using System.Data; -using System.Linq; -using System.Reflection; - -namespace roundhouse.connections -{ - using System.Data.SqlClient; - - public class AdoNetConnection : IConnection - { - private readonly IDbConnection server_connection; - - public AdoNetConnection(IDbConnection server_connection) - { - this.server_connection = server_connection; - } - - public void open() - { - try - { - - server_connection.Open(); } - - catch (ReflectionTypeLoadException rtle) - { - throw rtle.LoaderExceptions.First(); - - } - - catch (TypeInitializationException tie) - { - var inner = tie.InnerException; - if (inner is ReflectionTypeLoadException r) - { - throw r.LoaderExceptions.First(); - } - } - - } - - public void clear_pool() - { - var sql_conn = server_connection as SqlConnection; - if (sql_conn != null) - { - SqlConnection.ClearPool(sql_conn); - } - } - - public void close() - { - if (server_connection !=null && server_connection.State != ConnectionState.Closed) - { - server_connection.Close(); - } - } - - public IDbConnection underlying_type() - { - return server_connection; - } - - public void Dispose() - { - server_connection.Dispose(); - } - } +using System; +using System.Data; +using System.Linq; +using System.Reflection; + +namespace roundhouse.connections +{ + using System.Data.SqlClient; + + public class AdoNetConnection : IConnection + { + private readonly IDbConnection server_connection; + + public AdoNetConnection(IDbConnection server_connection) + { + this.server_connection = server_connection; + } + + public void open() + { + try + { + server_connection.Open(); + }catch (ReflectionTypeLoadException rtle) + { + throw rtle.LoaderExceptions.First(); + } + + catch (TypeInitializationException tie) + { + var inner = tie.InnerException; + if (inner is ReflectionTypeLoadException r) + { + throw r.LoaderExceptions.First(); + } + } + } + + public void clear_pool() + { + var sql_conn = server_connection as SqlConnection; + if (sql_conn != null) + { + SqlConnection.ClearPool(sql_conn); + } + } + + public void close() + { + if (server_connection != null && server_connection.State != ConnectionState.Closed) + { + server_connection.Close(); + } + } + + public IDbConnection underlying_type() + { + return server_connection; + } + + void IDisposable.Dispose() + { + server_connection.Dispose(); + } + } } \ No newline at end of file diff --git a/product/roundhouse/connections/IConnection.cs b/product/roundhouse.core/connections/IConnection.cs similarity index 99% rename from product/roundhouse/connections/IConnection.cs rename to product/roundhouse.core/connections/IConnection.cs index d59eb73c..9801bb65 100644 --- a/product/roundhouse/connections/IConnection.cs +++ b/product/roundhouse.core/connections/IConnection.cs @@ -4,9 +4,9 @@ namespace roundhouse.connections { public interface IConnection : IDisposable { - void open(); + void open(); void clear_pool(); - void close(); + void close(); T underlying_type(); } } \ No newline at end of file diff --git a/product/roundhouse/consoles/CommandExecutor.cs b/product/roundhouse.core/consoles/CommandExecutor.cs similarity index 90% rename from product/roundhouse/consoles/CommandExecutor.cs rename to product/roundhouse.core/consoles/CommandExecutor.cs index 20696dc9..6152270c 100644 --- a/product/roundhouse/consoles/CommandExecutor.cs +++ b/product/roundhouse.core/consoles/CommandExecutor.cs @@ -1,34 +1,34 @@ -namespace roundhouse.consoles -{ - using System.Diagnostics; - using System.IO; - using System.Reflection; - - public class CommandExecutor - { - public static int execute(string process, string arguments, bool wait_for_exit) - { - int exit_code = -1; - ProcessStartInfo psi = new ProcessStartInfo(Path.GetFullPath(process), arguments) - { - WorkingDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), - UseShellExecute = false, - RedirectStandardOutput = false, - CreateNoWindow = false - }; - - using (Process p = new Process()) - { - p.StartInfo = psi; - p.Start(); - if (wait_for_exit) - { - p.WaitForExit(); - } - exit_code = p.ExitCode; - } - - return exit_code; - } - } +namespace roundhouse.consoles +{ + using System.Diagnostics; + using System.IO; + using System.Reflection; + + public static class CommandExecutor + { + public static int execute(string process, string arguments, bool wait_for_exit) + { + int exit_code; + ProcessStartInfo psi = new ProcessStartInfo(Path.GetFullPath(process), arguments) + { + WorkingDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), + UseShellExecute = false, + RedirectStandardOutput = false, + CreateNoWindow = false + }; + + using (Process p = new Process()) + { + p.StartInfo = psi; + p.Start(); + if (wait_for_exit) + { + p.WaitForExit(); + } + exit_code = p.ExitCode; + } + + return exit_code; + } + } } \ No newline at end of file diff --git a/product/roundhouse/consoles/DefaultConfiguration.cs b/product/roundhouse.core/consoles/DefaultConfiguration.cs similarity index 98% rename from product/roundhouse/consoles/DefaultConfiguration.cs rename to product/roundhouse.core/consoles/DefaultConfiguration.cs index 41995765..cc19ac4a 100644 --- a/product/roundhouse/consoles/DefaultConfiguration.cs +++ b/product/roundhouse.core/consoles/DefaultConfiguration.cs @@ -1,160 +1,160 @@ -using System.Collections.Generic; - -namespace roundhouse.consoles -{ - using System; - using databases; - using infrastructure.app; - using infrastructure.extensions; - using infrastructure.logging; - using System.Linq; - - public sealed class DefaultConfiguration : ConfigurationPropertyHolder - { - public DefaultConfiguration() - { - EnvironmentNames = new List(); - } - public Logger Logger { get; set; } - public string ServerName { get; set; } - public string DatabaseName { get; set; } - public string ConnectionString { get; set; } - public string ConnectionStringAdmin { get; set; } - public int CommandTimeout { get; set; } - public int CommandTimeoutAdmin { get; set; } - public string SqlFilesDirectory { get; set; } - public string RepositoryPath { get; set; } - public string Version { get; set; } - public string VersionFile { get; set; } - public string VersionXPath { get; set; } - public string AlterDatabaseFolderName { get; set; } - public string RunAfterCreateDatabaseFolderName { get; set; } - public string RunBeforeUpFolderName { get; set; } - public string UpFolderName { get; set; } - public string DownFolderName { get; set; } - public string RunFirstAfterUpFolderName { get; set; } - public string FunctionsFolderName { get; set; } - public string ViewsFolderName { get; set; } - public string SprocsFolderName { get; set; } - public string TriggersFolderName { get; set; } - public string IndexesFolderName { get; set; } - public string RunAfterOtherAnyTimeScriptsFolderName { get; set; } - public string PermissionsFolderName { get; set; } - public string BeforeMigrationFolderName { get; set; } - public string AfterMigrationFolderName { get; set; } - public string SchemaName { get; set; } - public string VersionTableName { get; set; } - public string ScriptsRunTableName { get; set; } - public string ScriptsRunErrorsTableName { get; set; } - [Obsolete("Use EnvironmentNames")] - public string EnvironmentName { - get { return EnvironmentNames.SingleOrDefault(); } - set - { - EnvironmentNames.Clear(); - EnvironmentNames.Add(value); - } - } - public IList EnvironmentNames { get; private set; } - public bool Restore { get; set; } - public string RestoreFromPath { get; set; } - public string RestoreCustomOptions { get; set; } - public int RestoreTimeout { get; set; } - public string CreateDatabaseCustomScript { get; set; } - public string OutputPath { get; set; } - public bool WarnOnOneTimeScriptChanges { get; set; } - public bool WarnAndIgnoreOnOneTimeScriptChanges { get; set; } - public bool Silent { get; set; } - public string DatabaseType { get; set; } - public bool Drop { get; set; } - public bool DoNotCreateDatabase { get; set; } - public bool DoNotAlterDatabase { get; set; } - public bool WithTransaction { get; set; } - public RecoveryMode RecoveryMode { get; set; } - [Obsolete("Use RecoveryMode = Simple")] - public bool RecoveryModeSimple { get; set; } - public bool Debug { get; set; } - public bool DryRun { get; set; } - public bool Baseline { get; set; } - public bool RunAllAnyTimeScripts { get; set; } - public bool DisableTokenReplacement { get; set; } - public bool SearchAllSubdirectoriesInsteadOfTraverse { get; set; } - public bool DisableOutput { get; set; } - public Dictionary UserTokens { get; set; } - public bool Initialize { get; set; } - public string ConfigurationFile { get; set; } - public System.Text.Encoding DefaultEncoding { get; set; } - - public IDictionary to_token_dictionary() - { - var tokens = new Dictionary(StringComparer.OrdinalIgnoreCase); - tokens["AfterMigrationFolderName"] = AfterMigrationFolderName.to_string(); - tokens["AlterDatabaseFolderName"] = AlterDatabaseFolderName.to_string(); - tokens["Baseline"] = Baseline.to_string(); - tokens["BeforeMigrationFolderName"] = BeforeMigrationFolderName.to_string(); - tokens["CommandTimeout"] = CommandTimeout.to_string(); - tokens["CommandTimeoutAdmin"] = CommandTimeoutAdmin.to_string(); - tokens["ConfigurationFile"] = ConfigurationFile.to_string(); - tokens["ConnectionString"] = ConnectionString.to_string(); - tokens["ConnectionStringAdmin"] = ConnectionStringAdmin.to_string(); - tokens["CreateDatabaseCustomScript"] = CreateDatabaseCustomScript.to_string(); - tokens["DatabaseName"] = DatabaseName.to_string(); - tokens["DatabaseType"] = DatabaseType.to_string(); - tokens["Debug"] = Debug.to_string(); - tokens["DisableOutput"] = DisableOutput.to_string(); - tokens["DisableTokenReplacement"] = DisableTokenReplacement.to_string(); - tokens["DoNotAlterDatabase"] = DoNotAlterDatabase.to_string(); - tokens["DoNotCreateDatabase"] = DoNotCreateDatabase.to_string(); - tokens["DownFolderName"] = DownFolderName.to_string(); - tokens["Drop"] = Drop.to_string(); - tokens["DryRun"] = DryRun.to_string(); - tokens["EnvironmentName"] = string.Join(",", EnvironmentNames); - tokens["EnvironmentNames"] = string.Join(",", EnvironmentNames); - tokens["FunctionsFolderName"] = FunctionsFolderName.to_string(); - tokens["IndexesFolderName"] = IndexesFolderName.to_string(); - tokens["Initialize"] = Initialize.to_string(); - tokens["OutputPath"] = OutputPath.to_string(); - tokens["PermissionsFolderName"] = PermissionsFolderName.to_string(); - tokens["RecoveryMode"] = RecoveryMode.to_string(); - tokens["RepositoryPath"] = RepositoryPath.to_string(); - tokens["Restore"] = Restore.to_string(); - tokens["RestoreCustomOptions"] = RestoreCustomOptions.to_string(); - tokens["RestoreFromPath"] = RestoreFromPath.to_string(); - tokens["RestoreTimeout"] = RestoreTimeout.to_string(); - tokens["RunAfterCreateDatabaseFolderName"] = RunAfterCreateDatabaseFolderName.to_string(); - tokens["RunAfterOtherAnyTimeScriptsFolderName"] = RunAfterOtherAnyTimeScriptsFolderName.to_string(); - tokens["RunAllAnyTimeScripts"] = RunAllAnyTimeScripts.to_string(); - tokens["RunBeforeUpFolderName"] = RunBeforeUpFolderName.to_string(); - tokens["RunFirstAfterUpFolderName"] = RunFirstAfterUpFolderName.to_string(); - tokens["SchemaName"] = SchemaName.to_string(); - tokens["ScriptsRunErrorsTableName"] = ScriptsRunErrorsTableName.to_string(); - tokens["ScriptsRunTableName"] = ScriptsRunTableName.to_string(); - tokens["SearchAllSubdirectoriesInsteadOfTraverse"] = SearchAllSubdirectoriesInsteadOfTraverse.to_string(); - tokens["ServerName"] = ServerName.to_string(); - tokens["Silent"] = Silent.to_string(); - tokens["SprocsFolderName"] = SprocsFolderName.to_string(); - tokens["SqlFilesDirectory"] = SqlFilesDirectory.to_string(); - tokens["TriggersFolderName"] = TriggersFolderName.to_string(); - tokens["UpFolderName"] = UpFolderName.to_string(); - tokens["Version"] = Version.to_string(); - tokens["VersionFile"] = VersionFile.to_string(); - tokens["VersionTableName"] = VersionTableName.to_string(); - tokens["VersionXPath"] = VersionXPath.to_string(); - tokens["ViewsFolderName"] = ViewsFolderName.to_string(); - tokens["WarnAndIgnoreOnOneTimeScriptChanges"] = WarnAndIgnoreOnOneTimeScriptChanges.to_string(); - tokens["WarnOnOneTimeScriptChanges"] = WarnOnOneTimeScriptChanges.to_string(); - tokens["WithTransaction"] = WithTransaction.to_string(); - - if (UserTokens != null) - { - foreach (var t in UserTokens) - { - tokens[t.Key] = t.Value; - } - } - - return tokens; - } - - } +using System.Collections.Generic; + +namespace roundhouse.consoles +{ + using System; + using databases; + using infrastructure.app; + using infrastructure.extensions; + using infrastructure.logging; + using System.Linq; + + public sealed class DefaultConfiguration : ConfigurationPropertyHolder + { + public DefaultConfiguration() + { + EnvironmentNames = new List(); + } + public Logger Logger { get; set; } + public string ServerName { get; set; } + public string DatabaseName { get; set; } + public string ConnectionString { get; set; } + public string ConnectionStringAdmin { get; set; } + public int CommandTimeout { get; set; } + public int CommandTimeoutAdmin { get; set; } + public string SqlFilesDirectory { get; set; } + public string RepositoryPath { get; set; } + public string Version { get; set; } + public string VersionFile { get; set; } + public string VersionXPath { get; set; } + public string AlterDatabaseFolderName { get; set; } + public string RunAfterCreateDatabaseFolderName { get; set; } + public string RunBeforeUpFolderName { get; set; } + public string UpFolderName { get; set; } + public string DownFolderName { get; set; } + public string RunFirstAfterUpFolderName { get; set; } + public string FunctionsFolderName { get; set; } + public string ViewsFolderName { get; set; } + public string SprocsFolderName { get; set; } + public string TriggersFolderName { get; set; } + public string IndexesFolderName { get; set; } + public string RunAfterOtherAnyTimeScriptsFolderName { get; set; } + public string PermissionsFolderName { get; set; } + public string BeforeMigrationFolderName { get; set; } + public string AfterMigrationFolderName { get; set; } + public string SchemaName { get; set; } + public string VersionTableName { get; set; } + public string ScriptsRunTableName { get; set; } + public string ScriptsRunErrorsTableName { get; set; } + [Obsolete("Use EnvironmentNames")] + public string EnvironmentName { + get { return EnvironmentNames.SingleOrDefault(); } + set + { + EnvironmentNames.Clear(); + EnvironmentNames.Add(value); + } + } + public IList EnvironmentNames { get; private set; } + public bool Restore { get; set; } + public string RestoreFromPath { get; set; } + public string RestoreCustomOptions { get; set; } + public int RestoreTimeout { get; set; } + public string CreateDatabaseCustomScript { get; set; } + public string OutputPath { get; set; } + public bool WarnOnOneTimeScriptChanges { get; set; } + public bool WarnAndIgnoreOnOneTimeScriptChanges { get; set; } + public bool Silent { get; set; } + public string DatabaseType { get; set; } + public bool Drop { get; set; } + public bool DoNotCreateDatabase { get; set; } + public bool DoNotAlterDatabase { get; set; } + public bool WithTransaction { get; set; } + public RecoveryMode RecoveryMode { get; set; } + [Obsolete("Use RecoveryMode = Simple")] + public bool RecoveryModeSimple { get; set; } + public bool Debug { get; set; } + public bool DryRun { get; set; } + public bool Baseline { get; set; } + public bool RunAllAnyTimeScripts { get; set; } + public bool DisableTokenReplacement { get; set; } + public bool SearchAllSubdirectoriesInsteadOfTraverse { get; set; } + public bool DisableOutput { get; set; } + public Dictionary UserTokens { get; set; } + public bool Initialize { get; set; } + public string ConfigurationFile { get; set; } + public System.Text.Encoding DefaultEncoding { get; set; } + + public IDictionary to_token_dictionary() + { + var tokens = new Dictionary(StringComparer.OrdinalIgnoreCase); + tokens["AfterMigrationFolderName"] = AfterMigrationFolderName.to_string(); + tokens["AlterDatabaseFolderName"] = AlterDatabaseFolderName.to_string(); + tokens["Baseline"] = Baseline.to_string(); + tokens["BeforeMigrationFolderName"] = BeforeMigrationFolderName.to_string(); + tokens["CommandTimeout"] = CommandTimeout.to_string(); + tokens["CommandTimeoutAdmin"] = CommandTimeoutAdmin.to_string(); + tokens["ConfigurationFile"] = ConfigurationFile.to_string(); + tokens["ConnectionString"] = ConnectionString.to_string(); + tokens["ConnectionStringAdmin"] = ConnectionStringAdmin.to_string(); + tokens["CreateDatabaseCustomScript"] = CreateDatabaseCustomScript.to_string(); + tokens["DatabaseName"] = DatabaseName.to_string(); + tokens["DatabaseType"] = DatabaseType.to_string(); + tokens["Debug"] = Debug.to_string(); + tokens["DisableOutput"] = DisableOutput.to_string(); + tokens["DisableTokenReplacement"] = DisableTokenReplacement.to_string(); + tokens["DoNotAlterDatabase"] = DoNotAlterDatabase.to_string(); + tokens["DoNotCreateDatabase"] = DoNotCreateDatabase.to_string(); + tokens["DownFolderName"] = DownFolderName.to_string(); + tokens["Drop"] = Drop.to_string(); + tokens["DryRun"] = DryRun.to_string(); + tokens["EnvironmentName"] = string.Join(",", EnvironmentNames); + tokens["EnvironmentNames"] = string.Join(",", EnvironmentNames); + tokens["FunctionsFolderName"] = FunctionsFolderName.to_string(); + tokens["IndexesFolderName"] = IndexesFolderName.to_string(); + tokens["Initialize"] = Initialize.to_string(); + tokens["OutputPath"] = OutputPath.to_string(); + tokens["PermissionsFolderName"] = PermissionsFolderName.to_string(); + tokens["RecoveryMode"] = RecoveryMode.to_string(); + tokens["RepositoryPath"] = RepositoryPath.to_string(); + tokens["Restore"] = Restore.to_string(); + tokens["RestoreCustomOptions"] = RestoreCustomOptions.to_string(); + tokens["RestoreFromPath"] = RestoreFromPath.to_string(); + tokens["RestoreTimeout"] = RestoreTimeout.to_string(); + tokens["RunAfterCreateDatabaseFolderName"] = RunAfterCreateDatabaseFolderName.to_string(); + tokens["RunAfterOtherAnyTimeScriptsFolderName"] = RunAfterOtherAnyTimeScriptsFolderName.to_string(); + tokens["RunAllAnyTimeScripts"] = RunAllAnyTimeScripts.to_string(); + tokens["RunBeforeUpFolderName"] = RunBeforeUpFolderName.to_string(); + tokens["RunFirstAfterUpFolderName"] = RunFirstAfterUpFolderName.to_string(); + tokens["SchemaName"] = SchemaName.to_string(); + tokens["ScriptsRunErrorsTableName"] = ScriptsRunErrorsTableName.to_string(); + tokens["ScriptsRunTableName"] = ScriptsRunTableName.to_string(); + tokens["SearchAllSubdirectoriesInsteadOfTraverse"] = SearchAllSubdirectoriesInsteadOfTraverse.to_string(); + tokens["ServerName"] = ServerName.to_string(); + tokens["Silent"] = Silent.to_string(); + tokens["SprocsFolderName"] = SprocsFolderName.to_string(); + tokens["SqlFilesDirectory"] = SqlFilesDirectory.to_string(); + tokens["TriggersFolderName"] = TriggersFolderName.to_string(); + tokens["UpFolderName"] = UpFolderName.to_string(); + tokens["Version"] = Version.to_string(); + tokens["VersionFile"] = VersionFile.to_string(); + tokens["VersionTableName"] = VersionTableName.to_string(); + tokens["VersionXPath"] = VersionXPath.to_string(); + tokens["ViewsFolderName"] = ViewsFolderName.to_string(); + tokens["WarnAndIgnoreOnOneTimeScriptChanges"] = WarnAndIgnoreOnOneTimeScriptChanges.to_string(); + tokens["WarnOnOneTimeScriptChanges"] = WarnOnOneTimeScriptChanges.to_string(); + tokens["WithTransaction"] = WithTransaction.to_string(); + + if (UserTokens != null) + { + foreach (var t in UserTokens) + { + tokens[t.Key] = t.Value; + } + } + + return tokens; + } + + } } \ No newline at end of file diff --git a/product/roundhouse/consoles/InteractivePrompt.cs b/product/roundhouse.core/consoles/InteractivePrompt.cs similarity index 93% rename from product/roundhouse/consoles/InteractivePrompt.cs rename to product/roundhouse.core/consoles/InteractivePrompt.cs index 26157ded..e9ea5630 100644 --- a/product/roundhouse/consoles/InteractivePrompt.cs +++ b/product/roundhouse.core/consoles/InteractivePrompt.cs @@ -1,85 +1,91 @@ -using System; -using roundhouse.infrastructure.app; -using roundhouse.infrastructure.logging; - -namespace roundhouse.consoles -{ - public class InteractivePrompt - { - public static bool in_interactive_mode(ConfigurationPropertyHolder configuration_property_holder) - { - if (Environment.UserInteractive && !configuration_property_holder.Silent) return true; - return false; - } - - public static void write_header(ConfigurationPropertyHolder configuration_property_holder) - { - Log.bound_to(typeof(InteractivePrompt)).log_an_info_event_containing("RoundhousE Interactive Setup (only prompts if not in silent mode)"); - Log.bound_to(typeof(InteractivePrompt)).log_an_info_event_containing("{0}", "=".PadRight(50, '=')); - } - - public static string get_user(string default_user_name, ConfigurationPropertyHolder configuration_property_holder) - { - var user_name = string.Empty; - if (in_interactive_mode(configuration_property_holder)) - { - Console.WriteLine("Please enter a user name and press enter (leave empty for '{0}')", default_user_name); - user_name = Console.ReadLine(); - } - user_name = !string.IsNullOrEmpty(user_name) ? user_name : default_user_name; - Log.bound_to(typeof(InteractivePrompt)).log_an_info_event_containing("Using '{0}' for the user name.", user_name); - - return user_name; - } - - public static string get_password(string default_password, ConfigurationPropertyHolder configuration_property_holder) - { - string password = string.Empty; - - if (in_interactive_mode(configuration_property_holder)) - { - Console.WriteLine("Please enter a password and press enter (leave empty for '{0}')", default_password); - - //http://www.c-sharpcorner.com/Forums/Thread/32102/ - ConsoleKeyInfo info = Console.ReadKey(true); - while (info.Key != ConsoleKey.Enter) - { - if (info.Key != ConsoleKey.Backspace) - { - Console.Write("*"); - password += info.KeyChar; - info = Console.ReadKey(true); - } - else if (info.Key == ConsoleKey.Backspace) - { - if (!string.IsNullOrEmpty(password)) - { - password = password.Substring(0, password.Length - 1); - // get the location of the cursor - int pos = Console.CursorLeft; - // move the cursor to the left by one character - Console.SetCursorPosition(pos - 1, Console.CursorTop); - // replace it with space - Console.Write(" "); - // move the cursor to the left by one character again - Console.SetCursorPosition(pos - 1, Console.CursorTop); - } - info = Console.ReadKey(true); - } - } - for (int i = 0; i < password.Length; i++) Console.Write("*"); - } - Console.WriteLine(); - password = !string.IsNullOrEmpty(password) ? password : default_password; - Log.bound_to(typeof(InteractivePrompt)).log_an_info_event_containing("Using '*******' for the password. When YOU type hunter2, it shows to us as '*******'. ;-)"); - - return password; - } - - public static void write_footer() - { - Log.bound_to(typeof(InteractivePrompt)).log_an_info_event_containing("Completed. Thank you!"); - Log.bound_to(typeof(InteractivePrompt)).log_an_info_event_containing("{0}", "=".PadRight(50, '=')); - } - } +using System; +using roundhouse.infrastructure.app; +using roundhouse.infrastructure.logging; + +namespace roundhouse.consoles +{ + public static class InteractivePrompt + { + public static bool in_interactive_mode(ConfigurationPropertyHolder configuration_property_holder) + { + if (Environment.UserInteractive && !configuration_property_holder.Silent) + { + return true; + } + return false; + } + + public static void write_header(ConfigurationPropertyHolder configuration_property_holder) + { + Log.bound_to(typeof(InteractivePrompt)).log_an_info_event_containing("RoundhousE Interactive Setup (only prompts if not in silent mode)"); + Log.bound_to(typeof(InteractivePrompt)).log_an_info_event_containing("{0}", "=".PadRight(50, '=')); + } + + public static string get_user(string default_user_name, ConfigurationPropertyHolder configuration_property_holder) + { + var user_name = string.Empty; + if (in_interactive_mode(configuration_property_holder)) + { + Console.WriteLine("Please enter a user name and press enter (leave empty for '{0}')", default_user_name); + user_name = Console.ReadLine(); + } + user_name = !string.IsNullOrEmpty(user_name) ? user_name : default_user_name; + Log.bound_to(typeof(InteractivePrompt)).log_an_info_event_containing("Using '{0}' for the user name.", user_name); + + return user_name; + } + + public static string get_password(string default_password, ConfigurationPropertyHolder configuration_property_holder) + { + string password = string.Empty; + + if (in_interactive_mode(configuration_property_holder)) + { + Console.WriteLine("Please enter a password and press enter (leave empty for '{0}')", default_password); + + //http://www.c-sharpcorner.com/Forums/Thread/32102/ + ConsoleKeyInfo info = Console.ReadKey(true); + while (info.Key != ConsoleKey.Enter) + { + if (info.Key != ConsoleKey.Backspace) + { + Console.Write("*"); + password += info.KeyChar; + info = Console.ReadKey(true); + } + else if (info.Key == ConsoleKey.Backspace) + { + if (!string.IsNullOrEmpty(password)) + { + password = password.Substring(0, password.Length - 1); + // get the location of the cursor + int pos = Console.CursorLeft; + // move the cursor to the left by one character + Console.SetCursorPosition(pos - 1, Console.CursorTop); + // replace it with space + Console.Write(" "); + // move the cursor to the left by one character again + Console.SetCursorPosition(pos - 1, Console.CursorTop); + } + info = Console.ReadKey(true); + } + } + for (int i = 0; i < password.Length; i++) + { + Console.Write("*"); + } + } + Console.WriteLine(); + password = !string.IsNullOrEmpty(password) ? password : default_password; + Log.bound_to(typeof(InteractivePrompt)).log_an_info_event_containing("Using '*******' for the password. When YOU type hunter2, it shows to us as '*******'. ;-)"); + + return password; + } + + public static void write_footer() + { + Log.bound_to(typeof(InteractivePrompt)).log_an_info_event_containing("Completed. Thank you!"); + Log.bound_to(typeof(InteractivePrompt)).log_an_info_event_containing("{0}", "=".PadRight(50, '=')); + } + } } \ No newline at end of file diff --git a/product/roundhouse/cryptography/CryptographicService.cs b/product/roundhouse.core/cryptography/CryptographicService.cs similarity index 96% rename from product/roundhouse/cryptography/CryptographicService.cs rename to product/roundhouse.core/cryptography/CryptographicService.cs index 577244a1..0848fe4b 100644 --- a/product/roundhouse/cryptography/CryptographicService.cs +++ b/product/roundhouse.core/cryptography/CryptographicService.cs @@ -1,9 +1,9 @@ -namespace roundhouse.cryptography -{ - public interface CryptographicService - { - //something encrypt; - //something else decrypt; - string hash(string clear_text_of_what_to_hash); - } +namespace roundhouse.cryptography +{ + public interface CryptographicService + { + //something encrypt; + //something else decrypt; + string hash(string clear_text_of_what_to_hash); + } } \ No newline at end of file diff --git a/product/roundhouse/cryptography/LocalMD5Implementation.cs b/product/roundhouse.core/cryptography/LocalMD5Implementation.cs similarity index 100% rename from product/roundhouse/cryptography/LocalMD5Implementation.cs rename to product/roundhouse.core/cryptography/LocalMD5Implementation.cs diff --git a/product/roundhouse/cryptography/MD5CryptographicService.cs b/product/roundhouse.core/cryptography/MD5CryptographicService.cs similarity index 100% rename from product/roundhouse/cryptography/MD5CryptographicService.cs rename to product/roundhouse.core/cryptography/MD5CryptographicService.cs diff --git a/product/roundhouse/databases/AdoNetDatabase.cs b/product/roundhouse.core/databases/AdoNetDatabase.cs similarity index 93% rename from product/roundhouse/databases/AdoNetDatabase.cs rename to product/roundhouse.core/databases/AdoNetDatabase.cs index 1fe812c3..6ef86cfc 100644 --- a/product/roundhouse/databases/AdoNetDatabase.cs +++ b/product/roundhouse.core/databases/AdoNetDatabase.cs @@ -1,218 +1,225 @@ -using System.Linq; - -namespace roundhouse.databases -{ - using System.Collections.Generic; - using System.Data; - using System.Data.Common; - using connections; - using infrastructure.app; - using infrastructure.logging; - using parameters; - - public abstract class AdoNetDatabase : DefaultDatabase - { - private bool split_batches_in_ado = true; - - public override bool split_batch_statements - { - get { return split_batches_in_ado; } - set { split_batches_in_ado = value; } - } - - protected IDbTransaction transaction; - - private DbProviderFactory provider_factory; - - protected virtual AdoNetConnection GetAdoNetConnection(string conn_string) - { - provider_factory = get_db_provider_factory(); - IDbConnection connection = provider_factory.CreateConnection(); - connection_specific_setup(connection); - - connection.ConnectionString = conn_string; - return new AdoNetConnection(connection); - } - - protected abstract DbProviderFactory get_db_provider_factory(); - - protected virtual void connection_specific_setup(IDbConnection connection) - { - } - - - public override void open_admin_connection() - { - Log.bound_to(this) - .log_a_debug_event_containing("Opening admin connection to '{0}'", admin_connection_string); - admin_connection = GetAdoNetConnection(admin_connection_string); - admin_connection.open(); - } - - public override void close_admin_connection() - { - Log.bound_to(this).log_a_debug_event_containing("Closing admin connection"); - if (admin_connection != null) - { - admin_connection.clear_pool(); - admin_connection.close(); - admin_connection.Dispose(); - admin_connection = null; - } - } - - public override void open_connection(bool with_transaction) - { - Log.bound_to(this).log_a_debug_event_containing("Opening connection to '{0}'", connection_string); - server_connection = GetAdoNetConnection(connection_string); - server_connection.open(); - - set_repository(); - - if (with_transaction) - { - transaction = server_connection.underlying_type().BeginTransaction(); - repository.start(true); - } - } - - public override void close_connection() - { - Log.bound_to(this).log_a_debug_event_containing("Closing connection"); - if (transaction != null) - { - transaction.Commit(); - transaction = null; - } - - if (repository != null) - { - repository.finish(); - } - - if (server_connection != null) - { - server_connection.clear_pool(); - server_connection.close(); - server_connection.Dispose(); - server_connection = null; - } - } - - public override void rollback() - { - Log.bound_to(this).log_a_debug_event_containing("Rolling back changes"); - repository.rollback(); - - if (transaction != null) - { - //rollback previous transaction - transaction.Rollback(); - server_connection.close(); - - //open a new transaction - server_connection.open(); - //use_database(database_name); - transaction = server_connection.underlying_type().BeginTransaction(); - repository.start(true); - } - } - - protected override void run_sql(string sql_to_run, ConnectionType connection_type, - IList> parameters) - { - if (string.IsNullOrEmpty(sql_to_run)) return; - - if (transaction == null) - { - retry_policy.Execute(() => run_command_with(sql_to_run, connection_type, parameters)); - } - else - { - run_command_with(sql_to_run, connection_type, parameters); - } - } - - private void run_command_with(string sql_to_run, ConnectionType connection_type, - IList> parameters) - { - using (IDbCommand command = setup_database_command(sql_to_run, connection_type, parameters)) - { - command.ExecuteNonQuery(); - } - } - - protected override object run_sql_scalar(string sql_to_run, ConnectionType connection_type, - IList> parameters) - { - object return_value = new object(); - if (string.IsNullOrEmpty(sql_to_run)) return return_value; - - using (IDbCommand command = setup_database_command(sql_to_run, connection_type, null)) - { - if (transaction == null) - { - return_value = retry_policy.Execute(() => command.ExecuteScalar()); - } - else - { - return_value = command.ExecuteScalar(); - } - } - - return return_value; - } - - protected IDbCommand setup_database_command(string sql_to_run, ConnectionType connection_type, - IEnumerable> parameters) - { - IDbCommand command = null; - - - switch (connection_type) - { - case ConnectionType.Default: - if (server_connection == null || - server_connection.underlying_type().State != ConnectionState.Open) - { - open_connection(false); - } - - Log.bound_to(this).log_a_debug_event_containing("Setting up command for normal connection"); - command = server_connection.underlying_type().CreateCommand(); - command.CommandTimeout = command_timeout; - break; - case ConnectionType.Admin: - if (admin_connection == null || - admin_connection.underlying_type().State != ConnectionState.Open) - { - open_admin_connection(); - } - - Log.bound_to(this).log_a_debug_event_containing("Setting up command for admin connection"); - command = admin_connection.underlying_type().CreateCommand(); - command.CommandTimeout = admin_command_timeout; - break; - } - - if (parameters != null) - { - foreach (IParameter parameter in parameters) - { - command.Parameters.Add(parameter.underlying_type); - } - } - - if (connection_type != ConnectionType.Admin) - { - command.Transaction = transaction; - } - - command.CommandText = sql_to_run; - command.CommandType = CommandType.Text; - - - return command; - } - } +using System; +using System.Linq; + +namespace roundhouse.databases +{ + using System.Collections.Generic; + using System.Data; + using System.Data.Common; + using connections; + using infrastructure.app; + using infrastructure.logging; + using parameters; + + public abstract class AdoNetDatabase : DefaultDatabase + { + private bool split_batches_in_ado = true; + + public override bool split_batch_statements + { + get { return split_batches_in_ado; } + set { split_batches_in_ado = value; } + } + + protected IDbTransaction transaction; + + protected virtual AdoNetConnection GetAdoNetConnection(string conn_string) + { + var provider_factory = get_db_provider_factory(); + IDbConnection connection = provider_factory.CreateConnection(); + connection_specific_setup(connection); + + connection.ConnectionString = conn_string; + return new AdoNetConnection(connection); + } + + protected abstract DbProviderFactory get_db_provider_factory(); + + protected virtual void connection_specific_setup(IDbConnection connection) + { + } + + + public override void open_admin_connection() + { + Log.bound_to(this) + .log_a_debug_event_containing("Opening admin connection to '{0}'", admin_connection_string); + admin_connection = GetAdoNetConnection(admin_connection_string); + admin_connection.open(); + } + + public override void close_admin_connection() + { + Log.bound_to(this).log_a_debug_event_containing("Closing admin connection"); + if (admin_connection != null) + { + admin_connection.clear_pool(); + admin_connection.close(); + admin_connection.Dispose(); + admin_connection = null; + } + } + + public override void open_connection(bool with_transaction) + { + Log.bound_to(this).log_a_debug_event_containing("Opening connection to '{0}'", connection_string); + server_connection = GetAdoNetConnection(connection_string); + server_connection.open(); + + set_repository(); + + if (with_transaction) + { + transaction = server_connection.underlying_type().BeginTransaction(); + repository.start(true); + } + } + + public override void close_connection() + { + Log.bound_to(this).log_a_debug_event_containing("Closing connection"); + if (transaction != null) + { + transaction.Commit(); + transaction = null; + } + + if (repository != null) + { + repository.finish(); + } + + if (server_connection != null) + { + server_connection.clear_pool(); + server_connection.close(); + server_connection.Dispose(); + server_connection = null; + } + } + + public override void rollback() + { + Log.bound_to(this).log_a_debug_event_containing("Rolling back changes"); + repository.rollback(); + + if (transaction != null) + { + //rollback previous transaction + transaction.Rollback(); + server_connection.close(); + + //open a new transaction + server_connection.open(); + //use_database(database_name); + transaction = server_connection.underlying_type().BeginTransaction(); + repository.start(true); + } + } + + protected override void run_sql(string sql_to_run, ConnectionType connection_type, + IList> parameters) + { + if (string.IsNullOrEmpty(sql_to_run)) + { + return; + } + + if (transaction == null) + { + retry_policy.Execute(() => run_command_with(sql_to_run, connection_type, parameters)); + } + else + { + run_command_with(sql_to_run, connection_type, parameters); + } + } + + private void run_command_with(string sql_to_run, ConnectionType connection_type, + IList> parameters) + { + using (IDbCommand command = setup_database_command(sql_to_run, connection_type, parameters)) + { + command.ExecuteNonQuery(); + } + } + + protected override object run_sql_scalar(string sql_to_run, ConnectionType connection_type, + IList> parameters) + { + object return_value = new object(); + if (string.IsNullOrEmpty(sql_to_run)) + { + return return_value; + } + + using (IDbCommand command = setup_database_command(sql_to_run, connection_type, null)) + { + if (transaction == null) + { + return_value = retry_policy.Execute(() => command.ExecuteScalar()); + } + else + { + return_value = command.ExecuteScalar(); + } + } + + return return_value; + } + + protected IDbCommand setup_database_command(string sql_to_run, ConnectionType connection_type, + IEnumerable> parameters) + { + IDbCommand command = null; + + + switch (connection_type) + { + case ConnectionType.Default: + if (server_connection == null || + server_connection.underlying_type().State != ConnectionState.Open) + { + open_connection(false); + } + + Log.bound_to(this).log_a_debug_event_containing("Setting up command for normal connection"); + command = server_connection.underlying_type().CreateCommand(); + command.CommandTimeout = command_timeout; + break; + case ConnectionType.Admin: + if (admin_connection == null || + admin_connection.underlying_type().State != ConnectionState.Open) + { + open_admin_connection(); + } + + Log.bound_to(this).log_a_debug_event_containing("Setting up command for admin connection"); + command = admin_connection.underlying_type().CreateCommand(); + command.CommandTimeout = admin_command_timeout; + break; + default: + throw new ArgumentOutOfRangeException(nameof(connection_type), connection_type, "Invalid connection type: " + connection_type); + } + + if (parameters != null) + { + foreach (IParameter parameter in parameters) + { + command.Parameters.Add(parameter.underlying_type); + } + } + + if (connection_type != ConnectionType.Admin) + { + command.Transaction = transaction; + } + + command.CommandText = sql_to_run; + command.CommandType = CommandType.Text; + + + return command; + } + } } \ No newline at end of file diff --git a/product/roundhouse/databases/Database.cs b/product/roundhouse.core/databases/Database.cs similarity index 98% rename from product/roundhouse/databases/Database.cs rename to product/roundhouse.core/databases/Database.cs index 6de9d241..9e507158 100644 --- a/product/roundhouse/databases/Database.cs +++ b/product/roundhouse.core/databases/Database.cs @@ -1,113 +1,113 @@ -// :iji -// #WWWWWW -// :,#WWWWWWWGW -// ,WWWWWWWWWWWWW;K -// iWWWWWWWWWWWWWWW D -// WWWWWWWWWWWWWWWWWW: -// WWWWWWWWWWWWWWWWWWWW -// ,WWWWWWWWWWWWWWWWWWWW. -// iWWWWWWWWWWWWWWWWWWWWi -// WWWWWWWWWWWWWWWWWWWWK -// ,WWWWWWWWWWtWWWWWWWWW# -// LWWWWWWWWWL: LW#WWWWWW: -// ,WWWWWWWW#i ,WWWWWWj -// ,WWWWGWWW .WWWWWWW -// WWWWWWWK EWWWWW# -// #WWW::: WWWWW# -// tWW. .WWW#W# -// DW j :EKGf WWD.WW -// .G. #WWWE WWW#W .fK.W# -// #j LWWW# L , Li WD -// .EL ;WEWG W :W -// E;: i W, :W KW -// #j W. iE tWE -// fKWD D W K# LW -// :WWWD WGW ,G i. -// :WWW#,:#iK EWW:L: W#: G -// fWW K # , :WWWW;. t #WL, WL -// WW#f :tjDWWWWWWWWWWWWWWW EW -// .WWWGL WWWWWWWWWt: GWWEW WW: -// WWWW,. #WWWWWWWWE,,iEWiW# GWWj -// #WWWWD WWWWWWWWWWWWWWWWL fWWWW; -// :WWWWfD; WWWWWWWWWWWWWWW. ;WWWWWWL -// #WWWW.W: WWWWWWWWWWWWWWGWWWWWWWWWW -// iWWWWWK, #WWWWWWWWWWWWWWWWWWWWWWWW# -// WWWWW:D :WWWWWWWWWWWWWWWWWWWWWWWWWW. -// :WWWW# G #WWWWWWWWWWWWWWWWWWWWWWWWW, -// WWWWWW, WWWWWWWWWWWWWWWWWWWWWWWWWW -// ;WWWWWW.K KWWWWWWWWWWWWWWWWWWWWWWWWWD -// DWWWWWWW L WWWWWWWWWWWWWWWWWWWWWWWWWWf -// WWWWWWW L: :WWWWWWWWWWWWWWWWWWWWWWWWWWK -// #WWWWWE: jW KWWWWWWWWWWWWWWWWWWWWWWWWWW; -// WWWWWWWGt; ; WWWWWWWWWWWWWWWWWWWWWWWWWWW -// GWWWWWWWW; GjEjtWWWWWWWWWWWWWWWWWWWWWWEWWW. -// WWWWWWtKtWt WWW EWWWWWWWWWWWWWWWWWWj #WD -//;. WWWWWWWi DKGGWWK WWWWWWWWWWWWWWWWL WD -//;: .WWWWWWWW W WWWijWWWWWWWWWWWWWWf #E -//t : WWWWWL EW: :WG,WWK WWWWWWWWWWWWW, #E -//L i DWWWWiWE .. : fDGD:j WWWWWWWWWWW LE -//G .K WWWWWfLWi K W .f. jWWWWWWWWW. tL -//G #K##fWWW#G :DLG. W WWWWWWWWW t -//fjj; t LWE tKWG : WWWWWWWW: L -//Df j :WWK WWW:.Dt LWWWWWWWj W -//WG W WWG WWWWf E WL .WWW G -//WWKK :WG WWWWjiG .Li :Wi . -//#WW .WW WWWWW G; : K -//WWWL WWj :WWWWW#D , L -//#WWW L GWW KWWWWWL .# K -//#WWK G W:WW WW#WKE LL f -//jWWW,Ef Lf . -// t##K# i, j -// ;i - -namespace roundhouse.databases -{ - using System; - using infrastructure.app; - - public interface Database : IDisposable - { - ConfigurationPropertyHolder configuration { get; set; } - string server_name { get; set; } - string database_name { get; set; } - string provider { get; set; } - string connection_string { get; set; } - string admin_connection_string { get; set; } - string roundhouse_schema_name { get; set; } - string version_table_name { get; set; } - string scripts_run_table_name { get; set; } - string scripts_run_errors_table_name { get; set; } - string user_name { get; set; } - string sql_statement_separator_regex_pattern { get; } - int command_timeout { get; set; } - int admin_command_timeout { get; set; } - int restore_timeout { get; set; } - bool split_batch_statements { get; set; } - bool supports_ddl_transactions { get; } - - void initialize_connections(ConfigurationPropertyHolder configuration_property_holder); - void open_connection(bool with_transaction); - void close_connection(); - void open_admin_connection(); - void close_admin_connection(); - void rollback(); - - bool create_database_if_it_doesnt_exist(string custom_create_database_script); - void set_recovery_mode(bool simple); - void backup_database(string output_path_minus_database); - void restore_database(string restore_from_path, string custom_restore_options); - void delete_database_if_it_exists(); - void run_database_specific_tasks(); - void create_or_update_roundhouse_tables(); - void run_sql(string sql_to_run,ConnectionType connection_type); - object run_sql_scalar(string sql_to_run, ConnectionType connection_type); - void insert_script_run(string script_name, string sql_to_run, string sql_to_run_hash, bool run_this_script_once, long version_id); - void insert_script_run_error(string script_name, string sql_to_run, string sql_erroneous_part, string error_message, string repository_version, string repository_path); - - string get_version(string repository_path); - long insert_version_and_get_version_id(string repository_path, string repository_version); - bool has_run_script_already(string script_name); - string get_current_script_hash(string script_name); - //object run_sql_scalar(string sql_to_run); - } +// :iji +// #WWWWWW +// :,#WWWWWWWGW +// ,WWWWWWWWWWWWW;K +// iWWWWWWWWWWWWWWW D +// WWWWWWWWWWWWWWWWWW: +// WWWWWWWWWWWWWWWWWWWW +// ,WWWWWWWWWWWWWWWWWWWW. +// iWWWWWWWWWWWWWWWWWWWWi +// WWWWWWWWWWWWWWWWWWWWK +// ,WWWWWWWWWWtWWWWWWWWW# +// LWWWWWWWWWL: LW#WWWWWW: +// ,WWWWWWWW#i ,WWWWWWj +// ,WWWWGWWW .WWWWWWW +// WWWWWWWK EWWWWW# +// #WWW::: WWWWW# +// tWW. .WWW#W# +// DW j :EKGf WWD.WW +// .G. #WWWE WWW#W .fK.W# +// #j LWWW# L , Li WD +// .EL ;WEWG W :W +// E;: i W, :W KW +// #j W. iE tWE +// fKWD D W K# LW +// :WWWD WGW ,G i. +// :WWW#,:#iK EWW:L: W#: G +// fWW K # , :WWWW;. t #WL, WL +// WW#f :tjDWWWWWWWWWWWWWWW EW +// .WWWGL WWWWWWWWWt: GWWEW WW: +// WWWW,. #WWWWWWWWE,,iEWiW# GWWj +// #WWWWD WWWWWWWWWWWWWWWWL fWWWW; +// :WWWWfD; WWWWWWWWWWWWWWW. ;WWWWWWL +// #WWWW.W: WWWWWWWWWWWWWWGWWWWWWWWWW +// iWWWWWK, #WWWWWWWWWWWWWWWWWWWWWWWW# +// WWWWW:D :WWWWWWWWWWWWWWWWWWWWWWWWWW. +// :WWWW# G #WWWWWWWWWWWWWWWWWWWWWWWWW, +// WWWWWW, WWWWWWWWWWWWWWWWWWWWWWWWWW +// ;WWWWWW.K KWWWWWWWWWWWWWWWWWWWWWWWWWD +// DWWWWWWW L WWWWWWWWWWWWWWWWWWWWWWWWWWf +// WWWWWWW L: :WWWWWWWWWWWWWWWWWWWWWWWWWWK +// #WWWWWE: jW KWWWWWWWWWWWWWWWWWWWWWWWWWW; +// WWWWWWWGt; ; WWWWWWWWWWWWWWWWWWWWWWWWWWW +// GWWWWWWWW; GjEjtWWWWWWWWWWWWWWWWWWWWWWEWWW. +// WWWWWWtKtWt WWW EWWWWWWWWWWWWWWWWWWj #WD +//;. WWWWWWWi DKGGWWK WWWWWWWWWWWWWWWWL WD +//;: .WWWWWWWW W WWWijWWWWWWWWWWWWWWf #E +//t : WWWWWL EW: :WG,WWK WWWWWWWWWWWWW, #E +//L i DWWWWiWE .. : fDGD:j WWWWWWWWWWW LE +//G .K WWWWWfLWi K W .f. jWWWWWWWWW. tL +//G #K##fWWW#G :DLG. W WWWWWWWWW t +//fjj; t LWE tKWG : WWWWWWWW: L +//Df j :WWK WWW:.Dt LWWWWWWWj W +//WG W WWG WWWWf E WL .WWW G +//WWKK :WG WWWWjiG .Li :Wi . +//#WW .WW WWWWW G; : K +//WWWL WWj :WWWWW#D , L +//#WWW L GWW KWWWWWL .# K +//#WWK G W:WW WW#WKE LL f +//jWWW,Ef Lf . +// t##K# i, j +// ;i + +namespace roundhouse.databases +{ + using System; + using infrastructure.app; + + public interface Database : IDisposable + { + ConfigurationPropertyHolder configuration { get; set; } + string server_name { get; set; } + string database_name { get; set; } + string provider { get; set; } + string connection_string { get; set; } + string admin_connection_string { get; set; } + string roundhouse_schema_name { get; set; } + string version_table_name { get; set; } + string scripts_run_table_name { get; set; } + string scripts_run_errors_table_name { get; set; } + string user_name { get; set; } + string sql_statement_separator_regex_pattern { get; } + int command_timeout { get; set; } + int admin_command_timeout { get; set; } + int restore_timeout { get; set; } + bool split_batch_statements { get; set; } + bool supports_ddl_transactions { get; } + + void initialize_connections(ConfigurationPropertyHolder configuration_property_holder); + void open_connection(bool with_transaction); + void close_connection(); + void open_admin_connection(); + void close_admin_connection(); + void rollback(); + + bool create_database_if_it_doesnt_exist(string custom_create_database_script); + void set_recovery_mode(bool simple); + void backup_database(string output_path_minus_database); + void restore_database(string restore_from_path, string custom_restore_options); + void delete_database_if_it_exists(); + void run_database_specific_tasks(); + void create_or_update_roundhouse_tables(); + void run_sql(string sql_to_run,ConnectionType connection_type); + object run_sql_scalar(string sql_to_run, ConnectionType connection_type); + void insert_script_run(string script_name, string sql_to_run, string sql_to_run_hash, bool run_this_script_once, long version_id); + void insert_script_run_error(string script_name, string sql_to_run, string sql_erroneous_part, string error_message, string repository_version, string repository_path); + + string get_version(string repository_path); + long insert_version_and_get_version_id(string repository_path, string repository_version); + bool has_run_script_already(string script_name); + string get_current_script_hash(string script_name); + //object run_sql_scalar(string sql_to_run); + } } \ No newline at end of file diff --git a/product/roundhouse/databases/DefaultDatabase.cs b/product/roundhouse.core/databases/DefaultDatabase.cs similarity index 97% rename from product/roundhouse/databases/DefaultDatabase.cs rename to product/roundhouse.core/databases/DefaultDatabase.cs index 08187f2c..5cec2fd1 100644 --- a/product/roundhouse/databases/DefaultDatabase.cs +++ b/product/roundhouse.core/databases/DefaultDatabase.cs @@ -1,398 +1,397 @@ -using Polly; -using Polly.Retry; - -namespace roundhouse.databases -{ - using System; - using System.Collections.Generic; - using System.Data; - using System.Linq; - using connections; - using infrastructure.app; - using infrastructure.app.tokens; - using infrastructure.extensions; - using infrastructure.logging; - using infrastructure.persistence; - using model; - using NHibernate; - using NHibernate.Cfg; - using NHibernate.Criterion; - using NHibernate.Tool.hbm2ddl; - using parameters; - using sqlsplitters; - using Environment = System.Environment; - using Version = model.Version; - - public abstract class DefaultDatabase : Database - { - protected RetryPolicy retry_policy = Policy.Handle().Retry(0); - - public ConfigurationPropertyHolder configuration { get; set; } - public string server_name { get; set; } - public string database_name { get; set; } - public string provider { get; set; } - public string connection_string { get; set; } - public string admin_connection_string { get; set; } - public string roundhouse_schema_name { get; set; } - public string version_table_name { get; set; } - public string scripts_run_table_name { get; set; } - public string scripts_run_errors_table_name { get; set; } - public string user_name { get; set; } - public string master_database_name { get; set; } - public IRepository repository { get; set; } - - public virtual string sql_statement_separator_regex_pattern - { - get { return @"(?^(?:[\s\t])*(?:-{2}).*$)|(?/{1}\*{1}[\S\s]*?\*{1}/{1})|(?'{1}(?:[^']|\n[^'])*?'{1})|(?^|\s)(?\;)(?\s|$)"; } - } - - public int command_timeout { get; set; } - public int admin_command_timeout { get; set; } - public int restore_timeout { get; set; } - protected bool split_batches = true; - - public virtual bool split_batch_statements - { - get { return split_batches; } - set { split_batches = value; } - } - - public virtual bool supports_ddl_transactions - { - get { return true; } - } - - protected IConnection server_connection; - protected IConnection admin_connection; - - private bool disposing; - private Dictionary scripts_cache; - - //this method must set the provider - public abstract void initialize_connections(ConfigurationPropertyHolder configuration_property_holder); - public abstract void set_provider(); - - public void set_repository() - { - NHibernateSessionFactoryBuilder session_factory_builder = new NHibernateSessionFactoryBuilder(configuration); - Configuration cfg = null; - ISessionFactory factory = session_factory_builder.build_session_factory(x => { cfg = x; }); - repository = new Repository(factory, cfg); - } - - public abstract void open_connection(bool with_transaction); - public abstract void close_connection(); - public abstract void open_admin_connection(); - public abstract void close_admin_connection(); - - public abstract void rollback(); - - public abstract string create_database_script(); - public abstract string set_recovery_mode_script(bool simple); - public abstract string restore_database_script(string restore_from_path, string custom_restore_options); - public abstract string delete_database_script(); - - public virtual bool create_database_if_it_doesnt_exist(string custom_create_database_script) - { - bool database_was_created = false; - try - { - string create_script = create_database_script(); - if (!string.IsNullOrEmpty(custom_create_database_script)) - { - create_script = custom_create_database_script; - if (!configuration.DisableTokenReplacement) - { - create_script = TokenReplacer.replace_tokens(configuration, create_script); - } - } - - if (split_batch_statements) - { - foreach (var sql_statement in StatementSplitter.split_sql_on_regex_and_remove_empty_statements(create_script, sql_statement_separator_regex_pattern)) - { - //should only receive a return value once - var return_value = run_sql_scalar_boolean(sql_statement, ConnectionType.Admin); - if (return_value != null) - { - database_was_created = return_value.Value; - } - } - } - else - { - //should only receive a return value once - var return_value = run_sql_scalar_boolean(create_script, ConnectionType.Admin); - database_was_created = return_value.GetValueOrDefault(false); - } - } - catch (Exception ex) - { - Log.bound_to(this).log_a_warning_event_containing( - "{0} with provider {1} does not provide a facility for creating a database at this time.{2}{3}", - GetType(), provider, Environment.NewLine, ex.to_string()); - } - - return database_was_created; - } - - private bool? run_sql_scalar_boolean(string sql_to_run, ConnectionType connection_type) - { - var return_value = run_sql_scalar(sql_to_run, connection_type); - if (return_value != null && return_value != DBNull.Value) - { - return Convert.ToBoolean(return_value); - } - return null; - } - - public void set_recovery_mode(bool simple) - { - try - { - run_sql(set_recovery_mode_script(simple), ConnectionType.Admin); - } - catch (Exception ex) - { - Log.bound_to(this).log_a_warning_event_containing( - "{0} with provider {1} does not provide a facility for setting recovery mode to simple at this time.{2}{3}", - GetType(), provider, Environment.NewLine, ex.Message); - } - } - - public void backup_database(string output_path_minus_database) - { - Log.bound_to(this).log_a_warning_event_containing("{0} with provider {1} does not provide a facility for backing up a database at this time.", - GetType(), provider); - //todo: backup database is not a script - it is a command - //Server sql_server = - // new Server(new ServerConnection(new SqlConnection(build_connection_string(server_name, database_name)))); - //sql_server.BackupDevices.Add(new BackupDevice(sql_server,database_name)); - } - - public void restore_database(string restore_from_path, string custom_restore_options) - { - try - { - int current_connection_timeout = command_timeout; - admin_command_timeout = restore_timeout; - run_sql(restore_database_script(restore_from_path, custom_restore_options), ConnectionType.Admin); - admin_command_timeout = current_connection_timeout; - } - catch (Exception ex) - { - Log.bound_to(this).log_a_warning_event_containing( - "{0} with provider {1} does not provide a facility for restoring a database at this time.{2}{3}", - GetType(), provider, Environment.NewLine, ex.Message); - } - } - - public virtual void delete_database_if_it_exists() - { - try - { - run_sql(delete_database_script(), ConnectionType.Admin); - } - catch (Exception ex) - { - Log.bound_to(this).log_an_error_event_containing( - "{0} with provider {1} does not provide a facility for deleting a database at this time.{2}{3}", - GetType(), provider, Environment.NewLine, ex.Message); - throw; - } - } - - public abstract void run_database_specific_tasks(); - - public virtual void create_or_update_roundhouse_tables() - { - SchemaUpdate s = new SchemaUpdate(repository.nhibernate_configuration); - s.Execute(false, true); - } - - public virtual void run_sql(string sql_to_run, ConnectionType connection_type) - { - Log.bound_to(this).log_a_debug_event_containing("[SQL] Running (on connection '{0}'): {1}{2}", connection_type.ToString(), Environment.NewLine, sql_to_run); - run_sql(sql_to_run, connection_type, null); - } - - public virtual object run_sql_scalar(string sql_to_run, ConnectionType connection_type) - { - Log.bound_to(this).log_a_debug_event_containing("[SQL] Running (on connection '{0}'): {1}{2}", connection_type.ToString(), Environment.NewLine, sql_to_run); - return run_sql_scalar(sql_to_run, connection_type, null); - } - - protected abstract void run_sql(string sql_to_run, ConnectionType connection_type, IList> parameters); - - protected abstract object run_sql_scalar(string sql_to_run, ConnectionType connection_type, IList> parameters); - - public virtual void insert_script_run(string script_name, string sql_to_run, string sql_to_run_hash, bool run_this_script_once, long version_id) - { - ScriptsRun script_run = new ScriptsRun - { - version_id = version_id, - script_name = script_name, - text_of_script = sql_to_run, - text_hash = sql_to_run_hash, - one_time_script = run_this_script_once - }; - - try - { - retry_policy.Execute(() => repository.save_or_update(script_run)); - scripts_cache[script_name] = script_run; - } - catch (Exception ex) - { - Log.bound_to(this).log_an_error_event_containing( - "{0} with provider {1} does not provide a facility for recording scripts run at this time.{2}{3}", - GetType(), provider, Environment.NewLine, ex.Message); - throw; - } - } - - public virtual void insert_script_run_error(string script_name, string sql_to_run, string sql_erroneous_part, string error_message, string repository_version, - string repository_path) - { - ScriptsRunError script_run_error = new ScriptsRunError - { - version = repository_version ?? string.Empty, - script_name = script_name, - text_of_script = sql_to_run, - erroneous_part_of_script = sql_erroneous_part, - repository_path = repository_path ?? string.Empty, - error_message = error_message, - }; - - try - { - retry_policy.Execute(() => repository.save_or_update(script_run_error)); - } - catch (Exception ex) - { - Log.bound_to(this).log_an_error_event_containing( - "{0} with provider {1} does not provide a facility for recording scripts run errors at this time.{2}{3}", - GetType(), provider, Environment.NewLine, ex.Message); - throw; - } - } - - public virtual string get_version(string repository_path) - { - string version = "0"; - - QueryOver crit = QueryOver.Of() - .Where(x => x.repository_path == (repository_path ?? string.Empty)) - .OrderBy(x => x.entry_date).Desc - .Take(1); - - IList items = null; - try - { - items = retry_policy.Execute(() => repository.get_with_criteria(crit)); - } - catch (Exception ex) - { - Log.bound_to(this).log_a_warning_event_containing("{0} with provider {1} does not provide a facility for retrieving versions at this time.{2}{3}", - GetType(), provider, Environment.NewLine, ex.to_string()); - } - - if (items != null && items.Count > 0) - { - version = items[0].version; - } - - return version; - } - - //get rid of the virtual - public virtual long insert_version_and_get_version_id(string repository_path, string repository_version) - { - long version_id = 0; - - Version version = new Version - { - version = repository_version ?? string.Empty, - repository_path = repository_path ?? string.Empty, - }; - - try - { - retry_policy.Execute(() => repository.save_or_update(version)); - version_id = version.id; - } - catch (Exception ex) - { - Log.bound_to(this).log_an_error_event_containing("{0} with provider {1} does not provide a facility for inserting versions at this time.{2}{3}", - GetType(), provider, Environment.NewLine, ex.Message); - throw; - } - - return version_id; - } - - public virtual string get_current_script_hash(string script_name) - { - var script = get_script_run(script_name); - return script != null ? script.text_hash : string.Empty; - } - - public virtual bool has_run_script_already(string script_name) - { - var script = get_script_run(script_name); - return script != null; - } - - protected IList get_all_scripts() - { - return retry_policy.Execute(() => repository.get_all()); - } - - protected ScriptsRun get_script_run(string script_name) - { - if (scripts_cache == null) - { - scripts_cache = new Dictionary(); - - // latest id overrides possible old one, just like in queries searching for scripts - foreach (var script in get_all_scripts().OrderBy(x => x.id)) - { - scripts_cache[script.script_name] = script; - } - } - - ScriptsRun script_run; - return scripts_cache.TryGetValue(script_name, out script_run) ? script_run : null; - } - - public virtual void Dispose() - { - if (!disposing) - { - Log.bound_to(this).log_a_debug_event_containing("Database is disposing normal connection."); - dispose_connection(server_connection); - Log.bound_to(this).log_a_debug_event_containing("Database is disposing admin connection."); - dispose_connection(admin_connection); - - disposing = true; - } - } - - private void dispose_connection(IConnection connection) - { - if (connection != null) - { - IDbConnection conn = (IDbConnection)connection.underlying_type(); - if (conn != null) - { - if (conn.State != ConnectionState.Closed) - { - conn.Close(); - } - } - - connection.Dispose(); - } - } - } +using Polly; +using Polly.Retry; + +namespace roundhouse.databases +{ + using System; + using System.Collections.Generic; + using System.Data; + using System.Linq; + using connections; + using infrastructure.app; + using infrastructure.app.tokens; + using infrastructure.extensions; + using infrastructure.logging; + using infrastructure.persistence; + using model; + using NHibernate; + using NHibernate.Cfg; + using NHibernate.Criterion; + using NHibernate.Tool.hbm2ddl; + using parameters; + using sqlsplitters; + using Environment = System.Environment; + using Version = model.Version; + + public abstract class DefaultDatabase : Database + { + protected RetryPolicy retry_policy = Policy.Handle().Retry(0); + + public ConfigurationPropertyHolder configuration { get; set; } + public string server_name { get; set; } + public string database_name { get; set; } + public string provider { get; set; } + public string connection_string { get; set; } + public string admin_connection_string { get; set; } + public string roundhouse_schema_name { get; set; } + public string version_table_name { get; set; } + public string scripts_run_table_name { get; set; } + public string scripts_run_errors_table_name { get; set; } + public string user_name { get; set; } + public string master_database_name { get; set; } + public IRepository repository { get; set; } + + public virtual string sql_statement_separator_regex_pattern + { + get { return @"(?^(?:[\s\t])*(?:-{2}).*$)|(?/{1}\*{1}[\S\s]*?\*{1}/{1})|(?'{1}(?:[^']|\n[^'])*?'{1})|(?^|\s)(?\;)(?\s|$)"; } + } + + public int command_timeout { get; set; } + public int admin_command_timeout { get; set; } + public int restore_timeout { get; set; } + protected bool split_batches = true; + + public virtual bool split_batch_statements + { + get { return split_batches; } + set { split_batches = value; } + } + + public virtual bool supports_ddl_transactions + { + get { return true; } + } + + protected IConnection server_connection; + protected IConnection admin_connection; + + private bool disposing; + private Dictionary scripts_cache; + + //this method must set the provider + public abstract void initialize_connections(ConfigurationPropertyHolder configuration_property_holder); + public abstract void set_provider(); + + public void set_repository() + { + NHibernateSessionFactoryBuilder session_factory_builder = new NHibernateSessionFactoryBuilder(configuration); + Configuration cfg = null; + ISessionFactory factory = session_factory_builder.build_session_factory(x => { cfg = x; }); + repository = new Repository(factory, cfg); + } + + public abstract void open_connection(bool with_transaction); + public abstract void close_connection(); + public abstract void open_admin_connection(); + public abstract void close_admin_connection(); + + public abstract void rollback(); + + public abstract string create_database_script(); + public abstract string set_recovery_mode_script(bool simple); + public abstract string restore_database_script(string restore_from_path, string custom_restore_options); + public abstract string delete_database_script(); + + public virtual bool create_database_if_it_doesnt_exist(string custom_create_database_script) + { + bool database_was_created = false; + try + { + string create_script = create_database_script(); + if (!string.IsNullOrEmpty(custom_create_database_script)) + { + create_script = custom_create_database_script; + if (!configuration.DisableTokenReplacement) + { + create_script = TokenReplacer.replace_tokens(configuration, create_script); + } + } + + if (split_batch_statements) + { + foreach (var sql_statement in StatementSplitter.split_sql_on_regex_and_remove_empty_statements(create_script, sql_statement_separator_regex_pattern)) + { + //should only receive a return value once + var return_value = run_sql_scalar_boolean(sql_statement, ConnectionType.Admin); + if (return_value != null) + { + database_was_created = return_value.Value; + } + } + } + else + { + //should only receive a return value once + var return_value = run_sql_scalar_boolean(create_script, ConnectionType.Admin); + database_was_created = return_value.GetValueOrDefault(false); + } + } + catch (Exception ex) + { + Log.bound_to(this).log_a_warning_event_containing( + "{0} with provider {1} does not provide a facility for creating a database at this time.{2}{3}", + GetType(), provider, Environment.NewLine, ex.to_string()); + } + + return database_was_created; + } + + private bool? run_sql_scalar_boolean(string sql_to_run, ConnectionType connection_type) + { + var return_value = run_sql_scalar(sql_to_run, connection_type); + if (return_value != null && return_value != DBNull.Value) + { + return Convert.ToBoolean(return_value); + } + return null; + } + + public void set_recovery_mode(bool simple) + { + try + { + run_sql(set_recovery_mode_script(simple), ConnectionType.Admin); + } + catch (Exception ex) + { + Log.bound_to(this).log_a_warning_event_containing( + "{0} with provider {1} does not provide a facility for setting recovery mode to simple at this time.{2}{3}", + GetType(), provider, Environment.NewLine, ex.Message); + } + } + + public void backup_database(string output_path_minus_database) + { + Log.bound_to(this).log_a_warning_event_containing("{0} with provider {1} does not provide a facility for backing up a database at this time.", + GetType(), provider); + //todo: backup database is not a script - it is a command + //Server sql_server = + // new Server(new ServerConnection(new SqlConnection(build_connection_string(server_name, database_name)))); + //sql_server.BackupDevices.Add(new BackupDevice(sql_server,database_name)); + } + + public void restore_database(string restore_from_path, string custom_restore_options) + { + try + { + int current_connection_timeout = command_timeout; + admin_command_timeout = restore_timeout; + run_sql(restore_database_script(restore_from_path, custom_restore_options), ConnectionType.Admin); + admin_command_timeout = current_connection_timeout; + } + catch (Exception ex) + { + Log.bound_to(this).log_a_warning_event_containing( + "{0} with provider {1} does not provide a facility for restoring a database at this time.{2}{3}", + GetType(), provider, Environment.NewLine, ex.Message); + } + } + + public virtual void delete_database_if_it_exists() + { + try + { + run_sql(delete_database_script(), ConnectionType.Admin); + } + catch (Exception ex) + { + Log.bound_to(this).log_an_error_event_containing( + "{0} with provider {1} does not provide a facility for deleting a database at this time.{2}{3}", + GetType(), provider, Environment.NewLine, ex.Message); + throw; + } + } + + public abstract void run_database_specific_tasks(); + + public virtual void create_or_update_roundhouse_tables() + { + SchemaUpdate s = new SchemaUpdate(repository.nhibernate_configuration); + s.Execute(false, true); + } + + public virtual void run_sql(string sql_to_run, ConnectionType connection_type) + { + Log.bound_to(this).log_a_debug_event_containing("[SQL] Running (on connection '{0}'): {1}{2}", connection_type.ToString(), Environment.NewLine, sql_to_run); + run_sql(sql_to_run, connection_type, null); + } + + public virtual object run_sql_scalar(string sql_to_run, ConnectionType connection_type) + { + Log.bound_to(this).log_a_debug_event_containing("[SQL] Running (on connection '{0}'): {1}{2}", connection_type.ToString(), Environment.NewLine, sql_to_run); + return run_sql_scalar(sql_to_run, connection_type, null); + } + + protected abstract void run_sql(string sql_to_run, ConnectionType connection_type, IList> parameters); + + protected abstract object run_sql_scalar(string sql_to_run, ConnectionType connection_type, IList> parameters); + + public virtual void insert_script_run(string script_name, string sql_to_run, string sql_to_run_hash, bool run_this_script_once, long version_id) + { + ScriptsRun script_run = new ScriptsRun + { + version_id = version_id, + script_name = script_name, + text_of_script = sql_to_run, + text_hash = sql_to_run_hash, + one_time_script = run_this_script_once + }; + + try + { + retry_policy.Execute(() => repository.save_or_update(script_run)); + scripts_cache[script_name] = script_run; + } + catch (Exception ex) + { + Log.bound_to(this).log_an_error_event_containing( + "{0} with provider {1} does not provide a facility for recording scripts run at this time.{2}{3}", + GetType(), provider, Environment.NewLine, ex.Message); + throw; + } + } + + public virtual void insert_script_run_error(string script_name, string sql_to_run, string sql_erroneous_part, string error_message, string repository_version, + string repository_path) + { + ScriptsRunError script_run_error = new ScriptsRunError + { + version = repository_version ?? string.Empty, + script_name = script_name, + text_of_script = sql_to_run, + erroneous_part_of_script = sql_erroneous_part, + repository_path = repository_path ?? string.Empty, + error_message = error_message, + }; + + try + { + retry_policy.Execute(() => repository.save_or_update(script_run_error)); + } + catch (Exception ex) + { + Log.bound_to(this).log_an_error_event_containing( + "{0} with provider {1} does not provide a facility for recording scripts run errors at this time.{2}{3}", + GetType(), provider, Environment.NewLine, ex.Message); + throw; + } + } + + public virtual string get_version(string repository_path) + { + string version = "0"; + + QueryOver crit = QueryOver.Of() + .Where(x => x.repository_path == (repository_path ?? string.Empty)) + .OrderBy(x => x.entry_date).Desc + .Take(1); + + IList items = null; + try + { + items = retry_policy.Execute(() => repository.get_with_criteria(crit)); + } + catch (Exception ex) + { + Log.bound_to(this).log_a_warning_event_containing("{0} with provider {1} does not provide a facility for retrieving versions at this time.{2}{3}", + GetType(), provider, Environment.NewLine, ex.to_string()); + } + + if (items != null && items.Count > 0) + { + version = items[0].version; + } + + return version; + } + + //get rid of the virtual + public virtual long insert_version_and_get_version_id(string repository_path, string repository_version) + { + long version_id = 0; + + Version version = new Version + { + version = repository_version ?? string.Empty, + repository_path = repository_path ?? string.Empty, + }; + + try + { + retry_policy.Execute(() => repository.save_or_update(version)); + version_id = version.id; + } + catch (Exception ex) + { + Log.bound_to(this).log_an_error_event_containing("{0} with provider {1} does not provide a facility for inserting versions at this time.{2}{3}", + GetType(), provider, Environment.NewLine, ex.Message); + throw; + } + + return version_id; + } + + public virtual string get_current_script_hash(string script_name) + { + var script = get_script_run(script_name); + return script != null ? script.text_hash : string.Empty; + } + + public virtual bool has_run_script_already(string script_name) + { + var script = get_script_run(script_name); + return script != null; + } + + protected IList get_all_scripts() + { + return retry_policy.Execute(() => repository.get_all()); + } + + protected ScriptsRun get_script_run(string script_name) + { + if (scripts_cache == null) + { + scripts_cache = new Dictionary(); + + // latest id overrides possible old one, just like in queries searching for scripts + foreach (var script in get_all_scripts().OrderBy(x => x.id)) + { + scripts_cache[script.script_name] = script; + } + } + + ScriptsRun script_run; + return scripts_cache.TryGetValue(script_name, out script_run) ? script_run : null; + } + + public virtual void Dispose() + { + if (!disposing) + { + Log.bound_to(this).log_a_debug_event_containing("Database is disposing normal connection."); + dispose_connection(server_connection); + Log.bound_to(this).log_a_debug_event_containing("Database is disposing admin connection."); + dispose_connection(admin_connection); + + disposing = true; + } + } + + private static void dispose_connection(IConnection connection) + { + if (connection != null) + { + IDbConnection conn = (IDbConnection)connection.underlying_type(); + if (conn != null) + { + if (conn.State != ConnectionState.Closed) + { + conn.Close(); + } + } + connection.Dispose(); + } + } + } } \ No newline at end of file diff --git a/product/roundhouse/databases/MockDatabase.cs b/product/roundhouse.core/databases/MockDatabase.cs similarity index 95% rename from product/roundhouse/databases/MockDatabase.cs rename to product/roundhouse.core/databases/MockDatabase.cs index 7222d293..562a7e00 100644 --- a/product/roundhouse/databases/MockDatabase.cs +++ b/product/roundhouse.core/databases/MockDatabase.cs @@ -1,274 +1,276 @@ -namespace roundhouse.databases -{ - using System; - using infrastructure.app; - using infrastructure.logging; - using infrastructure.persistence; - - public class MockDatabase : Database - { - - private bool database_exists = false; - private readonly Database database; - - public MockDatabase(Database database) - { - this.database = database; - } - - public ConfigurationPropertyHolder configuration - { - get { return database.configuration; } - set { database.configuration = value; } - } - - public string connection_string - { - get { return database.connection_string; } - set { database.connection_string = value; } - } - - public string admin_connection_string - { - get { return database.admin_connection_string; } - set { database.admin_connection_string = value; } - } - - public string server_name - { - get { return database.server_name; } - set { database.server_name = value; } - } - - public string database_name - { - get { return database.database_name; } - set { database.database_name = value; } - } - - public string provider - { - get { return database.provider; } - set { database.provider = value; } - } - - public string roundhouse_schema_name - { - get { return database.roundhouse_schema_name; } - set { database.roundhouse_schema_name = value; } - } - - public string version_table_name - { - get { return database.version_table_name; } - set { database.version_table_name = value; } - } - - public string scripts_run_table_name - { - get { return database.scripts_run_table_name; } - set { database.scripts_run_table_name = value; } - } - - public string scripts_run_errors_table_name - { - get { return database.scripts_run_errors_table_name; } - set { database.scripts_run_errors_table_name = value; } - } - - public string user_name - { - get { return database.user_name; } - set { database.user_name = value; } - } - - public string sql_statement_separator_regex_pattern - { - get { return database.sql_statement_separator_regex_pattern; } - } - - public int command_timeout - { - get { return database.command_timeout; } - set { database.command_timeout = value; } - } - - public int admin_command_timeout - { - get { return database.admin_command_timeout; } - set { database.admin_command_timeout = value; } - } - - public int restore_timeout - { - get { return database.restore_timeout; } - set { database.restore_timeout = value; } - } - - public bool split_batch_statements - { - get { return database.split_batch_statements; } - set { database.split_batch_statements = value; } - } - - public bool supports_ddl_transactions - { - get { return database.supports_ddl_transactions; } - } - - //public IRepository repository - //{ - // get { return database.repository; } - // set { database.repository = value; } - //} - - public void initialize_connections(ConfigurationPropertyHolder configuration_property_holder) - { - database.initialize_connections(configuration_property_holder); - } - - public void open_connection(bool with_transaction) - { - if (database_exists) - { - database.open_connection(with_transaction); - } - } - - public void close_connection() - { - if (database_exists) - { - database.close_connection(); - } - } - - public void open_admin_connection() - { - database.open_connection(false); - } - - public void close_admin_connection() - { - database.close_connection(); - } - - public void rollback() - { - database.rollback(); - } - - public bool create_database_if_it_doesnt_exist(string custom_create_database_script) - { - //TODO: Don't allow creation of the database - record everything from here on out as something that would run - //database_exists = database.database_exists - return true; - //return database. - } - - public void set_recovery_mode(bool simple) - { - Log.bound_to(this).log_an_info_event_containing("Changing the database recovery mode if it has one to {0}", simple ? "simple" : "full"); - } - - public void backup_database(string output_path_minus_database) - { - Log.bound_to(this).log_an_info_event_containing("Backing up the database to \"{0}\".", output_path_minus_database); - } - - public void restore_database(string restore_from_path, string custom_restore_options) - { - string message = "Mocking mode does NOT support what would happen under a restore circumstance, because it would have to actually restore the database to do so."; - Log.bound_to(this).log_a_warning_event_containing(message); - throw new ApplicationException(message); - } - - public void delete_database_if_it_exists() - { - //TODO: Determine whether the database exists - //database.delete_database_if_it_exists(); - } - - public void run_database_specific_tasks() - { - if (!database_exists) - { - //TODO: figure out whether we do this or not - //database.run_database_specific_tasks(); - } - } - - public void create_or_update_roundhouse_tables() - { - database.create_or_update_roundhouse_tables(); - } - - public void run_sql(string sql_to_run,ConnectionType connection_type) - { - Log.bound_to(this).log_an_info_event_containing("Running statemtent: {0}{1}", Environment.NewLine, sql_to_run); - //database.run_sql(sql_to_run); - } - - public object run_sql_scalar(string sql_to_run,ConnectionType connection_type) - { - Log.bound_to(this).log_an_info_event_containing("Running statemtent: {0}{1}", Environment.NewLine, sql_to_run); - //database.run_sql(sql_to_run); - return new object(); - } - - public void insert_script_run(string script_name, string sql_to_run, string sql_to_run_hash, bool run_this_script_once, long version_id) - { - // database.insert_script_run(script_name, sql_to_run, sql_to_run_hash, run_this_script_once, version_id); - } - - public void insert_script_run_error(string script_name, string sql_to_run, string sql_erroneous_part, string error_message, string repository_version, string repository_path) - { - // database.insert_script_run_error(script_name, sql_to_run, sql_erroneous_part, error_message, repository_version, repository_path); - } - - public string get_version(string repository_path) - { - if (database_exists) - { - return database.get_version(repository_path); - } - - return string.Empty; - } - - public long insert_version_and_get_version_id(string repository_path, string repository_version) - { - return 0; - } - - public bool has_run_script_already(string script_name) - { - if (database_exists) - { - return database.has_run_script_already(script_name); - } - - return false; - } - - public string get_current_script_hash(string script_name) - { - if (database_exists) - { - return database.get_current_script_hash(script_name); - } - - return string.Empty; - } - - private bool disposing = false; - public void Dispose() - { - if (!disposing) - { - database.Dispose(); - disposing = true; - } - } - } +using roundhouse.infrastructure; + +namespace roundhouse.databases +{ + using System; + using infrastructure.app; + using infrastructure.logging; + using infrastructure.persistence; + + public class MockDatabase : Database + { + + private bool database_exists = false; + private readonly Database database; + + public MockDatabase(Database database) + { + this.database = database; + } + + public ConfigurationPropertyHolder configuration + { + get { return database.configuration; } + set { database.configuration = value; } + } + + public string connection_string + { + get { return database.connection_string; } + set { database.connection_string = value; } + } + + public string admin_connection_string + { + get { return database.admin_connection_string; } + set { database.admin_connection_string = value; } + } + + public string server_name + { + get { return database.server_name; } + set { database.server_name = value; } + } + + public string database_name + { + get { return database.database_name; } + set { database.database_name = value; } + } + + public string provider + { + get { return database.provider; } + set { database.provider = value; } + } + + public string roundhouse_schema_name + { + get { return database.roundhouse_schema_name; } + set { database.roundhouse_schema_name = value; } + } + + public string version_table_name + { + get { return database.version_table_name; } + set { database.version_table_name = value; } + } + + public string scripts_run_table_name + { + get { return database.scripts_run_table_name; } + set { database.scripts_run_table_name = value; } + } + + public string scripts_run_errors_table_name + { + get { return database.scripts_run_errors_table_name; } + set { database.scripts_run_errors_table_name = value; } + } + + public string user_name + { + get { return database.user_name; } + set { database.user_name = value; } + } + + public string sql_statement_separator_regex_pattern + { + get { return database.sql_statement_separator_regex_pattern; } + } + + public int command_timeout + { + get { return database.command_timeout; } + set { database.command_timeout = value; } + } + + public int admin_command_timeout + { + get { return database.admin_command_timeout; } + set { database.admin_command_timeout = value; } + } + + public int restore_timeout + { + get { return database.restore_timeout; } + set { database.restore_timeout = value; } + } + + public bool split_batch_statements + { + get { return database.split_batch_statements; } + set { database.split_batch_statements = value; } + } + + public bool supports_ddl_transactions + { + get { return database.supports_ddl_transactions; } + } + + //public IRepository repository + //{ + // get { return database.repository; } + // set { database.repository = value; } + //} + + public void initialize_connections(ConfigurationPropertyHolder configuration_property_holder) + { + database.initialize_connections(configuration_property_holder); + } + + public void open_connection(bool with_transaction) + { + if (database_exists) + { + database.open_connection(with_transaction); + } + } + + public void close_connection() + { + if (database_exists) + { + database.close_connection(); + } + } + + public void open_admin_connection() + { + database.open_connection(false); + } + + public void close_admin_connection() + { + database.close_connection(); + } + + public void rollback() + { + database.rollback(); + } + + public bool create_database_if_it_doesnt_exist(string custom_create_database_script) + { + //TODO: Don't allow creation of the database - record everything from here on out as something that would run + //database_exists = database.database_exists + return true; + //return database. + } + + public void set_recovery_mode(bool simple) + { + Log.bound_to(this).log_an_info_event_containing("Changing the database recovery mode if it has one to {0}", simple ? "simple" : "full"); + } + + public void backup_database(string output_path_minus_database) + { + Log.bound_to(this).log_an_info_event_containing("Backing up the database to \"{0}\".", output_path_minus_database); + } + + public void restore_database(string restore_from_path, string custom_restore_options) + { + string message = "Mocking mode does NOT support what would happen under a restore circumstance, because it would have to actually restore the database to do so."; + Log.bound_to(this).log_a_warning_event_containing(message); + throw new ConfigurationException(message); + } + + public void delete_database_if_it_exists() + { + //TODO: Determine whether the database exists + //database.delete_database_if_it_exists(); + } + + public void run_database_specific_tasks() + { + if (!database_exists) + { + //TODO: figure out whether we do this or not + //database.run_database_specific_tasks(); + } + } + + public void create_or_update_roundhouse_tables() + { + database.create_or_update_roundhouse_tables(); + } + + public void run_sql(string sql_to_run,ConnectionType connection_type) + { + Log.bound_to(this).log_an_info_event_containing("Running statemtent: {0}{1}", Environment.NewLine, sql_to_run); + //database.run_sql(sql_to_run); + } + + public object run_sql_scalar(string sql_to_run,ConnectionType connection_type) + { + Log.bound_to(this).log_an_info_event_containing("Running statemtent: {0}{1}", Environment.NewLine, sql_to_run); + //database.run_sql(sql_to_run); + return new object(); + } + + public void insert_script_run(string script_name, string sql_to_run, string sql_to_run_hash, bool run_this_script_once, long version_id) + { + // database.insert_script_run(script_name, sql_to_run, sql_to_run_hash, run_this_script_once, version_id); + } + + public void insert_script_run_error(string script_name, string sql_to_run, string sql_erroneous_part, string error_message, string repository_version, string repository_path) + { + // database.insert_script_run_error(script_name, sql_to_run, sql_erroneous_part, error_message, repository_version, repository_path); + } + + public string get_version(string repository_path) + { + if (database_exists) + { + return database.get_version(repository_path); + } + + return string.Empty; + } + + public long insert_version_and_get_version_id(string repository_path, string repository_version) + { + return 0; + } + + public bool has_run_script_already(string script_name) + { + if (database_exists) + { + return database.has_run_script_already(script_name); + } + + return false; + } + + public string get_current_script_hash(string script_name) + { + if (database_exists) + { + return database.get_current_script_hash(script_name); + } + + return string.Empty; + } + + private bool disposing = false; + void IDisposable.Dispose() + { + if (!disposing) + { + database.Dispose(); + disposing = true; + } + } + } } \ No newline at end of file diff --git a/product/roundhouse/databases/RecoveryMode.cs b/product/roundhouse.core/databases/RecoveryMode.cs similarity index 93% rename from product/roundhouse/databases/RecoveryMode.cs rename to product/roundhouse.core/databases/RecoveryMode.cs index f76743f4..a9b9cdc5 100644 --- a/product/roundhouse/databases/RecoveryMode.cs +++ b/product/roundhouse.core/databases/RecoveryMode.cs @@ -1,9 +1,9 @@ -namespace roundhouse.databases -{ - public enum RecoveryMode - { - NoChange, - Simple, - Full - } +namespace roundhouse.databases +{ + public enum RecoveryMode + { + NoChange, + Simple, + Full + } } \ No newline at end of file diff --git a/product/roundhouse/databases/SqlServerLiteSpeedDatabase.cs b/product/roundhouse.core/databases/SqlServerLiteSpeedDatabase.cs similarity index 96% rename from product/roundhouse/databases/SqlServerLiteSpeedDatabase.cs rename to product/roundhouse.core/databases/SqlServerLiteSpeedDatabase.cs index e1a925ae..b5d8ba81 100644 --- a/product/roundhouse/databases/SqlServerLiteSpeedDatabase.cs +++ b/product/roundhouse.core/databases/SqlServerLiteSpeedDatabase.cs @@ -1,259 +1,259 @@ -namespace roundhouse.databases -{ - using System; - using infrastructure.app; - using infrastructure.persistence; - - public sealed class SqlServerLiteSpeedDatabase : Database - { - private readonly Database database; - - public SqlServerLiteSpeedDatabase(Database database) - { - this.database = database; - } - - public ConfigurationPropertyHolder configuration - { - get { return database.configuration; } - set { database.configuration = value; } - } - - public string connection_string - { - get { return database.connection_string; } - set { database.connection_string = value; } - } - - public string admin_connection_string - { - get { return database.admin_connection_string; } - set { database.admin_connection_string = value; } - } - - public string server_name - { - get { return database.server_name; } - set { database.server_name = value; } - } - - public string database_name - { - get { return database.database_name; } - set { database.database_name = value; } - } - - public string provider - { - get { return database.provider; } - set { database.provider = value; } - } - - public string roundhouse_schema_name - { - get { return database.roundhouse_schema_name; } - set { database.roundhouse_schema_name = value; } - } - - public string version_table_name - { - get { return database.version_table_name; } - set { database.version_table_name = value; } - } - - public string scripts_run_table_name - { - get { return database.scripts_run_table_name; } - set { database.scripts_run_table_name = value; } - } - - public string scripts_run_errors_table_name - { - get { return database.scripts_run_errors_table_name; } - set { database.scripts_run_errors_table_name = value; } - } - - public string user_name - { - get { return database.user_name; } - set { database.user_name = value; } - } - - public string sql_statement_separator_regex_pattern - { - get { return database.sql_statement_separator_regex_pattern; } - } - - public int command_timeout - { - get { return database.command_timeout; } - set { database.command_timeout = value; } - } - - public int admin_command_timeout - { - get { return database.admin_command_timeout; } - set { database.admin_command_timeout = value; } - } - - public int restore_timeout - { - get { return database.restore_timeout; } - set { database.restore_timeout = value; } - } - - public bool split_batch_statements - { - get { return database.split_batch_statements; } - set { database.split_batch_statements = value; } - } - - public bool supports_ddl_transactions - { - get { return database.supports_ddl_transactions; } - } - - //public IRepository repository - //{ - // get { return database.repository; } - // set { database.repository = value; } - //} - - public void initialize_connections(ConfigurationPropertyHolder configuration_property_holder) - { - database.initialize_connections(configuration_property_holder); - } - - public void open_admin_connection() - { - database.open_admin_connection(); - } - - public void close_admin_connection() - { - database.close_admin_connection(); - } - public void open_connection(bool with_transaction) - { - database.open_connection(with_transaction); - } - - public void close_connection() - { - database.close_connection(); - } - - public void rollback() - { - database.rollback(); - } - - public bool create_database_if_it_doesnt_exist(string custom_create_database_script) - { - return database.create_database_if_it_doesnt_exist(custom_create_database_script); - } - - public void set_recovery_mode(bool simple) - { - database.set_recovery_mode(simple); - } - - public void backup_database(string output_path_minus_database) - { - database.backup_database(output_path_minus_database); - } - - public void restore_database(string restore_from_path, string custom_restore_options) - { - int current_timeout = command_timeout; - command_timeout = restore_timeout; - run_sql(string.Format( - @"USE master - ALTER DATABASE [{0}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE; - ALTER DATABASE [{0}] SET MULTI_USER; - - exec master.dbo.xp_restore_database @database = N'{0}', - @filename = N'{1}', - @filenumber = 1, - @with = N'RECOVERY', - @with = N'NOUNLOAD', - @with = N'REPLACE', - @with = N'STATS = 10' - {2}; - - ALTER DATABASE [{0}] SET MULTI_USER; - ALTER DATABASE [{0}] SET RECOVERY SIMPLE; - --DBCC SHRINKDATABASE ([{0}]); - ", - database_name, restore_from_path, - string.IsNullOrEmpty(custom_restore_options) ? string.Empty : ", @with = N'" + custom_restore_options.Replace("'", "''") + "'" - ),ConnectionType.Admin); - command_timeout = current_timeout; - } - - public void delete_database_if_it_exists() - { - database.delete_database_if_it_exists(); - } - - public void run_database_specific_tasks() - { - database.run_database_specific_tasks(); - } - - public void create_or_update_roundhouse_tables() - { - database.create_or_update_roundhouse_tables(); - } - - public void run_sql(string sql_to_run,ConnectionType connection_type) - { - database.run_sql(sql_to_run,connection_type); - } - - public object run_sql_scalar(string sql_to_run,ConnectionType connection_type) - { - return database.run_sql_scalar(sql_to_run,connection_type); - } - - public void insert_script_run(string script_name, string sql_to_run, string sql_to_run_hash, bool run_this_script_once, long version_id) - { - database.insert_script_run(script_name, sql_to_run, sql_to_run_hash, run_this_script_once, version_id); - } - - public void insert_script_run_error(string script_name, string sql_to_run, string sql_erroneous_part, string error_message, string repository_version, string repository_path) - { - database.insert_script_run_error(script_name, sql_to_run, sql_erroneous_part, error_message, repository_version, repository_path); - } - - public string get_version(string repository_path) - { - return database.get_version(repository_path); - } - - public long insert_version_and_get_version_id(string repository_path, string repository_version) - { - return database.insert_version_and_get_version_id(repository_path, repository_version); - } - - public bool has_run_script_already(string script_name) - { - return database.has_run_script_already(script_name); - } - - public string get_current_script_hash(string script_name) - { - return database.get_current_script_hash(script_name); - } - - private bool disposing = false; - public void Dispose() - { - if (!disposing) - { - database.Dispose(); - disposing = true; - } - } - } +namespace roundhouse.databases +{ + using System; + using infrastructure.app; + using infrastructure.persistence; + + public sealed class SqlServerLiteSpeedDatabase : Database + { + private readonly Database database; + + public SqlServerLiteSpeedDatabase(Database database) + { + this.database = database; + } + + public ConfigurationPropertyHolder configuration + { + get { return database.configuration; } + set { database.configuration = value; } + } + + public string connection_string + { + get { return database.connection_string; } + set { database.connection_string = value; } + } + + public string admin_connection_string + { + get { return database.admin_connection_string; } + set { database.admin_connection_string = value; } + } + + public string server_name + { + get { return database.server_name; } + set { database.server_name = value; } + } + + public string database_name + { + get { return database.database_name; } + set { database.database_name = value; } + } + + public string provider + { + get { return database.provider; } + set { database.provider = value; } + } + + public string roundhouse_schema_name + { + get { return database.roundhouse_schema_name; } + set { database.roundhouse_schema_name = value; } + } + + public string version_table_name + { + get { return database.version_table_name; } + set { database.version_table_name = value; } + } + + public string scripts_run_table_name + { + get { return database.scripts_run_table_name; } + set { database.scripts_run_table_name = value; } + } + + public string scripts_run_errors_table_name + { + get { return database.scripts_run_errors_table_name; } + set { database.scripts_run_errors_table_name = value; } + } + + public string user_name + { + get { return database.user_name; } + set { database.user_name = value; } + } + + public string sql_statement_separator_regex_pattern + { + get { return database.sql_statement_separator_regex_pattern; } + } + + public int command_timeout + { + get { return database.command_timeout; } + set { database.command_timeout = value; } + } + + public int admin_command_timeout + { + get { return database.admin_command_timeout; } + set { database.admin_command_timeout = value; } + } + + public int restore_timeout + { + get { return database.restore_timeout; } + set { database.restore_timeout = value; } + } + + public bool split_batch_statements + { + get { return database.split_batch_statements; } + set { database.split_batch_statements = value; } + } + + public bool supports_ddl_transactions + { + get { return database.supports_ddl_transactions; } + } + + //public IRepository repository + //{ + // get { return database.repository; } + // set { database.repository = value; } + //} + + public void initialize_connections(ConfigurationPropertyHolder configuration_property_holder) + { + database.initialize_connections(configuration_property_holder); + } + + public void open_admin_connection() + { + database.open_admin_connection(); + } + + public void close_admin_connection() + { + database.close_admin_connection(); + } + public void open_connection(bool with_transaction) + { + database.open_connection(with_transaction); + } + + public void close_connection() + { + database.close_connection(); + } + + public void rollback() + { + database.rollback(); + } + + public bool create_database_if_it_doesnt_exist(string custom_create_database_script) + { + return database.create_database_if_it_doesnt_exist(custom_create_database_script); + } + + public void set_recovery_mode(bool simple) + { + database.set_recovery_mode(simple); + } + + public void backup_database(string output_path_minus_database) + { + database.backup_database(output_path_minus_database); + } + + public void restore_database(string restore_from_path, string custom_restore_options) + { + int current_timeout = command_timeout; + command_timeout = restore_timeout; + run_sql(string.Format( + @"USE master + ALTER DATABASE [{0}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE; + ALTER DATABASE [{0}] SET MULTI_USER; + + exec master.dbo.xp_restore_database @database = N'{0}', + @filename = N'{1}', + @filenumber = 1, + @with = N'RECOVERY', + @with = N'NOUNLOAD', + @with = N'REPLACE', + @with = N'STATS = 10' + {2}; + + ALTER DATABASE [{0}] SET MULTI_USER; + ALTER DATABASE [{0}] SET RECOVERY SIMPLE; + --DBCC SHRINKDATABASE ([{0}]); + ", + database_name, restore_from_path, + string.IsNullOrEmpty(custom_restore_options) ? string.Empty : ", @with = N'" + custom_restore_options.Replace("'", "''") + "'" + ),ConnectionType.Admin); + command_timeout = current_timeout; + } + + public void delete_database_if_it_exists() + { + database.delete_database_if_it_exists(); + } + + public void run_database_specific_tasks() + { + database.run_database_specific_tasks(); + } + + public void create_or_update_roundhouse_tables() + { + database.create_or_update_roundhouse_tables(); + } + + public void run_sql(string sql_to_run,ConnectionType connection_type) + { + database.run_sql(sql_to_run,connection_type); + } + + public object run_sql_scalar(string sql_to_run,ConnectionType connection_type) + { + return database.run_sql_scalar(sql_to_run,connection_type); + } + + public void insert_script_run(string script_name, string sql_to_run, string sql_to_run_hash, bool run_this_script_once, long version_id) + { + database.insert_script_run(script_name, sql_to_run, sql_to_run_hash, run_this_script_once, version_id); + } + + public void insert_script_run_error(string script_name, string sql_to_run, string sql_erroneous_part, string error_message, string repository_version, string repository_path) + { + database.insert_script_run_error(script_name, sql_to_run, sql_erroneous_part, error_message, repository_version, repository_path); + } + + public string get_version(string repository_path) + { + return database.get_version(repository_path); + } + + public long insert_version_and_get_version_id(string repository_path, string repository_version) + { + return database.insert_version_and_get_version_id(repository_path, repository_version); + } + + public bool has_run_script_already(string script_name) + { + return database.has_run_script_already(script_name); + } + + public string get_current_script_hash(string script_name) + { + return database.get_current_script_hash(script_name); + } + + private bool disposing = false; + public void Dispose() + { + if (!disposing) + { + database.Dispose(); + disposing = true; + } + } + } } \ No newline at end of file diff --git a/product/roundhouse/environments/DefaultEnvironment.cs b/product/roundhouse.core/environments/DefaultEnvironment.cs similarity index 100% rename from product/roundhouse/environments/DefaultEnvironment.cs rename to product/roundhouse.core/environments/DefaultEnvironment.cs diff --git a/product/roundhouse/environments/DefaultEnvironmentSet.cs b/product/roundhouse.core/environments/DefaultEnvironmentSet.cs similarity index 100% rename from product/roundhouse/environments/DefaultEnvironmentSet.cs rename to product/roundhouse.core/environments/DefaultEnvironmentSet.cs diff --git a/product/roundhouse/environments/Environment.cs b/product/roundhouse.core/environments/Environment.cs similarity index 96% rename from product/roundhouse/environments/Environment.cs rename to product/roundhouse.core/environments/Environment.cs index 9e30b497..e7602d3e 100644 --- a/product/roundhouse/environments/Environment.cs +++ b/product/roundhouse.core/environments/Environment.cs @@ -1,8 +1,8 @@ -namespace roundhouse.environments -{ - public interface Environment - { - string name {get;} - bool item_is_for_this_environment(string item_name); - } +namespace roundhouse.environments +{ + public interface Environment + { + string name {get;} + bool item_is_for_this_environment(string item_name); + } } \ No newline at end of file diff --git a/product/roundhouse/environments/EnvironmentSet.cs b/product/roundhouse.core/environments/EnvironmentSet.cs similarity index 100% rename from product/roundhouse/environments/EnvironmentSet.cs rename to product/roundhouse.core/environments/EnvironmentSet.cs diff --git a/product/roundhouse/folders/DefaultFolder.cs b/product/roundhouse.core/folders/DefaultFolder.cs similarity index 96% rename from product/roundhouse/folders/DefaultFolder.cs rename to product/roundhouse.core/folders/DefaultFolder.cs index 010f8a6b..2a91be9a 100644 --- a/product/roundhouse/folders/DefaultFolder.cs +++ b/product/roundhouse.core/folders/DefaultFolder.cs @@ -1,24 +1,24 @@ -using roundhouse.infrastructure.filesystem; - -namespace roundhouse.folders -{ - public class DefaultFolder : Folder - { - private readonly FileSystemAccess file_system; - - public DefaultFolder(FileSystemAccess file_system, string folder_path, string folder_name) - { - this.file_system = file_system; - this.folder_path = folder_path; - this.folder_name = folder_name; - } - - public string folder_name { get; set; } - public string folder_path { get; private set; } - - public string folder_full_path - { - get { return file_system.combine_paths(folder_path, folder_name); } - } - } +using roundhouse.infrastructure.filesystem; + +namespace roundhouse.folders +{ + public class DefaultFolder : Folder + { + private readonly FileSystemAccess file_system; + + public DefaultFolder(FileSystemAccess file_system, string folder_path, string folder_name) + { + this.file_system = file_system; + this.folder_path = folder_path; + this.folder_name = folder_name; + } + + public string folder_name { get; set; } + public string folder_path { get; private set; } + + public string folder_full_path + { + get { return file_system.combine_paths(folder_path, folder_name); } + } + } } \ No newline at end of file diff --git a/product/roundhouse/folders/DefaultKnownFolders.cs b/product/roundhouse.core/folders/DefaultKnownFolders.cs similarity index 98% rename from product/roundhouse/folders/DefaultKnownFolders.cs rename to product/roundhouse.core/folders/DefaultKnownFolders.cs index a748301b..6ef87e73 100644 --- a/product/roundhouse/folders/DefaultKnownFolders.cs +++ b/product/roundhouse.core/folders/DefaultKnownFolders.cs @@ -1,61 +1,61 @@ -namespace roundhouse.folders -{ - public sealed class DefaultKnownFolders : KnownFolders - { - public DefaultKnownFolders( - MigrationsFolder alter_database, - MigrationsFolder run_after_create_database, - MigrationsFolder run_before_up, - MigrationsFolder up, - MigrationsFolder down, - MigrationsFolder run_first_after_up, - MigrationsFolder functions, - MigrationsFolder views, - MigrationsFolder sprocs, - MigrationsFolder triggers, - MigrationsFolder indexes, - MigrationsFolder runAfterOtherAnyTimeScripts, - MigrationsFolder permissions, - MigrationsFolder before_migration, - MigrationsFolder after_migration, - Folder change_drop - ) - { - this.alter_database = alter_database; - this.run_after_create_database = run_after_create_database; - this.run_before_up = run_before_up; - this.up = up; - this.down = down; - this.run_first_after_up = run_first_after_up; - this.functions = functions; - this.views = views; - this.sprocs = sprocs; - this.triggers = triggers; - this.indexes = indexes; - this.run_after_other_any_time_scripts = runAfterOtherAnyTimeScripts; - this.permissions = permissions; - this.change_drop = change_drop; - this.before_migration = before_migration; - this.after_migration = after_migration; - } - - public MigrationsFolder alter_database { get; private set; } - public MigrationsFolder run_after_create_database { get; private set; } - public MigrationsFolder run_before_up { get; private set; } - public MigrationsFolder up { get; private set; } - public MigrationsFolder down { get; private set; } - public MigrationsFolder run_first_after_up { get; private set; } - public MigrationsFolder functions { get; private set; } - public MigrationsFolder views { get; private set; } - public MigrationsFolder sprocs { get; private set; } - public MigrationsFolder triggers { get; private set; } - public MigrationsFolder indexes { get; private set; } - public MigrationsFolder run_after_other_any_time_scripts { get; private set; } - public MigrationsFolder permissions { get; private set; } - public MigrationsFolder before_migration { get; private set; } - public MigrationsFolder after_migration { get; private set; } - - public Folder change_drop{get; private set;} - - } +namespace roundhouse.folders +{ + public sealed class DefaultKnownFolders : KnownFolders + { + public DefaultKnownFolders( + MigrationsFolder alter_database, + MigrationsFolder run_after_create_database, + MigrationsFolder run_before_up, + MigrationsFolder up, + MigrationsFolder down, + MigrationsFolder run_first_after_up, + MigrationsFolder functions, + MigrationsFolder views, + MigrationsFolder sprocs, + MigrationsFolder triggers, + MigrationsFolder indexes, + MigrationsFolder runAfterOtherAnyTimeScripts, + MigrationsFolder permissions, + MigrationsFolder before_migration, + MigrationsFolder after_migration, + Folder change_drop + ) + { + this.alter_database = alter_database; + this.run_after_create_database = run_after_create_database; + this.run_before_up = run_before_up; + this.up = up; + this.down = down; + this.run_first_after_up = run_first_after_up; + this.functions = functions; + this.views = views; + this.sprocs = sprocs; + this.triggers = triggers; + this.indexes = indexes; + this.run_after_other_any_time_scripts = runAfterOtherAnyTimeScripts; + this.permissions = permissions; + this.change_drop = change_drop; + this.before_migration = before_migration; + this.after_migration = after_migration; + } + + public MigrationsFolder alter_database { get; private set; } + public MigrationsFolder run_after_create_database { get; private set; } + public MigrationsFolder run_before_up { get; private set; } + public MigrationsFolder up { get; private set; } + public MigrationsFolder down { get; private set; } + public MigrationsFolder run_first_after_up { get; private set; } + public MigrationsFolder functions { get; private set; } + public MigrationsFolder views { get; private set; } + public MigrationsFolder sprocs { get; private set; } + public MigrationsFolder triggers { get; private set; } + public MigrationsFolder indexes { get; private set; } + public MigrationsFolder run_after_other_any_time_scripts { get; private set; } + public MigrationsFolder permissions { get; private set; } + public MigrationsFolder before_migration { get; private set; } + public MigrationsFolder after_migration { get; private set; } + + public Folder change_drop{get; private set;} + + } } \ No newline at end of file diff --git a/product/roundhouse/folders/DefaultMigrationsFolder.cs b/product/roundhouse.core/folders/DefaultMigrationsFolder.cs similarity index 97% rename from product/roundhouse/folders/DefaultMigrationsFolder.cs rename to product/roundhouse.core/folders/DefaultMigrationsFolder.cs index c4196ff8..17c5f6bf 100644 --- a/product/roundhouse/folders/DefaultMigrationsFolder.cs +++ b/product/roundhouse.core/folders/DefaultMigrationsFolder.cs @@ -1,19 +1,19 @@ -namespace roundhouse.folders -{ - using infrastructure.filesystem; - - public class DefaultMigrationsFolder : DefaultFolder, MigrationsFolder - { - public DefaultMigrationsFolder(FileSystemAccess file_system, string folder_path, string folder_name, bool should_run_items_in_folder_once,bool should_run_items_every_time, string friendly_name) - : base(file_system, folder_path, folder_name) - { - this.should_run_items_in_folder_once = should_run_items_in_folder_once; - should_run_items_in_folder_every_time = should_run_items_every_time; - this.friendly_name = friendly_name; - } - - public bool should_run_items_in_folder_once { get; private set; } - public bool should_run_items_in_folder_every_time { get; private set; } - public string friendly_name { get; private set; } - } +namespace roundhouse.folders +{ + using infrastructure.filesystem; + + public class DefaultMigrationsFolder : DefaultFolder, MigrationsFolder + { + public DefaultMigrationsFolder(FileSystemAccess file_system, string folder_path, string folder_name, bool should_run_items_in_folder_once,bool should_run_items_every_time, string friendly_name) + : base(file_system, folder_path, folder_name) + { + this.should_run_items_in_folder_once = should_run_items_in_folder_once; + should_run_items_in_folder_every_time = should_run_items_every_time; + this.friendly_name = friendly_name; + } + + public bool should_run_items_in_folder_once { get; private set; } + public bool should_run_items_in_folder_every_time { get; private set; } + public string friendly_name { get; private set; } + } } \ No newline at end of file diff --git a/product/roundhouse/folders/Folder.cs b/product/roundhouse.core/folders/Folder.cs similarity index 95% rename from product/roundhouse/folders/Folder.cs rename to product/roundhouse.core/folders/Folder.cs index 815fa235..f618ac66 100644 --- a/product/roundhouse/folders/Folder.cs +++ b/product/roundhouse.core/folders/Folder.cs @@ -1,9 +1,9 @@ -namespace roundhouse.folders -{ - public interface Folder - { - string folder_name { get; set; } - string folder_path { get; } - string folder_full_path { get; } - } +namespace roundhouse.folders +{ + public interface Folder + { + string folder_name { get; set; } + string folder_path { get; } + string folder_full_path { get; } + } } \ No newline at end of file diff --git a/product/roundhouse/folders/KnownFolders.cs b/product/roundhouse.core/folders/KnownFolders.cs similarity index 97% rename from product/roundhouse/folders/KnownFolders.cs rename to product/roundhouse.core/folders/KnownFolders.cs index 6a8477c9..b5240338 100644 --- a/product/roundhouse/folders/KnownFolders.cs +++ b/product/roundhouse.core/folders/KnownFolders.cs @@ -1,22 +1,22 @@ -namespace roundhouse.folders -{ - public interface KnownFolders - { - MigrationsFolder alter_database { get; } - MigrationsFolder run_after_create_database { get; } - MigrationsFolder run_before_up { get; } - MigrationsFolder up { get; } - MigrationsFolder down { get; } - MigrationsFolder run_first_after_up { get; } - MigrationsFolder functions { get; } - MigrationsFolder views { get; } - MigrationsFolder sprocs { get; } - MigrationsFolder triggers { get; } - MigrationsFolder indexes { get; } - MigrationsFolder run_after_other_any_time_scripts { get; } - MigrationsFolder permissions { get; } - MigrationsFolder before_migration { get; } - MigrationsFolder after_migration { get; } - Folder change_drop { get; } - } +namespace roundhouse.folders +{ + public interface KnownFolders + { + MigrationsFolder alter_database { get; } + MigrationsFolder run_after_create_database { get; } + MigrationsFolder run_before_up { get; } + MigrationsFolder up { get; } + MigrationsFolder down { get; } + MigrationsFolder run_first_after_up { get; } + MigrationsFolder functions { get; } + MigrationsFolder views { get; } + MigrationsFolder sprocs { get; } + MigrationsFolder triggers { get; } + MigrationsFolder indexes { get; } + MigrationsFolder run_after_other_any_time_scripts { get; } + MigrationsFolder permissions { get; } + MigrationsFolder before_migration { get; } + MigrationsFolder after_migration { get; } + Folder change_drop { get; } + } } \ No newline at end of file diff --git a/product/roundhouse/folders/MigrationsFolder.cs b/product/roundhouse.core/folders/MigrationsFolder.cs similarity index 96% rename from product/roundhouse/folders/MigrationsFolder.cs rename to product/roundhouse.core/folders/MigrationsFolder.cs index ced76af8..3ef24197 100644 --- a/product/roundhouse/folders/MigrationsFolder.cs +++ b/product/roundhouse.core/folders/MigrationsFolder.cs @@ -1,9 +1,9 @@ -namespace roundhouse.folders -{ - public interface MigrationsFolder : Folder - { - bool should_run_items_in_folder_once { get; } - bool should_run_items_in_folder_every_time { get; } - string friendly_name { get; } - } +namespace roundhouse.folders +{ + public interface MigrationsFolder : Folder + { + bool should_run_items_in_folder_once { get; } + bool should_run_items_in_folder_every_time { get; } + string friendly_name { get; } + } } \ No newline at end of file diff --git a/product/roundhouse/infrastructure.app/ApplicationConfiguraton.cs b/product/roundhouse.core/infrastructure.app/ApplicationConfiguraton.cs similarity index 98% rename from product/roundhouse/infrastructure.app/ApplicationConfiguraton.cs rename to product/roundhouse.core/infrastructure.app/ApplicationConfiguraton.cs index 3bcc3a5b..8647f3d2 100644 --- a/product/roundhouse/infrastructure.app/ApplicationConfiguraton.cs +++ b/product/roundhouse.core/infrastructure.app/ApplicationConfiguraton.cs @@ -1,258 +1,258 @@ -using System; -using System.Collections.Generic; -using System.Reflection; -using log4net; -using Microsoft.Build.Framework; -using log4net.Core; -using log4net.Repository; -using ILogger = Microsoft.Build.Framework.ILogger; - -namespace roundhouse.infrastructure.app -{ - using System.IO; - using builders; - using containers; - using containers.custom; - using cryptography; - using databases; - using environments; - using filesystem; - using folders; - using infrastructure.logging; - using infrastructure.logging.custom; - using init; - using logging; - using migrators; - using resolvers; - using System.Linq; - - public static class ApplicationConfiguraton - { - public static void set_defaults_if_properties_are_not_set(ConfigurationPropertyHolder configuration_property_holder) - { - if (string.IsNullOrEmpty(configuration_property_holder.SqlFilesDirectory)) - { - configuration_property_holder.SqlFilesDirectory = ApplicationParameters.default_files_directory; - } - if (string.IsNullOrEmpty(configuration_property_holder.ServerName) && string.IsNullOrEmpty(configuration_property_holder.ConnectionString)) - { - configuration_property_holder.ServerName = ApplicationParameters.default_server_name; - } - if (configuration_property_holder.CommandTimeout == 0) - { - configuration_property_holder.CommandTimeout = ApplicationParameters.default_command_timeout; - } - if (configuration_property_holder.CommandTimeoutAdmin == 0) - { - configuration_property_holder.CommandTimeoutAdmin = ApplicationParameters.default_admin_command_timeout; - } - if (string.IsNullOrEmpty(configuration_property_holder.AlterDatabaseFolderName)) - { - configuration_property_holder.AlterDatabaseFolderName = ApplicationParameters.default_alter_database_folder_name; - } - if (string.IsNullOrEmpty(configuration_property_holder.RunAfterCreateDatabaseFolderName)) - { - configuration_property_holder.RunAfterCreateDatabaseFolderName = ApplicationParameters.default_run_after_create_database_folder_name; - } - if (string.IsNullOrEmpty(configuration_property_holder.RunBeforeUpFolderName)) - { - configuration_property_holder.RunBeforeUpFolderName = ApplicationParameters.default_run_before_up_folder_name; - } - if (string.IsNullOrEmpty(configuration_property_holder.UpFolderName)) - { - configuration_property_holder.UpFolderName = ApplicationParameters.default_up_folder_name; - } - if (string.IsNullOrEmpty(configuration_property_holder.DownFolderName)) - { - configuration_property_holder.DownFolderName = ApplicationParameters.default_down_folder_name; - } - if (string.IsNullOrEmpty(configuration_property_holder.RunFirstAfterUpFolderName)) - { - configuration_property_holder.RunFirstAfterUpFolderName = ApplicationParameters.default_run_first_after_up_folder_name; - } - if (string.IsNullOrEmpty(configuration_property_holder.FunctionsFolderName)) - { - configuration_property_holder.FunctionsFolderName = ApplicationParameters.default_functions_folder_name; - } - if (string.IsNullOrEmpty(configuration_property_holder.ViewsFolderName)) - { - configuration_property_holder.ViewsFolderName = ApplicationParameters.default_views_folder_name; - } - if (string.IsNullOrEmpty(configuration_property_holder.SprocsFolderName)) - { - configuration_property_holder.SprocsFolderName = ApplicationParameters.default_sprocs_folder_name; - } - if (string.IsNullOrEmpty(configuration_property_holder.TriggersFolderName)) - { - configuration_property_holder.TriggersFolderName = ApplicationParameters.default_triggers_folder_name; - } - if (string.IsNullOrEmpty(configuration_property_holder.IndexesFolderName)) - { - configuration_property_holder.IndexesFolderName = ApplicationParameters.default_indexes_folder_name; - } - if (string.IsNullOrEmpty(configuration_property_holder.RunAfterOtherAnyTimeScriptsFolderName)) - { - configuration_property_holder.RunAfterOtherAnyTimeScriptsFolderName = ApplicationParameters.default_runAfterOtherAnyTime_folder_name; - } - if (string.IsNullOrEmpty(configuration_property_holder.PermissionsFolderName)) - { - configuration_property_holder.PermissionsFolderName = ApplicationParameters.default_permissions_folder_name; - } - if (string.IsNullOrEmpty(configuration_property_holder.SchemaName)) - { - configuration_property_holder.SchemaName = ApplicationParameters.default_roundhouse_schema_name; - } - if (string.IsNullOrEmpty(configuration_property_holder.ScriptsRunTableName)) - { - configuration_property_holder.ScriptsRunTableName = ApplicationParameters.default_scripts_run_table_name; - } - if (string.IsNullOrEmpty(configuration_property_holder.ScriptsRunErrorsTableName)) - { - configuration_property_holder.ScriptsRunErrorsTableName = ApplicationParameters.default_scripts_run_errors_table_name; - } - if (string.IsNullOrEmpty(configuration_property_holder.VersionTableName)) - { - configuration_property_holder.VersionTableName = ApplicationParameters.default_version_table_name; - } - if (string.IsNullOrEmpty(configuration_property_holder.VersionFile)) - { - configuration_property_holder.VersionFile = ApplicationParameters.default_version_file; - } - if (string.IsNullOrEmpty(configuration_property_holder.VersionXPath)) - { - configuration_property_holder.VersionXPath = ApplicationParameters.default_version_x_path; - } - if (!configuration_property_holder.EnvironmentNames.Any()) - { - configuration_property_holder.EnvironmentNames.Add(ApplicationParameters.default_environment_name); - } - if (string.IsNullOrEmpty(configuration_property_holder.OutputPath)) - { - configuration_property_holder.OutputPath = ApplicationParameters.default_output_path; - } - if (string.IsNullOrEmpty(configuration_property_holder.DatabaseType)) - { - configuration_property_holder.DatabaseType = ApplicationParameters.default_database_type; - } - if (configuration_property_holder.RestoreTimeout == 0) - { - configuration_property_holder.RestoreTimeout = ApplicationParameters.default_restore_timeout; - } - if (!string.IsNullOrEmpty(configuration_property_holder.RestoreFromPath)) - { - configuration_property_holder.RestoreFromPath = Path.GetFullPath(configuration_property_holder.RestoreFromPath); - } - } - - private static void set_up_current_mappings(ConfigurationPropertyHolder configuration_property_holder) - { - ApplicationParameters.CurrentMappings.roundhouse_schema_name = configuration_property_holder.SchemaName; - ApplicationParameters.CurrentMappings.version_table_name = configuration_property_holder.VersionTableName; - ApplicationParameters.CurrentMappings.scripts_run_table_name = configuration_property_holder.ScriptsRunTableName; - ApplicationParameters.CurrentMappings.scripts_run_errors_table_name = configuration_property_holder.ScriptsRunErrorsTableName; - ApplicationParameters.CurrentMappings.database_type = configuration_property_holder.DatabaseType; - } - - public static void build_the_container(ConfigurationPropertyHolder configuration_property_holder) - { - Container.initialize_with(null); - Container.initialize_with(build_items_for_container(configuration_property_holder)); - initialize_file_log_appender(); - set_logging_level_debug_when_debug(configuration_property_holder); - } - - private static InversionContainer build_items_for_container(ConfigurationPropertyHolder configuration_property_holder) - { - configuration_property_holder.DatabaseType = DatabaseTypeSynonyms.convert_database_type_synonyms(configuration_property_holder.DatabaseType); - - set_up_current_mappings(configuration_property_holder); - - Logger multi_logger = GetMultiLogger(configuration_property_holder); - - var file_system = new DotNetFileSystemAccess(configuration_property_holder); - - var database = DatabaseBuilder.build(file_system, configuration_property_holder); - - // forcing a build of database to initialize connections so we can be sure server/database have values - database.initialize_connections(configuration_property_holder); - configuration_property_holder.ServerName = database.server_name; - configuration_property_holder.DatabaseName = database.database_name; - configuration_property_holder.ConnectionString = database.connection_string; - - var known_folders = KnownFoldersBuilder.build(file_system, configuration_property_holder); - var log_factory = new MultipleLoggerLogFactory(); - var crypto_service = new MD5CryptographicService(); - var db_migrator = new DefaultDatabaseMigrator(database, crypto_service, configuration_property_holder); - var version_resolver = VersionResolverBuilder.build(file_system, configuration_property_holder); - var environment_set = new DefaultEnvironmentSet(configuration_property_holder); - var initializer = new FileSystemInitializer(known_folders); - - HardcodedContainer.Register(configuration_property_holder); - HardcodedContainer.Register(file_system); - HardcodedContainer.Register(database); - HardcodedContainer.Register(known_folders); - HardcodedContainer.Register(log_factory); - HardcodedContainer.Register(multi_logger); - HardcodedContainer.Register(crypto_service); - HardcodedContainer.Register(db_migrator); - HardcodedContainer.Register(version_resolver); - HardcodedContainer.Register(environment_set); - HardcodedContainer.Register(initializer); - - - return HardcodedContainer.Instance; - } - - private static Logger GetMultiLogger(ConfigurationPropertyHolder configuration_property_holder) - { - IList loggers = new List(); - - // This doesn't work on macOS, at least. Try, and fail silently. - try - { - var task = configuration_property_holder as ITask; - if (task != null) - { - Logger msbuild_logger = new MSBuildLogger(configuration_property_holder); - loggers.Add(msbuild_logger); - } - } - catch (FileNotFoundException) - {} - - Logger log4net_logger = new Log4NetLogger(LogManager.GetLogger(typeof(ApplicationConfiguraton))); - loggers.Add(log4net_logger); - - if (configuration_property_holder.Logger != null && !loggers.Contains(configuration_property_holder.Logger)) - { - loggers.Add(configuration_property_holder.Logger); - } - - return new MultipleLogger(loggers); - } - - private static void initialize_file_log_appender() - { - var known_folders = Container.get_an_instance_of(); - - Log4NetAppender.set_file_appender(known_folders.change_drop.folder_full_path); - } - - private static void set_logging_level_debug_when_debug(ConfigurationPropertyHolder configuration_property_holder) - { - if (configuration_property_holder.Debug) - { - ILoggerRepository log_repository = LogManager.GetRepository(Assembly.GetCallingAssembly()); - log_repository.Threshold = Level.Debug; - foreach (log4net.Core.ILogger log in log_repository.GetCurrentLoggers()) - { - var logger = log as log4net.Repository.Hierarchy.Logger; - if (logger != null) - { - logger.Level = Level.Debug; - } - } - } - } - } +using System; +using System.Collections.Generic; +using System.Reflection; +using log4net; +using Microsoft.Build.Framework; +using log4net.Core; +using log4net.Repository; +using ILogger = Microsoft.Build.Framework.ILogger; + +namespace roundhouse.infrastructure.app +{ + using System.IO; + using builders; + using containers; + using containers.custom; + using cryptography; + using databases; + using environments; + using filesystem; + using folders; + using infrastructure.logging; + using infrastructure.logging.custom; + using init; + using logging; + using migrators; + using resolvers; + using System.Linq; + + public static class ApplicationConfiguraton + { + public static void set_defaults_if_properties_are_not_set(ConfigurationPropertyHolder configuration_property_holder) + { + if (string.IsNullOrEmpty(configuration_property_holder.SqlFilesDirectory)) + { + configuration_property_holder.SqlFilesDirectory = ApplicationParameters.default_files_directory; + } + if (string.IsNullOrEmpty(configuration_property_holder.ServerName) && string.IsNullOrEmpty(configuration_property_holder.ConnectionString)) + { + configuration_property_holder.ServerName = ApplicationParameters.default_server_name; + } + if (configuration_property_holder.CommandTimeout == 0) + { + configuration_property_holder.CommandTimeout = ApplicationParameters.default_command_timeout; + } + if (configuration_property_holder.CommandTimeoutAdmin == 0) + { + configuration_property_holder.CommandTimeoutAdmin = ApplicationParameters.default_admin_command_timeout; + } + if (string.IsNullOrEmpty(configuration_property_holder.AlterDatabaseFolderName)) + { + configuration_property_holder.AlterDatabaseFolderName = ApplicationParameters.default_alter_database_folder_name; + } + if (string.IsNullOrEmpty(configuration_property_holder.RunAfterCreateDatabaseFolderName)) + { + configuration_property_holder.RunAfterCreateDatabaseFolderName = ApplicationParameters.default_run_after_create_database_folder_name; + } + if (string.IsNullOrEmpty(configuration_property_holder.RunBeforeUpFolderName)) + { + configuration_property_holder.RunBeforeUpFolderName = ApplicationParameters.default_run_before_up_folder_name; + } + if (string.IsNullOrEmpty(configuration_property_holder.UpFolderName)) + { + configuration_property_holder.UpFolderName = ApplicationParameters.default_up_folder_name; + } + if (string.IsNullOrEmpty(configuration_property_holder.DownFolderName)) + { + configuration_property_holder.DownFolderName = ApplicationParameters.default_down_folder_name; + } + if (string.IsNullOrEmpty(configuration_property_holder.RunFirstAfterUpFolderName)) + { + configuration_property_holder.RunFirstAfterUpFolderName = ApplicationParameters.default_run_first_after_up_folder_name; + } + if (string.IsNullOrEmpty(configuration_property_holder.FunctionsFolderName)) + { + configuration_property_holder.FunctionsFolderName = ApplicationParameters.default_functions_folder_name; + } + if (string.IsNullOrEmpty(configuration_property_holder.ViewsFolderName)) + { + configuration_property_holder.ViewsFolderName = ApplicationParameters.default_views_folder_name; + } + if (string.IsNullOrEmpty(configuration_property_holder.SprocsFolderName)) + { + configuration_property_holder.SprocsFolderName = ApplicationParameters.default_sprocs_folder_name; + } + if (string.IsNullOrEmpty(configuration_property_holder.TriggersFolderName)) + { + configuration_property_holder.TriggersFolderName = ApplicationParameters.default_triggers_folder_name; + } + if (string.IsNullOrEmpty(configuration_property_holder.IndexesFolderName)) + { + configuration_property_holder.IndexesFolderName = ApplicationParameters.default_indexes_folder_name; + } + if (string.IsNullOrEmpty(configuration_property_holder.RunAfterOtherAnyTimeScriptsFolderName)) + { + configuration_property_holder.RunAfterOtherAnyTimeScriptsFolderName = ApplicationParameters.default_runAfterOtherAnyTime_folder_name; + } + if (string.IsNullOrEmpty(configuration_property_holder.PermissionsFolderName)) + { + configuration_property_holder.PermissionsFolderName = ApplicationParameters.default_permissions_folder_name; + } + if (string.IsNullOrEmpty(configuration_property_holder.SchemaName)) + { + configuration_property_holder.SchemaName = ApplicationParameters.default_roundhouse_schema_name; + } + if (string.IsNullOrEmpty(configuration_property_holder.ScriptsRunTableName)) + { + configuration_property_holder.ScriptsRunTableName = ApplicationParameters.default_scripts_run_table_name; + } + if (string.IsNullOrEmpty(configuration_property_holder.ScriptsRunErrorsTableName)) + { + configuration_property_holder.ScriptsRunErrorsTableName = ApplicationParameters.default_scripts_run_errors_table_name; + } + if (string.IsNullOrEmpty(configuration_property_holder.VersionTableName)) + { + configuration_property_holder.VersionTableName = ApplicationParameters.default_version_table_name; + } + if (string.IsNullOrEmpty(configuration_property_holder.VersionFile)) + { + configuration_property_holder.VersionFile = ApplicationParameters.default_version_file; + } + if (string.IsNullOrEmpty(configuration_property_holder.VersionXPath)) + { + configuration_property_holder.VersionXPath = ApplicationParameters.default_version_x_path; + } + if (!configuration_property_holder.EnvironmentNames.Any()) + { + configuration_property_holder.EnvironmentNames.Add(ApplicationParameters.default_environment_name); + } + if (string.IsNullOrEmpty(configuration_property_holder.OutputPath)) + { + configuration_property_holder.OutputPath = ApplicationParameters.default_output_path; + } + if (string.IsNullOrEmpty(configuration_property_holder.DatabaseType)) + { + configuration_property_holder.DatabaseType = ApplicationParameters.default_database_type; + } + if (configuration_property_holder.RestoreTimeout == 0) + { + configuration_property_holder.RestoreTimeout = ApplicationParameters.default_restore_timeout; + } + if (!string.IsNullOrEmpty(configuration_property_holder.RestoreFromPath)) + { + configuration_property_holder.RestoreFromPath = Path.GetFullPath(configuration_property_holder.RestoreFromPath); + } + } + + private static void set_up_current_mappings(ConfigurationPropertyHolder configuration_property_holder) + { + ApplicationParameters.CurrentMappings.roundhouse_schema_name = configuration_property_holder.SchemaName; + ApplicationParameters.CurrentMappings.version_table_name = configuration_property_holder.VersionTableName; + ApplicationParameters.CurrentMappings.scripts_run_table_name = configuration_property_holder.ScriptsRunTableName; + ApplicationParameters.CurrentMappings.scripts_run_errors_table_name = configuration_property_holder.ScriptsRunErrorsTableName; + ApplicationParameters.CurrentMappings.database_type = configuration_property_holder.DatabaseType; + } + + public static void build_the_container(ConfigurationPropertyHolder configuration_property_holder) + { + Container.initialize_with(null); + Container.initialize_with(build_items_for_container(configuration_property_holder)); + initialize_file_log_appender(); + set_logging_level_debug_when_debug(configuration_property_holder); + } + + private static InversionContainer build_items_for_container(ConfigurationPropertyHolder configuration_property_holder) + { + configuration_property_holder.DatabaseType = DatabaseTypeSynonyms.convert_database_type_synonyms(configuration_property_holder.DatabaseType); + + set_up_current_mappings(configuration_property_holder); + + Logger multi_logger = GetMultiLogger(configuration_property_holder); + + var file_system = new DotNetFileSystemAccess(configuration_property_holder); + + var database = DatabaseBuilder.build(file_system, configuration_property_holder); + + // forcing a build of database to initialize connections so we can be sure server/database have values + database.initialize_connections(configuration_property_holder); + configuration_property_holder.ServerName = database.server_name; + configuration_property_holder.DatabaseName = database.database_name; + configuration_property_holder.ConnectionString = database.connection_string; + + var known_folders = KnownFoldersBuilder.build(file_system, configuration_property_holder); + var log_factory = new MultipleLoggerLogFactory(); + var crypto_service = new MD5CryptographicService(); + var db_migrator = new DefaultDatabaseMigrator(database, crypto_service, configuration_property_holder); + var version_resolver = VersionResolverBuilder.build(file_system, configuration_property_holder); + var environment_set = new DefaultEnvironmentSet(configuration_property_holder); + var initializer = new FileSystemInitializer(known_folders); + + HardcodedContainer.Register(configuration_property_holder); + HardcodedContainer.Register(file_system); + HardcodedContainer.Register(database); + HardcodedContainer.Register(known_folders); + HardcodedContainer.Register(log_factory); + HardcodedContainer.Register(multi_logger); + HardcodedContainer.Register(crypto_service); + HardcodedContainer.Register(db_migrator); + HardcodedContainer.Register(version_resolver); + HardcodedContainer.Register(environment_set); + HardcodedContainer.Register(initializer); + + + return HardcodedContainer.Instance; + } + + private static Logger GetMultiLogger(ConfigurationPropertyHolder configuration_property_holder) + { + IList loggers = new List(); + + // This doesn't work on macOS, at least. Try, and fail silently. + try + { + var task = configuration_property_holder as ITask; + if (task != null) + { + Logger msbuild_logger = new MSBuildLogger(configuration_property_holder); + loggers.Add(msbuild_logger); + } + } + catch (FileNotFoundException) + {} + + Logger log4net_logger = new Log4NetLogger(LogManager.GetLogger(typeof(ApplicationConfiguraton))); + loggers.Add(log4net_logger); + + if (configuration_property_holder.Logger != null && !loggers.Contains(configuration_property_holder.Logger)) + { + loggers.Add(configuration_property_holder.Logger); + } + + return new MultipleLogger(loggers); + } + + private static void initialize_file_log_appender() + { + var known_folders = Container.get_an_instance_of(); + + Log4NetAppender.set_file_appender(known_folders.change_drop.folder_full_path); + } + + private static void set_logging_level_debug_when_debug(ConfigurationPropertyHolder configuration_property_holder) + { + if (configuration_property_holder.Debug) + { + ILoggerRepository log_repository = LogManager.GetRepository(Assembly.GetCallingAssembly()); + log_repository.Threshold = Level.Debug; + foreach (log4net.Core.ILogger log in log_repository.GetCurrentLoggers()) + { + var logger = log as log4net.Repository.Hierarchy.Logger; + if (logger != null) + { + logger.Level = Level.Debug; + } + } + } + } + } } \ No newline at end of file diff --git a/product/roundhouse/infrastructure.app/ConfigurationPropertyHolder.cs b/product/roundhouse.core/infrastructure.app/ConfigurationPropertyHolder.cs similarity index 97% rename from product/roundhouse/infrastructure.app/ConfigurationPropertyHolder.cs rename to product/roundhouse.core/infrastructure.app/ConfigurationPropertyHolder.cs index f1274cd2..00263e29 100644 --- a/product/roundhouse/infrastructure.app/ConfigurationPropertyHolder.cs +++ b/product/roundhouse.core/infrastructure.app/ConfigurationPropertyHolder.cs @@ -1,73 +1,73 @@ -using System.Collections.Generic; -using roundhouse.infrastructure.logging; -// ReSharper disable InconsistentNaming - -namespace roundhouse.infrastructure.app -{ - using System; - using databases; - - public interface ConfigurationPropertyHolder - { - Logger Logger { get; set; } - string ServerName { get; set; } - string DatabaseName { get; set; } - string ConnectionString { get; set; } - string ConnectionStringAdmin { get; set; } - int CommandTimeout { get; set; } - int CommandTimeoutAdmin { get; set; } - string SqlFilesDirectory { get; set; } - string RepositoryPath { get; set; } - string Version { get; set; } - string VersionFile { get; set; } - string VersionXPath { get; set; } - string AlterDatabaseFolderName { get; set; } - string RunAfterCreateDatabaseFolderName { get; set; } - string RunBeforeUpFolderName { get; set; } - string UpFolderName { get; set; } - string DownFolderName { get; set; } - string RunFirstAfterUpFolderName { get; set; } - string FunctionsFolderName { get; set; } - string ViewsFolderName { get; set; } - string SprocsFolderName { get; set; } - string TriggersFolderName { get; set; } - string IndexesFolderName { get; set; } - string RunAfterOtherAnyTimeScriptsFolderName { get; set; } - string PermissionsFolderName { get; set; } - string BeforeMigrationFolderName { get; set; } - string AfterMigrationFolderName { get; set; } - string SchemaName { get; set; } - string VersionTableName { get; set; } - string ScriptsRunTableName { get; set; } - string ScriptsRunErrorsTableName { get; set; } - [Obsolete("Use EnvironmentNames")] - string EnvironmentName { get; set; } - IList EnvironmentNames { get; } - bool Restore { get; set; } - string RestoreFromPath { get; set; } - string RestoreCustomOptions { get; set; } - int RestoreTimeout { get; set; } - string CreateDatabaseCustomScript { get; set; } - string OutputPath { get; set; } - bool WarnOnOneTimeScriptChanges { get; set; } - bool WarnAndIgnoreOnOneTimeScriptChanges { get; set; } - bool Silent { get; set; } - string DatabaseType { get; set; } - bool Drop { get; set; } - bool DoNotCreateDatabase { get; set; } - bool DoNotAlterDatabase { get; set; } - bool WithTransaction { get; set; } - RecoveryMode RecoveryMode { get; set; } - bool Debug { get; set; } - bool DryRun { get; set; } - bool Baseline { get; set; } - bool RunAllAnyTimeScripts { get; set; } - bool DisableTokenReplacement { get; set; } - bool SearchAllSubdirectoriesInsteadOfTraverse { get; set; } - bool DisableOutput { get; set; } - Dictionary UserTokens { get; set; } - System.Text.Encoding DefaultEncoding { get; set; } - string ConfigurationFile { get; set; } - IDictionary to_token_dictionary(); - } +using System.Collections.Generic; +using roundhouse.infrastructure.logging; +// ReSharper disable InconsistentNaming + +namespace roundhouse.infrastructure.app +{ + using System; + using databases; + + public interface ConfigurationPropertyHolder + { + Logger Logger { get; set; } + string ServerName { get; set; } + string DatabaseName { get; set; } + string ConnectionString { get; set; } + string ConnectionStringAdmin { get; set; } + int CommandTimeout { get; set; } + int CommandTimeoutAdmin { get; set; } + string SqlFilesDirectory { get; set; } + string RepositoryPath { get; set; } + string Version { get; set; } + string VersionFile { get; set; } + string VersionXPath { get; set; } + string AlterDatabaseFolderName { get; set; } + string RunAfterCreateDatabaseFolderName { get; set; } + string RunBeforeUpFolderName { get; set; } + string UpFolderName { get; set; } + string DownFolderName { get; set; } + string RunFirstAfterUpFolderName { get; set; } + string FunctionsFolderName { get; set; } + string ViewsFolderName { get; set; } + string SprocsFolderName { get; set; } + string TriggersFolderName { get; set; } + string IndexesFolderName { get; set; } + string RunAfterOtherAnyTimeScriptsFolderName { get; set; } + string PermissionsFolderName { get; set; } + string BeforeMigrationFolderName { get; set; } + string AfterMigrationFolderName { get; set; } + string SchemaName { get; set; } + string VersionTableName { get; set; } + string ScriptsRunTableName { get; set; } + string ScriptsRunErrorsTableName { get; set; } + [Obsolete("Use EnvironmentNames")] + string EnvironmentName { get; set; } + IList EnvironmentNames { get; } + bool Restore { get; set; } + string RestoreFromPath { get; set; } + string RestoreCustomOptions { get; set; } + int RestoreTimeout { get; set; } + string CreateDatabaseCustomScript { get; set; } + string OutputPath { get; set; } + bool WarnOnOneTimeScriptChanges { get; set; } + bool WarnAndIgnoreOnOneTimeScriptChanges { get; set; } + bool Silent { get; set; } + string DatabaseType { get; set; } + bool Drop { get; set; } + bool DoNotCreateDatabase { get; set; } + bool DoNotAlterDatabase { get; set; } + bool WithTransaction { get; set; } + RecoveryMode RecoveryMode { get; set; } + bool Debug { get; set; } + bool DryRun { get; set; } + bool Baseline { get; set; } + bool RunAllAnyTimeScripts { get; set; } + bool DisableTokenReplacement { get; set; } + bool SearchAllSubdirectoriesInsteadOfTraverse { get; set; } + bool DisableOutput { get; set; } + Dictionary UserTokens { get; set; } + System.Text.Encoding DefaultEncoding { get; set; } + string ConfigurationFile { get; set; } + IDictionary to_token_dictionary(); + } } \ No newline at end of file diff --git a/product/roundhouse/infrastructure.app/ConnectionType.cs b/product/roundhouse.core/infrastructure.app/ConnectionType.cs similarity index 94% rename from product/roundhouse/infrastructure.app/ConnectionType.cs rename to product/roundhouse.core/infrastructure.app/ConnectionType.cs index 3e4fff38..b6ec4bf0 100644 --- a/product/roundhouse/infrastructure.app/ConnectionType.cs +++ b/product/roundhouse.core/infrastructure.app/ConnectionType.cs @@ -1,8 +1,8 @@ -namespace roundhouse.infrastructure.app -{ - public enum ConnectionType - { - Default, - Admin - } +namespace roundhouse.infrastructure.app +{ + public enum ConnectionType + { + Default, + Admin + } } \ No newline at end of file diff --git a/product/roundhouse/infrastructure.app/DatabaseTypeSynonyms.cs b/product/roundhouse.core/infrastructure.app/DatabaseTypeSynonyms.cs similarity index 97% rename from product/roundhouse/infrastructure.app/DatabaseTypeSynonyms.cs rename to product/roundhouse.core/infrastructure.app/DatabaseTypeSynonyms.cs index a949ac9b..31966d72 100644 --- a/product/roundhouse/infrastructure.app/DatabaseTypeSynonyms.cs +++ b/product/roundhouse.core/infrastructure.app/DatabaseTypeSynonyms.cs @@ -1,66 +1,66 @@ -namespace roundhouse.infrastructure.app -{ - using extensions; - - public class DatabaseTypeSynonyms - { - public static string convert_database_type_synonyms(string database_type) - { - string database_type_full_name = database_type; - - switch (database_type.to_lower()) - { - case "2008": - case "sql2008": - case "sqlserver2008": - case "2005": - case "sql2005": - case "sqlserver2005": - case "sql": - case "sql.net": - case "sqlserver": - case "sqlado.net": - database_type_full_name = - "roundhouse.databases.sqlserver.SqlServerDatabase, roundhouse.databases.sqlserver"; - break; - case "2000": - case "sql2000": - case "sqlserver2000": - database_type_full_name = - "roundhouse.databases.sqlserver2000.SqlServerDatabase, roundhouse.databases.sqlserver2000"; - break; - case "sqlce": - case "sqlserverce": - database_type_full_name = - "roundhouse.databases.sqlserverce.SqlServerCEDatabase, roundhouse.databases.sqlserverce"; - break; - case "mysql": - database_type_full_name = - "roundhouse.databases.mysql.MySqlDatabase, roundhouse.databases.mysql"; - break; - case "sqlite": - database_type_full_name = - "roundhouse.databases.sqlite.SqliteDatabase, roundhouse.databases.sqlite"; - break; - case "oracle": - database_type_full_name = - "roundhouse.databases.oracle.OracleDatabase, roundhouse.databases.oracle"; - break; - case "access": - database_type_full_name = "roundhouse.databases.access.AccessDatabase, roundhouse.databases.access"; - break; - case "pg": - case "postgres": - case "postgresql": - database_type_full_name = "roundhouse.databases.postgresql.PostgreSQLDatabase, roundhouse.databases.postgresql"; - break; - //case "oledb": - // database_type_full_name = - // "roundhouse.databases.oledb.OleDbDatabase, roundhouse.databases.oledb"; - // break; - } - - return database_type_full_name; - } - } +namespace roundhouse.infrastructure.app +{ + using extensions; + + public class DatabaseTypeSynonyms + { + public static string convert_database_type_synonyms(string database_type) + { + string database_type_full_name = database_type; + + switch (database_type.to_lower()) + { + case "2008": + case "sql2008": + case "sqlserver2008": + case "2005": + case "sql2005": + case "sqlserver2005": + case "sql": + case "sql.net": + case "sqlserver": + case "sqlado.net": + database_type_full_name = + "roundhouse.databases.sqlserver.SqlServerDatabase, roundhouse.databases.sqlserver"; + break; + case "2000": + case "sql2000": + case "sqlserver2000": + database_type_full_name = + "roundhouse.databases.sqlserver2000.SqlServerDatabase, roundhouse.databases.sqlserver2000"; + break; + case "sqlce": + case "sqlserverce": + database_type_full_name = + "roundhouse.databases.sqlserverce.SqlServerCEDatabase, roundhouse.databases.sqlserverce"; + break; + case "mysql": + database_type_full_name = + "roundhouse.databases.mysql.MySqlDatabase, roundhouse.databases.mysql"; + break; + case "sqlite": + database_type_full_name = + "roundhouse.databases.sqlite.SqliteDatabase, roundhouse.databases.sqlite"; + break; + case "oracle": + database_type_full_name = + "roundhouse.databases.oracle.OracleDatabase, roundhouse.databases.oracle"; + break; + case "access": + database_type_full_name = "roundhouse.databases.access.AccessDatabase, roundhouse.databases.access"; + break; + case "pg": + case "postgres": + case "postgresql": + database_type_full_name = "roundhouse.databases.postgresql.PostgreSQLDatabase, roundhouse.databases.postgresql"; + break; + //case "oledb": + // database_type_full_name = + // "roundhouse.databases.oledb.OleDbDatabase, roundhouse.databases.oledb"; + // break; + } + + return database_type_full_name; + } + } } \ No newline at end of file diff --git a/product/roundhouse/infrastructure.app/UserTokenParser.cs b/product/roundhouse.core/infrastructure.app/UserTokenParser.cs similarity index 100% rename from product/roundhouse/infrastructure.app/UserTokenParser.cs rename to product/roundhouse.core/infrastructure.app/UserTokenParser.cs diff --git a/product/roundhouse/infrastructure.app/builders/DatabaseBuilder.cs b/product/roundhouse.core/infrastructure.app/builders/DatabaseBuilder.cs similarity index 96% rename from product/roundhouse/infrastructure.app/builders/DatabaseBuilder.cs rename to product/roundhouse.core/infrastructure.app/builders/DatabaseBuilder.cs index 8c299efe..c81bcb48 100644 --- a/product/roundhouse/infrastructure.app/builders/DatabaseBuilder.cs +++ b/product/roundhouse.core/infrastructure.app/builders/DatabaseBuilder.cs @@ -1,80 +1,83 @@ -namespace roundhouse.infrastructure.app.builders -{ - using System; - using System.Reflection; - using System.Security.Principal; - using databases; - using filesystem; - using loaders; - - public static class DatabaseBuilder - { - private static string merge_assembly_name = "rh"; - - public static Database build(FileSystemAccess file_system, ConfigurationPropertyHolder configuration_property_holder) - { - Database database_to_migrate; - - if (Assembly.GetExecutingAssembly().Location.Contains("roundhouse.dll")) - { - merge_assembly_name = "roundhouse"; - } - - try - { - string database_type = configuration_property_holder.DatabaseType; - database_type = database_type.Substring(0, database_type.IndexOf(',')); - database_to_migrate = DefaultInstanceCreator.create_object_from_string_type(database_type + ", " + merge_assembly_name); - - } - catch (NullReferenceException) - { - database_to_migrate = DefaultInstanceCreator.create_object_from_string_type(configuration_property_holder.DatabaseType); - } - - if (restore_from_file_ends_with_LiteSpeed_extension(file_system, configuration_property_holder.RestoreFromPath)) - { - database_to_migrate = new SqlServerLiteSpeedDatabase(database_to_migrate); - } - database_to_migrate.configuration = configuration_property_holder; - database_to_migrate.server_name = configuration_property_holder.ServerName ?? string.Empty; - database_to_migrate.database_name = configuration_property_holder.DatabaseName ?? string.Empty; - database_to_migrate.connection_string = configuration_property_holder.ConnectionString; - database_to_migrate.admin_connection_string = configuration_property_holder.ConnectionStringAdmin; - database_to_migrate.roundhouse_schema_name = configuration_property_holder.SchemaName; - database_to_migrate.version_table_name = configuration_property_holder.VersionTableName; - database_to_migrate.scripts_run_table_name = configuration_property_holder.ScriptsRunTableName; - database_to_migrate.scripts_run_errors_table_name = configuration_property_holder.ScriptsRunErrorsTableName; - database_to_migrate.user_name = get_identity_of_person_running_roundhouse(); - database_to_migrate.command_timeout = configuration_property_holder.CommandTimeout; - database_to_migrate.admin_command_timeout = configuration_property_holder.CommandTimeoutAdmin; - database_to_migrate.restore_timeout = configuration_property_holder.RestoreTimeout; - - return database_to_migrate; - } - - private static string get_identity_of_person_running_roundhouse() - { - string identity_of_runner = string.Empty; - - try - { - WindowsIdentity windows_identity = WindowsIdentity.GetCurrent(); - identity_of_runner = windows_identity.Name; - } - catch (System.PlatformNotSupportedException) - { - identity_of_runner = Environment.UserName; - } - - return identity_of_runner; - } - - private static bool restore_from_file_ends_with_LiteSpeed_extension(FileSystemAccess file_system, string restore_path) - { - if (string.IsNullOrEmpty(restore_path)) return false; - - return file_system.get_file_name_without_extension_from(restore_path).ToLower().EndsWith("ls"); - } - } +namespace roundhouse.infrastructure.app.builders +{ + using System; + using System.Reflection; + using System.Security.Principal; + using databases; + using filesystem; + using loaders; + + public static class DatabaseBuilder + { + private static string merge_assembly_name = "rh"; + + public static Database build(FileSystemAccess file_system, ConfigurationPropertyHolder configuration_property_holder) + { + Database database_to_migrate; + + if (Assembly.GetExecutingAssembly().Location.Contains("roundhouse.dll")) + { + merge_assembly_name = "roundhouse"; + } + + try + { + string database_type = configuration_property_holder.DatabaseType; + database_type = database_type.Substring(0, database_type.IndexOf(',')); + database_to_migrate = DefaultInstanceCreator.create_object_from_string_type(database_type + ", " + merge_assembly_name); + + } + catch (NullReferenceException) + { + database_to_migrate = DefaultInstanceCreator.create_object_from_string_type(configuration_property_holder.DatabaseType); + } + + if (restore_from_file_ends_with_LiteSpeed_extension(file_system, configuration_property_holder.RestoreFromPath)) + { + database_to_migrate = new SqlServerLiteSpeedDatabase(database_to_migrate); + } + database_to_migrate.configuration = configuration_property_holder; + database_to_migrate.server_name = configuration_property_holder.ServerName ?? string.Empty; + database_to_migrate.database_name = configuration_property_holder.DatabaseName ?? string.Empty; + database_to_migrate.connection_string = configuration_property_holder.ConnectionString; + database_to_migrate.admin_connection_string = configuration_property_holder.ConnectionStringAdmin; + database_to_migrate.roundhouse_schema_name = configuration_property_holder.SchemaName; + database_to_migrate.version_table_name = configuration_property_holder.VersionTableName; + database_to_migrate.scripts_run_table_name = configuration_property_holder.ScriptsRunTableName; + database_to_migrate.scripts_run_errors_table_name = configuration_property_holder.ScriptsRunErrorsTableName; + database_to_migrate.user_name = get_identity_of_person_running_roundhouse(); + database_to_migrate.command_timeout = configuration_property_holder.CommandTimeout; + database_to_migrate.admin_command_timeout = configuration_property_holder.CommandTimeoutAdmin; + database_to_migrate.restore_timeout = configuration_property_holder.RestoreTimeout; + + return database_to_migrate; + } + + private static string get_identity_of_person_running_roundhouse() + { + string identity_of_runner = string.Empty; + + try + { + WindowsIdentity windows_identity = WindowsIdentity.GetCurrent(); + identity_of_runner = windows_identity.Name; + } + catch (System.PlatformNotSupportedException) + { + identity_of_runner = Environment.UserName; + } + + return identity_of_runner; + } + + private static bool restore_from_file_ends_with_LiteSpeed_extension(FileSystemAccess file_system, string restore_path) + { + if (string.IsNullOrEmpty(restore_path)) + { + return false; + } + + return file_system.get_file_name_without_extension_from(restore_path).ToLower().EndsWith("ls"); + } + } } \ No newline at end of file diff --git a/product/roundhouse/infrastructure.app/builders/KnownFoldersBuilder.cs b/product/roundhouse.core/infrastructure.app/builders/KnownFoldersBuilder.cs similarity index 98% rename from product/roundhouse/infrastructure.app/builders/KnownFoldersBuilder.cs rename to product/roundhouse.core/infrastructure.app/builders/KnownFoldersBuilder.cs index d26517df..e00e5a92 100644 --- a/product/roundhouse/infrastructure.app/builders/KnownFoldersBuilder.cs +++ b/product/roundhouse.core/infrastructure.app/builders/KnownFoldersBuilder.cs @@ -1,73 +1,73 @@ -namespace roundhouse.infrastructure.app.builders -{ - using System; - using filesystem; - using folders; - - public static class KnownFoldersBuilder - { - public static KnownFolders build(FileSystemAccess file_system, ConfigurationPropertyHolder configuration_property_holder) - { - MigrationsFolder alter_database_folder = new DefaultMigrationsFolder(file_system, configuration_property_holder.SqlFilesDirectory, configuration_property_holder.AlterDatabaseFolderName, false, false, "AlterDatabase"); - MigrationsFolder run_after_create_database_folder = new DefaultMigrationsFolder(file_system, configuration_property_holder.SqlFilesDirectory, configuration_property_holder.RunAfterCreateDatabaseFolderName, true, false, "Run After Create Database"); - MigrationsFolder run_before_up_folder = new DefaultMigrationsFolder(file_system, configuration_property_holder.SqlFilesDirectory, configuration_property_holder.RunBeforeUpFolderName, false, false, "Run Before Update"); - MigrationsFolder up_folder = new DefaultMigrationsFolder(file_system, configuration_property_holder.SqlFilesDirectory, configuration_property_holder.UpFolderName, true, false, "Update"); - MigrationsFolder down_folder = new DefaultMigrationsFolder(file_system, configuration_property_holder.SqlFilesDirectory, configuration_property_holder.DownFolderName, true, false, "Down Folder - Nothing to see here. Move along."); - MigrationsFolder run_first_folder = new DefaultMigrationsFolder(file_system, configuration_property_holder.SqlFilesDirectory, configuration_property_holder.RunFirstAfterUpFolderName, false, false, "Run First After Update"); - MigrationsFolder functions_folder = new DefaultMigrationsFolder(file_system, configuration_property_holder.SqlFilesDirectory, configuration_property_holder.FunctionsFolderName, false, false, "Function"); - MigrationsFolder views_folder = new DefaultMigrationsFolder(file_system, configuration_property_holder.SqlFilesDirectory, configuration_property_holder.ViewsFolderName, false, false, "View"); - MigrationsFolder sprocs_folder = new DefaultMigrationsFolder(file_system, configuration_property_holder.SqlFilesDirectory, configuration_property_holder.SprocsFolderName, false, false, "Stored Procedure"); - MigrationsFolder triggers_folder = new DefaultMigrationsFolder(file_system, configuration_property_holder.SqlFilesDirectory, configuration_property_holder.TriggersFolderName, false, false, "Triggers"); - MigrationsFolder indexes_folder = new DefaultMigrationsFolder(file_system, configuration_property_holder.SqlFilesDirectory, configuration_property_holder.IndexesFolderName, false, false, "Index"); - MigrationsFolder runAfterOtherAnyTimeScripts_folder = new DefaultMigrationsFolder(file_system, configuration_property_holder.SqlFilesDirectory, configuration_property_holder.RunAfterOtherAnyTimeScriptsFolderName, false, false, "Run after Other Anytime Scripts"); - MigrationsFolder permissions_folder = new DefaultMigrationsFolder(file_system, configuration_property_holder.SqlFilesDirectory, configuration_property_holder.PermissionsFolderName, false, true, "Permission"); - MigrationsFolder before_migration_folder = new DefaultMigrationsFolder(file_system, configuration_property_holder.SqlFilesDirectory, configuration_property_holder.BeforeMigrationFolderName, false, true, "BeforeMigration"); - MigrationsFolder after_migration_folder = new DefaultMigrationsFolder(file_system, configuration_property_holder.SqlFilesDirectory, configuration_property_holder.AfterMigrationFolderName, false, true, "AfterMigration"); - - - Folder change_drop_folder = new DefaultFolder(file_system, combine_items_into_one_path(file_system, - configuration_property_holder.OutputPath, - "migrations", - remove_invalid_characters_from(configuration_property_holder.DatabaseName,file_system), - remove_invalid_characters_from(configuration_property_holder.ServerName,file_system)), - get_run_date_time_string()); - - return new DefaultKnownFolders( - alter_database_folder, - run_after_create_database_folder, - run_before_up_folder, up_folder, - down_folder, - run_first_folder, - functions_folder, - views_folder, - sprocs_folder, - triggers_folder, - indexes_folder, - runAfterOtherAnyTimeScripts_folder, - permissions_folder, - before_migration_folder, - after_migration_folder, - change_drop_folder); - } - - private static string combine_items_into_one_path(FileSystemAccess file_system, params string[] paths) - { - return file_system.combine_paths(paths); - } - - private static string remove_paths_from(string name, FileSystemAccess file_system) - { - return file_system.get_file_name_without_extension_from(name); - } - - private static string remove_invalid_characters_from(string path_segment, FileSystemAccess file_system) - { - return file_system.remove_invalid_characters_from(path_segment); - } - - private static string get_run_date_time_string() - { - return string.Format("{0:yyyyMMdd_HHmmss_ffff}", DateTime.Now); - } - } +namespace roundhouse.infrastructure.app.builders +{ + using System; + using filesystem; + using folders; + + public static class KnownFoldersBuilder + { + public static KnownFolders build(FileSystemAccess file_system, ConfigurationPropertyHolder configuration_property_holder) + { + MigrationsFolder alter_database_folder = new DefaultMigrationsFolder(file_system, configuration_property_holder.SqlFilesDirectory, configuration_property_holder.AlterDatabaseFolderName, false, false, "AlterDatabase"); + MigrationsFolder run_after_create_database_folder = new DefaultMigrationsFolder(file_system, configuration_property_holder.SqlFilesDirectory, configuration_property_holder.RunAfterCreateDatabaseFolderName, true, false, "Run After Create Database"); + MigrationsFolder run_before_up_folder = new DefaultMigrationsFolder(file_system, configuration_property_holder.SqlFilesDirectory, configuration_property_holder.RunBeforeUpFolderName, false, false, "Run Before Update"); + MigrationsFolder up_folder = new DefaultMigrationsFolder(file_system, configuration_property_holder.SqlFilesDirectory, configuration_property_holder.UpFolderName, true, false, "Update"); + MigrationsFolder down_folder = new DefaultMigrationsFolder(file_system, configuration_property_holder.SqlFilesDirectory, configuration_property_holder.DownFolderName, true, false, "Down Folder - Nothing to see here. Move along."); + MigrationsFolder run_first_folder = new DefaultMigrationsFolder(file_system, configuration_property_holder.SqlFilesDirectory, configuration_property_holder.RunFirstAfterUpFolderName, false, false, "Run First After Update"); + MigrationsFolder functions_folder = new DefaultMigrationsFolder(file_system, configuration_property_holder.SqlFilesDirectory, configuration_property_holder.FunctionsFolderName, false, false, "Function"); + MigrationsFolder views_folder = new DefaultMigrationsFolder(file_system, configuration_property_holder.SqlFilesDirectory, configuration_property_holder.ViewsFolderName, false, false, "View"); + MigrationsFolder sprocs_folder = new DefaultMigrationsFolder(file_system, configuration_property_holder.SqlFilesDirectory, configuration_property_holder.SprocsFolderName, false, false, "Stored Procedure"); + MigrationsFolder triggers_folder = new DefaultMigrationsFolder(file_system, configuration_property_holder.SqlFilesDirectory, configuration_property_holder.TriggersFolderName, false, false, "Triggers"); + MigrationsFolder indexes_folder = new DefaultMigrationsFolder(file_system, configuration_property_holder.SqlFilesDirectory, configuration_property_holder.IndexesFolderName, false, false, "Index"); + MigrationsFolder runAfterOtherAnyTimeScripts_folder = new DefaultMigrationsFolder(file_system, configuration_property_holder.SqlFilesDirectory, configuration_property_holder.RunAfterOtherAnyTimeScriptsFolderName, false, false, "Run after Other Anytime Scripts"); + MigrationsFolder permissions_folder = new DefaultMigrationsFolder(file_system, configuration_property_holder.SqlFilesDirectory, configuration_property_holder.PermissionsFolderName, false, true, "Permission"); + MigrationsFolder before_migration_folder = new DefaultMigrationsFolder(file_system, configuration_property_holder.SqlFilesDirectory, configuration_property_holder.BeforeMigrationFolderName, false, true, "BeforeMigration"); + MigrationsFolder after_migration_folder = new DefaultMigrationsFolder(file_system, configuration_property_holder.SqlFilesDirectory, configuration_property_holder.AfterMigrationFolderName, false, true, "AfterMigration"); + + + Folder change_drop_folder = new DefaultFolder(file_system, combine_items_into_one_path(file_system, + configuration_property_holder.OutputPath, + "migrations", + remove_invalid_characters_from(configuration_property_holder.DatabaseName,file_system), + remove_invalid_characters_from(configuration_property_holder.ServerName,file_system)), + get_run_date_time_string()); + + return new DefaultKnownFolders( + alter_database_folder, + run_after_create_database_folder, + run_before_up_folder, up_folder, + down_folder, + run_first_folder, + functions_folder, + views_folder, + sprocs_folder, + triggers_folder, + indexes_folder, + runAfterOtherAnyTimeScripts_folder, + permissions_folder, + before_migration_folder, + after_migration_folder, + change_drop_folder); + } + + private static string combine_items_into_one_path(FileSystemAccess file_system, params string[] paths) + { + return file_system.combine_paths(paths); + } + + private static string remove_paths_from(string name, FileSystemAccess file_system) + { + return file_system.get_file_name_without_extension_from(name); + } + + private static string remove_invalid_characters_from(string path_segment, FileSystemAccess file_system) + { + return file_system.remove_invalid_characters_from(path_segment); + } + + private static string get_run_date_time_string() + { + return string.Format("{0:yyyyMMdd_HHmmss_ffff}", DateTime.Now); + } + } } \ No newline at end of file diff --git a/product/roundhouse/infrastructure.app/builders/VersionResolverBuilder.cs b/product/roundhouse.core/infrastructure.app/builders/VersionResolverBuilder.cs similarity index 95% rename from product/roundhouse/infrastructure.app/builders/VersionResolverBuilder.cs rename to product/roundhouse.core/infrastructure.app/builders/VersionResolverBuilder.cs index 72c0cda6..d75ef4af 100644 --- a/product/roundhouse/infrastructure.app/builders/VersionResolverBuilder.cs +++ b/product/roundhouse.core/infrastructure.app/builders/VersionResolverBuilder.cs @@ -1,31 +1,31 @@ -namespace roundhouse.infrastructure.app.builders -{ - using System.Collections.Generic; - using filesystem; - using resolvers; - - public class VersionResolverBuilder - { - public static VersionResolver build(FileSystemAccess file_system, ConfigurationPropertyHolder configuration_property_holder) - { - VersionResolver commandLine_version_finder = new CommandLineVersionResolver(configuration_property_holder.Version); - - if (commandLine_version_finder.meets_criteria()) - { - return commandLine_version_finder; - } - else - { - VersionResolver xml_version_finder = new XmlFileVersionResolver(file_system, configuration_property_holder.VersionXPath, configuration_property_holder.VersionFile); - VersionResolver dll_version_finder = new DllFileVersionResolver(file_system, configuration_property_holder.VersionFile); - VersionResolver text_version_finder = new TextVersionResolver(file_system, configuration_property_holder.VersionFile); - VersionResolver script_number_version_finder = new ScriptfileVersionResolver(file_system, configuration_property_holder); - VersionResolver json_version_finder = new JsonVersionResolver(file_system, configuration_property_holder.VersionFile); - - IEnumerable resolvers = new List { xml_version_finder, dll_version_finder, text_version_finder, script_number_version_finder, json_version_finder }; - - return new ComplexVersionResolver(resolvers); - } - } - } +namespace roundhouse.infrastructure.app.builders +{ + using System.Collections.Generic; + using filesystem; + using resolvers; + + public static class VersionResolverBuilder + { + public static VersionResolver build(FileSystemAccess file_system, ConfigurationPropertyHolder configuration_property_holder) + { + VersionResolver commandLine_version_finder = new CommandLineVersionResolver(configuration_property_holder.Version); + + if (commandLine_version_finder.meets_criteria()) + { + return commandLine_version_finder; + } + else + { + VersionResolver xml_version_finder = new XmlFileVersionResolver(file_system, configuration_property_holder.VersionXPath, configuration_property_holder.VersionFile); + VersionResolver dll_version_finder = new DllFileVersionResolver(file_system, configuration_property_holder.VersionFile); + VersionResolver text_version_finder = new TextVersionResolver(file_system, configuration_property_holder.VersionFile); + VersionResolver script_number_version_finder = new ScriptfileVersionResolver(file_system, configuration_property_holder); + VersionResolver json_version_finder = new JsonVersionResolver(file_system, configuration_property_holder.VersionFile); + + IEnumerable resolvers = new List { xml_version_finder, dll_version_finder, text_version_finder, script_number_version_finder, json_version_finder }; + + return new ComplexVersionResolver(resolvers); + } + } + } } \ No newline at end of file diff --git a/product/roundhouse/infrastructure.app/logging/Log4NetAppender.cs b/product/roundhouse.core/infrastructure.app/logging/Log4NetAppender.cs similarity index 93% rename from product/roundhouse/infrastructure.app/logging/Log4NetAppender.cs rename to product/roundhouse.core/infrastructure.app/logging/Log4NetAppender.cs index 5290a701..a1326e02 100644 --- a/product/roundhouse/infrastructure.app/logging/Log4NetAppender.cs +++ b/product/roundhouse.core/infrastructure.app/logging/Log4NetAppender.cs @@ -1,102 +1,102 @@ -using System; -using System.IO; -using System.Reflection; -using log4net; -using log4net.Appender; -using log4net.Config; -using log4net.Layout; -using log4net.Repository; - -namespace roundhouse.infrastructure.app.logging -{ - public class Log4NetAppender - { - private static readonly ILog the_logger = LogManager.GetLogger(typeof(Log4NetAppender)); - private static bool used_merged = true; - - public static void configure() - { - string assembly_name = ApplicationParameters.log4net_configuration_assembly; - Stream xml_config_stream; - - try - { - xml_config_stream = Assembly.Load(ApplicationParameters.get_merged_assembly_name()).GetManifestResourceStream(ApplicationParameters.log4net_configuration_resource); - - if (xml_config_stream == null) - { - throw new NullReferenceException("Failed to load xml configuration for log4net, consider that assemblies was not merged"); - } - } - catch (Exception) - { - used_merged = false; - xml_config_stream = Assembly.Load(assembly_name).GetManifestResourceStream(ApplicationParameters.log4net_configuration_resource); - } - - XmlConfigurator.Configure(get_logger_repository(), xml_config_stream); - - the_logger.DebugFormat("Configured {0} from assembly {1}", ApplicationParameters.log4net_configuration_resource, used_merged ? ApplicationParameters.get_merged_assembly_name() : assembly_name); - } - - private static ILoggerRepository get_logger_repository() - { - return LogManager.GetRepository(typeof(Log4NetAppender).Assembly); - } - - public static void configure_without_console() - { - string assembly_name = ApplicationParameters.log4net_configuration_assembly; - Stream xml_config_stream; - - try - { - xml_config_stream = Assembly.Load(ApplicationParameters.get_merged_assembly_name()).GetManifestResourceStream(ApplicationParameters.log4net_configuration_resource_no_console); - - } - catch (Exception) - { - used_merged = false; - xml_config_stream = Assembly.Load(assembly_name).GetManifestResourceStream(ApplicationParameters.log4net_configuration_resource_no_console); - } - - XmlConfigurator.Configure(get_logger_repository(), xml_config_stream); - - the_logger.DebugFormat("Configured {0} from assembly {1}", ApplicationParameters.log4net_configuration_resource_no_console, used_merged ? ApplicationParameters.get_merged_assembly_name() : assembly_name); - } - - private static bool already_configured_file_appender = false; - - public static void set_file_appender(string output_directory) - { - if (!already_configured_file_appender) - { - already_configured_file_appender = true; - - var layout = new PatternLayout - { - ConversionPattern = "%date [%-5level] - %message%newline" - }; - layout.ActivateOptions(); - - var rollingFileAppender = new RollingFileAppender - { - Name = "roundhouse.changes.log.appender", - File = Path.Combine(Path.GetFullPath(output_directory), "roundhouse.changes.log"), - Layout = layout, - AppendToFile = false - }; - rollingFileAppender.ActivateOptions(); - - var log = LogManager.GetLogger(get_logger_repository().Name, "roundhouse"); - var logger = (log4net.Repository.Hierarchy.Logger)log.Logger; - logger.AddAppender(rollingFileAppender); - - var nhLog = LogManager.GetLogger(get_logger_repository().Name, "NHibernate.SQL"); - var nhLogger = (log4net.Repository.Hierarchy.Logger)nhLog.Logger; - nhLogger.AddAppender(rollingFileAppender); - } - } - - } +using System; +using System.IO; +using System.Reflection; +using log4net; +using log4net.Appender; +using log4net.Config; +using log4net.Layout; +using log4net.Repository; + +namespace roundhouse.infrastructure.app.logging +{ + public static class Log4NetAppender + { + private static readonly ILog the_logger = LogManager.GetLogger(typeof(Log4NetAppender)); + private static bool used_merged = true; + + public static void configure() + { + string assembly_name = ApplicationParameters.log4net_configuration_assembly; + Stream xml_config_stream; + + try + { + xml_config_stream = Assembly.Load(ApplicationParameters.get_merged_assembly_name()).GetManifestResourceStream(ApplicationParameters.log4net_configuration_resource); + + if (xml_config_stream == null) + { + throw new Exception("Failed to load xml configuration for log4net, consider that assemblies was not merged"); + } + } + catch (Exception) + { + used_merged = false; + xml_config_stream = Assembly.Load(assembly_name).GetManifestResourceStream(ApplicationParameters.log4net_configuration_resource); + } + + XmlConfigurator.Configure(get_logger_repository(), xml_config_stream); + + the_logger.DebugFormat("Configured {0} from assembly {1}", ApplicationParameters.log4net_configuration_resource, used_merged ? ApplicationParameters.get_merged_assembly_name() : assembly_name); + } + + private static ILoggerRepository get_logger_repository() + { + return LogManager.GetRepository(typeof(Log4NetAppender).Assembly); + } + + public static void configure_without_console() + { + string assembly_name = ApplicationParameters.log4net_configuration_assembly; + Stream xml_config_stream; + + try + { + xml_config_stream = Assembly.Load(ApplicationParameters.get_merged_assembly_name()).GetManifestResourceStream(ApplicationParameters.log4net_configuration_resource_no_console); + + } + catch (Exception) + { + used_merged = false; + xml_config_stream = Assembly.Load(assembly_name).GetManifestResourceStream(ApplicationParameters.log4net_configuration_resource_no_console); + } + + XmlConfigurator.Configure(get_logger_repository(), xml_config_stream); + + the_logger.DebugFormat("Configured {0} from assembly {1}", ApplicationParameters.log4net_configuration_resource_no_console, used_merged ? ApplicationParameters.get_merged_assembly_name() : assembly_name); + } + + private static bool already_configured_file_appender = false; + + public static void set_file_appender(string output_directory) + { + if (!already_configured_file_appender) + { + already_configured_file_appender = true; + + var layout = new PatternLayout + { + ConversionPattern = "%date [%-5level] - %message%newline" + }; + layout.ActivateOptions(); + + var rollingFileAppender = new RollingFileAppender + { + Name = "roundhouse.changes.log.appender", + File = Path.Combine(Path.GetFullPath(output_directory), "roundhouse.changes.log"), + Layout = layout, + AppendToFile = false + }; + rollingFileAppender.ActivateOptions(); + + var log = LogManager.GetLogger(get_logger_repository().Name, "roundhouse"); + var logger = (log4net.Repository.Hierarchy.Logger)log.Logger; + logger.AddAppender(rollingFileAppender); + + var nhLog = LogManager.GetLogger(get_logger_repository().Name, "NHibernate.SQL"); + var nhLogger = (log4net.Repository.Hierarchy.Logger)nhLog.Logger; + nhLogger.AddAppender(rollingFileAppender); + } + } + + } } \ No newline at end of file diff --git a/product/roundhouse/infrastructure.app/logging/Log4NetDll.cs b/product/roundhouse.core/infrastructure.app/logging/Log4NetDll.cs similarity index 86% rename from product/roundhouse/infrastructure.app/logging/Log4NetDll.cs rename to product/roundhouse.core/infrastructure.app/logging/Log4NetDll.cs index a33b4118..425d2d3c 100644 --- a/product/roundhouse/infrastructure.app/logging/Log4NetDll.cs +++ b/product/roundhouse.core/infrastructure.app/logging/Log4NetDll.cs @@ -1,39 +1,42 @@ -namespace roundhouse.infrastructure.app.logging -{ - using System; - using System.IO; - using loaders; - - public class Log4NetDll - { - public static bool is_resolved() - { - if (ApplicationParameters.get_merged_assembly_name() == ApplicationParameters.default_merged_assembly_name) return true; - - string log4net_file = "log4net.dll"; - bool log4net_dll_exists = false; - - if (File.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, log4net_file))) - { - log4net_dll_exists = true; - } - - if (!log4net_dll_exists) - { - //try to resolve it anywhere - try - { - DefaultAssemblyLoader.load_assembly(log4net_file); - log4net_dll_exists = true; - } - catch (Exception) - { - //the file doesn't exist - } - } - - return log4net_dll_exists; - } - - } +namespace roundhouse.infrastructure.app.logging +{ + using System; + using System.IO; + using loaders; + + public static class Log4NetDll + { + public static bool is_resolved() + { + if (ApplicationParameters.get_merged_assembly_name() == ApplicationParameters.default_merged_assembly_name) + { + return true; + } + + string log4net_file = "log4net.dll"; + bool log4net_dll_exists = false; + + if (File.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, log4net_file))) + { + log4net_dll_exists = true; + } + + if (!log4net_dll_exists) + { + //try to resolve it anywhere + try + { + DefaultAssemblyLoader.load_assembly(log4net_file); + log4net_dll_exists = true; + } + catch (Exception) + { + //the file doesn't exist + } + } + + return log4net_dll_exists; + } + + } } \ No newline at end of file diff --git a/product/roundhouse/infrastructure.app/logging/log4net.config.no.console.xml b/product/roundhouse.core/infrastructure.app/logging/log4net.config.no.console.xml similarity index 94% rename from product/roundhouse/infrastructure.app/logging/log4net.config.no.console.xml rename to product/roundhouse.core/infrastructure.app/logging/log4net.config.no.console.xml index 07b35dae..75623789 100644 --- a/product/roundhouse/infrastructure.app/logging/log4net.config.no.console.xml +++ b/product/roundhouse.core/infrastructure.app/logging/log4net.config.no.console.xml @@ -1,21 +1,21 @@ - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/product/roundhouse/infrastructure.app/logging/log4net.config.xml b/product/roundhouse.core/infrastructure.app/logging/log4net.config.xml similarity index 96% rename from product/roundhouse/infrastructure.app/logging/log4net.config.xml rename to product/roundhouse.core/infrastructure.app/logging/log4net.config.xml index 1c53d496..c20f936d 100644 --- a/product/roundhouse/infrastructure.app/logging/log4net.config.xml +++ b/product/roundhouse.core/infrastructure.app/logging/log4net.config.xml @@ -1,49 +1,49 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/product/roundhouse/infrastructure.app/persistence/NHibernateMigrationSessionFactory.cs b/product/roundhouse.core/infrastructure.app/persistence/NHibernateMigrationSessionFactory.cs similarity index 97% rename from product/roundhouse/infrastructure.app/persistence/NHibernateMigrationSessionFactory.cs rename to product/roundhouse.core/infrastructure.app/persistence/NHibernateMigrationSessionFactory.cs index 6f4ff0da..e15cc575 100644 --- a/product/roundhouse/infrastructure.app/persistence/NHibernateMigrationSessionFactory.cs +++ b/product/roundhouse.core/infrastructure.app/persistence/NHibernateMigrationSessionFactory.cs @@ -1,41 +1,41 @@ -namespace roundhouse.infrastructure.app.persistence -{ - using System; - using FluentNHibernate.Cfg; - using FluentNHibernate.Cfg.Db; - using log4net; - using NHibernate; - using NHibernate.Cfg; - - public class NHibernateMigrationSessionFactory - { - private static readonly ILog logger = LogManager.GetLogger(typeof(NHibernateMigrationSessionFactory)); - - public ISessionFactory build_session_factory(string db_server, string db_name) - { - return build_session_factory(db_server, db_name, no_operation); - } - - public static ISessionFactory build_session_factory(string db_server, string db_name, Action additional_function) - { - logger.Debug("Building Session Factory"); - //todo: will have to figure out how to make the IPC passable - return Fluently.Configure() - .Database(MsSqlConfiguration.MsSql2005 - .ConnectionString(c => c.Server(db_server).Database(db_name).TrustedConnection()) - ) - .Mappings(m => - { - m.FluentMappings.AddFromAssemblyOf() - .Conventions.AddFromAssemblyOf(); - }) - .ExposeConfiguration(additional_function) - .BuildSessionFactory(); - - } - - private static void no_operation(Configuration cfg) - { - } - } +namespace roundhouse.infrastructure.app.persistence +{ + using System; + using FluentNHibernate.Cfg; + using FluentNHibernate.Cfg.Db; + using log4net; + using NHibernate; + using NHibernate.Cfg; + + public class NHibernateMigrationSessionFactory + { + private static readonly ILog logger = LogManager.GetLogger(typeof(NHibernateMigrationSessionFactory)); + + public ISessionFactory build_session_factory(string db_server, string db_name) + { + return build_session_factory(db_server, db_name, no_operation); + } + + public static ISessionFactory build_session_factory(string db_server, string db_name, Action additional_function) + { + logger.Debug("Building Session Factory"); + //todo: will have to figure out how to make the IPC passable + return Fluently.Configure() + .Database(MsSqlConfiguration.MsSql2005 + .ConnectionString(c => c.Server(db_server).Database(db_name).TrustedConnection()) + ) + .Mappings(m => + { + m.FluentMappings.AddFromAssemblyOf() + .Conventions.AddFromAssemblyOf(); + }) + .ExposeConfiguration(additional_function) + .BuildSessionFactory(); + + } + + private static void no_operation(Configuration cfg) + { + } + } } \ No newline at end of file diff --git a/product/roundhouse/infrastructure.app/tokens/TokenReplacer.cs b/product/roundhouse.core/infrastructure.app/tokens/TokenReplacer.cs similarity index 96% rename from product/roundhouse/infrastructure.app/tokens/TokenReplacer.cs rename to product/roundhouse.core/infrastructure.app/tokens/TokenReplacer.cs index ed51882e..8b208ce8 100644 --- a/product/roundhouse/infrastructure.app/tokens/TokenReplacer.cs +++ b/product/roundhouse.core/infrastructure.app/tokens/TokenReplacer.cs @@ -1,31 +1,31 @@ -namespace roundhouse.infrastructure.app.tokens -{ - using System.Text.RegularExpressions; - - public class TokenReplacer - { - public static string replace_tokens(ConfigurationPropertyHolder configuration, string text_to_replace) - { - if (string.IsNullOrEmpty(text_to_replace)) return string.Empty; - - var dictionary = configuration.to_token_dictionary(); - Regex regex = new Regex("{{(?\\w+)}}"); - - string output = regex.Replace(text_to_replace, m => - { - string key = ""; - - key = m.Groups["key"].Value; - if (!dictionary.ContainsKey(key)) - { - return "{{" + key + "}}"; - } - - var value = dictionary[key]; - return value; - }); - - return output; - } - } +namespace roundhouse.infrastructure.app.tokens +{ + using System.Text.RegularExpressions; + + public class TokenReplacer + { + public static string replace_tokens(ConfigurationPropertyHolder configuration, string text_to_replace) + { + if (string.IsNullOrEmpty(text_to_replace)) return string.Empty; + + var dictionary = configuration.to_token_dictionary(); + Regex regex = new Regex("{{(?\\w+)}}"); + + string output = regex.Replace(text_to_replace, m => + { + string key = ""; + + key = m.Groups["key"].Value; + if (!dictionary.ContainsKey(key)) + { + return "{{" + key + "}}"; + } + + var value = dictionary[key]; + return value; + }); + + return output; + } + } } \ No newline at end of file diff --git a/product/roundhouse/infrastructure/ApplicationParameters.cs b/product/roundhouse.core/infrastructure/ApplicationParameters.cs similarity index 94% rename from product/roundhouse/infrastructure/ApplicationParameters.cs rename to product/roundhouse.core/infrastructure/ApplicationParameters.cs index d1a41503..8ed2188d 100644 --- a/product/roundhouse/infrastructure/ApplicationParameters.cs +++ b/product/roundhouse.core/infrastructure/ApplicationParameters.cs @@ -1,80 +1,80 @@ -namespace roundhouse.infrastructure -{ - using System; - using System.IO; - using System.Reflection; - using extensions; - using logging; - - public static class ApplicationParameters - { - public static string name = "RoundhousE"; - // defaults - public static readonly string default_alter_database_folder_name = "alterDatabase"; - public static readonly string default_run_after_create_database_folder_name = "runAfterCreateDatabase"; - public static readonly string default_run_before_up_folder_name = "runBeforeUp"; - public static readonly string default_up_folder_name = "up"; - public static readonly string default_down_folder_name = "down"; - public static readonly string default_run_first_after_up_folder_name = "runFirstAfterUp"; - public static readonly string default_functions_folder_name = "functions"; - public static readonly string default_views_folder_name = "views"; - public static readonly string default_sprocs_folder_name = "sprocs"; - public static readonly string default_triggers_folder_name = "triggers"; - public static readonly string default_indexes_folder_name = "indexes"; - public static readonly string default_runAfterOtherAnyTime_folder_name = "runAfterOtherAnyTimeScripts"; - public static readonly string default_permissions_folder_name = "permissions"; - public static readonly string default_before_migration_folder_name = "beforeMigration"; - public static readonly string default_after_migration_folder_name = "afterMigration"; - public static readonly string default_environment_name = "LOCAL"; - public static readonly string default_roundhouse_schema_name = "RoundhousE"; - public static readonly string default_version_table_name = "Version"; - public static readonly string default_scripts_run_table_name = "ScriptsRun"; - public static readonly string default_scripts_run_errors_table_name = "ScriptsRunErrors"; - public static readonly string default_version_file = @"_BuildInfo.xml"; - public static readonly string default_version_x_path = @"//buildInfo/version"; - public static readonly string default_files_directory = @"."; - public static readonly string default_server_name = "(local)"; - public static readonly string default_output_path = Path.Combine(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "ChuckNorris"), name); - public static readonly string default_database_type = "roundhouse.databases.sqlserver.SqlServerDatabase, roundhouse.databases.sqlserver"; - public static readonly string logging_file = @"C:\Temp\RoundhousE\roundhouse.changes.log"; - public static readonly string log4net_configuration_assembly = @"roundhouse"; - public static readonly string log4net_configuration_resource = @"roundhouse.infrastructure.app.logging.log4net.config.xml"; - public static readonly string log4net_configuration_resource_no_console = @"roundhouse.infrastructure.app.logging.log4net.config.no.console.xml"; - public static readonly string sqlite_dll_resource = @"roundhouse.databases.sqlite.assemblyresource.System.Data.SQLite.dll"; - public static readonly int default_command_timeout = 60; - public static readonly int default_admin_command_timeout = 300; - public static readonly int default_restore_timeout = 900; - public static readonly bool default_disable_output = false; - - public static string get_merged_assembly_name() - { - string merged_assembly_name = "rh"; - Log.bound_to(typeof(ApplicationParameters)).log_a_debug_event_containing("The executing assembly is \"{0}\"", Assembly.GetExecutingAssembly().Location); - - if (Assembly.GetExecutingAssembly().Location.to_lower().Contains("roundhouse.dll")) merged_assembly_name = "roundhouse"; - - return merged_assembly_name; - } - - public static bool is_type_merged_in_this_assembly(string type_to_check) - { - bool is_merged = true; - var assembly = Assembly.GetExecutingAssembly(); - - var type = assembly.GetType(type_to_check); - - if (type == null) is_merged = false; - - return is_merged; - } - - public class CurrentMappings - { - public static string roundhouse_schema_name = default_roundhouse_schema_name; - public static string version_table_name = default_version_table_name; - public static string scripts_run_table_name = default_scripts_run_table_name; - public static string scripts_run_errors_table_name = default_scripts_run_errors_table_name; - public static string database_type = default_database_type; - } - } +namespace roundhouse.infrastructure +{ + using System; + using System.IO; + using System.Reflection; + using extensions; + using logging; + + public static class ApplicationParameters + { + public static string name = "RoundhousE"; + // defaults + public static readonly string default_alter_database_folder_name = "alterDatabase"; + public static readonly string default_run_after_create_database_folder_name = "runAfterCreateDatabase"; + public static readonly string default_run_before_up_folder_name = "runBeforeUp"; + public static readonly string default_up_folder_name = "up"; + public static readonly string default_down_folder_name = "down"; + public static readonly string default_run_first_after_up_folder_name = "runFirstAfterUp"; + public static readonly string default_functions_folder_name = "functions"; + public static readonly string default_views_folder_name = "views"; + public static readonly string default_sprocs_folder_name = "sprocs"; + public static readonly string default_triggers_folder_name = "triggers"; + public static readonly string default_indexes_folder_name = "indexes"; + public static readonly string default_runAfterOtherAnyTime_folder_name = "runAfterOtherAnyTimeScripts"; + public static readonly string default_permissions_folder_name = "permissions"; + public static readonly string default_before_migration_folder_name = "beforeMigration"; + public static readonly string default_after_migration_folder_name = "afterMigration"; + public static readonly string default_environment_name = "LOCAL"; + public static readonly string default_roundhouse_schema_name = "RoundhousE"; + public static readonly string default_version_table_name = "Version"; + public static readonly string default_scripts_run_table_name = "ScriptsRun"; + public static readonly string default_scripts_run_errors_table_name = "ScriptsRunErrors"; + public static readonly string default_version_file = @"_BuildInfo.xml"; + public static readonly string default_version_x_path = @"//buildInfo/version"; + public static readonly string default_files_directory = @"."; + public static readonly string default_server_name = "(local)"; + public static readonly string default_output_path = Path.Combine(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "ChuckNorris"), name); + public static readonly string default_database_type = "roundhouse.databases.sqlserver.SqlServerDatabase, roundhouse.databases.sqlserver"; + public static readonly string logging_file = @"C:\Temp\RoundhousE\roundhouse.changes.log"; + public static readonly string log4net_configuration_assembly = @"roundhouse.core"; + public static readonly string log4net_configuration_resource = @"roundhouse.core.infrastructure.app.logging.log4net.config.xml"; + public static readonly string log4net_configuration_resource_no_console = @"roundhouse.core.infrastructure.app.logging.log4net.config.no.console.xml"; + public static readonly string sqlite_dll_resource = @"roundhouse.databases.sqlite.assemblyresource.System.Data.SQLite.dll"; + public static readonly int default_command_timeout = 60; + public static readonly int default_admin_command_timeout = 300; + public static readonly int default_restore_timeout = 900; + public static readonly bool default_disable_output = false; + + public static string get_merged_assembly_name() + { + string merged_assembly_name = "rh"; + Log.bound_to(typeof(ApplicationParameters)).log_a_debug_event_containing("The executing assembly is \"{0}\"", Assembly.GetExecutingAssembly().Location); + + if (Assembly.GetExecutingAssembly().Location.to_lower().Contains("roundhouse.dll")) merged_assembly_name = "roundhouse"; + + return merged_assembly_name; + } + + public static bool is_type_merged_in_this_assembly(string type_to_check) + { + bool is_merged = true; + var assembly = Assembly.GetExecutingAssembly(); + + var type = assembly.GetType(type_to_check); + + if (type == null) is_merged = false; + + return is_merged; + } + + public class CurrentMappings + { + public static string roundhouse_schema_name = default_roundhouse_schema_name; + public static string version_table_name = default_version_table_name; + public static string scripts_run_table_name = default_scripts_run_table_name; + public static string scripts_run_errors_table_name = default_scripts_run_errors_table_name; + public static string database_type = default_database_type; + } + } } \ No newline at end of file diff --git a/product/roundhouse.core/infrastructure/ConfigurationException.cs b/product/roundhouse.core/infrastructure/ConfigurationException.cs new file mode 100644 index 00000000..422e08cd --- /dev/null +++ b/product/roundhouse.core/infrastructure/ConfigurationException.cs @@ -0,0 +1,11 @@ +using System; + +namespace roundhouse.infrastructure +{ + public class ConfigurationException: Exception + { + public ConfigurationException(string message) : base(message) + { + } + } +} \ No newline at end of file diff --git a/product/roundhouse/infrastructure/VersionInformation.cs b/product/roundhouse.core/infrastructure/VersionInformation.cs similarity index 96% rename from product/roundhouse/infrastructure/VersionInformation.cs rename to product/roundhouse.core/infrastructure/VersionInformation.cs index 798133bb..66ab653b 100644 --- a/product/roundhouse/infrastructure/VersionInformation.cs +++ b/product/roundhouse.core/infrastructure/VersionInformation.cs @@ -1,22 +1,22 @@ -using System.Diagnostics; -using System.Reflection; - -namespace roundhouse.infrastructure -{ - public class VersionInformation - { - public static string get_current_assembly_version() - { - string version = string.Empty; - Assembly executing_assembly = Assembly.GetCallingAssembly(); - string location = executing_assembly != null ? executing_assembly.Location : string.Empty; - - if (!string.IsNullOrEmpty(location)) - { - version = FileVersionInfo.GetVersionInfo(location).FileVersion; - } - - return version; - } - } +using System.Diagnostics; +using System.Reflection; + +namespace roundhouse.infrastructure +{ + public class VersionInformation + { + public static string get_current_assembly_version() + { + string version = string.Empty; + Assembly executing_assembly = Assembly.GetCallingAssembly(); + string location = executing_assembly != null ? executing_assembly.Location : string.Empty; + + if (!string.IsNullOrEmpty(location)) + { + version = FileVersionInfo.GetVersionInfo(location).FileVersion; + } + + return version; + } + } } \ No newline at end of file diff --git a/product/roundhouse/infrastructure/commandline.options/Options.cs b/product/roundhouse.core/infrastructure/commandline.options/Options.cs similarity index 100% rename from product/roundhouse/infrastructure/commandline.options/Options.cs rename to product/roundhouse.core/infrastructure/commandline.options/Options.cs diff --git a/product/roundhouse/infrastructure/containers/Container.cs b/product/roundhouse.core/infrastructure/containers/Container.cs similarity index 96% rename from product/roundhouse/infrastructure/containers/Container.cs rename to product/roundhouse.core/infrastructure/containers/Container.cs index 91fb5931..2be66b4b 100644 --- a/product/roundhouse/infrastructure/containers/Container.cs +++ b/product/roundhouse.core/infrastructure/containers/Container.cs @@ -1,20 +1,20 @@ -namespace roundhouse.infrastructure.containers -{ - using System; - - public static class Container - { - private static InversionContainer the_container; - - public static void initialize_with(InversionContainer container) - { - the_container = container; - } - - public static TypeToGet get_an_instance_of() - { - if (the_container == null) throw new NullReferenceException("The container has not been initialized yet, can't return anything."); - return the_container.Resolve(); - } - } +namespace roundhouse.infrastructure.containers +{ + using System; + + public static class Container + { + private static InversionContainer the_container; + + public static void initialize_with(InversionContainer container) + { + the_container = container; + } + + public static TypeToGet get_an_instance_of() + { + if (the_container == null) throw new NullReferenceException("The container has not been initialized yet, can't return anything."); + return the_container.Resolve(); + } + } } \ No newline at end of file diff --git a/product/roundhouse/infrastructure/containers/InversionContainer.cs b/product/roundhouse.core/infrastructure/containers/InversionContainer.cs similarity index 96% rename from product/roundhouse/infrastructure/containers/InversionContainer.cs rename to product/roundhouse.core/infrastructure/containers/InversionContainer.cs index 9efe24ab..f4ba4c56 100644 --- a/product/roundhouse/infrastructure/containers/InversionContainer.cs +++ b/product/roundhouse.core/infrastructure/containers/InversionContainer.cs @@ -1,7 +1,7 @@ -namespace roundhouse.infrastructure.containers -{ - public interface InversionContainer - { - TypeToReturn Resolve(); - } +namespace roundhouse.infrastructure.containers +{ + public interface InversionContainer + { + TypeToReturn Resolve(); + } } \ No newline at end of file diff --git a/product/roundhouse/infrastructure/containers/custom/HardcodedContainer.cs b/product/roundhouse.core/infrastructure/containers/custom/HardcodedContainer.cs similarity index 97% rename from product/roundhouse/infrastructure/containers/custom/HardcodedContainer.cs rename to product/roundhouse.core/infrastructure/containers/custom/HardcodedContainer.cs index 67e29e2a..49ddfd64 100644 --- a/product/roundhouse/infrastructure/containers/custom/HardcodedContainer.cs +++ b/product/roundhouse.core/infrastructure/containers/custom/HardcodedContainer.cs @@ -1,32 +1,32 @@ -using System; -using System.Collections.Generic; - -namespace roundhouse.infrastructure.containers.custom -{ - /// - /// This is just a silly class that performs a simple type to implementation mapping. - /// The ultimate goal must be to get rid of the "Service Locator" pattern altogether, - /// and rather _inject_ the dependencies in the classes that need them, instead of asking the global - /// static class to resolve a dependency. - /// - /// However, in the mean time, this class removes the dependency on StructureMap, which has issues - /// runtime when running on .net core (apparently). - /// - /// - public sealed class HardcodedContainer : InversionContainer - { - private static readonly IDictionary registrations = new Dictionary(); - - public static void Register(TDependency implementation) - { - registrations[typeof(TDependency)] = implementation; - } - - TypeToReturn InversionContainer.Resolve() - { - return (TypeToReturn) registrations[typeof(TypeToReturn)]; - } - - public static HardcodedContainer Instance { get; } = new HardcodedContainer(); - } +using System; +using System.Collections.Generic; + +namespace roundhouse.infrastructure.containers.custom +{ + /// + /// This is just a silly class that performs a simple type to implementation mapping. + /// The ultimate goal must be to get rid of the "Service Locator" pattern altogether, + /// and rather _inject_ the dependencies in the classes that need them, instead of asking the global + /// static class to resolve a dependency. + /// + /// However, in the mean time, this class removes the dependency on StructureMap, which has issues + /// runtime when running on .net core (apparently). + /// + /// + public sealed class HardcodedContainer : InversionContainer + { + private static readonly IDictionary registrations = new Dictionary(); + + public static void Register(TDependency implementation) + { + registrations[typeof(TDependency)] = implementation; + } + + TypeToReturn InversionContainer.Resolve() + { + return (TypeToReturn) registrations[typeof(TypeToReturn)]; + } + + public static HardcodedContainer Instance { get; } = new HardcodedContainer(); + } } \ No newline at end of file diff --git a/product/roundhouse/infrastructure/extensions/Iteration.cs b/product/roundhouse.core/infrastructure/extensions/Iteration.cs similarity index 96% rename from product/roundhouse/infrastructure/extensions/Iteration.cs rename to product/roundhouse.core/infrastructure/extensions/Iteration.cs index caefc040..e11e610d 100644 --- a/product/roundhouse/infrastructure/extensions/Iteration.cs +++ b/product/roundhouse.core/infrastructure/extensions/Iteration.cs @@ -1,24 +1,24 @@ -namespace roundhouse.infrastructure.extensions -{ - using System; - using System.Collections.Generic; - using System.Linq; - - public static class Iteration - { - public static IEnumerable one_at_a_time(this IEnumerable items) - { - return items.Select(item => item); - } - - public static void each(this IEnumerable items, Action action) - { - foreach (var item in items) action(item); - } - - public static IEnumerable to(this int start, int end) - { - for (var i = start; i <= end; i++) yield return i; - } - } +namespace roundhouse.infrastructure.extensions +{ + using System; + using System.Collections.Generic; + using System.Linq; + + public static class Iteration + { + public static IEnumerable one_at_a_time(this IEnumerable items) + { + return items.Select(item => item); + } + + public static void each(this IEnumerable items, Action action) + { + foreach (var item in items) action(item); + } + + public static IEnumerable to(this int start, int end) + { + for (var i = start; i <= end; i++) yield return i; + } + } } \ No newline at end of file diff --git a/product/roundhouse/infrastructure/extensions/ObjectExtensions.cs b/product/roundhouse.core/infrastructure/extensions/ObjectExtensions.cs similarity index 96% rename from product/roundhouse/infrastructure/extensions/ObjectExtensions.cs rename to product/roundhouse.core/infrastructure/extensions/ObjectExtensions.cs index 05f0948e..03ad44e3 100644 --- a/product/roundhouse/infrastructure/extensions/ObjectExtensions.cs +++ b/product/roundhouse.core/infrastructure/extensions/ObjectExtensions.cs @@ -1,30 +1,30 @@ -namespace roundhouse.infrastructure.extensions -{ - using System.Text; - using System.Data.SqlClient; - - public static class ObjectExtensions { - - public static string to_string(this object input) - { - if (input == null) return string.Empty; - - var sqlException = input as SqlException; - if (sqlException != null) - { - var msg = new StringBuilder(sqlException.ToString()) - .AppendLine() - .AppendLine("SqlErrors:"); - - foreach (SqlError error in sqlException.Errors) - { - msg.AppendFormat("Error Number: {0}, Message: {1}", error.Number, error.Message).AppendLine(); - } - - return msg.ToString(); - } - - return input.ToString(); - } - } +namespace roundhouse.infrastructure.extensions +{ + using System.Text; + using System.Data.SqlClient; + + public static class ObjectExtensions { + + public static string to_string(this object input) + { + if (input == null) return string.Empty; + + var sqlException = input as SqlException; + if (sqlException != null) + { + var msg = new StringBuilder(sqlException.ToString()) + .AppendLine() + .AppendLine("SqlErrors:"); + + foreach (SqlError error in sqlException.Errors) + { + msg.AppendFormat("Error Number: {0}, Message: {1}", error.Number, error.Message).AppendLine(); + } + + return msg.ToString(); + } + + return input.ToString(); + } + } } \ No newline at end of file diff --git a/product/roundhouse/infrastructure/extensions/StringExtensions.cs b/product/roundhouse.core/infrastructure/extensions/StringExtensions.cs similarity index 96% rename from product/roundhouse/infrastructure/extensions/StringExtensions.cs rename to product/roundhouse.core/infrastructure/extensions/StringExtensions.cs index 61ec3dc0..8c7e18bf 100644 --- a/product/roundhouse/infrastructure/extensions/StringExtensions.cs +++ b/product/roundhouse.core/infrastructure/extensions/StringExtensions.cs @@ -1,24 +1,24 @@ -namespace roundhouse.infrastructure.extensions -{ - public static class StringExtensions - { - public static string format_using(this string format, params object[] args) - { - return string.Format(format, args); - } - - public static string to_lower(this string input) - { - if (string.IsNullOrEmpty(input)) return string.Empty; - - return input.ToLower(); - } - - public static string to_upper(this string input) - { - if (string.IsNullOrEmpty(input)) return string.Empty; - - return input.ToUpper(); - } - } +namespace roundhouse.infrastructure.extensions +{ + public static class StringExtensions + { + public static string format_using(this string format, params object[] args) + { + return string.Format(format, args); + } + + public static string to_lower(this string input) + { + if (string.IsNullOrEmpty(input)) return string.Empty; + + return input.ToLower(); + } + + public static string to_upper(this string input) + { + if (string.IsNullOrEmpty(input)) return string.Empty; + + return input.ToUpper(); + } + } } \ No newline at end of file diff --git a/product/roundhouse/infrastructure/extensions/TypeCasting.cs b/product/roundhouse.core/infrastructure/extensions/TypeCasting.cs similarity index 95% rename from product/roundhouse/infrastructure/extensions/TypeCasting.cs rename to product/roundhouse.core/infrastructure/extensions/TypeCasting.cs index e812d5c4..49a19583 100644 --- a/product/roundhouse/infrastructure/extensions/TypeCasting.cs +++ b/product/roundhouse.core/infrastructure/extensions/TypeCasting.cs @@ -1,23 +1,23 @@ -namespace roundhouse.infrastructure.extensions -{ - public static class TypeCasting - { - public static T downcast_to(this object item) - { - return (T) item; - } - - public static bool is_not_a(this object item) - { - try - { - var typeToCastTo = (T) item; - return false; - } - catch - { - return true; - } - } - } +namespace roundhouse.infrastructure.extensions +{ + public static class TypeCasting + { + public static T downcast_to(this object item) + { + return (T) item; + } + + public static bool is_not_a(this object item) + { + try + { + var typeToCastTo = (T) item; + return false; + } + catch + { + return true; + } + } + } } \ No newline at end of file diff --git a/product/roundhouse/infrastructure/extensions/TypeExtensions.cs b/product/roundhouse.core/infrastructure/extensions/TypeExtensions.cs similarity index 96% rename from product/roundhouse/infrastructure/extensions/TypeExtensions.cs rename to product/roundhouse.core/infrastructure/extensions/TypeExtensions.cs index 2ad39bb3..62df1ec9 100644 --- a/product/roundhouse/infrastructure/extensions/TypeExtensions.cs +++ b/product/roundhouse.core/infrastructure/extensions/TypeExtensions.cs @@ -1,30 +1,30 @@ -namespace roundhouse.infrastructure.extensions -{ - using System; - using System.Linq; - using System.Reflection; - using System.Text; - - public static class TypeExtensions - { - public const string exception_message_typed_format = "<{0}>"; - - public static ConstructorInfo greediest_constructor(this Type type) - { - return type.GetConstructors() - .OrderByDescending(x => x.GetParameters().Count()) - .First(); - } - - - public static string proper_name(this Type type) - { - var message = new StringBuilder(type.Name); - if (!type.IsGenericType) return message.ToString(); - - type.GetGenericArguments().each(x => message.AppendFormat(exception_message_typed_format, x)); - - return message.ToString(); - } - } +namespace roundhouse.infrastructure.extensions +{ + using System; + using System.Linq; + using System.Reflection; + using System.Text; + + public static class TypeExtensions + { + public const string exception_message_typed_format = "<{0}>"; + + public static ConstructorInfo greediest_constructor(this Type type) + { + return type.GetConstructors() + .OrderByDescending(x => x.GetParameters().Count()) + .First(); + } + + + public static string proper_name(this Type type) + { + var message = new StringBuilder(type.Name); + if (!type.IsGenericType) return message.ToString(); + + type.GetGenericArguments().each(x => message.AppendFormat(exception_message_typed_format, x)); + + return message.ToString(); + } + } } \ No newline at end of file diff --git a/product/roundhouse/infrastructure/filesystem/DotNetFileSystemAccess.cs b/product/roundhouse.core/infrastructure/filesystem/DotNetFileSystemAccess.cs similarity index 97% rename from product/roundhouse/infrastructure/filesystem/DotNetFileSystemAccess.cs rename to product/roundhouse.core/infrastructure/filesystem/DotNetFileSystemAccess.cs index 97717329..5957aea0 100644 --- a/product/roundhouse/infrastructure/filesystem/DotNetFileSystemAccess.cs +++ b/product/roundhouse.core/infrastructure/filesystem/DotNetFileSystemAccess.cs @@ -1,438 +1,438 @@ -using System.Diagnostics; -using System.Linq; -using System.Text; - -namespace roundhouse.infrastructure.filesystem -{ - using System; - using System.IO; - using System.Runtime.InteropServices; - using logging; - using extensions; - using roundhouse.infrastructure.app; - - /// - /// All file system access code comes through here - /// - public sealed class DotNetFileSystemAccess : FileSystemAccess - { - private static readonly bool is_running_on_mono = Type.GetType("Mono.Runtime") != null; - private static readonly bool is_running_dotnet_core = RuntimeInformation.FrameworkDescription.StartsWith(".NET Core"); - - public DotNetFileSystemAccess(ConfigurationPropertyHolder configuration) - { - this.configuration = configuration; - } - - private ConfigurationPropertyHolder configuration; - private static readonly char[] InvalidPathCharacters = Path.GetInvalidPathChars().Append(':').ToArray(); - - - #region File - - /// - /// Determines if a file exists - /// - /// Path to the file - /// True if there is a file already existing, otherwise false - public bool file_exists(string file_path) - { - return File.Exists(file_path); - } - - /// - /// Creates a file - /// - /// Path to the file name - /// A file stream object for use after creating the file - public FileStream create_file(string file_path) - { - return new FileStream(file_path, FileMode.OpenOrCreate); - } - - /// - /// Opens a file - /// - /// Path to the file name - /// A file stream object for use after accessing the file - public FileStream open_file_in_read_mode_from(string file_path) - { - return File.OpenRead(file_path); - } - - /// - /// Returns the contents of a file - /// - /// Path to the file name - /// A string of the file contents - public string read_file_text(string file_path) - { - return File.ReadAllText(file_path, get_file_encoding(file_path)); - } - - /// - /// Try to use BOM to detect encoding. If BOM is not present, use default from configuration or UTF-8 if configuration is empty. - /// - /// Path to the file name - /// A best guess at the encoding of the file - /// https://stackoverflow.com/a/4522251/381282 - public Encoding get_file_encoding(string file_path) - { - Encoding enc = configuration.DefaultEncoding ?? Encoding.UTF8; - - // *** Detect byte order mark if any - byte[] buffer = new byte[5]; - int bytes_read; - using (FileStream file = new FileStream(file_path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) - { - bytes_read = file.Read(buffer, 0, 5); - } - - if (buffer[0] == 0xef && buffer[1] == 0xbb && buffer[2] == 0xbf) - enc = Encoding.UTF8; - else if (buffer[0] == 0xfe && buffer[1] == 0xff) - enc = Encoding.BigEndianUnicode; // UTF-16 BE - if (buffer[0] == 0xff && buffer[1] == 0xfe) - { - if(bytes_read >= 4 && buffer[2] == 0 && buffer[3] == 0) - enc = Encoding.UTF32; // UTF-32 LE - else - enc = Encoding.Unicode; // UTF-16 LE - } - else if (buffer[0] == 0 && buffer[1] == 0 && buffer[2] == 0xfe && buffer[3] == 0xff) - enc = Encoding.GetEncoding(12001); // UTF-32 BE - else if (buffer[0] == 0x2b && buffer[1] == 0x2f && buffer[2] == 0x76) - enc = Encoding.UTF7; - - return enc; - } - - /// - /// Copies a file from one directory to another - /// - /// Where is the file now? - /// Where would you like it to go? - /// If there is an existing file already there, would you like to delete it? - public void file_copy(string source_file_name, string destination_file_name, bool overwrite_the_existing_file) - { - Log.bound_to(this).log_a_debug_event_containing("Attempting to copy from \"{0}\" to \"{1}\".", source_file_name, destination_file_name); - File.Copy(source_file_name, destination_file_name, overwrite_the_existing_file); - } - - /// - /// Copies a file from one directory to another using PInvoke - /// - /// Where is the file now? - /// Where would you like it to go? - /// If there is an existing file already there, would you like to delete it? - public void file_copy_unsafe(string source_file_name, string destination_file_name, bool overwrite_the_existing_file) - { - Log.bound_to(this).log_a_debug_event_containing("Attempting to copy from \"{0}\" to \"{1}\".", source_file_name, destination_file_name); - //Private Declare Function apiCopyFile Lib "kernel32" Alias "CopyFileA" _ - if (is_running_on_mono || is_running_dotnet_core) - { - File.Copy(source_file_name, destination_file_name, overwrite_the_existing_file); - } - else { - int success = CopyFileA(source_file_name, destination_file_name, overwrite_the_existing_file ? 0 : 1); - } - } - - [DllImport("kernel32")] - private static extern int CopyFileA(string lpExistingFileName, string lpNewFileName, int bFailIfExists); - - - /// - /// Determines the file information given a path to an existing file - /// - /// Path to an existing file - /// FileInfo object - public FileInfo get_file_info_from(string file_path) - { - return new FileInfo(file_path); - } - - /// - /// Determines the FileVersion of the file passed in - /// - /// Relative or full path to a file - /// A string representing the FileVersion of the passed in file - public string get_file_version_from(string file_path) - { - return FileVersionInfo.GetVersionInfo(get_full_path(file_path)).FileVersion; - } - - /// - /// Determines if a file is a system file - /// - /// File to check - /// True if the file has the System attribute marked, otherwise false - public bool is_system_file(FileInfo file) - { - bool is_system_file = ((file.Attributes & FileAttributes.System) == FileAttributes.System); - if (!is_system_file) - { - //check the directory to be sure - DirectoryInfo directory_info = get_directory_info_from(file.DirectoryName); - is_system_file = ((directory_info.Attributes & FileAttributes.System) == FileAttributes.System); - Log.bound_to(this).log_a_debug_event_containing("Is directory \"{0}\" a system directory? {1}", file.DirectoryName, - is_system_file.to_string()); - } - else - { - Log.bound_to(this).log_a_debug_event_containing("File \"{0}\" is a system file.", file.FullName); - } - return is_system_file; - } - - /// - /// Determines if a file is encrypted or not - /// - /// File to check - /// True if the file has the Encrypted attribute marked, otherwise false - public bool is_encrypted_file(FileInfo file) - { - bool is_encrypted = ((file.Attributes & FileAttributes.Encrypted) == FileAttributes.Encrypted); - Log.bound_to(this).log_a_debug_event_containing("Is file \"{0}\" an encrypted file? {1}", file.FullName, is_encrypted.to_string()); - return is_encrypted; - } - - /// - /// Determines if a file has the same extension as in the list of types - /// - /// File to check - /// File types to check against, listed as file extensions - /// True if the file in question has a file type in the list - public bool file_in_file_types(string file_name, string[] file_types) - { - if (Array.IndexOf(file_types, ".*") > -1 || Array.IndexOf(file_types, get_file_extension_from(file_name).to_lower()) > -1) - { - Log.bound_to(this).log_a_debug_event_containing("File \"{0}\" is in the approved file types of \"{1}\".", file_name, - string.Join(";", file_types)); - return true; - } - - Log.bound_to(this).log_an_info_event_containing("File \"{0}\" is not in the approved file types of \"{1}\".", file_name, - string.Join(";", file_types)); - return false; - } - - /// - /// Determines the older of the file dates, Creation Date or Modified Date - /// - /// File to analyze - /// The oldest date on the file - public string get_file_date(string file_path) - { - FileInfo file = get_file_info_from(file_path); - return file.CreationTime < file.LastWriteTime - ? file.CreationTime.Date.ToString("yyyyMMdd") - : file.LastWriteTime.Date.ToString("yyyyMMdd"); - } - - /// - /// Determines the file name from the filepath - /// - /// Full path to file including file name - /// Returns only the file name from the filepath - public string get_file_name_from(string file_path) - { - return Path.GetFileName(file_path); - } - - /// - /// Determines the file name from the filepath without the extension - /// - /// Full path to file including file name - /// Returns only the file name minus extensions from the filepath - public string get_file_name_without_extension_from(string file_path) - { - return Path.GetFileNameWithoutExtension(file_path); - } - - public string remove_invalid_characters_from(string path_segment) - { - foreach (var c in InvalidPathCharacters) - { - path_segment = path_segment.Replace(c, '_'); - } - - return path_segment; - } - - /// - /// Determines the file extension for a given path to a file - /// - /// The file to find the extension for - /// The extension of the file. - public string get_file_extension_from(string file_path) - { - return Path.GetExtension(file_path); - } - - #endregion - - #region Directory - - /// - /// Verifies a directory exists, if it doesn't, it creates a new directory at that location - /// - /// Directory to verify exists - public void verify_or_create_directory(string directory) - { - if (!directory_exists(directory)) - { - try - { - create_directory(directory); - } - catch (SystemException e) - { - Log.bound_to(this).log_an_error_event_containing("Cannot create directory \"{0}\". Error was:{1}{2}", - get_full_path(directory), - Environment.NewLine, e - ); - throw; - } - } - else - { - Log.bound_to(this).log_a_debug_event_containing("Directory \"{0}\" already exists", get_full_path(directory)); - } - } - - /// - /// Determines the directory name for a given file path. Useful when working with relative files - /// - /// File to get the directory name from - /// Returns only the path to the directory name - public string get_directory_name_from(string file_path) - { - return Path.GetDirectoryName(get_full_path(file_path)); - } - - /// - /// Returns a DirectoryInfo object from a string - /// - /// Full path to the directory you want the directory information for - /// DirectoryInfo object - public DirectoryInfo get_directory_info_from(string directory) - { - return new DirectoryInfo(directory); - } - - /// - /// Returns a DirectoryInfo object from a string to a filepath - /// - /// Full path to the file you want directory information for - /// DirectoryInfo object - public DirectoryInfo get_directory_info_from_file_path(string file_path) - { - return new DirectoryInfo(file_path).Parent; - } - - /// - /// Determines if a directory exists - /// - /// Path to the directory - /// True if there is a directory already existing, otherwise false - public bool directory_exists(string directory) - { - return Directory.Exists(directory); - } - - /// - /// Creates a directory - /// - /// Path to the directory - /// A directory information object for use after creating the directory - public DirectoryInfo create_directory(string directory) - { - Log.bound_to(this).log_a_debug_event_containing("Attempting to create directory \"{0}\".", get_full_path(directory)); - return Directory.CreateDirectory(directory); - } - - /// - /// Deletes a directory - /// - /// Path to the directory - /// Would you like to delete the directories inside of this directory? Almost always true. - public void delete_directory(string directory, bool recursive) - { - Log.bound_to(this).log_a_debug_event_containing("Attempting to delete directory \"{0}\".", get_full_path(directory)); - Directory.Delete(directory, recursive); - } - - /// - /// Gets a list of directories inside of an existing directory - /// - /// Directory to look for subdirectories in - /// A list of subdirectories inside of the existing directory - public string[] get_all_directory_name_strings_in(string directory) - { - return Directory.GetDirectories(directory); - } - - /// - /// Gets a list of files inside of an existing directory - /// - /// Path to the directory - /// A list of files inside of an existing directory - public string[] get_all_file_name_strings_in(string directory) - { - return get_all_file_name_strings_in(directory, "*.*"); - } - - /// - /// Gets a list of files inside of an existing directory - /// - /// Path to the directory - /// Pattern or extension - /// A list of files inside of an existing directory - public string[] get_all_file_name_strings_in(string directory, string pattern) - { - string[] returnList = Directory.GetFiles(directory, pattern); - return returnList.OrderBy(get_file_name_from).ToArray(); - } - - /// - /// Gets a list of all files inside of an existing directory, includes files in subdirectories also - /// - /// Path to the directory - /// Pattern or extension - /// A list of files inside of an existing directory - public string[] get_all_file_name_strings_recurevly_in(string directory, string pattern) - { - string[] returnList = Directory.GetFiles(directory, pattern, SearchOption.AllDirectories); - return returnList.OrderBy(get_file_name_from).ToArray(); - } - - #endregion - - /// - /// Determines the full path to a given directory. Useful when working with relative directories - /// - /// Where to get the full path from - /// Returns the full path to the file or directory - public string get_full_path(string path) - { - return Path.GetFullPath(path); - } - - /// - /// Combines a set of paths into one path - /// - /// Each item in order from left to right of the path - /// - public string combine_paths(params string[] paths) - { - string combined_path = string.Empty; - foreach (string path in paths) - { - combined_path = Path.Combine(combined_path, path); - } - - return combined_path; - } - } +using System.Diagnostics; +using System.Linq; +using System.Text; + +namespace roundhouse.infrastructure.filesystem +{ + using System; + using System.IO; + using System.Runtime.InteropServices; + using logging; + using extensions; + using roundhouse.infrastructure.app; + + /// + /// All file system access code comes through here + /// + public sealed class DotNetFileSystemAccess : FileSystemAccess + { + private static readonly bool is_running_on_mono = Type.GetType("Mono.Runtime") != null; + private static readonly bool is_running_dotnet_core = RuntimeInformation.FrameworkDescription.StartsWith(".NET Core"); + + public DotNetFileSystemAccess(ConfigurationPropertyHolder configuration) + { + this.configuration = configuration; + } + + private ConfigurationPropertyHolder configuration; + private static readonly char[] InvalidPathCharacters = Path.GetInvalidPathChars().Append(':').ToArray(); + + + #region File + + /// + /// Determines if a file exists + /// + /// Path to the file + /// True if there is a file already existing, otherwise false + public bool file_exists(string file_path) + { + return File.Exists(file_path); + } + + /// + /// Creates a file + /// + /// Path to the file name + /// A file stream object for use after creating the file + public FileStream create_file(string file_path) + { + return new FileStream(file_path, FileMode.OpenOrCreate); + } + + /// + /// Opens a file + /// + /// Path to the file name + /// A file stream object for use after accessing the file + public FileStream open_file_in_read_mode_from(string file_path) + { + return File.OpenRead(file_path); + } + + /// + /// Returns the contents of a file + /// + /// Path to the file name + /// A string of the file contents + public string read_file_text(string file_path) + { + return File.ReadAllText(file_path, get_file_encoding(file_path)); + } + + /// + /// Try to use BOM to detect encoding. If BOM is not present, use default from configuration or UTF-8 if configuration is empty. + /// + /// Path to the file name + /// A best guess at the encoding of the file + /// https://stackoverflow.com/a/4522251/381282 + public Encoding get_file_encoding(string file_path) + { + Encoding enc = configuration.DefaultEncoding ?? Encoding.UTF8; + + // *** Detect byte order mark if any + byte[] buffer = new byte[5]; + int bytes_read; + using (FileStream file = new FileStream(file_path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) + { + bytes_read = file.Read(buffer, 0, 5); + } + + if (buffer[0] == 0xef && buffer[1] == 0xbb && buffer[2] == 0xbf) + enc = Encoding.UTF8; + else if (buffer[0] == 0xfe && buffer[1] == 0xff) + enc = Encoding.BigEndianUnicode; // UTF-16 BE + if (buffer[0] == 0xff && buffer[1] == 0xfe) + { + if(bytes_read >= 4 && buffer[2] == 0 && buffer[3] == 0) + enc = Encoding.UTF32; // UTF-32 LE + else + enc = Encoding.Unicode; // UTF-16 LE + } + else if (buffer[0] == 0 && buffer[1] == 0 && buffer[2] == 0xfe && buffer[3] == 0xff) + enc = Encoding.GetEncoding(12001); // UTF-32 BE + else if (buffer[0] == 0x2b && buffer[1] == 0x2f && buffer[2] == 0x76) + enc = Encoding.UTF7; + + return enc; + } + + /// + /// Copies a file from one directory to another + /// + /// Where is the file now? + /// Where would you like it to go? + /// If there is an existing file already there, would you like to delete it? + public void file_copy(string source_file_name, string destination_file_name, bool overwrite_the_existing_file) + { + Log.bound_to(this).log_a_debug_event_containing("Attempting to copy from \"{0}\" to \"{1}\".", source_file_name, destination_file_name); + File.Copy(source_file_name, destination_file_name, overwrite_the_existing_file); + } + + /// + /// Copies a file from one directory to another using PInvoke + /// + /// Where is the file now? + /// Where would you like it to go? + /// If there is an existing file already there, would you like to delete it? + public void file_copy_unsafe(string source_file_name, string destination_file_name, bool overwrite_the_existing_file) + { + Log.bound_to(this).log_a_debug_event_containing("Attempting to copy from \"{0}\" to \"{1}\".", source_file_name, destination_file_name); + //Private Declare Function apiCopyFile Lib "kernel32" Alias "CopyFileA" _ + if (is_running_on_mono || is_running_dotnet_core) + { + File.Copy(source_file_name, destination_file_name, overwrite_the_existing_file); + } + else { + int success = CopyFileA(source_file_name, destination_file_name, overwrite_the_existing_file ? 0 : 1); + } + } + + [DllImport("kernel32")] + private static extern int CopyFileA(string lpExistingFileName, string lpNewFileName, int bFailIfExists); + + + /// + /// Determines the file information given a path to an existing file + /// + /// Path to an existing file + /// FileInfo object + public FileInfo get_file_info_from(string file_path) + { + return new FileInfo(file_path); + } + + /// + /// Determines the FileVersion of the file passed in + /// + /// Relative or full path to a file + /// A string representing the FileVersion of the passed in file + public string get_file_version_from(string file_path) + { + return FileVersionInfo.GetVersionInfo(get_full_path(file_path)).FileVersion; + } + + /// + /// Determines if a file is a system file + /// + /// File to check + /// True if the file has the System attribute marked, otherwise false + public bool is_system_file(FileInfo file) + { + bool is_system_file = ((file.Attributes & FileAttributes.System) == FileAttributes.System); + if (!is_system_file) + { + //check the directory to be sure + DirectoryInfo directory_info = get_directory_info_from(file.DirectoryName); + is_system_file = ((directory_info.Attributes & FileAttributes.System) == FileAttributes.System); + Log.bound_to(this).log_a_debug_event_containing("Is directory \"{0}\" a system directory? {1}", file.DirectoryName, + is_system_file.to_string()); + } + else + { + Log.bound_to(this).log_a_debug_event_containing("File \"{0}\" is a system file.", file.FullName); + } + return is_system_file; + } + + /// + /// Determines if a file is encrypted or not + /// + /// File to check + /// True if the file has the Encrypted attribute marked, otherwise false + public bool is_encrypted_file(FileInfo file) + { + bool is_encrypted = ((file.Attributes & FileAttributes.Encrypted) == FileAttributes.Encrypted); + Log.bound_to(this).log_a_debug_event_containing("Is file \"{0}\" an encrypted file? {1}", file.FullName, is_encrypted.to_string()); + return is_encrypted; + } + + /// + /// Determines if a file has the same extension as in the list of types + /// + /// File to check + /// File types to check against, listed as file extensions + /// True if the file in question has a file type in the list + public bool file_in_file_types(string file_name, string[] file_types) + { + if (Array.IndexOf(file_types, ".*") > -1 || Array.IndexOf(file_types, get_file_extension_from(file_name).to_lower()) > -1) + { + Log.bound_to(this).log_a_debug_event_containing("File \"{0}\" is in the approved file types of \"{1}\".", file_name, + string.Join(";", file_types)); + return true; + } + + Log.bound_to(this).log_an_info_event_containing("File \"{0}\" is not in the approved file types of \"{1}\".", file_name, + string.Join(";", file_types)); + return false; + } + + /// + /// Determines the older of the file dates, Creation Date or Modified Date + /// + /// File to analyze + /// The oldest date on the file + public string get_file_date(string file_path) + { + FileInfo file = get_file_info_from(file_path); + return file.CreationTime < file.LastWriteTime + ? file.CreationTime.Date.ToString("yyyyMMdd") + : file.LastWriteTime.Date.ToString("yyyyMMdd"); + } + + /// + /// Determines the file name from the filepath + /// + /// Full path to file including file name + /// Returns only the file name from the filepath + public string get_file_name_from(string file_path) + { + return Path.GetFileName(file_path); + } + + /// + /// Determines the file name from the filepath without the extension + /// + /// Full path to file including file name + /// Returns only the file name minus extensions from the filepath + public string get_file_name_without_extension_from(string file_path) + { + return Path.GetFileNameWithoutExtension(file_path); + } + + public string remove_invalid_characters_from(string path_segment) + { + foreach (var c in InvalidPathCharacters) + { + path_segment = path_segment.Replace(c, '_'); + } + + return path_segment; + } + + /// + /// Determines the file extension for a given path to a file + /// + /// The file to find the extension for + /// The extension of the file. + public string get_file_extension_from(string file_path) + { + return Path.GetExtension(file_path); + } + + #endregion + + #region Directory + + /// + /// Verifies a directory exists, if it doesn't, it creates a new directory at that location + /// + /// Directory to verify exists + public void verify_or_create_directory(string directory) + { + if (!directory_exists(directory)) + { + try + { + create_directory(directory); + } + catch (SystemException e) + { + Log.bound_to(this).log_an_error_event_containing("Cannot create directory \"{0}\". Error was:{1}{2}", + get_full_path(directory), + Environment.NewLine, e + ); + throw; + } + } + else + { + Log.bound_to(this).log_a_debug_event_containing("Directory \"{0}\" already exists", get_full_path(directory)); + } + } + + /// + /// Determines the directory name for a given file path. Useful when working with relative files + /// + /// File to get the directory name from + /// Returns only the path to the directory name + public string get_directory_name_from(string file_path) + { + return Path.GetDirectoryName(get_full_path(file_path)); + } + + /// + /// Returns a DirectoryInfo object from a string + /// + /// Full path to the directory you want the directory information for + /// DirectoryInfo object + public DirectoryInfo get_directory_info_from(string directory) + { + return new DirectoryInfo(directory); + } + + /// + /// Returns a DirectoryInfo object from a string to a filepath + /// + /// Full path to the file you want directory information for + /// DirectoryInfo object + public DirectoryInfo get_directory_info_from_file_path(string file_path) + { + return new DirectoryInfo(file_path).Parent; + } + + /// + /// Determines if a directory exists + /// + /// Path to the directory + /// True if there is a directory already existing, otherwise false + public bool directory_exists(string directory) + { + return Directory.Exists(directory); + } + + /// + /// Creates a directory + /// + /// Path to the directory + /// A directory information object for use after creating the directory + public DirectoryInfo create_directory(string directory) + { + Log.bound_to(this).log_a_debug_event_containing("Attempting to create directory \"{0}\".", get_full_path(directory)); + return Directory.CreateDirectory(directory); + } + + /// + /// Deletes a directory + /// + /// Path to the directory + /// Would you like to delete the directories inside of this directory? Almost always true. + public void delete_directory(string directory, bool recursive) + { + Log.bound_to(this).log_a_debug_event_containing("Attempting to delete directory \"{0}\".", get_full_path(directory)); + Directory.Delete(directory, recursive); + } + + /// + /// Gets a list of directories inside of an existing directory + /// + /// Directory to look for subdirectories in + /// A list of subdirectories inside of the existing directory + public string[] get_all_directory_name_strings_in(string directory) + { + return Directory.GetDirectories(directory); + } + + /// + /// Gets a list of files inside of an existing directory + /// + /// Path to the directory + /// A list of files inside of an existing directory + public string[] get_all_file_name_strings_in(string directory) + { + return get_all_file_name_strings_in(directory, "*.*"); + } + + /// + /// Gets a list of files inside of an existing directory + /// + /// Path to the directory + /// Pattern or extension + /// A list of files inside of an existing directory + public string[] get_all_file_name_strings_in(string directory, string pattern) + { + string[] returnList = Directory.GetFiles(directory, pattern); + return returnList.OrderBy(get_file_name_from).ToArray(); + } + + /// + /// Gets a list of all files inside of an existing directory, includes files in subdirectories also + /// + /// Path to the directory + /// Pattern or extension + /// A list of files inside of an existing directory + public string[] get_all_file_name_strings_recurevly_in(string directory, string pattern) + { + string[] returnList = Directory.GetFiles(directory, pattern, SearchOption.AllDirectories); + return returnList.OrderBy(get_file_name_from).ToArray(); + } + + #endregion + + /// + /// Determines the full path to a given directory. Useful when working with relative directories + /// + /// Where to get the full path from + /// Returns the full path to the file or directory + public string get_full_path(string path) + { + return Path.GetFullPath(path); + } + + /// + /// Combines a set of paths into one path + /// + /// Each item in order from left to right of the path + /// + public string combine_paths(params string[] paths) + { + string combined_path = string.Empty; + foreach (string path in paths) + { + combined_path = Path.Combine(combined_path, path); + } + + return combined_path; + } + } } \ No newline at end of file diff --git a/product/roundhouse/infrastructure/filesystem/FileSystemAccess.cs b/product/roundhouse.core/infrastructure/filesystem/FileSystemAccess.cs similarity index 97% rename from product/roundhouse/infrastructure/filesystem/FileSystemAccess.cs rename to product/roundhouse.core/infrastructure/filesystem/FileSystemAccess.cs index 80985463..46affc88 100644 --- a/product/roundhouse/infrastructure/filesystem/FileSystemAccess.cs +++ b/product/roundhouse.core/infrastructure/filesystem/FileSystemAccess.cs @@ -1,226 +1,226 @@ -namespace roundhouse.infrastructure.filesystem -{ - using System.IO; - - /// - /// Handles all access to the file system objects - /// - public interface FileSystemAccess - { - #region File - - /// - /// Determines if a file exists - /// - /// Path to the file - /// True if there is a file already existing, otherwise false - bool file_exists(string file_path); - - /// - /// Creates a file - /// - /// Path to the file name - /// A file stream object for use after creating the file - FileStream create_file(string file_path); - - /// - /// Opens a file - /// - /// Path to the file name - /// A file stream object for use after accessing the file - FileStream open_file_in_read_mode_from(string file_path); - - /// - /// Returns the contents of a file - /// - /// Path to the file name - /// A string of the file contents - string read_file_text(string file_path); - - /// - /// Determines the file information given a path to an existing file - /// - /// Path to an existing file - /// FileInfo object - FileInfo get_file_info_from(string file_path); - - /// - /// Determines the FileVersion of the file passed in - /// - /// Relative or full path to a file - /// A string representing the FileVersion of the passed in file - string get_file_version_from(string file_path); - - /// - /// Copies a file from one directory to another - /// - /// Where is the file now? - /// Where would you like it to go? - /// If there is an existing file already there, would you like to delete it? - void file_copy(string source_file_name, string destination_file_name, bool overwrite_the_existing_file); - - /// - /// Copies a file from one directory to another using PInvoke - /// - /// Where is the file now? - /// Where would you like it to go? - /// If there is an existing file already there, would you like to delete it? - void file_copy_unsafe(string source_file_name, string destination_file_name, bool overwrite_the_existing_file); - - /// - /// Determines if a file is a system file - /// - /// File to check - /// True if the file has the System attribute marked, otherwise false - bool is_system_file(FileInfo file); - - /// - /// Determines if a file is encrypted or not - /// - /// File to check - /// True if the file has the Encrypted attribute marked, otherwise false - bool is_encrypted_file(FileInfo file); - - /// - /// Determines if a file has the same extension as in the list of types - /// - /// File to check - /// File types to check against, listed as file extensions - /// True if the file in question has a file type in the list - bool file_in_file_types(string file_name, string[] file_types); - - /// - /// Determines the older of the file dates, Creation Date or Modified Date - /// - /// File to analyze - /// The oldest date on the file - string get_file_date(string file_path); - - /// - /// Determines the file name from the filepath - /// - /// Full path to file including file name - /// Returns only the file name from the filepath - string get_file_name_from(string file_path); - - /// - /// Determines the file name from the filepath without the extension - /// - /// Full path to file including file name - /// Returns only the file name minus extensions from the filepath - string get_file_name_without_extension_from(string file_path); - - /// - /// Removes invalid characters from a path segment - /// - /// segment of path to clean - /// The path with all illegal characters stripped away - string remove_invalid_characters_from(string path_segment); - - - /// - /// Determines the file extension for a given path to a file - /// - /// The file to find the extension for - /// The extension of the file. - string get_file_extension_from(string file_path); - - /// - /// Gets a list of files inside of an existing directory - /// - /// Path to the directory - /// A list of files inside of an existing directory - string[] get_all_file_name_strings_in(string directory); - - #endregion - - #region Directory - - /// - /// Determines if a directory exists - /// - /// Path to the directory - /// True if there is a directory already existing, otherwise false - bool directory_exists(string directory); - - /// - /// Verifies a directory exists, if it doesn't, it creates a new directory at that location - /// - /// Directory to verify exists - void verify_or_create_directory(string directory); - - /// - /// Determines the directory name for a given file path. Useful when working with relative files - /// - /// File to get the directory name from - /// Returns only the path to the directory name - string get_directory_name_from(string file_path); - - /// - /// Returns a DirectoryInfo object from a string - /// - /// Full path to the directory you want the directory information for - /// DirectoryInfo object - DirectoryInfo get_directory_info_from(string directory); - - /// - /// Returns a DirectoryInfo object from a string to a filepath - /// - /// Full path to the file you want directory information for - /// DirectoryInfo object - DirectoryInfo get_directory_info_from_file_path(string file_path); - - /// - /// Creates a directory - /// - /// Path to the directory - /// A directory information object for use after creating the directory - DirectoryInfo create_directory(string directory); - - /// - /// Deletes a directory - /// - /// Path to the directory - /// Would you like to delete the directories inside of this directory? Almost always true. - void delete_directory(string directory, bool recursive); - - /// - /// Gets a list of directories inside of an existing directory - /// - /// Directory to look for subdirectories in - /// A list of subdirectories inside of the existing directory - string[] get_all_directory_name_strings_in(string directory); - - /// - /// Gets a list of files inside of an existing directory - /// - /// Path to the directory - /// Pattern or extension - /// A list of files inside of an existing directory - string[] get_all_file_name_strings_in(string directory, string pattern); - - /// - /// Gets a list of all files inside of an existing directory, includes files in subdirectories also - /// - /// Path to the directory - /// Pattern or extension - /// A list of files inside of an existing directory - string[] get_all_file_name_strings_recurevly_in(string directory, string pattern); - - #endregion - - /// - /// Determines the full path to a given directory. Useful when working with relative directories - /// - /// Where to get the full path from - /// Returns the full path to the file or directory - string get_full_path(string path); - - /// - /// Combines a set of paths into one path - /// - /// Each item in order from left to right of the path - /// - string combine_paths(params string[] paths); - } +namespace roundhouse.infrastructure.filesystem +{ + using System.IO; + + /// + /// Handles all access to the file system objects + /// + public interface FileSystemAccess + { + #region File + + /// + /// Determines if a file exists + /// + /// Path to the file + /// True if there is a file already existing, otherwise false + bool file_exists(string file_path); + + /// + /// Creates a file + /// + /// Path to the file name + /// A file stream object for use after creating the file + FileStream create_file(string file_path); + + /// + /// Opens a file + /// + /// Path to the file name + /// A file stream object for use after accessing the file + FileStream open_file_in_read_mode_from(string file_path); + + /// + /// Returns the contents of a file + /// + /// Path to the file name + /// A string of the file contents + string read_file_text(string file_path); + + /// + /// Determines the file information given a path to an existing file + /// + /// Path to an existing file + /// FileInfo object + FileInfo get_file_info_from(string file_path); + + /// + /// Determines the FileVersion of the file passed in + /// + /// Relative or full path to a file + /// A string representing the FileVersion of the passed in file + string get_file_version_from(string file_path); + + /// + /// Copies a file from one directory to another + /// + /// Where is the file now? + /// Where would you like it to go? + /// If there is an existing file already there, would you like to delete it? + void file_copy(string source_file_name, string destination_file_name, bool overwrite_the_existing_file); + + /// + /// Copies a file from one directory to another using PInvoke + /// + /// Where is the file now? + /// Where would you like it to go? + /// If there is an existing file already there, would you like to delete it? + void file_copy_unsafe(string source_file_name, string destination_file_name, bool overwrite_the_existing_file); + + /// + /// Determines if a file is a system file + /// + /// File to check + /// True if the file has the System attribute marked, otherwise false + bool is_system_file(FileInfo file); + + /// + /// Determines if a file is encrypted or not + /// + /// File to check + /// True if the file has the Encrypted attribute marked, otherwise false + bool is_encrypted_file(FileInfo file); + + /// + /// Determines if a file has the same extension as in the list of types + /// + /// File to check + /// File types to check against, listed as file extensions + /// True if the file in question has a file type in the list + bool file_in_file_types(string file_name, string[] file_types); + + /// + /// Determines the older of the file dates, Creation Date or Modified Date + /// + /// File to analyze + /// The oldest date on the file + string get_file_date(string file_path); + + /// + /// Determines the file name from the filepath + /// + /// Full path to file including file name + /// Returns only the file name from the filepath + string get_file_name_from(string file_path); + + /// + /// Determines the file name from the filepath without the extension + /// + /// Full path to file including file name + /// Returns only the file name minus extensions from the filepath + string get_file_name_without_extension_from(string file_path); + + /// + /// Removes invalid characters from a path segment + /// + /// segment of path to clean + /// The path with all illegal characters stripped away + string remove_invalid_characters_from(string path_segment); + + + /// + /// Determines the file extension for a given path to a file + /// + /// The file to find the extension for + /// The extension of the file. + string get_file_extension_from(string file_path); + + /// + /// Gets a list of files inside of an existing directory + /// + /// Path to the directory + /// A list of files inside of an existing directory + string[] get_all_file_name_strings_in(string directory); + + #endregion + + #region Directory + + /// + /// Determines if a directory exists + /// + /// Path to the directory + /// True if there is a directory already existing, otherwise false + bool directory_exists(string directory); + + /// + /// Verifies a directory exists, if it doesn't, it creates a new directory at that location + /// + /// Directory to verify exists + void verify_or_create_directory(string directory); + + /// + /// Determines the directory name for a given file path. Useful when working with relative files + /// + /// File to get the directory name from + /// Returns only the path to the directory name + string get_directory_name_from(string file_path); + + /// + /// Returns a DirectoryInfo object from a string + /// + /// Full path to the directory you want the directory information for + /// DirectoryInfo object + DirectoryInfo get_directory_info_from(string directory); + + /// + /// Returns a DirectoryInfo object from a string to a filepath + /// + /// Full path to the file you want directory information for + /// DirectoryInfo object + DirectoryInfo get_directory_info_from_file_path(string file_path); + + /// + /// Creates a directory + /// + /// Path to the directory + /// A directory information object for use after creating the directory + DirectoryInfo create_directory(string directory); + + /// + /// Deletes a directory + /// + /// Path to the directory + /// Would you like to delete the directories inside of this directory? Almost always true. + void delete_directory(string directory, bool recursive); + + /// + /// Gets a list of directories inside of an existing directory + /// + /// Directory to look for subdirectories in + /// A list of subdirectories inside of the existing directory + string[] get_all_directory_name_strings_in(string directory); + + /// + /// Gets a list of files inside of an existing directory + /// + /// Path to the directory + /// Pattern or extension + /// A list of files inside of an existing directory + string[] get_all_file_name_strings_in(string directory, string pattern); + + /// + /// Gets a list of all files inside of an existing directory, includes files in subdirectories also + /// + /// Path to the directory + /// Pattern or extension + /// A list of files inside of an existing directory + string[] get_all_file_name_strings_recurevly_in(string directory, string pattern); + + #endregion + + /// + /// Determines the full path to a given directory. Useful when working with relative directories + /// + /// Where to get the full path from + /// Returns the full path to the file or directory + string get_full_path(string path); + + /// + /// Combines a set of paths into one path + /// + /// Each item in order from left to right of the path + /// + string combine_paths(params string[] paths); + } } \ No newline at end of file diff --git a/product/roundhouse/infrastructure/loaders/DefaultAssemblyLoader.cs b/product/roundhouse.core/infrastructure/loaders/DefaultAssemblyLoader.cs similarity index 96% rename from product/roundhouse/infrastructure/loaders/DefaultAssemblyLoader.cs rename to product/roundhouse.core/infrastructure/loaders/DefaultAssemblyLoader.cs index 261bc525..03c96481 100644 --- a/product/roundhouse/infrastructure/loaders/DefaultAssemblyLoader.cs +++ b/product/roundhouse.core/infrastructure/loaders/DefaultAssemblyLoader.cs @@ -1,12 +1,12 @@ -namespace roundhouse.infrastructure.loaders -{ - using System.Reflection; - - public class DefaultAssemblyLoader - { - public static Assembly load_assembly(string assembly_name) - { - return Assembly.Load(assembly_name); - } - } +namespace roundhouse.infrastructure.loaders +{ + using System.Reflection; + + public class DefaultAssemblyLoader + { + public static Assembly load_assembly(string assembly_name) + { + return Assembly.Load(assembly_name); + } + } } \ No newline at end of file diff --git a/product/roundhouse/infrastructure/loaders/DefaultInstanceCreator.cs b/product/roundhouse.core/infrastructure/loaders/DefaultInstanceCreator.cs similarity index 97% rename from product/roundhouse/infrastructure/loaders/DefaultInstanceCreator.cs rename to product/roundhouse.core/infrastructure/loaders/DefaultInstanceCreator.cs index 120bdf2f..2d938b39 100644 --- a/product/roundhouse/infrastructure/loaders/DefaultInstanceCreator.cs +++ b/product/roundhouse.core/infrastructure/loaders/DefaultInstanceCreator.cs @@ -1,34 +1,34 @@ -namespace roundhouse.infrastructure.loaders -{ - using System; - using System.Reflection; - using logging; - - public class DefaultInstanceCreator - { - //Type generic = typeof(Container.get_an_instance_of<>); - //Type specific = generic.MakeGenericType(typeof(from.system_type)); - //ConstructorInfo ci = specific.GetConstructor(new Type[] { }); - //object o = ci.Invoke(new object[] { }); - - //http://www.google.com/search?hl=en&q=passing+runtime+Type+to+Generic&aq=f&oq=&aqi= - //http://stackoverflow.com/questions/513952/c-specifying-generic-collection-type-param-at-runtime - - public static T create_object_from_string_type(string object_to_create) - { - return (T) create_object_from_string_type(object_to_create); - } - public static object create_object_from_string_type(string object_to_create) - { - Log.bound_to(typeof(DefaultInstanceCreator)).log_a_debug_event_containing("Resolving and creating an instance of \"{0}\".", object_to_create); - - Type object_type = Type.GetType(object_to_create); - - if (object_type == null) throw new NullReferenceException(string.Format("A type could not be created from the object you passed. \"{0}\" resolves to null.", object_to_create)); - - ConstructorInfo ci = object_type.GetConstructor(new Type[] { }); - - return ci.Invoke(new object[] { }); - } - } +namespace roundhouse.infrastructure.loaders +{ + using System; + using System.Reflection; + using logging; + + public class DefaultInstanceCreator + { + //Type generic = typeof(Container.get_an_instance_of<>); + //Type specific = generic.MakeGenericType(typeof(from.system_type)); + //ConstructorInfo ci = specific.GetConstructor(new Type[] { }); + //object o = ci.Invoke(new object[] { }); + + //http://www.google.com/search?hl=en&q=passing+runtime+Type+to+Generic&aq=f&oq=&aqi= + //http://stackoverflow.com/questions/513952/c-specifying-generic-collection-type-param-at-runtime + + public static T create_object_from_string_type(string object_to_create) + { + return (T) create_object_from_string_type(object_to_create); + } + public static object create_object_from_string_type(string object_to_create) + { + Log.bound_to(typeof(DefaultInstanceCreator)).log_a_debug_event_containing("Resolving and creating an instance of \"{0}\".", object_to_create); + + Type object_type = Type.GetType(object_to_create); + + if (object_type == null) throw new NullReferenceException(string.Format("A type could not be created from the object you passed. \"{0}\" resolves to null.", object_to_create)); + + ConstructorInfo ci = object_type.GetConstructor(new Type[] { }); + + return ci.Invoke(new object[] { }); + } + } } \ No newline at end of file diff --git a/product/roundhouse/infrastructure/logging/Log.cs b/product/roundhouse.core/infrastructure/logging/Log.cs similarity index 96% rename from product/roundhouse/infrastructure/logging/Log.cs rename to product/roundhouse.core/infrastructure/logging/Log.cs index 4d6f7836..688cbbe6 100644 --- a/product/roundhouse/infrastructure/logging/Log.cs +++ b/product/roundhouse.core/infrastructure/logging/Log.cs @@ -1,32 +1,32 @@ -namespace roundhouse.infrastructure.logging -{ - using System; - using containers; - using custom; - using extensions; - using log4net; - - public static class Log - { - private static bool have_displayed_error_message; - - public static Logger bound_to(object object_that_needs_logging) - { - Logger logger; - try - { - logger = Container.get_an_instance_of().create_logger_bound_to(object_that_needs_logging.GetType()); - } - catch(Exception) - { - if(!have_displayed_error_message) - { - have_displayed_error_message = true; - } - logger = new Log4NetLogger(LogManager.GetLogger(object_that_needs_logging?.GetType())); - } - - return logger; - } - } +namespace roundhouse.infrastructure.logging +{ + using System; + using containers; + using custom; + using extensions; + using log4net; + + public static class Log + { + private static bool have_displayed_error_message; + + public static Logger bound_to(object object_that_needs_logging) + { + Logger logger; + try + { + logger = Container.get_an_instance_of().create_logger_bound_to(object_that_needs_logging.GetType()); + } + catch(Exception) + { + if(!have_displayed_error_message) + { + have_displayed_error_message = true; + } + logger = new Log4NetLogger(LogManager.GetLogger(object_that_needs_logging?.GetType())); + } + + return logger; + } + } } \ No newline at end of file diff --git a/product/roundhouse/infrastructure/logging/LogFactory.cs b/product/roundhouse.core/infrastructure/logging/LogFactory.cs similarity index 95% rename from product/roundhouse/infrastructure/logging/LogFactory.cs rename to product/roundhouse.core/infrastructure/logging/LogFactory.cs index 06183573..6da21af0 100644 --- a/product/roundhouse/infrastructure/logging/LogFactory.cs +++ b/product/roundhouse.core/infrastructure/logging/LogFactory.cs @@ -1,9 +1,9 @@ -namespace roundhouse.infrastructure.logging -{ - using System; - - public interface LogFactory - { - Logger create_logger_bound_to(Object type); - } +namespace roundhouse.infrastructure.logging +{ + using System; + + public interface LogFactory + { + Logger create_logger_bound_to(Object type); + } } \ No newline at end of file diff --git a/product/roundhouse/infrastructure/logging/Logger.cs b/product/roundhouse.core/infrastructure/logging/Logger.cs similarity index 97% rename from product/roundhouse/infrastructure/logging/Logger.cs rename to product/roundhouse.core/infrastructure/logging/Logger.cs index 35a67782..0d23ac54 100644 --- a/product/roundhouse/infrastructure/logging/Logger.cs +++ b/product/roundhouse.core/infrastructure/logging/Logger.cs @@ -1,12 +1,12 @@ -namespace roundhouse.infrastructure.logging -{ - public interface Logger - { - void log_a_debug_event_containing(string message, params object[] args); - void log_an_info_event_containing(string message, params object[] args); - void log_a_warning_event_containing(string message, params object[] args); - void log_an_error_event_containing(string message, params object[] args); - void log_a_fatal_event_containing(string message, params object[] args); - object underlying_type { get;} - } +namespace roundhouse.infrastructure.logging +{ + public interface Logger + { + void log_a_debug_event_containing(string message, params object[] args); + void log_an_info_event_containing(string message, params object[] args); + void log_a_warning_event_containing(string message, params object[] args); + void log_an_error_event_containing(string message, params object[] args); + void log_a_fatal_event_containing(string message, params object[] args); + object underlying_type { get;} + } } \ No newline at end of file diff --git a/product/roundhouse/infrastructure/logging/custom/ConsoleLogger.cs b/product/roundhouse.core/infrastructure/logging/custom/ConsoleLogger.cs similarity index 96% rename from product/roundhouse/infrastructure/logging/custom/ConsoleLogger.cs rename to product/roundhouse.core/infrastructure/logging/custom/ConsoleLogger.cs index fb7659bf..060e5efb 100644 --- a/product/roundhouse/infrastructure/logging/custom/ConsoleLogger.cs +++ b/product/roundhouse.core/infrastructure/logging/custom/ConsoleLogger.cs @@ -1,49 +1,49 @@ -namespace roundhouse.infrastructure.logging.custom -{ - public class ConsoleLogger : Logger - { - private readonly bool debugging; - - public ConsoleLogger() : this(false) { } - - public ConsoleLogger(bool debugging) - { - this.debugging = debugging; - } - - private void log_message(string message) - { - System.Console.WriteLine(message); - } - - public void log_a_debug_event_containing(string message, params object[] args) - { - if (debugging) log_message("[DEBUG]: " + string.Format(message, args)); - } - - public void log_an_info_event_containing(string message, params object[] args) - { - log_message("[INFO]: " + string.Format(message, args)); - } - - public void log_a_warning_event_containing(string message, params object[] args) - { - log_message("[WARN]: " + string.Format(message, args)); - } - - public void log_an_error_event_containing(string message, params object[] args) - { - log_message("[ERROR]: " + string.Format(message, args)); - } - - public void log_a_fatal_event_containing(string message, params object[] args) - { - log_message("[FATAL]: " + string.Format(message, args)); - } - - public object underlying_type - { - get { return new object(); } - } - } +namespace roundhouse.infrastructure.logging.custom +{ + public class ConsoleLogger : Logger + { + private readonly bool debugging; + + public ConsoleLogger() : this(false) { } + + public ConsoleLogger(bool debugging) + { + this.debugging = debugging; + } + + private void log_message(string message) + { + System.Console.WriteLine(message); + } + + public void log_a_debug_event_containing(string message, params object[] args) + { + if (debugging) log_message("[DEBUG]: " + string.Format(message, args)); + } + + public void log_an_info_event_containing(string message, params object[] args) + { + log_message("[INFO]: " + string.Format(message, args)); + } + + public void log_a_warning_event_containing(string message, params object[] args) + { + log_message("[WARN]: " + string.Format(message, args)); + } + + public void log_an_error_event_containing(string message, params object[] args) + { + log_message("[ERROR]: " + string.Format(message, args)); + } + + public void log_a_fatal_event_containing(string message, params object[] args) + { + log_message("[FATAL]: " + string.Format(message, args)); + } + + public object underlying_type + { + get { return new object(); } + } + } } \ No newline at end of file diff --git a/product/roundhouse/infrastructure/logging/custom/FileLogger.cs b/product/roundhouse.core/infrastructure/logging/custom/FileLogger.cs similarity index 97% rename from product/roundhouse/infrastructure/logging/custom/FileLogger.cs rename to product/roundhouse.core/infrastructure/logging/custom/FileLogger.cs index f57f6c07..8aca4156 100644 --- a/product/roundhouse/infrastructure/logging/custom/FileLogger.cs +++ b/product/roundhouse.core/infrastructure/logging/custom/FileLogger.cs @@ -1,56 +1,56 @@ -namespace roundhouse.infrastructure.logging.custom -{ - using System; - using System.IO; - using filesystem; - - public class FileLogger : Logger - { - private readonly string log_file_path; - private readonly FileSystemAccess file_system; - - public FileLogger(string log_file_path, FileSystemAccess file_system) - { - this.log_file_path = log_file_path; - this.file_system = file_system; - } - - private void log_message(string message) - { - string dateTime = string.Format("{0:MM/dd/yyyy HH:mm:ss;ffff} ", DateTime.Now); - file_system.verify_or_create_directory(file_system.get_directory_name_from(log_file_path)); - - File.AppendAllText(log_file_path, dateTime + message, System.Text.Encoding.UTF8); - } - - public void log_a_debug_event_containing(string message, params object[] args) - { - log_message("[DEBUG]: " + string.Format(message, args)); - } - - public void log_an_info_event_containing(string message, params object[] args) - { - log_message("[INFO]: " + string.Format(message, args)); - } - - public void log_a_warning_event_containing(string message, params object[] args) - { - log_message("[WARN]: " + string.Format(message, args)); - } - - public void log_an_error_event_containing(string message, params object[] args) - { - log_message("[ERROR]: " + string.Format(message, args)); - } - - public void log_a_fatal_event_containing(string message, params object[] args) - { - log_message("[FATAL]: " + string.Format(message, args)); - } - - public object underlying_type - { - get { return file_system; } - } - } +namespace roundhouse.infrastructure.logging.custom +{ + using System; + using System.IO; + using filesystem; + + public class FileLogger : Logger + { + private readonly string log_file_path; + private readonly FileSystemAccess file_system; + + public FileLogger(string log_file_path, FileSystemAccess file_system) + { + this.log_file_path = log_file_path; + this.file_system = file_system; + } + + private void log_message(string message) + { + string dateTime = string.Format("{0:MM/dd/yyyy HH:mm:ss;ffff} ", DateTime.Now); + file_system.verify_or_create_directory(file_system.get_directory_name_from(log_file_path)); + + File.AppendAllText(log_file_path, dateTime + message, System.Text.Encoding.UTF8); + } + + public void log_a_debug_event_containing(string message, params object[] args) + { + log_message("[DEBUG]: " + string.Format(message, args)); + } + + public void log_an_info_event_containing(string message, params object[] args) + { + log_message("[INFO]: " + string.Format(message, args)); + } + + public void log_a_warning_event_containing(string message, params object[] args) + { + log_message("[WARN]: " + string.Format(message, args)); + } + + public void log_an_error_event_containing(string message, params object[] args) + { + log_message("[ERROR]: " + string.Format(message, args)); + } + + public void log_a_fatal_event_containing(string message, params object[] args) + { + log_message("[FATAL]: " + string.Format(message, args)); + } + + public object underlying_type + { + get { return file_system; } + } + } } \ No newline at end of file diff --git a/product/roundhouse/infrastructure/logging/custom/Log4NetLogFactory.cs b/product/roundhouse.core/infrastructure/logging/custom/Log4NetLogFactory.cs similarity index 96% rename from product/roundhouse/infrastructure/logging/custom/Log4NetLogFactory.cs rename to product/roundhouse.core/infrastructure/logging/custom/Log4NetLogFactory.cs index d4857f9e..9a152627 100644 --- a/product/roundhouse/infrastructure/logging/custom/Log4NetLogFactory.cs +++ b/product/roundhouse.core/infrastructure/logging/custom/Log4NetLogFactory.cs @@ -1,12 +1,12 @@ -namespace roundhouse.infrastructure.logging.custom -{ - using log4net; - - public sealed class Log4NetLogFactory : LogFactory - { - public Logger create_logger_bound_to(object type) - { - return new Log4NetLogger(LogManager.GetLogger(type?.GetType())); - } - } +namespace roundhouse.infrastructure.logging.custom +{ + using log4net; + + public sealed class Log4NetLogFactory : LogFactory + { + public Logger create_logger_bound_to(object type) + { + return new Log4NetLogger(LogManager.GetLogger(type?.GetType())); + } + } } \ No newline at end of file diff --git a/product/roundhouse/infrastructure/logging/custom/Log4NetLogger.cs b/product/roundhouse.core/infrastructure/logging/custom/Log4NetLogger.cs similarity index 96% rename from product/roundhouse/infrastructure/logging/custom/Log4NetLogger.cs rename to product/roundhouse.core/infrastructure/logging/custom/Log4NetLogger.cs index 1935843a..e7093f3f 100644 --- a/product/roundhouse/infrastructure/logging/custom/Log4NetLogger.cs +++ b/product/roundhouse.core/infrastructure/logging/custom/Log4NetLogger.cs @@ -1,46 +1,46 @@ -using System; - -namespace roundhouse.infrastructure.logging.custom -{ - using log4net; - - public sealed class Log4NetLogger : Logger - { - private readonly ILog logger; - - public Log4NetLogger(ILog logger) - { - this.logger = logger; - } - - public void log_a_debug_event_containing(string message, params object[] args) - { - logger.DebugFormat(message, args); - } - - public void log_an_info_event_containing(string message, params object[] args) - { - logger.InfoFormat(message, args); - } - - public void log_a_warning_event_containing(string message, params object[] args) - { - logger.WarnFormat(message, args); - } - - public void log_an_error_event_containing(string message, params object[] args) - { - logger.ErrorFormat(message, args); - } - - public void log_a_fatal_event_containing(string message, params object[] args) - { - logger.FatalFormat(message, args); - } - - public object underlying_type - { - get { return logger; } - } - } +using System; + +namespace roundhouse.infrastructure.logging.custom +{ + using log4net; + + public sealed class Log4NetLogger : Logger + { + private readonly ILog logger; + + public Log4NetLogger(ILog logger) + { + this.logger = logger; + } + + public void log_a_debug_event_containing(string message, params object[] args) + { + logger.DebugFormat(message, args); + } + + public void log_an_info_event_containing(string message, params object[] args) + { + logger.InfoFormat(message, args); + } + + public void log_a_warning_event_containing(string message, params object[] args) + { + logger.WarnFormat(message, args); + } + + public void log_an_error_event_containing(string message, params object[] args) + { + logger.ErrorFormat(message, args); + } + + public void log_a_fatal_event_containing(string message, params object[] args) + { + logger.FatalFormat(message, args); + } + + public object underlying_type + { + get { return logger; } + } + } } \ No newline at end of file diff --git a/product/roundhouse/infrastructure/logging/custom/MSBuildLogger.cs b/product/roundhouse.core/infrastructure/logging/custom/MSBuildLogger.cs similarity index 96% rename from product/roundhouse/infrastructure/logging/custom/MSBuildLogger.cs rename to product/roundhouse.core/infrastructure/logging/custom/MSBuildLogger.cs index 5c623fb5..05c10451 100644 --- a/product/roundhouse/infrastructure/logging/custom/MSBuildLogger.cs +++ b/product/roundhouse.core/infrastructure/logging/custom/MSBuildLogger.cs @@ -1,85 +1,85 @@ -using System; - -namespace roundhouse.infrastructure.logging.custom -{ - using app; - using Microsoft.Build.Framework; - - public sealed class MSBuildLogger : Logger - { - private readonly IBuildEngine build_engine; - private readonly object calling_task; - - public MSBuildLogger(ConfigurationPropertyHolder configuration) - { - var task = configuration as ITask; - if (task != null) - { - build_engine = task.BuildEngine; - } - - calling_task = configuration; - } - - public void log_a_debug_event_containing(string message, params object[] args) - { - if (build_engine == null) return; - - build_engine.LogMessageEvent(new BuildMessageEventArgs( - string.Format(message, args), - string.Empty, - calling_task.GetType().Name, - MessageImportance.Low)); - } - - public void log_an_info_event_containing(string message, params object[] args) - { - if (build_engine == null) return; - - build_engine.LogMessageEvent(new BuildMessageEventArgs( - string.Format(message, args), - string.Empty, - calling_task.GetType().Name, - MessageImportance.Normal)); - } - - public void log_a_warning_event_containing(string message, params object[] args) - { - //build_engine.LogMessageEvent(new BuildMessageEventArgs( - // string.Format(message, args), - // string.Empty, - // calling_task.GetType().Name, - // MessageImportance.High)); - if (build_engine == null) return; - - build_engine.LogWarningEvent(new BuildWarningEventArgs( - string.Empty, - string.Empty, - string.Empty, 0, 0, 0, 0, - string.Format(message, args), - string.Empty, calling_task.GetType().Name)); - } - - public void log_an_error_event_containing(string message, params object[] args) - { - if (build_engine == null) return; - - build_engine.LogErrorEvent(new BuildErrorEventArgs( - string.Empty, - string.Empty, - string.Empty, 0, 0, 0, 0, - string.Format(message, args), - string.Empty, calling_task.GetType().Name)); - } - - public void log_a_fatal_event_containing(string message, params object[] args) - { - log_an_error_event_containing(message, args); - } - - public object underlying_type - { - get { return build_engine; } - } - } +using System; + +namespace roundhouse.infrastructure.logging.custom +{ + using app; + using Microsoft.Build.Framework; + + public sealed class MSBuildLogger : Logger + { + private readonly IBuildEngine build_engine; + private readonly object calling_task; + + public MSBuildLogger(ConfigurationPropertyHolder configuration) + { + var task = configuration as ITask; + if (task != null) + { + build_engine = task.BuildEngine; + } + + calling_task = configuration; + } + + public void log_a_debug_event_containing(string message, params object[] args) + { + if (build_engine == null) return; + + build_engine.LogMessageEvent(new BuildMessageEventArgs( + string.Format(message, args), + string.Empty, + calling_task.GetType().Name, + MessageImportance.Low)); + } + + public void log_an_info_event_containing(string message, params object[] args) + { + if (build_engine == null) return; + + build_engine.LogMessageEvent(new BuildMessageEventArgs( + string.Format(message, args), + string.Empty, + calling_task.GetType().Name, + MessageImportance.Normal)); + } + + public void log_a_warning_event_containing(string message, params object[] args) + { + //build_engine.LogMessageEvent(new BuildMessageEventArgs( + // string.Format(message, args), + // string.Empty, + // calling_task.GetType().Name, + // MessageImportance.High)); + if (build_engine == null) return; + + build_engine.LogWarningEvent(new BuildWarningEventArgs( + string.Empty, + string.Empty, + string.Empty, 0, 0, 0, 0, + string.Format(message, args), + string.Empty, calling_task.GetType().Name)); + } + + public void log_an_error_event_containing(string message, params object[] args) + { + if (build_engine == null) return; + + build_engine.LogErrorEvent(new BuildErrorEventArgs( + string.Empty, + string.Empty, + string.Empty, 0, 0, 0, 0, + string.Format(message, args), + string.Empty, calling_task.GetType().Name)); + } + + public void log_a_fatal_event_containing(string message, params object[] args) + { + log_an_error_event_containing(message, args); + } + + public object underlying_type + { + get { return build_engine; } + } + } } \ No newline at end of file diff --git a/product/roundhouse/infrastructure/logging/custom/MultipleLogger.cs b/product/roundhouse.core/infrastructure/logging/custom/MultipleLogger.cs similarity index 96% rename from product/roundhouse/infrastructure/logging/custom/MultipleLogger.cs rename to product/roundhouse.core/infrastructure/logging/custom/MultipleLogger.cs index b4eb1672..9d42d553 100644 --- a/product/roundhouse/infrastructure/logging/custom/MultipleLogger.cs +++ b/product/roundhouse.core/infrastructure/logging/custom/MultipleLogger.cs @@ -1,61 +1,61 @@ -using System; - -namespace roundhouse.infrastructure.logging.custom -{ - using System.Collections.Generic; - - public sealed class MultipleLogger : Logger - { - private readonly IList the_loggers; - - public MultipleLogger(IList loggers) - { - the_loggers = loggers ?? new List(); - } - - public void log_a_debug_event_containing(string message, params object[] args) - { - foreach (Logger logger in the_loggers) - { - logger.log_a_debug_event_containing(message, args); - } - } - - public void log_an_info_event_containing(string message, params object[] args) - { - foreach (Logger logger in the_loggers) - { - logger.log_an_info_event_containing(message, args); - } - } - - public void log_a_warning_event_containing(string message, params object[] args) - { - foreach (Logger logger in the_loggers) - { - logger.log_a_warning_event_containing(message, args); - } - } - - public void log_an_error_event_containing(string message, params object[] args) - { - foreach (Logger logger in the_loggers) - { - logger.log_an_error_event_containing(message, args); - } - } - - public void log_a_fatal_event_containing(string message, params object[] args) - { - foreach (Logger logger in the_loggers) - { - logger.log_a_fatal_event_containing(message, args); - } - } - - public object underlying_type - { - get { return the_loggers; } - } - } +using System; + +namespace roundhouse.infrastructure.logging.custom +{ + using System.Collections.Generic; + + public sealed class MultipleLogger : Logger + { + private readonly IList the_loggers; + + public MultipleLogger(IList loggers) + { + the_loggers = loggers ?? new List(); + } + + public void log_a_debug_event_containing(string message, params object[] args) + { + foreach (Logger logger in the_loggers) + { + logger.log_a_debug_event_containing(message, args); + } + } + + public void log_an_info_event_containing(string message, params object[] args) + { + foreach (Logger logger in the_loggers) + { + logger.log_an_info_event_containing(message, args); + } + } + + public void log_a_warning_event_containing(string message, params object[] args) + { + foreach (Logger logger in the_loggers) + { + logger.log_a_warning_event_containing(message, args); + } + } + + public void log_an_error_event_containing(string message, params object[] args) + { + foreach (Logger logger in the_loggers) + { + logger.log_an_error_event_containing(message, args); + } + } + + public void log_a_fatal_event_containing(string message, params object[] args) + { + foreach (Logger logger in the_loggers) + { + logger.log_a_fatal_event_containing(message, args); + } + } + + public object underlying_type + { + get { return the_loggers; } + } + } } \ No newline at end of file diff --git a/product/roundhouse/infrastructure/logging/custom/MultipleLoggerLogFactory.cs b/product/roundhouse.core/infrastructure/logging/custom/MultipleLoggerLogFactory.cs similarity index 96% rename from product/roundhouse/infrastructure/logging/custom/MultipleLoggerLogFactory.cs rename to product/roundhouse.core/infrastructure/logging/custom/MultipleLoggerLogFactory.cs index 44750267..c46b9a12 100644 --- a/product/roundhouse/infrastructure/logging/custom/MultipleLoggerLogFactory.cs +++ b/product/roundhouse.core/infrastructure/logging/custom/MultipleLoggerLogFactory.cs @@ -1,14 +1,14 @@ -namespace roundhouse.infrastructure.logging.custom -{ - using System; - using containers; - - public sealed class MultipleLoggerLogFactory : LogFactory - { - public Logger create_logger_bound_to(Object type) - { - return Container.get_an_instance_of(); - } - - } +namespace roundhouse.infrastructure.logging.custom +{ + using System; + using containers; + + public sealed class MultipleLoggerLogFactory : LogFactory + { + public Logger create_logger_bound_to(Object type) + { + return Container.get_an_instance_of(); + } + + } } \ No newline at end of file diff --git a/product/roundhouse/infrastructure/logging/custom/TraceLogger.cs b/product/roundhouse.core/infrastructure/logging/custom/TraceLogger.cs similarity index 96% rename from product/roundhouse/infrastructure/logging/custom/TraceLogger.cs rename to product/roundhouse.core/infrastructure/logging/custom/TraceLogger.cs index 53a823dc..4380fa10 100644 --- a/product/roundhouse/infrastructure/logging/custom/TraceLogger.cs +++ b/product/roundhouse.core/infrastructure/logging/custom/TraceLogger.cs @@ -1,51 +1,51 @@ -using System.Diagnostics; - -namespace roundhouse.infrastructure.logging.custom -{ - public class TraceLogger : Logger - { - private readonly bool debugging; - - public TraceLogger() : this(false) { } - - public TraceLogger(bool debugging) - { - this.debugging = debugging; - } - - private void log_message(string message) - { - Trace.WriteLine(message); - } - - public void log_a_debug_event_containing(string message, params object[] args) - { - if (debugging) log_message("[DEBUG]: " + string.Format(message, args)); - } - - public void log_an_info_event_containing(string message, params object[] args) - { - log_message("[INFO]: " + string.Format(message, args)); - } - - public void log_a_warning_event_containing(string message, params object[] args) - { - log_message("[WARN]: " + string.Format(message, args)); - } - - public void log_an_error_event_containing(string message, params object[] args) - { - log_message("[ERROR]: " + string.Format(message, args)); - } - - public void log_a_fatal_event_containing(string message, params object[] args) - { - log_message("[FATAL]: " + string.Format(message, args)); - } - - public object underlying_type - { - get { return new object(); } - } - } +using System.Diagnostics; + +namespace roundhouse.infrastructure.logging.custom +{ + public class TraceLogger : Logger + { + private readonly bool debugging; + + public TraceLogger() : this(false) { } + + public TraceLogger(bool debugging) + { + this.debugging = debugging; + } + + private void log_message(string message) + { + Trace.WriteLine(message); + } + + public void log_a_debug_event_containing(string message, params object[] args) + { + if (debugging) log_message("[DEBUG]: " + string.Format(message, args)); + } + + public void log_an_info_event_containing(string message, params object[] args) + { + log_message("[INFO]: " + string.Format(message, args)); + } + + public void log_a_warning_event_containing(string message, params object[] args) + { + log_message("[WARN]: " + string.Format(message, args)); + } + + public void log_an_error_event_containing(string message, params object[] args) + { + log_message("[ERROR]: " + string.Format(message, args)); + } + + public void log_a_fatal_event_containing(string message, params object[] args) + { + log_message("[FATAL]: " + string.Format(message, args)); + } + + public object underlying_type + { + get { return new object(); } + } + } } \ No newline at end of file diff --git a/product/roundhouse/infrastructure/persistence/AuditEventListener.cs b/product/roundhouse.core/infrastructure/persistence/AuditEventListener.cs similarity index 97% rename from product/roundhouse/infrastructure/persistence/AuditEventListener.cs rename to product/roundhouse.core/infrastructure/persistence/AuditEventListener.cs index 48655696..24f381a2 100644 --- a/product/roundhouse/infrastructure/persistence/AuditEventListener.cs +++ b/product/roundhouse.core/infrastructure/persistence/AuditEventListener.cs @@ -1,93 +1,93 @@ -using System.Threading; -using System.Threading.Tasks; - -namespace roundhouse.infrastructure.persistence -{ - using System; - using System.Security.Principal; - using NHibernate.Event; - using NHibernate.Persister.Entity; - using roundhouse.model; - - public class AuditEventListener : IPreInsertEventListener, IPreUpdateEventListener - { - public string get_identity() - { - string identity_of_updater = null; - try - { - identity_of_updater = WindowsIdentity.GetCurrent().Name; - } - catch (PlatformNotSupportedException) - { - identity_of_updater = Environment.UserName; - } - - return identity_of_updater; - } - - //http://ayende.com/Blog/archive/2009/04/29/nhibernate-ipreupdateeventlistener-amp-ipreinserteventlistener.aspx - public async Task OnPreInsertAsync(PreInsertEvent @event, CancellationToken cancellationToken) - { - return await Task.FromResult(OnPreInsert(@event)); - } - - public bool OnPreInsert(PreInsertEvent event_item) - { - Auditable audit = event_item.Entity as Auditable; - if (audit == null) - { - return false; - } - - DateTime? entry_date = DateTime.Now; - DateTime? modified_date = DateTime.Now; - string identity_of_updater = get_identity(); - - store(event_item.Persister, event_item.State, "entry_date", entry_date); - store(event_item.Persister, event_item.State, "modified_date", modified_date); - store(event_item.Persister, event_item.State, "entered_by", identity_of_updater); - audit.entry_date = entry_date; - audit.modified_date = modified_date; - audit.entered_by = identity_of_updater; - - return false; - } - - public async Task OnPreUpdateAsync(PreUpdateEvent @event, CancellationToken cancellationToken) - { - return await Task.FromResult(OnPreUpdate(@event)); - } - - public bool OnPreUpdate(PreUpdateEvent event_item) - { - Auditable audit = event_item.Entity as Auditable; - if (audit == null) - { - return false; - } - - DateTime? modified_date = DateTime.Now; - string identity_of_updater = get_identity(); - - store(event_item.Persister, event_item.State, "modified_date", modified_date); - store(event_item.Persister, event_item.State, "entered_by", identity_of_updater); - audit.modified_date = modified_date; - audit.entered_by = identity_of_updater; - - //insert auditing object here - - return false; - } - - public void store(IEntityPersister persister, object[] state, string property_name, object value) - { - int index = Array.IndexOf(persister.PropertyNames, property_name); - if (index == -1) - { - return; - } - state[index] = value; - } - } +using System.Threading; +using System.Threading.Tasks; + +namespace roundhouse.infrastructure.persistence +{ + using System; + using System.Security.Principal; + using NHibernate.Event; + using NHibernate.Persister.Entity; + using roundhouse.model; + + public class AuditEventListener : IPreInsertEventListener, IPreUpdateEventListener + { + public string get_identity() + { + string identity_of_updater = null; + try + { + identity_of_updater = WindowsIdentity.GetCurrent().Name; + } + catch (PlatformNotSupportedException) + { + identity_of_updater = Environment.UserName; + } + + return identity_of_updater; + } + + //http://ayende.com/Blog/archive/2009/04/29/nhibernate-ipreupdateeventlistener-amp-ipreinserteventlistener.aspx + public async Task OnPreInsertAsync(PreInsertEvent @event, CancellationToken cancellationToken) + { + return await Task.FromResult(OnPreInsert(@event)); + } + + public bool OnPreInsert(PreInsertEvent event_item) + { + Auditable audit = event_item.Entity as Auditable; + if (audit == null) + { + return false; + } + + DateTime? entry_date = DateTime.Now; + DateTime? modified_date = DateTime.Now; + string identity_of_updater = get_identity(); + + store(event_item.Persister, event_item.State, "entry_date", entry_date); + store(event_item.Persister, event_item.State, "modified_date", modified_date); + store(event_item.Persister, event_item.State, "entered_by", identity_of_updater); + audit.entry_date = entry_date; + audit.modified_date = modified_date; + audit.entered_by = identity_of_updater; + + return false; + } + + public async Task OnPreUpdateAsync(PreUpdateEvent @event, CancellationToken cancellationToken) + { + return await Task.FromResult(OnPreUpdate(@event)); + } + + public bool OnPreUpdate(PreUpdateEvent event_item) + { + Auditable audit = event_item.Entity as Auditable; + if (audit == null) + { + return false; + } + + DateTime? modified_date = DateTime.Now; + string identity_of_updater = get_identity(); + + store(event_item.Persister, event_item.State, "modified_date", modified_date); + store(event_item.Persister, event_item.State, "entered_by", identity_of_updater); + audit.modified_date = modified_date; + audit.entered_by = identity_of_updater; + + //insert auditing object here + + return false; + } + + public void store(IEntityPersister persister, object[] state, string property_name, object value) + { + int index = Array.IndexOf(persister.PropertyNames, property_name); + if (index == -1) + { + return; + } + state[index] = value; + } + } } \ No newline at end of file diff --git a/product/roundhouse/infrastructure/persistence/DifferencingNHibernateSessionFactory.cs b/product/roundhouse.core/infrastructure/persistence/DifferencingNHibernateSessionFactory.cs similarity index 98% rename from product/roundhouse/infrastructure/persistence/DifferencingNHibernateSessionFactory.cs rename to product/roundhouse.core/infrastructure/persistence/DifferencingNHibernateSessionFactory.cs index 0f0bbf5d..3338fa31 100644 --- a/product/roundhouse/infrastructure/persistence/DifferencingNHibernateSessionFactory.cs +++ b/product/roundhouse.core/infrastructure/persistence/DifferencingNHibernateSessionFactory.cs @@ -1,92 +1,92 @@ -//namespace roundhouse.infrastructure.persistence -//{ -// using System; -// using System.Reflection; -// using FluentNHibernate.Cfg; -// using FluentNHibernate.Cfg.Db; -// using NHibernate; -// using NHibernate.Cfg; -// using System.Linq; - -// public class DifferencingNHibernateSessionFactory -// { -// private const string proxy_factory = NHibernate.Cfg.Environment.ProxyFactoryFactoryClass; -// private static bool is_merged = true; - -// public static ISessionFactory build_session_factory(string db_name, Assembly mappings_assembly, Assembly conventions_assembly, Action additional_function) -// { -// if (conventions_assembly == null) conventions_assembly = mappings_assembly; -// if (additional_function == null) additional_function = no_operation; - -// return Fluently.Configure() -// .Database(MsSqlConfiguration.MsSql2008.ConnectionString(c => c.Server("(local)").Database(db_name).TrustedConnection())) -// .Mappings(m => -// { -// m.HbmMappings.AddFromAssembly(mappings_assembly); -// GetMappingsFromExternalAssemblies(m, mappings_assembly, conventions_assembly); -// }) -// .ExposeConfiguration(additional_function) -// .BuildSessionFactory(); -// } - -// /// -// /// This loads up FluentNHibernate from the referenced assembly to get the right thing loaded into the conventions - hacky hackity hack hack hack...hack -// /// This crap will get the right ones, but will not load them. -// /// -// /// -// /// -// /// -// /// -// public static FluentMappingsContainer GetMappingsFromExternalAssemblies(MappingConfiguration config, Assembly mappings_assembly, Assembly conventions_assembly) -// { -// var mappings = config.FluentMappings; -// var conventions = mappings.Conventions; -// var nh_assembly = Assembly.ReflectionOnlyLoadFrom("NHibernate.dll"); -// var fluent_assembly = Assembly.Load("FluentNHibernate"); -// //var fluent_assembly = Assembly.ReflectionOnlyLoadFrom("FluentNHibernate.dll"); - -// // mappings -// // source.GetTypes() -// //.Where(x => IsMappingOf(x) || -// // IsMappingOf(x) || -// // IsMappingOf(x) || -// // IsMappingOf(x)) -// //.Each(Add); -// //ISmapping of: return !type.IsGenericType && typeof(T).IsAssignableFrom(type); - -// var IMappingProvider = fluent_assembly.GetTypes().Where(x => x.IsInterface && x.ToString().Contains("FluentNHibernate.IMappingProvider")).First(); -// var IIndeterminateSubclassMappingProvider = fluent_assembly.GetTypes().Where(x => x.IsInterface && x.ToString().Contains("FluentNHibernate.Mapping.Providers.IIndeterminateSubclassMappingProvider")).First(); -// var IExternalComponentMappingProvider = fluent_assembly.GetTypes().Where(x => x.IsInterface && x.ToString().Contains("FluentNHibernate.Mapping.Providers.IExternalComponentMappingProvider")).First(); -// var IFilterDefinition = fluent_assembly.GetTypes().Where(x => x.IsInterface && x.ToString().Contains("FluentNHibernate.Mapping.IFilterDefinition")).First(); - -// foreach (var mappingType in mappings_assembly.GetTypes().Where(x => !x.IsGenericType)) -// { -// if (IMappingProvider.IsAssignableFrom(mappingType) -// || IIndeterminateSubclassMappingProvider.IsAssignableFrom(mappingType) -// || IExternalComponentMappingProvider.IsAssignableFrom(mappingType) -// || IFilterDefinition.IsAssignableFrom(mappingType) -// ) -// { -// mappings.Add(mappingType); -// } -// } - -// //conventions if (type.IsAbstract || type.IsGenericType || !typeof(IConvention).IsAssignableFrom(type)) continue; (else add)!) -// var IConvention = fluent_assembly.GetTypes().Where(x => x.IsInterface && x.ToString().Contains("FluentNHibernate.Conventions.IConvention")).First(); -// foreach (var conventionType in mappings_assembly.GetTypes().Where(x => !x.IsGenericType && !x.IsAbstract)) -// { -// if (IMappingProvider.IsAssignableFrom(conventionType)) -// { -// conventions.Add(conventionType); -// } -// } - -// return mappings; -// //config.FluentMappings.AddFromAssembly(mappings_assembly) -// // .Conventions.AddAssembly(conventions_assembly); -// } - -// private static void no_operation(Configuration cfg) { } - -// } +//namespace roundhouse.infrastructure.persistence +//{ +// using System; +// using System.Reflection; +// using FluentNHibernate.Cfg; +// using FluentNHibernate.Cfg.Db; +// using NHibernate; +// using NHibernate.Cfg; +// using System.Linq; + +// public class DifferencingNHibernateSessionFactory +// { +// private const string proxy_factory = NHibernate.Cfg.Environment.ProxyFactoryFactoryClass; +// private static bool is_merged = true; + +// public static ISessionFactory build_session_factory(string db_name, Assembly mappings_assembly, Assembly conventions_assembly, Action additional_function) +// { +// if (conventions_assembly == null) conventions_assembly = mappings_assembly; +// if (additional_function == null) additional_function = no_operation; + +// return Fluently.Configure() +// .Database(MsSqlConfiguration.MsSql2008.ConnectionString(c => c.Server("(local)").Database(db_name).TrustedConnection())) +// .Mappings(m => +// { +// m.HbmMappings.AddFromAssembly(mappings_assembly); +// GetMappingsFromExternalAssemblies(m, mappings_assembly, conventions_assembly); +// }) +// .ExposeConfiguration(additional_function) +// .BuildSessionFactory(); +// } + +// /// +// /// This loads up FluentNHibernate from the referenced assembly to get the right thing loaded into the conventions - hacky hackity hack hack hack...hack +// /// This crap will get the right ones, but will not load them. +// /// +// /// +// /// +// /// +// /// +// public static FluentMappingsContainer GetMappingsFromExternalAssemblies(MappingConfiguration config, Assembly mappings_assembly, Assembly conventions_assembly) +// { +// var mappings = config.FluentMappings; +// var conventions = mappings.Conventions; +// var nh_assembly = Assembly.ReflectionOnlyLoadFrom("NHibernate.dll"); +// var fluent_assembly = Assembly.Load("FluentNHibernate"); +// //var fluent_assembly = Assembly.ReflectionOnlyLoadFrom("FluentNHibernate.dll"); + +// // mappings +// // source.GetTypes() +// //.Where(x => IsMappingOf(x) || +// // IsMappingOf(x) || +// // IsMappingOf(x) || +// // IsMappingOf(x)) +// //.Each(Add); +// //ISmapping of: return !type.IsGenericType && typeof(T).IsAssignableFrom(type); + +// var IMappingProvider = fluent_assembly.GetTypes().Where(x => x.IsInterface && x.ToString().Contains("FluentNHibernate.IMappingProvider")).First(); +// var IIndeterminateSubclassMappingProvider = fluent_assembly.GetTypes().Where(x => x.IsInterface && x.ToString().Contains("FluentNHibernate.Mapping.Providers.IIndeterminateSubclassMappingProvider")).First(); +// var IExternalComponentMappingProvider = fluent_assembly.GetTypes().Where(x => x.IsInterface && x.ToString().Contains("FluentNHibernate.Mapping.Providers.IExternalComponentMappingProvider")).First(); +// var IFilterDefinition = fluent_assembly.GetTypes().Where(x => x.IsInterface && x.ToString().Contains("FluentNHibernate.Mapping.IFilterDefinition")).First(); + +// foreach (var mappingType in mappings_assembly.GetTypes().Where(x => !x.IsGenericType)) +// { +// if (IMappingProvider.IsAssignableFrom(mappingType) +// || IIndeterminateSubclassMappingProvider.IsAssignableFrom(mappingType) +// || IExternalComponentMappingProvider.IsAssignableFrom(mappingType) +// || IFilterDefinition.IsAssignableFrom(mappingType) +// ) +// { +// mappings.Add(mappingType); +// } +// } + +// //conventions if (type.IsAbstract || type.IsGenericType || !typeof(IConvention).IsAssignableFrom(type)) continue; (else add)!) +// var IConvention = fluent_assembly.GetTypes().Where(x => x.IsInterface && x.ToString().Contains("FluentNHibernate.Conventions.IConvention")).First(); +// foreach (var conventionType in mappings_assembly.GetTypes().Where(x => !x.IsGenericType && !x.IsAbstract)) +// { +// if (IMappingProvider.IsAssignableFrom(conventionType)) +// { +// conventions.Add(conventionType); +// } +// } + +// return mappings; +// //config.FluentMappings.AddFromAssembly(mappings_assembly) +// // .Conventions.AddAssembly(conventions_assembly); +// } + +// private static void no_operation(Configuration cfg) { } + +// } //} \ No newline at end of file diff --git a/product/roundhouse/infrastructure/persistence/IRepository.cs b/product/roundhouse.core/infrastructure/persistence/IRepository.cs similarity index 97% rename from product/roundhouse/infrastructure/persistence/IRepository.cs rename to product/roundhouse.core/infrastructure/persistence/IRepository.cs index 248f6905..44c082e2 100644 --- a/product/roundhouse/infrastructure/persistence/IRepository.cs +++ b/product/roundhouse.core/infrastructure/persistence/IRepository.cs @@ -1,26 +1,26 @@ -namespace roundhouse.infrastructure.persistence -{ - using System.Collections.Generic; - using NHibernate; - using NHibernate.Cfg; - using NHibernate.Criterion; - - public interface IRepository - { - void start(bool using_transaction); - void rollback(); - void finish(); - - IList get_all() where T : class; - IList get_with_criteria(QueryOver detachedCriteria) where T : class; - IList get_transformation_with_criteria(QueryOver detachedCriteria) where T : class; - void save_or_update(IList list) where T : class; - void save_or_update(T item) where T : class; - void delete(IList list) where T : class; - - ITransaction transaction { get;} - ISessionFactory session_factory { get; } - Configuration nhibernate_configuration { get; } - //string connection_string { get; } - } +namespace roundhouse.infrastructure.persistence +{ + using System.Collections.Generic; + using NHibernate; + using NHibernate.Cfg; + using NHibernate.Criterion; + + public interface IRepository + { + void start(bool using_transaction); + void rollback(); + void finish(); + + IList get_all() where T : class; + IList get_with_criteria(QueryOver detachedCriteria) where T : class; + IList get_transformation_with_criteria(QueryOver detachedCriteria) where T : class; + void save_or_update(IList list) where T : class; + void save_or_update(T item) where T : class; + void delete(IList list) where T : class; + + ITransaction transaction { get;} + ISessionFactory session_factory { get; } + Configuration nhibernate_configuration { get; } + //string connection_string { get; } + } } \ No newline at end of file diff --git a/product/roundhouse/infrastructure/persistence/NHibernateSessionFactoryBuilder.cs b/product/roundhouse.core/infrastructure/persistence/NHibernateSessionFactoryBuilder.cs similarity index 98% rename from product/roundhouse/infrastructure/persistence/NHibernateSessionFactoryBuilder.cs rename to product/roundhouse.core/infrastructure/persistence/NHibernateSessionFactoryBuilder.cs index cf0b1cde..814e1898 100644 --- a/product/roundhouse/infrastructure/persistence/NHibernateSessionFactoryBuilder.cs +++ b/product/roundhouse.core/infrastructure/persistence/NHibernateSessionFactoryBuilder.cs @@ -1,124 +1,124 @@ -namespace roundhouse.infrastructure.persistence -{ - using System; - using System.Collections.Generic; - using System.Globalization; - using System.Reflection; - using app; - using FluentNHibernate.Cfg; - using FluentNHibernate.Cfg.Db; - using loaders; - using logging; - using NHibernate; - using NHibernate.Cfg; - using NHibernate.Event; - - public class NHibernateSessionFactoryBuilder - { - private readonly ConfigurationPropertyHolder configuration_holder; - private readonly Dictionary> func_dictionary; - //private const string proxy_factory = Environment.ProxyFactoryFactoryClass; - - public NHibernateSessionFactoryBuilder(ConfigurationPropertyHolder config) - { - configuration_holder = config; - func_dictionary = new Dictionary>(); - func_dictionary.Add("roundhouse.databases.sqlserver.SqlServerDatabase, roundhouse.databases.sqlserver", - () => MsSqlConfiguration.MsSql2005.ConnectionString(configuration_holder.ConnectionString)); - func_dictionary.Add("roundhouse.databases.sqlserver2000.SqlServerDatabase, roundhouse.databases.sqlserver2000", - () => MsSqlConfiguration.MsSql2000.ConnectionString(configuration_holder.ConnectionString)); - func_dictionary.Add("roundhouse.databases.sqlserverce.SqlServerCEDatabase, roundhouse.databases.sqlserverce", - () => MsSqlCeConfiguration.Standard.ConnectionString(configuration_holder.ConnectionString)); - func_dictionary.Add("roundhouse.databases.mysql.MySqlDatabase, roundhouse.databases.mysql", - () => MySQLConfiguration.Standard.ConnectionString(configuration_holder.ConnectionString)); - func_dictionary.Add("roundhouse.databases.oracle.OracleDatabase, roundhouse.databases.oracle", - () => OracleClientConfiguration.Oracle9.ConnectionString(configuration_holder.ConnectionString) - .Driver("roundhouse.databases.oracle.RoundhousEOracleDriver, roundhouse.databases.oracle")); - func_dictionary.Add("roundhouse.databases.access.AccessDatabase, roundhouse.databases.access", - () => JetDriverConfiguration.Standard.ConnectionString(configuration_holder.ConnectionString)); - func_dictionary.Add("roundhouse.databases.sqlite.SqliteDatabase, roundhouse.databases.sqlite", - () => SQLiteConfiguration.Standard.ConnectionString(configuration_holder.ConnectionString)); - func_dictionary.Add("roundhouse.databases.postgresql.PostgreSQLDatabase, roundhouse.databases.postgresql", - () => PostgreSQLConfiguration.Standard.ConnectionString(configuration_holder.ConnectionString)); - // merged - string merged_assembly_name = ApplicationParameters.get_merged_assembly_name(); - func_dictionary.Add("roundhouse.databases.sqlserver.SqlServerDatabase, " + merged_assembly_name, - () => MsSqlConfiguration.MsSql2005.ConnectionString(configuration_holder.ConnectionString)); - func_dictionary.Add("roundhouse.databases.sqlserver2000.SqlServerDatabase, " + merged_assembly_name, - () => MsSqlConfiguration.MsSql2000.ConnectionString(configuration_holder.ConnectionString)); - func_dictionary.Add("roundhouse.databases.sqlserverce.SqlServerCEDatabase, " + merged_assembly_name, - () => MsSqlCeConfiguration.Standard.ConnectionString(configuration_holder.ConnectionString)); - func_dictionary.Add("roundhouse.databases.mysql.MySqlDatabase, " + merged_assembly_name, - () => MySQLConfiguration.Standard.ConnectionString(configuration_holder.ConnectionString)); - func_dictionary.Add("roundhouse.databases.oracle.OracleDatabase, " + merged_assembly_name, - () => OracleClientConfiguration.Oracle9.ConnectionString(configuration_holder.ConnectionString) - .Driver("roundhouse.databases.oracle.RoundhousEOracleDriver, " + merged_assembly_name)); - func_dictionary.Add("roundhouse.databases.access.AccessDatabase, " + merged_assembly_name, - () => JetDriverConfiguration.Standard.ConnectionString(configuration_holder.ConnectionString)); - func_dictionary.Add("roundhouse.databases.sqlite.SqliteDatabase, " + merged_assembly_name, - () => SQLiteConfiguration.Standard.ConnectionString(configuration_holder.ConnectionString)); - func_dictionary.Add("roundhouse.databases.postgresql.PostgreSQLDatabase, " + merged_assembly_name, - () => PostgreSQLConfiguration.Standard.ConnectionString(configuration_holder.ConnectionString)); - } - - public ISessionFactory build_session_factory() - { - return build_session_factory(no_operation); - } - - public ISessionFactory build_session_factory(Action additional_function) - { - string top_namespace = configuration_holder.DatabaseType.Substring(0, configuration_holder.DatabaseType.IndexOf(',')); - top_namespace = top_namespace.Substring(0, top_namespace.LastIndexOf('.')); - string assembly_name = configuration_holder.DatabaseType.Substring(configuration_holder.DatabaseType.IndexOf(',') + 1); - - try - { - string key = configuration_holder.DatabaseType.Substring(0, configuration_holder.DatabaseType.IndexOf(',')) + ", " + - ApplicationParameters.get_merged_assembly_name(); - return build_session_factory(func_dictionary[key](), Assembly.GetExecutingAssembly(),top_namespace, additional_function); - //return build_session_factory(func_dictionary[key](), DefaultAssemblyLoader.load_assembly(ApplicationParameters.get_merged_assembly_name()), - //top_namespace, additional_function); - } - catch (Exception ex) - { - // Changed from warning to debug. I may not be using session factory and this warning just adds noise. - Log.bound_to(this).log_a_debug_event_containing("Had an error building session factory from merged, attempting unmerged. The error:{0}{1}",System.Environment.NewLine,ex.ToString()); - return build_session_factory(func_dictionary[configuration_holder.DatabaseType](), DefaultAssemblyLoader.load_assembly(assembly_name), - top_namespace, additional_function); - } - } - - public ISessionFactory build_session_factory(IPersistenceConfigurer db_configuration, Assembly assembly, string top_namespace, - Action additional_function) - { - Log.bound_to(this).log_a_debug_event_containing("Building Session Factory"); - var config = Fluently.Configure() - .Database(db_configuration) - .Mappings(m => - { - m.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)); - //.Conventions.AddAssembly(assembly); - //m.HbmMappings.AddFromAssembly(assembly); - }) - .ExposeConfiguration(cfg => - { - // FIXME: Quick workaround for MySQL's defect with reserved words auto-quoting http://216.121.112.228/browse/NH-1906 - //TODO:please verify fixed Diyan cfg.Properties["hbm2ddl.keywords"] = "none"; - - cfg.SetListener(ListenerType.PreInsert, new AuditEventListener()); - cfg.SetListener(ListenerType.PreUpdate, new AuditEventListener()); - cfg.SetProperty("command_timeout", TimeSpan.FromMinutes(5).TotalSeconds.ToString(CultureInfo.InvariantCulture)); - }) - .ExposeConfiguration(additional_function); - - return config.BuildSessionFactory(); - } - - public NHibernateSessionFactoryBuilder() { } - - private static void no_operation(Configuration cfg) { } - } +namespace roundhouse.infrastructure.persistence +{ + using System; + using System.Collections.Generic; + using System.Globalization; + using System.Reflection; + using app; + using FluentNHibernate.Cfg; + using FluentNHibernate.Cfg.Db; + using loaders; + using logging; + using NHibernate; + using NHibernate.Cfg; + using NHibernate.Event; + + public class NHibernateSessionFactoryBuilder + { + private readonly ConfigurationPropertyHolder configuration_holder; + private readonly Dictionary> func_dictionary; + //private const string proxy_factory = Environment.ProxyFactoryFactoryClass; + + public NHibernateSessionFactoryBuilder(ConfigurationPropertyHolder config) + { + configuration_holder = config; + func_dictionary = new Dictionary>(); + func_dictionary.Add("roundhouse.databases.sqlserver.SqlServerDatabase, roundhouse.databases.sqlserver", + () => MsSqlConfiguration.MsSql2005.ConnectionString(configuration_holder.ConnectionString)); + func_dictionary.Add("roundhouse.databases.sqlserver2000.SqlServerDatabase, roundhouse.databases.sqlserver2000", + () => MsSqlConfiguration.MsSql2000.ConnectionString(configuration_holder.ConnectionString)); + func_dictionary.Add("roundhouse.databases.sqlserverce.SqlServerCEDatabase, roundhouse.databases.sqlserverce", + () => MsSqlCeConfiguration.Standard.ConnectionString(configuration_holder.ConnectionString)); + func_dictionary.Add("roundhouse.databases.mysql.MySqlDatabase, roundhouse.databases.mysql", + () => MySQLConfiguration.Standard.ConnectionString(configuration_holder.ConnectionString)); + func_dictionary.Add("roundhouse.databases.oracle.OracleDatabase, roundhouse.databases.oracle", + () => OracleClientConfiguration.Oracle9.ConnectionString(configuration_holder.ConnectionString) + .Driver("roundhouse.databases.oracle.RoundhousEOracleDriver, roundhouse.databases.oracle")); + func_dictionary.Add("roundhouse.databases.access.AccessDatabase, roundhouse.databases.access", + () => JetDriverConfiguration.Standard.ConnectionString(configuration_holder.ConnectionString)); + func_dictionary.Add("roundhouse.databases.sqlite.SqliteDatabase, roundhouse.databases.sqlite", + () => SQLiteConfiguration.Standard.ConnectionString(configuration_holder.ConnectionString)); + func_dictionary.Add("roundhouse.databases.postgresql.PostgreSQLDatabase, roundhouse.databases.postgresql", + () => PostgreSQLConfiguration.Standard.ConnectionString(configuration_holder.ConnectionString)); + // merged + string merged_assembly_name = ApplicationParameters.get_merged_assembly_name(); + func_dictionary.Add("roundhouse.databases.sqlserver.SqlServerDatabase, " + merged_assembly_name, + () => MsSqlConfiguration.MsSql2005.ConnectionString(configuration_holder.ConnectionString)); + func_dictionary.Add("roundhouse.databases.sqlserver2000.SqlServerDatabase, " + merged_assembly_name, + () => MsSqlConfiguration.MsSql2000.ConnectionString(configuration_holder.ConnectionString)); + func_dictionary.Add("roundhouse.databases.sqlserverce.SqlServerCEDatabase, " + merged_assembly_name, + () => MsSqlCeConfiguration.Standard.ConnectionString(configuration_holder.ConnectionString)); + func_dictionary.Add("roundhouse.databases.mysql.MySqlDatabase, " + merged_assembly_name, + () => MySQLConfiguration.Standard.ConnectionString(configuration_holder.ConnectionString)); + func_dictionary.Add("roundhouse.databases.oracle.OracleDatabase, " + merged_assembly_name, + () => OracleClientConfiguration.Oracle9.ConnectionString(configuration_holder.ConnectionString) + .Driver("roundhouse.databases.oracle.RoundhousEOracleDriver, " + merged_assembly_name)); + func_dictionary.Add("roundhouse.databases.access.AccessDatabase, " + merged_assembly_name, + () => JetDriverConfiguration.Standard.ConnectionString(configuration_holder.ConnectionString)); + func_dictionary.Add("roundhouse.databases.sqlite.SqliteDatabase, " + merged_assembly_name, + () => SQLiteConfiguration.Standard.ConnectionString(configuration_holder.ConnectionString)); + func_dictionary.Add("roundhouse.databases.postgresql.PostgreSQLDatabase, " + merged_assembly_name, + () => PostgreSQLConfiguration.Standard.ConnectionString(configuration_holder.ConnectionString)); + } + + public ISessionFactory build_session_factory() + { + return build_session_factory(no_operation); + } + + public ISessionFactory build_session_factory(Action additional_function) + { + string top_namespace = configuration_holder.DatabaseType.Substring(0, configuration_holder.DatabaseType.IndexOf(',')); + top_namespace = top_namespace.Substring(0, top_namespace.LastIndexOf('.')); + string assembly_name = configuration_holder.DatabaseType.Substring(configuration_holder.DatabaseType.IndexOf(',') + 1); + + try + { + string key = configuration_holder.DatabaseType.Substring(0, configuration_holder.DatabaseType.IndexOf(',')) + ", " + + ApplicationParameters.get_merged_assembly_name(); + return build_session_factory(func_dictionary[key](), Assembly.GetExecutingAssembly(),top_namespace, additional_function); + //return build_session_factory(func_dictionary[key](), DefaultAssemblyLoader.load_assembly(ApplicationParameters.get_merged_assembly_name()), + //top_namespace, additional_function); + } + catch (Exception ex) + { + // Changed from warning to debug. I may not be using session factory and this warning just adds noise. + Log.bound_to(this).log_a_debug_event_containing("Had an error building session factory from merged, attempting unmerged. The error:{0}{1}",System.Environment.NewLine,ex.ToString()); + return build_session_factory(func_dictionary[configuration_holder.DatabaseType](), DefaultAssemblyLoader.load_assembly(assembly_name), + top_namespace, additional_function); + } + } + + public ISessionFactory build_session_factory(IPersistenceConfigurer db_configuration, Assembly assembly, string top_namespace, + Action additional_function) + { + Log.bound_to(this).log_a_debug_event_containing("Building Session Factory"); + var config = Fluently.Configure() + .Database(db_configuration) + .Mappings(m => + { + m.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)); + //.Conventions.AddAssembly(assembly); + //m.HbmMappings.AddFromAssembly(assembly); + }) + .ExposeConfiguration(cfg => + { + // FIXME: Quick workaround for MySQL's defect with reserved words auto-quoting http://216.121.112.228/browse/NH-1906 + //TODO:please verify fixed Diyan cfg.Properties["hbm2ddl.keywords"] = "none"; + + cfg.SetListener(ListenerType.PreInsert, new AuditEventListener()); + cfg.SetListener(ListenerType.PreUpdate, new AuditEventListener()); + cfg.SetProperty("command_timeout", TimeSpan.FromMinutes(5).TotalSeconds.ToString(CultureInfo.InvariantCulture)); + }) + .ExposeConfiguration(additional_function); + + return config.BuildSessionFactory(); + } + + public NHibernateSessionFactoryBuilder() { } + + private static void no_operation(Configuration cfg) { } + } } \ No newline at end of file diff --git a/product/roundhouse/infrastructure/persistence/Repository.cs b/product/roundhouse.core/infrastructure/persistence/Repository.cs similarity index 97% rename from product/roundhouse/infrastructure/persistence/Repository.cs rename to product/roundhouse.core/infrastructure/persistence/Repository.cs index 10d32148..81eb85ce 100644 --- a/product/roundhouse/infrastructure/persistence/Repository.cs +++ b/product/roundhouse.core/infrastructure/persistence/Repository.cs @@ -1,226 +1,226 @@ -namespace roundhouse.infrastructure.persistence -{ - using System; - using System.Collections.Generic; - using extensions; - using logging; - using NHibernate; - using NHibernate.Cfg; - using NHibernate.Criterion; - using NHibernate.Transform; - - public sealed class Repository : IRepository - { - private bool running_in_a_transaction; - - public ISessionFactory session_factory { get; private set; } - public Configuration nhibernate_configuration { get; private set; } - public ITransaction transaction { get; private set; } - private ISession session - { - get; - set; - } - - public Repository(ISessionFactory session_factory, Configuration cfg) - { - this.session_factory = session_factory; - this.nhibernate_configuration = cfg; - if (session_factory == null) - { - throw new ApplicationException("Repository cannot do any with a null session factory. Please provide a session factory."); - } - } - - public void start(bool using_transaction) - { - running_in_a_transaction = using_transaction; - session = session_factory.OpenSession(); - if (using_transaction) - { - transaction = session.BeginTransaction(); - } - } - - public void rollback() - { - if (running_in_a_transaction) - { - transaction.Rollback(); - } - running_in_a_transaction = false; - - finish(); - } - - public void finish() - { - if (session != null && session.IsOpen) - { - if (running_in_a_transaction) - { - transaction.Commit(); - } - - if (session == null) return; - - session.Close(); - session.Dispose(); - - } - session = null; - } - - public IList get_all() where T : class - { - IList list; - - using (ensure_session_started()) - { - IQueryOver criteria = session.QueryOver(); - list = criteria.List(); - } - - Log.bound_to(this).log_a_debug_event_containing("Repository found {0} records of type {1}.", list.Count, typeof(T).Name); - - return list; - } - - public IList get_with_criteria(QueryOver detachedCriteria) where T : class - { - if (detachedCriteria == null) - { - Log.bound_to(this).log_a_warning_event_containing("Please ensure you send in a criteria when you want to limit records. Otherwise please consider using GetAll(). Returning empty list."); - return null; - } - - IList list; - - using (ensure_session_started()) - { - IQueryOver criteria = detachedCriteria.GetExecutableQueryOver(session); - list = criteria.List(); - } - - Log.bound_to(this).log_a_debug_event_containing("Repository found {0} records of type {1} with criteria {2}.", list.Count, typeof(T).Name, detachedCriteria.to_string()); - - return list; - } - - public IList get_transformation_with_criteria(QueryOver detachedCriteria) where T : class - { - if (detachedCriteria == null) - { - Log.bound_to(this).log_a_warning_event_containing("Please ensure you send in a criteria when you want to get transformed records. Otherwise please consider using GetAll(). Returning empty list."); - return null; - } - - IList list; - - using (ensure_session_started()) - { - IQueryOver criteria = detachedCriteria.GetExecutableQueryOver(session); - list = criteria - .TransformUsing(Transformers.AliasToBean()) - .List(); - } - - Log.bound_to(this).log_a_debug_event_containing("Repository found {0} records of type {1} with criteria {2}.", list.Count, typeof(T).Name, detachedCriteria.to_string()); - - return list; - } - - public void save_or_update(IList list) where T : class - { - if (list == null || list.Count == 0) - { - Log.bound_to(this).log_a_warning_event_containing("Please ensure you send a non null list of records to save."); - return; - } - Log.bound_to(this).log_a_debug_event_containing("Received {0} records of type {1} marked for save/update.", list.Count, typeof(T).Name); - - using (ensure_session_started()) - { - foreach (T item in list) - { - save_or_update(item); - } - } - - Log.bound_to(this).log_a_debug_event_containing("Saved {0} records of type {1} successfully.", list.Count, typeof(T).Name); - } - - public void save_or_update(T item) where T : class - { - if (item == null) - { - Log.bound_to(this).log_a_warning_event_containing("Please ensure you send a non null record to save."); - return; - } - - using (ensure_session_started()) - { - session.SaveOrUpdate(item); - session.Flush(); - } - - Log.bound_to(this).log_a_debug_event_containing("Saved item of type {0} successfully.", typeof(T).Name); - } - - public void delete(IList list) where T : class - { - if (list == null || list.Count == 0) - { - Log.bound_to(this).log_a_warning_event_containing("Please ensure you send a non null list of records to delete."); - return; - } - - Log.bound_to(this).log_an_info_event_containing("Received {0} records of type {1} marked for deletion.", list.Count, typeof(T).Name); - - using (ensure_session_started()) - { - foreach (T item in list) - { - session.Delete(item); - session.Flush(); - } - } - - Log.bound_to(this).log_an_info_event_containing("Removed {0} records of type {1} successfully.", list.Count, typeof(T).Name); - } - - private IDisposable ensure_session_started() - { - bool running_long_session = session != null; - if (running_long_session) - { - return null; - } - - start(using_transaction: false); - return new Cleanup(finish); - } - - private class Cleanup : IDisposable - { - private readonly Action cleanupAction; - private bool disposed; - - public Cleanup(Action cleanupAction) - { - this.cleanupAction = cleanupAction; - } - - public void Dispose() - { - if (disposed) return; - - disposed = true; - if (cleanupAction != null) - { - cleanupAction(); - } - } - } - } +namespace roundhouse.infrastructure.persistence +{ + using System; + using System.Collections.Generic; + using extensions; + using logging; + using NHibernate; + using NHibernate.Cfg; + using NHibernate.Criterion; + using NHibernate.Transform; + + public sealed class Repository : IRepository + { + private bool running_in_a_transaction; + + public ISessionFactory session_factory { get; private set; } + public Configuration nhibernate_configuration { get; private set; } + public ITransaction transaction { get; private set; } + private ISession session + { + get; + set; + } + + public Repository(ISessionFactory session_factory, Configuration cfg) + { + this.session_factory = session_factory; + this.nhibernate_configuration = cfg; + if (session_factory == null) + { + throw new ApplicationException("Repository cannot do any with a null session factory. Please provide a session factory."); + } + } + + public void start(bool using_transaction) + { + running_in_a_transaction = using_transaction; + session = session_factory.OpenSession(); + if (using_transaction) + { + transaction = session.BeginTransaction(); + } + } + + public void rollback() + { + if (running_in_a_transaction) + { + transaction.Rollback(); + } + running_in_a_transaction = false; + + finish(); + } + + public void finish() + { + if (session != null && session.IsOpen) + { + if (running_in_a_transaction) + { + transaction.Commit(); + } + + if (session == null) return; + + session.Close(); + session.Dispose(); + + } + session = null; + } + + public IList get_all() where T : class + { + IList list; + + using (ensure_session_started()) + { + IQueryOver criteria = session.QueryOver(); + list = criteria.List(); + } + + Log.bound_to(this).log_a_debug_event_containing("Repository found {0} records of type {1}.", list.Count, typeof(T).Name); + + return list; + } + + public IList get_with_criteria(QueryOver detachedCriteria) where T : class + { + if (detachedCriteria == null) + { + Log.bound_to(this).log_a_warning_event_containing("Please ensure you send in a criteria when you want to limit records. Otherwise please consider using GetAll(). Returning empty list."); + return null; + } + + IList list; + + using (ensure_session_started()) + { + IQueryOver criteria = detachedCriteria.GetExecutableQueryOver(session); + list = criteria.List(); + } + + Log.bound_to(this).log_a_debug_event_containing("Repository found {0} records of type {1} with criteria {2}.", list.Count, typeof(T).Name, detachedCriteria.to_string()); + + return list; + } + + public IList get_transformation_with_criteria(QueryOver detachedCriteria) where T : class + { + if (detachedCriteria == null) + { + Log.bound_to(this).log_a_warning_event_containing("Please ensure you send in a criteria when you want to get transformed records. Otherwise please consider using GetAll(). Returning empty list."); + return null; + } + + IList list; + + using (ensure_session_started()) + { + IQueryOver criteria = detachedCriteria.GetExecutableQueryOver(session); + list = criteria + .TransformUsing(Transformers.AliasToBean()) + .List(); + } + + Log.bound_to(this).log_a_debug_event_containing("Repository found {0} records of type {1} with criteria {2}.", list.Count, typeof(T).Name, detachedCriteria.to_string()); + + return list; + } + + public void save_or_update(IList list) where T : class + { + if (list == null || list.Count == 0) + { + Log.bound_to(this).log_a_warning_event_containing("Please ensure you send a non null list of records to save."); + return; + } + Log.bound_to(this).log_a_debug_event_containing("Received {0} records of type {1} marked for save/update.", list.Count, typeof(T).Name); + + using (ensure_session_started()) + { + foreach (T item in list) + { + save_or_update(item); + } + } + + Log.bound_to(this).log_a_debug_event_containing("Saved {0} records of type {1} successfully.", list.Count, typeof(T).Name); + } + + public void save_or_update(T item) where T : class + { + if (item == null) + { + Log.bound_to(this).log_a_warning_event_containing("Please ensure you send a non null record to save."); + return; + } + + using (ensure_session_started()) + { + session.SaveOrUpdate(item); + session.Flush(); + } + + Log.bound_to(this).log_a_debug_event_containing("Saved item of type {0} successfully.", typeof(T).Name); + } + + public void delete(IList list) where T : class + { + if (list == null || list.Count == 0) + { + Log.bound_to(this).log_a_warning_event_containing("Please ensure you send a non null list of records to delete."); + return; + } + + Log.bound_to(this).log_an_info_event_containing("Received {0} records of type {1} marked for deletion.", list.Count, typeof(T).Name); + + using (ensure_session_started()) + { + foreach (T item in list) + { + session.Delete(item); + session.Flush(); + } + } + + Log.bound_to(this).log_an_info_event_containing("Removed {0} records of type {1} successfully.", list.Count, typeof(T).Name); + } + + private IDisposable ensure_session_started() + { + bool running_long_session = session != null; + if (running_long_session) + { + return null; + } + + start(using_transaction: false); + return new Cleanup(finish); + } + + private class Cleanup : IDisposable + { + private readonly Action cleanupAction; + private bool disposed; + + public Cleanup(Action cleanupAction) + { + this.cleanupAction = cleanupAction; + } + + public void Dispose() + { + if (disposed) return; + + disposed = true; + if (cleanupAction != null) + { + cleanupAction(); + } + } + } + } } \ No newline at end of file diff --git a/product/roundhouse/init/Initializer.cs b/product/roundhouse.core/init/Initializer.cs similarity index 97% rename from product/roundhouse/init/Initializer.cs rename to product/roundhouse.core/init/Initializer.cs index 1d3d358c..bd0d38f1 100644 --- a/product/roundhouse/init/Initializer.cs +++ b/product/roundhouse.core/init/Initializer.cs @@ -1,44 +1,44 @@ -namespace roundhouse.init -{ - using System.IO; - using folders; - using infrastructure.app; - - public interface Initializer - { - void Initialize(ConfigurationPropertyHolder properties, string path); - } - - public class FileSystemInitializer : Initializer - { - readonly KnownFolders _knownFolders; - - public FileSystemInitializer(KnownFolders knownFolders) - { - _knownFolders = knownFolders; - } - - public void Initialize(ConfigurationPropertyHolder properties, string path) - { - makeDir(_knownFolders.alter_database); - makeDir(_knownFolders.change_drop); - makeDir(_knownFolders.down); - makeDir(_knownFolders.functions); - makeDir(_knownFolders.indexes); - makeDir(_knownFolders.permissions); - makeDir(_knownFolders.run_after_create_database); - makeDir(_knownFolders.run_after_other_any_time_scripts); - makeDir(_knownFolders.run_before_up); - makeDir(_knownFolders.run_first_after_up); - makeDir(_knownFolders.sprocs); - makeDir(_knownFolders.up); - makeDir(_knownFolders.views); - } - - void makeDir(Folder folder) - { - if (!Directory.Exists(folder.folder_full_path)) - Directory.CreateDirectory(folder.folder_full_path); - } - } +namespace roundhouse.init +{ + using System.IO; + using folders; + using infrastructure.app; + + public interface Initializer + { + void Initialize(ConfigurationPropertyHolder properties, string path); + } + + public class FileSystemInitializer : Initializer + { + readonly KnownFolders _knownFolders; + + public FileSystemInitializer(KnownFolders knownFolders) + { + _knownFolders = knownFolders; + } + + public void Initialize(ConfigurationPropertyHolder properties, string path) + { + makeDir(_knownFolders.alter_database); + makeDir(_knownFolders.change_drop); + makeDir(_knownFolders.down); + makeDir(_knownFolders.functions); + makeDir(_knownFolders.indexes); + makeDir(_knownFolders.permissions); + makeDir(_knownFolders.run_after_create_database); + makeDir(_knownFolders.run_after_other_any_time_scripts); + makeDir(_knownFolders.run_before_up); + makeDir(_knownFolders.run_first_after_up); + makeDir(_knownFolders.sprocs); + makeDir(_knownFolders.up); + makeDir(_knownFolders.views); + } + + void makeDir(Folder folder) + { + if (!Directory.Exists(folder.folder_full_path)) + Directory.CreateDirectory(folder.folder_full_path); + } + } } \ No newline at end of file diff --git a/product/roundhouse/migrators/DatabaseMigrator.cs b/product/roundhouse.core/migrators/DatabaseMigrator.cs similarity index 97% rename from product/roundhouse/migrators/DatabaseMigrator.cs rename to product/roundhouse.core/migrators/DatabaseMigrator.cs index b45b98a1..1ddd690b 100644 --- a/product/roundhouse/migrators/DatabaseMigrator.cs +++ b/product/roundhouse.core/migrators/DatabaseMigrator.cs @@ -1,28 +1,28 @@ -using roundhouse.databases; -using roundhouse.infrastructure.app; - -namespace roundhouse.migrators -{ - using environments; - - public interface DatabaseMigrator - { - Database database { get; set; } - void initialize_connections(); - void open_admin_connection(); - void close_admin_connection(); - void open_connection(bool with_transaction); - void close_connection(); - void backup_database_if_it_exists(); - bool create_or_restore_database(string custom_create_database_script); - void set_recovery_mode(bool simple); - //void restore_database(string restore_from_path); - void delete_database(); - void run_roundhouse_support_tasks(); - string get_current_version(string repository_path); - long version_the_database(string repository_path, string repository_version); - bool run_sql(string sql_to_run, string script_name, bool run_this_script_once, bool run_this_script_every_time, long version_id, EnvironmentSet migrating_environment_set, string repository_version, string repository_path, ConnectionType connection_type); - //void transfer_to_database_for_changes(); - bool this_script_is_new_or_updated(string script_name, string sql_to_run, EnvironmentSet environment_set); - } +using roundhouse.databases; +using roundhouse.infrastructure.app; + +namespace roundhouse.migrators +{ + using environments; + + public interface DatabaseMigrator + { + Database database { get; set; } + void initialize_connections(); + void open_admin_connection(); + void close_admin_connection(); + void open_connection(bool with_transaction); + void close_connection(); + void backup_database_if_it_exists(); + bool create_or_restore_database(string custom_create_database_script); + void set_recovery_mode(bool simple); + //void restore_database(string restore_from_path); + void delete_database(); + void run_roundhouse_support_tasks(); + string get_current_version(string repository_path); + long version_the_database(string repository_path, string repository_version); + bool run_sql(string sql_to_run, string script_name, bool run_this_script_once, bool run_this_script_every_time, long version_id, EnvironmentSet migrating_environment_set, string repository_version, string repository_path, ConnectionType connection_type); + //void transfer_to_database_for_changes(); + bool this_script_is_new_or_updated(string script_name, string sql_to_run, EnvironmentSet environment_set); + } } \ No newline at end of file diff --git a/product/roundhouse/migrators/DefaultDatabaseMigrator.cs b/product/roundhouse.core/migrators/DefaultDatabaseMigrator.cs similarity index 97% rename from product/roundhouse/migrators/DefaultDatabaseMigrator.cs rename to product/roundhouse.core/migrators/DefaultDatabaseMigrator.cs index 7ed6c010..df639bbf 100644 --- a/product/roundhouse/migrators/DefaultDatabaseMigrator.cs +++ b/product/roundhouse.core/migrators/DefaultDatabaseMigrator.cs @@ -1,418 +1,418 @@ -using System.Collections.Generic; -using System.Linq; -using roundhouse.environments; - -namespace roundhouse.migrators -{ - using System; - using cryptography; - using databases; - using infrastructure.app; - using infrastructure.app.tokens; - using infrastructure.extensions; - using infrastructure.logging; - using sqlsplitters; - using Environment = roundhouse.environments.Environment; - using System.Linq; - - public sealed class DefaultDatabaseMigrator : DatabaseMigrator - { - public Database database { get; set; } - private readonly CryptographicService crypto_provider; - private readonly ConfigurationPropertyHolder configuration; - private readonly bool restoring_database; - private readonly string restore_path; - private readonly string custom_restore_options; - private readonly string output_path; - private readonly bool error_on_one_time_script_changes; - private readonly bool ignore_one_time_script_changes; - private bool running_in_a_transaction; - private readonly bool is_running_all_any_time_scripts; - private readonly bool is_baseline; - private readonly bool is_dryrun; - - public DefaultDatabaseMigrator(Database database, CryptographicService crypto_provider, ConfigurationPropertyHolder configuration) - { - this.database = database; - this.crypto_provider = crypto_provider; - this.configuration = configuration; - restoring_database = configuration.Restore; - restore_path = configuration.RestoreFromPath; - custom_restore_options = configuration.RestoreCustomOptions; - output_path = configuration.OutputPath; - error_on_one_time_script_changes = !configuration.WarnOnOneTimeScriptChanges && !configuration.WarnAndIgnoreOnOneTimeScriptChanges; - ignore_one_time_script_changes = configuration.WarnAndIgnoreOnOneTimeScriptChanges; - is_running_all_any_time_scripts = configuration.RunAllAnyTimeScripts; - is_baseline = configuration.Baseline; - is_dryrun = configuration.DryRun; - } - - public void initialize_connections() - { - database.initialize_connections(configuration); - } - - public void open_admin_connection() - { - database.open_admin_connection(); - } - - public void close_admin_connection() - { - database.close_admin_connection(); - } - - public void open_connection(bool with_transaction) - { - running_in_a_transaction = with_transaction; - database.open_connection(with_transaction); - } - - public void close_connection() - { - database.close_connection(); - } - - public bool create_or_restore_database(string custom_create_database_script) - { - var database_created = false; - - if (string.IsNullOrEmpty(custom_create_database_script)) - { - Log.bound_to(this).log_an_info_event_containing("Creating {0} database on {1} server if it doesn't exist.", database.database_name, database.server_name); - } - else - { - Log.bound_to(this).log_an_info_event_containing("Creating {0} database on {1} server with custom script.", database.database_name, database.server_name); - } - - database_created = database.create_database_if_it_doesnt_exist(custom_create_database_script); - - if (restoring_database) - { - database_created = false; - string custom_script = custom_restore_options; - if (!configuration.DisableTokenReplacement) - { - custom_script = TokenReplacer.replace_tokens(configuration, custom_script); - } - restore_database(restore_path, custom_script); - } - - return database_created; - } - - public void backup_database_if_it_exists() - { - database.backup_database(output_path); - } - - public void restore_database(string restore_from_path, string restore_options) - { - Log.bound_to(this).log_an_info_event_containing("Restoring {0} database on {1} server from path {2}.", database.database_name, database.server_name, restore_from_path); - database.restore_database(restore_from_path, restore_options); - } - - public void set_recovery_mode(bool simple) - { - //database.open_connection(false); - Log.bound_to(this).log_an_info_event_containing("Setting recovery mode to '{0}' for database {1}.", simple ? "Simple" : "Full", database.database_name); - database.set_recovery_mode(simple); - //database.close_connection(); - } - - public void run_roundhouse_support_tasks() - { - if (running_in_a_transaction) - { - database.close_connection(); - database.open_connection(false); - } - - Log.bound_to(this).log_an_info_event_containing(" Running database type specific tasks."); - database.run_database_specific_tasks(); - Log.bound_to(this).log_an_info_event_containing(" Creating [{0}] table if it doesn't exist.", database.version_table_name); - Log.bound_to(this).log_an_info_event_containing(" Creating [{0}] table if it doesn't exist.", database.scripts_run_table_name); - Log.bound_to(this).log_an_info_event_containing(" Creating [{0}] table if it doesn't exist.", database.scripts_run_errors_table_name); - database.create_or_update_roundhouse_tables(); - - if (running_in_a_transaction) - { - database.close_connection(); - database.open_connection(true); - //transfer_to_database_for_changes(); - } - } - - public string get_current_version(string repository_path) - { - string current_version = database.get_version(repository_path); - - if (string.IsNullOrEmpty(current_version)) - { - current_version = "0"; - } - - return current_version; - } - - public void delete_database() - { - Log.bound_to(this).log_an_info_event_containing("Deleting {0} database on {1} server if it exists.", database.database_name, database.server_name); - database.delete_database_if_it_exists(); - } - - public long version_the_database(string repository_path, string repository_version) - { - Log.bound_to(this).log_an_info_event_containing(" Versioning {0} database with version {1} based on {2}.", database.database_name, repository_version, repository_path); - return database.insert_version_and_get_version_id(repository_path, repository_version); - } - - public bool run_sql(string sql_to_run, string script_name, bool run_this_script_once, bool run_this_script_every_time, long version_id, EnvironmentSet environment_set, string repository_version, string repository_path, ConnectionType connection_type) - { - bool this_sql_ran = false; - bool skip_run = is_baseline; - - if (this_is_a_one_time_script_that_has_changes_but_has_already_been_run(script_name, sql_to_run, run_this_script_once)) - { - if (error_on_one_time_script_changes) - { - database.rollback(); - string error_message = string.Format("{0} has changed since the last time it was run. By default this is not allowed - scripts that run once should never change. To change this behavior to a warning, please set warnOnOneTimeScriptChanges to true and run again. Stopping execution.", script_name); - record_script_in_scripts_run_errors_table(script_name, sql_to_run, sql_to_run, error_message, repository_version, repository_path); - database.close_connection(); - throw new Exception(error_message); - } - if (ignore_one_time_script_changes) - { - skip_run = true; - } - Log.bound_to(this).log_a_warning_event_containing("{0} is a one time script that has changed since it was run.", script_name); - } - - if (this_is_an_environment_file_and_its_in_the_right_environment(script_name, environment_set) - && this_script_should_run(script_name, sql_to_run, run_this_script_once, run_this_script_every_time)) - { - if (!is_dryrun) - { - Log.bound_to(this).log_an_info_event_containing(" {3} {0} on {1} - {2}.", script_name, database.server_name, database.database_name, - skip_run ? "BASELINING: Recording" : "Running"); - } - if (!skip_run) - { - if (!is_dryrun) - { - foreach (var sql_statement in get_statements_to_run(sql_to_run)) - { - try - { - database.run_sql(sql_statement, connection_type); - } - catch (Exception ex) - { - database.rollback(); - - record_script_in_scripts_run_errors_table(script_name, sql_to_run, sql_statement, ex.Message, repository_version, repository_path); - database.close_connection(); - throw; - } - } - } - else - { - Log.bound_to(this).log_a_warning_event_containing(" DryRun: {0} on {1} - {2}.", script_name, database.server_name, database.database_name); - } - } - if (!is_dryrun) - { - record_script_in_scripts_run_table(script_name, sql_to_run, run_this_script_once, version_id); - this_sql_ran = true; - } - } - else - { - Log.bound_to(this).log_an_info_event_containing(" Skipped {0} - {1}.", script_name, run_this_script_once ? "One time script" : "No changes were found to run"); - } - - return this_sql_ran; - } - - public IEnumerable get_statements_to_run(string sql_to_run) - { - IList sql_statements = new List(); - - if (database.split_batch_statements) - { - foreach (var sql_statement in StatementSplitter.split_sql_on_regex_and_remove_empty_statements(sql_to_run, database.sql_statement_separator_regex_pattern)) - { - sql_statements.Add(sql_statement); - } - } - else - { - sql_statements.Add(sql_to_run); - } - - return sql_statements; - } - - public void record_script_in_scripts_run_table(string script_name, string sql_to_run, bool run_this_script_once, long version_id) - { - Log.bound_to(this).log_a_debug_event_containing("Recording {0} script ran on {1} - {2}.", script_name, database.server_name, database.database_name); - database.insert_script_run(script_name, sql_to_run, create_hash(sql_to_run, true), run_this_script_once, version_id); - } - - public void record_script_in_scripts_run_errors_table(string script_name, string sql_to_run, string sql_erroneous_part, string error_message, string repository_version, string repository_path) - { - Log.bound_to(this).log_a_debug_event_containing("Recording {0} script ran with error on {1} - {2}.", script_name, database.server_name, database.database_name); - database.insert_script_run_error(script_name, sql_to_run, sql_erroneous_part, error_message, repository_version, repository_path); - } - - private string create_hash(string sql_to_run, bool normalizeEndings) - { - var input = sql_to_run.Replace(@"'", @"''"); - if (normalizeEndings) - input = input.Replace(WindowsLineEnding, UnixLineEnding).Replace(MacLineEnding, UnixLineEnding); - return crypto_provider.hash(input); - } - - public bool this_is_an_every_time_script(string script_name, bool run_this_script_every_time) - { - bool this_is_an_everytime_script = false; - - if (run_this_script_every_time) - { - this_is_an_everytime_script = true; - } - - if (script_name.to_lower().StartsWith("everytime.")) - { - this_is_an_everytime_script = true; - } - - if (script_name.to_lower().Contains(".everytime.")) - { - this_is_an_everytime_script = true; - } - - return this_is_an_everytime_script; - } - - private bool this_script_has_run_already(string script_name) - { - return database.has_run_script_already(script_name); - } - - private bool this_is_a_one_time_script_that_has_changes_but_has_already_been_run(string script_name, string sql_to_run, bool run_this_script_once) - { - return this_script_has_changed_since_last_run(script_name, sql_to_run) && this_script_has_run_already(script_name) && run_this_script_once; - } - - private bool this_script_has_changed_since_last_run(string script_name, string sql_to_run) - { - string old_text_hash = string.Empty; - try - { - old_text_hash = database.get_current_script_hash(script_name); - } - catch (Exception ex) - { - Log.bound_to(this).log_a_warning_event_containing("{0} - I didn't find this script executed before.{1}{2}", script_name, System.Environment.NewLine, ex.to_string()); - } - - if (string.IsNullOrEmpty(old_text_hash)) return true; - - - // These check hashes from before the normalization change and after - // The change does result in a different hash that will not be the result of - // any sore of file change and therefore should not be logged. - bool hash_is_same = - hashes_are_equal(create_hash(sql_to_run, true), old_text_hash) || // New hash - hashes_are_equal(create_hash(sql_to_run, false), old_text_hash); // Old hash - - if (!hash_is_same) - { - // extra checks if only line endings have changed - hash_is_same = have_same_hash_ignoring_platform(sql_to_run, old_text_hash); - if (hash_is_same) - { - Log.bound_to(this).log_a_warning_event_containing("Script {0} had different line endings than before but equal content", script_name); - } - } - - return !hash_is_same; - } - - private bool hashes_are_equal(string new_text_hash, string old_text_hash) - { - return string.Compare(old_text_hash, new_text_hash, true) == 0; - } - - private const string WindowsLineEnding = "\r\n"; - private const string UnixLineEnding = "\n"; - private const string MacLineEnding = "\r"; - - private bool have_same_hash_ignoring_platform(string sql_to_run, string old_text_hash) - { - var lineEndingVariations = new List {WindowsLineEnding, UnixLineEnding, MacLineEnding}; - - return lineEndingVariations.Any(variation => { - var normalized_sql = lineEndingVariations.Aggregate(sql_to_run, (norm, ending) => norm.Replace(ending, variation)); - return hashes_are_equal(create_hash(normalized_sql, false), old_text_hash); - }); - } - - private bool this_script_should_run(string script_name, string sql_to_run, bool run_this_script_once, bool run_this_script_every_time) - { - if (this_is_an_every_time_script(script_name, run_this_script_every_time)) - { - return true; - } - - if (is_running_all_any_time_scripts && !run_this_script_once) - { - return true; - } - - if (this_script_has_run_already(script_name) - && !this_script_has_changed_since_last_run(script_name, sql_to_run)) - { - return false; - } - - return true; - } - - public bool this_script_is_new_or_updated(string script_name, string sql_to_run, EnvironmentSet environment_set) - { - if (!this_is_an_environment_file_and_its_in_the_right_environment(script_name, environment_set)) - return false; - - if (this_script_has_run_already(script_name) - && !this_script_has_changed_since_last_run(script_name, sql_to_run)) - return false; - - return true; - } - - public bool this_is_an_environment_file_and_its_in_the_right_environment(string script_name, EnvironmentSet environment_set) - { - string environment_set_names = string.Join(", ", environment_set.set_items.Select(x => x.name)); - - Log.bound_to(this).log_a_debug_event_containing("Checking to see if {0} is an environment file. We have an environment set containing: .", script_name, environment_set_names); - - if (!script_name.to_lower().Contains(".env.")) - { - // return true because this is NOT an environment file for the next check - return true; - } - - bool environment_file_is_in_the_right_environment = environment_set.item_is_for_this_environment_set(script_name); - - Log.bound_to(this).log_an_info_event_containing(" {0} is an environment file. We have an environment set containing: {1}. This will{2} run based on this check.", - script_name, environment_set_names, environment_file_is_in_the_right_environment ? string.Empty : " NOT"); - - return environment_file_is_in_the_right_environment; - } - } +using System.Collections.Generic; +using System.Linq; +using roundhouse.environments; + +namespace roundhouse.migrators +{ + using System; + using cryptography; + using databases; + using infrastructure.app; + using infrastructure.app.tokens; + using infrastructure.extensions; + using infrastructure.logging; + using sqlsplitters; + using Environment = roundhouse.environments.Environment; + using System.Linq; + + public sealed class DefaultDatabaseMigrator : DatabaseMigrator + { + public Database database { get; set; } + private readonly CryptographicService crypto_provider; + private readonly ConfigurationPropertyHolder configuration; + private readonly bool restoring_database; + private readonly string restore_path; + private readonly string custom_restore_options; + private readonly string output_path; + private readonly bool error_on_one_time_script_changes; + private readonly bool ignore_one_time_script_changes; + private bool running_in_a_transaction; + private readonly bool is_running_all_any_time_scripts; + private readonly bool is_baseline; + private readonly bool is_dryrun; + + public DefaultDatabaseMigrator(Database database, CryptographicService crypto_provider, ConfigurationPropertyHolder configuration) + { + this.database = database; + this.crypto_provider = crypto_provider; + this.configuration = configuration; + restoring_database = configuration.Restore; + restore_path = configuration.RestoreFromPath; + custom_restore_options = configuration.RestoreCustomOptions; + output_path = configuration.OutputPath; + error_on_one_time_script_changes = !configuration.WarnOnOneTimeScriptChanges && !configuration.WarnAndIgnoreOnOneTimeScriptChanges; + ignore_one_time_script_changes = configuration.WarnAndIgnoreOnOneTimeScriptChanges; + is_running_all_any_time_scripts = configuration.RunAllAnyTimeScripts; + is_baseline = configuration.Baseline; + is_dryrun = configuration.DryRun; + } + + public void initialize_connections() + { + database.initialize_connections(configuration); + } + + public void open_admin_connection() + { + database.open_admin_connection(); + } + + public void close_admin_connection() + { + database.close_admin_connection(); + } + + public void open_connection(bool with_transaction) + { + running_in_a_transaction = with_transaction; + database.open_connection(with_transaction); + } + + public void close_connection() + { + database.close_connection(); + } + + public bool create_or_restore_database(string custom_create_database_script) + { + var database_created = false; + + if (string.IsNullOrEmpty(custom_create_database_script)) + { + Log.bound_to(this).log_an_info_event_containing("Creating {0} database on {1} server if it doesn't exist.", database.database_name, database.server_name); + } + else + { + Log.bound_to(this).log_an_info_event_containing("Creating {0} database on {1} server with custom script.", database.database_name, database.server_name); + } + + database_created = database.create_database_if_it_doesnt_exist(custom_create_database_script); + + if (restoring_database) + { + database_created = false; + string custom_script = custom_restore_options; + if (!configuration.DisableTokenReplacement) + { + custom_script = TokenReplacer.replace_tokens(configuration, custom_script); + } + restore_database(restore_path, custom_script); + } + + return database_created; + } + + public void backup_database_if_it_exists() + { + database.backup_database(output_path); + } + + public void restore_database(string restore_from_path, string restore_options) + { + Log.bound_to(this).log_an_info_event_containing("Restoring {0} database on {1} server from path {2}.", database.database_name, database.server_name, restore_from_path); + database.restore_database(restore_from_path, restore_options); + } + + public void set_recovery_mode(bool simple) + { + //database.open_connection(false); + Log.bound_to(this).log_an_info_event_containing("Setting recovery mode to '{0}' for database {1}.", simple ? "Simple" : "Full", database.database_name); + database.set_recovery_mode(simple); + //database.close_connection(); + } + + public void run_roundhouse_support_tasks() + { + if (running_in_a_transaction) + { + database.close_connection(); + database.open_connection(false); + } + + Log.bound_to(this).log_an_info_event_containing(" Running database type specific tasks."); + database.run_database_specific_tasks(); + Log.bound_to(this).log_an_info_event_containing(" Creating [{0}] table if it doesn't exist.", database.version_table_name); + Log.bound_to(this).log_an_info_event_containing(" Creating [{0}] table if it doesn't exist.", database.scripts_run_table_name); + Log.bound_to(this).log_an_info_event_containing(" Creating [{0}] table if it doesn't exist.", database.scripts_run_errors_table_name); + database.create_or_update_roundhouse_tables(); + + if (running_in_a_transaction) + { + database.close_connection(); + database.open_connection(true); + //transfer_to_database_for_changes(); + } + } + + public string get_current_version(string repository_path) + { + string current_version = database.get_version(repository_path); + + if (string.IsNullOrEmpty(current_version)) + { + current_version = "0"; + } + + return current_version; + } + + public void delete_database() + { + Log.bound_to(this).log_an_info_event_containing("Deleting {0} database on {1} server if it exists.", database.database_name, database.server_name); + database.delete_database_if_it_exists(); + } + + public long version_the_database(string repository_path, string repository_version) + { + Log.bound_to(this).log_an_info_event_containing(" Versioning {0} database with version {1} based on {2}.", database.database_name, repository_version, repository_path); + return database.insert_version_and_get_version_id(repository_path, repository_version); + } + + public bool run_sql(string sql_to_run, string script_name, bool run_this_script_once, bool run_this_script_every_time, long version_id, EnvironmentSet environment_set, string repository_version, string repository_path, ConnectionType connection_type) + { + bool this_sql_ran = false; + bool skip_run = is_baseline; + + if (this_is_a_one_time_script_that_has_changes_but_has_already_been_run(script_name, sql_to_run, run_this_script_once)) + { + if (error_on_one_time_script_changes) + { + database.rollback(); + string error_message = string.Format("{0} has changed since the last time it was run. By default this is not allowed - scripts that run once should never change. To change this behavior to a warning, please set warnOnOneTimeScriptChanges to true and run again. Stopping execution.", script_name); + record_script_in_scripts_run_errors_table(script_name, sql_to_run, sql_to_run, error_message, repository_version, repository_path); + database.close_connection(); + throw new Exception(error_message); + } + if (ignore_one_time_script_changes) + { + skip_run = true; + } + Log.bound_to(this).log_a_warning_event_containing("{0} is a one time script that has changed since it was run.", script_name); + } + + if (this_is_an_environment_file_and_its_in_the_right_environment(script_name, environment_set) + && this_script_should_run(script_name, sql_to_run, run_this_script_once, run_this_script_every_time)) + { + if (!is_dryrun) + { + Log.bound_to(this).log_an_info_event_containing(" {3} {0} on {1} - {2}.", script_name, database.server_name, database.database_name, + skip_run ? "BASELINING: Recording" : "Running"); + } + if (!skip_run) + { + if (!is_dryrun) + { + foreach (var sql_statement in get_statements_to_run(sql_to_run)) + { + try + { + database.run_sql(sql_statement, connection_type); + } + catch (Exception ex) + { + database.rollback(); + + record_script_in_scripts_run_errors_table(script_name, sql_to_run, sql_statement, ex.Message, repository_version, repository_path); + database.close_connection(); + throw; + } + } + } + else + { + Log.bound_to(this).log_a_warning_event_containing(" DryRun: {0} on {1} - {2}.", script_name, database.server_name, database.database_name); + } + } + if (!is_dryrun) + { + record_script_in_scripts_run_table(script_name, sql_to_run, run_this_script_once, version_id); + this_sql_ran = true; + } + } + else + { + Log.bound_to(this).log_an_info_event_containing(" Skipped {0} - {1}.", script_name, run_this_script_once ? "One time script" : "No changes were found to run"); + } + + return this_sql_ran; + } + + public IEnumerable get_statements_to_run(string sql_to_run) + { + IList sql_statements = new List(); + + if (database.split_batch_statements) + { + foreach (var sql_statement in StatementSplitter.split_sql_on_regex_and_remove_empty_statements(sql_to_run, database.sql_statement_separator_regex_pattern)) + { + sql_statements.Add(sql_statement); + } + } + else + { + sql_statements.Add(sql_to_run); + } + + return sql_statements; + } + + public void record_script_in_scripts_run_table(string script_name, string sql_to_run, bool run_this_script_once, long version_id) + { + Log.bound_to(this).log_a_debug_event_containing("Recording {0} script ran on {1} - {2}.", script_name, database.server_name, database.database_name); + database.insert_script_run(script_name, sql_to_run, create_hash(sql_to_run, true), run_this_script_once, version_id); + } + + public void record_script_in_scripts_run_errors_table(string script_name, string sql_to_run, string sql_erroneous_part, string error_message, string repository_version, string repository_path) + { + Log.bound_to(this).log_a_debug_event_containing("Recording {0} script ran with error on {1} - {2}.", script_name, database.server_name, database.database_name); + database.insert_script_run_error(script_name, sql_to_run, sql_erroneous_part, error_message, repository_version, repository_path); + } + + private string create_hash(string sql_to_run, bool normalizeEndings) + { + var input = sql_to_run.Replace(@"'", @"''"); + if (normalizeEndings) + input = input.Replace(WindowsLineEnding, UnixLineEnding).Replace(MacLineEnding, UnixLineEnding); + return crypto_provider.hash(input); + } + + public bool this_is_an_every_time_script(string script_name, bool run_this_script_every_time) + { + bool this_is_an_everytime_script = false; + + if (run_this_script_every_time) + { + this_is_an_everytime_script = true; + } + + if (script_name.to_lower().StartsWith("everytime.")) + { + this_is_an_everytime_script = true; + } + + if (script_name.to_lower().Contains(".everytime.")) + { + this_is_an_everytime_script = true; + } + + return this_is_an_everytime_script; + } + + private bool this_script_has_run_already(string script_name) + { + return database.has_run_script_already(script_name); + } + + private bool this_is_a_one_time_script_that_has_changes_but_has_already_been_run(string script_name, string sql_to_run, bool run_this_script_once) + { + return this_script_has_changed_since_last_run(script_name, sql_to_run) && this_script_has_run_already(script_name) && run_this_script_once; + } + + private bool this_script_has_changed_since_last_run(string script_name, string sql_to_run) + { + string old_text_hash = string.Empty; + try + { + old_text_hash = database.get_current_script_hash(script_name); + } + catch (Exception ex) + { + Log.bound_to(this).log_a_warning_event_containing("{0} - I didn't find this script executed before.{1}{2}", script_name, System.Environment.NewLine, ex.to_string()); + } + + if (string.IsNullOrEmpty(old_text_hash)) return true; + + + // These check hashes from before the normalization change and after + // The change does result in a different hash that will not be the result of + // any sore of file change and therefore should not be logged. + bool hash_is_same = + hashes_are_equal(create_hash(sql_to_run, true), old_text_hash) || // New hash + hashes_are_equal(create_hash(sql_to_run, false), old_text_hash); // Old hash + + if (!hash_is_same) + { + // extra checks if only line endings have changed + hash_is_same = have_same_hash_ignoring_platform(sql_to_run, old_text_hash); + if (hash_is_same) + { + Log.bound_to(this).log_a_warning_event_containing("Script {0} had different line endings than before but equal content", script_name); + } + } + + return !hash_is_same; + } + + private bool hashes_are_equal(string new_text_hash, string old_text_hash) + { + return string.Compare(old_text_hash, new_text_hash, true) == 0; + } + + private const string WindowsLineEnding = "\r\n"; + private const string UnixLineEnding = "\n"; + private const string MacLineEnding = "\r"; + + private bool have_same_hash_ignoring_platform(string sql_to_run, string old_text_hash) + { + var lineEndingVariations = new List {WindowsLineEnding, UnixLineEnding, MacLineEnding}; + + return lineEndingVariations.Any(variation => { + var normalized_sql = lineEndingVariations.Aggregate(sql_to_run, (norm, ending) => norm.Replace(ending, variation)); + return hashes_are_equal(create_hash(normalized_sql, false), old_text_hash); + }); + } + + private bool this_script_should_run(string script_name, string sql_to_run, bool run_this_script_once, bool run_this_script_every_time) + { + if (this_is_an_every_time_script(script_name, run_this_script_every_time)) + { + return true; + } + + if (is_running_all_any_time_scripts && !run_this_script_once) + { + return true; + } + + if (this_script_has_run_already(script_name) + && !this_script_has_changed_since_last_run(script_name, sql_to_run)) + { + return false; + } + + return true; + } + + public bool this_script_is_new_or_updated(string script_name, string sql_to_run, EnvironmentSet environment_set) + { + if (!this_is_an_environment_file_and_its_in_the_right_environment(script_name, environment_set)) + return false; + + if (this_script_has_run_already(script_name) + && !this_script_has_changed_since_last_run(script_name, sql_to_run)) + return false; + + return true; + } + + public bool this_is_an_environment_file_and_its_in_the_right_environment(string script_name, EnvironmentSet environment_set) + { + string environment_set_names = string.Join(", ", environment_set.set_items.Select(x => x.name)); + + Log.bound_to(this).log_a_debug_event_containing("Checking to see if {0} is an environment file. We have an environment set containing: .", script_name, environment_set_names); + + if (!script_name.to_lower().Contains(".env.")) + { + // return true because this is NOT an environment file for the next check + return true; + } + + bool environment_file_is_in_the_right_environment = environment_set.item_is_for_this_environment_set(script_name); + + Log.bound_to(this).log_an_info_event_containing(" {0} is an environment file. We have an environment set containing: {1}. This will{2} run based on this check.", + script_name, environment_set_names, environment_file_is_in_the_right_environment ? string.Empty : " NOT"); + + return environment_file_is_in_the_right_environment; + } + } } \ No newline at end of file diff --git a/product/roundhouse/model/Auditable.cs b/product/roundhouse.core/model/Auditable.cs similarity index 95% rename from product/roundhouse/model/Auditable.cs rename to product/roundhouse.core/model/Auditable.cs index 98107268..6be788d0 100644 --- a/product/roundhouse/model/Auditable.cs +++ b/product/roundhouse.core/model/Auditable.cs @@ -1,11 +1,11 @@ -namespace roundhouse.model -{ - using System; - - public interface Auditable - { - DateTime? entry_date { get; set; } - DateTime? modified_date { get; set; } - string entered_by { get; set; } - } +namespace roundhouse.model +{ + using System; + + public interface Auditable + { + DateTime? entry_date { get; set; } + DateTime? modified_date { get; set; } + string entered_by { get; set; } + } } \ No newline at end of file diff --git a/product/roundhouse/model/ScriptsRun.cs b/product/roundhouse.core/model/ScriptsRun.cs similarity index 96% rename from product/roundhouse/model/ScriptsRun.cs rename to product/roundhouse.core/model/ScriptsRun.cs index d06668f5..8a676fd0 100644 --- a/product/roundhouse/model/ScriptsRun.cs +++ b/product/roundhouse.core/model/ScriptsRun.cs @@ -1,19 +1,19 @@ -namespace roundhouse.model -{ - using System; - - public class ScriptsRun : Auditable - { - public long id { get; set; } - public long version_id { get; set; } - public string script_name { get; set; } - public string text_of_script { get; set; } - public string text_hash { get; set; } - public bool one_time_script { get; set; } - - //auditing - public DateTime? entry_date { get; set; } - public DateTime? modified_date { get; set; } - public string entered_by { get; set; } - } +namespace roundhouse.model +{ + using System; + + public class ScriptsRun : Auditable + { + public long id { get; set; } + public long version_id { get; set; } + public string script_name { get; set; } + public string text_of_script { get; set; } + public string text_hash { get; set; } + public bool one_time_script { get; set; } + + //auditing + public DateTime? entry_date { get; set; } + public DateTime? modified_date { get; set; } + public string entered_by { get; set; } + } } \ No newline at end of file diff --git a/product/roundhouse/model/ScriptsRunError.cs b/product/roundhouse.core/model/ScriptsRunError.cs similarity index 97% rename from product/roundhouse/model/ScriptsRunError.cs rename to product/roundhouse.core/model/ScriptsRunError.cs index b54b93ed..0cd77d44 100644 --- a/product/roundhouse/model/ScriptsRunError.cs +++ b/product/roundhouse.core/model/ScriptsRunError.cs @@ -1,20 +1,20 @@ -namespace roundhouse.model -{ - using System; - - public class ScriptsRunError : Auditable - { - public long id { get; set; } - public string repository_path { get; set; } - public string version { get; set; } - public string script_name { get; set; } - public string text_of_script { get; set; } - public string erroneous_part_of_script { get; set; } - public string error_message { get; set; } - - //auditing - public DateTime? entry_date { get; set; } - public DateTime? modified_date { get; set; } - public string entered_by { get; set; } - } +namespace roundhouse.model +{ + using System; + + public class ScriptsRunError : Auditable + { + public long id { get; set; } + public string repository_path { get; set; } + public string version { get; set; } + public string script_name { get; set; } + public string text_of_script { get; set; } + public string erroneous_part_of_script { get; set; } + public string error_message { get; set; } + + //auditing + public DateTime? entry_date { get; set; } + public DateTime? modified_date { get; set; } + public string entered_by { get; set; } + } } \ No newline at end of file diff --git a/product/roundhouse/model/Version.cs b/product/roundhouse.core/model/Version.cs similarity index 96% rename from product/roundhouse/model/Version.cs rename to product/roundhouse.core/model/Version.cs index 7c725969..46698b88 100644 --- a/product/roundhouse/model/Version.cs +++ b/product/roundhouse.core/model/Version.cs @@ -1,16 +1,16 @@ -namespace roundhouse.model -{ - using System; - - public class Version : Auditable - { - public long id { get; set; } - public string repository_path { get; set; } - public string version { get; set; } - - //auditing - public DateTime? entry_date { get; set; } - public DateTime? modified_date { get; set; } - public string entered_by { get; set; } - } +namespace roundhouse.model +{ + using System; + + public class Version : Auditable + { + public long id { get; set; } + public string repository_path { get; set; } + public string version { get; set; } + + //auditing + public DateTime? entry_date { get; set; } + public DateTime? modified_date { get; set; } + public string entered_by { get; set; } + } } \ No newline at end of file diff --git a/product/roundhouse/parameters/AdoNetParameter.cs b/product/roundhouse.core/parameters/AdoNetParameter.cs similarity index 96% rename from product/roundhouse/parameters/AdoNetParameter.cs rename to product/roundhouse.core/parameters/AdoNetParameter.cs index df42a271..aae7d8cd 100644 --- a/product/roundhouse/parameters/AdoNetParameter.cs +++ b/product/roundhouse.core/parameters/AdoNetParameter.cs @@ -1,29 +1,29 @@ -namespace roundhouse.parameters -{ - using System.Data; - - public class AdoNetParameter : IParameter - { - private readonly IDbDataParameter parameter; - - public AdoNetParameter(IDbDataParameter parameter) - { - this.parameter = parameter; - } - - public IDbDataParameter underlying_type - { - get { return parameter; } - } - - public string name - { - get { return parameter != null ? parameter.ParameterName : string.Empty; } - } - - public object value - { - get { return parameter != null ? parameter.Value : string.Empty; } - } - } +namespace roundhouse.parameters +{ + using System.Data; + + public class AdoNetParameter : IParameter + { + private readonly IDbDataParameter parameter; + + public AdoNetParameter(IDbDataParameter parameter) + { + this.parameter = parameter; + } + + public IDbDataParameter underlying_type + { + get { return parameter; } + } + + public string name + { + get { return parameter != null ? parameter.ParameterName : string.Empty; } + } + + public object value + { + get { return parameter != null ? parameter.Value : string.Empty; } + } + } } \ No newline at end of file diff --git a/product/roundhouse/parameters/IParameter.cs b/product/roundhouse.core/parameters/IParameter.cs similarity index 95% rename from product/roundhouse/parameters/IParameter.cs rename to product/roundhouse.core/parameters/IParameter.cs index 3d51e9f8..65928d42 100644 --- a/product/roundhouse/parameters/IParameter.cs +++ b/product/roundhouse.core/parameters/IParameter.cs @@ -1,9 +1,9 @@ -namespace roundhouse.parameters -{ - public interface IParameter - { - T underlying_type {get;} - string name {get;} - object value{get;} - } +namespace roundhouse.parameters +{ + public interface IParameter + { + T underlying_type {get;} + string name {get;} + object value{get;} + } } \ No newline at end of file diff --git a/product/roundhouse/resolvers/CommandLineVersionResolver.cs b/product/roundhouse.core/resolvers/CommandLineVersionResolver.cs similarity index 100% rename from product/roundhouse/resolvers/CommandLineVersionResolver.cs rename to product/roundhouse.core/resolvers/CommandLineVersionResolver.cs diff --git a/product/roundhouse/resolvers/ComplexVersionResolver.cs b/product/roundhouse.core/resolvers/ComplexVersionResolver.cs similarity index 96% rename from product/roundhouse/resolvers/ComplexVersionResolver.cs rename to product/roundhouse.core/resolvers/ComplexVersionResolver.cs index 1ce1bbf5..c4a57a07 100644 --- a/product/roundhouse/resolvers/ComplexVersionResolver.cs +++ b/product/roundhouse.core/resolvers/ComplexVersionResolver.cs @@ -1,33 +1,33 @@ -using System.Collections.Generic; - -namespace roundhouse.resolvers -{ - public sealed class ComplexVersionResolver : VersionResolver - { - private readonly IEnumerable resolvers; - - public ComplexVersionResolver(IEnumerable resolvers) - { - this.resolvers = resolvers; - } - - public bool meets_criteria() - { - return true; - } - - public string resolve_version() - { - string version = "0"; - foreach (VersionResolver resolver in resolvers) - { - if (resolver.meets_criteria()) - { - version = resolver.resolve_version(); - } - } - - return version; - } - } +using System.Collections.Generic; + +namespace roundhouse.resolvers +{ + public sealed class ComplexVersionResolver : VersionResolver + { + private readonly IEnumerable resolvers; + + public ComplexVersionResolver(IEnumerable resolvers) + { + this.resolvers = resolvers; + } + + public bool meets_criteria() + { + return true; + } + + public string resolve_version() + { + string version = "0"; + foreach (VersionResolver resolver in resolvers) + { + if (resolver.meets_criteria()) + { + version = resolver.resolve_version(); + } + } + + return version; + } + } } \ No newline at end of file diff --git a/product/roundhouse/resolvers/DllFileVersionResolver.cs b/product/roundhouse.core/resolvers/DllFileVersionResolver.cs similarity index 96% rename from product/roundhouse/resolvers/DllFileVersionResolver.cs rename to product/roundhouse.core/resolvers/DllFileVersionResolver.cs index 7bda2bc4..b18665c1 100644 --- a/product/roundhouse/resolvers/DllFileVersionResolver.cs +++ b/product/roundhouse.core/resolvers/DllFileVersionResolver.cs @@ -1,47 +1,47 @@ -using roundhouse.infrastructure.extensions; -using roundhouse.infrastructure.filesystem; -using roundhouse.infrastructure.logging; - -namespace roundhouse.resolvers -{ - public sealed class DllFileVersionResolver : VersionResolver - { - private readonly FileSystemAccess file_system; - private readonly string version_file; - private const string dll_extension = ".dll"; - - public DllFileVersionResolver(FileSystemAccess file_system, string version_file) - { - this.file_system = file_system; - this.version_file = file_system.get_full_path(version_file); - } - - public bool meets_criteria() - { - if (version_file_is_dll(version_file)) - { - return true; - } - - return false; - } - - public string resolve_version() - { - string version = "0"; - - Log.bound_to(this).log_an_info_event_containing( - " Attempting to resolve assembly file version from {0}.", version_file); - - version = file_system.get_file_version_from(version_file); - Log.bound_to(this).log_an_info_event_containing(" Found version {0} from {1}.", version, version_file); - - return version; - } - - private bool version_file_is_dll(string version_file) - { - return file_system.get_file_extension_from(version_file).to_lower() == dll_extension; - } - } +using roundhouse.infrastructure.extensions; +using roundhouse.infrastructure.filesystem; +using roundhouse.infrastructure.logging; + +namespace roundhouse.resolvers +{ + public sealed class DllFileVersionResolver : VersionResolver + { + private readonly FileSystemAccess file_system; + private readonly string version_file; + private const string dll_extension = ".dll"; + + public DllFileVersionResolver(FileSystemAccess file_system, string version_file) + { + this.file_system = file_system; + this.version_file = file_system.get_full_path(version_file); + } + + public bool meets_criteria() + { + if (version_file_is_dll(version_file)) + { + return true; + } + + return false; + } + + public string resolve_version() + { + string version = "0"; + + Log.bound_to(this).log_an_info_event_containing( + " Attempting to resolve assembly file version from {0}.", version_file); + + version = file_system.get_file_version_from(version_file); + Log.bound_to(this).log_an_info_event_containing(" Found version {0} from {1}.", version, version_file); + + return version; + } + + private bool version_file_is_dll(string version_file) + { + return file_system.get_file_extension_from(version_file).to_lower() == dll_extension; + } + } } \ No newline at end of file diff --git a/product/roundhouse/resolvers/JsonVersionResolver.cs b/product/roundhouse.core/resolvers/JsonVersionResolver.cs similarity index 100% rename from product/roundhouse/resolvers/JsonVersionResolver.cs rename to product/roundhouse.core/resolvers/JsonVersionResolver.cs diff --git a/product/roundhouse/resolvers/ScriptfileVersionResolver.cs b/product/roundhouse.core/resolvers/ScriptfileVersionResolver.cs similarity index 97% rename from product/roundhouse/resolvers/ScriptfileVersionResolver.cs rename to product/roundhouse.core/resolvers/ScriptfileVersionResolver.cs index dcb87fe0..dec8d909 100644 --- a/product/roundhouse/resolvers/ScriptfileVersionResolver.cs +++ b/product/roundhouse.core/resolvers/ScriptfileVersionResolver.cs @@ -1,66 +1,66 @@ -using System; -using roundhouse.infrastructure.filesystem; -using roundhouse.infrastructure.logging; -using System.Linq; - -namespace roundhouse.resolvers -{ - using infrastructure.app; - using System.IO; - - public class ScriptfileVersionResolver : VersionResolver - { - private string version_file; - private FileSystemAccess file_system; - private string up_folder; - private string extension = "sql"; - - public ScriptfileVersionResolver(FileSystemAccess file_system, ConfigurationPropertyHolder configuration_property_holder) - { - this.file_system = file_system; - this.version_file = configuration_property_holder.VersionFile; - this.up_folder = file_system.combine_paths(configuration_property_holder.SqlFilesDirectory, configuration_property_holder.UpFolderName); - } - - public bool meets_criteria() - { - return version_file.Equals(extension, StringComparison.InvariantCultureIgnoreCase); - } - - public string resolve_version() - { - string version = "0"; - Version ver = new Version(); - - if (file_system.directory_exists(up_folder)) - { - var files = file_system.get_directory_info_from(up_folder) - .GetFiles("*." + extension).OrderBy(x => x.Name); - long max = 0; - foreach (var file in files) - { - string fileName = Path.GetFileNameWithoutExtension(file.Name); - if (fileName.Contains("_")) fileName = fileName.Substring(0, fileName.IndexOf("_")); - if (fileName.Contains(".")) //using ##.##.##_description.sql format - { - Version tmp = new Version(fileName); - if (tmp > ver) - { - ver = tmp; - version = ver.ToString(); - } - } - else //using ###_description.sql format - { - long fileNumber = 0; - long.TryParse(fileName, out fileNumber); - max = Math.Max(max, fileNumber); - version = max.ToString(); - } - } - Log.bound_to(this).log_an_info_event_containing(" Found version {0} from up directory.", version); - } - return version; - } - } +using System; +using roundhouse.infrastructure.filesystem; +using roundhouse.infrastructure.logging; +using System.Linq; + +namespace roundhouse.resolvers +{ + using infrastructure.app; + using System.IO; + + public class ScriptfileVersionResolver : VersionResolver + { + private string version_file; + private FileSystemAccess file_system; + private string up_folder; + private string extension = "sql"; + + public ScriptfileVersionResolver(FileSystemAccess file_system, ConfigurationPropertyHolder configuration_property_holder) + { + this.file_system = file_system; + this.version_file = configuration_property_holder.VersionFile; + this.up_folder = file_system.combine_paths(configuration_property_holder.SqlFilesDirectory, configuration_property_holder.UpFolderName); + } + + public bool meets_criteria() + { + return version_file.Equals(extension, StringComparison.InvariantCultureIgnoreCase); + } + + public string resolve_version() + { + string version = "0"; + Version ver = new Version(); + + if (file_system.directory_exists(up_folder)) + { + var files = file_system.get_directory_info_from(up_folder) + .GetFiles("*." + extension).OrderBy(x => x.Name); + long max = 0; + foreach (var file in files) + { + string fileName = Path.GetFileNameWithoutExtension(file.Name); + if (fileName.Contains("_")) fileName = fileName.Substring(0, fileName.IndexOf("_")); + if (fileName.Contains(".")) //using ##.##.##_description.sql format + { + Version tmp = new Version(fileName); + if (tmp > ver) + { + ver = tmp; + version = ver.ToString(); + } + } + else //using ###_description.sql format + { + long fileNumber = 0; + long.TryParse(fileName, out fileNumber); + max = Math.Max(max, fileNumber); + version = max.ToString(); + } + } + Log.bound_to(this).log_an_info_event_containing(" Found version {0} from up directory.", version); + } + return version; + } + } } \ No newline at end of file diff --git a/product/roundhouse/resolvers/TextVersionResolver.cs b/product/roundhouse.core/resolvers/TextVersionResolver.cs similarity index 97% rename from product/roundhouse/resolvers/TextVersionResolver.cs rename to product/roundhouse.core/resolvers/TextVersionResolver.cs index dd6f6656..66511323 100644 --- a/product/roundhouse/resolvers/TextVersionResolver.cs +++ b/product/roundhouse.core/resolvers/TextVersionResolver.cs @@ -1,52 +1,52 @@ -using System; - -using roundhouse.infrastructure.filesystem; -using roundhouse.infrastructure.logging; - -namespace roundhouse.resolvers -{ - public class TextVersionResolver : VersionResolver - { - private readonly FileSystemAccess file_system; - private readonly string version_file; - - public TextVersionResolver(FileSystemAccess file_system, string version_file) - { - this.file_system = file_system; - this.version_file = file_system.get_full_path(version_file); - } - - public bool meets_criteria() - { - return version_file.EndsWith(".txt", StringComparison.OrdinalIgnoreCase); - } - - public string resolve_version() - { - Log.bound_to(this).log_an_info_event_containing( - " Attempting to resolve version from text file {0}.", version_file); - - string version = "0"; - if (file_system.file_exists(version_file)) - { - try - { - version = file_system.read_file_text(version_file).Trim(); - Log.bound_to(this).log_an_info_event_containing(" Found version {0} from {1}.", version, version_file); - } - catch (Exception e) - { - Log.bound_to(this).log_an_error_event_containing( - "Unable to get version from text file {0}:{1}{2}", version_file, Environment.NewLine, e.Message); - } - } - else - { - Log.bound_to(this).log_a_warning_event_containing( - "Unable to get version from text file {0}. File doesn't exist.", version_file); - } - - return version; - } - } +using System; + +using roundhouse.infrastructure.filesystem; +using roundhouse.infrastructure.logging; + +namespace roundhouse.resolvers +{ + public class TextVersionResolver : VersionResolver + { + private readonly FileSystemAccess file_system; + private readonly string version_file; + + public TextVersionResolver(FileSystemAccess file_system, string version_file) + { + this.file_system = file_system; + this.version_file = file_system.get_full_path(version_file); + } + + public bool meets_criteria() + { + return version_file.EndsWith(".txt", StringComparison.OrdinalIgnoreCase); + } + + public string resolve_version() + { + Log.bound_to(this).log_an_info_event_containing( + " Attempting to resolve version from text file {0}.", version_file); + + string version = "0"; + if (file_system.file_exists(version_file)) + { + try + { + version = file_system.read_file_text(version_file).Trim(); + Log.bound_to(this).log_an_info_event_containing(" Found version {0} from {1}.", version, version_file); + } + catch (Exception e) + { + Log.bound_to(this).log_an_error_event_containing( + "Unable to get version from text file {0}:{1}{2}", version_file, Environment.NewLine, e.Message); + } + } + else + { + Log.bound_to(this).log_a_warning_event_containing( + "Unable to get version from text file {0}. File doesn't exist.", version_file); + } + + return version; + } + } } \ No newline at end of file diff --git a/product/roundhouse/resolvers/VersionResolver.cs b/product/roundhouse.core/resolvers/VersionResolver.cs similarity index 95% rename from product/roundhouse/resolvers/VersionResolver.cs rename to product/roundhouse.core/resolvers/VersionResolver.cs index 7aade4c2..657aa207 100644 --- a/product/roundhouse/resolvers/VersionResolver.cs +++ b/product/roundhouse.core/resolvers/VersionResolver.cs @@ -1,8 +1,8 @@ -namespace roundhouse.resolvers -{ - public interface VersionResolver - { - bool meets_criteria(); - string resolve_version(); - } +namespace roundhouse.resolvers +{ + public interface VersionResolver + { + bool meets_criteria(); + string resolve_version(); + } } \ No newline at end of file diff --git a/product/roundhouse/resolvers/XmlFileVersionResolver.cs b/product/roundhouse.core/resolvers/XmlFileVersionResolver.cs similarity index 97% rename from product/roundhouse/resolvers/XmlFileVersionResolver.cs rename to product/roundhouse.core/resolvers/XmlFileVersionResolver.cs index 2f39b0cf..14bfeba8 100644 --- a/product/roundhouse/resolvers/XmlFileVersionResolver.cs +++ b/product/roundhouse.core/resolvers/XmlFileVersionResolver.cs @@ -1,69 +1,69 @@ -using System; -using System.Xml; -using roundhouse.infrastructure.extensions; -using roundhouse.infrastructure.filesystem; -using roundhouse.infrastructure.logging; - -namespace roundhouse.resolvers -{ - public sealed class XmlFileVersionResolver : VersionResolver - { - private readonly FileSystemAccess file_system; - private readonly string x_path; - private readonly string version_file; - private const string xml_extension = ".xml"; - - public XmlFileVersionResolver(FileSystemAccess file_system, string x_path, string version_file) - { - this.file_system = file_system; - this.x_path = x_path; - this.version_file = file_system.get_full_path(version_file); - } - - public bool meets_criteria() - { - if (version_file_is_xml(version_file)) - { - return true; - } - - return false; - } - - public string resolve_version() - { - Log.bound_to(this).log_an_info_event_containing(" Attempting to resolve version from {0} using {1}.", - version_file, x_path); - string version = "0"; - XmlDocument xml = new XmlDocument(); - if (file_system.file_exists(version_file)) - { - try - { - xml.Load(version_file); - XmlNode node = xml.SelectSingleNode(x_path); - version = node.InnerText; - Log.bound_to(this).log_an_info_event_containing(" Found version {0} from {1}.", version, version_file); - } - catch (Exception) - { - Log.bound_to(this).log_an_error_event_containing( - "Unable to get version from xml file {0} using xpath {1}", version_file, x_path); - } - } else - { - Log.bound_to(this).log_a_warning_event_containing( - "Unable to get version from xml file {0}. File doesn't exist.", version_file); - } - - return version; - } - - private bool version_file_is_xml(string version_file) - { - return file_system.get_file_extension_from(version_file).to_lower() == xml_extension; - } - - - } +using System; +using System.Xml; +using roundhouse.infrastructure.extensions; +using roundhouse.infrastructure.filesystem; +using roundhouse.infrastructure.logging; + +namespace roundhouse.resolvers +{ + public sealed class XmlFileVersionResolver : VersionResolver + { + private readonly FileSystemAccess file_system; + private readonly string x_path; + private readonly string version_file; + private const string xml_extension = ".xml"; + + public XmlFileVersionResolver(FileSystemAccess file_system, string x_path, string version_file) + { + this.file_system = file_system; + this.x_path = x_path; + this.version_file = file_system.get_full_path(version_file); + } + + public bool meets_criteria() + { + if (version_file_is_xml(version_file)) + { + return true; + } + + return false; + } + + public string resolve_version() + { + Log.bound_to(this).log_an_info_event_containing(" Attempting to resolve version from {0} using {1}.", + version_file, x_path); + string version = "0"; + XmlDocument xml = new XmlDocument(); + if (file_system.file_exists(version_file)) + { + try + { + xml.Load(version_file); + XmlNode node = xml.SelectSingleNode(x_path); + version = node.InnerText; + Log.bound_to(this).log_an_info_event_containing(" Found version {0} from {1}.", version, version_file); + } + catch (Exception) + { + Log.bound_to(this).log_an_error_event_containing( + "Unable to get version from xml file {0} using xpath {1}", version_file, x_path); + } + } else + { + Log.bound_to(this).log_a_warning_event_containing( + "Unable to get version from xml file {0}. File doesn't exist.", version_file); + } + + return version; + } + + private bool version_file_is_xml(string version_file) + { + return file_system.get_file_extension_from(version_file).to_lower() == xml_extension; + } + + + } } \ No newline at end of file diff --git a/product/roundhouse/roundhouse.csproj b/product/roundhouse.core/roundhouse.core.csproj similarity index 66% rename from product/roundhouse/roundhouse.csproj rename to product/roundhouse.core/roundhouse.core.csproj index 760ef0bb..44d6ba04 100644 --- a/product/roundhouse/roundhouse.csproj +++ b/product/roundhouse.core/roundhouse.core.csproj @@ -1,79 +1,88 @@ - - - netstandard2.0 - true - true - Debug - AnyCPU - Library - Properties - roundhouse - roundhouse - ..\..\ - NU1701 - true - true - bin\$(Configuration)\ - 0.8.9 - alpha - $(VersionPrefix) - $(Version)-$(VersionSuffix) - $(Version) - - - - AllRules.ruleset - - - - true - full - false - DEBUG;TRACE - prompt - 4 - AnyCPU - false - default - - - none - true - TRACE - prompt - 4 - AnyCPU - false - - - default - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + netstandard2.0 + true + true + Debug + AnyCPU + Library + Properties + roundhouse.core + roundhouse.core + NU1701,CS3003 + true + true + bin\$(Configuration)\ + + + + $(Version) + $(NugetVersion) + roundhouse.core + RoundhousE Library - core + Rob Reynolds, Erik A. Brandstadmoen + + RoundhousE is a Professional Database Change and Versioning Management tool. + +This is the core package, which implements the basic functionality. If you want to create your own RoundhousE database implementation, this is the package you want. If not, you probably want one of the database-specific versions. + + http://projectroundhouse.org + Apache-2.0 + false + roundhouse db migration database migrator chucknorris + https://raw.github.com/chucknorris/roundhouse/master/nuget/RoundhousE_Logo.NuGet.jpg + + + + + true + full + false + DEBUG;TRACE + prompt + 4 + AnyCPU + false + default + + + none + true + TRACE + prompt + 4 + AnyCPU + false + + + default + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/product/roundhouse/runners/IRunner.cs b/product/roundhouse.core/runners/IRunner.cs similarity index 93% rename from product/roundhouse/runners/IRunner.cs rename to product/roundhouse.core/runners/IRunner.cs index 4f405a07..48c5b8db 100644 --- a/product/roundhouse/runners/IRunner.cs +++ b/product/roundhouse.core/runners/IRunner.cs @@ -1,7 +1,7 @@ -namespace roundhouse.runners -{ - public interface IRunner - { - void run(); - } +namespace roundhouse.runners +{ + public interface IRunner + { + void run(); + } } \ No newline at end of file diff --git a/product/roundhouse/runners/RoundhouseMigrationRunner.cs b/product/roundhouse.core/runners/RoundhouseMigrationRunner.cs similarity index 98% rename from product/roundhouse/runners/RoundhouseMigrationRunner.cs rename to product/roundhouse.core/runners/RoundhouseMigrationRunner.cs index 820fb71c..b57e134d 100644 --- a/product/roundhouse/runners/RoundhouseMigrationRunner.cs +++ b/product/roundhouse.core/runners/RoundhouseMigrationRunner.cs @@ -1,342 +1,342 @@ -namespace roundhouse.runners -{ - using System; - using databases; - using folders; - using infrastructure; - using infrastructure.app; - using infrastructure.app.tokens; - using infrastructure.extensions; - using infrastructure.filesystem; - using infrastructure.logging; - using migrators; - using resolvers; - using roundhouse.environments; - - public sealed class RoundhouseMigrationRunner : IRunner - { - private readonly string repository_path; - private readonly EnvironmentSet environment_set; - private readonly KnownFolders known_folders; - private readonly FileSystemAccess file_system; - public DatabaseMigrator database_migrator { get; private set; } - private readonly VersionResolver version_resolver; - public bool silent { get; set; } - public bool dropping_the_database { get; set; } - private readonly bool dont_create_the_database; - private bool run_in_a_transaction; - private readonly ConfigurationPropertyHolder configuration; - private const string SQL_EXTENSION = "*.sql"; - - public RoundhouseMigrationRunner( - string repository_path, - EnvironmentSet environment_set, - KnownFolders known_folders, - FileSystemAccess file_system, - DatabaseMigrator database_migrator, - VersionResolver version_resolver, - bool silent, - bool dropping_the_database, - bool dont_create_the_database, - bool run_in_a_transaction, - ConfigurationPropertyHolder configuration) - { - this.known_folders = known_folders; - this.repository_path = repository_path; - this.environment_set = environment_set; - this.file_system = file_system; - this.database_migrator = database_migrator; - this.version_resolver = version_resolver; - this.silent = silent; - this.dropping_the_database = dropping_the_database; - this.dont_create_the_database = dont_create_the_database; - this.run_in_a_transaction = run_in_a_transaction; - this.configuration = configuration; - } - - public void run() - { - database_migrator.initialize_connections(); - - Log.bound_to(this).log_an_info_event_containing("Running {0} v{1} against {2} - {3}.", - ApplicationParameters.name, - VersionInformation.get_current_assembly_version(), - database_migrator.database.server_name, - database_migrator.database.database_name); - - Log.bound_to(this).log_an_info_event_containing("Looking in {0} for scripts to run.", known_folders.up.folder_path); - if (!silent) - { - Log.bound_to(this).log_an_info_event_containing("Please press enter when ready to kick..."); - Console.ReadLine(); - } - - if (run_in_a_transaction && !database_migrator.database.supports_ddl_transactions) - { - Log.bound_to(this).log_a_warning_event_containing("You asked to run in a transaction, but this databasetype doesn't support DDL transactions."); - if (!silent) - { - Log.bound_to(this).log_an_info_event_containing("Please press enter to continue without transaction support..."); - Console.ReadLine(); - } - run_in_a_transaction = false; - } - - create_change_drop_folder(); - Log.bound_to(this).log_a_debug_event_containing("The change_drop (output) folder is: {0}", known_folders.change_drop.folder_full_path); - Log.bound_to(this).log_a_debug_event_containing("Using SearchAllSubdirectoriesInsteadOfTraverse execution: {0}", configuration.SearchAllSubdirectoriesInsteadOfTraverse); - - try - { - Log.bound_to(this).log_an_info_event_containing("{0}", "=".PadRight(50, '=')); - Log.bound_to(this).log_an_info_event_containing("Setup, Backup, Create/Restore/Drop"); - Log.bound_to(this).log_an_info_event_containing("{0}", "=".PadRight(50, '=')); - create_share_and_set_permissions_for_change_drop_folder(); - //database_migrator.backup_database_if_it_exists(); - remove_share_from_change_drop_folder(); - - bool database_was_created = false; - - if (!dropping_the_database) - { - if (!dont_create_the_database) - { - database_was_created = database_migrator.create_or_restore_database(get_custom_create_database_script()); - } - - if (configuration.RecoveryMode != RecoveryMode.NoChange) - { - database_migrator.set_recovery_mode(configuration.RecoveryMode == RecoveryMode.Simple); - } - - database_migrator.open_connection(run_in_a_transaction); - Log.bound_to(this).log_an_info_event_containing("{0}", "=".PadRight(50, '=')); - Log.bound_to(this).log_an_info_event_containing("RoundhousE Structure"); - Log.bound_to(this).log_an_info_event_containing("{0}", "=".PadRight(50, '=')); - database_migrator.run_roundhouse_support_tasks(); - - Log.bound_to(this).log_an_info_event_containing("{0}", "=".PadRight(50, '=')); - Log.bound_to(this).log_an_info_event_containing("Versioning"); - Log.bound_to(this).log_an_info_event_containing("{0}", "=".PadRight(50, '=')); - string current_version = database_migrator.get_current_version(repository_path); - string new_version = version_resolver.resolve_version(); - Log.bound_to(this).log_an_info_event_containing(" Migrating {0} from version {1} to {2}.", database_migrator.database.database_name, current_version, new_version); - long version_id = database_migrator.version_the_database(repository_path, new_version); - - Log.bound_to(this).log_an_info_event_containing("{0}", "=".PadRight(50, '=')); - Log.bound_to(this).log_an_info_event_containing("Migration Scripts"); - Log.bound_to(this).log_an_info_event_containing("{0}", "=".PadRight(50, '=')); - - run_out_side_of_transaction_folder(known_folders.before_migration, version_id, new_version); - - if (!configuration.DoNotAlterDatabase) - { - database_migrator.open_admin_connection(); - log_and_traverse(known_folders.alter_database, version_id, new_version, ConnectionType.Admin); - database_migrator.close_admin_connection(); - } - - if (database_was_created) - { - log_and_traverse(known_folders.run_after_create_database, version_id, new_version, ConnectionType.Default); - } - - log_and_traverse(known_folders.run_before_up, version_id, new_version, ConnectionType.Default); - log_and_traverse(known_folders.up, version_id, new_version, ConnectionType.Default); - - //int last_errors = -1; - //int new_errors = 0; - //while (last_errors != new_errors || last_errors !=0) - //{ - - //} - log_and_traverse(known_folders.run_first_after_up, version_id, new_version, ConnectionType.Default); - log_and_traverse(known_folders.functions, version_id, new_version, ConnectionType.Default); - log_and_traverse(known_folders.views, version_id, new_version, ConnectionType.Default); - log_and_traverse(known_folders.sprocs, version_id, new_version, ConnectionType.Default); - log_and_traverse(known_folders.triggers, version_id, new_version, ConnectionType.Default); - log_and_traverse(known_folders.indexes, version_id, new_version, ConnectionType.Default); - log_and_traverse(known_folders.run_after_other_any_time_scripts, version_id, new_version, ConnectionType.Default); - - if (run_in_a_transaction) - { - database_migrator.close_connection(); - database_migrator.open_connection(false); - } - log_and_traverse(known_folders.permissions, version_id, new_version, ConnectionType.Default); - run_out_side_of_transaction_folder(known_folders.after_migration, version_id, new_version); - - Log.bound_to(this).log_an_info_event_containing( - "{0}{0}{1} v{2} has kicked your database ({3})! You are now at version {4}. All changes and backups can be found at \"{5}\".", - System.Environment.NewLine, - ApplicationParameters.name, - VersionInformation.get_current_assembly_version(), - database_migrator.database.database_name, - new_version, - known_folders.change_drop.folder_full_path); - database_migrator.close_connection(); - } - else - { - database_migrator.open_admin_connection(); - database_migrator.delete_database(); - database_migrator.close_admin_connection(); - database_migrator.close_connection(); - Log.bound_to(this).log_an_info_event_containing("{0}{0}{1} has removed database ({2}). All changes and backups can be found at \"{3}\".", - System.Environment.NewLine, - ApplicationParameters.name, - database_migrator.database.database_name, - known_folders.change_drop.folder_full_path); - } - } - catch (Exception ex) - { - Log.bound_to(this).log_an_error_event_containing("{0} encountered an error.{1}{2}{3}", - ApplicationParameters.name, - run_in_a_transaction - ? " You were running in a transaction though, so the database should be in the state it was in prior to this piece running. This does not include a drop/create or any creation of a database, as those items can not run in a transaction." - : string.Empty, - System.Environment.NewLine, - ex.to_string()); - - throw; - } - finally - { - database_migrator.database.Dispose(); - //copy_log_file_to_change_drop_folder(); - } - } - - public void log_and_traverse(MigrationsFolder folder, long version_id, string new_version, ConnectionType connection_type) - { - Log.bound_to(this).log_an_info_event_containing("{0}", "-".PadRight(50, '-')); - - Log.bound_to(this).log_an_info_event_containing("Looking for {0} scripts in \"{1}\".{2}{3}", - folder.friendly_name, - folder.folder_full_path, - folder.should_run_items_in_folder_once ? " These should be one time only scripts." : string.Empty, - folder.should_run_items_in_folder_every_time ? " These scripts will run every time" : string.Empty); - - Log.bound_to(this).log_an_info_event_containing("{0}", "-".PadRight(50, '-')); - traverse_files_and_run_sql(folder.folder_full_path, version_id, folder, environment_set, new_version, connection_type); - } - - public void run_out_side_of_transaction_folder(MigrationsFolder folder, long version_id, string new_version) - { - if (!string.IsNullOrEmpty(folder.folder_name)) - { - if (run_in_a_transaction) - { - database_migrator.close_connection(); - database_migrator.open_connection(false); - } - - log_and_traverse(folder, version_id, new_version, ConnectionType.Default); - - if (run_in_a_transaction) - { - database_migrator.close_connection(); - database_migrator.open_connection(run_in_a_transaction); - } - } - } - - private string get_custom_create_database_script() - { - if (string.IsNullOrEmpty(configuration.CreateDatabaseCustomScript)) - { - return configuration.CreateDatabaseCustomScript; - } - - if (file_system.file_exists(configuration.CreateDatabaseCustomScript)) - { - return file_system.read_file_text(configuration.CreateDatabaseCustomScript); - } - - return configuration.CreateDatabaseCustomScript; - } - - private void create_change_drop_folder() - { - file_system.create_directory(known_folders.change_drop.folder_full_path); - } - - private void create_share_and_set_permissions_for_change_drop_folder() - { - //todo: implement creating share with change permissions - //todo: implement setting Everyone to full acess to this folder - } - - private void remove_share_from_change_drop_folder() - { - //todo: implement removal of the file share - } - - //todo:down story - - public void traverse_files_and_run_sql(string directory, long version_id, MigrationsFolder migration_folder, EnvironmentSet migrating_environment_set, - string repository_version, ConnectionType connection_type) - { - if (!file_system.directory_exists(directory)) return; - - var fileNames = configuration.SearchAllSubdirectoriesInsteadOfTraverse - ? file_system.get_all_file_name_strings_recurevly_in(directory, SQL_EXTENSION) - : file_system.get_all_file_name_strings_in(directory, SQL_EXTENSION); - foreach (string sql_file in fileNames) - { - string sql_file_text = replace_tokens(get_file_text(sql_file)); - Log.bound_to(this).log_a_debug_event_containing(" Found and running {0}.", sql_file); - bool the_sql_ran = database_migrator.run_sql(sql_file_text, file_system.get_file_name_from(sql_file), - migration_folder.should_run_items_in_folder_once, - migration_folder.should_run_items_in_folder_every_time, - version_id, migrating_environment_set, repository_version, repository_path, connection_type); - if (the_sql_ran) - { - try - { - copy_to_change_drop_folder(sql_file, migration_folder); - } - catch (Exception ex) - { - Log.bound_to(this).log_a_warning_event_containing("Unable to copy {0} to {1}. {2}{3}", sql_file, migration_folder.folder_full_path, - System.Environment.NewLine, ex.to_string()); - } - } - } - - if (configuration.SearchAllSubdirectoriesInsteadOfTraverse) return; - foreach (string child_directory in file_system.get_all_directory_name_strings_in(directory)) - { - traverse_files_and_run_sql(child_directory, version_id, migration_folder, migrating_environment_set, repository_version, connection_type); - } - } - - public string get_file_text(string file_location) - { - return file_system.read_file_text(file_location); - } - - public string replace_tokens(string sql_text) - { - if (configuration.DisableTokenReplacement) - { - return sql_text; - } - - return TokenReplacer.replace_tokens(configuration, sql_text); - } - - private void copy_to_change_drop_folder(string sql_file_ran, Folder migration_folder) - { - if (!configuration.DisableOutput) - { - string destination_file = file_system.combine_paths(known_folders.change_drop.folder_full_path, "itemsRan", - sql_file_ran.Replace(migration_folder.folder_path + System.IO.Path.DirectorySeparatorChar , string.Empty)); - file_system.verify_or_create_directory(file_system.get_directory_name_from(destination_file)); - Log.bound_to(this).log_a_debug_event_containing("Copying file {0} to {1}.", file_system.get_file_name_from(sql_file_ran), destination_file); - file_system.file_copy_unsafe(sql_file_ran, destination_file, true); - } - } - } +namespace roundhouse.runners +{ + using System; + using databases; + using folders; + using infrastructure; + using infrastructure.app; + using infrastructure.app.tokens; + using infrastructure.extensions; + using infrastructure.filesystem; + using infrastructure.logging; + using migrators; + using resolvers; + using roundhouse.environments; + + public sealed class RoundhouseMigrationRunner : IRunner + { + private readonly string repository_path; + private readonly EnvironmentSet environment_set; + private readonly KnownFolders known_folders; + private readonly FileSystemAccess file_system; + public DatabaseMigrator database_migrator { get; private set; } + private readonly VersionResolver version_resolver; + public bool silent { get; set; } + public bool dropping_the_database { get; set; } + private readonly bool dont_create_the_database; + private bool run_in_a_transaction; + private readonly ConfigurationPropertyHolder configuration; + private const string SQL_EXTENSION = "*.sql"; + + public RoundhouseMigrationRunner( + string repository_path, + EnvironmentSet environment_set, + KnownFolders known_folders, + FileSystemAccess file_system, + DatabaseMigrator database_migrator, + VersionResolver version_resolver, + bool silent, + bool dropping_the_database, + bool dont_create_the_database, + bool run_in_a_transaction, + ConfigurationPropertyHolder configuration) + { + this.known_folders = known_folders; + this.repository_path = repository_path; + this.environment_set = environment_set; + this.file_system = file_system; + this.database_migrator = database_migrator; + this.version_resolver = version_resolver; + this.silent = silent; + this.dropping_the_database = dropping_the_database; + this.dont_create_the_database = dont_create_the_database; + this.run_in_a_transaction = run_in_a_transaction; + this.configuration = configuration; + } + + public void run() + { + database_migrator.initialize_connections(); + + Log.bound_to(this).log_an_info_event_containing("Running {0} v{1} against {2} - {3}.", + ApplicationParameters.name, + VersionInformation.get_current_assembly_version(), + database_migrator.database.server_name, + database_migrator.database.database_name); + + Log.bound_to(this).log_an_info_event_containing("Looking in {0} for scripts to run.", known_folders.up.folder_path); + if (!silent) + { + Log.bound_to(this).log_an_info_event_containing("Please press enter when ready to kick..."); + Console.ReadLine(); + } + + if (run_in_a_transaction && !database_migrator.database.supports_ddl_transactions) + { + Log.bound_to(this).log_a_warning_event_containing("You asked to run in a transaction, but this databasetype doesn't support DDL transactions."); + if (!silent) + { + Log.bound_to(this).log_an_info_event_containing("Please press enter to continue without transaction support..."); + Console.ReadLine(); + } + run_in_a_transaction = false; + } + + create_change_drop_folder(); + Log.bound_to(this).log_a_debug_event_containing("The change_drop (output) folder is: {0}", known_folders.change_drop.folder_full_path); + Log.bound_to(this).log_a_debug_event_containing("Using SearchAllSubdirectoriesInsteadOfTraverse execution: {0}", configuration.SearchAllSubdirectoriesInsteadOfTraverse); + + try + { + Log.bound_to(this).log_an_info_event_containing("{0}", "=".PadRight(50, '=')); + Log.bound_to(this).log_an_info_event_containing("Setup, Backup, Create/Restore/Drop"); + Log.bound_to(this).log_an_info_event_containing("{0}", "=".PadRight(50, '=')); + create_share_and_set_permissions_for_change_drop_folder(); + //database_migrator.backup_database_if_it_exists(); + remove_share_from_change_drop_folder(); + + bool database_was_created = false; + + if (!dropping_the_database) + { + if (!dont_create_the_database) + { + database_was_created = database_migrator.create_or_restore_database(get_custom_create_database_script()); + } + + if (configuration.RecoveryMode != RecoveryMode.NoChange) + { + database_migrator.set_recovery_mode(configuration.RecoveryMode == RecoveryMode.Simple); + } + + database_migrator.open_connection(run_in_a_transaction); + Log.bound_to(this).log_an_info_event_containing("{0}", "=".PadRight(50, '=')); + Log.bound_to(this).log_an_info_event_containing("RoundhousE Structure"); + Log.bound_to(this).log_an_info_event_containing("{0}", "=".PadRight(50, '=')); + database_migrator.run_roundhouse_support_tasks(); + + Log.bound_to(this).log_an_info_event_containing("{0}", "=".PadRight(50, '=')); + Log.bound_to(this).log_an_info_event_containing("Versioning"); + Log.bound_to(this).log_an_info_event_containing("{0}", "=".PadRight(50, '=')); + string current_version = database_migrator.get_current_version(repository_path); + string new_version = version_resolver.resolve_version(); + Log.bound_to(this).log_an_info_event_containing(" Migrating {0} from version {1} to {2}.", database_migrator.database.database_name, current_version, new_version); + long version_id = database_migrator.version_the_database(repository_path, new_version); + + Log.bound_to(this).log_an_info_event_containing("{0}", "=".PadRight(50, '=')); + Log.bound_to(this).log_an_info_event_containing("Migration Scripts"); + Log.bound_to(this).log_an_info_event_containing("{0}", "=".PadRight(50, '=')); + + run_out_side_of_transaction_folder(known_folders.before_migration, version_id, new_version); + + if (!configuration.DoNotAlterDatabase) + { + database_migrator.open_admin_connection(); + log_and_traverse(known_folders.alter_database, version_id, new_version, ConnectionType.Admin); + database_migrator.close_admin_connection(); + } + + if (database_was_created) + { + log_and_traverse(known_folders.run_after_create_database, version_id, new_version, ConnectionType.Default); + } + + log_and_traverse(known_folders.run_before_up, version_id, new_version, ConnectionType.Default); + log_and_traverse(known_folders.up, version_id, new_version, ConnectionType.Default); + + //int last_errors = -1; + //int new_errors = 0; + //while (last_errors != new_errors || last_errors !=0) + //{ + + //} + log_and_traverse(known_folders.run_first_after_up, version_id, new_version, ConnectionType.Default); + log_and_traverse(known_folders.functions, version_id, new_version, ConnectionType.Default); + log_and_traverse(known_folders.views, version_id, new_version, ConnectionType.Default); + log_and_traverse(known_folders.sprocs, version_id, new_version, ConnectionType.Default); + log_and_traverse(known_folders.triggers, version_id, new_version, ConnectionType.Default); + log_and_traverse(known_folders.indexes, version_id, new_version, ConnectionType.Default); + log_and_traverse(known_folders.run_after_other_any_time_scripts, version_id, new_version, ConnectionType.Default); + + if (run_in_a_transaction) + { + database_migrator.close_connection(); + database_migrator.open_connection(false); + } + log_and_traverse(known_folders.permissions, version_id, new_version, ConnectionType.Default); + run_out_side_of_transaction_folder(known_folders.after_migration, version_id, new_version); + + Log.bound_to(this).log_an_info_event_containing( + "{0}{0}{1} v{2} has kicked your database ({3})! You are now at version {4}. All changes and backups can be found at \"{5}\".", + System.Environment.NewLine, + ApplicationParameters.name, + VersionInformation.get_current_assembly_version(), + database_migrator.database.database_name, + new_version, + known_folders.change_drop.folder_full_path); + database_migrator.close_connection(); + } + else + { + database_migrator.open_admin_connection(); + database_migrator.delete_database(); + database_migrator.close_admin_connection(); + database_migrator.close_connection(); + Log.bound_to(this).log_an_info_event_containing("{0}{0}{1} has removed database ({2}). All changes and backups can be found at \"{3}\".", + System.Environment.NewLine, + ApplicationParameters.name, + database_migrator.database.database_name, + known_folders.change_drop.folder_full_path); + } + } + catch (Exception ex) + { + Log.bound_to(this).log_an_error_event_containing("{0} encountered an error.{1}{2}{3}", + ApplicationParameters.name, + run_in_a_transaction + ? " You were running in a transaction though, so the database should be in the state it was in prior to this piece running. This does not include a drop/create or any creation of a database, as those items can not run in a transaction." + : string.Empty, + System.Environment.NewLine, + ex.to_string()); + + throw; + } + finally + { + database_migrator.database.Dispose(); + //copy_log_file_to_change_drop_folder(); + } + } + + public void log_and_traverse(MigrationsFolder folder, long version_id, string new_version, ConnectionType connection_type) + { + Log.bound_to(this).log_an_info_event_containing("{0}", "-".PadRight(50, '-')); + + Log.bound_to(this).log_an_info_event_containing("Looking for {0} scripts in \"{1}\".{2}{3}", + folder.friendly_name, + folder.folder_full_path, + folder.should_run_items_in_folder_once ? " These should be one time only scripts." : string.Empty, + folder.should_run_items_in_folder_every_time ? " These scripts will run every time" : string.Empty); + + Log.bound_to(this).log_an_info_event_containing("{0}", "-".PadRight(50, '-')); + traverse_files_and_run_sql(folder.folder_full_path, version_id, folder, environment_set, new_version, connection_type); + } + + public void run_out_side_of_transaction_folder(MigrationsFolder folder, long version_id, string new_version) + { + if (!string.IsNullOrEmpty(folder.folder_name)) + { + if (run_in_a_transaction) + { + database_migrator.close_connection(); + database_migrator.open_connection(false); + } + + log_and_traverse(folder, version_id, new_version, ConnectionType.Default); + + if (run_in_a_transaction) + { + database_migrator.close_connection(); + database_migrator.open_connection(run_in_a_transaction); + } + } + } + + private string get_custom_create_database_script() + { + if (string.IsNullOrEmpty(configuration.CreateDatabaseCustomScript)) + { + return configuration.CreateDatabaseCustomScript; + } + + if (file_system.file_exists(configuration.CreateDatabaseCustomScript)) + { + return file_system.read_file_text(configuration.CreateDatabaseCustomScript); + } + + return configuration.CreateDatabaseCustomScript; + } + + private void create_change_drop_folder() + { + file_system.create_directory(known_folders.change_drop.folder_full_path); + } + + private void create_share_and_set_permissions_for_change_drop_folder() + { + //todo: implement creating share with change permissions + //todo: implement setting Everyone to full acess to this folder + } + + private void remove_share_from_change_drop_folder() + { + //todo: implement removal of the file share + } + + //todo:down story + + public void traverse_files_and_run_sql(string directory, long version_id, MigrationsFolder migration_folder, EnvironmentSet migrating_environment_set, + string repository_version, ConnectionType connection_type) + { + if (!file_system.directory_exists(directory)) return; + + var fileNames = configuration.SearchAllSubdirectoriesInsteadOfTraverse + ? file_system.get_all_file_name_strings_recurevly_in(directory, SQL_EXTENSION) + : file_system.get_all_file_name_strings_in(directory, SQL_EXTENSION); + foreach (string sql_file in fileNames) + { + string sql_file_text = replace_tokens(get_file_text(sql_file)); + Log.bound_to(this).log_a_debug_event_containing(" Found and running {0}.", sql_file); + bool the_sql_ran = database_migrator.run_sql(sql_file_text, file_system.get_file_name_from(sql_file), + migration_folder.should_run_items_in_folder_once, + migration_folder.should_run_items_in_folder_every_time, + version_id, migrating_environment_set, repository_version, repository_path, connection_type); + if (the_sql_ran) + { + try + { + copy_to_change_drop_folder(sql_file, migration_folder); + } + catch (Exception ex) + { + Log.bound_to(this).log_a_warning_event_containing("Unable to copy {0} to {1}. {2}{3}", sql_file, migration_folder.folder_full_path, + System.Environment.NewLine, ex.to_string()); + } + } + } + + if (configuration.SearchAllSubdirectoriesInsteadOfTraverse) return; + foreach (string child_directory in file_system.get_all_directory_name_strings_in(directory)) + { + traverse_files_and_run_sql(child_directory, version_id, migration_folder, migrating_environment_set, repository_version, connection_type); + } + } + + public string get_file_text(string file_location) + { + return file_system.read_file_text(file_location); + } + + public string replace_tokens(string sql_text) + { + if (configuration.DisableTokenReplacement) + { + return sql_text; + } + + return TokenReplacer.replace_tokens(configuration, sql_text); + } + + private void copy_to_change_drop_folder(string sql_file_ran, Folder migration_folder) + { + if (!configuration.DisableOutput) + { + string destination_file = file_system.combine_paths(known_folders.change_drop.folder_full_path, "itemsRan", + sql_file_ran.Replace(migration_folder.folder_path + System.IO.Path.DirectorySeparatorChar , string.Empty)); + file_system.verify_or_create_directory(file_system.get_directory_name_from(destination_file)); + Log.bound_to(this).log_a_debug_event_containing("Copying file {0} to {1}.", file_system.get_file_name_from(sql_file_ran), destination_file); + file_system.file_copy_unsafe(sql_file_ran, destination_file, true); + } + } + } } \ No newline at end of file diff --git a/product/roundhouse/runners/RoundhouseNHibernateCompareRunner.cs b/product/roundhouse.core/runners/RoundhouseNHibernateCompareRunner.cs similarity index 96% rename from product/roundhouse/runners/RoundhouseNHibernateCompareRunner.cs rename to product/roundhouse.core/runners/RoundhouseNHibernateCompareRunner.cs index bbbc378f..9909886d 100644 --- a/product/roundhouse/runners/RoundhouseNHibernateCompareRunner.cs +++ b/product/roundhouse.core/runners/RoundhouseNHibernateCompareRunner.cs @@ -1,18 +1,18 @@ -namespace roundhouse.runners -{ - public class RoundhouseNHibernateCompareRunner{ - private readonly string server; - private readonly string database_name; - - public RoundhouseNHibernateCompareRunner(string server, string database_name) - { - this.server = server; - this.database_name = database_name; - } - - public void run() - { - - } - } +namespace roundhouse.runners +{ + public class RoundhouseNHibernateCompareRunner{ + private readonly string server; + private readonly string database_name; + + public RoundhouseNHibernateCompareRunner(string server, string database_name) + { + this.server = server; + this.database_name = database_name; + } + + public void run() + { + + } + } } \ No newline at end of file diff --git a/product/roundhouse/runners/RoundhouseRedGateCompareRunner.cs b/product/roundhouse.core/runners/RoundhouseRedGateCompareRunner.cs similarity index 98% rename from product/roundhouse/runners/RoundhouseRedGateCompareRunner.cs rename to product/roundhouse.core/runners/RoundhouseRedGateCompareRunner.cs index e86161ac..0e6572d5 100644 --- a/product/roundhouse/runners/RoundhouseRedGateCompareRunner.cs +++ b/product/roundhouse.core/runners/RoundhouseRedGateCompareRunner.cs @@ -1,81 +1,81 @@ -namespace roundhouse.runners -{ - using System.Collections.Generic; - using System.Linq; - using consoles; - using folders; - using infrastructure.app; - using infrastructure.extensions; - using infrastructure.filesystem; - using Environment = environments.Environment; - - public class RoundhouseRedGateCompareRunner : IRunner - { - private readonly KnownFolders known_folders; - private readonly FileSystemAccess file_system; - private readonly ConfigurationPropertyHolder configuration; - private readonly RoundhouseMigrationRunner migration_runner; - private readonly string redgate_install_location = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ProgramFiles) + @"\Red Gate\SQL Compare 8"; - private const string redgate_compare_tool = @"sqlcompare.exe"; - - public RoundhouseRedGateCompareRunner(KnownFolders known_folders, FileSystemAccess file_system, ConfigurationPropertyHolder configuration, RoundhouseMigrationRunner migration_runner) - { - this.known_folders = known_folders; - this.file_system = file_system; - this.configuration = configuration; - this.migration_runner = migration_runner; - } - - - public void run() - { - string database_name = migration_runner.database_migrator.database.database_name; - - // run roundhouse to drop a database + base - migration_runner.database_migrator.database.database_name += "_BASE"; - migration_runner.silent = true; - migration_runner.dropping_the_database = true; - migration_runner.run(); - // run roundhouse to create a database + base - migration_runner.silent = true; - migration_runner.dropping_the_database = false; - migration_runner.run(); - // get the next number from the folder - string next_change_number = get_new_change_number(); - // set up your arguments - - string redgate_args = string.Format(@"/database1:""{0}"" /database2:""{0}_BASE"" /include:table /exclude:table:\[{1}\]^|\[{2}\]^|\[{3}\] /exclude:view /options:Default,IgnoreConstraintNames,IgnorePermissions /ignoreparsererrors /f /scriptfile:""{4}\{5}_Changes.sql""", database_name, configuration.VersionTableName, configuration.ScriptsRunTableName, configuration.ScriptsRunErrorsTableName, file_system.get_full_path(known_folders.up.folder_full_path), next_change_number); - // run redgate - CommandExecutor.execute(file_system.combine_paths(redgate_install_location, redgate_compare_tool), redgate_args, true); - // run rouhdhouse to drop a database + base - migration_runner.silent = true; - migration_runner.dropping_the_database = true; - migration_runner.run(); - } - - public string get_new_change_number() - { - string[] files = file_system.get_all_file_name_strings_in(known_folders.up.folder_full_path); - IList file_numbers = files.Select(file => file_system.get_file_name_from(file).Substring(0, file_system.get_file_name_from(file).IndexOf('_'))).ToList(); - - int length_of_number_format = 0; - decimal highest_number = 0; - foreach (string file_number in file_numbers) - { - decimal test_number = 0; - decimal.TryParse(file_number, out test_number); - if (test_number != 0) - { - if (test_number > highest_number) - { - highest_number = test_number; - } - length_of_number_format = file_number.Length; - } - } - string next_change_number = (highest_number + 1).to_string().PadLeft(length_of_number_format, '0'); - - return next_change_number; - } - } +namespace roundhouse.runners +{ + using System.Collections.Generic; + using System.Linq; + using consoles; + using folders; + using infrastructure.app; + using infrastructure.extensions; + using infrastructure.filesystem; + using Environment = environments.Environment; + + public class RoundhouseRedGateCompareRunner : IRunner + { + private readonly KnownFolders known_folders; + private readonly FileSystemAccess file_system; + private readonly ConfigurationPropertyHolder configuration; + private readonly RoundhouseMigrationRunner migration_runner; + private readonly string redgate_install_location = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ProgramFiles) + @"\Red Gate\SQL Compare 8"; + private const string redgate_compare_tool = @"sqlcompare.exe"; + + public RoundhouseRedGateCompareRunner(KnownFolders known_folders, FileSystemAccess file_system, ConfigurationPropertyHolder configuration, RoundhouseMigrationRunner migration_runner) + { + this.known_folders = known_folders; + this.file_system = file_system; + this.configuration = configuration; + this.migration_runner = migration_runner; + } + + + public void run() + { + string database_name = migration_runner.database_migrator.database.database_name; + + // run roundhouse to drop a database + base + migration_runner.database_migrator.database.database_name += "_BASE"; + migration_runner.silent = true; + migration_runner.dropping_the_database = true; + migration_runner.run(); + // run roundhouse to create a database + base + migration_runner.silent = true; + migration_runner.dropping_the_database = false; + migration_runner.run(); + // get the next number from the folder + string next_change_number = get_new_change_number(); + // set up your arguments + + string redgate_args = string.Format(@"/database1:""{0}"" /database2:""{0}_BASE"" /include:table /exclude:table:\[{1}\]^|\[{2}\]^|\[{3}\] /exclude:view /options:Default,IgnoreConstraintNames,IgnorePermissions /ignoreparsererrors /f /scriptfile:""{4}\{5}_Changes.sql""", database_name, configuration.VersionTableName, configuration.ScriptsRunTableName, configuration.ScriptsRunErrorsTableName, file_system.get_full_path(known_folders.up.folder_full_path), next_change_number); + // run redgate + CommandExecutor.execute(file_system.combine_paths(redgate_install_location, redgate_compare_tool), redgate_args, true); + // run rouhdhouse to drop a database + base + migration_runner.silent = true; + migration_runner.dropping_the_database = true; + migration_runner.run(); + } + + public string get_new_change_number() + { + string[] files = file_system.get_all_file_name_strings_in(known_folders.up.folder_full_path); + IList file_numbers = files.Select(file => file_system.get_file_name_from(file).Substring(0, file_system.get_file_name_from(file).IndexOf('_'))).ToList(); + + int length_of_number_format = 0; + decimal highest_number = 0; + foreach (string file_number in file_numbers) + { + decimal test_number = 0; + decimal.TryParse(file_number, out test_number); + if (test_number != 0) + { + if (test_number > highest_number) + { + highest_number = test_number; + } + length_of_number_format = file_number.Length; + } + } + string next_change_number = (highest_number + 1).to_string().PadLeft(length_of_number_format, '0'); + + return next_change_number; + } + } } \ No newline at end of file diff --git a/product/roundhouse/runners/RoundhouseUpdateCheckRunner.cs b/product/roundhouse.core/runners/RoundhouseUpdateCheckRunner.cs similarity index 100% rename from product/roundhouse/runners/RoundhouseUpdateCheckRunner.cs rename to product/roundhouse.core/runners/RoundhouseUpdateCheckRunner.cs diff --git a/product/roundhouse/sqlsplitters/StatementSplitter.cs b/product/roundhouse.core/sqlsplitters/StatementSplitter.cs similarity index 97% rename from product/roundhouse/sqlsplitters/StatementSplitter.cs rename to product/roundhouse.core/sqlsplitters/StatementSplitter.cs index 5e202462..9fc5f135 100644 --- a/product/roundhouse/sqlsplitters/StatementSplitter.cs +++ b/product/roundhouse.core/sqlsplitters/StatementSplitter.cs @@ -1,50 +1,50 @@ -namespace roundhouse.sqlsplitters -{ - using System.Collections.Generic; - using System.Text.RegularExpressions; - using infrastructure.extensions; - - public class StatementSplitter - { - public static string batch_terminator_replacement_string = @" |{[_REMOVE_]}| "; - public static string regex_split_string = @"\|\{\[_REMOVE_\]\}\|"; - - public static IEnumerable split_sql_on_regex_and_remove_empty_statements(string sql_to_run, string sql_statement_separator_regex_pattern) - { - IList return_sql_list = new List(); - - Regex regex_replace = new Regex(sql_statement_separator_regex_pattern, RegexOptions.IgnoreCase | RegexOptions.Multiline); - - string sql_statement_scrubbed = regex_replace.Replace(sql_to_run, match => evaluate_and_replace_batch_split_items(match, regex_replace)); - - foreach (string sql_statement in Regex.Split(sql_statement_scrubbed, regex_split_string, RegexOptions.IgnoreCase | RegexOptions.Multiline)) - { - if (script_has_text_to_run(sql_statement, sql_statement_separator_regex_pattern)) - { - return_sql_list.Add(sql_statement); - } - } - - return return_sql_list; - } - - public static string evaluate_and_replace_batch_split_items(Match matched_item, Regex regex) - { - if (matched_item.Groups["BATCHSPLITTER"].Success) - { - return matched_item.Groups["KEEP1"].Value + batch_terminator_replacement_string + matched_item.Groups["KEEP2"].Value; - } - else - { - return matched_item.Groups["KEEP1"].Value + matched_item.Groups["KEEP2"].Value; - } - } - - private static bool script_has_text_to_run(string sql_statement, string sql_statement_separator_regex_pattern) - { - sql_statement = Regex.Replace(sql_statement, regex_split_string, string.Empty, RegexOptions.IgnoreCase | RegexOptions.Multiline); - - return !string.IsNullOrEmpty(sql_statement.to_lower().Replace(System.Environment.NewLine, string.Empty).Replace(" ", string.Empty)); - } - } +namespace roundhouse.sqlsplitters +{ + using System.Collections.Generic; + using System.Text.RegularExpressions; + using infrastructure.extensions; + + public class StatementSplitter + { + public static string batch_terminator_replacement_string = @" |{[_REMOVE_]}| "; + public static string regex_split_string = @"\|\{\[_REMOVE_\]\}\|"; + + public static IEnumerable split_sql_on_regex_and_remove_empty_statements(string sql_to_run, string sql_statement_separator_regex_pattern) + { + IList return_sql_list = new List(); + + Regex regex_replace = new Regex(sql_statement_separator_regex_pattern, RegexOptions.IgnoreCase | RegexOptions.Multiline); + + string sql_statement_scrubbed = regex_replace.Replace(sql_to_run, match => evaluate_and_replace_batch_split_items(match, regex_replace)); + + foreach (string sql_statement in Regex.Split(sql_statement_scrubbed, regex_split_string, RegexOptions.IgnoreCase | RegexOptions.Multiline)) + { + if (script_has_text_to_run(sql_statement, sql_statement_separator_regex_pattern)) + { + return_sql_list.Add(sql_statement); + } + } + + return return_sql_list; + } + + public static string evaluate_and_replace_batch_split_items(Match matched_item, Regex regex) + { + if (matched_item.Groups["BATCHSPLITTER"].Success) + { + return matched_item.Groups["KEEP1"].Value + batch_terminator_replacement_string + matched_item.Groups["KEEP2"].Value; + } + else + { + return matched_item.Groups["KEEP1"].Value + matched_item.Groups["KEEP2"].Value; + } + } + + private static bool script_has_text_to_run(string sql_statement, string sql_statement_separator_regex_pattern) + { + sql_statement = Regex.Replace(sql_statement, regex_split_string, string.Empty, RegexOptions.IgnoreCase | RegexOptions.Multiline); + + return !string.IsNullOrEmpty(sql_statement.to_lower().Replace(System.Environment.NewLine, string.Empty).Replace(" ", string.Empty)); + } + } } \ No newline at end of file diff --git a/product/roundhouse/targets/Microsoft.Application.targets b/product/roundhouse.core/targets/Microsoft.Application.targets similarity index 98% rename from product/roundhouse/targets/Microsoft.Application.targets rename to product/roundhouse.core/targets/Microsoft.Application.targets index 4b32a2f9..4dc41308 100644 --- a/product/roundhouse/targets/Microsoft.Application.targets +++ b/product/roundhouse.core/targets/Microsoft.Application.targets @@ -1,234 +1,234 @@ - - - - - - False - True - False - $(ExeProjectOutputDirInsideProjectDefault) - $(MSBuildProjectDirectory) - $(OutDir)_PublishedApplications\$(MSBuildProjectName) - False - False - True - False - - - - - $(PrepareForRunDependsOn); - - - $(PrepareForRunDependsOn); - _CopyExeApplication; - _BuiltExeOutputGroupOutput - - - - - - - - - - - - - - - - $(CleanDependsOn); - CleanExeProjectOutputDir; - - - - - - - - - - - - - - - - - - - - - - _CopyExeApplicationLegacy; - - - $(OnBefore_CopyExeApplicationDefault); - - - - - - <_CopyExeApplicationDependsOn Condition="'$(_CopyExeApplicationDependsOn)'==''"> - $(OnBefore_CopyExeApplication); - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + False + True + False + $(ExeProjectOutputDirInsideProjectDefault) + $(MSBuildProjectDirectory) + $(OutDir)_PublishedApplications\$(MSBuildProjectName) + False + False + True + False + + + + + $(PrepareForRunDependsOn); + + + $(PrepareForRunDependsOn); + _CopyExeApplication; + _BuiltExeOutputGroupOutput + + + + + + + + + + + + + + + + $(CleanDependsOn); + CleanExeProjectOutputDir; + + + + + + + + + + + + + + + + + + + + + + _CopyExeApplicationLegacy; + + + $(OnBefore_CopyExeApplicationDefault); + + + + + + <_CopyExeApplicationDependsOn Condition="'$(_CopyExeApplicationDependsOn)'==''"> + $(OnBefore_CopyExeApplication); + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/product/roundhouse.databases.access/roundhouse.databases.access.csproj b/product/roundhouse.databases.access/roundhouse.databases.access.csproj index ac972978..b9360014 100644 --- a/product/roundhouse.databases.access/roundhouse.databases.access.csproj +++ b/product/roundhouse.databases.access/roundhouse.databases.access.csproj @@ -1,4 +1,4 @@ - + net461 true @@ -13,10 +13,25 @@ true bin\$(Configuration)\ - - - AllRules.ruleset + + + $(Version) + $(NugetVersion) + roundhouse.access + RoundhousE Library - Microsoft Access + Rob Reynolds + + RoundhousE is a Professional Database Change and Versioning Management tool. + +This is the MS Access database package. + + http://projectroundhouse.org + Apache-2.0 + false + roundhouse db migration database migrator chucknorris access + https://raw.github.com/chucknorris/roundhouse/master/nuget/RoundhousE_Logo.NuGet.jpg + true @@ -36,12 +51,6 @@ false - - - - - - - + \ No newline at end of file diff --git a/product/roundhouse.databases.mysql/roundhouse.databases.mysql.csproj b/product/roundhouse.databases.mysql/roundhouse.databases.mysql.csproj index c2bdc0aa..05bc86ef 100644 --- a/product/roundhouse.databases.mysql/roundhouse.databases.mysql.csproj +++ b/product/roundhouse.databases.mysql/roundhouse.databases.mysql.csproj @@ -1,4 +1,4 @@ - + netstandard2.0 true @@ -13,11 +13,26 @@ true bin\$(Configuration)\ - - - AllRules.ruleset + + + $(Version) + $(NugetVersion) + roundhouse.mysql + RoundhousE Library - MySql + Rob Reynolds, Erik A. Brandstadmoen + + RoundhousE is a Professional Database Change and Versioning Management tool. + +This is the MySql database package. + + http://projectroundhouse.org + Apache-2.0 + false + roundhouse db migration database migrator chucknorris mysql mariadb + https://raw.github.com/chucknorris/roundhouse/master/nuget/RoundhousE_Logo.NuGet.jpg - + + true full @@ -37,13 +52,10 @@ false - - - - + - + \ No newline at end of file diff --git a/product/roundhouse.databases.oracle/roundhouse.databases.oracle.csproj b/product/roundhouse.databases.oracle/roundhouse.databases.oracle.csproj index 7ec13357..12503ab9 100644 --- a/product/roundhouse.databases.oracle/roundhouse.databases.oracle.csproj +++ b/product/roundhouse.databases.oracle/roundhouse.databases.oracle.csproj @@ -1,4 +1,4 @@ - + net461 true @@ -14,11 +14,27 @@ true bin\$(Configuration)\ - - - AllRules.ruleset + + + + $(Version) + $(NugetVersion) + roundhouse.oracle + RoundhousE Library - Oracle + Rob Reynolds + + RoundhousE is a Professional Database Change and Versioning Management tool. + +This is the Oracle database package. + + http://projectroundhouse.org + Apache-2.0 + false + roundhouse db migration database migrator chucknorris oracle + https://raw.github.com/chucknorris/roundhouse/master/nuget/RoundhousE_Logo.NuGet.jpg - + + true full @@ -39,18 +55,13 @@ false - + - - - - - - + \ No newline at end of file diff --git a/product/roundhouse.databases.postgresql/roundhouse.databases.postgresql.csproj b/product/roundhouse.databases.postgresql/roundhouse.databases.postgresql.csproj index 1bbd9a78..77aa4411 100644 --- a/product/roundhouse.databases.postgresql/roundhouse.databases.postgresql.csproj +++ b/product/roundhouse.databases.postgresql/roundhouse.databases.postgresql.csproj @@ -1,49 +1,61 @@ - - - netstandard2.0 - true - true - Debug - AnyCPU - Library - roundhouse.databases.postgresql - roundhouse.databases.postgresql - ..\..\ - NU1701 - true - true - bin\$(Configuration)\ - - - - AllRules.ruleset - - - - true - full - false - DEBUG;TRACE - prompt - 4 - false - - - pdbonly - true - TRACE - prompt - 4 - false - - - - - - - - - - - + + + netstandard2.0 + true + true + Debug + AnyCPU + Library + roundhouse.databases.postgresql + roundhouse.databases.postgresql + ..\..\ + NU1701 + true + true + bin\$(Configuration)\ + + + + $(Version) + $(NugetVersion) + roundhouse.postgresql + RoundhousE Library - PostgreSQL + Rob Reynolds, Erik A. Brandstadmoen + + RoundhousE is a Professional Database Change and Versioning Management tool. + +This is the PostgreSQL database package. + + http://projectroundhouse.org + Apache-2.0 + false + roundhouse db migration database migrator chucknorris postgresql postgres + https://raw.github.com/chucknorris/roundhouse/master/nuget/RoundhousE_Logo.NuGet.jpg + + + + + true + full + false + DEBUG;TRACE + prompt + 4 + false + + + pdbonly + true + TRACE + prompt + 4 + false + + + + + + + + \ No newline at end of file diff --git a/product/roundhouse.databases.sqlite/packages.config b/product/roundhouse.databases.sqlite/packages.config deleted file mode 100644 index d3d87e97..00000000 --- a/product/roundhouse.databases.sqlite/packages.config +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/product/roundhouse.databases.sqlite/roundhouse.databases.sqlite.csproj b/product/roundhouse.databases.sqlite/roundhouse.databases.sqlite.csproj index bba2b7d8..53a1d5d7 100644 --- a/product/roundhouse.databases.sqlite/roundhouse.databases.sqlite.csproj +++ b/product/roundhouse.databases.sqlite/roundhouse.databases.sqlite.csproj @@ -14,11 +14,26 @@ true bin\$(Configuration)\ - - - AllRules.ruleset + + + $(Version) + $(NugetVersion) + roundhouse.sqlite + RoundhousE Library - SQLite + Rob Reynolds, Erik A. Brandstadmoen + + RoundhousE is a Professional Database Change and Versioning Management tool. + +This is the SQLite database package. + + http://projectroundhouse.org + Apache-2.0 + false + roundhouse db migration database migrator chucknorris sqlite + https://raw.github.com/chucknorris/roundhouse/master/nuget/RoundhousE_Logo.NuGet.jpg - + + true full @@ -40,14 +55,10 @@ false - - - - - + - + diff --git a/product/roundhouse.databases.sqlserver/ReliableSqlConnection.cs b/product/roundhouse.databases.sqlserver/ReliableSqlConnection.cs index 86603bf0..3a9ecddf 100644 --- a/product/roundhouse.databases.sqlserver/ReliableSqlConnection.cs +++ b/product/roundhouse.databases.sqlserver/ReliableSqlConnection.cs @@ -14,7 +14,7 @@ namespace roundhouse.databases.sqlserver { - public sealed class ReliableSqlConnection : IDbConnection, ICloneable + internal sealed class ReliableSqlConnection : IDbConnection, ICloneable { private static readonly TransientErrorDetectionStrategy error_detection_strategy = new TransientErrorDetectionStrategy(); diff --git a/product/roundhouse.databases.sqlserver/roundhouse.databases.sqlserver.csproj b/product/roundhouse.databases.sqlserver/roundhouse.databases.sqlserver.csproj index a7451075..904ac8bf 100644 --- a/product/roundhouse.databases.sqlserver/roundhouse.databases.sqlserver.csproj +++ b/product/roundhouse.databases.sqlserver/roundhouse.databases.sqlserver.csproj @@ -1,4 +1,4 @@ - + netstandard2.0 true @@ -8,16 +8,33 @@ Library roundhouse.databases.sqlserver roundhouse.databases.sqlserver + roundhouse.sqlserver ..\..\ NU1701 true true bin\$(Configuration)\ - - - AllRules.ruleset + + + + $(Version) + $(NugetVersion) + roundhouse.sqlserver + RoundhousE Library - SQLServer + Rob Reynolds, Erik A. Brandstadmoen + + RoundhousE is a Professional Database Change and Versioning Management tool. + +This is the Microsoft SQL Server database package. + + http://projectroundhouse.org + Apache-2.0 + false + roundhouse db migration database migrator chucknorris sqlserver + https://raw.github.com/chucknorris/roundhouse/master/nuget/RoundhousE_Logo.NuGet.jpg + true @@ -38,13 +55,10 @@ false - - - - - + + - + \ No newline at end of file diff --git a/product/roundhouse.databases.sqlserver2000/packages.config b/product/roundhouse.databases.sqlserver2000/packages.config deleted file mode 100644 index dd827cd1..00000000 --- a/product/roundhouse.databases.sqlserver2000/packages.config +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/product/roundhouse.databases.sqlserver2000/roundhouse.databases.sqlserver2000.csproj b/product/roundhouse.databases.sqlserver2000/roundhouse.databases.sqlserver2000.csproj index f6142fbf..38d2a0b9 100644 --- a/product/roundhouse.databases.sqlserver2000/roundhouse.databases.sqlserver2000.csproj +++ b/product/roundhouse.databases.sqlserver2000/roundhouse.databases.sqlserver2000.csproj @@ -1,4 +1,4 @@ - + netstandard2.0 true @@ -8,15 +8,30 @@ Library roundhouse.databases.sqlserver2000 roundhouse.databases.sqlserver2000 + roundhouse.sqlserver2000 ..\..\ NU1701 true true bin\$(Configuration)\ - - - AllRules.ruleset + + + $(Version) + $(NugetVersion) + roundhouse.sqlserver2000 + RoundhousE Library - SQLServer 2000 + Rob Reynolds, Erik A. Brandstadmoen + + RoundhousE is a Professional Database Change and Versioning Management tool. + +This is the Microsoft SQL Server 2000 database package. + + http://projectroundhouse.org + Apache-2.0 + false + roundhouse db migration database migrator chucknorris sqlserver sqlserver2000 + https://raw.github.com/chucknorris/roundhouse/master/nuget/RoundhousE_Logo.NuGet.jpg @@ -38,11 +53,6 @@ false - - - - - - + \ No newline at end of file diff --git a/product/roundhouse.databases.sqlserverce/roundhouse.databases.sqlserverce.csproj b/product/roundhouse.databases.sqlserverce/roundhouse.databases.sqlserverce.csproj index 77e9d14a..d9d7211f 100644 --- a/product/roundhouse.databases.sqlserverce/roundhouse.databases.sqlserverce.csproj +++ b/product/roundhouse.databases.sqlserverce/roundhouse.databases.sqlserverce.csproj @@ -1,4 +1,4 @@ - + netstandard2.0 true @@ -9,15 +9,30 @@ Library roundhouse.databases.sqlserverce roundhouse.databases.sqlserverce + roundhouse.sqlserverce ..\..\ NU1701 true true bin\$(Configuration)\ - - - AllRules.ruleset + + + $(Version) + $(NugetVersion) + roundhouse.sqlserverce + RoundhousE Library - SQLServer CE + Rob Reynolds, Erik A. Brandstadmoen + + RoundhousE is a Professional Database Change and Versioning Management tool. + +This is the SQL Server CE (Compact Edition) database package. + + http://projectroundhouse.org + Apache-2.0 + false + roundhouse db migration database migrator chucknorris sqlserver sqlserverce sqlservercompact + https://raw.github.com/chucknorris/roundhouse/master/nuget/RoundhousE_Logo.NuGet.jpg @@ -37,12 +52,9 @@ false - - - - + \ No newline at end of file diff --git a/product/roundhouse.lib/Properties/AssemblyInfo.cs b/product/roundhouse.lib/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..4f559238 --- /dev/null +++ b/product/roundhouse.lib/Properties/AssemblyInfo.cs @@ -0,0 +1,6 @@ +using System.Reflection; +using System.Runtime.InteropServices; + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("98970d0a-698b-4b84-a01c-a0555d1b178c")] +[assembly: System.CLSCompliant(true)] diff --git a/product/roundhouse.lib.merged/roundhouse.lib.merged.csproj b/product/roundhouse.lib/roundhouse.lib.csproj similarity index 54% rename from product/roundhouse.lib.merged/roundhouse.lib.merged.csproj rename to product/roundhouse.lib/roundhouse.lib.csproj index 8785ebad..730352cf 100644 --- a/product/roundhouse.lib.merged/roundhouse.lib.merged.csproj +++ b/product/roundhouse.lib/roundhouse.lib.csproj @@ -1,4 +1,4 @@ - + net461;netstandard2.0 true @@ -8,32 +8,32 @@ Library Properties roundhouse - roundhouse.lib.merged + roundhouse.lib ..\..\ NU1701 true true bin\$(Configuration)\ - 0.8.9 - alpha - $(VersionPrefix) - $(Version)-$(VersionSuffix) + + + $(Version) $(NugetVersion) roundhouse.lib - RoundhousE Library + RoundhousE Library - all in one Rob Reynolds - RoundhousE is a Professional Database Change and Versioning Management tool. + + RoundhousE is a Professional Database Change and Versioning Management tool. + +This is an "include all" package that gives you all the databases. If you want only a single one, please feel fre to reference only the database of your choice (e.g. roundhouse.sqlserver). + http://projectroundhouse.org - http://www.apache.org/licenses/LICENSE-2.0 + Apache-2.0 false roundhouse db migration database migrator chucknorris https://raw.github.com/chucknorris/roundhouse/master/nuget/RoundhousE_Logo.NuGet.jpg - - - AllRules.ruleset - + true @@ -44,7 +44,7 @@ 4 AnyCPU false - 5 + default none @@ -66,8 +66,9 @@ - + + roundhouse.ico @@ -79,48 +80,7 @@ - + - - - - ..\..\code_drop\merge\ - ..\..\code_drop\log\ - $(ILMergeDir)roundhouse.dll - - - - - - - - - ..\..\build.custom\ilmerge.internalize.ignore.txt - ..\..\lib\ILMerge\ILMerge.exe - $(NugetPackageRoot)\ilmerge\3.0.21\tools\net452\ILMerge.exe - $(LogDir)roundhouse.ILMerge.log - $(ILMerge) /internalize:$(IgnoreFile) /target:dll /out:$(ILMergeTarget) /log:$(ILMergeLog) /ndebug /zeroPeKind /allowDup @(ILMergeAssemblies, ' ') - - - - - - - - - - - - roundhouse.lib.nuspec - mergedDll=$(ILMergeTarget);configuration=$(Configuration);assemblyName=$(AssemblyName);version=$(NugetVersion) - - - - - - - - - \ No newline at end of file diff --git a/product/roundhouse.lib.merged/roundhouse.lib.nuspec b/product/roundhouse.lib/roundhouse.lib.nuspecZ similarity index 100% rename from product/roundhouse.lib.merged/roundhouse.lib.nuspec rename to product/roundhouse.lib/roundhouse.lib.nuspecZ diff --git a/product/roundhouse.tasks/packages.config b/product/roundhouse.tasks/packages.config deleted file mode 100644 index d36a244d..00000000 --- a/product/roundhouse.tasks/packages.config +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - \ No newline at end of file diff --git a/product/roundhouse.tasks/roundhouse.tasks.csproj b/product/roundhouse.tasks/roundhouse.tasks.csproj index 8d4aa9c2..90ad97d9 100644 --- a/product/roundhouse.tasks/roundhouse.tasks.csproj +++ b/product/roundhouse.tasks/roundhouse.tasks.csproj @@ -1,4 +1,4 @@ - + net461 true @@ -13,27 +13,23 @@ true true bin\$(Configuration)\ - 0.8.9 - alpha - $(VersionPrefix) - $(Version)-$(VersionSuffix) + + + + $(Version) $(NugetVersion) roundhouse.msbuild RoundhousE MSBuild - Rob Reynolds + Rob Reynolds, Erik A. Brandstaedmoen RoundhousE is a Professional Database Change and Versioning Management tool. http://projectroundhouse.org - http://www.apache.org/licenses/LICENSE-2.0 + Apache-2.0 false roundhouse db migration database migrator chucknorris https://raw.github.com/chucknorris/roundhouse/master/nuget/RoundhousE_Logo.NuGet.jpg - - AllRules.ruleset - - true full @@ -68,7 +64,7 @@ - + @@ -81,7 +77,7 @@ - + diff --git a/product/roundhouse.test.merged/app.config b/product/roundhouse.test.merged/app.config new file mode 100644 index 00000000..807d8db5 --- /dev/null +++ b/product/roundhouse.test.merged/app.config @@ -0,0 +1,24 @@ + + + + + + \ No newline at end of file diff --git a/product/roundhouse.test.merged/roundhouse.test.merged.csproj b/product/roundhouse.test.merged/roundhouse.test.merged.csproj new file mode 100644 index 00000000..2b0a3ae4 --- /dev/null +++ b/product/roundhouse.test.merged/roundhouse.test.merged.csproj @@ -0,0 +1,47 @@ + + + + net461 + true + true + Library + roundhouse.test.merged + roundhouse.test.merged + NU1701;CS0618 + true + true + ..\..\ + bin\$(Configuration)\ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Always + + + + diff --git a/product/roundhouse.tests.integration/roundhouse.tests.integration.csproj b/product/roundhouse.tests.integration/roundhouse.tests.integration.csproj index 0bc51da9..9844d2fd 100644 --- a/product/roundhouse.tests.integration/roundhouse.tests.integration.csproj +++ b/product/roundhouse.tests.integration/roundhouse.tests.integration.csproj @@ -16,10 +16,6 @@ bin\$(Configuration)\ - - AllRules.ruleset - - true full @@ -39,25 +35,17 @@ false 5 - - - - - - - - - - - - + + + + - + @@ -65,7 +53,7 @@ - + diff --git a/product/roundhouse.tests/roundhouse.tests.csproj b/product/roundhouse.tests/roundhouse.tests.csproj index bf733f9d..7621da5d 100644 --- a/product/roundhouse.tests/roundhouse.tests.csproj +++ b/product/roundhouse.tests/roundhouse.tests.csproj @@ -14,24 +14,21 @@ bin\$(Configuration)\ - - AllRules.ruleset - - - + - - - - - - + + + + + + - + + @@ -47,7 +44,7 @@ - + diff --git a/roundhouse.sln b/roundhouse.sln index 92b34f97..5075c673 100644 --- a/roundhouse.sln +++ b/roundhouse.sln @@ -7,8 +7,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{807C6B2C EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "databases", "databases", "{BCFAF88B-B6C0-48C1-B23E-FCC95B75588C}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "roundhouse", "product\roundhouse\roundhouse.csproj", "{A95DE649-D5BA-4402-9D9C-3D8D67E2FF44}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "roundhouse.tests", "product\roundhouse.tests\roundhouse.tests.csproj", "{0726928C-FDAC-4C79-B423-841C7E0DF5B8}" ProjectSection(ProjectDependencies) = postProject {1D41D70E-E310-4699-B7CB-C1F77476A685} = {1D41D70E-E310-4699-B7CB-C1F77476A685} @@ -45,7 +43,11 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "roundhouse.databases.postgr EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "roundhouse.databases.sqlserverce", "product\roundhouse.databases.sqlserverce\roundhouse.databases.sqlserverce.csproj", "{3447F080-CF50-4B02-9521-671E7AEE8D34}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "roundhouse.lib.merged", "product\roundhouse.lib.merged\roundhouse.lib.merged.csproj", "{6BB8E05F-CEC6-4CC8-87CF-8A9C439C8122}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "roundhouse.lib", "product\roundhouse.lib\roundhouse.lib.csproj", "{6BB8E05F-CEC6-4CC8-87CF-8A9C439C8122}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "roundhouse.test.merged", "product\roundhouse.test.merged\roundhouse.test.merged.csproj", "{729625F9-E8E5-472B-BAA8-F7DEDACBD700}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "roundhouse.core", "product\roundhouse.core\roundhouse.core.csproj", "{328AA2A7-D213-46EB-861E-5D9CA94F8BFD}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -54,12 +56,6 @@ Global Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {A95DE649-D5BA-4402-9D9C-3D8D67E2FF44}.Build|Any CPU.ActiveCfg = Release|Any CPU - {A95DE649-D5BA-4402-9D9C-3D8D67E2FF44}.Build|Any CPU.Build.0 = Release|Any CPU - {A95DE649-D5BA-4402-9D9C-3D8D67E2FF44}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {A95DE649-D5BA-4402-9D9C-3D8D67E2FF44}.Debug|Any CPU.Build.0 = Debug|Any CPU - {A95DE649-D5BA-4402-9D9C-3D8D67E2FF44}.Release|Any CPU.ActiveCfg = Release|Any CPU - {A95DE649-D5BA-4402-9D9C-3D8D67E2FF44}.Release|Any CPU.Build.0 = Release|Any CPU {0726928C-FDAC-4C79-B423-841C7E0DF5B8}.Build|Any CPU.ActiveCfg = Release|Any CPU {0726928C-FDAC-4C79-B423-841C7E0DF5B8}.Build|Any CPU.Build.0 = Release|Any CPU {0726928C-FDAC-4C79-B423-841C7E0DF5B8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU @@ -138,6 +134,18 @@ Global {6BB8E05F-CEC6-4CC8-87CF-8A9C439C8122}.Debug|Any CPU.Build.0 = Debug|Any CPU {6BB8E05F-CEC6-4CC8-87CF-8A9C439C8122}.Release|Any CPU.ActiveCfg = Release|Any CPU {6BB8E05F-CEC6-4CC8-87CF-8A9C439C8122}.Release|Any CPU.Build.0 = Release|Any CPU + {729625F9-E8E5-472B-BAA8-F7DEDACBD700}.Build|Any CPU.ActiveCfg = Debug|Any CPU + {729625F9-E8E5-472B-BAA8-F7DEDACBD700}.Build|Any CPU.Build.0 = Debug|Any CPU + {729625F9-E8E5-472B-BAA8-F7DEDACBD700}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {729625F9-E8E5-472B-BAA8-F7DEDACBD700}.Debug|Any CPU.Build.0 = Debug|Any CPU + {729625F9-E8E5-472B-BAA8-F7DEDACBD700}.Release|Any CPU.ActiveCfg = Release|Any CPU + {729625F9-E8E5-472B-BAA8-F7DEDACBD700}.Release|Any CPU.Build.0 = Release|Any CPU + {328AA2A7-D213-46EB-861E-5D9CA94F8BFD}.Build|Any CPU.ActiveCfg = Debug|Any CPU + {328AA2A7-D213-46EB-861E-5D9CA94F8BFD}.Build|Any CPU.Build.0 = Debug|Any CPU + {328AA2A7-D213-46EB-861E-5D9CA94F8BFD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {328AA2A7-D213-46EB-861E-5D9CA94F8BFD}.Debug|Any CPU.Build.0 = Debug|Any CPU + {328AA2A7-D213-46EB-861E-5D9CA94F8BFD}.Release|Any CPU.ActiveCfg = Release|Any CPU + {328AA2A7-D213-46EB-861E-5D9CA94F8BFD}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -153,6 +161,7 @@ Global {1D41D70E-E310-4699-B7CB-C1F77476A685} = {BCFAF88B-B6C0-48C1-B23E-FCC95B75588C} {41CE538E-E6F1-4AB6-AB66-508DEF669A39} = {BCFAF88B-B6C0-48C1-B23E-FCC95B75588C} {3447F080-CF50-4B02-9521-671E7AEE8D34} = {BCFAF88B-B6C0-48C1-B23E-FCC95B75588C} + {729625F9-E8E5-472B-BAA8-F7DEDACBD700} = {807C6B2C-496F-4A41-ABFE-EA5478EB9CFF} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {54AD825C-DC48-4C69-88E5-356B43AC3674}