internal CompiledCommandParameter(MemberInfo member, bool processingDynamicParameters)
 {
     this.name = string.Empty;
     this.typeName = string.Empty;
     this.argumentTransformationAttributes = new Collection<ArgumentTransformationAttribute>();
     this.validationAttributes = new Collection<ValidateArgumentsAttribute>();
     this.aliases = new Collection<string>();
     if (member == null)
     {
         throw PSTraceSource.NewArgumentNullException("member");
     }
     this.name = member.Name;
     this.declaringType = member.DeclaringType;
     this.isDynamic = processingDynamicParameters;
     if (member.MemberType == MemberTypes.Property)
     {
         this.type = ((PropertyInfo) member).PropertyType;
     }
     else
     {
         if (member.MemberType != MemberTypes.Field)
         {
             throw PSTraceSource.NewArgumentException("member", "DiscoveryExceptions", "CompiledCommandParameterMemberMustBeFieldOrProperty", new object[0]);
         }
         this.type = ((FieldInfo) member).FieldType;
     }
     this.collectionTypeInformation = new ParameterCollectionTypeInformation(this.type);
     this.ConstructCompiledAttributesUsingReflection(member);
 }
Exemple #2
0
 internal CompiledCommandParameter(MemberInfo member, bool processingDynamicParameters)
 {
     this.name     = string.Empty;
     this.typeName = string.Empty;
     this.argumentTransformationAttributes = new Collection <ArgumentTransformationAttribute>();
     this.validationAttributes             = new Collection <ValidateArgumentsAttribute>();
     this.aliases = new Collection <string>();
     if (member == null)
     {
         throw PSTraceSource.NewArgumentNullException("member");
     }
     this.name          = member.Name;
     this.declaringType = member.DeclaringType;
     this.isDynamic     = processingDynamicParameters;
     if (member.MemberType == MemberTypes.Property)
     {
         this.type = ((PropertyInfo)member).PropertyType;
     }
     else
     {
         if (member.MemberType != MemberTypes.Field)
         {
             throw PSTraceSource.NewArgumentException("member", "DiscoveryExceptions", "CompiledCommandParameterMemberMustBeFieldOrProperty", new object[0]);
         }
         this.type = ((FieldInfo)member).FieldType;
     }
     this.collectionTypeInformation = new ParameterCollectionTypeInformation(this.type);
     this.ConstructCompiledAttributesUsingReflection(member);
 }
Exemple #3
0
 internal CompiledCommandParameter(
     RuntimeDefinedParameter runtimeDefinedParameter,
     bool processingDynamicParameters)
 {
     this.name      = runtimeDefinedParameter != null ? runtimeDefinedParameter.Name : throw CompiledCommandParameter.tracer.NewArgumentNullException(nameof(runtimeDefinedParameter));
     this.type      = runtimeDefinedParameter.ParameterType;
     this.isDynamic = processingDynamicParameters;
     this.collectionTypeInformation = new ParameterCollectionTypeInformation(runtimeDefinedParameter.ParameterType);
     this.ConstructCompiledAttributesUsingRuntimeDefinedParameter(runtimeDefinedParameter);
 }
Exemple #4
0
 internal CompiledCommandParameter(RuntimeDefinedParameter runtimeDefinedParameter, bool processingDynamicParameters)
 {
     this.name     = string.Empty;
     this.typeName = string.Empty;
     this.argumentTransformationAttributes = new Collection <ArgumentTransformationAttribute>();
     this.validationAttributes             = new Collection <ValidateArgumentsAttribute>();
     this.aliases = new Collection <string>();
     if (runtimeDefinedParameter == null)
     {
         throw PSTraceSource.NewArgumentNullException("runtimeDefinedParameter");
     }
     this.name      = runtimeDefinedParameter.Name;
     this.type      = runtimeDefinedParameter.ParameterType;
     this.isDynamic = processingDynamicParameters;
     this.collectionTypeInformation = new ParameterCollectionTypeInformation(runtimeDefinedParameter.ParameterType);
     this.ConstructCompiledAttributesUsingRuntimeDefinedParameter(runtimeDefinedParameter);
 }
 internal CompiledCommandParameter(RuntimeDefinedParameter runtimeDefinedParameter, bool processingDynamicParameters)
 {
     this.name = string.Empty;
     this.typeName = string.Empty;
     this.argumentTransformationAttributes = new Collection<ArgumentTransformationAttribute>();
     this.validationAttributes = new Collection<ValidateArgumentsAttribute>();
     this.aliases = new Collection<string>();
     if (runtimeDefinedParameter == null)
     {
         throw PSTraceSource.NewArgumentNullException("runtimeDefinedParameter");
     }
     this.name = runtimeDefinedParameter.Name;
     this.type = runtimeDefinedParameter.ParameterType;
     this.isDynamic = processingDynamicParameters;
     this.collectionTypeInformation = new ParameterCollectionTypeInformation(runtimeDefinedParameter.ParameterType);
     this.ConstructCompiledAttributesUsingRuntimeDefinedParameter(runtimeDefinedParameter);
 }
