Ejemplo n.º 1
0
 /// <summary>
 /// Determines if an object is a COM object.
 /// </summary>
 /// <param name="value">The object to test.</param>
 /// <returns>True if the object is a COM object, false otherwise.</returns>
 public static bool IsComObject(object value)
 {
     return
         ((value != null) &&
          (!WinRTHelper.IsWinRTType(value.GetType())) &&
          ComObject.IsComObject(value));
 }
Ejemplo n.º 2
0
        /// <summary> Create the object </summary>
        protected override void BeginProcessing()
        {
            Type type = null;
            PSArgumentException mshArgE = null;

            if (string.Equals(ParameterSetName, netSetName, StringComparison.Ordinal))
            {
                object _newObject = null;
                try
                {
                    type = LanguagePrimitives.ConvertTo(TypeName, typeof(Type), CultureInfo.InvariantCulture) as Type;
                }
                catch (Exception e)
                {
                    // these complications in Exception handling are aim to make error messages better.
                    if (e is InvalidCastException || e is ArgumentException)
                    {
                        if (e.InnerException != null && e.InnerException is TypeResolver.AmbiguousTypeException)
                        {
                            ThrowTerminatingError(
                                new ErrorRecord(
                                    e,
                                    "AmbiguousTypeReference",
                                    ErrorCategory.InvalidType,
                                    targetObject: null));
                        }

                        mshArgE = PSTraceSource.NewArgumentException(
                            "TypeName",
                            NewObjectStrings.TypeNotFound,
                            TypeName);

                        ThrowTerminatingError(
                            new ErrorRecord(
                                mshArgE,
                                "TypeNotFound",
                                ErrorCategory.InvalidType,
                                targetObject: null));
                    }

                    throw;
                }

                Diagnostics.Assert(type != null, "LanguagePrimitives.TryConvertTo failed but returned true");

                if (type.IsByRefLike)
                {
                    ThrowTerminatingError(
                        new ErrorRecord(
                            PSTraceSource.NewInvalidOperationException(
                                NewObjectStrings.CannotInstantiateBoxedByRefLikeType,
                                type),
                            nameof(NewObjectStrings.CannotInstantiateBoxedByRefLikeType),
                            ErrorCategory.InvalidOperation,
                            targetObject: null));
                }

                if (Context.LanguageMode == PSLanguageMode.ConstrainedLanguage)
                {
                    if (!CoreTypes.Contains(type))
                    {
                        ThrowTerminatingError(
                            new ErrorRecord(
                                new PSNotSupportedException(NewObjectStrings.CannotCreateTypeConstrainedLanguage), "CannotCreateTypeConstrainedLanguage", ErrorCategory.PermissionDenied, null));
                    }
                }

                // WinRT does not support creating instances of attribute & delegate WinRT types.
                if (WinRTHelper.IsWinRTType(type) && ((typeof(System.Attribute)).IsAssignableFrom(type) || (typeof(System.Delegate)).IsAssignableFrom(type)))
                {
                    ThrowTerminatingError(new ErrorRecord(new InvalidOperationException(NewObjectStrings.CannotInstantiateWinRTType),
                                                          "CannotInstantiateWinRTType", ErrorCategory.InvalidOperation, null));
                }

                if (ArgumentList is null || ArgumentList.Length == 0)
                {
                    ConstructorInfo ci = type.GetConstructor(Type.EmptyTypes);
                    if (ci != null && ci.IsPublic)
                    {
                        _newObject = CallConstructor(type, new ConstructorInfo[] { ci }, new object[] { });
                        if (_newObject != null && Property != null)
                        {
                            // The method invocation is disabled for "Hashtable to Object conversion" (Win8:649519), but we need to keep it enabled for New-Object for compatibility to PSv2
                            _newObject = LanguagePrimitives.SetObjectProperties(_newObject, Property, type, CreateMemberNotFoundError, CreateMemberSetValueError, enableMethodCall: true);
                        }

                        WriteObject(_newObject);
                        return;
                    }
                    else if (type.GetTypeInfo().IsValueType)
                    {
                        // This is for default parameterless struct ctor which is not returned by
                        // Type.GetConstructor(System.Type.EmptyTypes).
                        try
                        {
                            _newObject = Activator.CreateInstance(type);
                            if (_newObject != null && Property != null)
                            {
                                // Win8:649519
                                _newObject = LanguagePrimitives.SetObjectProperties(_newObject, Property, type, CreateMemberNotFoundError, CreateMemberSetValueError, enableMethodCall: true);
                            }
                        }
                        catch (TargetInvocationException e)
                        {
                            ThrowTerminatingError(
                                new ErrorRecord(
                                    e.InnerException ?? e,
                                    "ConstructorCalledThrowException",
                                    ErrorCategory.InvalidOperation, null));
                        }

                        WriteObject(_newObject);
                        return;
                    }
                }
                else
                {
                    ConstructorInfo[] ctorInfos = type.GetConstructors();

                    if (ctorInfos.Length != 0)
                    {
                        _newObject = CallConstructor(type, ctorInfos, ArgumentList);
                        if (_newObject != null && Property != null)
                        {
                            // Win8:649519
                            _newObject = LanguagePrimitives.SetObjectProperties(_newObject, Property, type, CreateMemberNotFoundError, CreateMemberSetValueError, enableMethodCall: true);
                        }

                        WriteObject(_newObject);
                        return;
                    }
                }

                mshArgE = PSTraceSource.NewArgumentException(
                    "TypeName", NewObjectStrings.CannotFindAppropriateCtor, TypeName);
                ThrowTerminatingError(
                    new ErrorRecord(
                        mshArgE,
                        "CannotFindAppropriateCtor",
                        ErrorCategory.ObjectNotFound, null));
            }
Ejemplo n.º 3
0
        /// <summary> Create the object </summary>
        protected override void BeginProcessing()
        {
            Type type = null;
            PSArgumentException mshArgE = null;

            if (string.Compare(ParameterSetName, netSetName, StringComparison.Ordinal) == 0)
            {
                object _newObject = null;
                try
                {
                    type = LanguagePrimitives.ConvertTo(TypeName, typeof(Type), CultureInfo.InvariantCulture) as Type;
                }
                catch (Exception e)
                {
                    // these complications in Exception handling are aim to make error messages better.
                    if (e is InvalidCastException || e is ArgumentException)
                    {
                        if (e.InnerException != null && e.InnerException is TypeResolver.AmbiguousTypeException)
                        {
                            ThrowTerminatingError(
                                new ErrorRecord(
                                    e,
                                    "AmbiguousTypeReference",
                                    ErrorCategory.InvalidType,
                                    targetObject: null));
                        }

                        mshArgE = PSTraceSource.NewArgumentException(
                            "TypeName",
                            NewObjectStrings.TypeNotFound,
                            TypeName);

                        ThrowTerminatingError(
                            new ErrorRecord(
                                mshArgE,
                                "TypeNotFound",
                                ErrorCategory.InvalidType,
                                targetObject: null));
                    }

                    throw e;
                }

                Diagnostics.Assert(type != null, "LanguagePrimitives.TryConvertTo failed but returned true");

                if (type.IsByRefLike)
                {
                    ThrowTerminatingError(
                        new ErrorRecord(
                            PSTraceSource.NewInvalidOperationException(
                                NewObjectStrings.CannotInstantiateBoxedByRefLikeType,
                                type),
                            nameof(NewObjectStrings.CannotInstantiateBoxedByRefLikeType),
                            ErrorCategory.InvalidOperation,
                            targetObject: null));
                }

                if (Context.LanguageMode == PSLanguageMode.ConstrainedLanguage)
                {
                    if (!CoreTypes.Contains(type))
                    {
                        ThrowTerminatingError(
                            new ErrorRecord(
                                new PSNotSupportedException(NewObjectStrings.CannotCreateTypeConstrainedLanguage), "CannotCreateTypeConstrainedLanguage", ErrorCategory.PermissionDenied, null));
                    }
                }

                // WinRT does not support creating instances of attribute & delegate WinRT types.
                if (WinRTHelper.IsWinRTType(type) && ((typeof(System.Attribute)).IsAssignableFrom(type) || (typeof(System.Delegate)).IsAssignableFrom(type)))
                {
                    ThrowTerminatingError(new ErrorRecord(new InvalidOperationException(NewObjectStrings.CannotInstantiateWinRTType),
                                                          "CannotInstantiateWinRTType", ErrorCategory.InvalidOperation, null));
                }

                if (ArgumentList == null || ArgumentList.Length == 0)
                {
                    ConstructorInfo ci = type.GetConstructor(Type.EmptyTypes);
                    if (ci != null && ci.IsPublic)
                    {
                        _newObject = CallConstructor(type, new ConstructorInfo[] { ci }, new object[] { });
                        if (_newObject != null && Property != null)
                        {
                            // The method invocation is disabled for "Hashtable to Object conversion" (Win8:649519), but we need to keep it enabled for New-Object for compatibility to PSv2
                            _newObject = LanguagePrimitives.SetObjectProperties(_newObject, Property, type, CreateMemberNotFoundError, CreateMemberSetValueError, enableMethodCall: true);
                        }

                        WriteObject(_newObject);
                        return;
                    }
                    else if (type.GetTypeInfo().IsValueType)
                    {
                        // This is for default parameterless struct ctor which is not returned by
                        // Type.GetConstructor(System.Type.EmptyTypes).
                        try
                        {
                            _newObject = Activator.CreateInstance(type);
                            if (_newObject != null && Property != null)
                            {
                                // Win8:649519
                                _newObject = LanguagePrimitives.SetObjectProperties(_newObject, Property, type, CreateMemberNotFoundError, CreateMemberSetValueError, enableMethodCall: true);
                            }
                        }
                        catch (TargetInvocationException e)
                        {
                            ThrowTerminatingError(
                                new ErrorRecord(
                                    e.InnerException ?? e,
                                    "ConstructorCalledThrowException",
                                    ErrorCategory.InvalidOperation, null));
                        }

                        WriteObject(_newObject);
                        return;
                    }
                }
                else
                {
                    ConstructorInfo[] ctorInfos = type.GetConstructors();

                    if (ctorInfos.Length != 0)
                    {
                        _newObject = CallConstructor(type, ctorInfos, ArgumentList);
                        if (_newObject != null && Property != null)
                        {
                            // Win8:649519
                            _newObject = LanguagePrimitives.SetObjectProperties(_newObject, Property, type, CreateMemberNotFoundError, CreateMemberSetValueError, enableMethodCall: true);
                        }

                        WriteObject(_newObject);
                        return;
                    }
                }

                mshArgE = PSTraceSource.NewArgumentException(
                    "TypeName", NewObjectStrings.CannotFindAppropriateCtor, TypeName);
                ThrowTerminatingError(
                    new ErrorRecord(
                        mshArgE,
                        "CannotFindAppropriateCtor",
                        ErrorCategory.ObjectNotFound, null));
            }
#if !UNIX
            else // Parameterset -Com
            {
                int result = NewObjectNativeMethods.CLSIDFromProgID(ComObject, out _comObjectClsId);

                // If we're in ConstrainedLanguage, do additional restrictions
                if (Context.LanguageMode == PSLanguageMode.ConstrainedLanguage)
                {
                    bool isAllowed = false;

                    // If it's a system-wide lockdown, we may allow additional COM types
                    if (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce)
                    {
                        if ((result >= 0) &&
                            SystemPolicy.IsClassInApprovedList(_comObjectClsId))
                        {
                            isAllowed = true;
                        }
                    }

                    if (!isAllowed)
                    {
                        ThrowTerminatingError(
                            new ErrorRecord(
                                new PSNotSupportedException(NewObjectStrings.CannotCreateTypeConstrainedLanguage), "CannotCreateComTypeConstrainedLanguage", ErrorCategory.PermissionDenied, null));
                        return;
                    }
                }

                object comObject         = CreateComObject();
                string comObjectTypeName = comObject.GetType().FullName;
                if (!comObjectTypeName.Equals("System.__ComObject"))
                {
                    mshArgE = PSTraceSource.NewArgumentException(
                        "TypeName", NewObjectStrings.ComInteropLoaded, comObjectTypeName);
                    WriteVerbose(mshArgE.Message);
                    if (Strict)
                    {
                        WriteError(new ErrorRecord(
                                       mshArgE,
                                       "ComInteropLoaded",
                                       ErrorCategory.InvalidArgument, comObject));
                    }
                }

                if (comObject != null && Property != null)
                {
                    // Win8:649519
                    comObject = LanguagePrimitives.SetObjectProperties(comObject, Property, type, CreateMemberNotFoundError, CreateMemberSetValueError, enableMethodCall: true);
                }

                WriteObject(comObject);
            }
#endif
        }
Ejemplo n.º 4
0
        protected override void BeginProcessing()
        {
            Type result = null;
            PSArgumentException exception = null;

            if (string.Compare(base.ParameterSetName, "Net", StringComparison.Ordinal) == 0)
            {
                object o = null;
                if (!LanguagePrimitives.TryConvertTo <Type>(this.typeName, out result))
                {
                    exception = PSTraceSource.NewArgumentException("TypeName", "NewObjectStrings", "TypeNotFound", new object[] { this.typeName });
                    base.ThrowTerminatingError(new ErrorRecord(exception, "TypeNotFound", ErrorCategory.InvalidType, null));
                }
                if ((base.Context.LanguageMode == PSLanguageMode.ConstrainedLanguage) && !CoreTypes.Contains(result))
                {
                    base.ThrowTerminatingError(new ErrorRecord(new PSNotSupportedException(NewObjectStrings.CannotCreateTypeConstrainedLanguage), "CannotCreateTypeConstrainedLanguage", ErrorCategory.PermissionDenied, null));
                }
                if (WinRTHelper.IsWinRTType(result) && (typeof(Attribute).IsAssignableFrom(result) || typeof(Delegate).IsAssignableFrom(result)))
                {
                    base.ThrowTerminatingError(new ErrorRecord(new InvalidOperationException(NewObjectStrings.CannotInstantiateWinRTType), "CannotInstantiateWinRTType", ErrorCategory.InvalidOperation, null));
                }
                if ((this.arguments == null) || (this.arguments.Length == 0))
                {
                    ConstructorInfo constructor = result.GetConstructor(Type.EmptyTypes);
                    if ((constructor != null) && constructor.IsPublic)
                    {
                        o = this.CallConstructor(result, new ConstructorInfo[] { constructor }, new object[0]);
                        if ((o != null) && (this.property != null))
                        {
                            o = LanguagePrimitives.SetObjectProperties(o, this.Property, result, new LanguagePrimitives.MemberNotFoundError(this.CreateMemberNotFoundError), new LanguagePrimitives.MemberSetValueError(this.CreateMemberSetValueError), true);
                        }
                        base.WriteObject(o);
                        return;
                    }
                    if (result.IsValueType)
                    {
                        try
                        {
                            o = Activator.CreateInstance(result, false);
                            if ((o != null) && (this.property != null))
                            {
                                o = LanguagePrimitives.SetObjectProperties(o, this.Property, result, new LanguagePrimitives.MemberNotFoundError(this.CreateMemberNotFoundError), new LanguagePrimitives.MemberSetValueError(this.CreateMemberSetValueError), true);
                            }
                        }
                        catch (TargetInvocationException exception2)
                        {
                            base.ThrowTerminatingError(new ErrorRecord((exception2.InnerException == null) ? exception2 : exception2.InnerException, "ConstructorCalledThrowException", ErrorCategory.InvalidOperation, null));
                        }
                        base.WriteObject(o);
                        return;
                    }
                }
                else
                {
                    ConstructorInfo[] constructors = result.GetConstructors();
                    if (constructors.Length != 0)
                    {
                        o = this.CallConstructor(result, constructors, this.arguments);
                        if ((o != null) && (this.property != null))
                        {
                            o = LanguagePrimitives.SetObjectProperties(o, this.Property, result, new LanguagePrimitives.MemberNotFoundError(this.CreateMemberNotFoundError), new LanguagePrimitives.MemberSetValueError(this.CreateMemberSetValueError), true);
                        }
                        base.WriteObject(o);
                        return;
                    }
                }
                exception = PSTraceSource.NewArgumentException("TypeName", "NewObjectStrings", "CannotFindAppropriateCtor", new object[] { this.typeName });
                base.ThrowTerminatingError(new ErrorRecord(exception, "CannotFindAppropriateCtor", ErrorCategory.ObjectNotFound, null));
            }
            else
            {
                NewObjectNativeMethods.CLSIDFromProgID(this.comObject, out this.comObjectClsId);
                if (base.Context.LanguageMode == PSLanguageMode.ConstrainedLanguage)
                {
                    bool flag2 = false;
                    if ((SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce) && SystemPolicy.IsClassInApprovedList(this.comObjectClsId))
                    {
                        flag2 = true;
                    }
                    if (!flag2)
                    {
                        base.ThrowTerminatingError(new ErrorRecord(new PSNotSupportedException(NewObjectStrings.CannotCreateTypeConstrainedLanguage), "CannotCreateComTypeConstrainedLanguage", ErrorCategory.PermissionDenied, null));
                        return;
                    }
                }
                PSSQMAPI.IncrementDataPoint((int)0x2099);
                object targetObject = this.CreateComObject();
                string fullName     = targetObject.GetType().FullName;
                if (!fullName.Equals("System.__ComObject"))
                {
                    exception = PSTraceSource.NewArgumentException("TypeName", "NewObjectStrings", "ComInteropLoaded", new object[] { fullName });
                    base.WriteVerbose(exception.Message);
                    if (this.Strict != 0)
                    {
                        base.WriteError(new ErrorRecord(exception, "ComInteropLoaded", ErrorCategory.InvalidArgument, targetObject));
                    }
                }
                if ((targetObject != null) && (this.property != null))
                {
                    targetObject = LanguagePrimitives.SetObjectProperties(targetObject, this.Property, result, new LanguagePrimitives.MemberNotFoundError(this.CreateMemberNotFoundError), new LanguagePrimitives.MemberSetValueError(this.CreateMemberSetValueError), true);
                }
                base.WriteObject(targetObject);
            }
        }