Beispiel #1
0
 private static bool AliasDefinitionsTypeValidationCallback(string key, object obj, PSCmdlet cmdlet, string path)
 {
     Hashtable[] hashtableArray = DISCPowerShellConfiguration.TryGetHashtableArray(obj);
     if (hashtableArray == null)
     {
         cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeHashtableArray, key, path));
         return false;
     }
     foreach (Hashtable hashtable in hashtableArray)
     {
         if (!hashtable.ContainsKey(AliasNameToken))
         {
             cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustContainKey, new object[] { key, AliasNameToken, path }));
             return false;
         }
         if (!hashtable.ContainsKey(AliasValueToken))
         {
             cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustContainKey, new object[] { key, AliasValueToken, path }));
             return false;
         }
         foreach (string str in hashtable.Keys)
         {
             if ((!string.Equals(str, AliasNameToken, StringComparison.OrdinalIgnoreCase) && !string.Equals(str, AliasValueToken, StringComparison.OrdinalIgnoreCase)) && (!string.Equals(str, AliasDescriptionToken, StringComparison.OrdinalIgnoreCase) && !string.Equals(str, AliasOptionsToken, StringComparison.OrdinalIgnoreCase)))
             {
                 cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCTypeContainsInvalidKey, new object[] { str, key, path }));
                 return false;
             }
         }
     }
     return true;
 }
        /// <summary>
        /// Run script to restart the WinRM service. The script will write
        /// output and error into the cmdlets streams.
        /// </summary>
        /// <param name="cmdlet">
        /// Cmdlet's context in which the restart-service script is run.
        /// </param>
        /// <param name="isErrorReported">
        /// if true, then this method is a no-op.
        /// </param>
        /// <param name="force">
        /// if true, then the user will not be prompted.
        /// </param>
        /// <param name="noServiceRestart">
        /// if true, we dont attempt to restart winrm service ie. this will be a no-op. 
        /// </param>
        internal static void RestartWinRMService(PSCmdlet cmdlet, bool isErrorReported, bool force, bool noServiceRestart)
        {
            // restart the service only if there is no error running WSMan config command
            if (!(isErrorReported || noServiceRestart))
            {
                // restart-service winrm to make the changes effective.
                string restartServiceAction = RemotingErrorIdStrings.RestartWSManServiceAction;
                string restartServiceTarget = StringUtil.Format(RemotingErrorIdStrings.RestartWSManServiceTarget, "WinRM");

                if (force || cmdlet.ShouldProcess(restartServiceTarget, restartServiceAction))
                {
                    cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.RestartWSManServiceMessageV));

                    ScriptBlock restartServiceScript = cmdlet.InvokeCommand.NewScriptBlock(restartWSManFormat);
                    var emptyArray = Utils.EmptyArray<object>();
                    restartServiceScript.InvokeUsingCmdlet(
                        contextCmdlet: cmdlet,
                        useLocalScope: true,
                        errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe,
                        dollarUnder: AutomationNull.Value,
                        input: emptyArray,
                        scriptThis: AutomationNull.Value,
                        args: emptyArray);
                }
            }
        }
        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");
                    }
                }
            }
        }
        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));
            }
        }
        public Dictionary<string, List<string>> CheckRuleExtension(string[] path, PSCmdlet cmdlet)
        {
            Dictionary<string, List<string>> results = new Dictionary<string, List<string>>();

            List<string> invalidPaths = new List<string>();
            List<string> validDllPaths = new List<string>();
            List<string> validModPaths = new List<string>();

            // Gets valid module names
            foreach (string childPath in path)
            {
                try
                {
                    cmdlet.WriteVerbose(string.Format(CultureInfo.CurrentCulture, Strings.CheckModuleName, childPath));

                    string resolvedPath = string.Empty;

                    // Users may provide a valid module path or name,
                    // We have to identify the childPath is really a directory or just a module name.
                    // You can also consider following two commands.
                    //   Get-ScriptAnalyzerRule -RuleExtension "ContosoAnalyzerRules"
                    //   Get-ScriptAnalyzerRule -RuleExtension "%USERPROFILE%\WindowsPowerShell\Modules\ContosoAnalyzerRules"
                    if (Path.GetDirectoryName(childPath) == string.Empty)
                    {
                        resolvedPath = childPath;
                    }
                    else
                    {
                        resolvedPath = cmdlet.SessionState.Path
                            .GetResolvedPSPathFromPSPath(childPath).First().ToString();
                    }

                    using (System.Management.Automation.PowerShell posh =
                           System.Management.Automation.PowerShell.Create())
                    {
                        string script = string.Format(CultureInfo.CurrentCulture, "Get-Module -Name '{0}' -ListAvailable", resolvedPath);
                        PSModuleInfo moduleInfo = posh.AddScript(script).Invoke<PSModuleInfo>().First();

                        // Adds original path, otherwise path.Except<string>(validModPaths) will fail.
                        // It's possible that user can provide something like this:
                        // "..\..\..\ScriptAnalyzer.UnitTest\modules\CommunityAnalyzerRules\CommunityAnalyzerRules.psd1"
                        if (moduleInfo.ExportedFunctions.Count > 0) validModPaths.Add(childPath);
                    }
                }
                catch
                {
                    // User may provide an invalid module name, like c:\temp.
                    // It's a invalid name for a Windows PowerShell module,
                    // But we need test it further since we allow user to provide a folder to extend rules.
                    // You can also consider following two commands.
                    //   Get-ScriptAnalyzerRule -RuleExtension "ContosoAnalyzerRules", "C:\Temp\ExtendScriptAnalyzerRules.dll"
                    //   Get-ScriptAnalyzerRule -RuleExtension "ContosoAnalyzerRules", "C:\Temp\"
                    continue;
                }
            }

            // Gets valid dll paths
            foreach (string childPath in path.Except<string>(validModPaths))
            {
                try
                {
                    string resolvedPath = cmdlet.SessionState.Path
                        .GetResolvedPSPathFromPSPath(childPath).First().ToString();

                    cmdlet.WriteDebug(string.Format(CultureInfo.CurrentCulture, Strings.CheckAssemblyFile, resolvedPath));

                    if (String.Equals(Path.GetExtension(resolvedPath),".dll", StringComparison.OrdinalIgnoreCase))
                    {
                        if (!File.Exists(resolvedPath))
                        {
                            invalidPaths.Add(resolvedPath);
                            continue;
                        }
                    }
                    else
                    {
                        if (!Directory.Exists(resolvedPath))
                        {
                            invalidPaths.Add(resolvedPath);
                            continue;
                        }
                    }

                    validDllPaths.Add(resolvedPath);
                }
                catch
                {
                    invalidPaths.Add(childPath);
                }
            }

            // Resloves relative paths.
            try
            {
                for (int i = 0; i < validModPaths.Count; i++)
                {
                    validModPaths[i] = cmdlet.SessionState.Path
                        .GetResolvedPSPathFromPSPath(validModPaths[i]).First().ToString();
                }
                for (int i = 0; i < validDllPaths.Count; i++)
                {
                    validDllPaths[i] = cmdlet.SessionState.Path
                        .GetResolvedPSPathFromPSPath(validDllPaths[i]).First().ToString();
                }
            }
            catch
            {
                // If GetResolvedPSPathFromPSPath failed. We can safely ignore the exception.
                // Because GetResolvedPSPathFromPSPath always fails when trying to resolve a module name.
            }

            // Returns valid rule extensions
            results.Add("InvalidPaths", invalidPaths);
            results.Add("ValidModPaths", validModPaths);
            results.Add("ValidDllPaths", validDllPaths);

            return results;
        }
 internal static void RestartWinRMService(PSCmdlet cmdlet, bool isErrorReported, bool force, bool noServiceRestart)
 {
     if (!isErrorReported && !noServiceRestart)
     {
         string restartWSManServiceAction = RemotingErrorIdStrings.RestartWSManServiceAction;
         string target = StringUtil.Format(RemotingErrorIdStrings.RestartWSManServiceTarget, "WinRM");
         if (force || cmdlet.ShouldProcess(target, restartWSManServiceAction))
         {
             cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.RestartWSManServiceMessageV, new object[0]));
             cmdlet.InvokeCommand.NewScriptBlock("restart-service winrm -force -confirm:$false").InvokeUsingCmdlet(cmdlet, true, ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe, AutomationNull.Value, new object[0], AutomationNull.Value, new object[0]);
         }
     }
 }
