public OldHtmlDescriptionUpdater(string description, PSCmdlet callingCmdlet)
        {
            try
            {
                var settings = new XmlReaderSettings();
                settings.ProhibitDtd = false;
                callingCmdlet.WriteWarning("Reading HTML descrption");
                using (XmlReader reader = XmlReader.Create(new StringReader(XmlDeclaration + description), settings))
                {
                    reader.ReadToFollowing("div");
                    var id = reader.GetAttribute("id");
                    if (id == "GlymaNodeDescriptionDiv")
                    {
                        callingCmdlet.WriteWarning("GlymaNodeDescriptionDiv div tag found");

                        var widthString = reader.GetAttribute("width");
                        int width;
                        if (widthString != null && int.TryParse(widthString, out width) && width > 0)
                        {
                            Width = width;
                        }

                        var heightString = reader.GetAttribute("height");
                        int height;
                        if (heightString != null && int.TryParse(heightString, out height) && height > 0)
                        {
                            Height = height;
                        }

                        Description = reader.ReadInnerXml();
                    }
                    else
                    {
                        Description = description;
                    }
                }
            }
            catch
            {
                Description = description;
            }
        }
        /**
         * This function takes in a CommandInfo (CmdletInfo or FunctionInfo)
         * And reads all the deprecation attributes attached to it
         * Prints a message on the cmdline For each of the attribute found
         *
         * the boundParameterNames is a list of parameters bound to the cmdlet at runtime,
         * We only process the Parameter beaking change attributes attached only params listed in this list (if present)
         * */
        public static void ProcessCustomAttributesAtRuntime(CommandInfo commandInfo, InvocationInfo invocationInfo, String parameterSet, System.Management.Automation.PSCmdlet psCmdlet)
        {
            bool supressWarningOrError = false;

            try
            {
                supressWarningOrError = bool.Parse(System.Environment.GetEnvironmentVariable(SUPPRESS_ERROR_OR_WARNING_MESSAGE_ENV_VARIABLE_NAME));
            }
            catch (Exception)
            {
                //no action
            }

            if (supressWarningOrError)
            {
                //Do not process the attributes at runtime... The env variable to override the warning messages is set
                return;
            }

            List <GenericBreakingChangeAttribute> attributes = new List <GenericBreakingChangeAttribute>(GetAllBreakingChangeAttributesInType(commandInfo, invocationInfo, parameterSet));
            StringBuilder   sb = new StringBuilder();
            Action <string> appendBreakingChangeInfo = (string s) => sb.Append(s);

            if (attributes != null && attributes.Count > 0)
            {
                appendBreakingChangeInfo(string.Format(Resources.BreakingChangesAttributesHeaderMessage, commandInfo.Name.Split('_')[0]));

                foreach (GenericBreakingChangeAttribute attribute in attributes)
                {
                    attribute.PrintCustomAttributeInfo(appendBreakingChangeInfo);
                }

                appendBreakingChangeInfo(string.Format(Resources.BreakingChangesAttributesFooterMessage, BREAKING_CHANGE_ATTRIBUTE_INFORMATION_LINK));

                psCmdlet.WriteWarning(sb.ToString());
            }

            List <PreviewMessageAttribute> previewAttributes = new List <PreviewMessageAttribute>(GetAllPreviewAttributesInType(commandInfo, invocationInfo));

            if (previewAttributes != null && previewAttributes.Count > 0)
            {
                foreach (PreviewMessageAttribute attribute in previewAttributes)
                {
                    attribute.PrintCustomAttributeInfo(psCmdlet);
                }
            }
        }