Exemple #6
0
 internal CompiledCommandParameter(MemberInfo member, bool processingDynamicParameters)
 {
     this.name          = member != null ? member.Name : throw CompiledCommandParameter.tracer.NewArgumentNullException(nameof(member));
     this.declaringType = member.DeclaringType;
     this.isDynamic     = processingDynamicParameters;
     if (member.MemberType == MemberTypes.Property)
     {
         this.type = ((PropertyInfo)member).PropertyType;
     }
     else if (member.MemberType == MemberTypes.Field)
     {
         this.type = ((FieldInfo)member).FieldType;
     }
     else
     {
         ArgumentException argumentException = (ArgumentException)CompiledCommandParameter.tracer.NewArgumentException(nameof(member), "DiscoveryExceptions", "CompiledCommandParameterMemberMustBeFieldOrProperty");
         CompiledCommandParameter.tracer.TraceException((Exception)argumentException);
         throw argumentException;
     }
     this.collectionTypeInformation = new ParameterCollectionTypeInformation(this.type);
     this.ConstructCompiledAttributesUsingReflection(member);
 }
        internal object Transform(EngineIntrinsics engineIntrinsics, object inputData, bool bindingParameters, bool bindingScriptCmdlet)
        {
            if (_convertTypes == null)
            {
                return(inputData);
            }

            object result = inputData;

            try
            {
                for (int i = 0; i < _convertTypes.Length; i++)
                {
                    if (bindingParameters)
                    {
                        // We should not be doing a conversion here if [ref] is the last type.
                        // When [ref] appears in an argument list, it is used for checking only.
                        // No Conversion should be done.
                        if (_convertTypes[i].Equals(typeof(System.Management.Automation.PSReference)))
                        {
                            object   temp;
                            PSObject mshObject = result as PSObject;
                            if (mshObject != null)
                            {
                                temp = mshObject.BaseObject;
                            }
                            else
                            {
                                temp = result;
                            }

                            PSReference reference = temp as PSReference;

                            if (reference == null)
                            {
                                throw new PSInvalidCastException("InvalidCastExceptionReferenceTypeExpected", null,
                                                                 ExtendedTypeSystem.ReferenceTypeExpected);
                            }
                        }
                        else
                        {
                            object   temp;
                            PSObject mshObject = result as PSObject;
                            if (mshObject != null)
                            {
                                temp = mshObject.BaseObject;
                            }
                            else
                            {
                                temp = result;
                            }

                            // If a non-ref type is expected but currently passed in is a ref, do an implicit dereference.
                            PSReference reference = temp as PSReference;

                            if (reference != null)
                            {
                                result = reference.Value;
                            }

                            if (bindingScriptCmdlet && _convertTypes[i] == typeof(string))
                            {
                                // Don't allow conversion from array to string in script w/ cmdlet binding.  Allow
                                // the conversion for ordinary script parameter binding for V1 compatibility.
                                temp = PSObject.Base(result);
                                if (temp != null && temp.GetType().IsArray)
                                {
                                    throw new PSInvalidCastException("InvalidCastFromAnyTypeToString", null,
                                                                     ExtendedTypeSystem.InvalidCastCannotRetrieveString);
                                }
                            }
                        }
                    }

                    //BUGBUG
                    //NTRAID#Windows Out of Band Releases - 930116 - 03/14/06
                    //handling special case for boolean, switchparameter and Nullable<bool>
                    //These parameter types will not be converted if the incoming value types are not
                    //one of the accepted categories - $true/$false or numbers (0 or otherwise)
                    if (LanguagePrimitives.IsBoolOrSwitchParameterType(_convertTypes[i]))
                    {
                        CheckBoolValue(result, _convertTypes[i]);
                    }

                    if (bindingScriptCmdlet)
                    {
                        // Check for conversion to something like bool[] or ICollection<bool>, but only for cmdlet binding
                        // to stay compatible with V1.
                        ParameterCollectionTypeInformation collectionTypeInfo = new ParameterCollectionTypeInformation(_convertTypes[i]);
                        if (collectionTypeInfo.ParameterCollectionType != ParameterCollectionType.NotCollection &&
                            LanguagePrimitives.IsBoolOrSwitchParameterType(collectionTypeInfo.ElementType))
                        {
                            IList currentValueAsIList = ParameterBinderBase.GetIList(result);
                            if (currentValueAsIList != null)
                            {
                                foreach (object val in currentValueAsIList)
                                {
                                    CheckBoolValue(val, collectionTypeInfo.ElementType);
                                }
                            }
                            else
                            {
                                CheckBoolValue(result, collectionTypeInfo.ElementType);
                            }
                        }
                    }

                    result = LanguagePrimitives.ConvertTo(result, _convertTypes[i], CultureInfo.InvariantCulture);

                    // Do validation of invalid direct variable assignments which are allowed to
                    // be used for parameters.
                    //
                    // Note - this is duplicated in ExecutionContext.cs as parameter binding for script cmdlets can avoid this code path.
                    if ((!bindingScriptCmdlet) && (!bindingParameters))
                    {
                        // ActionPreference of Suspend is not supported as a preference variable. We can only block "Suspend"
                        // during variable assignment (here) - "Ignore" is blocked during variable retrieval.
                        if (_convertTypes[i] == typeof(ActionPreference))
                        {
                            ActionPreference resultPreference = (ActionPreference)result;

                            if (resultPreference == ActionPreference.Suspend)
                            {
                                throw new PSInvalidCastException("InvalidActionPreference", null, ErrorPackage.UnsupportedPreferenceVariable, resultPreference);
                            }
                        }
                    }
                }
            }
            catch (PSInvalidCastException e)
            {
                throw new ArgumentTransformationMetadataException(e.Message, e);
            }

            return(result);
        }
