Exemple #1
0
        /// <summary>
        /// Performs an install of a database
        /// </summary>
        public void Install(InstallSetup setup)
        {
            //The connection string must reference an existing database
            if (!DatabaseServer.TestConnectionString(setup.ConnectionString))
            {
                throw new Exception("The connection string does not reference a valid database.");
            }

            try
            {
                UpgradeInstaller.UpgradeDatabase(setup);
            }
            catch (InvalidSQLException ex)
            {
                var sb = new StringBuilder();
                sb.AppendLine();
                sb.AppendLine("BEGIN ERROR SQL");
                sb.AppendLine(ex.SQL);
                sb.AppendLine("END ERROR SQL");
                sb.AppendLine();
                Log.Verbose(sb.ToString());
                UpgradeInstaller.LogError(ex, sb.ToString());
                throw;
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Exemple #2
0
        public void SetupGeneric(Exception exception)
        {
            try
            {
                this.Text = "Error";
                this.splitter1.Visible = false;
                this.panel3.Dock       = DockStyle.None;
                this.panel3.Visible    = false;
                this.panel1.Dock       = DockStyle.Fill;
                this.panel1.BringToFront();
                var errorText = exception.ToString();
                if (exception is InvalidSQLException)
                {
                    errorText = "FileName: '" + ((InvalidSQLException)exception).FileName + "'" + errorText;
                }

                UpgradeInstaller.LogError(exception.InnerException, "[ERROR]\r\n" + errorText);
                if (exception.InnerException != null)
                {
                    txtError.Text = exception.InnerException.ToString();
                }
                else
                {
                    txtError.Text = exception.ToString();
                }
                cmdSkip.Visible = false;
            }
            catch (Exception ex)
            {
                //Do Nothing
            }
        }
        /// <summary />
        private void UIInstall()
        {
            if (IdentifyDatabaseConnectionString())
            {
                var setup = new InstallSetup()
                {
                    ConnectionString = this.Settings.GetPrimaryConnectionString(),
                    InstallStatus    = InstallStatusConstants.Upgrade,
                };

                if (this.Action == ActionTypeConstants.Create)
                {
                    setup.InstallStatus = InstallStatusConstants.Create;
                    UpgradeInstaller.UpgradeDatabase(setup);
                }
                else if (this.Action == ActionTypeConstants.Upgrade)
                {
                    UpgradeInstaller.UpgradeDatabase(setup);
                }
                else if (this.Action == ActionTypeConstants.AzureCopy)
                {
                    UpgradeInstaller.AzureCopyDatabase(this.Settings);
                }
            }
        }
Exemple #4
0
 public void Setup(InvalidSQLException exception, bool allowSkip)
 {
     UpgradeInstaller.LogError(exception.InnerException, "[ERROR SCRIPT]\r\n" + exception.SQL);
     txtError.Text   = exception.InnerException.ToString();
     txtSql.Text     = exception.SQL;
     cmdSkip.Visible = allowSkip;
 }
Exemple #5
0
 public void Setup(InvalidSQLException exception, bool allowSkip)
 {
     UpgradeInstaller.LogError(exception.InnerException, "[ERROR]\r\n" + "FileName: '" + ((InvalidSQLException)exception).FileName + "'\r\n" + exception.SQL);
     txtError.Text   = "FileName: '" + exception.FileName + "'\r\n" + exception.InnerException.ToString();
     txtSql.Text     = exception.SQL;
     cmdSkip.Visible = allowSkip;
 }
        /// <summary>
        /// Returns the upgrade script for the specified database
        /// </summary>
        /// <param name="connectionString">The database connection string</param>
        /// <param name="skipSections">A list of script sections to skip when executing</param>
        public string GetUpgradeScript(string connectionString, IEnumerable <string> skipSections)
        {
            var setup = new InstallSetup();

            setup.ConnectionString = connectionString;
            setup.SkipSections     = skipSections;
            return(UpgradeInstaller.GetUpgradeScript(setup));
        }
Exemple #7
0
        /// <summary>
        /// Performs an install of a database
        /// </summary>
        public void Install(InstallSetup setup)
        {
            if (setup.InstallStatus == InstallStatusConstants.Create)
            {
                //Connection cannot reference an existing database
                if (SqlServers.TestConnectionString(setup.ConnectionString))
                {
                    throw new Exception("The connection string references an existing database.");
                }

                //The new database name must be specified
                if (string.IsNullOrEmpty(setup.NewDatabaseName))
                {
                    throw new Exception("A new database name was not specified.");
                }

                //The connection string and the new database name must be the same
                var builder = new SqlConnectionStringBuilder(setup.ConnectionString);
                if (builder.InitialCatalog.ToLower() != setup.NewDatabaseName.ToLower())
                {
                    throw new Exception("A new database name does not match the specified connection string.");
                }

                SqlServers.CreateDatabase(setup);
            }
            else if (setup.InstallStatus == InstallStatusConstants.Upgrade)
            {
                //The connection string must reference an existing database
                if (!SqlServers.TestConnectionString(setup.ConnectionString))
                {
                    throw new Exception("The connection string does not reference a valid database.");
                }
            }

            try
            {
                UpgradeInstaller.UpgradeDatabase(setup);
            }
            catch (InvalidSQLException ex)
            {
                var sb = new StringBuilder();
                sb.AppendLine();
                sb.AppendLine("BEGIN ERROR SQL");
                sb.AppendLine(ex.SQL);
                sb.AppendLine("END ERROR SQL");
                sb.AppendLine();
                System.Diagnostics.Trace.WriteLine(sb.ToString());
                UpgradeInstaller.LogError(ex, sb.ToString());
                throw;
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Exemple #8
0
 /// <summary>
 /// Returns the upgrade script for the specified database
 /// </summary>
 public string GetScript(InstallSetup setup)
 {
     if (string.IsNullOrEmpty(setup.ConnectionString) && setup.Version == null)
     {
         throw new Exception("The connection string must be set.");
     }
     if (setup.SkipSections == null)
     {
         setup.SkipSections = new List <string>();
     }
     return(UpgradeInstaller.GetScript(setup));
 }
        /// <summary />
        private void UIInstall(InstallSetup setup)
        {
            if (IdentifyDatabaseConnectionString(setup))
            {
                setup.ConnectionString = this.Settings.GetPrimaryConnectionString();
                setup.InstallStatus    = InstallStatusConstants.Upgrade;

                if (this.Action == ActionTypeConstants.Create)
                {
                    setup.InstallStatus = InstallStatusConstants.Create;
                    UpgradeInstaller.UpgradeDatabase(setup);
                }
                else if (this.Action == ActionTypeConstants.Upgrade)
                {
                    UpgradeInstaller.UpgradeDatabase(setup);
                }
            }
        }
Exemple #10
0
        /// <summary>
        /// Performs an install of a database
        /// </summary>
        public void Install(InstallSetup setup)
        {
            if (setup.InstallStatus == InstallStatusConstants.Create)
            {
                //Conection cannot reference an existing database
                if (SqlServers.TestConnectionString(setup.ConnectionString))
                {
                    throw new Exception("The connection string references an existing database.");
                }

                //The new database name must be specified
                if (string.IsNullOrEmpty(setup.NewDatabaseName))
                {
                    throw new Exception("A new database name was not specified.");
                }

                //The connection string and the new database name must be the same
                var builder = new System.Data.SqlClient.SqlConnectionStringBuilder(setup.ConnectionString);
                if (builder.InitialCatalog.ToLower() != setup.NewDatabaseName.ToLower())
                {
                    throw new Exception("A new database name does not match the specified connection string.");
                }

                SqlServers.CreateDatabase(setup);
            }
            else if (setup.InstallStatus == InstallStatusConstants.Upgrade)
            {
                //The connection string must reference an existing database
                if (!SqlServers.TestConnectionString(setup.ConnectionString))
                {
                    throw new Exception("The connection string does not reference a valid database.");
                }
            }

            UpgradeInstaller.UpgradeDatabase(setup);
        }
Exemple #11
0
        /// <summary>
        /// Performs an install of a database
        /// </summary>
        public override void Install(System.Collections.IDictionary stateSaver)
        {
            //base.Install(stateSaver);
            var commandParams = stateSaver as Dictionary <string, string>;

            foreach (var action in GetDatabaseActions()
                     .Select(x => Activator.CreateInstance(x) as IDatabaseAction)
                     .OrderBy(x => x.SortOrder)
                     .ToList())
            {
                action.Execute(commandParams);
            }

            var paramUICount = 0;
            var setup        = new InstallSetup();

            if (commandParams.Count > 0)
            {
                if (commandParams.Any(x => PARAMKEYS_TRAN.Contains(x.Key)))
                {
                    setup.UseTransaction = GetSetting(commandParams, PARAMKEYS_TRAN, true);
                    paramUICount++;
                }

                if (commandParams.ContainsKey(PARAMKEYS_SKIPNORMALIZE))
                {
                    setup.SkipNormalize = true;
                    paramUICount++;
                }

                if (commandParams.ContainsKey(PARAMKEYS_HASH))
                {
                    if (commandParams[PARAMKEYS_HASH].ToLower() == "true" || commandParams[PARAMKEYS_HASH].ToLower() == "1" || commandParams[PARAMKEYS_HASH].ToLower() == string.Empty)
                    {
                        setup.UseHash = true;
                    }
                    else if (commandParams[PARAMKEYS_HASH].ToLower() == "false" || commandParams[PARAMKEYS_HASH].ToLower() == "0")
                    {
                        setup.UseHash = false;
                    }
                    else
                    {
                        throw new Exception("The /" + PARAMKEYS_HASH + " parameter must be set to 'true or false'.");
                    }
                    paramUICount++;
                }

                if (commandParams.ContainsKey(PARAMKEYS_CHECKONLY))
                {
                    setup.CheckOnly = true;
                    paramUICount++;
                }

                if (commandParams.ContainsKey(PARAMKEYS_VERSIONWARN))
                {
                    if (commandParams[PARAMKEYS_VERSIONWARN].ToLower() == "all")
                    {
                        setup.AcceptVersionWarningsChangedScripts = true;
                        setup.AcceptVersionWarningsNewScripts     = true;
                    }
                    else if (commandParams[PARAMKEYS_VERSIONWARN].ToLower() == "none")
                    {
                        setup.AcceptVersionWarningsChangedScripts = false;
                        setup.AcceptVersionWarningsNewScripts     = false;
                    }
                    else if (commandParams[PARAMKEYS_VERSIONWARN].ToLower() == "new")
                    {
                        setup.AcceptVersionWarningsNewScripts = true;
                    }
                    else if (commandParams[PARAMKEYS_VERSIONWARN].ToLower() == "changed")
                    {
                        setup.AcceptVersionWarningsChangedScripts = true;
                    }
                    else
                    {
                        throw new Exception("The /" + PARAMKEYS_VERSIONWARN + " parameter must be set to 'all, none, new, or changed'.");
                    }
                    paramUICount++;
                }

                if (GetSetting(commandParams, PARAMKEYS_HELP, false))
                {
                    ShowHelp();
                    return;
                }

                setup.ConnectionString = GetSetting(commandParams, PARAMKEYS_APPDB, string.Empty);

                //Determine if calling as a script generator
                if (commandParams.ContainsKey(PARAMKEYS_SCRIPT))
                {
                    var scriptAction = commandParams[PARAMKEYS_SCRIPT].ToLower();
                    switch (scriptAction)
                    {
                    case "versioned": break;

                    case "unversioned": break;

                    default:
                        throw new Exception("The script action must be 'versioned' or 'unversioned'.");
                    }

                    if (!commandParams.ContainsKey(PARAMKEYS_SCRIPTFILE))
                    {
                        throw new Exception("The '" + PARAMKEYS_SCRIPTFILE + "' parameter must be set for script generation.");
                    }

                    var dumpFile = commandParams[PARAMKEYS_SCRIPTFILE];
                    if (!IsValidFileName(dumpFile))
                    {
                        throw new Exception("The '" + PARAMKEYS_SCRIPTFILE + "' parameter is not valid.");
                    }

                    var fileCreate = true;
                    if (commandParams.ContainsKey(PARAMKEYS_SCRIPTFILEACTION) && (commandParams[PARAMKEYS_SCRIPTFILEACTION] + string.Empty) == "append")
                    {
                        fileCreate = false;
                    }

                    if (File.Exists(dumpFile) && fileCreate)
                    {
                        File.Delete(dumpFile);
                        System.Threading.Thread.Sleep(500);
                    }

                    switch (scriptAction)
                    {
                    case "versioned":
                        if (commandParams.ContainsKey(PARAMKEYS_DBVERSION))
                        {
                            if (!GeneratedVersion.IsValid(commandParams[PARAMKEYS_DBVERSION]))
                            {
                                throw new Exception("The '" + PARAMKEYS_DBVERSION + "' parameter is not valid.");
                            }

                            setup.Version = new GeneratedVersion(commandParams[PARAMKEYS_DBVERSION]);
                        }
                        else
                        {
                            if (string.IsNullOrEmpty(setup.ConnectionString))
                            {
                                throw new Exception("Generation of versioned scripts requires a '" + PARAMKEYS_DBVERSION + "' parameter or valid connection string.");
                            }
                            else
                            {
                                var s = new nHydrateSetting();
                                s.Load(setup.ConnectionString);
                                setup.Version = new GeneratedVersion(s.dbVersion);
                            }
                        }

                        File.AppendAllText(dumpFile, UpgradeInstaller.GetScript(setup));
                        break;

                    case "unversioned":
                        setup.Version = UpgradeInstaller._def_Version;
                        File.AppendAllText(dumpFile, UpgradeInstaller.GetScript(setup));
                        break;
                    }

                    return;
                }

                //If we processed all parameters and they were UI then we need to show UI
                if (paramUICount < commandParams.Count)
                {
                    Install(setup);
                    return;
                }
            }

            Log.Information("Invalid configuration");
        }
Exemple #12
0
 /// <summary>
 /// Determines if the specified database has ever been versioned by the framework
 /// </summary>
 /// <param name="connectionString"></param>
 public virtual bool IsVersioned(string connectionString)
 {
     return(UpgradeInstaller.IsVersioned(connectionString));
 }
Exemple #13
0
 /// <summary>
 /// The database version to which this installer will upgrade a database
 /// </summary>
 public virtual string VersionLatest()
 {
     return(UpgradeInstaller.VersionLatest());
 }
Exemple #14
0
 /// <summary>
 /// Determines the current version of the specified database
 /// </summary>
 public virtual string VersionInstalled(string connectionString)
 {
     return(UpgradeInstaller.VersionInstalled(connectionString));
 }
Exemple #15
0
 /// <summary>
 /// Determines if the specified database needs to be upgraded
 /// </summary>
 public virtual bool NeedsUpdate(string connectionString)
 {
     return(UpgradeInstaller.NeedsUpdate(connectionString));
 }
Exemple #16
0
        /// <summary>
        /// Performs an install of a database
        /// </summary>
        public override void Install(System.Collections.IDictionary stateSaver)
        {
            base.Install(stateSaver);

            var commandParams = GetCommandLineParameters();

            if (PrintHelp(commandParams))
            {
                return;
            }

            if (commandParams.Count > 0)
            {
                var setup = new InstallSetup();
                setup.ConnectionString       = GetAppDbString(commandParams);
                setup.MasterConnectionString = GetMasterDbConnectionString(commandParams);
                if (GetUpgradeDbSetting(commandParams, setup.IsUpgrade))
                {
                    setup.InstallStatus = InstallStatusConstants.Upgrade;
                }
                if (commandParams.Any(x => PARAMKEYS_CREATE.Contains(x.Key)))
                {
                    setup.InstallStatus = InstallStatusConstants.Create;
                }

                if (commandParams.Any(x => PARAMKEYS_UPGRADE.Contains(x.Key)) && commandParams.Any(x => PARAMKEYS_CREATE.Contains(x.Key)))
                {
                    throw new Exception("You cannot specify both the create and update action.");
                }
                if (commandParams.Count(x => PARAMKEYS_NEWNAME.Contains(x.Key)) > 1)
                {
                    throw new Exception("The new database name was specified more than once.");
                }
                if (commandParams.Count(x => PARAMKEYS_MASTERDB.Contains(x.Key)) > 1)
                {
                    throw new Exception("The master database connection string was specified more than once.");
                }
                if (commandParams.Count(x => PARAMKEYS_APPDB.Contains(x.Key)) > 1)
                {
                    throw new Exception("The connection string was specified more than once.");
                }

                //Determine if calling as a script generator
                if (commandParams.ContainsKey(PARAMKEYS_SCRIPT))
                {
                    var scriptAction = commandParams[PARAMKEYS_SCRIPT].ToLower();
                    switch (scriptAction)
                    {
                    case "versioned":
                    case "unversioned":
                    case "create":
                        break;

                    default:
                        throw new Exception("The script action must be 'create', 'versioned', or 'unversioned'.");
                    }

                    if (!commandParams.ContainsKey(PARAMKEYS_SCRIPTFILE))
                    {
                        throw new Exception("The '" + PARAMKEYS_SCRIPTFILE + "' parameter must be set for script generation.");
                    }

                    var dumpFile = commandParams[PARAMKEYS_SCRIPTFILE];
                    if (!IsValidFileName(dumpFile))
                    {
                        throw new Exception("The '" + PARAMKEYS_SCRIPTFILE + "' is not valid.");
                    }

                    var fileCreate = true;
                    if (commandParams.ContainsKey(PARAMKEYS_SCRIPTFILEACTION) &&
                        (commandParams[PARAMKEYS_SCRIPTFILEACTION] + string.Empty) == "append")
                    {
                        fileCreate = false;
                    }

                    if (File.Exists(dumpFile) && fileCreate)
                    {
                        File.Delete(dumpFile);
                        System.Threading.Thread.Sleep(500);
                    }

                    switch (scriptAction)
                    {
                    case "versioned":
                        if (!commandParams.ContainsKey(PARAMKEYS_DBVERSION))
                        {
                            throw new Exception("Generation of versioned scripts requires a '" + PARAMKEYS_DBVERSION + "' parameter.");
                        }

                        if (!GeneratedVersion.IsValid(commandParams[PARAMKEYS_DBVERSION]))
                        {
                            throw new Exception("The '" + PARAMKEYS_DBVERSION + "' parameter is not valid.");
                        }

                        Console.WriteLine("Generate Script Started");
                        setup.InstallStatus = InstallStatusConstants.Upgrade;
                        setup.Version       = new GeneratedVersion(commandParams[PARAMKEYS_DBVERSION]);
                        File.AppendAllText(dumpFile, UpgradeInstaller.GetUpgradeScript(setup));
                        Console.WriteLine("Generated Create Script");
                        break;

                    case "unversioned":
                        if (commandParams.ContainsKey(PARAMKEYS_DBVERSION))
                        {
                            throw new Exception("Generation of unversioned scripts cannot use a '" + PARAMKEYS_DBVERSION + "' parameter.");
                        }

                        Console.WriteLine("Generate Script Started");
                        setup.InstallStatus = InstallStatusConstants.Upgrade;
                        setup.Version       = UpgradeInstaller._def_Version;
                        File.AppendAllText(dumpFile, UpgradeInstaller.GetUpgradeScript(setup));
                        Console.WriteLine("Generated Create Script");
                        break;

                    case "create":
                        Console.WriteLine("Generate Script Started");
                        setup.InstallStatus = InstallStatusConstants.Create;
                        setup.Version       = new GeneratedVersion(-1, -1, -1, -1, -1);
                        File.AppendAllText(dumpFile, UpgradeInstaller.GetUpgradeScript(setup));
                        Console.WriteLine("Generated Create Script");
                        break;
                    }

                    return;
                }

                setup.NewDatabaseName = commandParams.Where(x => PARAMKEYS_NEWNAME.Contains(x.Key)).Select(x => x.Value).FirstOrDefault();
                Install(setup);
            }
            else
            {
                UIInstall();
            }
        }
Exemple #17
0
        public void Run(InstallSettings settings)
        {
            //STEPS TO COPY DATABASE TO AZURE
            //1. Verify that target is a blank database
            //2. Execute only tables schemas with no defaults, relations, etc
            //3. Copy data with BCP one table at a time
            //4. Run full installer on the target database

            //1. Verify that target is a blank database
            if (!this.TargetIsBlank(settings))
            {
                throw new Exception("The target database must be empty!");
            }

            //2. Execute only tables schemas and PK with no defaults, relations, etc
            Assembly assem = Assembly.GetExecutingAssembly();

            string[] resourceNames = assem.GetManifestResourceNames();
            var      resourceName  = resourceNames.FirstOrDefault(x => x.EndsWith(".Create_Scripts.Generated.CreateSchema.sql"));

            if (string.IsNullOrEmpty(resourceName))
            {
                throw new Exception("Could not find the 'CreateSchema.sql' resource!");
            }

            var scripts = SqlServers.ReadSQLFileSectionsFromResource(resourceName, new InstallSetup());

            SqlConnection connection = null;

            try
            {
                connection = new SqlConnection(settings.GetCloudConnectionString());
                connection.Open();

                ////Create version table
                //var sb = new StringBuilder();
                //sb.AppendLine("if not exists(select * from sysobjects where name = '__nhydrateschema' and xtype = 'U')");
                //sb.AppendLine("BEGIN");
                //sb.AppendLine("CREATE TABLE [__nhydrateschema] (");
                //sb.AppendLine("[dbVersion] [varchar] (50) NOT NULL,");
                //sb.AppendLine("[LastUpdate] [datetime] NOT NULL,");
                //sb.AppendLine("[ModelKey] [uniqueidentifier] NOT NULL,");
                //sb.AppendLine("[History] [text] NOT NULL");
                //sb.AppendLine(")");
                //sb.AppendLine("--PRIMARY KEY FOR TABLE");
                //sb.AppendLine("if not exists(select * from sysobjects where name = '__pk__nhydrateschema' and xtype = 'PK')");
                //sb.AppendLine("ALTER TABLE [__nhydrateschema] WITH NOCHECK ADD CONSTRAINT [__pk__nhydrateschema] PRIMARY KEY CLUSTERED ([ModelKey])");
                //sb.AppendLine("END");
                //var command2 = new SqlCommand(sb.ToString(), connection);
                //command2.ExecuteNonQuery();

                foreach (string sql in scripts)
                {
                    if (
                        sql.Contains("--CREATE TABLE") ||
                        sql.Contains("--CREATE AUDIT TABLE") ||
                        sql.StartsWith("--APPEND AUDIT") ||
                        sql.StartsWith("--PRIMARY KEY FOR TABLE"))
                    {
                        var command = new SqlCommand(sql, connection);
                        command.ExecuteNonQuery();
                    }
                }
            }
            catch (Exception ex)
            {
                throw;
            }
            finally
            {
                if (connection != null)
                {
                    connection.Close();
                }
            }

            //3. Copy data with BCP one table at a time
            this.CopyData(settings);

            //4. Run full installer on the target database
            var setup = new InstallSetup()
            {
                ConnectionString = settings.GetCloudConnectionString(),
                InstallStatus    = InstallStatusConstants.Upgrade,
            };

            UpgradeInstaller.UpgradeDatabase(setup);
        }
Exemple #18
0
        /// <summary>
        /// Performs an install of a database
        /// </summary>
        public override void Install(System.Collections.IDictionary stateSaver)
        {
            base.Install(stateSaver);

            var commandParams = GetCommandLineParameters();

            var paramUICount = 0;
            var setup        = new InstallSetup();

            if (commandParams.Count > 0)
            {
                if (commandParams.ContainsKey(PARAMKEYS_SHOWSQL))
                {
                    if (commandParams[PARAMKEYS_SHOWSQL].ToLower() == "true" || commandParams[PARAMKEYS_SHOWSQL].ToLower() == "1" || commandParams[PARAMKEYS_SHOWSQL].ToLower() == string.Empty)
                    {
                        setup.ShowSql = true;
                    }
                    else if (commandParams[PARAMKEYS_SHOWSQL].ToLower() == "false" || commandParams[PARAMKEYS_SHOWSQL].ToLower() == "0")
                    {
                        setup.ShowSql = false;
                    }
                    else
                    {
                        throw new Exception("The /" + PARAMKEYS_SHOWSQL + " parameter must be set to 'true or false'.");
                    }
                    paramUICount++;
                }

                if (commandParams.ContainsKey(PARAMKEYS_LOGSQL))
                {
                    var logFile = commandParams[PARAMKEYS_LOGSQL];
                    if (!string.IsNullOrEmpty(logFile))
                    {
                        //var isValid = !string.IsNullOrEmpty(logFile) && logFile.IndexOfAny(Path.GetInvalidFileNameChars()) < 0;
                        //if (!isValid)
                        //    throw new Exception("The /" + PARAMKEYS_LOGSQL + " parameter must have a valid file name.");
                        if (File.Exists(logFile))
                        {
                            File.Delete(logFile);
                        }
                        setup.LogFilename = logFile;
                    }
                    paramUICount++;
                }

                if (commandParams.Any(x => PARAMKEYS_TRAN.Contains(x.Key)))
                {
                    setup.UseTransaction = GetSetting(commandParams, PARAMKEYS_TRAN, true);
                    paramUICount++;
                }

                if (commandParams.ContainsKey(PARAMKEYS_SKIPNORMALIZE))
                {
                    setup.SkipNormalize = true;
                    paramUICount++;
                }

                if (commandParams.ContainsKey(PARAMKEYS_HASH))
                {
                    if (commandParams[PARAMKEYS_HASH].ToLower() == "true" || commandParams[PARAMKEYS_HASH].ToLower() == "1" || commandParams[PARAMKEYS_HASH].ToLower() == string.Empty)
                    {
                        setup.UseHash = true;
                    }
                    else if (commandParams[PARAMKEYS_HASH].ToLower() == "false" || commandParams[PARAMKEYS_HASH].ToLower() == "0")
                    {
                        setup.UseHash = false;
                    }
                    else
                    {
                        throw new Exception("The /" + PARAMKEYS_HASH + " parameter must be set to 'true or false'.");
                    }
                    paramUICount++;
                }

                if (commandParams.ContainsKey(PARAMKEYS_CHECKONLY))
                {
                    setup.CheckOnly = true;
                    paramUICount++;
                }

                if (commandParams.ContainsKey(PARAMKEYS_QUIET))
                {
                    setup.SuppressUI = true;
                    paramUICount++;
                }

                //Setup trace if need be. If showing SQL then auto trace on
                if (commandParams.ContainsKey(PARAMKEYS_TRACE) || setup.ShowSql)
                {
                    var trc = new System.Diagnostics.ConsoleTraceListener();
                    System.Diagnostics.Trace.Listeners.Add(trc);
                    paramUICount++;
                }

                if (commandParams.ContainsKey(PARAMKEYS_VERSIONWARN))
                {
                    if (commandParams[PARAMKEYS_VERSIONWARN].ToLower() == "all")
                    {
                        setup.AcceptVersionWarningsChangedScripts = true;
                        setup.AcceptVersionWarningsNewScripts     = true;
                    }
                    else if (commandParams[PARAMKEYS_VERSIONWARN].ToLower() == "none")
                    {
                        setup.AcceptVersionWarningsChangedScripts = false;
                        setup.AcceptVersionWarningsNewScripts     = false;
                    }
                    else if (commandParams[PARAMKEYS_VERSIONWARN].ToLower() == "new")
                    {
                        setup.AcceptVersionWarningsNewScripts = true;
                    }
                    else if (commandParams[PARAMKEYS_VERSIONWARN].ToLower() == "changed")
                    {
                        setup.AcceptVersionWarningsChangedScripts = true;
                    }
                    else
                    {
                        throw new Exception("The /" + PARAMKEYS_VERSIONWARN + " parameter must be set to 'all, none, new, or changed'.");
                    }
                    paramUICount++;
                }

                if (GetSetting(commandParams, PARAMKEYS_HELP, false))
                {
                    ShowHelp();
                    return;
                }

                //Try to drop database
                if (commandParams.Any(x => PARAMKEYS_DROP.Contains(x.Key)))
                {
                    var masterConnectionString = GetSetting(commandParams, PARAMKEYS_MASTERDB, string.Empty);
                    var dbname = commandParams.Where(x => PARAMKEYS_NEWNAME.Contains(x.Key)).Select(x => x.Value).FirstOrDefault();
                    if (commandParams.Count == 3 && !string.IsNullOrEmpty(masterConnectionString))
                    {
                        if (!DropDatabase(dbname, masterConnectionString))
                        {
                            throw new Exception("The database '" + dbname + "' could not dropped.");
                        }
                        System.Diagnostics.Trace.WriteLine("Database successfully dropped.");
                        return;
                    }
                    throw new Exception("Invalid drop database configuration.");
                }

                setup.ConnectionString       = GetSetting(commandParams, PARAMKEYS_APPDB, string.Empty);
                setup.MasterConnectionString = GetSetting(commandParams, PARAMKEYS_MASTERDB, string.Empty);
                if (GetSetting(commandParams, PARAMKEYS_UPGRADE, setup.IsUpgrade))
                {
                    setup.InstallStatus = InstallStatusConstants.Upgrade;
                }
                if (commandParams.Any(x => PARAMKEYS_CREATE.Contains(x.Key)))
                {
                    setup.InstallStatus = InstallStatusConstants.Create;
                }

                if (commandParams.Any(x => PARAMKEYS_UPGRADE.Contains(x.Key)) && commandParams.Any(x => PARAMKEYS_CREATE.Contains(x.Key)))
                {
                    throw new Exception("You cannot specify both the create and update action.");
                }
                if (commandParams.Count(x => PARAMKEYS_NEWNAME.Contains(x.Key)) > 1)
                {
                    throw new Exception("The new database name was specified more than once.");
                }
                if (commandParams.Count(x => PARAMKEYS_MASTERDB.Contains(x.Key)) > 1)
                {
                    throw new Exception("The master database connection string was specified more than once.");
                }
                if (commandParams.Count(x => PARAMKEYS_APPDB.Contains(x.Key)) > 1)
                {
                    throw new Exception("The connection string was specified more than once.");
                }

                //Determine if calling as a script generator
                if (commandParams.ContainsKey(PARAMKEYS_SCRIPT))
                {
                    var scriptAction = commandParams[PARAMKEYS_SCRIPT].ToLower();
                    switch (scriptAction)
                    {
                    case "versioned":
                    case "unversioned":
                    case "create":
                        break;

                    default:
                        throw new Exception("The script action must be 'create', 'versioned', or 'unversioned'.");
                    }

                    if (!commandParams.ContainsKey(PARAMKEYS_SCRIPTFILE))
                    {
                        throw new Exception("The '" + PARAMKEYS_SCRIPTFILE + "' parameter must be set for script generation.");
                    }

                    var dumpFile = commandParams[PARAMKEYS_SCRIPTFILE];
                    if (!IsValidFileName(dumpFile))
                    {
                        throw new Exception("The '" + PARAMKEYS_SCRIPTFILE + "' parameter is not valid.");
                    }

                    var fileCreate = true;
                    if (commandParams.ContainsKey(PARAMKEYS_SCRIPTFILEACTION) && (commandParams[PARAMKEYS_SCRIPTFILEACTION] + string.Empty) == "append")
                    {
                        fileCreate = false;
                    }

                    if (File.Exists(dumpFile) && fileCreate)
                    {
                        File.Delete(dumpFile);
                        System.Threading.Thread.Sleep(500);
                    }

                    switch (scriptAction)
                    {
                    case "versioned":
                        if (commandParams.ContainsKey(PARAMKEYS_DBVERSION))
                        {
                            if (!GeneratedVersion.IsValid(commandParams[PARAMKEYS_DBVERSION]))
                            {
                                throw new Exception("The '" + PARAMKEYS_DBVERSION + "' parameter is not valid.");
                            }

                            setup.Version = new GeneratedVersion(commandParams[PARAMKEYS_DBVERSION]);
                        }
                        else
                        {
                            if (string.IsNullOrEmpty(setup.ConnectionString))
                            {
                                throw new Exception("Generation of versioned scripts requires a '" + PARAMKEYS_DBVERSION + "' parameter or valid connection string.");
                            }
                            else
                            {
                                var s = new nHydrateSetting();
                                s.Load(setup.ConnectionString);
                                setup.Version = new GeneratedVersion(s.dbVersion);
                            }
                        }

                        setup.InstallStatus = InstallStatusConstants.Upgrade;
                        File.AppendAllText(dumpFile, UpgradeInstaller.GetScript(setup));
                        break;

                    case "unversioned":
                        setup.InstallStatus = InstallStatusConstants.Upgrade;
                        setup.Version       = UpgradeInstaller._def_Version;
                        File.AppendAllText(dumpFile, UpgradeInstaller.GetScript(setup));
                        break;

                    case "create":
                        setup.InstallStatus = InstallStatusConstants.Create;
                        setup.Version       = new GeneratedVersion(-1, -1, -1, -1, -1);
                        File.AppendAllText(dumpFile, UpgradeInstaller.GetScript(setup));
                        break;
                    }

                    return;
                }

                //If we processed all parameters and they were UI then we need to show UI
                if ((paramUICount < commandParams.Count) || setup.SuppressUI)
                {
                    setup.NewDatabaseName = commandParams.Where(x => PARAMKEYS_NEWNAME.Contains(x.Key)).Select(x => x.Value).FirstOrDefault();
                    Install(setup);
                    return;
                }
            }

            Console.WriteLine("Invalid configuration");
        }