Exemple #3
0
        public bool PopulateCmdletBase(PSCmdlet cmdlet, ref Get_GLDomainBase cmdletBase)
        {
            bool isSuccessful = false;

            object identityAsObject = Identity;

            if (Identity is PSObject)
            {
                PSObject identityAsPSObject = Identity as PSObject;

                identityAsObject = identityAsPSObject.BaseObject;
            }

            if (identityAsObject is SPSite)
            {
                SPSite site = identityAsObject as SPSite;

                using (SPWeb web = site.RootWeb)
                {
                    isSuccessful = GetDatabaseDetails(web, ref cmdletBase);
                }
            }
            else if (identityAsObject is SPWeb)
            {
                SPWeb web = identityAsObject as SPWeb;

                isSuccessful = GetDatabaseDetails(web, ref cmdletBase);
            }
            else if (identityAsObject is string)
            {
                string siteUrl = identityAsObject as string;

                using (SPSite site = new SPSite(siteUrl))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        isSuccessful = GetDatabaseDetails(web, ref cmdletBase);
                    }
                }
            }
            else if (identityAsObject is Guid)
            {
                Guid siteId = (Guid)identityAsObject;

                using (SPSite site = new SPSite(siteId))
                {
                    using (SPWeb web = site.RootWeb)
                    {
                        isSuccessful = GetDatabaseDetails(web, ref cmdletBase);
                    }
                }
            }
            else
            {
                cmdlet.WriteWarning("No valid 'Identity' specified. Identity must be a SPSite, SPWeb, site/web URL, or site colleciton ID.");

                return isSuccessful;
            }

            if (!isSuccessful)
            {
                cmdlet.WriteWarning("Provided 'Identity' has no Glyma Server details declared for it. Try a parent if it's a sub-site.");

                return isSuccessful;
            }

            return isSuccessful;
        }
Exemple #4
0
 public void PrintCustomAttributeInfo(System.Management.Automation.PSCmdlet psCmdlet)
 {
     psCmdlet.WriteWarning(this._message);
 }
        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;
            }
        }
        /// <summary>
        /// Gets a sql auth connection context.
        /// </summary>
        /// <param name="cmdlet">The cmdlet requesting the context</param>
        /// <param name="serverName">The name of the server to connect to</param>
        /// <param name="manageUrl">The manage url of the server</param>
        /// <param name="credentials">The credentials to connect to the server</param>
        /// <param name="sessionActivityId">The session activity ID</param>
        /// <param name="managementServiceUri">The URI for management service</param>
        /// <returns>The connection context</returns>
        public static IServerDataServiceContext GetContext(
            PSCmdlet cmdlet,
            string serverName,
            Uri manageUrl,
            SqlAuthenticationCredentials credentials,
            Guid sessionActivityId,
            Uri managementServiceUri)
        {
            Version version;
            
            // If a version was specified (by tests) us it.
            if (sqlVersion == SqlVersion.v2)
            {
                version = new Version(11, 0);
            }
            else if (sqlVersion == SqlVersion.v12)
            {
                version = new Version(12, 0);
            }
            else // If no version specified, determine the version by querying the server.
            {
                version = GetVersion(manageUrl, credentials);
            }
            sqlVersion = SqlVersion.None;

            IServerDataServiceContext context = null;

            if (version.Major >= 12)
            {
                context = new TSqlConnectionContext(
                    sessionActivityId,
                    manageUrl.Host,
                    credentials,
                    serverName);
            }
            else
            {
                context = ServerDataServiceSqlAuth.Create(
                    managementServiceUri,
                    sessionActivityId,
                    credentials,
                    serverName);

                // Retrieve $metadata to verify model version compatibility
                XDocument metadata = ((ServerDataServiceSqlAuth)context).RetrieveMetadata();
                XDocument filteredMetadata = DataConnectionUtility.FilterMetadataDocument(metadata);
                string metadataHash = DataConnectionUtility.GetDocumentHash(filteredMetadata);
                if (!((ServerDataServiceSqlAuth)context).metadataHashes.Any(knownHash => metadataHash == knownHash))
                {
                    cmdlet.WriteWarning(Resources.WarningModelOutOfDate);
                }

                ((ServerDataServiceSqlAuth)context).MergeOption = MergeOption.PreserveChanges;
            }

            return context;
        }
        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();
            }
        }