Exemple #8
0
 private object EncodeCollection(CommandParameterInternal argument, string parameterName, ParameterCollectionTypeInformation collectionTypeInformation, Type toType, object currentValue, bool coerceElementTypeIfNeeded, out bool coercionRequired)
 {
     object obj2 = null;
     coercionRequired = false;
     bindingTracer.WriteLine("Binding collection parameter {0}: argument type [{1}], parameter type [{2}], collection type {3}, element type [{4}], {5}", new object[] { parameterName, (currentValue == null) ? "null" : currentValue.GetType().Name, toType, collectionTypeInformation.ParameterCollectionType, collectionTypeInformation.ElementType, coerceElementTypeIfNeeded ? "coerceElementType" : "no coerceElementType" });
     if (currentValue != null)
     {
         int length = 1;
         Type elementType = collectionTypeInformation.ElementType;
         IList iList = GetIList(currentValue);
         if (iList != null)
         {
             length = iList.Count;
             tracer.WriteLine("current value is an IList with {0} elements", new object[] { length });
             bindingTracer.WriteLine("Arg is IList with {0} elements", new object[] { length });
         }
         object obj3 = null;
         IList list2 = null;
         MethodInfo info = null;
         bool flag = toType == typeof(Array);
         if ((collectionTypeInformation.ParameterCollectionType == ParameterCollectionType.Array) || flag)
         {
             if (flag)
             {
                 elementType = typeof(object);
             }
             bindingTracer.WriteLine("Creating array with element type [{0}] and {1} elements", new object[] { elementType, length });
             obj3 = list2 = Array.CreateInstance(elementType, length);
         }
         else
         {
             if ((collectionTypeInformation.ParameterCollectionType != ParameterCollectionType.IList) && (collectionTypeInformation.ParameterCollectionType != ParameterCollectionType.ICollectionGeneric))
             {
                 return obj2;
             }
             bindingTracer.WriteLine("Creating collection [{0}]", new object[] { toType });
             bool flag2 = false;
             Exception innerException = null;
             try
             {
                 obj3 = Activator.CreateInstance(toType, BindingFlags.Default, null, new object[0], CultureInfo.InvariantCulture);
                 if (collectionTypeInformation.ParameterCollectionType == ParameterCollectionType.IList)
                 {
                     list2 = (IList) obj3;
                 }
                 else
                 {
                     Type type2 = collectionTypeInformation.ElementType;
                     BindingFlags bindingAttr = BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance;
                     Exception exception2 = null;
                     try
                     {
                         info = toType.GetMethod("Add", bindingAttr, null, new Type[] { type2 }, null);
                     }
                     catch (AmbiguousMatchException exception3)
                     {
                         bindingTracer.WriteLine("Ambiguous match to Add(T) for type " + toType.FullName + ": " + exception3.Message, new object[0]);
                         exception2 = exception3;
                     }
                     catch (ArgumentException exception4)
                     {
                         bindingTracer.WriteLine("ArgumentException matching Add(T) for type " + toType.FullName + ": " + exception4.Message, new object[0]);
                         exception2 = exception4;
                     }
                     if (null == info)
                     {
                         ParameterBindingException exception5 = new ParameterBindingException(exception2, ErrorCategory.InvalidArgument, this.InvocationInfo, this.GetErrorExtent(argument), parameterName, toType, (currentValue == null) ? null : currentValue.GetType(), "ParameterBinderStrings", "CannotExtractAddMethod", new object[] { (exception2 == null) ? "" : exception2.Message });
                         throw exception5;
                     }
                 }
             }
             catch (ArgumentException exception6)
             {
                 flag2 = true;
                 innerException = exception6;
             }
             catch (NotSupportedException exception7)
             {
                 flag2 = true;
                 innerException = exception7;
             }
             catch (TargetInvocationException exception8)
             {
                 flag2 = true;
                 innerException = exception8;
             }
             catch (MethodAccessException exception9)
             {
                 flag2 = true;
                 innerException = exception9;
             }
             catch (MemberAccessException exception10)
             {
                 flag2 = true;
                 innerException = exception10;
             }
             catch (InvalidComObjectException exception11)
             {
                 flag2 = true;
                 innerException = exception11;
             }
             catch (COMException exception12)
             {
                 flag2 = true;
                 innerException = exception12;
             }
             catch (TypeLoadException exception13)
             {
                 flag2 = true;
                 innerException = exception13;
             }
             if (flag2)
             {
                 ParameterBindingException exception14 = new ParameterBindingException(innerException, ErrorCategory.InvalidArgument, this.InvocationInfo, this.GetErrorExtent(argument), parameterName, toType, currentValue.GetType(), "ParameterBinderStrings", "CannotConvertArgument", new object[] { (obj2 == null) ? "null" : obj2, (innerException == null) ? "" : innerException.Message });
                 throw exception14;
             }
         }
         if (iList != null)
         {
             int num2 = 0;
             bindingTracer.WriteLine("Argument type {0} is IList", new object[] { currentValue.GetType() });
             foreach (object obj4 in iList)
             {
                 object obj5 = PSObject.Base(obj4);
                 if (coerceElementTypeIfNeeded)
                 {
                     bindingTracer.WriteLine("COERCE collection element from type {0} to type {1}", new object[] { (obj4 == null) ? "null" : obj4.GetType().Name, elementType });
                     obj5 = this.CoerceTypeAsNeeded(argument, parameterName, elementType, null, obj4);
                 }
                 else if ((null != elementType) && (obj5 != null))
                 {
                     Type type = obj5.GetType();
                     Type c = elementType;
                     if ((type != c) && !type.IsSubclassOf(c))
                     {
                         bindingTracer.WriteLine("COERCION REQUIRED: Did not attempt to coerce collection element from type {0} to type {1}", new object[] { (obj4 == null) ? "null" : obj4.GetType().Name, elementType });
                         coercionRequired = true;
                         break;
                     }
                 }
                 try
                 {
                     if ((collectionTypeInformation.ParameterCollectionType == ParameterCollectionType.Array) || flag)
                     {
                         bindingTracer.WriteLine("Adding element of type {0} to array position {1}", new object[] { (obj5 == null) ? "null" : obj5.GetType().Name, num2 });
                         list2[num2++] = obj5;
                     }
                     else if (collectionTypeInformation.ParameterCollectionType == ParameterCollectionType.IList)
                     {
                         bindingTracer.WriteLine("Adding element of type {0} via IList.Add", new object[] { (obj5 == null) ? "null" : obj5.GetType().Name });
                         list2.Add(obj5);
                     }
                     else
                     {
                         bindingTracer.WriteLine("Adding element of type {0} via ICollection<T>::Add()", new object[] { (obj5 == null) ? "null" : obj5.GetType().Name });
                         info.Invoke(obj3, new object[] { obj5 });
                     }
                 }
                 catch (Exception exception15)
                 {
                     CommandProcessorBase.CheckForSevereException(exception15);
                     if ((exception15 is TargetInvocationException) && (exception15.InnerException != null))
                     {
                         exception15 = exception15.InnerException;
                     }
                     ParameterBindingException exception16 = new ParameterBindingException(exception15, ErrorCategory.InvalidArgument, this.InvocationInfo, this.GetErrorExtent(argument), parameterName, toType, (obj5 == null) ? null : obj5.GetType(), "ParameterBinderStrings", "CannotConvertArgument", new object[] { (obj5 == null) ? "null" : obj5, exception15.Message });
                     throw exception16;
                 }
             }
         }
         else
         {
             bindingTracer.WriteLine("Argument type {0} is not IList, treating this as scalar", new object[] { (currentValue == null) ? "null" : currentValue.GetType().Name });
             if (elementType != null)
             {
                 if (coerceElementTypeIfNeeded)
                 {
                     bindingTracer.WriteLine("Coercing scalar arg value to type {0}", new object[] { elementType });
                     currentValue = this.CoerceTypeAsNeeded(argument, parameterName, elementType, null, currentValue);
                 }
                 else
                 {
                     Type type5 = currentValue.GetType();
                     Type type6 = elementType;
                     if ((type5 != type6) && !type5.IsSubclassOf(type6))
                     {
                         bindingTracer.WriteLine("COERCION REQUIRED: Did not coerce scalar arg value to type {1}", new object[] { elementType });
                         coercionRequired = true;
                         return obj2;
                     }
                 }
             }
             try
             {
                 if ((collectionTypeInformation.ParameterCollectionType == ParameterCollectionType.Array) || flag)
                 {
                     bindingTracer.WriteLine("Adding scalar element of type {0} to array position {1}", new object[] { (currentValue == null) ? "null" : currentValue.GetType().Name, 0 });
                     list2[0] = currentValue;
                 }
                 else if (collectionTypeInformation.ParameterCollectionType == ParameterCollectionType.IList)
                 {
                     bindingTracer.WriteLine("Adding scalar element of type {0} via IList.Add", new object[] { (currentValue == null) ? "null" : currentValue.GetType().Name });
                     list2.Add(currentValue);
                 }
                 else
                 {
                     bindingTracer.WriteLine("Adding scalar element of type {0} via ICollection<T>::Add()", new object[] { (currentValue == null) ? "null" : currentValue.GetType().Name });
                     info.Invoke(obj3, new object[] { currentValue });
                 }
             }
             catch (Exception exception17)
             {
                 CommandProcessorBase.CheckForSevereException(exception17);
                 if ((exception17 is TargetInvocationException) && (exception17.InnerException != null))
                 {
                     exception17 = exception17.InnerException;
                 }
                 ParameterBindingException exception18 = new ParameterBindingException(exception17, ErrorCategory.InvalidArgument, this.InvocationInfo, this.GetErrorExtent(argument), parameterName, toType, (currentValue == null) ? null : currentValue.GetType(), "ParameterBinderStrings", "CannotConvertArgument", new object[] { (currentValue == null) ? "null" : currentValue, exception17.Message });
                 throw exception18;
             }
         }
         if (!coercionRequired)
         {
             obj2 = obj3;
         }
     }
     return obj2;
 }