Beispiel #7
0
        /// <summary>
        /// Generate the Catalog file for Input Catalog Definition File
        /// </summary>
        ///
        /// <param name="cdfFilePath"> Path to the Input .cdf file </param>
        internal static void GenerateCatalogFile(string cdfFilePath)
        {
            string pwszFilePath = cdfFilePath;

            NativeMethods.CryptCATCDFOpenCallBack catOpenCallBack = new NativeMethods.CryptCATCDFOpenCallBack(ParseErrorCallback);

            // Open CDF File
            IntPtr resultCDF = NativeMethods.CryptCATCDFOpen(pwszFilePath, catOpenCallBack);

            // navigate CDF header and files sections
            if (resultCDF != IntPtr.Zero)
            {
                // First navigate all catalog level attributes entries first, they represent zero size files
                IntPtr catalogAttr = IntPtr.Zero;
                do
                {
                    catalogAttr = NativeMethods.CryptCATCDFEnumCatAttributes(resultCDF, catalogAttr, catOpenCallBack);

                    if (catalogAttr != IntPtr.Zero)
                    {
                        string filePath = ProcessFilePathAttributeInCatalog(catalogAttr);
                        _cmdlet.WriteVerbose(StringUtil.Format(CatalogStrings.AddFileToCatalog, filePath, filePath));
                    }
                } while (catalogAttr != IntPtr.Zero);

                // navigate all the files hash entries in the .cdf file
                IntPtr memberInfo = IntPtr.Zero;
                try
                {
                    IntPtr memberFile = IntPtr.Zero;
                    NativeMethods.CryptCATCDFEnumMembersByCDFTagExErrorCallBack memberCallBack = new NativeMethods.CryptCATCDFEnumMembersByCDFTagExErrorCallBack(ParseErrorCallback);
                    string fileName = string.Empty;
                    do
                    {
                        memberFile = NativeMethods.CryptCATCDFEnumMembersByCDFTagEx(resultCDF, memberFile, memberCallBack, ref memberInfo, true, IntPtr.Zero);
                        fileName   = Marshal.PtrToStringUni(memberFile);

                        if (!String.IsNullOrEmpty(fileName))
                        {
                            IntPtr memberAttr       = IntPtr.Zero;
                            string fileRelativePath = String.Empty;
                            do
                            {
                                memberAttr = NativeMethods.CryptCATCDFEnumAttributesWithCDFTag(resultCDF, memberFile, memberInfo, memberAttr, memberCallBack);

                                if (memberAttr != IntPtr.Zero)
                                {
                                    fileRelativePath = ProcessFilePathAttributeInCatalog(memberAttr);
                                    if (!String.IsNullOrEmpty(fileRelativePath))
                                    {
                                        // Found the attribute we are looking for
                                        // Filename we read from the above API has <Hash> appended to its name as per CDF file tags convention
                                        // Truncating that Information from the string.
                                        string itemName = fileName.Substring(6);
                                        _cmdlet.WriteVerbose(StringUtil.Format(CatalogStrings.AddFileToCatalog, itemName, fileRelativePath));
                                        break;
                                    }
                                }
                            } while (memberAttr != IntPtr.Zero);
                        }
                    } while (fileName != null);
                }
                finally
                {
                    NativeMethods.CryptCATCDFClose(resultCDF);
                }
            }
            else
            {
                // If we are not able to open CDF file we can not continue generating catalog
                ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(CatalogStrings.UnableToOpenCatalogDefinitionFile), "UnableToOpenCatalogDefinitionFile", ErrorCategory.InvalidOperation, null);
                _cmdlet.ThrowTerminatingError(errorRecord);
            }
        }
