/// <summary> /// Replaces any existing metadata in this object with the metadata specified. /// /// Note that this method should NOT be called after a MergedCommandParameterMetadata /// instance is made read only by calling MakeReadOnly(). This is because MakeReadOnly() /// will turn 'bindableParameters', 'aliasedParameters' and 'parameterSetMap' into /// ReadOnlyDictionary and ReadOnlyCollection. /// </summary> /// /// <param name="metadata"> /// The metadata to replace in this object. /// </param> /// /// <returns> /// A list of the merged parameter metadata that was added. /// </returns> internal List<MergedCompiledCommandParameter> ReplaceMetadata(MergedCommandParameterMetadata metadata) { var result = new List<MergedCompiledCommandParameter>(); // Replace bindable parameters _bindableParameters.Clear(); foreach (KeyValuePair<string, MergedCompiledCommandParameter> entry in metadata.BindableParameters) { _bindableParameters.Add(entry.Key, entry.Value); result.Add(entry.Value); } _aliasedParameters.Clear(); foreach (KeyValuePair<string, MergedCompiledCommandParameter> entry in metadata.AliasedParameters) { _aliasedParameters.Add(entry.Key, entry.Value); } // Replace additional meta info _defaultParameterSetName = metadata._defaultParameterSetName; _nextAvailableParameterSetIndex = metadata._nextAvailableParameterSetIndex; _parameterSetMap.Clear(); var parameterSetMapInList = (List<string>)_parameterSetMap; parameterSetMapInList.AddRange(metadata._parameterSetMap); Diagnostics.Assert(ParameterSetCount == _nextAvailableParameterSetIndex, "After replacement with the metadata of the new parameters, ParameterSetCount should be equal to nextAvailableParameterSetIndex"); return result; } // ReplaceMetadata
internal CommandParameterSetInfo(string name, bool isDefaultParameterSet, int parameterSetFlag, MergedCommandParameterMetadata parameterMetadata) { this.IsDefault = true; this.Name = string.Empty; if (string.IsNullOrEmpty(name)) { throw PSTraceSource.NewArgumentException("name"); } if (parameterMetadata == null) { throw PSTraceSource.NewArgumentNullException("parameterMetadata"); } this.Name = name; this.IsDefault = isDefaultParameterSet; this.Initialize(parameterMetadata, parameterSetFlag); }
internal static Collection<CommandParameterSetInfo> GetParameterMetadata(CommandMetadata metadata, MergedCommandParameterMetadata parameterMetadata) { Collection<CommandParameterSetInfo> result = new Collection<CommandParameterSetInfo>(); if (parameterMetadata != null) { if (parameterMetadata.ParameterSetCount == 0) { const string parameterSetName = ParameterAttribute.AllParameterSets; result.Add( new CommandParameterSetInfo( parameterSetName, false, uint.MaxValue, parameterMetadata)); } else { int parameterSetCount = parameterMetadata.ParameterSetCount; for (int index = 0; index < parameterSetCount; ++index) { uint currentFlagPosition = (uint)0x1 << index; // Get the parameter set name string parameterSetName = parameterMetadata.GetParameterSetName(currentFlagPosition); // Is the parameter set the default? bool isDefaultParameterSet = (currentFlagPosition & metadata.DefaultParameterSetFlag) != 0; result.Add( new CommandParameterSetInfo( parameterSetName, isDefaultParameterSet, currentFlagPosition, parameterMetadata)); } } } return result; } // GetParameterMetadata
internal CommandMetadata(string commandName, Type cmdletType, ExecutionContext context) { this._commandName = string.Empty; this._defaultParameterSetName = "__AllParameterSets"; this._positionalBinding = true; this._helpUri = string.Empty; this._remotingCapability = System.Management.Automation.RemotingCapability.PowerShell; this._confirmImpact = System.Management.Automation.ConfirmImpact.Medium; this._otherAttributes = new Collection<Attribute>(); if (string.IsNullOrEmpty(commandName)) { throw PSTraceSource.NewArgumentException("commandName"); } this._commandName = commandName; this.CommandType = cmdletType; if (cmdletType != null) { InternalParameterMetadata parameterMetadata = InternalParameterMetadata.Get(cmdletType, context, false); this.ConstructCmdletMetadataUsingReflection(); this.staticCommandParameterMetadata = this.MergeParameterMetadata(context, parameterMetadata, true); this._defaultParameterSetFlag = this.staticCommandParameterMetadata.GenerateParameterSetMappingFromMetadata(this._defaultParameterSetName); this.staticCommandParameterMetadata.MakeReadOnly(); } }
/// <summary> /// /// </summary> /// <param name="cmdParameterMetadata"></param> /// <returns></returns> internal static Dictionary<string, ParameterMetadata> GetParameterMetadata(MergedCommandParameterMetadata cmdParameterMetadata) { Dbg.Assert(null != cmdParameterMetadata, "cmdParameterMetadata cannot be null"); Dictionary<string, ParameterMetadata> result = new Dictionary<string, ParameterMetadata>(StringComparer.OrdinalIgnoreCase); foreach (var keyValuePair in cmdParameterMetadata.BindableParameters) { var key = keyValuePair.Key; var mergedCompiledPMD = keyValuePair.Value; ParameterMetadata parameterMetaData = new ParameterMetadata(mergedCompiledPMD.Parameter); result.Add(key, parameterMetaData); } return result; }
private void BuildSyntaxForParameterSet(XmlElement command, XmlElement syntax, MergedCommandParameterMetadata parameterMetadata, int i) { XmlElement syntaxItem = _doc.CreateElement("command:syntaxItem", commandURI); XmlElement syntaxItemName = _doc.CreateElement("maml:name", mamlURI); XmlText syntaxItemName_text = _doc.CreateTextNode(_commandName); syntaxItem.AppendChild(syntaxItemName).AppendChild(syntaxItemName_text); Collection<MergedCompiledCommandParameter> compiledParameters = parameterMetadata.GetParametersInParameterSet(1u << i); foreach (MergedCompiledCommandParameter mergedParameter in compiledParameters) { if (mergedParameter.BinderAssociation == ParameterBinderAssociation.CommonParameters) { continue; } CompiledCommandParameter parameter = mergedParameter.Parameter; ParameterSetSpecificMetadata parameterSetData = parameter.GetParameterSetData(1u << i); string description = GetParameterDescription(parameter.Name); bool supportsWildcards = parameter.CompiledAttributes.Any(attribute => attribute is SupportsWildcardsAttribute); XmlElement parameterElement = BuildXmlForParameter(parameter.Name, parameterSetData.IsMandatory, parameterSetData.ValueFromPipeline, parameterSetData.ValueFromPipelineByPropertyName, parameterSetData.IsPositional ? (1 + parameterSetData.Position).ToString(CultureInfo.InvariantCulture) : "named", parameter.Type, description, supportsWildcards, defaultValue: "", forSyntax: true); syntaxItem.AppendChild(parameterElement); } command.AppendChild(syntax).AppendChild(syntaxItem); }
internal static int ResolveParameterSetAmbiguityBasedOnMandatoryParameters( Dictionary<String, MergedCompiledCommandParameter> boundParameters, ICollection<MergedCompiledCommandParameter> unboundParameters, MergedCommandParameterMetadata bindableParameters, ref uint _currentParameterSetFlag, Cmdlet command ) { uint remainingParameterSetsWithNoMandatoryUnboundParameters = _currentParameterSetFlag; IEnumerable<ParameterSetSpecificMetadata> allParameterSetMetadatas = boundParameters.Values .Concat(unboundParameters) .SelectMany(p => p.Parameter.ParameterSetData.Values); uint allParameterSetFlags = 0; foreach (ParameterSetSpecificMetadata parameterSetMetadata in allParameterSetMetadatas) { allParameterSetFlags |= parameterSetMetadata.ParameterSetFlag; } remainingParameterSetsWithNoMandatoryUnboundParameters &= allParameterSetFlags; Diagnostics.Assert( ValidParameterSetCount(remainingParameterSetsWithNoMandatoryUnboundParameters) > 1, "This method should only be called when there is an ambiguity wrt parameter sets"); IEnumerable<ParameterSetSpecificMetadata> parameterSetMetadatasForUnboundMandatoryParameters = unboundParameters .SelectMany(p => p.Parameter.ParameterSetData.Values) .Where(p => p.IsMandatory); foreach (ParameterSetSpecificMetadata parameterSetMetadata in parameterSetMetadatasForUnboundMandatoryParameters) { remainingParameterSetsWithNoMandatoryUnboundParameters &= (~parameterSetMetadata.ParameterSetFlag); } int finalParameterSetCount = ValidParameterSetCount(remainingParameterSetsWithNoMandatoryUnboundParameters); if (finalParameterSetCount == 1) { _currentParameterSetFlag = remainingParameterSetsWithNoMandatoryUnboundParameters; if (command != null) { string currentParameterSetName = bindableParameters.GetParameterSetName(_currentParameterSetFlag); command.SetParameterSetName(currentParameterSetName); } return finalParameterSetCount; } return -1; }
} // ProcessCmdletAttribute /// <summary> /// Merges parameter metadata from different sources: those that are coming from Type, /// CommonParameters, should process etc. /// </summary> /// <param name="context"></param> /// <param name="parameterMetadata"></param> /// <param name="shouldGenerateCommonParameters"> /// true if metadata info about Verbose,Debug etc needs to be generated. /// false otherwise. /// </param> private MergedCommandParameterMetadata MergeParameterMetadata(ExecutionContext context, InternalParameterMetadata parameterMetadata, bool shouldGenerateCommonParameters) { // Create an instance of the static metadata class MergedCommandParameterMetadata staticCommandParameterMetadata = new MergedCommandParameterMetadata(); // First add the metadata for the formal cmdlet parameters staticCommandParameterMetadata.AddMetadataForBinder( parameterMetadata, ParameterBinderAssociation.DeclaredFormalParameters); // Now add the common parameters metadata if (shouldGenerateCommonParameters) { InternalParameterMetadata commonParametersMetadata = InternalParameterMetadata.Get(typeof(CommonParameters), context, false); staticCommandParameterMetadata.AddMetadataForBinder( commonParametersMetadata, ParameterBinderAssociation.CommonParameters); // If the command supports ShouldProcess, add the metadata for // those parameters if (this.SupportsShouldProcess) { InternalParameterMetadata shouldProcessParametersMetadata = InternalParameterMetadata.Get(typeof(ShouldProcessParameters), context, false); staticCommandParameterMetadata.AddMetadataForBinder( shouldProcessParametersMetadata, ParameterBinderAssociation.ShouldProcessParameters); } // If the command supports paging, add the metadata for // those parameters if (this.SupportsPaging) { InternalParameterMetadata pagingParametersMetadata = InternalParameterMetadata.Get(typeof(PagingParameters), context, false); staticCommandParameterMetadata.AddMetadataForBinder( pagingParametersMetadata, ParameterBinderAssociation.PagingParameters); } // If the command supports transactions, add the metadata for // those parameters if (this.SupportsTransactions) { InternalParameterMetadata transactionParametersMetadata = InternalParameterMetadata.Get(typeof(TransactionParameters), context, false); staticCommandParameterMetadata.AddMetadataForBinder( transactionParametersMetadata, ParameterBinderAssociation.TransactionParameters); } } return staticCommandParameterMetadata; } // MergeParameterMetadata
private bool PrepareCommandElements(ExecutionContext context) { int num = 0; bool dotSource = this._commandAst.InvocationOperator == TokenKind.Dot; CommandProcessorBase base2 = null; string resolvedCommandName = null; bool flag2 = false; try { base2 = this.PrepareFromAst(context, out resolvedCommandName) ?? context.CreateCommand(resolvedCommandName, dotSource); } catch (RuntimeException exception) { CommandProcessorBase.CheckForSevereException(exception); if ((this._commandAst.IsInWorkflow() && (resolvedCommandName != null)) && CompletionCompleters.PseudoWorkflowCommands.Contains<string>(resolvedCommandName, StringComparer.OrdinalIgnoreCase)) { flag2 = true; } else { return false; } } CommandProcessor commandProcessor = base2 as CommandProcessor; ScriptCommandProcessorBase base3 = base2 as ScriptCommandProcessorBase; bool flag3 = (commandProcessor != null) && commandProcessor.CommandInfo.ImplementsDynamicParameters; List<object> list = flag3 ? new List<object>(this._commandElements.Count) : null; if (((commandProcessor != null) || (base3 != null)) || flag2) { num++; while (num < this._commandElements.Count) { CommandParameterAst parameterAst = this._commandElements[num] as CommandParameterAst; if (parameterAst != null) { if (list != null) { list.Add(parameterAst.Extent.Text); } AstPair item = (parameterAst.Argument != null) ? new AstPair(parameterAst, parameterAst.Argument) : new AstPair(parameterAst); this._arguments.Add(item); } else { StringConstantExpressionAst ast2 = this._commandElements[num] as StringConstantExpressionAst; if ((ast2 == null) || !ast2.Value.Trim().Equals("-", StringComparison.OrdinalIgnoreCase)) { ExpressionAst argumentAst = this._commandElements[num] as ExpressionAst; if (argumentAst != null) { if (list != null) { list.Add(argumentAst.Extent.Text); } this._arguments.Add(new AstPair(null, argumentAst)); } } } num++; } } if (commandProcessor != null) { this._function = false; if (flag3) { ParameterBinderController.AddArgumentsToCommandProcessor(commandProcessor, list.ToArray()); bool flag4 = false; bool flag5 = false; do { CommandProcessorBase currentCommandProcessor = context.CurrentCommandProcessor; try { context.CurrentCommandProcessor = commandProcessor; commandProcessor.SetCurrentScopeToExecutionScope(); if (!flag4) { commandProcessor.CmdletParameterBinderController.BindCommandLineParametersNoValidation(commandProcessor.arguments); } else { flag5 = true; commandProcessor.CmdletParameterBinderController.ClearUnboundArguments(); commandProcessor.CmdletParameterBinderController.BindCommandLineParametersNoValidation(new Collection<CommandParameterInternal>()); } } catch (ParameterBindingException exception2) { if ((exception2.ErrorId == "MissingArgument") || (exception2.ErrorId == "AmbiguousParameter")) { flag4 = true; } } catch (Exception exception3) { CommandProcessorBase.CheckForSevereException(exception3); } finally { context.CurrentCommandProcessor = currentCommandProcessor; commandProcessor.RestorePreviousScope(); } } while (flag4 && !flag5); } this._commandInfo = commandProcessor.CommandInfo; this._commandName = commandProcessor.CommandInfo.Name; this._bindableParameters = commandProcessor.CmdletParameterBinderController.BindableParameters; this._defaultParameterSetFlag = commandProcessor.CommandInfo.CommandMetadata.DefaultParameterSetFlag; } else if (base3 != null) { this._function = true; this._commandInfo = base3.CommandInfo; this._commandName = base3.CommandInfo.Name; this._bindableParameters = base3.ScriptParameterBinderController.BindableParameters; this._defaultParameterSetFlag = 0; } else if (!flag2) { return false; } if (this._commandAst.IsInWorkflow()) { Type type = Type.GetType("Microsoft.PowerShell.Workflow.AstToWorkflowConverter, Microsoft.PowerShell.Activities, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"); if (type != null) { Dictionary<string, Type> dictionary = (Dictionary<string, Type>) type.GetMethod("GetActivityParameters").Invoke(null, new object[] { this._commandAst }); if (dictionary != null) { bool flag6 = dictionary.ContainsKey("PSComputerName") && !dictionary.ContainsKey("ComputerName"); List<MergedCompiledCommandParameter> source = new List<MergedCompiledCommandParameter>(); Collection<Attribute> attributes = new Collection<Attribute> { new ParameterAttribute() }; foreach (KeyValuePair<string, Type> pair2 in dictionary) { if (flag2 || !this._bindableParameters.BindableParameters.ContainsKey(pair2.Key)) { Type actualActivityParameterType = GetActualActivityParameterType(pair2.Value); RuntimeDefinedParameter runtimeDefinedParameter = new RuntimeDefinedParameter(pair2.Key, actualActivityParameterType, attributes); CompiledCommandParameter parameter = new CompiledCommandParameter(runtimeDefinedParameter, false) { IsInAllSets = true }; MergedCompiledCommandParameter parameter3 = new MergedCompiledCommandParameter(parameter, ParameterBinderAssociation.DeclaredFormalParameters); source.Add(parameter3); } } if (source.Any<MergedCompiledCommandParameter>()) { MergedCommandParameterMetadata metadata = new MergedCommandParameterMetadata(); if (!flag2) { metadata.ReplaceMetadata(this._bindableParameters); } foreach (MergedCompiledCommandParameter parameter5 in source) { metadata.BindableParameters.Add(parameter5.Parameter.Name, parameter5); } this._bindableParameters = metadata; } foreach (string str2 in ignoredWorkflowParameters) { if (this._bindableParameters.BindableParameters.ContainsKey(str2)) { this._bindableParameters.BindableParameters.Remove(str2); } } if (this._bindableParameters.BindableParameters.ContainsKey("ComputerName") && flag6) { this._bindableParameters.BindableParameters.Remove("ComputerName"); string key = (from aliasPair in this._bindableParameters.AliasedParameters where string.Equals("ComputerName", aliasPair.Value.Parameter.Name) select aliasPair.Key).FirstOrDefault<string>(); this._bindableParameters.AliasedParameters.Remove(key); } } } } this._unboundParameters.AddRange(this._bindableParameters.BindableParameters.Values); CommandBaseAst ast4 = null; PipelineAst parent = this._commandAst.Parent as PipelineAst; if (parent.PipelineElements.Count > 1) { foreach (CommandBaseAst ast6 in parent.PipelineElements) { if (ast6.GetHashCode() == this._commandAst.GetHashCode()) { this._isPipelineInputExpected = ast4 != null; if (this._isPipelineInputExpected) { this._pipelineInputType = typeof(object); } break; } ast4 = ast6; } } return true; }
internal static Collection<CommandParameterSetInfo> GetParameterMetadata(System.Management.Automation.CommandMetadata metadata, MergedCommandParameterMetadata parameterMetadata) { Collection<CommandParameterSetInfo> collection = new Collection<CommandParameterSetInfo>(); if (parameterMetadata != null) { if (parameterMetadata.ParameterSetCount == 0) { collection.Add(new CommandParameterSetInfo("__AllParameterSets", false, int.MaxValue, parameterMetadata)); return collection; } int parameterSetCount = parameterMetadata.ParameterSetCount; for (int i = 0; i < parameterSetCount; i++) { int parameterSet = ((int) 1) << i; string parameterSetName = parameterMetadata.GetParameterSetName(parameterSet); bool isDefaultParameterSet = (parameterSet & metadata.DefaultParameterSetFlag) != 0; collection.Add(new CommandParameterSetInfo(parameterSetName, isDefaultParameterSet, parameterSet, parameterMetadata)); } } return collection; }
private void Initialize(MergedCommandParameterMetadata parameterMetadata, int parameterSetFlag) { Collection<CommandParameterInfo> list = new Collection<CommandParameterInfo>(); foreach (MergedCompiledCommandParameter parameter in parameterMetadata.GetParametersInParameterSet(parameterSetFlag)) { if (parameter != null) { list.Add(new CommandParameterInfo(parameter.Parameter, parameterSetFlag)); } } this.Parameters = new ReadOnlyCollection<CommandParameterInfo>(list); }
private MergedCommandParameterMetadata MergeParameterMetadata(ExecutionContext context, InternalParameterMetadata parameterMetadata, bool shouldGenerateCommonParameters) { MergedCommandParameterMetadata metadata = new MergedCommandParameterMetadata(); metadata.AddMetadataForBinder(parameterMetadata, ParameterBinderAssociation.DeclaredFormalParameters); if (shouldGenerateCommonParameters) { InternalParameterMetadata metadata2 = InternalParameterMetadata.Get(typeof(CommonParameters), context, false); metadata.AddMetadataForBinder(metadata2, ParameterBinderAssociation.CommonParameters); if (this.SupportsShouldProcess) { InternalParameterMetadata metadata3 = InternalParameterMetadata.Get(typeof(ShouldProcessParameters), context, false); metadata.AddMetadataForBinder(metadata3, ParameterBinderAssociation.ShouldProcessParameters); } if (this.SupportsPaging) { InternalParameterMetadata metadata4 = InternalParameterMetadata.Get(typeof(PagingParameters), context, false); metadata.AddMetadataForBinder(metadata4, ParameterBinderAssociation.PagingParameters); } if (this.SupportsTransactions) { InternalParameterMetadata metadata5 = InternalParameterMetadata.Get(typeof(TransactionParameters), context, false); metadata.AddMetadataForBinder(metadata5, ParameterBinderAssociation.TransactionParameters); } } return metadata; }
public CommandMetadata(CommandMetadata other) { this._commandName = string.Empty; this._defaultParameterSetName = "__AllParameterSets"; this._positionalBinding = true; this._helpUri = string.Empty; this._remotingCapability = System.Management.Automation.RemotingCapability.PowerShell; this._confirmImpact = System.Management.Automation.ConfirmImpact.Medium; this._otherAttributes = new Collection<Attribute>(); if (other == null) { throw PSTraceSource.NewArgumentNullException("other"); } this._commandName = other._commandName; this._confirmImpact = other._confirmImpact; this._defaultParameterSetFlag = other._defaultParameterSetFlag; this._defaultParameterSetName = other._defaultParameterSetName; this._implementsDynamicParameters = other._implementsDynamicParameters; this._supportsShouldProcess = other._supportsShouldProcess; this._supportsPaging = other._supportsPaging; this._supportsTransactions = other._supportsTransactions; this.CommandType = other.CommandType; this._wrappedAnyCmdlet = other._wrappedAnyCmdlet; this._wrappedCommand = other._wrappedCommand; this._wrappedCommandType = other._wrappedCommandType; this._parameters = new Dictionary<string, ParameterMetadata>(other.Parameters.Count, StringComparer.OrdinalIgnoreCase); if (other.Parameters != null) { foreach (KeyValuePair<string, ParameterMetadata> pair in other.Parameters) { this._parameters.Add(pair.Key, new ParameterMetadata(pair.Value)); } } if (other._otherAttributes == null) { this._otherAttributes = null; } else { this._otherAttributes = new Collection<Attribute>(new List<Attribute>(other._otherAttributes.Count)); foreach (Attribute attribute in other._otherAttributes) { this._otherAttributes.Add(attribute); } } this.staticCommandParameterMetadata = null; }
private void BuildSyntaxForParameterSet(XmlElement command, XmlElement syntax, MergedCommandParameterMetadata parameterMetadata, int i) { XmlElement newChild = this.doc.CreateElement("command:syntaxItem", commandURI); XmlElement element2 = this.doc.CreateElement("maml:name", mamlURI); XmlText text = this.doc.CreateTextNode(this.commandName); newChild.AppendChild(element2).AppendChild(text); foreach (MergedCompiledCommandParameter parameter in parameterMetadata.GetParametersInParameterSet(((int) 1) << i)) { if (parameter.BinderAssociation != ParameterBinderAssociation.CommonParameters) { CompiledCommandParameter parameter2 = parameter.Parameter; ParameterSetSpecificMetadata parameterSetData = parameter2.GetParameterSetData(((int) 1) << i); string parameterDescription = this.GetParameterDescription(parameter2.Name); bool supportsWildcards = (from attribute in parameter2.CompiledAttributes where attribute is SupportsWildcardsAttribute select attribute).Any<System.Attribute>(); XmlElement element3 = this.BuildXmlForParameter(parameter2.Name, parameterSetData.IsMandatory, parameterSetData.ValueFromPipeline, parameterSetData.ValueFromPipelineByPropertyName, parameterSetData.IsPositional ? ((1 + parameterSetData.Position)).ToString(CultureInfo.InvariantCulture) : "named", parameter2.Type, parameterDescription, supportsWildcards, "", true); newChild.AppendChild(element3); } } command.AppendChild(syntax).AppendChild(newChild); }
private void InitializeMembers() { this._function = false; this._commandName = null; this._currentParameterSetFlag = int.MaxValue; this._defaultParameterSetFlag = 0; this._bindableParameters = null; this._arguments = this._arguments ?? new Collection<AstParameterArgumentPair>(); this._boundParameters = this._boundParameters ?? new Dictionary<string, MergedCompiledCommandParameter>(StringComparer.OrdinalIgnoreCase); this._boundArguments = this._boundArguments ?? new Dictionary<string, AstParameterArgumentPair>(StringComparer.OrdinalIgnoreCase); this._unboundParameters = this._unboundParameters ?? new List<MergedCompiledCommandParameter>(); this._boundPositionalParameter = this._boundPositionalParameter ?? new Collection<string>(); this._arguments.Clear(); this._boundParameters.Clear(); this._unboundParameters.Clear(); this._boundArguments.Clear(); this._boundPositionalParameter.Clear(); this._pipelineInputType = null; this._bindingEffective = true; this._isPipelineInputExpected = false; this._parametersNotFound = this._parametersNotFound ?? new Collection<CommandParameterAst>(); this._ambiguousParameters = this._ambiguousParameters ?? new Collection<CommandParameterAst>(); this._duplicateParameters = this._duplicateParameters ?? new Collection<AstParameterArgumentPair>(); this._parametersNotFound.Clear(); this._ambiguousParameters.Clear(); this._duplicateParameters.Clear(); }
internal static Collection <CommandParameterSetInfo> GetParameterMetadata(CommandMetadata metadata, MergedCommandParameterMetadata parameterMetadata) { Collection <CommandParameterSetInfo> result = new Collection <CommandParameterSetInfo>(); if (parameterMetadata != null) { if (parameterMetadata.ParameterSetCount == 0) { const string parameterSetName = ParameterAttribute.AllParameterSets; result.Add( new CommandParameterSetInfo( parameterSetName, false, uint.MaxValue, parameterMetadata)); } else { int parameterSetCount = parameterMetadata.ParameterSetCount; for (int index = 0; index < parameterSetCount; ++index) { uint currentFlagPosition = (uint)0x1 << index; // Get the parameter set name string parameterSetName = parameterMetadata.GetParameterSetName(currentFlagPosition); // Is the parameter set the default? bool isDefaultParameterSet = (currentFlagPosition & metadata.DefaultParameterSetFlag) != 0; result.Add( new CommandParameterSetInfo( parameterSetName, isDefaultParameterSet, currentFlagPosition, parameterMetadata)); } } } return(result); }
private void ThrowAmbiguousParameterSetException(int parameterSetFlags, MergedCommandParameterMetadata bindableParameters) { ParameterBindingException pbex = new ParameterBindingException(ErrorCategory.InvalidArgument, this.Command.MyInvocation, null, null, null, null, "ParameterBinderStrings", "AmbiguousParameterSet", new object[0]); for (int i = 1; parameterSetFlags != 0; i = i << 1) { int num2 = parameterSetFlags & 1; if (num2 == 1) { string parameterSetName = bindableParameters.GetParameterSetName(i); if (!string.IsNullOrEmpty(parameterSetName)) { ParameterBinderBase.bindingTracer.WriteLine("Remaining valid parameter set: {0}", new object[] { parameterSetName }); } } parameterSetFlags = parameterSetFlags >> 1; } if (!base.DefaultParameterBindingInUse) { throw pbex; } base.ThrowElaboratedBindingException(pbex); }
private void BuildSyntaxForParameterSet(XmlElement command, XmlElement syntax, MergedCommandParameterMetadata parameterMetadata, int i) { XmlElement newChild = this.doc.CreateElement("command:syntaxItem", commandURI); XmlElement element2 = this.doc.CreateElement("maml:name", mamlURI); XmlText text = this.doc.CreateTextNode(this.commandName); newChild.AppendChild(element2).AppendChild(text); foreach (MergedCompiledCommandParameter parameter in parameterMetadata.GetParametersInParameterSet(((int)1) << i)) { if (parameter.BinderAssociation != ParameterBinderAssociation.CommonParameters) { CompiledCommandParameter parameter2 = parameter.Parameter; ParameterSetSpecificMetadata parameterSetData = parameter2.GetParameterSetData(((int)1) << i); string parameterDescription = this.GetParameterDescription(parameter2.Name); bool supportsWildcards = (from attribute in parameter2.CompiledAttributes where attribute is SupportsWildcardsAttribute select attribute).Any <System.Attribute>(); XmlElement element3 = this.BuildXmlForParameter(parameter2.Name, parameterSetData.IsMandatory, parameterSetData.ValueFromPipeline, parameterSetData.ValueFromPipelineByPropertyName, parameterSetData.IsPositional ? ((1 + parameterSetData.Position)).ToString(CultureInfo.InvariantCulture) : "named", parameter2.Type, parameterDescription, supportsWildcards, "", true); newChild.AppendChild(element3); } } command.AppendChild(syntax).AppendChild(newChild); }
internal ICollection<MergedCompiledCommandParameter> ReplaceMetadata(MergedCommandParameterMetadata metadata) { ICollection<MergedCompiledCommandParameter> is2 = new Collection<MergedCompiledCommandParameter>(); this.bindableParameters.Clear(); foreach (KeyValuePair<string, MergedCompiledCommandParameter> pair in metadata.BindableParameters) { this.bindableParameters.Add(pair.Key, pair.Value); is2.Add(pair.Value); } this.aliasedParameters.Clear(); foreach (KeyValuePair<string, MergedCompiledCommandParameter> pair2 in metadata.AliasedParameters) { this.aliasedParameters.Add(pair2.Key, pair2.Value); } return is2; }
internal XmlDocument BuildXmlFromComments() { this.doc = new XmlDocument(); XmlElement newChild = this.doc.CreateElement("command:command", commandURI); newChild.SetAttribute("xmlns:maml", mamlURI); newChild.SetAttribute("xmlns:command", commandURI); newChild.SetAttribute("xmlns:dev", devURI); this.doc.AppendChild(newChild); XmlElement element2 = this.doc.CreateElement("command:details", commandURI); newChild.AppendChild(element2); XmlElement element3 = this.doc.CreateElement("command:name", commandURI); XmlText text = this.doc.CreateTextNode(this.commandName); element2.AppendChild(element3).AppendChild(text); if (!string.IsNullOrEmpty(this._sections.Synopsis)) { XmlElement element4 = this.doc.CreateElement("maml:description", mamlURI); XmlElement element5 = this.doc.CreateElement("maml:para", mamlURI); XmlText text2 = this.doc.CreateTextNode(this._sections.Synopsis); element2.AppendChild(element4).AppendChild(element5).AppendChild(text2); } this.DetermineParameterDescriptions(); XmlElement syntax = this.doc.CreateElement("command:syntax", commandURI); MergedCommandParameterMetadata staticCommandParameterMetadata = this.commandMetadata.StaticCommandParameterMetadata; if (staticCommandParameterMetadata.ParameterSetCount > 0) { for (int i = 0; i < staticCommandParameterMetadata.ParameterSetCount; i++) { this.BuildSyntaxForParameterSet(newChild, syntax, staticCommandParameterMetadata, i); } } else { this.BuildSyntaxForParameterSet(newChild, syntax, staticCommandParameterMetadata, 0x7fffffff); } XmlElement element7 = this.doc.CreateElement("command:parameters", commandURI); foreach (KeyValuePair <string, MergedCompiledCommandParameter> pair in staticCommandParameterMetadata.BindableParameters) { MergedCompiledCommandParameter parameter = pair.Value; if (parameter.BinderAssociation != ParameterBinderAssociation.CommonParameters) { ParameterSetSpecificMetadata parameterSetData; string key = pair.Key; string parameterDescription = this.GetParameterDescription(key); bool isMandatory = false; bool valueFromPipeline = false; bool valueFromPipelineByPropertyName = false; string position = "named"; int num2 = 0; CompiledCommandParameter parameter2 = parameter.Parameter; parameter2.ParameterSetData.TryGetValue("__AllParameterSets", out parameterSetData); while ((parameterSetData == null) && (num2 < 0x20)) { parameterSetData = parameter2.GetParameterSetData(((int)1) << num2++); } if (parameterSetData != null) { isMandatory = parameterSetData.IsMandatory; valueFromPipeline = parameterSetData.ValueFromPipeline; valueFromPipelineByPropertyName = parameterSetData.ValueFromPipelineByPropertyName; position = parameterSetData.IsPositional ? ((1 + parameterSetData.Position)).ToString(CultureInfo.InvariantCulture) : "named"; } Collection <System.Attribute> compiledAttributes = parameter2.CompiledAttributes; bool supportsWildcards = compiledAttributes.OfType <SupportsWildcardsAttribute>().Any <SupportsWildcardsAttribute>(); string help = ""; object obj2 = null; PSDefaultValueAttribute attribute = compiledAttributes.OfType <PSDefaultValueAttribute>().FirstOrDefault <PSDefaultValueAttribute>(); if (attribute != null) { help = attribute.Help; if (string.IsNullOrEmpty(help)) { obj2 = attribute.Value; } } if (string.IsNullOrEmpty(help)) { RuntimeDefinedParameter parameter3; if ((obj2 == null) && this.scriptBlock.RuntimeDefinedParameters.TryGetValue(key, out parameter3)) { obj2 = parameter3.Value; } Compiler.DefaultValueExpressionWrapper wrapper = obj2 as Compiler.DefaultValueExpressionWrapper; if (wrapper != null) { help = wrapper.Expression.Extent.Text; } else if (obj2 != null) { help = PSObject.ToStringParser(null, obj2); } } XmlElement element8 = this.BuildXmlForParameter(key, isMandatory, valueFromPipeline, valueFromPipelineByPropertyName, position, parameter2.Type, parameterDescription, supportsWildcards, help, false); element7.AppendChild(element8); } } newChild.AppendChild(element7); if (!string.IsNullOrEmpty(this._sections.Description)) { XmlElement element9 = this.doc.CreateElement("maml:description", mamlURI); XmlElement element10 = this.doc.CreateElement("maml:para", mamlURI); XmlText text3 = this.doc.CreateTextNode(this._sections.Description); newChild.AppendChild(element9).AppendChild(element10).AppendChild(text3); } if (!string.IsNullOrEmpty(this._sections.Notes)) { XmlElement element11 = this.doc.CreateElement("maml:alertSet", mamlURI); XmlElement element12 = this.doc.CreateElement("maml:alert", mamlURI); XmlElement element13 = this.doc.CreateElement("maml:para", mamlURI); XmlText text4 = this.doc.CreateTextNode(this._sections.Notes); newChild.AppendChild(element11).AppendChild(element12).AppendChild(element13).AppendChild(text4); } if (this._examples.Count > 0) { XmlElement element14 = this.doc.CreateElement("command:examples", commandURI); int num3 = 1; foreach (string str5 in this._examples) { string str7; string str8; string str9; XmlElement element15 = this.doc.CreateElement("command:example", commandURI); XmlElement element16 = this.doc.CreateElement("maml:title", mamlURI); string str6 = string.Format(CultureInfo.InvariantCulture, "\t\t\t\t-------------------------- {0} {1} --------------------------", new object[] { HelpDisplayStrings.ExampleUpperCase, num3++ }); XmlText text5 = this.doc.CreateTextNode(str6); element15.AppendChild(element16).AppendChild(text5); GetExampleSections(str5, out str7, out str8, out str9); XmlElement element17 = this.doc.CreateElement("maml:introduction", mamlURI); XmlElement element18 = this.doc.CreateElement("maml:para", mamlURI); XmlText text6 = this.doc.CreateTextNode(str7); element15.AppendChild(element17).AppendChild(element18).AppendChild(text6); XmlElement element19 = this.doc.CreateElement("dev:code", devURI); XmlText text7 = this.doc.CreateTextNode(str8); element15.AppendChild(element19).AppendChild(text7); XmlElement element20 = this.doc.CreateElement("dev:remarks", devURI); XmlElement element21 = this.doc.CreateElement("maml:para", mamlURI); XmlText text8 = this.doc.CreateTextNode(str9); element15.AppendChild(element20).AppendChild(element21).AppendChild(text8); for (int j = 0; j < 4; j++) { element20.AppendChild(this.doc.CreateElement("maml:para", mamlURI)); } element14.AppendChild(element15); } newChild.AppendChild(element14); } if (this._inputs.Count > 0) { XmlElement element22 = this.doc.CreateElement("command:inputTypes", commandURI); foreach (string str10 in this._inputs) { XmlElement element23 = this.doc.CreateElement("command:inputType", commandURI); XmlElement element24 = this.doc.CreateElement("dev:type", devURI); XmlElement element25 = this.doc.CreateElement("maml:name", mamlURI); XmlText text9 = this.doc.CreateTextNode(str10); element22.AppendChild(element23).AppendChild(element24).AppendChild(element25).AppendChild(text9); } newChild.AppendChild(element22); } IEnumerable outputType = null; if (this._outputs.Count > 0) { outputType = this._outputs; } else if (this.scriptBlock.OutputType.Count > 0) { outputType = this.scriptBlock.OutputType; } if (outputType != null) { XmlElement element26 = this.doc.CreateElement("command:returnValues", commandURI); foreach (object obj3 in outputType) { XmlElement element27 = this.doc.CreateElement("command:returnValue", commandURI); XmlElement element28 = this.doc.CreateElement("dev:type", devURI); XmlElement element29 = this.doc.CreateElement("maml:name", mamlURI); string str11 = (obj3 as string) ?? ((PSTypeName)obj3).Name; XmlText text10 = this.doc.CreateTextNode(str11); element26.AppendChild(element27).AppendChild(element28).AppendChild(element29).AppendChild(text10); } newChild.AppendChild(element26); } if (this._links.Count > 0) { XmlElement element30 = this.doc.CreateElement("maml:relatedLinks", mamlURI); foreach (string str12 in this._links) { XmlElement element31 = this.doc.CreateElement("maml:navigationLink", mamlURI); string qualifiedName = Uri.IsWellFormedUriString(Uri.EscapeUriString(str12), UriKind.Absolute) ? "maml:uri" : "maml:linkText"; XmlElement element32 = this.doc.CreateElement(qualifiedName, mamlURI); XmlText text11 = this.doc.CreateTextNode(str12); element30.AppendChild(element31).AppendChild(element32).AppendChild(text11); } newChild.AppendChild(element30); } return(this.doc); }
private void ThrowAmbiguousParameterSetException(uint parameterSetFlags, MergedCommandParameterMetadata bindableParameters) { ParameterBindingException bindingException = new ParameterBindingException( ErrorCategory.InvalidArgument, this.Command.MyInvocation, null, null, null, null, ParameterBinderStrings.AmbiguousParameterSet, "AmbiguousParameterSet"); // Trace the parameter sets still active uint currentParameterSet = 1; while (parameterSetFlags != 0) { uint currentParameterSetActive = parameterSetFlags & 0x1; if (currentParameterSetActive == 1) { string parameterSetName = bindableParameters.GetParameterSetName(currentParameterSet); if (!String.IsNullOrEmpty(parameterSetName)) { ParameterBinderBase.bindingTracer.WriteLine("Remaining valid parameter set: {0}", parameterSetName); } } parameterSetFlags >>= 1; currentParameterSet <<= 1; } if (!DefaultParameterBindingInUse) { throw bindingException; } else { ThrowElaboratedBindingException(bindingException); } }
private void Initialize(MergedCommandParameterMetadata parameterMetadata, uint parameterSetFlag) { Diagnostics.Assert( parameterMetadata != null, "The parameterMetadata should never be null"); Collection<CommandParameterInfo> processedParameters = new Collection<CommandParameterInfo>(); // Get the parameters in the parameter set Collection<MergedCompiledCommandParameter> compiledParameters = parameterMetadata.GetParametersInParameterSet(parameterSetFlag); foreach (MergedCompiledCommandParameter parameter in compiledParameters) { if (parameter != null) { processedParameters.Add( new CommandParameterInfo(parameter.Parameter, parameterSetFlag)); } } Parameters = new ReadOnlyCollection<CommandParameterInfo>(processedParameters); }
public MergedCommandParameterMetadata GetParameterMetadata(ScriptBlock scriptBlock) { if (this._parameterMetadata == null) { lock (this._syncObject) { if (this._parameterMetadata == null) { CommandMetadata metadata = new CommandMetadata(scriptBlock, "", LocalPipeline.GetExecutionContextFromTLS()); this._parameterMetadata = metadata.StaticCommandParameterMetadata; } } } return this._parameterMetadata; }
private void GetMergedCommandParameterMetadata(out MergedCommandParameterMetadata result) { // MSFT:652277 - When invoking cmdlets or advanced functions, MyInvocation.MyCommand.Parameters do not contain the dynamic parameters // When trying to get parameter metadata for a CommandInfo that has dynamic parameters, a new CommandProcessor will be // created out of this CommandInfo and the parameter binding algorithm will be invoked. However, when this happens via // 'MyInvocation.MyCommand.Parameter', it's actually retrieving the parameter metadata of the same cmdlet that is currently // running. In this case, information about the specified parameters are not kept around in 'MyInvocation.MyCommand', so // going through the binding algorithm again won't give us the metadata about the dynamic parameters that should have been // discovered already. // The fix is to check if the CommandInfo is actually representing the currently running cmdlet. If so, the retrieval of parameter // metadata actually stems from the running of the same cmdlet. In this case, we can just use the current CommandProcessor to // retrieve all bindable parameters, which should include the dynamic parameters that have been discovered already. CommandProcessor processor; if (Context.CurrentCommandProcessor != null && Context.CurrentCommandProcessor.CommandInfo == this) { // Accessing the parameters within the invocation of the same cmdlet/advanced function. processor = (CommandProcessor)Context.CurrentCommandProcessor; } else { IScriptCommandInfo scriptCommand = this as IScriptCommandInfo; processor = scriptCommand != null ? new CommandProcessor(scriptCommand, _context, useLocalScope: true, fromScriptFile: false, sessionState: scriptCommand.ScriptBlock.SessionStateInternal ?? Context.EngineSessionState) : new CommandProcessor((CmdletInfo)this, _context) { UseLocalScope = true }; ParameterBinderController.AddArgumentsToCommandProcessor(processor, Arguments); CommandProcessorBase oldCurrentCommandProcessor = Context.CurrentCommandProcessor; try { Context.CurrentCommandProcessor = processor; processor.SetCurrentScopeToExecutionScope(); processor.CmdletParameterBinderController.BindCommandLineParametersNoValidation(processor.arguments); } catch (ParameterBindingException) { // Ignore the binding exception if no argument is specified if (processor.arguments.Count > 0) { throw; } } finally { Context.CurrentCommandProcessor = oldCurrentCommandProcessor; processor.RestorePreviousScope(); } } result = processor.CmdletParameterBinderController.BindableParameters; }
internal static Dictionary<string, ParameterMetadata> GetParameterMetadata(MergedCommandParameterMetadata cmdParameterMetadata) { Dictionary<string, ParameterMetadata> dictionary = new Dictionary<string, ParameterMetadata>(StringComparer.OrdinalIgnoreCase); foreach (KeyValuePair<string, MergedCompiledCommandParameter> pair in cmdParameterMetadata.BindableParameters) { string key = pair.Key; ParameterMetadata metadata = new ParameterMetadata(pair.Value.Parameter); dictionary.Add(key, metadata); } return dictionary; }
internal CommandMetadata(ScriptBlock scriptblock, string commandName, ExecutionContext context) { this._commandName = string.Empty; this._defaultParameterSetName = "__AllParameterSets"; this._positionalBinding = true; this._helpUri = string.Empty; this._remotingCapability = System.Management.Automation.RemotingCapability.PowerShell; this._confirmImpact = System.Management.Automation.ConfirmImpact.Medium; this._otherAttributes = new Collection<Attribute>(); if (scriptblock == null) { throw PSTraceSource.NewArgumentException("scriptblock"); } CmdletBindingAttribute cmdletBindingAttribute = scriptblock.CmdletBindingAttribute; if (cmdletBindingAttribute != null) { this.ProcessCmdletAttribute(cmdletBindingAttribute); } else { this._defaultParameterSetName = null; } this._commandName = commandName; this.CommandType = typeof(PSScriptCmdlet); if (scriptblock.HasDynamicParameters) { this._implementsDynamicParameters = true; } InternalParameterMetadata parameterMetadata = InternalParameterMetadata.Get(scriptblock.RuntimeDefinedParameters, false, scriptblock.UsesCmdletBinding); this.staticCommandParameterMetadata = this.MergeParameterMetadata(context, parameterMetadata, scriptblock.UsesCmdletBinding); this._defaultParameterSetFlag = this.staticCommandParameterMetadata.GenerateParameterSetMappingFromMetadata(this._defaultParameterSetName); this.staticCommandParameterMetadata.MakeReadOnly(); }