Exemple #9
0
 private object CoerceTypeAsNeeded(CommandParameterInternal argument, string parameterName, Type toType, ParameterCollectionTypeInformation collectionTypeInfo, object currentValue)
 {
     if (argument == null)
     {
         throw PSTraceSource.NewArgumentNullException("argument");
     }
     if (toType == null)
     {
         throw PSTraceSource.NewArgumentNullException("toType");
     }
     if (collectionTypeInfo == null)
     {
         collectionTypeInfo = new ParameterCollectionTypeInformation(toType);
     }
     object result = currentValue;
     using (bindingTracer.TraceScope("COERCE arg to [{0}]", new object[] { toType }))
     {
         Type c = null;
         try
         {
             if (IsNullParameterValue(currentValue))
             {
                 return this.HandleNullParameterForSpecialTypes(argument, parameterName, toType, currentValue);
             }
             c = currentValue.GetType();
             if (toType.IsAssignableFrom(c))
             {
                 bindingTracer.WriteLine("Parameter and arg types the same, no coercion is needed.", new object[0]);
                 return currentValue;
             }
             bindingTracer.WriteLine("Trying to convert argument value from {0} to {1}", new object[] { c, toType });
             if (toType == typeof(PSObject))
             {
                 if ((this.command != null) && (currentValue == this.command.CurrentPipelineObject.BaseObject))
                 {
                     currentValue = this.command.CurrentPipelineObject;
                 }
                 bindingTracer.WriteLine("The parameter is of type [{0}] and the argument is an PSObject, so the parameter value is the argument value wrapped into an PSObject.", new object[] { toType });
                 return LanguagePrimitives.AsPSObjectOrNull(currentValue);
             }
             if ((toType == typeof(string)) && (c == typeof(PSObject)))
             {
                 PSObject obj3 = (PSObject) currentValue;
                 if (obj3 == AutomationNull.Value)
                 {
                     bindingTracer.WriteLine("CONVERT a null PSObject to a null string.", new object[0]);
                     return null;
                 }
             }
             if (((toType == typeof(bool)) || (toType == typeof(SwitchParameter))) || (toType == typeof(bool?)))
             {
                 Type type = null;
                 if (c == typeof(PSObject))
                 {
                     PSObject obj4 = (PSObject) currentValue;
                     currentValue = obj4.BaseObject;
                     if (currentValue is SwitchParameter)
                     {
                         SwitchParameter parameter = (SwitchParameter) currentValue;
                         currentValue = parameter.IsPresent;
                     }
                     type = currentValue.GetType();
                 }
                 else
                 {
                     type = c;
                 }
                 if (type == typeof(bool))
                 {
                     if (LanguagePrimitives.IsBooleanType(toType))
                     {
                         return ParserOps.BoolToObject((bool) currentValue);
                     }
                     return new SwitchParameter((bool) currentValue);
                 }
                 if (type == typeof(int))
                 {
                     if (((int) LanguagePrimitives.ConvertTo(currentValue, typeof(int), CultureInfo.InvariantCulture)) != 0)
                     {
                         if (LanguagePrimitives.IsBooleanType(toType))
                         {
                             return ParserOps.BoolToObject(true);
                         }
                         return new SwitchParameter(true);
                     }
                     if (LanguagePrimitives.IsBooleanType(toType))
                     {
                         return ParserOps.BoolToObject(false);
                     }
                     return new SwitchParameter(false);
                 }
                 if (LanguagePrimitives.IsNumeric(Type.GetTypeCode(type)))
                 {
                     double num = (double) LanguagePrimitives.ConvertTo(currentValue, typeof(double), CultureInfo.InvariantCulture);
                     if (num == 0.0)
                     {
                         if (LanguagePrimitives.IsBooleanType(toType))
                         {
                             return ParserOps.BoolToObject(false);
                         }
                         return new SwitchParameter(false);
                     }
                     if (LanguagePrimitives.IsBooleanType(toType))
                     {
                         return ParserOps.BoolToObject(true);
                     }
                     return new SwitchParameter(true);
                 }
                 ParameterBindingException exception = new ParameterBindingException(ErrorCategory.InvalidArgument, this.InvocationInfo, this.GetErrorExtent(argument), parameterName, toType, c, "ParameterBinderStrings", "CannotConvertArgument", new object[] { type, "" });
                 throw exception;
             }
             if ((collectionTypeInfo.ParameterCollectionType == ParameterCollectionType.ICollectionGeneric) || (collectionTypeInfo.ParameterCollectionType == ParameterCollectionType.IList))
             {
                 object obj5 = PSObject.Base(currentValue);
                 if (obj5 != null)
                 {
                     ConversionRank conversionRank = LanguagePrimitives.GetConversionRank(obj5.GetType(), toType);
                     if ((((conversionRank == ConversionRank.Constructor) || (conversionRank == ConversionRank.ImplicitCast)) || (conversionRank == ConversionRank.ExplicitCast)) && LanguagePrimitives.TryConvertTo(currentValue, toType, Thread.CurrentThread.CurrentCulture, out result))
                     {
                         return result;
                     }
                 }
             }
             if (collectionTypeInfo.ParameterCollectionType != ParameterCollectionType.NotCollection)
             {
                 bindingTracer.WriteLine("ENCODING arg into collection", new object[0]);
                 bool coercionRequired = false;
                 return this.EncodeCollection(argument, parameterName, collectionTypeInfo, toType, currentValue, collectionTypeInfo.ElementType != null, out coercionRequired);
             }
             if (((((GetIList(currentValue) != null) && (toType != typeof(object))) && ((toType != typeof(PSObject)) && (toType != typeof(PSListModifier)))) && ((!toType.IsGenericType || (toType.GetGenericTypeDefinition() != typeof(PSListModifier<>))) && (!toType.IsGenericType || (toType.GetGenericTypeDefinition() != typeof(FlagsExpression<>))))) && !toType.IsEnum)
             {
                 throw new NotSupportedException();
             }
             bindingTracer.WriteLine("CONVERT arg type to param type using LanguagePrimitives.ConvertTo", new object[0]);
             bool flag2 = false;
             if (this.context.LanguageMode == PSLanguageMode.ConstrainedLanguage)
             {
                 object obj6 = PSObject.Base(currentValue);
                 bool flag3 = obj6 is PSObject;
                 bool flag4 = (obj6 != null) && typeof(IDictionary).IsAssignableFrom(obj6.GetType());
                 flag2 = ((((PSLanguageMode) this.Command.CommandInfo.DefiningLanguageMode) == PSLanguageMode.FullLanguage) && !flag3) && !flag4;
             }
             try
             {
                 if (flag2)
                 {
                     this.context.LanguageMode = PSLanguageMode.FullLanguage;
                 }
                 result = LanguagePrimitives.ConvertTo(currentValue, toType, Thread.CurrentThread.CurrentCulture);
             }
             finally
             {
                 if (flag2)
                 {
                     this.context.LanguageMode = PSLanguageMode.ConstrainedLanguage;
                 }
             }
             bindingTracer.WriteLine("CONVERT SUCCESSFUL using LanguagePrimitives.ConvertTo: [{0}]", new object[] { (result == null) ? "null" : result.ToString() });
             return result;
         }
         catch (NotSupportedException exception2)
         {
             bindingTracer.TraceError("ERROR: COERCE FAILED: arg [{0}] could not be converted to the parameter type [{1}]", new object[] { (result == null) ? "null" : result, toType });
             ParameterBindingException exception3 = new ParameterBindingException(exception2, ErrorCategory.InvalidArgument, this.InvocationInfo, this.GetErrorExtent(argument), parameterName, toType, c, "ParameterBinderStrings", "CannotConvertArgument", new object[] { (result == null) ? "null" : result, exception2.Message });
             throw exception3;
         }
         catch (PSInvalidCastException exception4)
         {
             object[] args = new object[] { result ?? "null", toType };
             bindingTracer.TraceError("ERROR: COERCE FAILED: arg [{0}] could not be converted to the parameter type [{1}]", args);
             ParameterBindingException exception5 = new ParameterBindingException(exception4, ErrorCategory.InvalidArgument, this.InvocationInfo, this.GetErrorExtent(argument), parameterName, toType, c, "ParameterBinderStrings", "CannotConvertArgumentNoMessage", new object[] { exception4.Message });
             throw exception5;
         }
     }
     return result;
 }
 internal object Transform(EngineIntrinsics engineIntrinsics, object inputData, bool bindingParameters, bool bindingScriptCmdlet)
 {
     if (this._convertTypes == null)
     {
         return inputData;
     }
     object obj2 = inputData;
     try
     {
         for (int i = 0; i < this._convertTypes.Length; i++)
         {
             if (bindingParameters)
             {
                 if (this._convertTypes[i].Equals(typeof(PSReference)))
                 {
                     object baseObject;
                     PSObject obj4 = obj2 as PSObject;
                     if (obj4 != null)
                     {
                         baseObject = obj4.BaseObject;
                     }
                     else
                     {
                         baseObject = obj2;
                     }
                     if (!(baseObject is PSReference))
                     {
                         throw new PSInvalidCastException("InvalidCastExceptionReferenceTypeExpected", null, ExtendedTypeSystem.ReferenceTypeExpected, new object[0]);
                     }
                 }
                 else
                 {
                     object obj5;
                     PSObject obj6 = obj2 as PSObject;
                     if (obj6 != null)
                     {
                         obj5 = obj6.BaseObject;
                     }
                     else
                     {
                         obj5 = obj2;
                     }
                     PSReference reference2 = obj5 as PSReference;
                     if (reference2 != null)
                     {
                         obj2 = reference2.Value;
                     }
                     if (bindingScriptCmdlet && (this._convertTypes[i] == typeof(string)))
                     {
                         obj5 = PSObject.Base(obj2);
                         if ((obj5 != null) && obj5.GetType().IsArray)
                         {
                             throw new PSInvalidCastException("InvalidCastFromAnyTypeToString", null, ExtendedTypeSystem.InvalidCastCannotRetrieveString, new object[0]);
                         }
                     }
                 }
             }
             if (LanguagePrimitives.IsBoolOrSwitchParameterType(this._convertTypes[i]))
             {
                 CheckBoolValue(obj2, this._convertTypes[i]);
             }
             if (bindingScriptCmdlet)
             {
                 ParameterCollectionTypeInformation information = new ParameterCollectionTypeInformation(this._convertTypes[i]);
                 if ((information.ParameterCollectionType != ParameterCollectionType.NotCollection) && LanguagePrimitives.IsBoolOrSwitchParameterType(information.ElementType))
                 {
                     IList iList = ParameterBinderBase.GetIList(obj2);
                     if (iList != null)
                     {
                         foreach (object obj7 in iList)
                         {
                             CheckBoolValue(obj7, information.ElementType);
                         }
                     }
                     else
                     {
                         CheckBoolValue(obj2, information.ElementType);
                     }
                 }
             }
             obj2 = LanguagePrimitives.ConvertTo(obj2, this._convertTypes[i], CultureInfo.InvariantCulture);
         }
     }
     catch (PSInvalidCastException exception)
     {
         throw new ArgumentTransformationMetadataException(exception.Message, exception);
     }
     return obj2;
 }
        internal object Transform(EngineIntrinsics engineIntrinsics, object inputData, bool bindingParameters, bool bindingScriptCmdlet)
        {
            if (this._convertTypes == null)
            {
                return(inputData);
            }
            object obj2 = inputData;

            try
            {
                for (int i = 0; i < this._convertTypes.Length; i++)
                {
                    if (bindingParameters)
                    {
                        if (this._convertTypes[i].Equals(typeof(PSReference)))
                        {
                            object   baseObject;
                            PSObject obj4 = obj2 as PSObject;
                            if (obj4 != null)
                            {
                                baseObject = obj4.BaseObject;
                            }
                            else
                            {
                                baseObject = obj2;
                            }
                            if (!(baseObject is PSReference))
                            {
                                throw new PSInvalidCastException("InvalidCastExceptionReferenceTypeExpected", null, ExtendedTypeSystem.ReferenceTypeExpected, new object[0]);
                            }
                        }
                        else
                        {
                            object   obj5;
                            PSObject obj6 = obj2 as PSObject;
                            if (obj6 != null)
                            {
                                obj5 = obj6.BaseObject;
                            }
                            else
                            {
                                obj5 = obj2;
                            }
                            PSReference reference2 = obj5 as PSReference;
                            if (reference2 != null)
                            {
                                obj2 = reference2.Value;
                            }
                            if (bindingScriptCmdlet && (this._convertTypes[i] == typeof(string)))
                            {
                                obj5 = PSObject.Base(obj2);
                                if ((obj5 != null) && obj5.GetType().IsArray)
                                {
                                    throw new PSInvalidCastException("InvalidCastFromAnyTypeToString", null, ExtendedTypeSystem.InvalidCastCannotRetrieveString, new object[0]);
                                }
                            }
                        }
                    }
                    if (LanguagePrimitives.IsBoolOrSwitchParameterType(this._convertTypes[i]))
                    {
                        CheckBoolValue(obj2, this._convertTypes[i]);
                    }
                    if (bindingScriptCmdlet)
                    {
                        ParameterCollectionTypeInformation information = new ParameterCollectionTypeInformation(this._convertTypes[i]);
                        if ((information.ParameterCollectionType != ParameterCollectionType.NotCollection) && LanguagePrimitives.IsBoolOrSwitchParameterType(information.ElementType))
                        {
                            IList iList = ParameterBinderBase.GetIList(obj2);
                            if (iList != null)
                            {
                                foreach (object obj7 in iList)
                                {
                                    CheckBoolValue(obj7, information.ElementType);
                                }
                            }
                            else
                            {
                                CheckBoolValue(obj2, information.ElementType);
                            }
                        }
                    }
                    obj2 = LanguagePrimitives.ConvertTo(obj2, this._convertTypes[i], CultureInfo.InvariantCulture);
                }
            }
            catch (PSInvalidCastException exception)
            {
                throw new ArgumentTransformationMetadataException(exception.Message, exception);
            }
            return(obj2);
        }
        internal object Transform(EngineIntrinsics engineIntrinsics, object inputData, bool bindingParameters, bool bindingScriptCmdlet)
        {
            if (_convertTypes == null)
                return inputData;

            object result = inputData;

            try
            {
                for (int i = 0; i < _convertTypes.Length; i++)
                {
                    if (bindingParameters)
                    {
                        // We should not be doing a conversion here if [ref] is the last type. 
                        // When [ref] appears in an argument list, it is used for checking only.
                        // No Conversion should be done.
                        if (_convertTypes[i].Equals(typeof(System.Management.Automation.PSReference)))
                        {
                            object temp;
                            PSObject mshObject = result as PSObject;
                            if (mshObject != null)
                                temp = mshObject.BaseObject;
                            else
                                temp = result;

                            PSReference reference = temp as PSReference;

                            if (reference == null)
                            {
                                throw new PSInvalidCastException("InvalidCastExceptionReferenceTypeExpected", null,
                                                                   ExtendedTypeSystem.ReferenceTypeExpected);
                            }
                        }
                        else
                        {
                            object temp;
                            PSObject mshObject = result as PSObject;
                            if (mshObject != null)
                                temp = mshObject.BaseObject;
                            else
                                temp = result;

                            // If a non-ref type is expected but currently passed in is a ref, do an implicit dereference. 
                            PSReference reference = temp as PSReference;

                            if (reference != null)
                            {
                                result = reference.Value;
                            }

                            if (bindingScriptCmdlet && _convertTypes[i] == typeof(string))
                            {
                                // Don't allow conversion from array to string in script w/ cmdlet binding.  Allow
                                // the conversion for ordinary script parameter binding for V1 compatibility.
                                temp = PSObject.Base(result);
                                if (temp != null && temp.GetType().IsArray)
                                {
                                    throw new PSInvalidCastException("InvalidCastFromAnyTypeToString", null,
                                        ExtendedTypeSystem.InvalidCastCannotRetrieveString);
                                }
                            }
                        }
                    }

                    //BUGBUG
                    //NTRAID#Windows Out of Band Releases - 930116 - 03/14/06
                    //handling special case for boolean, switchparameter and Nullable<bool>
                    //These parameter types will not be converted if the incoming value types are not
                    //one of the accepted categories - $true/$false or numbers (0 or otherwise)
                    if (LanguagePrimitives.IsBoolOrSwitchParameterType(_convertTypes[i]))
                    {
                        CheckBoolValue(result, _convertTypes[i]);
                    }

                    if (bindingScriptCmdlet)
                    {
                        // Check for conversion to something like bool[] or ICollection<bool>, but only for cmdlet binding
                        // to stay compatible with V1.
                        ParameterCollectionTypeInformation collectionTypeInfo = new ParameterCollectionTypeInformation(_convertTypes[i]);
                        if (collectionTypeInfo.ParameterCollectionType != ParameterCollectionType.NotCollection
                            && LanguagePrimitives.IsBoolOrSwitchParameterType(collectionTypeInfo.ElementType))
                        {
                            IList currentValueAsIList = ParameterBinderBase.GetIList(result);
                            if (currentValueAsIList != null)
                            {
                                foreach (object val in currentValueAsIList)
                                {
                                    CheckBoolValue(val, collectionTypeInfo.ElementType);
                                }
                            }
                            else
                            {
                                CheckBoolValue(result, collectionTypeInfo.ElementType);
                            }
                        }
                    }

                    result = LanguagePrimitives.ConvertTo(result, _convertTypes[i], CultureInfo.InvariantCulture);

                    // Do validation of invalid direct variable assignments which are allowed to
                    // be used for parameters.
                    //
                    // Note - this is duplicated in ExecutionContext.cs as parameter binding for script cmdlets can avoid this code path.
                    if ((!bindingScriptCmdlet) && (!bindingParameters))
                    {
                        // ActionPreference of Suspend is not supported as a preference variable. We can only block "Suspend"
                        // during variable assignment (here) - "Ignore" is blocked during variable retrieval.
                        if (_convertTypes[i] == typeof(ActionPreference))
                        {
                            ActionPreference resultPreference = (ActionPreference)result;

                            if (resultPreference == ActionPreference.Suspend)
                            {
                                throw new PSInvalidCastException("InvalidActionPreference", null, ErrorPackage.UnsupportedPreferenceVariable, resultPreference);
                            }
                        }
                    }
                }
            }
            catch (PSInvalidCastException e)
            {
                throw new ArgumentTransformationMetadataException(e.Message, e);
            }

            return result;
        }
