private void UpdateMappingToolDatabase(PSCmdlet callingCmdlet)
        {
            using (var mapDatabaseContext = new MappingTool.MappingToolDatabaseDataContext(MapDatabaseConnectionString))
            {
                var glymaDbVersion = mapDatabaseContext.GetGlymaDbVersion();

                foreach (var row in glymaDbVersion)
                {
                    if (row.Column1 != "v1.5.0r3")
                    {
                        callingCmdlet.WriteWarning(string.Format("This update can only update the v1.5.0r3 database to v1.5.0r4 database. The version of this database is {0}.", row.Column1));

                        return;
                    }
                }
            }

            using (var mapDbConnection = new SqlConnection(MapDatabaseConnectionString))
            {
                mapDbConnection.Open();
                var transaction = mapDbConnection.BeginTransaction();
                try
                {
                    callingCmdlet.WriteWarning("Database update started, please wait...");
                    new UpdateAllMetadata().Execute(mapDbConnection, transaction);
                    callingCmdlet.WriteWarning("Updated to new description metadata name");

                    var descriptionTypeMetadataList = new QueryMetadata("Description.Type").GetItems(mapDbConnection, transaction);
                    callingCmdlet.WriteWarning(string.Format("{0} description type records found.", descriptionTypeMetadataList.Count()));

                    var descriptionMetadataList = new QueryMetadata("Description.Content").GetItems(mapDbConnection, transaction);
                    callingCmdlet.WriteWarning(string.Format("{0} description records found.", descriptionMetadataList.Count()));

                    foreach (var updatableNode in descriptionTypeMetadataList)
                    {
                        var found = descriptionMetadataList.FirstOrDefault(q => q.NodeUid == updatableNode.NodeUid);
                        if (found != null)
                        {
                            if (string.IsNullOrEmpty(found.MetadataValue))
                            {
                                new DeleteMetadata(updatableNode.MetadataId).Execute(mapDbConnection, transaction);
                                new DeleteMetadata(found.MetadataId).Execute(mapDbConnection, transaction);
                                callingCmdlet.WriteWarning(string.Format("Node Id {0} description deleted",
                                    updatableNode.NodeUid));
                            }
                            else if (found.MetadataValue.StartsWith("http://") || found.MetadataValue.StartsWith("https://") || updatableNode.MetadataValue == "Iframe")
                            {
                                var parts = found.MetadataValue.Split(',');
                                if (parts.Count() == 3)
                                {
                                    new UpdateMetadata(found.MetadataId, "Description.Url", parts[0])
                                        .Execute(mapDbConnection, transaction);
                                    new InsertMetadata("Description.Width", parts[1].Replace("px", ""),
                                        found.NodeUid, found.RootMapUid, found.DomainUid,
                                        found.Created, found.Modified, found.CreatedBy, found.ModifiedBy)
                                        .Execute(mapDbConnection, transaction);
                                    new InsertMetadata("Description.Height", parts[2].Replace("px", ""),
                                        found.NodeUid, found.RootMapUid, found.DomainUid,
                                        found.Created, found.Modified, found.CreatedBy, found.ModifiedBy)
                                        .Execute(mapDbConnection, transaction);
                                    new UpdateMetadata(updatableNode.MetadataId, "Description.Type", "Iframe")
                                        .Execute(mapDbConnection, transaction);
                                    callingCmdlet.WriteWarning(
                                        string.Format("Node Id {0} description has updated to Iframe",
                                            updatableNode.NodeUid));
                                }
                                else
                                {
                                    new UpdateMetadata(updatableNode.MetadataId, "Description.Type", "Html").Execute(mapDbConnection, transaction);
                                }
                            }
                            else
                            {
                                var descriptionUpdater = new OldHtmlDescriptionUpdater(found.MetadataValue, callingCmdlet);
                                new UpdateMetadata(updatableNode.MetadataId, "Description.Type", "Html")
                                    .Execute(mapDbConnection, transaction);
                                new UpdateMetadata(found.MetadataId, "Description.Content", descriptionUpdater.Description)
                                    .Execute(mapDbConnection, transaction);
                                if (descriptionUpdater.Width > 0)
                                {
                                    new InsertMetadata("Description.Width", descriptionUpdater.Width.ToString(CultureInfo.InvariantCulture), found.NodeUid, found.RootMapUid, found.DomainUid, found.Created, found.Modified, found.CreatedBy, found.ModifiedBy)
                                    .Execute(mapDbConnection, transaction);
                                }

                                if (descriptionUpdater.Height > 0)
                                {
                                    new InsertMetadata("Description.Height", descriptionUpdater.Height.ToString(CultureInfo.InvariantCulture), found.NodeUid, found.RootMapUid, found.DomainUid, found.Created, found.Modified, found.CreatedBy, found.ModifiedBy)
                                    .Execute(mapDbConnection, transaction);
                                }
                                callingCmdlet.WriteWarning(string.Format("Node Id {0} description has updated to Html", updatableNode.NodeUid));
                            }
                        }
                        else
                        {
                            new DeleteMetadata(updatableNode.MetadataId).Execute(mapDbConnection, transaction);
                            callingCmdlet.WriteWarning(string.Format("Node Id {0} description deleted",
                                    updatableNode.NodeUid));
                        }
                    }


                    foreach (var description in descriptionMetadataList)
                    {
                        var found = descriptionTypeMetadataList.FirstOrDefault(q => q.NodeUid == description.NodeUid);
                        if (found == null)
                        {
                            if (string.IsNullOrEmpty(description.MetadataValue))
                            {
                                new DeleteMetadata(description.MetadataId).Execute(mapDbConnection, transaction);
                                callingCmdlet.WriteWarning(string.Format("Node Id {0} description deleted", description.NodeUid));
                            }
                            else if (description.MetadataValue.StartsWith("http://") || description.MetadataValue.StartsWith("https://"))
                            {
                                var parts = description.MetadataValue.Split(',');
                                if (parts.Count() == 3)
                                {
                                    new UpdateMetadata(description.MetadataId, "Description.Url", parts[0])
                                        .Execute(mapDbConnection, transaction);
                                    new InsertMetadata("Description.Width", parts[1].Replace("px", ""), description.NodeUid, description.RootMapUid, description.DomainUid, description.Created, description.Modified, description.CreatedBy, description.ModifiedBy)
                                        .Execute(mapDbConnection, transaction);
                                    new InsertMetadata("Description.Height", parts[2].Replace("px", ""), description.NodeUid, description.RootMapUid, description.DomainUid, description.Created, description.Modified, description.CreatedBy, description.ModifiedBy)
                                        .Execute(mapDbConnection, transaction);
                                    new InsertMetadata("Description.Type", "Iframe", description.NodeUid, description.RootMapUid, description.DomainUid, description.Created, description.Modified, description.CreatedBy, description.ModifiedBy)
                                        .Execute(mapDbConnection, transaction);
                                    callingCmdlet.WriteWarning(string.Format("Node Id {0} description has updated to Iframe", description.NodeUid));
                                }
                                else
                                {
                                    new InsertMetadata("Description.Type", "Html", description.NodeUid, description.RootMapUid, description.DomainUid, description.Created, description.Modified, description.CreatedBy, description.ModifiedBy)
                                        .Execute(mapDbConnection, transaction);
                                    callingCmdlet.WriteWarning(string.Format("Node Id {0} description has updated to Iframe", description.NodeUid));
                                }
                            }
                            else
                            {
                                var descriptionUpdater = new OldHtmlDescriptionUpdater(description.MetadataValue, callingCmdlet);
                                new InsertMetadata("Description.Type", "Html", description.NodeUid, description.RootMapUid, description.DomainUid, description.Created, description.Modified, description.CreatedBy, description.ModifiedBy)
                                        .Execute(mapDbConnection, transaction);
                                new UpdateMetadata(description.MetadataId, "Description.Content", descriptionUpdater.Description)
                                        .Execute(mapDbConnection, transaction);
                                if (descriptionUpdater.Width > 0)
                                {
                                    new InsertMetadata("Description.Width", descriptionUpdater.Width.ToString(CultureInfo.InvariantCulture), description.NodeUid, description.RootMapUid, description.DomainUid, description.Created, description.Modified, description.CreatedBy, description.ModifiedBy)
                                    .Execute(mapDbConnection, transaction);
                                }

                                if (descriptionUpdater.Height > 0)
                                {
                                    new InsertMetadata("Description.Height", descriptionUpdater.Height.ToString(CultureInfo.InvariantCulture), description.NodeUid, description.RootMapUid, description.DomainUid, description.Created, description.Modified, description.CreatedBy, description.ModifiedBy)
                                    .Execute(mapDbConnection, transaction);
                                }
                                callingCmdlet.WriteWarning(string.Format("Node Id {0} description has updated to Html", description.NodeUid));
                            }
                            
                        }
                    }


                    transaction.Commit();

                    var updateGlymaDbVersion = new EmbeddedSqlScript("Glyma.Powershell.Update.v1_5_0_r4.UpdateGlymaDbVersion.sql");
                    updateGlymaDbVersion.ExecuteNonQuery(mapDbConnection);

                    
                    

                    callingCmdlet.WriteWarning("Database update completed");
                }
                catch (Exception ex)
                {
                    transaction.Rollback();
                    callingCmdlet.WriteWarning("Updated failed: " + ex.Message);
                    return;
                }

                mapDbConnection.Close();
            }

            using (var transactionDbConnection = new SqlConnection(TransactionDatabaseConnectionString))
            {
                try
                {
                    transactionDbConnection.Open();
                    var updateGlymatransactionDbVersion = new EmbeddedSqlScript("Glyma.Powershell.Update.v1_5_0_r4.UpdateGlymaDbVersion.sql");
                    updateGlymatransactionDbVersion.ExecuteNonQuery(transactionDbConnection);
                }
                catch (Exception ex)
                {
                    callingCmdlet.WriteWarning("Updated failed: " + ex.Message);
                    return;
                }
                transactionDbConnection.Close();
            }
        }
        public void ExecuteCmdletBase(PSCmdlet callingCmdlet)
        {
            SqlAssemblies sqlAssemblies = new SqlAssemblies();

            if (!sqlAssemblies.LoadedSuccessfully)
            {
                callingCmdlet.WriteWarning(sqlAssemblies.ErrorMessage);
                return;
            }

            try
            {
                SmoServer server = new SmoServer(sqlAssemblies, DatabaseServer);
                server.SetApplicationName("GlymaNewMapDbInstaller");

                SmoDatabase database = new SmoDatabase(sqlAssemblies, server, DatabaseName);

                SmoFileGroup fileGroup = new SmoFileGroup(sqlAssemblies, database, "PRIMARY");
                database.AddFileGroup(fileGroup);

                SmoDataFile dataFile = new SmoDataFile(sqlAssemblies, fileGroup, DatabaseName);
                fileGroup.AddDataFile(dataFile);
                dataFile.SetFileName(server.GetMasterDbPath() + "\\" + DatabaseName + ".mdf");
                dataFile.SetSize(50.0 * 1024.0);
                dataFile.SetGrowthType("KB");
                dataFile.SetGrowth(1024.0);
                dataFile.SetIsPrimaryFile(true);

                SmoLogFile logFile = new SmoLogFile(sqlAssemblies, database, DatabaseName + "_Log");
                database.AddLogFile(logFile);
                logFile.SetFileName(server.GetMasterDbPath() + "\\" + DatabaseName + "_Log.ldf");
                logFile.SetSize(164.0 * 1024.0);
                logFile.SetGrowthType("Percent");
                logFile.SetGrowth(10.0);

                database.Create();

                fileGroup = database.GetFileGroup("PRIMARY");
                fileGroup.SetIsDefault(true);
                fileGroup.Alter();
                database.Alter();

                using (SqlConnection connection = new SqlConnection(ConnectionString))
                {
                    connection.Open();

                    if (!string.IsNullOrEmpty(WebApplicationPoolAccount))
                    {
                        if (!IsWebApplicationPoolAccountDbo)
                        {
                            EmbeddedSqlScript createWebUserScript = new EmbeddedSqlScript("Glyma.Powershell.Resources.New_GLMapDB.CreateUser.sql");
                            createWebUserScript.AddToken("[ACCOUNT_NAME]", WebApplicationPoolAccount);
                            createWebUserScript.ExecuteNonQuery(connection);

                            EmbeddedSqlScript grantWebUserRoleScript = new EmbeddedSqlScript("Glyma.Powershell.Resources.New_GLMapDB.GrantUserRole.sql");
                            grantWebUserRoleScript.AddToken("[ACCOUNT_NAME]", WebApplicationPoolAccount);
                            grantWebUserRoleScript.AddToken("[ROLE]", "db_owner");
                            grantWebUserRoleScript.ExecuteNonQuery(connection);
                        }
                    }
                    else
                    {
                        callingCmdlet.WriteWarning("There was no web application pool account provided. As we are skipping this step, the web application pool account will need to be manually given db_owner rights to this Glyma Map DB.");
                    }

                    if (!string.IsNullOrEmpty(GlymaServiceApplicationPoolAccount))
                    {
                        if (!IsGlymaServiceApplicationPoolAccountDbo)
                        {
                            EmbeddedSqlScript createGlymaServiceUserScript = new EmbeddedSqlScript("Glyma.Powershell.Resources.New_GLMapDB.CreateUser.sql");
                            createGlymaServiceUserScript.AddToken("[ACCOUNT_NAME]", GlymaServiceApplicationPoolAccount);
                            createGlymaServiceUserScript.ExecuteNonQuery(connection);

                            EmbeddedSqlScript grantGlymaServiceUserRoleScript = new EmbeddedSqlScript("Glyma.Powershell.Resources.New_GLMapDB.GrantUserRole.sql");
                            grantGlymaServiceUserRoleScript.AddToken("[ACCOUNT_NAME]", GlymaServiceApplicationPoolAccount);
                            grantGlymaServiceUserRoleScript.AddToken("[ROLE]", "db_owner");
                            grantGlymaServiceUserRoleScript.ExecuteNonQuery(connection);
                        }
                    }
                    else
                    {
                        callingCmdlet.WriteWarning("There was no Glyma service application pool account provided. As we are skipping this step, the Glyma application pool account will need to be manually given db_owner rights to this Glyma Map DB.");
                    }

                    EmbeddedSqlScript createTablesScript = new EmbeddedSqlScript("Glyma.Powershell.Resources.New_GLMapDB.CreateTables.sql");
                    createTablesScript.ExecuteNonQuery(connection);

                    EmbeddedSqlScript createConstraintsScript = new EmbeddedSqlScript("Glyma.Powershell.Resources.New_GLMapDB.CreateConstraints.sql");
                    createConstraintsScript.ExecuteNonQuery(connection);

                    EmbeddedSqlScript insertTypesDataScript = new EmbeddedSqlScript("Glyma.Powershell.Resources.New_GLMapDB.InsertTypesData.sql");
                    insertTypesDataScript.ExecuteNonQuery(connection);

                    EmbeddedSqlScript createFullTextCatalogScript = new EmbeddedSqlScript("Glyma.Powershell.Resources.New_GLMapDB.CreateFullTextCatalog.sql");
                    createFullTextCatalogScript.ExecuteNonQuery(connection);

                    EmbeddedSqlScript createStoredProceduresScript = new EmbeddedSqlScript("Glyma.Powershell.Resources.New_GLMapDB.CreateStoredProcedures.sql");
                    createStoredProceduresScript.ExecuteNonQuery(connection);

                    EmbeddedSqlScript createQueryMapSPScript = new EmbeddedSqlScript("Glyma.Powershell.Resources.New_GLMapDB.CreateQueryMapSP.sql");
                    createQueryMapSPScript.ExecuteNonQuery(connection);

                    EmbeddedSqlScript createBasicSearchSPScript = new EmbeddedSqlScript("Glyma.Powershell.Resources.New_GLMapDB.CreateBasicSearchSP.sql");
                    createBasicSearchSPScript.ExecuteNonQuery(connection);

                    EmbeddedSqlScript createContainsUDFScript = new EmbeddedSqlScript("Glyma.Powershell.Resources.New_GLMapDB.CreateContainsUserDefinedFunction.sql");
                    createContainsUDFScript.ExecuteNonQuery(connection);

                    EmbeddedSqlScript createCreateFreeTextUDFScript = new EmbeddedSqlScript("Glyma.Powershell.Resources.New_GLMapDB.CreateFreeTextUserDefinedFunction.sql");
                    createCreateFreeTextUDFScript.ExecuteNonQuery(connection);

                    EmbeddedSqlScript createNodesListTableType = new EmbeddedSqlScript("Glyma.Powershell.Resources.New_GLMapDB.CreateNodesListTableType.sql");
                    createNodesListTableType.ExecuteNonQuery(connection);

                    EmbeddedSqlScript createQueryNodesSP = new EmbeddedSqlScript("Glyma.Powershell.Resources.New_GLMapDB.CreateQueryNodesSP.sql");
                    createQueryNodesSP.ExecuteNonQuery(connection);

                    EmbeddedSqlScript createGetGlymaDbVersionScript = new EmbeddedSqlScript("Glyma.Powershell.Resources.New_GLMapDB.CreateGetGlymaDbVersion.sql");
                    createGetGlymaDbVersionScript.ExecuteNonQuery(connection);

                    EmbeddedSqlScript createGetChildNodesSPScript = new EmbeddedSqlScript("Glyma.Powershell.Resources.New_GLMapDB.CreateGetChildNodesSP.sql");
                    createGetChildNodesSPScript.ExecuteNonQuery(connection);

                    EmbeddedSqlScript createGetNodeInMapDetailsSPScript = new EmbeddedSqlScript("Glyma.Powershell.Resources.New_GLMapDB.CreateGetNodeInMapDetailsSP.sql");
                    createGetNodeInMapDetailsSPScript.ExecuteNonQuery(connection);

                    EmbeddedSqlScript createGetNodesInMapSPScript = new EmbeddedSqlScript("Glyma.Powershell.Resources.New_GLMapDB.CreateGetNodesInMapSP.sql");
                    createGetNodesInMapSPScript.ExecuteNonQuery(connection);

                    EmbeddedSqlScript createGetParentNodesSPScript = new EmbeddedSqlScript("Glyma.Powershell.Resources.New_GLMapDB.CreateGetParentNodesSP.sql");
                    createGetParentNodesSPScript.ExecuteNonQuery(connection);

                    EmbeddedSqlScript createGetRootMapsSPScript = new EmbeddedSqlScript("Glyma.Powershell.Resources.New_GLMapDB.CreateGetRootMapsSP.sql");
                    createGetRootMapsSPScript.ExecuteNonQuery(connection);

                    EmbeddedSqlScript addNewColumnsScript = new EmbeddedSqlScript("Glyma.Powershell.Resources.New_GLMapDB.CreateAuditLogsTable.sql");
                    addNewColumnsScript.ExecuteNonQuery(connection);

                    if (!string.IsNullOrEmpty(SearchCrawlAccount))
                    {
                        if (!IsSearchCrawlAccountDbo)
                        {
                            EmbeddedSqlScript createSearchUserScript = new EmbeddedSqlScript("Glyma.Powershell.Resources.New_GLMapDB.CreateUser.sql");
                            createSearchUserScript.AddToken("[ACCOUNT_NAME]", SearchCrawlAccount);
                            createSearchUserScript.ExecuteNonQuery(connection);

                            EmbeddedSqlScript grantSearchPermissionsScript = new EmbeddedSqlScript("Glyma.Powershell.Resources.New_GLMapDB.GrantSearchPermissions.sql");
                            grantSearchPermissionsScript.AddToken("[ACCOUNT_NAME]", SearchCrawlAccount);
                            grantSearchPermissionsScript.ExecuteNonQuery(connection);
                        }
                    }
                    else
                    {
                        callingCmdlet.WriteWarning("There was no search crawl account provided. As we are skipping this step, the Glyma search crawl account will need to be manually granted execute permissions on the GetChildNodes, GetNodeInMapDetails, GetNodesInMap, GetParentNodes and GetRootMaps stored proecedures.");
                    }

                    connection.Close();
                }
            }
            catch (TargetInvocationException tiex)
            {
                //If it was a Target Invocation Exception find the last InnerException and throw it so the user gets a useful message to troubleshoot.
                Exception ex = Util.FindLastException(tiex);
                throw ex;
            }
        }
        public void ExecuteCmdletBase(PSCmdlet callingCmdlet)
        {
            SqlAssemblies sqlAssemblies = new SqlAssemblies();

            if (!sqlAssemblies.LoadedSuccessfully)
            {
                callingCmdlet.WriteWarning(sqlAssemblies.ErrorMessage);
                return;
            }

            SmoServer server = new SmoServer(sqlAssemblies, DatabaseServer);
            server.SetApplicationName("GlymaNewMapSecurityDbInstaller");

            SmoDatabase database = new SmoDatabase(sqlAssemblies, server, DatabaseName);

            SmoFileGroup fileGroup = new SmoFileGroup(sqlAssemblies, database, "PRIMARY");
            database.AddFileGroup(fileGroup);

            SmoDataFile dataFile = new SmoDataFile(sqlAssemblies, fileGroup, DatabaseName);
            fileGroup.AddDataFile(dataFile);
            dataFile.SetFileName(server.GetMasterDbPath() + "\\" + DatabaseName + ".mdf");
            dataFile.SetSize(50.0 * 1024.0);
            dataFile.SetGrowthType("KB");
            dataFile.SetGrowth(1024.0);
            dataFile.SetIsPrimaryFile(true);

            SmoLogFile logFile = new SmoLogFile(sqlAssemblies, database, DatabaseName + "_Log");
            database.AddLogFile(logFile);
            logFile.SetFileName(server.GetMasterDbPath() + "\\" + DatabaseName + "_Log.ldf");
            logFile.SetSize(164.0 * 1024.0);
            logFile.SetGrowthType("Percent");
            logFile.SetGrowth(10.0);

            database.Create();

            fileGroup = database.GetFileGroup("PRIMARY");
            fileGroup.SetIsDefault(true);
            fileGroup.Alter();
            database.Alter();

            using (SqlConnection connection = new SqlConnection(ConnectionString))
            {
                connection.Open();

                EmbeddedSqlScript createUserScript = new EmbeddedSqlScript("Glyma.Powershell.Resources.New_GLMapSecurityDB.CreateUser.sql");
                createUserScript.AddToken("[ACCOUNT_NAME]", ApplicationPoolAccount);
                createUserScript.ExecuteNonQuery(connection);

                EmbeddedSqlScript grantUserRoleScript = new EmbeddedSqlScript("Glyma.Powershell.Resources.New_GLMapSecurityDB.GrantUserRole.sql");
                grantUserRoleScript.AddToken("[ACCOUNT_NAME]", ApplicationPoolAccount);
                grantUserRoleScript.AddToken("[ROLE]", "db_owner");
                grantUserRoleScript.ExecuteNonQuery(connection);

                // TODO Create security database.

                EmbeddedSqlScript createGetRootMapsSPScript = new EmbeddedSqlScript("Glyma.Powershell.Resources.New_GLMapSecurityDB.CreateGetRootMapsSP.sql");
                createGetRootMapsSPScript.ExecuteNonQuery(connection);

                EmbeddedSqlScript createSearchUserScript = new EmbeddedSqlScript("Glyma.Powershell.Resources.New_GLMapSecurityDB.CreateUser.sql");
                createSearchUserScript.AddToken("[ACCOUNT_NAME]", SearchCrawlAccount);
                createSearchUserScript.ExecuteNonQuery(connection);

                EmbeddedSqlScript grantSearchPermissionsScript = new EmbeddedSqlScript("Glyma.Powershell.Resources.New_GLMapSecurityDB.GrantSearchPermissions.sql");
                grantSearchPermissionsScript.AddToken("[ACCOUNT_NAME]", SearchCrawlAccount);
                grantSearchPermissionsScript.ExecuteNonQuery(connection);

                connection.Close();
            }
        }
        public void ExecuteCmdletBase(PSCmdlet callingCmdlet)
        {
            EmbeddedSqlScript createGetGlymaDbVersionScript = new EmbeddedSqlScript("Glyma.Powershell.Update.v1_5_0_r1.CreateGetGlymaDbVersion.sql");

            using (SqlConnection mapDbConnection = new SqlConnection(MapDatabaseConnectionString))
            {
                mapDbConnection.Open();

                try
                {
                    EmbeddedSqlScript addNewColumnsScript = new EmbeddedSqlScript("Glyma.Powershell.Update.v1_5_0_r1.MapDbAddNewColumns.sql");
                    addNewColumnsScript.ExecuteNonQuery(mapDbConnection);
                }
                catch
                {
                }

                try
                {
                    EmbeddedSqlScript addNewColumnContraints = new EmbeddedSqlScript("Glyma.Powershell.Update.v1_5_0_r1.MapDbAddNewColumnConstraints.sql");
                    addNewColumnContraints.ExecuteNonQuery(mapDbConnection);
                }
                catch
                {
                }

                try
                {
                    EmbeddedSqlScript modifyQueryMapSP = new EmbeddedSqlScript("Glyma.Powershell.Update.v1_5_0_r1.ModifyQueryMapSP.sql");
                    modifyQueryMapSP.ExecuteNonQuery(mapDbConnection);
                }
                catch
                {
                }

                try
                {
                    EmbeddedSqlScript createQueryMapSP = new EmbeddedSqlScript("Glyma.Powershell.Update.v1_5_0_r1.CreateQueryMapSP.sql");
                    createQueryMapSP.ExecuteNonQuery(mapDbConnection);
                }
                catch
                {
                }

                try
                {
                    EmbeddedSqlScript createNodesListTableType = new EmbeddedSqlScript("Glyma.Powershell.Update.v1_5_0_r1.CreateNodesListTableType.sql");
                    createNodesListTableType.ExecuteNonQuery(mapDbConnection);
                }
                catch
                {
                }

                try
                {
                    EmbeddedSqlScript createQueryNodesSP = new EmbeddedSqlScript("Glyma.Powershell.Update.v1_5_0_r1.CreateQueryNodesSP.sql");
                    createQueryNodesSP.ExecuteNonQuery(mapDbConnection);
                }
                catch
                {
                }

                try
                {
                    createGetGlymaDbVersionScript.ExecuteNonQuery(mapDbConnection);
                }
                catch
                {
                }

                mapDbConnection.Close();
            }

            using (SqlConnection transactionDbConnection = new SqlConnection(TransactionDatabaseConnectionString))
            {
                transactionDbConnection.Open();

                try
                {
                    EmbeddedSqlScript addNewColumnsScript = new EmbeddedSqlScript("Glyma.Powershell.Update.v1_5_0_r1.TransactionDbModifyColumns.sql");
                    addNewColumnsScript.ExecuteNonQuery(transactionDbConnection);
                }
                catch
                {
                }

                try
                {
                    createGetGlymaDbVersionScript.ExecuteNonQuery(transactionDbConnection);
                }
                catch
                {
                }

                transactionDbConnection.Close();
            }

            QueryMapResultConsumer domainNodesConsumer = new QueryMapResultConsumer();

            using (MappingToolDatabaseDataContext mapDatabaseContext = new MappingToolDatabaseDataContext(MapDatabaseConnectionString))
            {
                mapDatabaseContext.CommandTimeout = 600;
                var domainNodes = from node in mapDatabaseContext.Nodes
                                  where node.NodeTypeUid.HasValue && node.NodeTypeUid.Value == DomainNodeType
                                  select node;

                if (domainNodes != null && domainNodes.Count() > 0)
                {
                    foreach (var domainNode in domainNodes)
                    {
                        var domainMaps = mapDatabaseContext.QueryMapMultiDepth(domainNode.DomainUid, domainNode.NodeUid, 1, true);

                        domainNodesConsumer.Consume(domainMaps);
                    }
                }

                var rootMaps = from qNode in domainNodesConsumer.Nodes.Values
                               select qNode.NodeUid;

                DateTime startTime = new DateTime(2014, 04, 01, 0, 0, 0);

                foreach (var map in domainNodesConsumer.Nodes.Values)
                {
                    if (map.NodeTypeUid.HasValue && map.NodeTypeUid != DomainNodeType)
                    {
                        QueryMapResultConsumer mapNodesConsumer = new QueryMapResultConsumer();
                        DbIntegrityUtilities integrityUtilities = new DbIntegrityUtilities(mapNodesConsumer);

                        var mapNodes = mapDatabaseContext.QueryMapMultiDepth(map.DomainUid, map.NodeUid, -1, false);

                        callingCmdlet.WriteVerbose("Processing nodes");
                        mapNodesConsumer.Consume(mapNodes);
                        integrityUtilities.DetectAndFixMapCollisions(callingCmdlet, mapDatabaseContext, rootMaps, false, false);
                        callingCmdlet.WriteVerbose("Finished processing nodes");

                        callingCmdlet.WriteVerbose("Processing nodes and related metadata");
                        foreach (var node in mapNodesConsumer.Nodes.Values)
                        {
                            var dbNodes = from qNode in mapDatabaseContext.Nodes
                                          where qNode.NodeUid == node.NodeUid
                                          select qNode;

                            if (dbNodes != null && dbNodes.Count() > 0)
                            {
                                var dbNode = dbNodes.First();

                                dbNode.Created = startTime;
                                dbNode.Modified = startTime;
                                dbNode.RootMapUid = map.NodeUid;

                                foreach (var dbMetadata in dbNode.Metadatas)
                                {
                                    dbMetadata.Created = startTime;
                                    dbMetadata.Modified = startTime;

                                    if (dbMetadata.DomainUid == null)
                                    {
                                        dbMetadata.DomainUid = map.DomainUid;
                                    }

                                    if (dbMetadata.RootMapUid == null)
                                    {
                                        dbMetadata.RootMapUid = map.NodeUid;
                                    }
                                }

                                mapDatabaseContext.SubmitChanges();
                            }

                            callingCmdlet.WriteVerbose("Finished node " + node.NodeUid);
                        }
                        callingCmdlet.WriteVerbose("Finished processing nodes");

                        callingCmdlet.WriteVerbose("Processing relationships and related metadata");
                        foreach (var relationship in mapNodesConsumer.Relationships.Values)
                        {
                            var dbRelationships = from qRelationship in mapDatabaseContext.Relationships
                                                  where qRelationship.RelationshipUid == relationship.RelationshipUid
                                                  select qRelationship;

                            if (dbRelationships != null && dbRelationships.Count() > 0)
                            {
                                var dbRelationship = dbRelationships.First();

                                dbRelationship.Created = startTime;
                                dbRelationship.Modified = startTime;
                                dbRelationship.RootMapUid = map.NodeUid;

                                foreach (var dbMetadata in dbRelationship.Metadatas)
                                {
                                    dbMetadata.Created = startTime;
                                    dbMetadata.Modified = startTime;

                                    if (dbMetadata.DomainUid == null)
                                    {
                                        dbMetadata.DomainUid = map.DomainUid;
                                    }

                                    if (dbMetadata.RootMapUid == null)
                                    {
                                        dbMetadata.RootMapUid = map.NodeUid;
                                    }
                                }

                                mapDatabaseContext.SubmitChanges();
                            }

                            callingCmdlet.WriteVerbose("Finished relationship " + relationship.RelationshipUid);
                        }
                        callingCmdlet.WriteVerbose("Finished processing relationships");
                    }
                }
            }
        }
        private bool UpdateMappingToolDatabase(PSCmdlet callingCmdlet)
        {
            using (MappingTool.MappingToolDatabaseDataContext mapDatabaseContext = new MappingTool.MappingToolDatabaseDataContext(MapDatabaseConnectionString))
            {
                var glymaDbVersion = mapDatabaseContext.GetGlymaDbVersion();

                foreach (var row in glymaDbVersion)
                {
                    if (row.Column1 != "v1.5.0r2")
                    {
                        callingCmdlet.WriteWarning(string.Format("This update can only update the v1.5.0r2 database to v1.5.0r3 database. The version of this database is {0}.", row.Column1));

                        return false;
                    }
                }
            }

            using (SqlConnection mapDbConnection = new SqlConnection(MapDatabaseConnectionString))
            {
                mapDbConnection.Open();

                try
                {
                    EmbeddedSqlScript updateGlymaDbVersion = new EmbeddedSqlScript("Glyma.Powershell.Update.v1_5_0_r3.UpdateGlymaDbVersion.sql");
                    updateGlymaDbVersion.ExecuteNonQuery(mapDbConnection);
                }
                catch
                {
                    return false;
                }

                mapDbConnection.Close();
            }

            return true;
        }
        private bool UpdateTransactionDatabase(PSCmdlet callingCmdlet)
        {
            using (Transaction.TransactionDatabaseDataContext transactionDatabaseContext = new Transaction.TransactionDatabaseDataContext(TransactionDatabaseConnectionString))
            {
                var glymaDbVersion = transactionDatabaseContext.GetGlymaDbVersion();

                foreach (var row in glymaDbVersion)
                {
                    if (row.Column1 != "v1.5.0r2")
                    {
                        callingCmdlet.WriteWarning(string.Format("This update can only update the v1.5.0r2 database to v1.5.0r3 database. The version of this database is {0}.", row.Column1));

                        return false;
                    }
                }
            }

            using (SqlConnection transactionDbConnection = new SqlConnection(TransactionDatabaseConnectionString))
            {
                transactionDbConnection.Open();

                try
                {
                    EmbeddedSqlScript updateGlymaDbVersion = new EmbeddedSqlScript("Glyma.Powershell.Update.v1_5_0_r3.UpdateGlymaDbVersion.sql");
                    updateGlymaDbVersion.ExecuteNonQuery(transactionDbConnection);
                }
                catch
                {
                    return false;
                }

                try
                {
                    EmbeddedSqlScript insertNewTransactionOperations = new EmbeddedSqlScript("Glyma.Powershell.Update.v1_5_0_r3.InsertTransactionOperations.sql");
                    insertNewTransactionOperations.ExecuteNonQuery(transactionDbConnection);
                }
                catch
                {
                    return false;
                }

                transactionDbConnection.Close();
            }

            return true;
        }