Beispiel #8
0
 internal static void ExportModuleMembers(PSCmdlet cmdlet, SessionStateInternal sessionState, List <WildcardPattern> functionPatterns, List <WildcardPattern> cmdletPatterns, List <WildcardPattern> aliasPatterns, List <WildcardPattern> variablePatterns, List <string> doNotExportCmdlets)
 {
     sessionState.UseExportList = true;
     if (functionPatterns != null)
     {
         foreach (KeyValuePair <string, FunctionInfo> pair in sessionState.ModuleScope.FunctionTable)
         {
             if (((pair.Value.Options & ScopedItemOptions.AllScope) == ScopedItemOptions.None) && SessionStateUtilities.MatchesAnyWildcardPattern(pair.Key, functionPatterns, false))
             {
                 string str;
                 if (pair.Value.CommandType == CommandTypes.Workflow)
                 {
                     str = StringUtil.Format(Modules.ExportingWorkflow, pair.Key);
                     sessionState.ExportedWorkflows.Add((WorkflowInfo)pair.Value);
                 }
                 else
                 {
                     str = StringUtil.Format(Modules.ExportingFunction, pair.Key);
                     sessionState.ExportedFunctions.Add(pair.Value);
                 }
                 cmdlet.WriteVerbose(str);
             }
         }
         SortAndRemoveDuplicates <FunctionInfo>(sessionState.ExportedFunctions, ci => ci.Name);
         SortAndRemoveDuplicates <WorkflowInfo>(sessionState.ExportedWorkflows, ci => ci.Name);
     }
     if (cmdletPatterns != null)
     {
         IDictionary <string, List <CmdletInfo> > cmdletTable = sessionState.ModuleScope.CmdletTable;
         if (sessionState.Module.CompiledExports.Count > 0)
         {
             CmdletInfo[] infoArray = sessionState.Module.CompiledExports.ToArray();
             sessionState.Module.CompiledExports.Clear();
             CmdletInfo[] infoArray2 = infoArray;
             for (int i = 0; i < infoArray2.Length; i++)
             {
                 Predicate <string> match   = null;
                 CmdletInfo         element = infoArray2[i];
                 if (doNotExportCmdlets != null)
                 {
                     if (match == null)
                     {
                         match = cmdletName => string.Equals(element.FullName, cmdletName, StringComparison.OrdinalIgnoreCase);
                     }
                     if (doNotExportCmdlets.Exists(match))
                     {
                         continue;
                     }
                 }
                 if (SessionStateUtilities.MatchesAnyWildcardPattern(element.Name, cmdletPatterns, false))
                 {
                     string text = StringUtil.Format(Modules.ExportingCmdlet, element.Name);
                     cmdlet.WriteVerbose(text);
                     CmdletInfo item = new CmdletInfo(element.Name, element.ImplementingType, element.HelpFile, null, element.Context);
                     item.SetModule(sessionState.Module);
                     sessionState.Module.CompiledExports.Add(item);
                 }
             }
         }
         foreach (KeyValuePair <string, List <CmdletInfo> > pair2 in cmdletTable)
         {
             CmdletInfo cmdletToImport = pair2.Value[0];
             if (((doNotExportCmdlets == null) || !doNotExportCmdlets.Exists(cmdletName => string.Equals(cmdletToImport.FullName, cmdletName, StringComparison.OrdinalIgnoreCase))) && SessionStateUtilities.MatchesAnyWildcardPattern(pair2.Key, cmdletPatterns, false))
             {
                 string str3 = StringUtil.Format(Modules.ExportingCmdlet, pair2.Key);
                 cmdlet.WriteVerbose(str3);
                 CmdletInfo info2 = new CmdletInfo(cmdletToImport.Name, cmdletToImport.ImplementingType, cmdletToImport.HelpFile, null, cmdletToImport.Context);
                 info2.SetModule(sessionState.Module);
                 sessionState.Module.CompiledExports.Add(info2);
             }
         }
         SortAndRemoveDuplicates <CmdletInfo>(sessionState.Module.CompiledExports, ci => ci.Name);
     }
     if (variablePatterns != null)
     {
         foreach (KeyValuePair <string, PSVariable> pair3 in sessionState.ModuleScope.Variables)
         {
             if ((!pair3.Value.IsAllScope && (Array.IndexOf <string>(PSModuleInfo._builtinVariables, pair3.Key) == -1)) && SessionStateUtilities.MatchesAnyWildcardPattern(pair3.Key, variablePatterns, false))
             {
                 string str4 = StringUtil.Format(Modules.ExportingVariable, pair3.Key);
                 cmdlet.WriteVerbose(str4);
                 sessionState.ExportedVariables.Add(pair3.Value);
             }
         }
         SortAndRemoveDuplicates <PSVariable>(sessionState.ExportedVariables, v => v.Name);
     }
     if (aliasPatterns != null)
     {
         foreach (AliasInfo info3 in sessionState.ModuleScope.AliasTable)
         {
             if (((info3.Options & ScopedItemOptions.AllScope) == ScopedItemOptions.None) && SessionStateUtilities.MatchesAnyWildcardPattern(info3.Name, aliasPatterns, false))
             {
                 string str5 = StringUtil.Format(Modules.ExportingAlias, info3.Name);
                 cmdlet.WriteVerbose(str5);
                 sessionState.ExportedAliases.Add(info3);
             }
         }
         SortAndRemoveDuplicates <AliasInfo>(sessionState.ExportedAliases, ci => ci.Name);
     }
 }