Exemple #9
0
        public void ExecuteCmdletBase(PSCmdlet callingCmdlet)
        {
            if (Domain == null)
            {
                callingCmdlet.WriteWarning("No valid domain has been provided.");

                return;
            }

            if (!Domain.CheckIsValid())
            {
                callingCmdlet.WriteWarning("An invalid domain object has been provided.");

                return;
            }

            Model.IDatabaseInfo dbInfo = Domain;

            using (MappingToolDatabaseDataContext dataContext = new MappingToolDatabaseDataContext(dbInfo.ConnectionString))
            {
                dataContext.CommandTimeout = 180;
                if (MapId != Guid.Empty)
                {
                    /// Find maps by ID.
                    /// 

                    Model.Map map = GetMapById(dataContext, MapId);

                    callingCmdlet.WriteObject(map);
                }
                else if (!string.IsNullOrEmpty(MapName))
                {
                    /// Find maps by name.
                    /// 

                    List<Model.Map> maps = GetMapsByName(dataContext, MapName);

                    callingCmdlet.WriteObject(maps, true);
                }
                else
                {
                    /// Fine all maps.
                    /// 

                    List<Model.Map> maps = GetAllMaps(dataContext);

                    callingCmdlet.WriteObject(maps, true);
                }
            }
        }
        public void ExecuteCmdletBase(PSCmdlet callingCmdlet)
        {
            HashSet<Guid> validMaps = new HashSet<Guid>();
            HashSet<Guid> orphanedNodes = new HashSet<Guid>();
            HashSet<Guid> orphanedRelationships = new HashSet<Guid>();

            if (RootMap == null || !RootMap.CheckIsValid())
            {
                callingCmdlet.WriteWarning("An invalid source map has been provided.");

                return;
            }

            Model.IDatabaseInfo mapDbInfo = RootMap.Domain;

            using (MappingToolDatabaseDataContext dataContext = new MappingToolDatabaseDataContext(mapDbInfo.ConnectionString))
            {
                dataContext.CommandTimeout = 180;

                var dbRootMapNodes = from dbNode in dataContext.Nodes
                                     where dbNode.NodeUid == RootMap.NodeId
                                     select dbNode;

                var dbRootMapNode = dbRootMapNodes.FirstOrDefault();

                if (dbRootMapNode == null)
                {
                    throw new KeyNotFoundException("The specified root map doesn't exist.");
                }

                if (dbRootMapNode.NodeUid != dbRootMapNode.RootMapUid)
                {
                    throw new NotSupportedException("The provided root map isn't a root map.");
                }

                /// We need to find all the valid children maps, starting at the root map. We'll do this recursively.
                #region Find valid maps
                validMaps.Add(dbRootMapNode.NodeUid);

                RecusivelyFindValidMaps(ref validMaps, dbRootMapNode);
                #endregion

                #region Find all nodes that aren't part of a valid map
                var allNodesInMap = from dbNode in dataContext.Nodes
                                    where dbNode.RootMapUid == RootMap.NodeId
                                    select dbNode;

                foreach (var node in allNodesInMap)
                {
                    if (validMaps.Contains(node.NodeUid))
                    {
                        continue;
                    }

                    bool isNodeValid = CheckIsValid(ref validMaps, node);

                    if (!isNodeValid)
                    {
                        /// If the orphaned nodes list doesn't contain the node, then add the node to the list.
                        if (!orphanedNodes.Contains(node.NodeUid))
                        {
                            orphanedNodes.Add(node.NodeUid);
                        }

                        /// Find all the orphaned relationships.
                        FindOrphanedRelationships(ref orphanedRelationships, node);
                    }
                }
                #endregion

                int orphanedNodesCount = 0;
                int orphanedMetadataCount = 0;
                int orphanedDescriptorsCount = 0;
                int orphanedRelationshipsCount = 0;

                foreach (Guid nodeId in orphanedNodes)
                {
                    var orphanedDescriptors = from dbDescriptor in dataContext.Descriptors
                                              where dbDescriptor.NodeUid == nodeId
                                              select dbDescriptor;

                    foreach (var orphanedDescriptor in orphanedDescriptors)
                    {
                        dataContext.Descriptors.DeleteOnSubmit(orphanedDescriptor);
                        orphanedDescriptorsCount++;
                    }

                    var orphanedMetadata = from dbMetadata in dataContext.Metadatas
                                           where dbMetadata.NodeUid == nodeId
                                           select dbMetadata;

                    foreach (var orphanedMetadatum in orphanedMetadata)
                    {
                        dataContext.Metadatas.DeleteOnSubmit(orphanedMetadatum);
                        orphanedMetadataCount++;
                    }
                }

                dataContext.SubmitChanges();

                foreach (Guid relationshipId in orphanedRelationships)
                {
                    var orphanedDescriptors = from dbDescriptor in dataContext.Descriptors
                                              where dbDescriptor.RelationshipUid == relationshipId
                                              select dbDescriptor;

                    foreach (var orphanedDescriptor in orphanedDescriptors)
                    {
                        dataContext.Descriptors.DeleteOnSubmit(orphanedDescriptor);
                        orphanedDescriptorsCount++;
                    }

                    var orphanedMetadata = from dbMetadata in dataContext.Metadatas
                                           where dbMetadata.RelationshipUid == relationshipId
                                           select dbMetadata;

                    foreach (var orphanedMetadatum in orphanedMetadata)
                    {
                        dataContext.Metadatas.DeleteOnSubmit(orphanedMetadatum);
                        orphanedMetadataCount++;
                    }
                }

                dataContext.SubmitChanges();

                foreach (Guid nodeId in orphanedNodes)
                {
                    var orphanedDbNodes = from dbNode in dataContext.Nodes
                                          where dbNode.NodeUid == nodeId
                                          select dbNode;

                    foreach (var orphanedNode in orphanedDbNodes)
                    {
                        dataContext.Nodes.DeleteOnSubmit(orphanedNode);
                        orphanedNodesCount++;
                    }
                }

                dataContext.SubmitChanges();

                foreach (Guid relationshipId in orphanedRelationships)
                {
                    var orphanedDbRelationships = from dbRelationship in dataContext.Relationships
                                                  where dbRelationship.RelationshipUid == relationshipId
                                                  select dbRelationship;

                    foreach (var orphanedRelationship in orphanedDbRelationships)
                    {
                        dataContext.Relationships.DeleteOnSubmit(orphanedRelationship);
                        orphanedRelationshipsCount++;
                    }
                }

                dataContext.SubmitChanges();

                callingCmdlet.WriteVerbose(string.Format("Deleted {0} orphaned node/s.", orphanedNodesCount));
                callingCmdlet.WriteVerbose(string.Format("Deleted {0} orphaned relationship/s.", orphanedRelationshipsCount));
                callingCmdlet.WriteVerbose(string.Format("Deleted {0} orphaned metadata/s.", orphanedMetadataCount));
                callingCmdlet.WriteVerbose(string.Format("Deleted {0} orphaned descriptor/s.", orphanedDescriptorsCount));
            }
        }
        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;
        }
