} // Arguments

        /// <summary>
        /// Passes the binding directly through to the parameter binder.
        /// It does no verification against metadata.
        /// </summary>
        /// 
        /// <param name="argument">
        /// The name and value of the variable to bind.
        /// </param>
        /// 
        /// <param name="flags">
        /// Ignored.
        /// </param>
        /// 
        /// <returns>
        /// True if the parameter was successfully bound. Any error condition
        /// produces an exception.
        /// </returns>
        /// 
        internal override bool BindParameter(
            CommandParameterInternal argument,
            ParameterBindingFlags flags)
        {
            Diagnostics.Assert(false, "Unreachable code");

            throw new InvalidOperationException();
        }
Exemple #2
0
        public ParameterWrapper(ParameterInfo info, Type type, string name, ParameterBindingFlags flags) {
            ContractUtils.RequiresNotNull(type, "type");
            
            _type = type;
            _info = info;
            _flags = flags;

            // params arrays & dictionaries don't allow assignment by keyword
            _name = (IsParamsArray || IsParamsDict || name == null) ? "<unknown>" : name;
        }
Exemple #3
0
 internal virtual bool BindParameter(CommandParameterInternal parameter, CompiledCommandParameter parameterMetadata, ParameterBindingFlags flags)
 {
     bool flag = false;
     bool flag2 = (flags & ParameterBindingFlags.ShouldCoerceType) != ParameterBindingFlags.None;
     if (parameter == null)
     {
         throw PSTraceSource.NewArgumentNullException("parameter");
     }
     if (parameterMetadata == null)
     {
         throw PSTraceSource.NewArgumentNullException("parameterMetadata");
     }
     using (bindingTracer.TraceScope("BIND arg [{0}] to parameter [{1}]", new object[] { parameter.ArgumentValue, parameterMetadata.Name }))
     {
         parameter.ParameterName = parameterMetadata.Name;
         object argumentValue = parameter.ArgumentValue;
         ScriptParameterBinder binder = this as ScriptParameterBinder;
         bool bindingScriptCmdlet = false;
         if (binder != null)
         {
             bindingScriptCmdlet = binder.Script.UsesCmdletBinding;
         }
         foreach (ArgumentTransformationAttribute attribute in parameterMetadata.ArgumentTransformationAttributes)
         {
             using (bindingTracer.TraceScope("Executing DATA GENERATION metadata: [{0}]", new object[] { attribute.GetType() }))
             {
                 try
                 {
                     ArgumentTypeConverterAttribute attribute2 = attribute as ArgumentTypeConverterAttribute;
                     if (attribute2 != null)
                     {
                         if (flag2)
                         {
                             argumentValue = attribute2.Transform(this.engine, argumentValue, true, bindingScriptCmdlet);
                         }
                     }
                     else
                     {
                         argumentValue = attribute.Transform(this.engine, argumentValue);
                     }
                     bindingTracer.WriteLine("result returned from DATA GENERATION: {0}", new object[] { argumentValue });
                 }
                 catch (Exception exception)
                 {
                     CommandProcessorBase.CheckForSevereException(exception);
                     bindingTracer.WriteLine("ERROR: DATA GENERATION: {0}", new object[] { exception.Message });
                     ParameterBindingException exception2 = new ParameterBindingArgumentTransformationException(exception, ErrorCategory.InvalidData, this.InvocationInfo, this.GetErrorExtent(parameter), parameterMetadata.Name, parameterMetadata.Type, (argumentValue == null) ? null : argumentValue.GetType(), "ParameterBinderStrings", "ParameterArgumentTransformationError", new object[] { exception.Message });
                     throw exception2;
                 }
             }
         }
         if (flag2)
         {
             argumentValue = this.CoerceTypeAsNeeded(parameter, parameterMetadata.Name, parameterMetadata.Type, parameterMetadata.CollectionTypeInformation, argumentValue);
         }
         else if (!this.ShouldContinueUncoercedBind(parameter, parameterMetadata, flags, ref argumentValue))
         {
             goto Label_040E;
         }
         if ((parameterMetadata.PSTypeName != null) && (argumentValue != null))
         {
             IEnumerable enumerable = LanguagePrimitives.GetEnumerable(argumentValue);
             if (enumerable != null)
             {
                 foreach (object obj3 in enumerable)
                 {
                     this.ValidatePSTypeName(parameter, parameterMetadata, !flag2, obj3);
                 }
             }
             else
             {
                 this.ValidatePSTypeName(parameter, parameterMetadata, !flag2, argumentValue);
             }
         }
         if ((flags & ParameterBindingFlags.IsDefaultValue) == ParameterBindingFlags.None)
         {
             foreach (ValidateArgumentsAttribute attribute3 in parameterMetadata.ValidationAttributes)
             {
                 using (bindingTracer.TraceScope("Executing VALIDATION metadata: [{0}]", new object[] { attribute3.GetType() }))
                 {
                     try
                     {
                         attribute3.InternalValidate(argumentValue, this.engine);
                     }
                     catch (Exception exception3)
                     {
                         CommandProcessorBase.CheckForSevereException(exception3);
                         bindingTracer.WriteLine("ERROR: VALIDATION FAILED: {0}", new object[] { exception3.Message });
                         ParameterBindingValidationException exception4 = new ParameterBindingValidationException(exception3, ErrorCategory.InvalidData, this.InvocationInfo, this.GetErrorExtent(parameter), parameterMetadata.Name, parameterMetadata.Type, (argumentValue == null) ? null : argumentValue.GetType(), "ParameterBinderStrings", "ParameterArgumentValidationError", new object[] { exception3.Message });
                         throw exception4;
                     }
                     tracer.WriteLine("Validation attribute on {0} returned {1}.", new object[] { parameterMetadata.Name, flag });
                 }
             }
             if (IsParameterMandatory(parameterMetadata))
             {
                 this.ValidateNullOrEmptyArgument(parameter, parameterMetadata, parameterMetadata.Type, argumentValue, true);
             }
         }
         Exception innerException = null;
         try
         {
             this.BindParameter(parameter.ParameterName, argumentValue);
             flag = true;
         }
         catch (SetValueException exception6)
         {
             innerException = exception6;
         }
         if (innerException != null)
         {
             Type typeSpecified = (argumentValue == null) ? null : argumentValue.GetType();
             ParameterBindingException exception7 = new ParameterBindingException(innerException, ErrorCategory.WriteError, this.InvocationInfo, this.GetErrorExtent(parameter), parameterMetadata.Name, parameterMetadata.Type, typeSpecified, "ParameterBinderStrings", "ParameterBindingFailed", new object[] { innerException.Message });
             throw exception7;
         }
     Label_040E:;
         bindingTracer.WriteLine("BIND arg [{0}] to param [{1}] {2}", new object[] { argumentValue, parameter.ParameterName, flag ? "SUCCESSFUL" : "SKIPPED" });
         if (flag)
         {
             if (this.RecordBoundParameters)
             {
                 this.CommandLineParameters.Add(parameter.ParameterName, argumentValue);
             }
             MshCommandRuntime commandRuntime = this.Command.commandRuntime as MshCommandRuntime;
             if ((commandRuntime != null) && commandRuntime.LogPipelineExecutionDetail)
             {
                 IEnumerable source = LanguagePrimitives.GetEnumerable(argumentValue);
                 if (source != null)
                 {
                     string parameterValue = string.Join(", ", source.Cast<object>().ToArray<object>());
                     commandRuntime.PipelineProcessor.LogExecutionParameterBinding(this.InvocationInfo, parameter.ParameterName, parameterValue);
                 }
                 else
                 {
                     commandRuntime.PipelineProcessor.LogExecutionParameterBinding(this.InvocationInfo, parameter.ParameterName, (argumentValue == null) ? "" : argumentValue.ToString());
                 }
             }
         }
         return flag;
     }
 }
 private bool BindValueFromPipelineByPropertyName(PSObject inputToOperateOn, MergedCompiledCommandParameter parameter, ParameterBindingFlags flags)
 {
     bool flag = false;
     ParameterBinderBase.bindingTracer.WriteLine(((flags & ParameterBindingFlags.ShouldCoerceType) != ParameterBindingFlags.None) ? "Parameter [{0}] PIPELINE INPUT ValueFromPipelineByPropertyName WITH COERCION" : "Parameter [{0}] PIPELINE INPUT ValueFromPipelineByPropertyName NO COERCION", new object[] { parameter.Parameter.Name });
     PSMemberInfo info = inputToOperateOn.Properties[parameter.Parameter.Name];
     if (info == null)
     {
         foreach (string str in parameter.Parameter.Aliases)
         {
             info = inputToOperateOn.Properties[str];
             if (info != null)
             {
                 break;
             }
         }
     }
     if (info != null)
     {
         ParameterBindingException pbex = null;
         try
         {
             flag = this.BindPipelineParameter(info.Value, parameter, flags);
         }
         catch (ParameterBindingArgumentTransformationException exception2)
         {
             pbex = exception2;
         }
         catch (ParameterBindingValidationException exception3)
         {
             pbex = exception3;
         }
         catch (ParameterBindingParameterDefaultValueException exception4)
         {
             pbex = exception4;
         }
         catch (ParameterBindingException)
         {
             flag = false;
         }
         if (pbex == null)
         {
             return flag;
         }
         if (!base.DefaultParameterBindingInUse)
         {
             throw pbex;
         }
         base.ThrowElaboratedBindingException(pbex);
     }
     return flag;
 }
 private bool BindValueFromPipeline(PSObject inputToOperateOn, MergedCompiledCommandParameter parameter, ParameterBindingFlags flags)
 {
     bool flag = false;
     ParameterBinderBase.bindingTracer.WriteLine(((flags & ParameterBindingFlags.ShouldCoerceType) != ParameterBindingFlags.None) ? "Parameter [{0}] PIPELINE INPUT ValueFromPipeline WITH COERCION" : "Parameter [{0}] PIPELINE INPUT ValueFromPipeline NO COERCION", new object[] { parameter.Parameter.Name });
     ParameterBindingException pbex = null;
     try
     {
         flag = this.BindPipelineParameter(inputToOperateOn, parameter, flags);
     }
     catch (ParameterBindingArgumentTransformationException exception2)
     {
         PSInvalidCastException innerException;
         if (exception2.InnerException is ArgumentTransformationMetadataException)
         {
             innerException = exception2.InnerException.InnerException as PSInvalidCastException;
         }
         else
         {
             innerException = exception2.InnerException as PSInvalidCastException;
         }
         if (innerException == null)
         {
             pbex = exception2;
         }
         flag = false;
     }
     catch (ParameterBindingValidationException exception4)
     {
         pbex = exception4;
     }
     catch (ParameterBindingParameterDefaultValueException exception5)
     {
         pbex = exception5;
     }
     catch (ParameterBindingException)
     {
         flag = false;
     }
     if (pbex != null)
     {
         if (!base.DefaultParameterBindingInUse)
         {
             throw pbex;
         }
         base.ThrowElaboratedBindingException(pbex);
     }
     return flag;
 }
 /// <summary>
 /// Passes the binding directly through to the parameter binder.
 /// It does no verification against metadata.
 /// </summary>
 /// <param name="argument">
 /// The name and value of the variable to bind.
 /// </param>
 /// <param name="flags">
 /// Ignored.
 /// </param>
 /// <returns>
 /// True if the parameter was successfully bound. Any error condition
 /// produces an exception.
 /// </returns>
 internal override bool BindParameter(CommandParameterInternal argument, ParameterBindingFlags flags)
 {
     // Just pass the binding straight through.  No metadata to verify the parameter against.
     DefaultParameterBinder.BindParameter(argument.ParameterName, argument.ArgumentValue, parameterMetadata: null);
     return(true);
 }
        /// <summary>
        /// Binds the specified value to the specified parameter
        /// </summary>
        /// 
        /// <param name="parameterValue">
        /// The value to bind to the parameter
        /// </param>
        /// 
        /// <param name="parameter">
        /// The parameter to bind the value to.
        /// </param>
        /// 
        /// <param name="flags">
        /// Parameter binding flags for type coercion and validation.
        /// </param>
        /// 
        /// <returns>
        /// True if the parameter was successfully bound. False if <paramref name="flags"/> 
        /// specifies no coercion and the type does not match the parameter type.
        /// </returns>
        /// 
        /// <exception cref="ParameterBindingParameterDefaultValueException">
        /// If the parameter binder encounters an error getting the default value.
        /// </exception>
        /// 
        private bool BindPipelineParameter(
            object parameterValue,
            MergedCompiledCommandParameter parameter,
            ParameterBindingFlags flags)
        {
            bool result = false;

            if (parameterValue != AutomationNull.Value)
            {
                s_tracer.WriteLine("Adding PipelineParameter name={0}; value={1}",
                                 parameter.Parameter.Name, parameterValue ?? "null");

                // Backup the default value
                BackupDefaultParameter(parameter);

                // Now bind the new value
                CommandParameterInternal param = CommandParameterInternal.CreateParameterWithArgument(
                    PositionUtilities.EmptyExtent, parameter.Parameter.Name, "-" + parameter.Parameter.Name + ":",
                    PositionUtilities.EmptyExtent, parameterValue,
                    false);

                flags = flags & ~ParameterBindingFlags.DelayBindScriptBlock;
                result = BindParameter(_currentParameterSetFlag, param, parameter, flags);

                if (result)
                {
                    // Now make sure to remember that the default value needs to be restored
                    // if we get another pipeline object
                    ParametersBoundThroughPipelineInput.Add(parameter);
                }
            }

            return result;
        }
        private bool BindValueFromPipeline(
            PSObject inputToOperateOn,
            MergedCompiledCommandParameter parameter,
            ParameterBindingFlags flags)
        {
            bool bindResult = false;

            // Attempt binding the value from the pipeline
            // without type coercion

            ParameterBinderBase.bindingTracer.WriteLine(
                ((flags & ParameterBindingFlags.ShouldCoerceType) != 0) ?
                    "Parameter [{0}] PIPELINE INPUT ValueFromPipeline WITH COERCION" :
                    "Parameter [{0}] PIPELINE INPUT ValueFromPipeline NO COERCION",
                parameter.Parameter.Name);

            ParameterBindingException parameterBindingException = null;
            try
            {
                bindResult = BindPipelineParameter(inputToOperateOn, parameter, flags);
            }
            catch (ParameterBindingArgumentTransformationException e)
            {
                PSInvalidCastException invalidCast;
                if (e.InnerException is ArgumentTransformationMetadataException)
                {
                    invalidCast = e.InnerException.InnerException as PSInvalidCastException;
                }
                else
                {
                    invalidCast = e.InnerException as PSInvalidCastException;
                }
                if (invalidCast == null)
                {
                    parameterBindingException = e;
                }
                // Just ignore and continue;
                bindResult = false;
            }
            catch (ParameterBindingValidationException e)
            {
                parameterBindingException = e;
            }
            catch (ParameterBindingParameterDefaultValueException e)
            {
                parameterBindingException = e;
            }
            catch (ParameterBindingException)
            {
                // Just ignore and continue;
                bindResult = false;
            }

            if (parameterBindingException != null)
            {
                if (!DefaultParameterBindingInUse)
                {
                    throw parameterBindingException;
                }
                else
                {
                    ThrowElaboratedBindingException(parameterBindingException);
                }
            }

            return bindResult;
        }
        /// <summary>
        /// Binds the specified argument to the specified parameter using the appropriate
        /// parameter binder. If the argument is of type ScriptBlock and the parameter takes
        /// pipeline input, then the ScriptBlock is saved off in the delay-bind ScriptBlock
        /// container for further processing of pipeline input and is not bound as the argument
        /// to the parameter.
        /// </summary>
        /// 
        /// <param name="parameterSets">
        /// The parameter set used to bind the arguments.
        /// </param>
        /// 
        /// <param name="argument">
        /// The argument to be bound.
        /// </param>
        /// 
        /// <param name="parameter">
        /// The metadata for the parameter to bind the argument to.
        /// </param>
        /// 
        /// <param name="flags">
        /// Flags for type coercion, validation, and script block binding.
        /// 
        /// ParameterBindingFlags.DelayBindScriptBlock:
        /// If set, arguments that are of type ScriptBlock where the parameter is not of type ScriptBlock,
        /// Object, or PSObject will be stored for execution during pipeline input and not bound as
        /// an argument to the parameter.
        /// </param>
        /// 
        /// <returns>
        /// True if the parameter was successfully bound. False if <paramref name="flags"/> 
        /// has the flag <see cref="ParameterBindingFlags.ShouldCoerceType"/> set and the type does not match the parameter type.
        /// </returns>
        /// 
        internal override bool BindParameter(
            uint parameterSets,
            CommandParameterInternal argument,
            MergedCompiledCommandParameter parameter,
            ParameterBindingFlags flags)
        {
            // Now we need to check to see if the argument value is
            // a ScriptBlock.  If it is and the parameter type is
            // not ScriptBlock and not Object, then we need to delay 
            // binding until a pipeline object is provided to invoke 
            // the ScriptBlock.

            // Note: we haven't yet determined that only a single parameter
            // set is valid, so we have to take a best guess on pipeline input
            // based on the current valid parameter sets.

            bool continueWithBinding = true;

            if ((flags & ParameterBindingFlags.DelayBindScriptBlock) != 0 &&
                parameter.Parameter.DoesParameterSetTakePipelineInput(parameterSets) &&
                argument.ArgumentSpecified)
            {
                object argumentValue = argument.ArgumentValue;
                if ((argumentValue is ScriptBlock || argumentValue is DelayedScriptBlockArgument) &&
                    !IsParameterScriptBlockBindable(parameter))
                {
                    // Now check to see if the command expects to have pipeline input.
                    // If not, we should throw an exception now to inform the
                    // user with more information than they would get if it was
                    // considered an unbound mandatory parameter.

                    if (_commandRuntime.IsClosed && _commandRuntime.InputPipe.Empty)
                    {
                        ParameterBindingException bindingException =
                            new ParameterBindingException(
                                    ErrorCategory.MetadataError,
                                    this.Command.MyInvocation,
                                    GetErrorExtent(argument),
                                    parameter.Parameter.Name,
                                    parameter.Parameter.Type,
                                    null,
                                    ParameterBinderStrings.ScriptBlockArgumentNoInput,
                                    "ScriptBlockArgumentNoInput");

                        throw bindingException;
                    }

                    ParameterBinderBase.bindingTracer.WriteLine(
                        "Adding ScriptBlock to delay-bind list for parameter '{0}'",
                        parameter.Parameter.Name);

                    // We need to delay binding of this argument to the parameter

                    DelayedScriptBlockArgument delayedArg = argumentValue as DelayedScriptBlockArgument ??
                                                            new DelayedScriptBlockArgument { _argument = argument, _parameterBinder = this };
                    if (!_delayBindScriptBlocks.ContainsKey(parameter))
                    {
                        _delayBindScriptBlocks.Add(parameter, delayedArg);
                    }

                    // We treat the parameter as bound, but really the
                    // script block gets run for each pipeline object and
                    // the result is bound.

                    if (parameter.Parameter.ParameterSetFlags != 0)
                    {
                        _currentParameterSetFlag &= parameter.Parameter.ParameterSetFlags;
                    }

                    UnboundParameters.Remove(parameter);

                    BoundParameters[parameter.Parameter.Name] = parameter;
                    BoundArguments[parameter.Parameter.Name] = argument;

                    if (DefaultParameterBinder.RecordBoundParameters &&
                        !DefaultParameterBinder.CommandLineParameters.ContainsKey(parameter.Parameter.Name))
                    {
                        DefaultParameterBinder.CommandLineParameters.Add(parameter.Parameter.Name, delayedArg);
                    }

                    continueWithBinding = false;
                }
            }

            bool result = false;
            if (continueWithBinding)
            {
                try
                {
                    result = BindParameter(argument, parameter, flags);
                }
                catch (Exception e)
                {
                    bool rethrow = true;
                    if ((flags & ParameterBindingFlags.ShouldCoerceType) == 0)
                    {
                        // Attributes are used to do type coercion and result in various exceptions.
                        // We assume that if we aren't trying to do type coercion, we should avoid
                        // propagating type conversion exceptions.
                        while (e != null)
                        {
                            if (e is PSInvalidCastException)
                            {
                                rethrow = false;
                                break;
                            }
                            e = e.InnerException;
                        }
                    }
                    if (rethrow)
                    {
                        throw;
                    }
                }
            }

            return result;
        }
        /// <summary>
        /// Bind the argument to the specified parameter
        /// </summary>
        /// 
        /// <param name="parameterSets">
        /// The parameter set used to bind the arguments.
        /// </param>
        /// 
        /// <param name="argument">
        /// The argument to be bound.
        /// </param>
        /// 
        /// <param name="parameter">
        /// The metadata for the parameter to bind the argument to.
        /// </param>
        /// 
        /// <param name="flags">
        /// Flags for type coercion and validation of the arguments.
        /// </param>
        /// 
        /// <returns>
        /// True if the parameter was successfully bound. False if <paramref name="flags"/> 
        /// specifies no type coercion and the type does not match the parameter type.
        /// </returns>
        /// 
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="parameter"/> or <paramref name="argument"/> is null.
        /// </exception>
        /// 
        /// <exception cref="ParameterBindingException">
        /// If argument transformation fails.
        /// or
        /// The argument could not be coerced to the appropriate type for the parameter.
        /// or
        /// The parameter argument transformation, prerequisite, or validation failed.
        /// or
        /// If the binding to the parameter fails.
        /// </exception>
        /// 
        internal virtual bool BindParameter(
            uint parameterSets,
            CommandParameterInternal argument,
            MergedCompiledCommandParameter parameter,
            ParameterBindingFlags flags)
        {
            bool result = false;

            switch (parameter.BinderAssociation)
            {
                case ParameterBinderAssociation.DeclaredFormalParameters:
                    result =
                        this.DefaultParameterBinder.BindParameter(
                            argument,
                            parameter.Parameter,
                            flags);
                    break;

                default:
                    Diagnostics.Assert(
                        false,
                        "Only the formal parameters are available for this type of command");
                    break;
            }

            if (result && ((flags & ParameterBindingFlags.IsDefaultValue) == 0))
            {
                UnboundParameters.Remove(parameter);
                BoundParameters.Add(parameter.Parameter.Name, parameter);
            }
            return result;
        }
        /// <summary>
        /// Bind the argument to the specified parameter
        /// </summary>
        /// 
        /// <param name="argument">
        /// The argument to be bound.
        /// </param>
        /// 
        /// <param name="flags">
        /// The flags for type coercion, validation, and script block binding.
        /// </param>
        /// 
        /// <returns>
        /// True if the parameter was successfully bound. False if <paramref name="flags"/> does not have the
        /// flag <see>ParameterBindingFlags.ShouldCoerceType</see> and the type does not match the parameter type.
        /// </returns>
        /// 
        /// <exception cref="ParameterBindingException">
        /// If argument transformation fails.
        /// or
        /// The argument could not be coerced to the appropriate type for the parameter.
        /// or
        /// The parameter argument transformation, prerequisite, or validation failed.
        /// or
        /// If the binding to the parameter fails.
        /// or
        /// The parameter has already been bound.
        /// </exception>
        /// 
        internal virtual bool BindParameter(
            CommandParameterInternal argument,
            ParameterBindingFlags flags)
        {
            bool result = false;

            MergedCompiledCommandParameter matchingParameter =
                BindableParameters.GetMatchingParameter(
                    argument.ParameterName,
                    (flags & ParameterBindingFlags.ThrowOnParameterNotFound) != 0,
                    true,
                    new InvocationInfo(this.InvocationInfo.MyCommand, argument.ParameterExtent));

            if (matchingParameter != null)
            {
                // Now check to make sure it hasn't already been
                // bound by looking in the boundParameters collection

                if (BoundParameters.ContainsKey(matchingParameter.Parameter.Name))
                {
                    ParameterBindingException bindingException =
                        new ParameterBindingException(
                            ErrorCategory.InvalidArgument,
                            this.InvocationInfo,
                            GetParameterErrorExtent(argument),
                            argument.ParameterName,
                            null,
                            null,
                            ParameterBinderStrings.ParameterAlreadyBound,
                            "ParameterAlreadyBound");


                    throw bindingException;
                }

                flags = flags & ~ParameterBindingFlags.DelayBindScriptBlock;
                result = BindParameter(_currentParameterSetFlag, argument, matchingParameter, flags);
            }

            return result;
        }
 private bool BindPositionalParametersInSet(int validParameterSets, Dictionary<MergedCompiledCommandParameter, PositionalCommandParameter> nextPositionalParameters, CommandParameterInternal argument, ParameterBindingFlags flags, out ParameterBindingException bindingException)
 {
     bool flag = false;
     bindingException = null;
     foreach (PositionalCommandParameter parameter in nextPositionalParameters.Values)
     {
         foreach (ParameterSetSpecificMetadata metadata in parameter.ParameterSetData)
         {
             if (((validParameterSets & metadata.ParameterSetFlag) != 0) || metadata.IsInAllSets)
             {
                 bool flag2 = false;
                 string name = parameter.Parameter.Parameter.Name;
                 ParameterBindingException pbex = null;
                 try
                 {
                     CommandParameterInternal internal2 = CommandParameterInternal.CreateParameterWithArgument(PositionUtilities.EmptyExtent, name, "-" + name + ":", argument.ArgumentExtent, argument.ArgumentValue, false);
                     flag2 = this.BindParameter(validParameterSets, internal2, parameter.Parameter, flags);
                 }
                 catch (ParameterBindingArgumentTransformationException exception2)
                 {
                     pbex = exception2;
                 }
                 catch (ParameterBindingValidationException exception3)
                 {
                     if (exception3.SwallowException)
                     {
                         flag2 = false;
                         bindingException = exception3;
                     }
                     else
                     {
                         pbex = exception3;
                     }
                 }
                 catch (ParameterBindingParameterDefaultValueException exception4)
                 {
                     pbex = exception4;
                 }
                 catch (ParameterBindingException exception5)
                 {
                     flag2 = false;
                     bindingException = exception5;
                 }
                 if (pbex != null)
                 {
                     if (!this.DefaultParameterBindingInUse)
                     {
                         throw pbex;
                     }
                     this.ThrowElaboratedBindingException(pbex);
                 }
                 if (flag2)
                 {
                     flag = true;
                     this.CommandLineParameters.MarkAsBoundPositionally(name);
                     break;
                 }
             }
         }
     }
     return flag;
 }
 internal virtual bool BindParameter(int parameterSets, CommandParameterInternal argument, MergedCompiledCommandParameter parameter, ParameterBindingFlags flags)
 {
     bool flag = false;
     if (parameter.BinderAssociation == ParameterBinderAssociation.DeclaredFormalParameters)
     {
         flag = this.DefaultParameterBinder.BindParameter(argument, parameter.Parameter, flags);
     }
     if (flag && ((flags & ParameterBindingFlags.IsDefaultValue) == ParameterBindingFlags.None))
     {
         this.UnboundParameters.Remove(parameter);
         this.BoundParameters.Add(parameter.Parameter.Name, parameter);
     }
     return flag;
 }
 internal virtual bool BindParameter(CommandParameterInternal argument, ParameterBindingFlags flags)
 {
     bool flag = false;
     MergedCompiledCommandParameter parameter = this.BindableParameters.GetMatchingParameter(argument.ParameterName, (flags & ParameterBindingFlags.ThrowOnParameterNotFound) != ParameterBindingFlags.None, true, new System.Management.Automation.InvocationInfo(this.InvocationInfo.MyCommand, argument.ParameterExtent));
     if (parameter == null)
     {
         return flag;
     }
     if (this.BoundParameters.ContainsKey(parameter.Parameter.Name))
     {
         ParameterBindingException exception = new ParameterBindingException(ErrorCategory.InvalidArgument, this.InvocationInfo, this.GetParameterErrorExtent(argument), argument.ParameterName, null, null, "ParameterBinderStrings", "ParameterAlreadyBound", new object[0]);
         throw exception;
     }
     flags &= ~ParameterBindingFlags.DelayBindScriptBlock;
     return this.BindParameter(this._currentParameterSetFlag, argument, parameter, flags);
 }