Exemple #13
0
        private object EncodeCollection(CommandParameterInternal argument, string parameterName, ParameterCollectionTypeInformation collectionTypeInformation, Type toType, object currentValue, bool coerceElementTypeIfNeeded, out bool coercionRequired)
        {
            object obj2 = null;

            coercionRequired = false;
            bindingTracer.WriteLine("Binding collection parameter {0}: argument type [{1}], parameter type [{2}], collection type {3}, element type [{4}], {5}", new object[] { parameterName, (currentValue == null) ? "null" : currentValue.GetType().Name, toType, collectionTypeInformation.ParameterCollectionType, collectionTypeInformation.ElementType, coerceElementTypeIfNeeded ? "coerceElementType" : "no coerceElementType" });
            if (currentValue != null)
            {
                int   length      = 1;
                Type  elementType = collectionTypeInformation.ElementType;
                IList iList       = GetIList(currentValue);
                if (iList != null)
                {
                    length = iList.Count;
                    tracer.WriteLine("current value is an IList with {0} elements", new object[] { length });
                    bindingTracer.WriteLine("Arg is IList with {0} elements", new object[] { length });
                }
                object     obj3  = null;
                IList      list2 = null;
                MethodInfo info  = null;
                bool       flag  = toType == typeof(Array);
                if ((collectionTypeInformation.ParameterCollectionType == ParameterCollectionType.Array) || flag)
                {
                    if (flag)
                    {
                        elementType = typeof(object);
                    }
                    bindingTracer.WriteLine("Creating array with element type [{0}] and {1} elements", new object[] { elementType, length });
                    obj3 = list2 = Array.CreateInstance(elementType, length);
                }
                else
                {
                    if ((collectionTypeInformation.ParameterCollectionType != ParameterCollectionType.IList) && (collectionTypeInformation.ParameterCollectionType != ParameterCollectionType.ICollectionGeneric))
                    {
                        return(obj2);
                    }
                    bindingTracer.WriteLine("Creating collection [{0}]", new object[] { toType });
                    bool      flag2          = false;
                    Exception innerException = null;
                    try
                    {
                        obj3 = Activator.CreateInstance(toType, BindingFlags.Default, null, new object[0], CultureInfo.InvariantCulture);
                        if (collectionTypeInformation.ParameterCollectionType == ParameterCollectionType.IList)
                        {
                            list2 = (IList)obj3;
                        }
                        else
                        {
                            Type         type2       = collectionTypeInformation.ElementType;
                            BindingFlags bindingAttr = BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance;
                            Exception    exception2  = null;
                            try
                            {
                                info = toType.GetMethod("Add", bindingAttr, null, new Type[] { type2 }, null);
                            }
                            catch (AmbiguousMatchException exception3)
                            {
                                bindingTracer.WriteLine("Ambiguous match to Add(T) for type " + toType.FullName + ": " + exception3.Message, new object[0]);
                                exception2 = exception3;
                            }
                            catch (ArgumentException exception4)
                            {
                                bindingTracer.WriteLine("ArgumentException matching Add(T) for type " + toType.FullName + ": " + exception4.Message, new object[0]);
                                exception2 = exception4;
                            }
                            if (null == info)
                            {
                                ParameterBindingException exception5 = new ParameterBindingException(exception2, ErrorCategory.InvalidArgument, this.InvocationInfo, this.GetErrorExtent(argument), parameterName, toType, (currentValue == null) ? null : currentValue.GetType(), "ParameterBinderStrings", "CannotExtractAddMethod", new object[] { (exception2 == null) ? "" : exception2.Message });
                                throw exception5;
                            }
                        }
                    }
                    catch (ArgumentException exception6)
                    {
                        flag2          = true;
                        innerException = exception6;
                    }
                    catch (NotSupportedException exception7)
                    {
                        flag2          = true;
                        innerException = exception7;
                    }
                    catch (TargetInvocationException exception8)
                    {
                        flag2          = true;
                        innerException = exception8;
                    }
                    catch (MethodAccessException exception9)
                    {
                        flag2          = true;
                        innerException = exception9;
                    }
                    catch (MemberAccessException exception10)
                    {
                        flag2          = true;
                        innerException = exception10;
                    }
                    catch (InvalidComObjectException exception11)
                    {
                        flag2          = true;
                        innerException = exception11;
                    }
                    catch (COMException exception12)
                    {
                        flag2          = true;
                        innerException = exception12;
                    }
                    catch (TypeLoadException exception13)
                    {
                        flag2          = true;
                        innerException = exception13;
                    }
                    if (flag2)
                    {
                        ParameterBindingException exception14 = new ParameterBindingException(innerException, ErrorCategory.InvalidArgument, this.InvocationInfo, this.GetErrorExtent(argument), parameterName, toType, currentValue.GetType(), "ParameterBinderStrings", "CannotConvertArgument", new object[] { (obj2 == null) ? "null" : obj2, (innerException == null) ? "" : innerException.Message });
                        throw exception14;
                    }
                }
                if (iList != null)
                {
                    int num2 = 0;
                    bindingTracer.WriteLine("Argument type {0} is IList", new object[] { currentValue.GetType() });
                    foreach (object obj4 in iList)
                    {
                        object obj5 = PSObject.Base(obj4);
                        if (coerceElementTypeIfNeeded)
                        {
                            bindingTracer.WriteLine("COERCE collection element from type {0} to type {1}", new object[] { (obj4 == null) ? "null" : obj4.GetType().Name, elementType });
                            obj5 = this.CoerceTypeAsNeeded(argument, parameterName, elementType, null, obj4);
                        }
                        else if ((null != elementType) && (obj5 != null))
                        {
                            Type type = obj5.GetType();
                            Type c    = elementType;
                            if ((type != c) && !type.IsSubclassOf(c))
                            {
                                bindingTracer.WriteLine("COERCION REQUIRED: Did not attempt to coerce collection element from type {0} to type {1}", new object[] { (obj4 == null) ? "null" : obj4.GetType().Name, elementType });
                                coercionRequired = true;
                                break;
                            }
                        }
                        try
                        {
                            if ((collectionTypeInformation.ParameterCollectionType == ParameterCollectionType.Array) || flag)
                            {
                                bindingTracer.WriteLine("Adding element of type {0} to array position {1}", new object[] { (obj5 == null) ? "null" : obj5.GetType().Name, num2 });
                                list2[num2++] = obj5;
                            }
                            else if (collectionTypeInformation.ParameterCollectionType == ParameterCollectionType.IList)
                            {
                                bindingTracer.WriteLine("Adding element of type {0} via IList.Add", new object[] { (obj5 == null) ? "null" : obj5.GetType().Name });
                                list2.Add(obj5);
                            }
                            else
                            {
                                bindingTracer.WriteLine("Adding element of type {0} via ICollection<T>::Add()", new object[] { (obj5 == null) ? "null" : obj5.GetType().Name });
                                info.Invoke(obj3, new object[] { obj5 });
                            }
                        }
                        catch (Exception exception15)
                        {
                            CommandProcessorBase.CheckForSevereException(exception15);
                            if ((exception15 is TargetInvocationException) && (exception15.InnerException != null))
                            {
                                exception15 = exception15.InnerException;
                            }
                            ParameterBindingException exception16 = new ParameterBindingException(exception15, ErrorCategory.InvalidArgument, this.InvocationInfo, this.GetErrorExtent(argument), parameterName, toType, (obj5 == null) ? null : obj5.GetType(), "ParameterBinderStrings", "CannotConvertArgument", new object[] { (obj5 == null) ? "null" : obj5, exception15.Message });
                            throw exception16;
                        }
                    }
                }
                else
                {
                    bindingTracer.WriteLine("Argument type {0} is not IList, treating this as scalar", new object[] { (currentValue == null) ? "null" : currentValue.GetType().Name });
                    if (elementType != null)
                    {
                        if (coerceElementTypeIfNeeded)
                        {
                            bindingTracer.WriteLine("Coercing scalar arg value to type {0}", new object[] { elementType });
                            currentValue = this.CoerceTypeAsNeeded(argument, parameterName, elementType, null, currentValue);
                        }
                        else
                        {
                            Type type5 = currentValue.GetType();
                            Type type6 = elementType;
                            if ((type5 != type6) && !type5.IsSubclassOf(type6))
                            {
                                bindingTracer.WriteLine("COERCION REQUIRED: Did not coerce scalar arg value to type {1}", new object[] { elementType });
                                coercionRequired = true;
                                return(obj2);
                            }
                        }
                    }
                    try
                    {
                        if ((collectionTypeInformation.ParameterCollectionType == ParameterCollectionType.Array) || flag)
                        {
                            bindingTracer.WriteLine("Adding scalar element of type {0} to array position {1}", new object[] { (currentValue == null) ? "null" : currentValue.GetType().Name, 0 });
                            list2[0] = currentValue;
                        }
                        else if (collectionTypeInformation.ParameterCollectionType == ParameterCollectionType.IList)
                        {
                            bindingTracer.WriteLine("Adding scalar element of type {0} via IList.Add", new object[] { (currentValue == null) ? "null" : currentValue.GetType().Name });
                            list2.Add(currentValue);
                        }
                        else
                        {
                            bindingTracer.WriteLine("Adding scalar element of type {0} via ICollection<T>::Add()", new object[] { (currentValue == null) ? "null" : currentValue.GetType().Name });
                            info.Invoke(obj3, new object[] { currentValue });
                        }
                    }
                    catch (Exception exception17)
                    {
                        CommandProcessorBase.CheckForSevereException(exception17);
                        if ((exception17 is TargetInvocationException) && (exception17.InnerException != null))
                        {
                            exception17 = exception17.InnerException;
                        }
                        ParameterBindingException exception18 = new ParameterBindingException(exception17, ErrorCategory.InvalidArgument, this.InvocationInfo, this.GetErrorExtent(argument), parameterName, toType, (currentValue == null) ? null : currentValue.GetType(), "ParameterBinderStrings", "CannotConvertArgument", new object[] { (currentValue == null) ? "null" : currentValue, exception17.Message });
                        throw exception18;
                    }
                }
                if (!coercionRequired)
                {
                    obj2 = obj3;
                }
            }
            return(obj2);
        }