Beispiel #9
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.");
            }
        }
Beispiel #10
0
 internal static bool VerifyConfigTable(Hashtable table, PSCmdlet cmdlet, string path)
 {
     bool flag = false;
     foreach (DictionaryEntry entry in table)
     {
         if (!ConfigFileContants.IsValidKey(entry, cmdlet, path))
         {
             return false;
         }
         if (entry.Key.ToString().Equals(ConfigFileContants.SchemaVersion, StringComparison.OrdinalIgnoreCase))
         {
             flag = true;
         }
     }
     if (!flag)
     {
         cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCMissingSchemaVersion, path));
         return false;
     }
     try
     {
         ValidateAbsolutePaths(cmdlet.SessionState, table, path);
         ValidateExtensions(table, path);
     }
     catch (InvalidOperationException exception)
     {
         cmdlet.WriteVerbose(exception.Message);
         return false;
     }
     return true;
 }
Beispiel #11
0
 private static bool ExecutionPolicyValidationCallback(string key, object obj, PSCmdlet cmdlet, string path)
 {
     string str = obj as string;
     if (!string.IsNullOrEmpty(str))
     {
         try
         {
             Enum.Parse(DISCUtils.ExecutionPolicyType, str, true);
             return true;
         }
         catch (ArgumentException)
         {
         }
     }
     cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeValidEnum, new object[] { key, DISCUtils.ExecutionPolicyType.FullName, LanguagePrimitives.EnumSingleTypeConverter.EnumValues(DISCUtils.ExecutionPolicyType), path }));
     return false;
 }