Exemple #15
0
 private bool ShouldContinueUncoercedBind(CommandParameterInternal parameter, CompiledCommandParameter parameterMetadata, ParameterBindingFlags flags, ref object parameterValue)
 {
     bool flag = false;
     Type c = parameterMetadata.Type;
     if (parameterValue == null)
     {
         return (((c == null) || ((flags & ParameterBindingFlags.IsDefaultValue) != ParameterBindingFlags.None)) || (!c.IsValueType && (c != typeof(string))));
     }
     Type type = parameterValue.GetType();
     if (type == c)
     {
         return true;
     }
     if (type.IsSubclassOf(c))
     {
         return true;
     }
     if (c.IsAssignableFrom(type))
     {
         return true;
     }
     if ((parameterValue is PSObject) && !((PSObject) parameterValue).immediateBaseObjectIsEmpty)
     {
         parameterValue = ((PSObject) parameterValue).BaseObject;
         type = parameterValue.GetType();
         if (((type == c) || type.IsSubclassOf(c)) || c.IsAssignableFrom(type))
         {
             return true;
         }
     }
     if (parameterMetadata.CollectionTypeInformation.ParameterCollectionType != ParameterCollectionType.NotCollection)
     {
         bool coercionRequired = false;
         object obj2 = this.EncodeCollection(parameter, parameterMetadata.Name, parameterMetadata.CollectionTypeInformation, c, parameterValue, false, out coercionRequired);
         if ((obj2 != null) && !coercionRequired)
         {
             parameterValue = obj2;
             flag = true;
         }
     }
     return flag;
 }
        private bool BindPositionalParametersInSet(
            uint validParameterSets,
            Dictionary<MergedCompiledCommandParameter, PositionalCommandParameter> nextPositionalParameters,
            CommandParameterInternal argument,
            ParameterBindingFlags flags,
            out ParameterBindingException bindingException
            )
        {
            bool result = false;
            bindingException = null;

            foreach (PositionalCommandParameter parameter in nextPositionalParameters.Values)
            {
                foreach (ParameterSetSpecificMetadata parameterSetData in parameter.ParameterSetData)
                {
                    // if the parameter is not in the specified parameter set, don't consider it

                    if ((validParameterSets & parameterSetData.ParameterSetFlag) == 0 &&
                        !parameterSetData.IsInAllSets)
                    {
                        continue;
                    }

                    bool bindResult = false;
                    string parameterName = parameter.Parameter.Parameter.Name;

                    ParameterBindingException parameterBindingExceptionToThrown = null;
                    try
                    {
                        CommandParameterInternal bindableArgument =
                            CommandParameterInternal.CreateParameterWithArgument(
                                PositionUtilities.EmptyExtent, parameterName, "-" + parameterName + ":",
                                argument.ArgumentExtent, argument.ArgumentValue,
                                false);

                        bindResult =
                            BindParameter(
                                validParameterSets,
                                bindableArgument,
                                parameter.Parameter,
                                flags);
                    }
                    catch (ParameterBindingArgumentTransformationException pbex)
                    {
                        parameterBindingExceptionToThrown = pbex;
                    }
                    catch (ParameterBindingValidationException pbex)
                    {
                        if (pbex.SwallowException)
                        {
                            // Just ignore and continue
                            bindResult = false;
                            bindingException = pbex;
                        }
                        else
                        {
                            parameterBindingExceptionToThrown = pbex;
                        }
                    }
                    catch (ParameterBindingParameterDefaultValueException pbex)
                    {
                        parameterBindingExceptionToThrown = pbex;
                    }
                    catch (ParameterBindingException e)
                    {
                        // Just ignore and continue;
                        bindResult = false;
                        bindingException = e;
                    }

                    if (parameterBindingExceptionToThrown != null)
                    {
                        if (!DefaultParameterBindingInUse)
                        {
                            throw parameterBindingExceptionToThrown;
                        }
                        else
                        {
                            ThrowElaboratedBindingException(parameterBindingExceptionToThrown);
                        }
                    }

                    if (bindResult)
                    {
                        result = true;
                        this.CommandLineParameters.MarkAsBoundPositionally(parameterName);
                        break;
                    }
                }
            }
            return result;
        }
 /// <summary>
 /// Passes the binding directly through to the parameter binder.
 /// It does no verification against metadata.
 /// </summary>
 /// 
 /// <param name="argument">
 /// The name and value of the variable to bind.
 /// </param>
 /// 
 /// <param name="flags">
 /// Ignored.
 /// </param>
 /// 
 /// <returns>
 /// True if the parameter was successfully bound. Any error condition
 /// produces an exception.
 /// </returns>
 /// 
 internal override bool BindParameter(CommandParameterInternal argument, ParameterBindingFlags flags)
 {
     // Just pass the binding straight through.  No metadata to verify the parameter against.
     DefaultParameterBinder.BindParameter(argument.ParameterName, argument.ArgumentValue, parameterMetadata: null);
     return true;
 }
        private bool BindParameter(CommandParameterInternal argument, MergedCompiledCommandParameter parameter, ParameterBindingFlags flags)
        {
            bool flag = false;
            switch (parameter.BinderAssociation)
            {
                case ParameterBinderAssociation.DeclaredFormalParameters:
                    flag = base.DefaultParameterBinder.BindParameter(argument, parameter.Parameter, flags);
                    break;

                case ParameterBinderAssociation.DynamicParameters:
                    if (this._dynamicParameterBinder != null)
                    {
                        flag = this._dynamicParameterBinder.BindParameter(argument, parameter.Parameter, flags);
                    }
                    break;

                case ParameterBinderAssociation.CommonParameters:
                    flag = this.CommonParametersBinder.BindParameter(argument, parameter.Parameter, flags);
                    break;

                case ParameterBinderAssociation.ShouldProcessParameters:
                    flag = this.ShouldProcessParametersBinder.BindParameter(argument, parameter.Parameter, flags);
                    break;

                case ParameterBinderAssociation.TransactionParameters:
                    flag = this.TransactionParametersBinder.BindParameter(argument, parameter.Parameter, flags);
                    break;

                case ParameterBinderAssociation.PagingParameters:
                    flag = this.PagingParametersBinder.BindParameter(argument, parameter.Parameter, flags);
                    break;
            }
            if (flag && ((flags & ParameterBindingFlags.IsDefaultValue) == ParameterBindingFlags.None))
            {
                if (parameter.Parameter.ParameterSetFlags != 0)
                {
                    base._currentParameterSetFlag &= parameter.Parameter.ParameterSetFlags;
                }
                base.UnboundParameters.Remove(parameter);
                if (!base.BoundParameters.ContainsKey(parameter.Parameter.Name))
                {
                    base.BoundParameters.Add(parameter.Parameter.Name, parameter);
                }
                if (!base.BoundArguments.ContainsKey(parameter.Parameter.Name))
                {
                    base.BoundArguments.Add(parameter.Parameter.Name, argument);
                }
            }
            return flag;
        }
        /// <summary>
        /// Binds the specified argument to the specified parameter using the appropriate
        /// parameter binder.
        /// </summary>
        /// 
        /// <param name="argument">
        /// The argument to be bound.
        /// </param>
        /// 
        /// <param name="parameter">
        /// The metadata for the parameter to bind the argument to.
        /// </param>
        /// 
        /// <param name="flags">
        /// Flags for type coercion and validation.
        /// </param>
        /// 
        /// <returns>
        /// True if the parameter was successfully bound. False if <paramref name="flags"/> 
        /// has the flag <see cref="ParameterBindingFlags.ShouldCoerceType"/> set and the type does not match the parameter type.
        /// </returns>
        /// 
        private bool BindParameter(
            CommandParameterInternal argument,
            MergedCompiledCommandParameter parameter,
            ParameterBindingFlags flags)
        {
            bool result = false;

            switch (parameter.BinderAssociation)
            {
                case ParameterBinderAssociation.DeclaredFormalParameters:
                    result =
                        DefaultParameterBinder.BindParameter(
                            argument,
                            parameter.Parameter,
                            flags);
                    break;

                case ParameterBinderAssociation.CommonParameters:
                    result =
                        CommonParametersBinder.BindParameter(
                            argument,
                            parameter.Parameter,
                            flags);
                    break;

                case ParameterBinderAssociation.ShouldProcessParameters:
                    Diagnostics.Assert(
                        _commandMetadata.SupportsShouldProcess,
                        "The metadata for the ShouldProcessParameters should only be available if the command supports ShouldProcess");

                    result =
                        ShouldProcessParametersBinder.BindParameter(
                            argument,
                            parameter.Parameter,
                            flags);
                    break;

                case ParameterBinderAssociation.PagingParameters:
                    Diagnostics.Assert(
                        _commandMetadata.SupportsPaging,
                        "The metadata for the PagingParameters should only be available if the command supports paging");

                    result =
                        PagingParametersBinder.BindParameter(
                            argument,
                            parameter.Parameter,
                            flags);
                    break;

                case ParameterBinderAssociation.TransactionParameters:
                    Diagnostics.Assert(
                        _commandMetadata.SupportsTransactions,
                        "The metadata for the TransactionsParameters should only be available if the command supports transactions");

                    result =
                        TransactionParametersBinder.BindParameter(
                            argument,
                            parameter.Parameter,
                            flags);
                    break;

                case ParameterBinderAssociation.DynamicParameters:
                    Diagnostics.Assert(
                        _commandMetadata.ImplementsDynamicParameters,
                        "The metadata for the dynamic parameters should only be available if the command supports IDynamicParameters");

                    if (_dynamicParameterBinder != null)
                    {
                        result =
                            _dynamicParameterBinder.BindParameter(
                                argument,
                                parameter.Parameter,
                                flags);
                    }
                    break;
            }

            if (result && ((flags & ParameterBindingFlags.IsDefaultValue) == 0))
            {
                // Update the current valid parameter set flags

                if (parameter.Parameter.ParameterSetFlags != 0)
                {
                    _currentParameterSetFlag &= parameter.Parameter.ParameterSetFlags;
                }

                UnboundParameters.Remove(parameter);

                if (!BoundParameters.ContainsKey(parameter.Parameter.Name))
                {
                    BoundParameters.Add(parameter.Parameter.Name, parameter);
                }

                if (!BoundArguments.ContainsKey(parameter.Parameter.Name))
                {
                    BoundArguments.Add(parameter.Parameter.Name, argument);
                }

                if (parameter.Parameter.ObsoleteAttribute != null &&
                    (flags & ParameterBindingFlags.IsDefaultValue) == 0 &&
                    !BoundObsoleteParameterNames.Contains(parameter.Parameter.Name))
                {
                    string obsoleteWarning = String.Format(
                        CultureInfo.InvariantCulture,
                        ParameterBinderStrings.UseOfDeprecatedParameterWarning,
                        parameter.Parameter.Name,
                        parameter.Parameter.ObsoleteAttribute.Message);
                    var warningRecord = new WarningRecord(ParameterBinderBase.FQIDParameterObsolete, obsoleteWarning);

                    BoundObsoleteParameterNames.Add(parameter.Parameter.Name);

                    if (ObsoleteParameterWarningList == null)
                        ObsoleteParameterWarningList = new List<WarningRecord>();

                    ObsoleteParameterWarningList.Add(warningRecord);
                }
            }

            return result;
        }
 internal override bool BindParameter(int parameterSets, CommandParameterInternal argument, MergedCompiledCommandParameter parameter, ParameterBindingFlags flags)
 {
     bool flag = true;
     if ((((flags & ParameterBindingFlags.DelayBindScriptBlock) != ParameterBindingFlags.None) && parameter.Parameter.DoesParameterSetTakePipelineInput(parameterSets)) && argument.ArgumentSpecified)
     {
         object argumentValue = argument.ArgumentValue;
         if (((argumentValue is ScriptBlock) || (argumentValue is DelayedScriptBlockArgument)) && !IsParameterScriptBlockBindable(parameter))
         {
             if (this._commandRuntime.IsClosed && this._commandRuntime.InputPipe.Empty)
             {
                 ParameterBindingException exception = new ParameterBindingException(ErrorCategory.MetadataError, this.Command.MyInvocation, base.GetErrorExtent(argument), parameter.Parameter.Name, parameter.Parameter.Type, null, "ParameterBinderStrings", "ScriptBlockArgumentNoInput", new object[0]);
                 throw exception;
             }
             ParameterBinderBase.bindingTracer.WriteLine("Adding ScriptBlock to delay-bind list for parameter '{0}'", new object[] { parameter.Parameter.Name });
             DelayedScriptBlockArgument argument2 = argumentValue as DelayedScriptBlockArgument;
             if (argument2 == null)
             {
                 argument2 = new DelayedScriptBlockArgument
                 {
                     _argument = argument,
                     _parameterBinder = this
                 };
             }
             if (!this._delayBindScriptBlocks.ContainsKey(parameter))
             {
                 this._delayBindScriptBlocks.Add(parameter, argument2);
             }
             if (parameter.Parameter.ParameterSetFlags != 0)
             {
                 base._currentParameterSetFlag &= parameter.Parameter.ParameterSetFlags;
             }
             base.UnboundParameters.Remove(parameter);
             if (!base.BoundParameters.ContainsKey(parameter.Parameter.Name))
             {
                 base.BoundParameters.Add(parameter.Parameter.Name, parameter);
             }
             if (!base.BoundArguments.ContainsKey(parameter.Parameter.Name))
             {
                 base.BoundArguments.Add(parameter.Parameter.Name, argument);
             }
             if (base.DefaultParameterBinder.RecordBoundParameters && !base.DefaultParameterBinder.CommandLineParameters.ContainsKey(parameter.Parameter.Name))
             {
                 base.DefaultParameterBinder.CommandLineParameters.Add(parameter.Parameter.Name, argument2);
             }
             flag = false;
         }
     }
     bool flag2 = false;
     if (flag)
     {
         try
         {
             flag2 = this.BindParameter(argument, parameter, flags);
         }
         catch (Exception innerException)
         {
             bool flag3 = true;
             if ((flags & ParameterBindingFlags.ShouldCoerceType) == ParameterBindingFlags.None)
             {
                 while (innerException != null)
                 {
                     if (innerException is PSInvalidCastException)
                     {
                         flag3 = false;
                         break;
                     }
                     innerException = innerException.InnerException;
                 }
             }
             if (flag3)
             {
                 throw;
             }
         }
     }
     return flag2;
 }
        private bool BindValueFromPipelineByPropertyName(
            PSObject inputToOperateOn,
            MergedCompiledCommandParameter parameter,
            ParameterBindingFlags flags)
        {
            bool bindResult = false;

            ParameterBinderBase.bindingTracer.WriteLine(
                ((flags & ParameterBindingFlags.ShouldCoerceType) != 0) ?
                    "Parameter [{0}] PIPELINE INPUT ValueFromPipelineByPropertyName WITH COERCION" :
                    "Parameter [{0}] PIPELINE INPUT ValueFromPipelineByPropertyName NO COERCION",
                parameter.Parameter.Name);

            PSMemberInfo member = inputToOperateOn.Properties[parameter.Parameter.Name];

            if (member == null)
            {
                // Since a member matching the name of the parameter wasn't found,
                // check the aliases.

                foreach (string alias in parameter.Parameter.Aliases)
                {
                    member = inputToOperateOn.Properties[alias];

                    if (member != null)
                    {
                        break;
                    }
                }
            }

            if (member != null)
            {
                ParameterBindingException parameterBindingException = null;
                try
                {
                    bindResult =
                        BindPipelineParameter(
                            member.Value,
                            parameter,
                            flags);
                }
                catch (ParameterBindingArgumentTransformationException e)
                {
                    parameterBindingException = e;
                }
                catch (ParameterBindingValidationException e)
                {
                    parameterBindingException = e;
                }
                catch (ParameterBindingParameterDefaultValueException e)
                {
                    parameterBindingException = e;
                }
                catch (ParameterBindingException)
                {
                    // Just ignore and continue;
                    bindResult = false;
                }

                if (parameterBindingException != null)
                {
                    if (!DefaultParameterBindingInUse)
                    {
                        throw parameterBindingException;
                    }
                    else
                    {
                        ThrowElaboratedBindingException(parameterBindingException);
                    }
                }
            }

            return bindResult;
        }
 private bool BindPipelineParameter(object parameterValue, MergedCompiledCommandParameter parameter, ParameterBindingFlags flags)
 {
     bool flag = false;
     if (parameterValue != AutomationNull.Value)
     {
         object[] args = new object[] { parameter.Parameter.Name, parameterValue ?? "null" };
         _tracer.WriteLine("Adding PipelineParameter name={0}; value={1}", args);
         this.BackupDefaultParameter(parameter);
         CommandParameterInternal argument = CommandParameterInternal.CreateParameterWithArgument(PositionUtilities.EmptyExtent, parameter.Parameter.Name, "-" + parameter.Parameter.Name + ":", PositionUtilities.EmptyExtent, parameterValue, false);
         flags &= ~ParameterBindingFlags.DelayBindScriptBlock;
         flag = this.BindParameter(base._currentParameterSetFlag, argument, parameter, flags);
         if (flag)
         {
             base.ParametersBoundThroughPipelineInput.Add(parameter);
         }
     }
     return flag;
 }
 internal override bool BindParameter(CommandParameterInternal argument, ParameterBindingFlags flags)
 {
     base.DefaultParameterBinder.BindParameter(argument.ParameterName, argument.ArgumentValue);
     return true;
 }
Exemple #24
0
 internal override bool BindParameter(CommandParameterInternal argument, ParameterBindingFlags flags)
 {
     base.DefaultParameterBinder.BindParameter(argument.ParameterName, argument.ArgumentValue);
     return(true);
 }