Exemple #13
0
        public void ExecuteCmdletBase(PSCmdlet callingCmdlet)
        {
            Dictionary<Guid, QueryMapNode> originalNodes = new Dictionary<Guid, QueryMapNode>();
            List<QueryMapRelationship> originalRelationships = new List<QueryMapRelationship>();
            List<QueryMapDescriptor> originalDescriptors = new List<QueryMapDescriptor>();
            List<QueryMapMetadata> originalMetadata = new List<QueryMapMetadata>();

            if (DestinationDomain == null || !DestinationDomain.CheckIsValid())
            {
                callingCmdlet.WriteWarning("An invalid destination domain has been provided.");

                return;
            }

            if (SourceMap == null || !SourceMap.CheckIsValid())
            {
                callingCmdlet.WriteWarning("An invalid source map has been provided.");

                return;
            }

            Model.IDatabaseInfo sourceMapDbInfo = SourceMap.Domain;

            using (MappingToolDatabaseDataContext dataContext = new MappingToolDatabaseDataContext(sourceMapDbInfo.ConnectionString))
            {
                dataContext.CommandTimeout = 180;
                var queryMapResultSets = dataContext.QueryMapMultiDepth(SourceMap.Domain.DomainId, SourceMap.NodeId, -1, false);

                var queryMapResultSet = queryMapResultSets.GetResult<QueryMapMultiDepthResult>();

                while (queryMapResultSet != null)
                {
                    foreach (var queryMapResult in queryMapResultSet)
                    {
                        if (queryMapResult.Level != null)
                        {
                            if (queryMapResult.NodeUid.HasValue && queryMapResult.NodeUid != Guid.Empty)
                            {
                                /// Make sure that we aren't copying across a domain node.
                                if (queryMapResult.NodeTypeUid.HasValue && queryMapResult.NodeTypeUid != new Guid("263754C2-2F31-4D21-B9C4-6509E00A5E94"))
                                {
                                    /// The QueryMap procedure returns ALL nodes by following relationships to max depth meaning some nodes are repeated in some of the levels multiple nodes may connect to them.
                                    if (!originalNodes.ContainsKey(queryMapResult.NodeUid.Value))
                                    {
                                        /// TODO: Need to consider copying the NodeOriginalId.
                                        QueryMapNode node = new QueryMapNode();
                                        node.NodeUid = queryMapResult.NodeUid.Value;
                                        node.DomainUid = DestinationDomain.DomainId;
                                        node.NodeTypeUid = queryMapResult.NodeTypeUid;
                                        node.RootMapUid = queryMapResult.RootMapUid;
                                        node.Created = queryMapResult.Created;
                                        node.Modified = queryMapResult.Modified;
                                        node.CreatedBy = queryMapResult.CreatedBy;
                                        node.ModifiedBy = queryMapResult.ModifiedBy;

                                        originalNodes[queryMapResult.NodeUid.Value] = node;
                                    }
                                }
                            }
                        }
                        else if (queryMapResult.MetadataId != null)
                        {
                            if (queryMapResult.MetadataId.HasValue && queryMapResult.MetadataId != Guid.Empty)
                            {
                                QueryMapMetadata metadatum = new QueryMapMetadata();
                                metadatum.MetadataId = queryMapResult.MetadataId.Value;
                                metadatum.NodeUid = queryMapResult.NodeUid;
                                metadatum.RelationshipUid = queryMapResult.RelationshipUid;
                                metadatum.DescriptorTypeUid = queryMapResult.DescriptorTypeUid;
                                metadatum.MetadataTypeUid = queryMapResult.MetadataTypeUid;
                                metadatum.MetadataName = queryMapResult.MetadataName;
                                metadatum.MetadataValue = queryMapResult.MetadataValue;
                                metadatum.DomainUid = queryMapResult.DomainUid;
                                metadatum.RootMapUid = queryMapResult.RootMapUid;
                                metadatum.Created = queryMapResult.Created;
                                metadatum.Modified = queryMapResult.Modified;
                                metadatum.CreatedBy = queryMapResult.CreatedBy;
                                metadatum.ModifiedBy = queryMapResult.ModifiedBy;

                                originalMetadata.Add(metadatum);
                            }
                        }
                        else if (queryMapResult.DescriptorUid != null)
                        {
                            if (queryMapResult.DescriptorUid.HasValue && queryMapResult.DescriptorUid != Guid.Empty)
                            {
                                QueryMapDescriptor descriptor = new QueryMapDescriptor();
                                descriptor.DescriptorUid = queryMapResult.DescriptorUid.Value;
                                descriptor.NodeUid = queryMapResult.NodeUid;
                                descriptor.RelationshipUid = queryMapResult.RelationshipUid;
                                descriptor.DescriptorTypeUid = queryMapResult.DescriptorTypeUid;

                                originalDescriptors.Add(descriptor);
                            }
                        }
                        else
                        {
                            if (queryMapResult.RelationshipUid.HasValue && queryMapResult.RelationshipUid != Guid.Empty)
                            {
                                /// TODO: Need to consider copying the RelationshipOriginalId.
                                QueryMapRelationship relationship = new QueryMapRelationship();
                                relationship.RelationshipUid = queryMapResult.RelationshipUid.Value;
                                relationship.DomainUid = DestinationDomain.DomainId;
                                relationship.RelationshipTypeUid = queryMapResult.RelationshipTypeUid;
                                relationship.RootMapUid = queryMapResult.RootMapUid;
                                relationship.Created = queryMapResult.Created;
                                relationship.Modified = queryMapResult.Modified;
                                relationship.CreatedBy = queryMapResult.CreatedBy;
                                relationship.ModifiedBy = queryMapResult.ModifiedBy;

                                originalRelationships.Add(relationship);
                            }
                        }
                    }

                    queryMapResultSet = queryMapResultSets.GetResult<QueryMapMultiDepthResult>();
                }
            }

            int totalNodes = originalNodes.Count;
            int totalRelationships = originalRelationships.Count;
            int totalMetadata = originalMetadata.Count;
            int totalDescriptors = originalDescriptors.Count;

            Dictionary<Guid, Guid> newNodeIds = new Dictionary<Guid, Guid>();
            Dictionary<Guid, Guid> newRelationshipIds = new Dictionary<Guid, Guid>();

            Model.IDatabaseInfo destinationDomainDbInfo = DestinationDomain;

            /// The following performs the creation of nodes in the new database
            using (MappingToolDatabaseDataContext dataContext = new MappingToolDatabaseDataContext(destinationDomainDbInfo.ConnectionString))
            {
                dataContext.CommandTimeout = 180;
                int count = 0;

                callingCmdlet.WriteVerbose("Processing of nodes starting.");

                DateTime currentTime = DateTime.Now;

                WindowsIdentity currentUserIdentity = WindowsIdentity.GetCurrent();
                string currentUserName = "******";

                if (currentUserIdentity != null)
                {
                    currentUserName = currentUserIdentity.Name;
                }

                Guid newRootMapId = Guid.NewGuid();

                /// If it is the root map node, we want to assign it the pre-determined ID as we've been using this as the RootMapUid for everything;
                QueryMapNode sourceMapNode = originalNodes[SourceMap.NodeId];

                Node newRootMapNode = new Node();
                newRootMapNode.NodeUid = newRootMapId;
                newRootMapNode.DomainUid = DestinationDomain.DomainId;
                newRootMapNode.NodeTypeUid = sourceMapNode.NodeTypeUid;
                newRootMapNode.RootMapUid = newRootMapId;
                newRootMapNode.Created = sourceMapNode.Created;
                newRootMapNode.Modified = currentTime;
                newRootMapNode.CreatedBy = sourceMapNode.CreatedBy;
                newRootMapNode.ModifiedBy = currentUserName;

                newNodeIds[sourceMapNode.NodeUid] = newRootMapNode.NodeUid;

                dataContext.Nodes.InsertOnSubmit(newRootMapNode);

                /// Iterate through all nodes in memory and change their node IDs and root map IDs so that they won't clash with the map from where they were copied.
                foreach (QueryMapNode memoryNode in originalNodes.Values)
                {
                    if (memoryNode.NodeUid == SourceMap.NodeId)
                    {
                        continue;
                    }

                    count++;

                    if (count % 10 == 0)
                    {
                        callingCmdlet.WriteVerbose(count + " / " + totalNodes + " Nodes Completed");
                    }

                    Node node = new Node();
                    node.NodeUid = Guid.NewGuid();
                    node.DomainUid = DestinationDomain.DomainId;
                    node.NodeTypeUid = memoryNode.NodeTypeUid;
                    node.RootMapUid = newRootMapId;
                    node.Created = memoryNode.Created;
                    node.Modified = currentTime;
                    node.CreatedBy = memoryNode.CreatedBy;
                    node.ModifiedBy = currentUserName;

                    newNodeIds[memoryNode.NodeUid] = node.NodeUid;

                    dataContext.Nodes.InsertOnSubmit(node);
                }

                if (!newNodeIds.ContainsKey(SourceMap.NodeId))
                {
                    callingCmdlet.WriteWarning("Unexpected scenario. The source map NodeId can't be found in the list of copied nodes.");

                    return;
                }

                callingCmdlet.WriteVerbose("Committing nodes starting.");

                /// Commit node additions.
                dataContext.SubmitChanges();

                callingCmdlet.WriteVerbose("Committing nodes completed.");

                count = 0;

                callingCmdlet.WriteVerbose("Processing of relationships starting.");

                foreach (QueryMapRelationship memoryRelationship in originalRelationships)
                {
                    count++;

                    if (count % 10 == 0)
                    {
                        callingCmdlet.WriteVerbose(count + " / " + totalRelationships + " Relationships Completed");
                    }

                    Relationship relationship = new Relationship();
                    relationship.RelationshipUid = Guid.NewGuid();
                    relationship.DomainUid = DestinationDomain.DomainId;
                    relationship.RelationshipTypeUid = memoryRelationship.RelationshipTypeUid;
                    relationship.RootMapUid = newRootMapId;
                    relationship.Created = memoryRelationship.Created;
                    relationship.Modified = currentTime;
                    relationship.CreatedBy = memoryRelationship.CreatedBy;
                    relationship.ModifiedBy = currentUserName;

                    newRelationshipIds[memoryRelationship.RelationshipUid] = relationship.RelationshipUid;

                    dataContext.Relationships.InsertOnSubmit(relationship);
                }

                callingCmdlet.WriteVerbose("Committing relationships starting.");

                /// Commit relationship additions.
                dataContext.SubmitChanges();

                callingCmdlet.WriteVerbose("Committing relationships completed.");

                count = 0;

                callingCmdlet.WriteVerbose("Processing of descriptors starting.");

                foreach (QueryMapDescriptor memoryDescriptor in originalDescriptors)
                {
                    count++;

                    if (count % 10 == 0)
                    {
                        callingCmdlet.WriteVerbose(count + " / " + totalDescriptors + " Descriptors Completed");
                    }

                    if (newNodeIds.ContainsKey(memoryDescriptor.NodeUid.Value) && newRelationshipIds.ContainsKey(memoryDescriptor.RelationshipUid.Value))
                    {
                        Descriptor descriptor = new Descriptor();
                        descriptor.DescriptorUid = Guid.NewGuid();
                        descriptor.NodeUid = newNodeIds[memoryDescriptor.NodeUid.Value];
                        descriptor.RelationshipUid = newRelationshipIds[memoryDescriptor.RelationshipUid.Value];
                        descriptor.DescriptorTypeUid = memoryDescriptor.DescriptorTypeUid;

                        dataContext.Descriptors.InsertOnSubmit(descriptor);
                    }
                }

                callingCmdlet.WriteVerbose("Committing descriptors starting.");

                /// Commit descriptor additions.
                dataContext.SubmitChanges();

                callingCmdlet.WriteVerbose("Committing descriptors completed.");

                count = 0;

                callingCmdlet.WriteVerbose("Processing of metadata starting.");

                foreach (QueryMapMetadata memoryMetadatum in originalMetadata)
                {
                    count++;

                    if (count % 10 == 0)
                    {
                        callingCmdlet.WriteVerbose(count + " / " + totalMetadata + " Metadata Completed");
                    }

                    if (memoryMetadatum.NodeUid == null || newNodeIds.ContainsKey(memoryMetadatum.NodeUid.Value))
                    {
                        if (memoryMetadatum.RelationshipUid == null || newRelationshipIds.ContainsKey(memoryMetadatum.RelationshipUid.Value))
                        {
                            Metadata metadatum = new Metadata();
                            metadatum.MetadataId = Guid.NewGuid();

                            if (memoryMetadatum.NodeUid != null)
                            {
                                metadatum.NodeUid = newNodeIds[memoryMetadatum.NodeUid.Value];
                            }
                            else
                            {
                                metadatum.NodeUid = null;
                            }

                            if (memoryMetadatum.RelationshipUid != null)
                            {
                                metadatum.RelationshipUid = newRelationshipIds[memoryMetadatum.RelationshipUid.Value];
                            }
                            else
                            {
                                metadatum.RelationshipUid = null;
                            }

                            metadatum.DescriptorTypeUid = memoryMetadatum.DescriptorTypeUid;
                            metadatum.MetadataTypeUid = memoryMetadatum.MetadataTypeUid;
                            metadatum.MetadataName = memoryMetadatum.MetadataName;
                            metadatum.MetadataValue = memoryMetadatum.MetadataValue;
                            metadatum.DomainUid = DestinationDomain.DomainId;
                            metadatum.RootMapUid = newRootMapId;
                            metadatum.Created = memoryMetadatum.Created;
                            metadatum.Modified = currentTime;
                            metadatum.CreatedBy = memoryMetadatum.CreatedBy;
                            metadatum.ModifiedBy = currentUserName;

                            dataContext.Metadatas.InsertOnSubmit(metadatum);
                        }
                    }
                }

                callingCmdlet.WriteVerbose("Committing metadata starting.");

                /// Commit metadata additions.
                dataContext.SubmitChanges();

                callingCmdlet.WriteVerbose("Committing metadata completed.");

                callingCmdlet.WriteVerbose("Connecting map to domain.");

                Relationship domainNodeMapRelationship = new Relationship();
                domainNodeMapRelationship.RelationshipUid = Guid.NewGuid();
                domainNodeMapRelationship.DomainUid = DestinationDomain.DomainId;
                domainNodeMapRelationship.RelationshipTypeUid = new Guid("4AFF46D7-87BE-48DD-B703-A93E38EF8FFB");
                domainNodeMapRelationship.RootMapUid = newRootMapId;
                domainNodeMapRelationship.Created = currentTime;
                domainNodeMapRelationship.Modified = currentTime;
                domainNodeMapRelationship.CreatedBy = currentUserName;
                domainNodeMapRelationship.ModifiedBy = currentUserName;

                Descriptor domainNodeMapFromDescriptor = new Descriptor();
                domainNodeMapFromDescriptor.DescriptorUid = Guid.NewGuid();
                domainNodeMapFromDescriptor.DescriptorTypeUid = new Guid("96DA1782-058C-4F9B-BB1A-31B048F8C75A");
                domainNodeMapFromDescriptor.NodeUid = newNodeIds[SourceMap.NodeId];
                domainNodeMapFromDescriptor.RelationshipUid = domainNodeMapRelationship.RelationshipUid;

                Descriptor domainNodeMapToDescriptor = new Descriptor();
                domainNodeMapToDescriptor.DescriptorUid = Guid.NewGuid();
                domainNodeMapToDescriptor.DescriptorTypeUid = new Guid("07C91D35-4DAC-431B-966B-64C924B8CDAB");
                domainNodeMapToDescriptor.NodeUid = DestinationDomain.NodeId;
                domainNodeMapToDescriptor.RelationshipUid = domainNodeMapRelationship.RelationshipUid;

                dataContext.Relationships.InsertOnSubmit(domainNodeMapRelationship);
                dataContext.Descriptors.InsertOnSubmit(domainNodeMapFromDescriptor);
                dataContext.Descriptors.InsertOnSubmit(domainNodeMapToDescriptor);

                dataContext.SubmitChanges();

                callingCmdlet.WriteVerbose("Completed connecting map to domain.");

                callingCmdlet.WriteVerbose("Copy completed.");
            }
        }