Beispiel #12
0
 private static bool StringTypeValidationCallback(string key, object obj, PSCmdlet cmdlet, string path)
 {
     if (obj is string)
     {
         return true;
     }
     cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeString, key, path));
     return false;
 }
Beispiel #13
0
 private static bool StringOrHashtableArrayTypeValidationCallback(string key, object obj, PSCmdlet cmdlet, string path)
 {
     if (DISCPowerShellConfiguration.TryGetObjectsOfType<object>(obj, new Type[] { typeof(string), typeof(Hashtable) }) == null)
     {
         cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeStringOrHashtableArrayInFile, key, path));
         return false;
     }
     return true;
 }
Beispiel #14
0
 private static bool StringArrayTypeValidationCallback(string key, object obj, PSCmdlet cmdlet, string path)
 {
     if (DISCPowerShellConfiguration.TryGetStringArray(obj) == null)
     {
         cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeStringArray, key, path));
         return false;
     }
     return true;
 }
Beispiel #15
0
 internal static bool IsValidKey(DictionaryEntry de, PSCmdlet cmdlet, string path)
 {
     bool flag = false;
     foreach (ConfigTypeEntry entry in ConfigFileKeys)
     {
         if (string.Equals(entry.Key, de.Key.ToString(), StringComparison.OrdinalIgnoreCase))
         {
             flag = true;
             if (entry.ValidationCallback(de.Key.ToString(), de.Value, cmdlet, path))
             {
                 return true;
             }
         }
     }
     if (!flag)
     {
         cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCInvalidKey, de.Key.ToString(), path));
     }
     return false;
 }
Beispiel #16
0
 private static bool ISSValidationCallback(string key, object obj, PSCmdlet cmdlet, string path)
 {
     string str = obj as string;
     if (!string.IsNullOrEmpty(str))
     {
         try
         {
             Enum.Parse(typeof(System.Management.Automation.Remoting.SessionType), str, true);
             return true;
         }
         catch (ArgumentException)
         {
         }
     }
     cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeValidEnum, new object[] { key, typeof(System.Management.Automation.Remoting.SessionType).FullName, LanguagePrimitives.EnumSingleTypeConverter.EnumValues(typeof(System.Management.Automation.Remoting.SessionType)), path }));
     return false;
 }