Exemple #14
0
        private object CoerceTypeAsNeeded(CommandParameterInternal argument, string parameterName, Type toType, ParameterCollectionTypeInformation collectionTypeInfo, object currentValue)
        {
            if (argument == null)
            {
                throw PSTraceSource.NewArgumentNullException("argument");
            }
            if (toType == null)
            {
                throw PSTraceSource.NewArgumentNullException("toType");
            }
            if (collectionTypeInfo == null)
            {
                collectionTypeInfo = new ParameterCollectionTypeInformation(toType);
            }
            object result = currentValue;

            using (bindingTracer.TraceScope("COERCE arg to [{0}]", new object[] { toType }))
            {
                Type c = null;
                try
                {
                    if (IsNullParameterValue(currentValue))
                    {
                        return(this.HandleNullParameterForSpecialTypes(argument, parameterName, toType, currentValue));
                    }
                    c = currentValue.GetType();
                    if (toType.IsAssignableFrom(c))
                    {
                        bindingTracer.WriteLine("Parameter and arg types the same, no coercion is needed.", new object[0]);
                        return(currentValue);
                    }
                    bindingTracer.WriteLine("Trying to convert argument value from {0} to {1}", new object[] { c, toType });
                    if (toType == typeof(PSObject))
                    {
                        if ((this.command != null) && (currentValue == this.command.CurrentPipelineObject.BaseObject))
                        {
                            currentValue = this.command.CurrentPipelineObject;
                        }
                        bindingTracer.WriteLine("The parameter is of type [{0}] and the argument is an PSObject, so the parameter value is the argument value wrapped into an PSObject.", new object[] { toType });
                        return(LanguagePrimitives.AsPSObjectOrNull(currentValue));
                    }
                    if ((toType == typeof(string)) && (c == typeof(PSObject)))
                    {
                        PSObject obj3 = (PSObject)currentValue;
                        if (obj3 == AutomationNull.Value)
                        {
                            bindingTracer.WriteLine("CONVERT a null PSObject to a null string.", new object[0]);
                            return(null);
                        }
                    }
                    if (((toType == typeof(bool)) || (toType == typeof(SwitchParameter))) || (toType == typeof(bool?)))
                    {
                        Type type = null;
                        if (c == typeof(PSObject))
                        {
                            PSObject obj4 = (PSObject)currentValue;
                            currentValue = obj4.BaseObject;
                            if (currentValue is SwitchParameter)
                            {
                                SwitchParameter parameter = (SwitchParameter)currentValue;
                                currentValue = parameter.IsPresent;
                            }
                            type = currentValue.GetType();
                        }
                        else
                        {
                            type = c;
                        }
                        if (type == typeof(bool))
                        {
                            if (LanguagePrimitives.IsBooleanType(toType))
                            {
                                return(ParserOps.BoolToObject((bool)currentValue));
                            }
                            return(new SwitchParameter((bool)currentValue));
                        }
                        if (type == typeof(int))
                        {
                            if (((int)LanguagePrimitives.ConvertTo(currentValue, typeof(int), CultureInfo.InvariantCulture)) != 0)
                            {
                                if (LanguagePrimitives.IsBooleanType(toType))
                                {
                                    return(ParserOps.BoolToObject(true));
                                }
                                return(new SwitchParameter(true));
                            }
                            if (LanguagePrimitives.IsBooleanType(toType))
                            {
                                return(ParserOps.BoolToObject(false));
                            }
                            return(new SwitchParameter(false));
                        }
                        if (LanguagePrimitives.IsNumeric(Type.GetTypeCode(type)))
                        {
                            double num = (double)LanguagePrimitives.ConvertTo(currentValue, typeof(double), CultureInfo.InvariantCulture);
                            if (num == 0.0)
                            {
                                if (LanguagePrimitives.IsBooleanType(toType))
                                {
                                    return(ParserOps.BoolToObject(false));
                                }
                                return(new SwitchParameter(false));
                            }
                            if (LanguagePrimitives.IsBooleanType(toType))
                            {
                                return(ParserOps.BoolToObject(true));
                            }
                            return(new SwitchParameter(true));
                        }
                        ParameterBindingException exception = new ParameterBindingException(ErrorCategory.InvalidArgument, this.InvocationInfo, this.GetErrorExtent(argument), parameterName, toType, c, "ParameterBinderStrings", "CannotConvertArgument", new object[] { type, "" });
                        throw exception;
                    }
                    if ((collectionTypeInfo.ParameterCollectionType == ParameterCollectionType.ICollectionGeneric) || (collectionTypeInfo.ParameterCollectionType == ParameterCollectionType.IList))
                    {
                        object obj5 = PSObject.Base(currentValue);
                        if (obj5 != null)
                        {
                            ConversionRank conversionRank = LanguagePrimitives.GetConversionRank(obj5.GetType(), toType);
                            if ((((conversionRank == ConversionRank.Constructor) || (conversionRank == ConversionRank.ImplicitCast)) || (conversionRank == ConversionRank.ExplicitCast)) && LanguagePrimitives.TryConvertTo(currentValue, toType, Thread.CurrentThread.CurrentCulture, out result))
                            {
                                return(result);
                            }
                        }
                    }
                    if (collectionTypeInfo.ParameterCollectionType != ParameterCollectionType.NotCollection)
                    {
                        bindingTracer.WriteLine("ENCODING arg into collection", new object[0]);
                        bool coercionRequired = false;
                        return(this.EncodeCollection(argument, parameterName, collectionTypeInfo, toType, currentValue, collectionTypeInfo.ElementType != null, out coercionRequired));
                    }
                    if (((((GetIList(currentValue) != null) && (toType != typeof(object))) && ((toType != typeof(PSObject)) && (toType != typeof(PSListModifier)))) && ((!toType.IsGenericType || (toType.GetGenericTypeDefinition() != typeof(PSListModifier <>))) && (!toType.IsGenericType || (toType.GetGenericTypeDefinition() != typeof(FlagsExpression <>))))) && !toType.IsEnum)
                    {
                        throw new NotSupportedException();
                    }
                    bindingTracer.WriteLine("CONVERT arg type to param type using LanguagePrimitives.ConvertTo", new object[0]);
                    bool flag2 = false;
                    if (this.context.LanguageMode == PSLanguageMode.ConstrainedLanguage)
                    {
                        object obj6  = PSObject.Base(currentValue);
                        bool   flag3 = obj6 is PSObject;
                        bool   flag4 = (obj6 != null) && typeof(IDictionary).IsAssignableFrom(obj6.GetType());
                        flag2 = ((((PSLanguageMode)this.Command.CommandInfo.DefiningLanguageMode) == PSLanguageMode.FullLanguage) && !flag3) && !flag4;
                    }
                    try
                    {
                        if (flag2)
                        {
                            this.context.LanguageMode = PSLanguageMode.FullLanguage;
                        }
                        result = LanguagePrimitives.ConvertTo(currentValue, toType, Thread.CurrentThread.CurrentCulture);
                    }
                    finally
                    {
                        if (flag2)
                        {
                            this.context.LanguageMode = PSLanguageMode.ConstrainedLanguage;
                        }
                    }
                    bindingTracer.WriteLine("CONVERT SUCCESSFUL using LanguagePrimitives.ConvertTo: [{0}]", new object[] { (result == null) ? "null" : result.ToString() });
                    return(result);
                }
                catch (NotSupportedException exception2)
                {
                    bindingTracer.TraceError("ERROR: COERCE FAILED: arg [{0}] could not be converted to the parameter type [{1}]", new object[] { (result == null) ? "null" : result, toType });
                    ParameterBindingException exception3 = new ParameterBindingException(exception2, ErrorCategory.InvalidArgument, this.InvocationInfo, this.GetErrorExtent(argument), parameterName, toType, c, "ParameterBinderStrings", "CannotConvertArgument", new object[] { (result == null) ? "null" : result, exception2.Message });
                    throw exception3;
                }
                catch (PSInvalidCastException exception4)
                {
                    object[] args = new object[] { result ?? "null", toType };
                    bindingTracer.TraceError("ERROR: COERCE FAILED: arg [{0}] could not be converted to the parameter type [{1}]", args);
                    ParameterBindingException exception5 = new ParameterBindingException(exception4, ErrorCategory.InvalidArgument, this.InvocationInfo, this.GetErrorExtent(argument), parameterName, toType, c, "ParameterBinderStrings", "CannotConvertArgumentNoMessage", new object[] { exception4.Message });
                    throw exception5;
                }
            }
            return(result);
        }