コード例 #1
0
    // Returns true if the expected result is right
    // Returns false if the expected result is wrong
    public bool PosTest2()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest2: the parameter string is null.");
        try
        {
            string                expectValue  = null;
            ArgumentException     dpoExpection = new ArgumentException();
            MemberAccessException myException  = new MemberAccessException(expectValue, dpoExpection);
            if (myException == null)
            {
                TestLibrary.TestFramework.LogError("002.1", "MemberAccessException instance can not create correctly.");
                retVal = false;
            }
            if (myException.Message == expectValue)
            {
                TestLibrary.TestFramework.LogError("002.2", "the Message should return the default value.");
                retVal = false;
            }
            if (!(myException.InnerException is ArgumentException))
            {
                TestLibrary.TestFramework.LogError("002.3", "the InnerException should return MemberAccessException.");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("002.0", "Unexpected exception: " + e);
            retVal = false;
        }
        return(retVal);
    }
コード例 #2
0
        public void ObjectNotTypeTest_MemberAccessExceptionCastToAbstractProductCallInvalidCastException()
        {
            var    obj     = new MemberAccessException();
            string message = "Problem";

            ValidationHelper.ObjectNotType <AbstractGood>(obj, message);
        }
コード例 #3
0
        public static void Ctor_String()
        {
            string message   = "you cannot access this member";
            var    exception = new MemberAccessException(message);

            ExceptionHelpers.ValidateExceptionProperties(exception, hResult: COR_E_MEMBERACCESS, message: message);
        }
コード例 #4
0
        /// <summary>
        /// 以指定的方法为基础,定义抛出未实现异常的重写方法,并添加到当前类型。
        /// </summary>
        /// <param name="type">要定义方法的 <see cref="TypeBuilder"/> 对象。</param>
        /// <param name="baseMethod">作为基础的方法。</param>
        /// <param name="explicitOverride">指定是否以显式方式重写。</param>
        /// <returns>定义的方法,抛出 <see cref="NotImplementedException"/> 异常。</returns>
        /// <exception cref="ArgumentException">
        /// <paramref name="baseMethod"/> 无法在程序集外部重写。</exception>
        /// <exception cref="ArgumentNullException">存在为 <see langword="null"/> 的参数。</exception>
        public static MethodBuilder DefineNotImplementedMethodOverride(
            this TypeBuilder type, MethodInfo baseMethod, bool explicitOverride = false)
        {
            if (type is null)
            {
                throw new ArgumentNullException(nameof(type));
            }
            if (baseMethod is null)
            {
                throw new ArgumentNullException(nameof(baseMethod));
            }
            if (!baseMethod.IsOverridable())
            {
                var inner = new MemberAccessException();
                throw new ArgumentException(inner.Message, nameof(baseMethod), inner);
            }

            var method = type.DefineMethodOverride(baseMethod, explicitOverride);

            var il = method.GetILGenerator();

            il.Emit(OpCodes.Newobj,
                    typeof(NotImplementedException).GetConstructor(Type.EmptyTypes) !);
            il.Emit(OpCodes.Throw);

            return(method);
        }
コード例 #5
0
        /// <summary>
        /// 以指定的构造函数为基础,定义仅调用此构造函数的构造函数,并添加到当前类型。
        /// </summary>
        /// <param name="type">要定义构造函数的 <see cref="TypeBuilder"/> 对象。</param>
        /// <param name="baseConstructor">作为基础的构造函数。</param>
        /// <returns>定义的构造函数,调用 <paramref name="baseConstructor"/> 构造函数。</returns>
        /// <exception cref="ArgumentException">
        /// <paramref name="baseConstructor"/> 的访问级别不为公共或保护。</exception>
        /// <exception cref="ArgumentNullException">存在为 <see langword="null"/> 的参数。</exception>
        public static ConstructorBuilder DefineBaseInvokeConstructorLike(
            this TypeBuilder type, ConstructorInfo baseConstructor)
        {
            if (type is null)
            {
                throw new ArgumentNullException(nameof(type));
            }
            if (baseConstructor is null)
            {
                throw new ArgumentNullException(nameof(baseConstructor));
            }
            if (!baseConstructor.IsInheritable())
            {
                var inner = new MemberAccessException();
                throw new ArgumentException(inner.Message, nameof(baseConstructor), inner);
            }

            var constructor = type.DefineConstructorLike(baseConstructor);

            var il = constructor.GetILGenerator();

            il.Emit(OpCodes.Ldarg_0);
            for (int index = 0; index < baseConstructor.GetParameters().Length; index++)
            {
                il.EmitLdarg(index + 1);
            }
            il.Emit(OpCodes.Call, baseConstructor);
            il.Emit(OpCodes.Ret);

            return(constructor);
        }
コード例 #6
0
 // Returns true if the expected result is right
 // Returns false if the expected result is wrong
 public bool PosTest2()
 {
     bool retVal = true;
     TestLibrary.TestFramework.BeginScenario("PosTest2: the parameter string is null.");
     try
     {
         string expectValue = null;
         ArgumentException dpoExpection = new ArgumentException();
         MemberAccessException myException = new MemberAccessException(expectValue, dpoExpection);
         if (myException == null)
         {
             TestLibrary.TestFramework.LogError("002.1", "MemberAccessException instance can not create correctly.");
             retVal = false;
         }
         if (myException.Message == expectValue)
         {
             TestLibrary.TestFramework.LogError("002.2", "the Message should return the default value.");
             retVal = false;
         }
         if (!(myException.InnerException is ArgumentException))
         {
             TestLibrary.TestFramework.LogError("002.3", "the InnerException should return MemberAccessException.");
             retVal = false;
         }
     }
     catch (Exception e)
     {
         TestLibrary.TestFramework.LogError("002.0", "Unexpected exception: " + e);
         retVal = false;
     }
     return retVal;
 }
コード例 #7
0
 // Returns true if the expected result is right
 // Returns false if the expected result is wrong
 public bool PosTest1()
 {
     bool retVal = true;
     TestLibrary.TestFramework.BeginScenario("PosTest1: Create a new instance of MemberAccessException.");
     try
     {
         string expectValue = "HELLO";
         ArgumentException notFoundException = new ArgumentException();
         MemberAccessException myException = new MemberAccessException(expectValue, notFoundException);
         if (myException == null)
         {
             TestLibrary.TestFramework.LogError("001.1", "MemberAccessException instance can not create correctly.");
             retVal = false;
         }
         if (myException.Message != expectValue)
         {
             TestLibrary.TestFramework.LogError("001.2", "the Message should return " + expectValue);
             retVal = false;
         }
         if (!(myException.InnerException is ArgumentException))
         {
             TestLibrary.TestFramework.LogError("001.3", "the InnerException should return ArgumentException.");
             retVal = false;
         }
     }
     catch (Exception e)
     {
         TestLibrary.TestFramework.LogError("001.0", "Unexpected exception: " + e);
         retVal = false;
     }
     return retVal;
 }
コード例 #8
0
        /// <summary>
        /// 以指定的构造函数为基础,定义构造函数,并添加到当前类型。
        /// </summary>
        /// <param name="type">要定义构造函数的 <see cref="TypeBuilder"/> 对象。</param>
        /// <param name="baseConstructor">作为基础的构造函数。</param>
        /// <returns>定义的构造函数,仅包括构造函数定义,不包括任何实现。</returns>
        /// <exception cref="ArgumentException">
        /// <paramref name="baseConstructor"/> 的访问级别不为公共或保护。</exception>
        /// <exception cref="ArgumentNullException">存在为 <see langword="null"/> 的参数。</exception>
        public static ConstructorBuilder DefineConstructorLike(
            this TypeBuilder type, ConstructorInfo baseConstructor)
        {
            if (type is null)
            {
                throw new ArgumentNullException(nameof(type));
            }
            if (baseConstructor is null)
            {
                throw new ArgumentNullException(nameof(baseConstructor));
            }
            if (!baseConstructor.IsInheritable())
            {
                var inner = new MemberAccessException();
                throw new ArgumentException(inner.Message, nameof(baseConstructor), inner);
            }

            var constructor = type.DefineConstructor(
                baseConstructor.Attributes, baseConstructor.CallingConvention,
                Array.ConvertAll(baseConstructor.GetParameters(), param => param.ParameterType));

            var baseParameters = baseConstructor.GetParameters();

            for (int index = 0; index < baseParameters.Length; index++)
            {
                var baseParameter = baseParameters[index];
                var parameter     = constructor.DefineParameter(index + 1,
                                                                baseParameter.Attributes, baseParameter.Name);
            }

            return(constructor);
        }
コード例 #9
0
        /// <summary>
        /// Verify caller has access to the getter/setter property
        /// </summary>
        private void CheckAccess(bool getValue)
        {
            if (m_isIndexerWithoutMetadata)
            {
                return;
            }

            MethodInfo accessor = getValue ? m_property.GetMethod : m_property.SetMethod;

            if (accessor == null)
            {
                throw new ArgumentException(getValue ? SR.Arg_GetMethNotFnd : SR.Arg_SetMethNotFnd);
            }

            if (!accessor.IsPublic)
            {
                Exception ex = new MemberAccessException(
                    String.Format(
                        CultureInfo.CurrentCulture,
                        SR.Arg_MethodAccessException_WithMethodName,
                        accessor.ToString(),
                        accessor.DeclaringType.FullName)
                    );

                // We need to make sure it has the same HR that we were returning in desktop
                InteropExtensions.SetExceptionErrorCode(ex, __HResults.COR_E_METHODACCESS);
                throw ex;
            }
        }
コード例 #10
0
    // Returns true if the expected result is right
    // Returns false if the expected result is wrong
    public bool PosTest1()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest1: Create a new instance of MemberAccessException.");
        try
        {
            string                expectValue       = "HELLO";
            ArgumentException     notFoundException = new ArgumentException();
            MemberAccessException myException       = new MemberAccessException(expectValue, notFoundException);
            if (myException == null)
            {
                TestLibrary.TestFramework.LogError("001.1", "MemberAccessException instance can not create correctly.");
                retVal = false;
            }
            if (myException.Message != expectValue)
            {
                TestLibrary.TestFramework.LogError("001.2", "the Message should return " + expectValue);
                retVal = false;
            }
            if (!(myException.InnerException is ArgumentException))
            {
                TestLibrary.TestFramework.LogError("001.3", "the InnerException should return ArgumentException.");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("001.0", "Unexpected exception: " + e);
            retVal = false;
        }
        return(retVal);
    }
コード例 #11
0
        private void Handle(MemberAccessException ex, String methodName)
        {
            String message = "Unexpected exception encountered invoking setter-method '" + methodName + "' on class '" +
                             _beanEventType.UnderlyingType.Name + "' : " + ex.Message;

            Log.Error(message, ex);
        }
コード例 #12
0
        public static void Ctor_String_Exception()
        {
            string message        = "you cannot access this member";
            var    innerException = new Exception("Inner exception");
            var    exception      = new MemberAccessException(message, innerException);

            ExceptionUtility.ValidateExceptionProperties(exception, hResult: COR_E_MEMBERACCESS, innerException: innerException, message: message);
        }
コード例 #13
0
 private static ArgumentException BuildUnableToResolveTypeDueToSecurityConfigException(
     Type type, MemberAccessException innerException, string paramName)
 {
     // This happens when the user tries to resolve an internal type inside a (Silverlight) sandbox.
     return(new ArgumentException(
                StringResources.UnableToResolveTypeDueToSecurityConfiguration(type, innerException) +
                Environment.NewLine + "paramName: " + paramName, innerException));
 }
コード例 #14
0
 public void HandleException(
     object targetObject,
     MethodInfo fastMethod,
     MemberAccessException ex,
     object[] parameters)
 {
     log.Error("Exception encountered: " + ex.Message, ex);
     HandleExceptionCommon(targetObject, fastMethod, ex, parameters);
 }
コード例 #15
0
        public override TData TryGetData(out Exception exception)
        {
            try {
                var metadata = (IParentSupport)Parent; if (!ValidateNotNull(metadata, "Metadata", "Parent", "{FB2701BA-78A8-4E72-811E-6D254188AC91}", out exception))
                {
                    return(default(TData));
                }
                var vm = (IObjectVM)metadata.Parent; if (!ValidateNotNull(vm, "Viewmodel", "Parent.Parent", "{D8F4FB1A-6C1B-4345-AF2E-A1FF2809A9D0}", out exception))
                {
                    return(default(TData));
                }
                var pvm = vm.Parent;                                      //if(!ValidateNotNull(pvm,"Viewmodel","Parent.Parent.Parent","{DC61F92C-82AB-4C9A-9E5E-0F31D968B90B}", out exception)) return default(TData);
                if (pvm == null)
                {
//					Debug.WriteLine("WARNING: throw NullReferenceException {602C1F25-9625-4B9C-B8F0-B45069067EC3}"
//						+"\r\n\t"+"ObjectVM.Parent"
//						+"\r\n\t"+vm.GetType().FullName
//						+"\r\n\t"+vm.MemberPath
//					);
                    exception = new NullReferenceException("Parent view model is null! UniqueID: {602C1F25-9625-4B9C-B8F0-B45069067EC3}");                   //TODO
                    return(default(TData));
                }
                if (!ValidateNotNull(pvm.Metadata, "Metadata", "*.Metadata", "{FB2701BA-78A8-4E72-811E-6D254188AC91}", out exception))
                {
                    return(default(TData));
                }
                if (!pvm.Metadata.HasDataProvider)
                {
                    exception = new NullReferenceException("Dataprovider ist null! UniqueID: {20BE48F4-B5DF-4B3B-930B-37D019AB9AF6}");
                    return(default(TData));
                }
                var rootData = pvm.Metadata.DataProvider.TryGetData(out exception);
                if (exception != null)
                {
                    exception = new MemberAccessException("Get data of parent model failed!", exception);
                    return(default(TData));
                }

                if (rootData == null)
                {
                    //Debug.WriteLine("throw NullReferenceException {28A9F70F-5977-49C0-893D-9CEEB95E9066}");
                    exception = new NullReferenceException("RootData is null! UniqueID: {28A9F70F-5977-49C0-893D-9CEEB95E9066}");                  //TODO
                    return(default(TData));
                }
//				var t = rootData.GetType();
//				var prop = t.GetProperty(_path);
//				var value = prop.GetValue(rootData, null);

                var value = new Json(rootData, parse: false, isReadonly: true)[_path].NativeValue;

                exception = null;
                return((TData)value);
            }catch (Exception ex) {
                exception = ex;
                return(default(TData));
            }
        }
コード例 #16
0
 private static void ThrowIfFullTrust(Type type, bool isFullyTrusted, MemberAccessException ex)
 {
     if (ex.InnerException != null && ex.InnerException is SecurityException)
     {
         if (LogSecurityException(type, isFullyTrusted, ex.InnerException as SecurityException))
         {
             return;
         }
     }
     throw ex;
 }
コード例 #17
0
        private void Handle(
            MemberAccessException ex,
            string fieldName)
        {
            var message = "Unexpected exception encountered invoking setter for field '" +
                          fieldName +
                          "' on class '" +
                          _jsonEventType.UnderlyingType.Name +
                          "' : " +
                          ex.Message;

            Log.Error(message, ex);
        }
コード例 #18
0
        /// <summary>
        /// Verify caller has access to the getter/setter property
        /// Return true if we can use reflection to access the property. False otherwise.
        /// </summary>
        private bool CheckAccess(bool getValue)
        {
            //
            // If no property, there is nothing to check against
            // We'll use IList/IDictionary to access them
            //
            if (m_property == null)
            {
                Debug.Assert(m_supportIndexerWithoutMetadata);

                return(false);
            }

            MethodInfo accessor = getValue ? m_property.GetMethod : m_property.SetMethod;

            if (accessor == null)
            {
                if (m_supportIndexerWithoutMetadata)
                {
                    return(false);
                }
                else
                {
                    throw new ArgumentException(getValue ? SR.Arg_GetMethNotFnd : SR.Arg_SetMethNotFnd);
                }
            }

            if (!accessor.IsPublic)
            {
                if (m_supportIndexerWithoutMetadata)
                {
                    return(false);
                }
                else
                {
                    Exception ex = new MemberAccessException(
                        String.Format(
                            CultureInfo.CurrentCulture,
                            SR.Arg_MethodAccessException_WithMethodName,
                            accessor.ToString(),
                            accessor.DeclaringType.FullName)
                        );

                    // We need to make sure it has the same HR that we were returning in desktop
                    InteropExtensions.SetExceptionErrorCode(ex, __HResults.COR_E_METHODACCESS);
                    throw ex;
                }
            }

            return(true);
        }
コード例 #19
0
        /// <summary>
        /// 以指定的属性为基础,定义抛出未实现异常的重写属性,并添加到当前类型。
        /// </summary>
        /// <param name="type">要定义属性的 <see cref="TypeBuilder"/> 对象。</param>
        /// <param name="baseProperty">作为基础的属性。</param>
        /// <param name="explicitOverride">指定是否以显式方式重写。</param>
        /// <returns>定义完成的属性,抛出 <see cref="NotImplementedException"/> 异常。</returns>
        /// <exception cref="ArgumentException">
        /// <paramref name="baseProperty"/> 的方法无法在程序集外部重写。</exception>
        /// <exception cref="ArgumentNullException">存在为 <see langword="null"/> 的参数。</exception>
        public static PropertyBuilder DefineNotImplementedPropertyOverride(
            this TypeBuilder type, PropertyInfo baseProperty, bool explicitOverride = false)
        {
            if (type is null)
            {
                throw new ArgumentNullException(nameof(type));
            }
            if (baseProperty is null)
            {
                throw new ArgumentNullException(nameof(baseProperty));
            }
            if (!baseProperty.GetAccessors().All(accessor => accessor.IsOverridable()))
            {
                var inner = new MemberAccessException();
                throw new ArgumentException(inner.Message, nameof(baseProperty), inner);
            }

            var propertyName = baseProperty.Name;

            if (explicitOverride)
            {
                var baseHandle = baseProperty.GetAccessors().First().MethodHandle;
                propertyName += $"#{baseHandle.Value.ToString()}";
            }

            var property = type.DefineProperty(
                propertyName, baseProperty.Attributes, baseProperty.PropertyType,
                Array.ConvertAll(baseProperty.GetIndexParameters(), param => param.ParameterType));

            if (baseProperty.CanRead)
            {
                var method = type.DefineNotImplementedMethodOverride(baseProperty.GetMethod !, explicitOverride);
                property.SetGetMethod(method);
            }

            if (baseProperty.CanWrite)
            {
                var method = type.DefineNotImplementedMethodOverride(baseProperty.SetMethod !, explicitOverride);
                property.SetSetMethod(method);
            }

            return(property);
        }
コード例 #20
0
        /// <summary>
        /// 以指定的事件为基础,定义抛出未实现异常的重写事件,并添加到当前类型。
        /// </summary>
        /// <param name="type">要定义事件的 <see cref="TypeBuilder"/> 对象。</param>
        /// <param name="baseEvent">作为基础的事件。</param>
        /// <param name="explicitOverride">指定是否以显式方式重写。</param>
        /// <returns>定义的事件,抛出 <see cref="NotImplementedException"/> 异常。</returns>
        /// <exception cref="ArgumentException">
        /// <paramref name="baseEvent"/> 的方法无法在程序集外部重写。</exception>
        /// <exception cref="ArgumentNullException">存在为 <see langword="null"/> 的参数。</exception>
        public static EventBuilder DefineNotImplementedEventOverride(
            this TypeBuilder type, EventInfo baseEvent, bool explicitOverride = false)
        {
            if (type is null)
            {
                throw new ArgumentNullException(nameof(type));
            }
            if (baseEvent is null)
            {
                throw new ArgumentNullException(nameof(baseEvent));
            }
            if (!baseEvent.AddMethod !.IsOverridable())
            {
                var inner = new MemberAccessException();
                throw new ArgumentException(inner.Message, nameof(baseEvent), inner);
            }

            var eventName = baseEvent.Name;

            if (explicitOverride)
            {
                var baseHandle = baseEvent.AddMethod !.MethodHandle;
                eventName += $"#{baseHandle.Value.ToString()}";
            }

            var @event = type.DefineEvent(
                eventName, baseEvent.Attributes, baseEvent.EventHandlerType !);

            {
                var baseMethod = baseEvent.AddMethod !;
                var method     = type.DefineNotImplementedMethodOverride(baseMethod, explicitOverride);
                @event.SetAddOnMethod(method);
            }

            {
                var baseMethod = baseEvent.RemoveMethod !;
                var method     = type.DefineNotImplementedMethodOverride(baseMethod, explicitOverride);
                @event.SetRemoveOnMethod(method);
            }

            return(@event);
        }
コード例 #21
0
 // Returns true if the expected result is right
 // Returns false if the expected result is wrong
 public bool PosTest1()
 {
     bool retVal = true;
     TestLibrary.TestFramework.BeginScenario("PosTest1: Create a new instance of MemberAccessException.");
     try
     {
         MemberAccessException myException = new MemberAccessException();
         if (myException == null)
         {
             TestLibrary.TestFramework.LogError("001.1", "MemberAccessException instance can not create correctly.");
             retVal = false;
         }
     }
     catch (Exception e)
     {
         TestLibrary.TestFramework.LogError("001.0", "Unexpected exception: " + e);
         retVal = false;
     }
     return retVal;
 }
コード例 #22
0
    // Returns true if the expected result is right
    // Returns false if the expected result is wrong
    public bool PosTest1()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest1: Create a new instance of MemberAccessException.");
        try
        {
            MemberAccessException myException = new MemberAccessException();
            if (myException == null)
            {
                TestLibrary.TestFramework.LogError("001.1", "MemberAccessException instance can not create correctly.");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("001.0", "Unexpected exception: " + e);
            retVal = false;
        }
        return(retVal);
    }
コード例 #23
0
        /// <summary>
        /// 以指定的方法为基础,定义调用代理对象方法的重写方法,并添加到当前类型。
        /// </summary>
        /// <param name="type">要定义方法的 <see cref="TypeBuilder"/> 对象。</param>
        /// <param name="baseMethod">作为基础的方法。</param>
        /// <param name="instanceField">代理对象的字段;<see langword="null"/> 表示代理对象为当前实例。</param>
        /// <param name="explicitOverride">指定是否以显式方式重写。</param>
        /// <returns>定义的方法,调用代理对象的 <paramref name="baseMethod"/> 方法。</returns>
        /// <exception cref="ArgumentException">
        /// <paramref name="baseMethod"/> 的声明类型不为接口。</exception>
        /// <exception cref="ArgumentNullException">存在为 <see langword="null"/> 的参数。</exception>
        internal static MethodBuilder DefineBaseInvokeMethodOverride(
            this TypeBuilder type, MethodInfo baseMethod,
            FieldInfo?instanceField = null, bool explicitOverride = false)
        {
            if (type is null)
            {
                throw new ArgumentNullException(nameof(type));
            }
            if (baseMethod is null)
            {
                throw new ArgumentNullException(nameof(baseMethod));
            }
            if (!baseMethod.IsProxyOverride())
            {
                var inner = new MemberAccessException();
                throw new ArgumentException(inner.Message, nameof(baseMethod), inner);
            }

            var method = type.DefineMethodOverride(baseMethod, explicitOverride);

            var il = method.GetILGenerator();

            il.Emit(OpCodes.Ldarg_0);
            if (instanceField is not null)
            {
                il.Emit(OpCodes.Ldfld, instanceField);
            }
            for (int index = 0; index < baseMethod.GetParameters().Length; index++)
            {
                il.EmitLdarg(index + 1);
            }
            il.Emit((instanceField is null) ? OpCodes.Call : OpCodes.Callvirt,
                    (baseMethod.GetGenericArguments().Length == 0) ? baseMethod :
                    baseMethod.MakeGenericMethod(method.GetGenericArguments()));
            il.Emit(OpCodes.Ret);

            type.DefineMethodOverride(method, baseMethod);

            return(method);
        }
コード例 #24
0
 private static void HandleInnerException(ref RunningResults results, MemberAccessException ex)
 {
     results.Verdict = Verdict.SecurityException;
     results.Error   = ex.ToString();
 }
コード例 #25
0
 private static RunningResults HandleInnerException(MemberAccessException ex)
 {
     return(new RunningResults(Verdict.SecurityException, output: ex.ToString()));
 }
コード例 #26
0
        /// <summary>
        /// Verify caller has access to the getter/setter property
        /// </summary>
        private void CheckAccess(bool getValue)
        {
            if (m_isIndexerWithoutMetadata)
            {
                return;
            }

            MethodInfo accessor = getValue ? m_property.GetMethod : m_property.SetMethod;

            if (accessor == null)
                throw new ArgumentException(getValue ? SR.Arg_GetMethNotFnd : SR.Arg_SetMethNotFnd);

            if (!accessor.IsPublic)
            {
                Exception ex = new MemberAccessException(
                    String.Format(
                        CultureInfo.CurrentCulture,
                        SR.Arg_MethodAccessException_WithMethodName,
                        accessor.ToString(),
                        accessor.DeclaringType.FullName)
                    );

                // We need to make sure it has the same HR that we were returning in desktop
                InteropExtensions.SetExceptionErrorCode(ex, __HResults.COR_E_METHODACCESS);
                throw ex;
            }
        }
コード例 #27
0
 public static PropertyAccessException GetIllegalAccessException(MethodInfo method, MemberAccessException e)
 {
     return(GetAccessExceptionMethod(method, e));
 }
コード例 #28
0
ファイル: CustomPropertyImpl.cs プロジェクト: tijoytom/corert
        /// <summary>
        /// Verify caller has access to the getter/setter property
        /// Return true if we can use reflection to access the property. False otherwise.
        /// </summary>
        private bool CheckAccess(bool getValue)
        {
            //
            // If no property, there is nothing to check against
            // We'll use IList/IDictionary to access them
            //
            if (m_property == null)
            {
                Debug.Assert(m_supportIndexerWithoutMetadata);

                return false;
            }

            MethodInfo accessor = getValue ? m_property.GetMethod : m_property.SetMethod;

            if (accessor == null)
            {
                if (m_supportIndexerWithoutMetadata)
                {
                    return false;
                }
                else
                {
                    throw new ArgumentException(getValue ? SR.Arg_GetMethNotFnd : SR.Arg_SetMethNotFnd);
                }
            }

            if (!accessor.IsPublic)
            {
                if (m_supportIndexerWithoutMetadata)
                {
                    return false;
                }
                else
                {
                    Exception ex = new MemberAccessException(
                    String.Format(
                        CultureInfo.CurrentCulture,
                        SR.Arg_MethodAccessException_WithMethodName,
                        accessor.ToString(),
                        accessor.DeclaringType.FullName)
                    );

                    // We need to make sure it has the same HR that we were returning in desktop
                    InteropExtensions.SetExceptionErrorCode(ex, __HResults.COR_E_METHODACCESS);
                    throw ex;
                }
            }

            return true;
        }
コード例 #29
0
        public static void Ctor_Empty()
        {
            var exception = new MemberAccessException();

            ExceptionHelpers.ValidateExceptionProperties(exception, hResult: COR_E_MEMBERACCESS, validateMessage: false);
        }
コード例 #30
0
        /// <summary>
        /// 以指定的方法为基础,定义重写方法,并添加到当前类型。
        /// </summary>
        /// <param name="type">要定义方法的 <see cref="TypeBuilder"/> 对象。</param>
        /// <param name="baseMethod">作为基础的方法。</param>
        /// <param name="explicitOverride">指定是否以显式方式重写。</param>
        /// <returns>定义的方法,仅包括方法定义,不包括任何实现。</returns>
        /// <exception cref="ArgumentException">
        /// <paramref name="baseMethod"/> 无法在程序集外部重写。</exception>
        /// <exception cref="ArgumentNullException">存在为 <see langword="null"/> 的参数。</exception>
        public static MethodBuilder DefineMethodOverride(
            this TypeBuilder type, MethodInfo baseMethod, bool explicitOverride = false)
        {
            if (type is null)
            {
                throw new ArgumentNullException(nameof(type));
            }
            if (baseMethod is null)
            {
                throw new ArgumentNullException(nameof(baseMethod));
            }
            if (!baseMethod.IsOverridable())
            {
                var inner = new MemberAccessException();
                throw new ArgumentException(inner.Message, nameof(baseMethod), inner);
            }

            var baseGenericParams = baseMethod.GetGenericArguments();
            var baseReturnParam   = baseMethod.ReturnParameter;
            var baseParameters    = baseMethod.GetParameters();

            var methodName = baseMethod.Name;

            if (explicitOverride)
            {
                var baseHandle = baseMethod.MethodHandle;
                methodName += $"#{baseHandle.Value.ToString()}";
            }
            var attributes = baseMethod.Attributes;

            attributes &= ~MethodAttributes.Abstract;
            if (!baseMethod.DeclaringType !.IsInterface)
            {
                attributes &= ~MethodAttributes.NewSlot;
            }
            if (explicitOverride)
            {
                attributes &= ~MethodAttributes.MemberAccessMask;
                attributes |= MethodAttributes.Private;
            }

            var method = type.DefineMethod(methodName,
                                           attributes, baseMethod.CallingConvention, baseReturnParam.ParameterType,
                                           Array.ConvertAll(baseParameters, param => param.ParameterType));

            var genericParams = (baseGenericParams.Length == 0) ?
                                Array.Empty <GenericTypeParameterBuilder>() :
                                method.DefineGenericParameters(
                Array.ConvertAll(baseGenericParams, param => param.Name));

            var returnParam = method.DefineParameter(0,
                                                     baseReturnParam.Attributes, baseReturnParam.Name);

            for (int index = 0; index < baseParameters.Length; index++)
            {
                var baseParameter = baseParameters[index];
                var parameter     = method.DefineParameter(index + 1,
                                                           baseParameter.Attributes, baseParameter.Name);
            }

            if (explicitOverride)
            {
                type.DefineMethodOverride(method, baseMethod);
            }

            return(method);
        }
コード例 #31
0
        /// <summary>
        /// 以指定的方法为基础,定义调用指定代理委托的重写方法,并添加到当前类型。
        /// </summary>
        /// <param name="type">要定义方法的 <see cref="TypeBuilder"/> 对象。</param>
        /// <param name="baseMethod">作为基础的方法。</param>
        /// <param name="baseType">定义基础方法的类型;若为泛型类型,则应为构造泛型类型。</param>
        /// <param name="baseMethodInfoField">基础方法的 <see cref="MethodInfo"/> 字段。</param>
        /// <param name="baseMethodDelegateField">基础方法的 <see cref="MethodDelegate"/> 字段。</param>
        /// <param name="methodInvokeHandlerField">当前类型的代理委托字段。</param>
        /// <param name="instanceField">代理对象的字段;<see langword="null"/> 表示代理对象为当前实例。</param>
        /// <param name="explicitOverride">指定是否以显式方式重写。</param>
        /// <returns>定义的方法,调用 <paramref name="methodInvokeHandlerField"/> 字段的代理委托。</returns>
        /// <exception cref="ArgumentException">
        /// <paramref name="baseMethod"/> 无法在程序集外部重写。</exception>
        /// <exception cref="ArgumentNullException">存在为 <see langword="null"/> 的参数。</exception>
        internal static MethodBuilder DefineProxyMethodOverride(
            this TypeBuilder type, MethodInfo baseMethod, Type baseType,
            FieldInfo baseMethodInfoField, FieldInfo baseMethodDelegateField,
            FieldInfo methodInvokeHandlerField,
            FieldInfo?instanceField = null, bool explicitOverride = false)
        {
            if (type is null)
            {
                throw new ArgumentNullException(nameof(type));
            }
            if (baseMethod is null)
            {
                throw new ArgumentNullException(nameof(baseMethod));
            }
            if (baseType is null)
            {
                throw new ArgumentNullException(nameof(baseType));
            }
            if (baseMethodInfoField is null)
            {
                throw new ArgumentNullException(nameof(baseMethodInfoField));
            }
            if (baseMethodDelegateField is null)
            {
                throw new ArgumentNullException(nameof(baseMethodDelegateField));
            }
            if (methodInvokeHandlerField is null)
            {
                throw new ArgumentNullException(nameof(methodInvokeHandlerField));
            }
            if (!baseMethod.IsProxyOverride())
            {
                var inner = new MemberAccessException();
                throw new ArgumentException(inner.Message, nameof(baseMethod), inner);
            }

            var method = type.DefineMethodOverride(baseMethod, explicitOverride);

            if (baseMethod.IsGenericMethod)
            {
                baseMethodDelegateField = TypeBuilder.GetField(
                    baseMethodDelegateField.DeclaringType !.MakeGenericType(
                        method.GetGenericArguments()), baseMethodDelegateField);
                baseMethodInfoField = TypeBuilder.GetField(
                    baseMethodInfoField.DeclaringType !.MakeGenericType(
                        method.GetGenericArguments()), baseMethodInfoField);
            }

            var baseHasGenericConstraints = baseMethod.GetGenericArguments().Any(
                param => param.GetGenericParameterConstraints().Length != 0);

            var il = method.GetILGenerator();

            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldfld, methodInvokeHandlerField);
            il.Emit(OpCodes.Ldarg_0);
            if (instanceField is not null)
            {
                il.Emit(OpCodes.Ldfld, instanceField);
            }
            il.EmitBox(baseType);
            if (baseHasGenericConstraints)
            {
                il.Emit(OpCodes.Ldtoken, baseMethodInfoField);
                il.Emit(OpCodes.Ldtoken, baseMethodInfoField.DeclaringType !);
                il.Emit(OpCodes.Call,
                        typeof(FieldInfo).GetMethod(
                            nameof(FieldInfo.GetFieldFromHandle),
                            new[] { typeof(RuntimeFieldHandle), typeof(RuntimeTypeHandle) }) !);
                il.Emit(OpCodes.Ldnull);
                il.Emit(OpCodes.Callvirt, typeof(FieldInfo).GetMethod(nameof(FieldInfo.GetValue)) !);
            }
            else
            {
                il.Emit(OpCodes.Ldsfld, baseMethodInfoField);
            }
            if (baseHasGenericConstraints)
            {
                il.Emit(OpCodes.Ldtoken, baseMethodDelegateField);
                il.Emit(OpCodes.Ldtoken, baseMethodDelegateField.DeclaringType !);
                il.Emit(OpCodes.Call,
                        typeof(FieldInfo).GetMethod(
                            nameof(FieldInfo.GetFieldFromHandle),
                            new[] { typeof(RuntimeFieldHandle), typeof(RuntimeTypeHandle) }) !);
                il.Emit(OpCodes.Ldnull);
                il.Emit(OpCodes.Callvirt, typeof(FieldInfo).GetMethod(nameof(FieldInfo.GetValue)) !);
            }
            else
            {
                il.Emit(OpCodes.Ldsfld, baseMethodDelegateField);
            }
            var baseParameters = baseMethod.GetParameters();

            il.EmitLdcI4(baseParameters.Length);
            il.Emit(OpCodes.Newarr, typeof(object));
            for (int index = 0; index < baseParameters.Length; index++)
            {
                var baseParameter = baseParameters[index];
                il.Emit(OpCodes.Dup);
                il.EmitLdcI4(index);
                il.EmitLdarg(index + 1);
                il.EmitBox(baseParameter.ParameterType);
                il.Emit(OpCodes.Stelem_Ref);
            }
            il.Emit(OpCodes.Callvirt,
                    typeof(MethodInvokeHandler).GetMethod(nameof(MethodInvokeHandler.Invoke)) !);
            if (baseMethod.ReturnType != typeof(void))
            {
                il.EmitUnbox(baseMethod.ReturnType);
            }
            else
            {
                il.Emit(OpCodes.Pop);
            }
            il.Emit(OpCodes.Ret);

            return(method);
        }
コード例 #32
0
        /// <summary>
        /// 以指定的方法为基础,定义基类方法的 <see cref="MethodInfo"/>
        /// 和 <see cref="MethodDelegate"/> 字段,并添加到当前类型。
        /// </summary>
        /// <param name="type">要定义方法的 <see cref="TypeBuilder"/> 对象。</param>
        /// <param name="baseMethod">作为基础的方法。</param>
        /// <param name="baseType">定义基础方法的类型;若为泛型类型,则应为构造泛型类型。</param>
        /// <param name="instanceField">代理对象的字段;<see langword="null"/> 表示代理对象为当前实例。</param>
        /// <returns>定义的基类方法的 <see cref="MethodInfo"/> 和 <see cref="MethodDelegate"/> 字段</returns>
        /// <exception cref="ArgumentException">
        /// <paramref name="baseMethod"/> 无法在程序集外部重写。</exception>
        /// <exception cref="ArgumentNullException">存在为 <see langword="null"/> 的参数。</exception>
        internal static KeyValuePair <FieldBuilder, FieldBuilder> DefineBaseMethodInfoAndDelegateField(
            this TypeBuilder type, MethodInfo baseMethod, Type baseType, FieldInfo?instanceField = null)
        {
            if (type is null)
            {
                throw new ArgumentNullException(nameof(type));
            }
            if (baseMethod is null)
            {
                throw new ArgumentNullException(nameof(baseMethod));
            }
            if (baseType is null)
            {
                throw new ArgumentNullException(nameof(baseType));
            }
            if (!baseMethod.IsProxyOverride())
            {
                var inner = new MemberAccessException();
                throw new ArgumentException(inner.Message, nameof(baseMethod), inner);
            }

            var baseGenericParams = baseMethod.GetGenericArguments();
            var baseReturnParam   = baseMethod.ReturnParameter;
            var baseParameters    = baseMethod.GetParameters();

            var nestedType = type.DefineNestedType(
                $"@{baseMethod.Name}#{baseMethod.MethodHandle.Value.ToString()}",
                TypeAttributes.Class | TypeAttributes.NestedPrivate |
                TypeAttributes.Abstract | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit);

            var genericParams = (baseGenericParams.Length == 0) ?
                                Array.Empty <GenericTypeParameterBuilder>() :
                                nestedType.DefineGenericParameters(
                Array.ConvertAll(baseGenericParams, param => param.Name));

            genericParams.SetGenericConstraintsLike(baseGenericParams, baseType.GetGenericArguments());

            var delegateMethod = nestedType.DefineMethod(nameof(MethodDelegate.Invoke),
                                                         MethodAttributes.Assembly | MethodAttributes.Static | MethodAttributes.HideBySig,
                                                         typeof(object), new[] { typeof(object), typeof(object[]) });
            {
                delegateMethod.DefineParameter(1, ParameterAttributes.None, "instance");
                delegateMethod.DefineParameter(2, ParameterAttributes.None, "arguments");

                var il = delegateMethod.GetILGenerator();
                il.Emit(OpCodes.Ldarg_0);
                il.EmitUnbox(baseType);
                for (int pIndex = 0; pIndex < baseParameters.Length; pIndex++)
                {
                    var baseParameter = baseParameters[pIndex];
                    int gIndex        = Array.IndexOf(
                        baseGenericParams, baseParameter.ParameterType);
                    var parameterType = (gIndex == -1) ?
                                        baseParameter.ParameterType : genericParams[gIndex];
                    il.Emit(OpCodes.Ldarg_1);
                    il.EmitLdcI4(pIndex);
                    il.Emit(OpCodes.Ldelem_Ref);
                    il.EmitUnbox(parameterType);
                }
                il.Emit((instanceField is null) ? OpCodes.Call : OpCodes.Callvirt,
                        !baseMethod.IsGenericMethod ? baseMethod :
                        baseMethod.MakeGenericMethod(nestedType.GetGenericArguments()));
                if (baseMethod.ReturnType != typeof(void))
                {
                    int gIndex = Array.IndexOf(
                        baseGenericParams, baseReturnParam.ParameterType);
                    var returnType = (gIndex == -1) ?
                                     baseReturnParam.ParameterType : genericParams[gIndex];
                    il.EmitBox(returnType);
                }
                else
                {
                    il.Emit(OpCodes.Ldnull);
                }
                il.Emit(OpCodes.Ret);
            }

            var infoField = nestedType.DefineField(nameof(MethodInfo), typeof(MethodInfo),
                                                   FieldAttributes.Assembly | FieldAttributes.Static | FieldAttributes.InitOnly);

            var delegateField = nestedType.DefineField(nameof(MethodDelegate), typeof(MethodDelegate),
                                                       FieldAttributes.Assembly | FieldAttributes.Static | FieldAttributes.InitOnly);

            var constructor = nestedType.DefineTypeInitializer();

            {
                var il = constructor.GetILGenerator();
                il.Emit(OpCodes.Ldtoken,
                        !baseMethod.IsGenericMethod ? baseMethod :
                        baseMethod.MakeGenericMethod(nestedType.GetGenericArguments()));
                il.Emit(OpCodes.Ldtoken, baseMethod.DeclaringType !);
                il.Emit(OpCodes.Call,
                        typeof(MethodBase).GetMethod(
                            nameof(MethodBase.GetMethodFromHandle),
                            new[] { typeof(RuntimeMethodHandle), typeof(RuntimeTypeHandle) }) !);
                il.Emit(OpCodes.Castclass, typeof(MethodInfo));
                il.Emit(OpCodes.Stsfld, infoField);
                il.Emit(OpCodes.Ldnull);
                il.Emit(OpCodes.Ldftn, delegateMethod);
                il.Emit(OpCodes.Newobj, typeof(MethodDelegate).GetConstructors()[0]);
                il.Emit(OpCodes.Stsfld, delegateField);
                il.Emit(OpCodes.Ret);
            }

            nestedType.CreateTypeInfo();

            return(new KeyValuePair <FieldBuilder, FieldBuilder>(infoField, delegateField));
        }
コード例 #33
0
ファイル: ExceptionHelpers.cs プロジェクト: ebeworld/corert
        /// <summary>
        /// This does a mapping from hr to the exception and also takes care of making default exception in case of classic COM as COMException.
        /// and in winrt and marshal APIs as Exception.
        /// </summary>
        /// <param name="errorCode"></param>
        /// <param name="message"></param>
        /// <param name="createCOMException"></param>
        /// <returns></returns>
        internal static Exception GetMappingExceptionForHR(int errorCode, string message, bool createCOMException, bool hasErrorInfo)
        {
            if (errorCode >= 0)
            {
                return(null);
            }

            Exception exception = null;

            bool shouldDisplayHR = false;

            switch (errorCode)
            {
            case __HResults.COR_E_NOTFINITENUMBER:     // NotFiniteNumberException
            case __HResults.COR_E_ARITHMETIC:
                exception = new ArithmeticException();
                break;

            case __HResults.COR_E_ARGUMENT:
            case unchecked ((int)0x800A01C1):
            case unchecked ((int)0x800A01C2):
            case __HResults.CLR_E_BIND_UNRECOGNIZED_IDENTITY_FORMAT:
                exception = new ArgumentException();

                if (errorCode != __HResults.COR_E_ARGUMENT)
                {
                    shouldDisplayHR = true;
                }

                break;

            case __HResults.E_BOUNDS:
            case __HResults.COR_E_ARGUMENTOUTOFRANGE:
            case __HResults.ERROR_NO_UNICODE_TRANSLATION:
                exception = new ArgumentOutOfRangeException();

                if (errorCode != __HResults.COR_E_ARGUMENTOUTOFRANGE)
                {
                    shouldDisplayHR = true;
                }

                break;

            case __HResults.COR_E_ARRAYTYPEMISMATCH:
                exception = new ArrayTypeMismatchException();
                break;

            case __HResults.COR_E_BADIMAGEFORMAT:
            case __HResults.CLDB_E_FILE_OLDVER:
            case __HResults.CLDB_E_INDEX_NOTFOUND:
            case __HResults.CLDB_E_FILE_CORRUPT:
            case __HResults.COR_E_NEWER_RUNTIME:
            case __HResults.COR_E_ASSEMBLYEXPECTED:
            case __HResults.ERROR_BAD_EXE_FORMAT:
            case __HResults.ERROR_EXE_MARKED_INVALID:
            case __HResults.CORSEC_E_INVALID_IMAGE_FORMAT:
            case __HResults.ERROR_NOACCESS:
            case __HResults.ERROR_INVALID_ORDINAL:
            case __HResults.ERROR_INVALID_DLL:
            case __HResults.ERROR_FILE_CORRUPT:
            case __HResults.COR_E_LOADING_REFERENCE_ASSEMBLY:
            case __HResults.META_E_BAD_SIGNATURE:
                exception = new BadImageFormatException();

                // Always show HR for BadImageFormatException
                shouldDisplayHR = true;

                break;

            case __HResults.COR_E_CUSTOMATTRIBUTEFORMAT:
                exception = new FormatException();
                break;     // CustomAttributeFormatException

            case __HResults.COR_E_DATAMISALIGNED:
                exception = InteropExtensions.CreateDataMisalignedException(message);     // TODO: Do we need to add msg here?
                break;

            case __HResults.COR_E_DIVIDEBYZERO:
            case __HResults.CTL_E_DIVISIONBYZERO:
                exception = new DivideByZeroException();

                if (errorCode != __HResults.COR_E_DIVIDEBYZERO)
                {
                    shouldDisplayHR = true;
                }

                break;

            case __HResults.COR_E_DLLNOTFOUND:
#if ENABLE_WINRT
                exception = new DllNotFoundException();
#endif
                break;

            case __HResults.COR_E_DUPLICATEWAITOBJECT:
                exception = new ArgumentException();
                break;     // DuplicateWaitObjectException

            case __HResults.COR_E_ENDOFSTREAM:
            case unchecked ((int)0x800A003E):
                exception = new CoreFX_IO::System.IO.EndOfStreamException();

                if (errorCode != __HResults.COR_E_ENDOFSTREAM)
                {
                    shouldDisplayHR = true;
                }

                break;

            case __HResults.COR_E_TYPEACCESS:     // TypeAccessException
            case __HResults.COR_E_ENTRYPOINTNOTFOUND:
                exception = new TypeLoadException();

                break;     // EntryPointNotFoundException

            case __HResults.COR_E_EXCEPTION:
                exception = new Exception();
                break;

            case __HResults.COR_E_DIRECTORYNOTFOUND:
            case __HResults.STG_E_PATHNOTFOUND:
            case __HResults.CTL_E_PATHNOTFOUND:
                exception = new System.IO.DirectoryNotFoundException();

                if (errorCode != __HResults.COR_E_DIRECTORYNOTFOUND)
                {
                    shouldDisplayHR = true;
                }

                break;

            case __HResults.COR_E_FILELOAD:
            case __HResults.FUSION_E_INVALID_PRIVATE_ASM_LOCATION:
            case __HResults.FUSION_E_SIGNATURE_CHECK_FAILED:
            case __HResults.FUSION_E_LOADFROM_BLOCKED:
            case __HResults.FUSION_E_CACHEFILE_FAILED:
            case __HResults.FUSION_E_ASM_MODULE_MISSING:
            case __HResults.FUSION_E_INVALID_NAME:
            case __HResults.FUSION_E_PRIVATE_ASM_DISALLOWED:
            case __HResults.FUSION_E_HOST_GAC_ASM_MISMATCH:
            case __HResults.COR_E_MODULE_HASH_CHECK_FAILED:
            case __HResults.FUSION_E_REF_DEF_MISMATCH:
            case __HResults.SECURITY_E_INCOMPATIBLE_SHARE:
            case __HResults.SECURITY_E_INCOMPATIBLE_EVIDENCE:
            case __HResults.SECURITY_E_UNVERIFIABLE:
            case __HResults.COR_E_FIXUPSINEXE:
            case __HResults.ERROR_TOO_MANY_OPEN_FILES:
            case __HResults.ERROR_SHARING_VIOLATION:
            case __HResults.ERROR_LOCK_VIOLATION:
            case __HResults.ERROR_OPEN_FAILED:
            case __HResults.ERROR_DISK_CORRUPT:
            case __HResults.ERROR_UNRECOGNIZED_VOLUME:
            case __HResults.ERROR_DLL_INIT_FAILED:
            case __HResults.FUSION_E_CODE_DOWNLOAD_DISABLED:
            case __HResults.CORSEC_E_MISSING_STRONGNAME:
            case __HResults.MSEE_E_ASSEMBLYLOADINPROGRESS:
            case __HResults.ERROR_FILE_INVALID:
                exception = new System.IO.FileLoadException();

                shouldDisplayHR = true;
                break;

            case __HResults.COR_E_PATHTOOLONG:
                exception = new System.IO.PathTooLongException();
                break;

            case __HResults.COR_E_IO:
            case __HResults.CTL_E_DEVICEIOERROR:
            case unchecked ((int)0x800A793C):
            case unchecked ((int)0x800A793D):
                exception = new System.IO.IOException();

                if (errorCode != __HResults.COR_E_IO)
                {
                    shouldDisplayHR = true;
                }

                break;

            case __HResults.ERROR_FILE_NOT_FOUND:
            case __HResults.ERROR_MOD_NOT_FOUND:
            case __HResults.ERROR_INVALID_NAME:
            case __HResults.CTL_E_FILENOTFOUND:
            case __HResults.ERROR_BAD_NET_NAME:
            case __HResults.ERROR_BAD_NETPATH:
            case __HResults.ERROR_NOT_READY:
            case __HResults.ERROR_WRONG_TARGET_NAME:
            case __HResults.INET_E_UNKNOWN_PROTOCOL:
            case __HResults.INET_E_CONNECTION_TIMEOUT:
            case __HResults.INET_E_CANNOT_CONNECT:
            case __HResults.INET_E_RESOURCE_NOT_FOUND:
            case __HResults.INET_E_OBJECT_NOT_FOUND:
            case __HResults.INET_E_DOWNLOAD_FAILURE:
            case __HResults.INET_E_DATA_NOT_AVAILABLE:
            case __HResults.ERROR_DLL_NOT_FOUND:
            case __HResults.CLR_E_BIND_ASSEMBLY_VERSION_TOO_LOW:
            case __HResults.CLR_E_BIND_ASSEMBLY_PUBLIC_KEY_MISMATCH:
            case __HResults.CLR_E_BIND_ASSEMBLY_NOT_FOUND:
                exception = new System.IO.FileNotFoundException();

                shouldDisplayHR = true;
                break;

            case __HResults.COR_E_FORMAT:
                exception = new FormatException();
                break;

            case __HResults.COR_E_INDEXOUTOFRANGE:
            case unchecked ((int)0x800a0009):
                exception = new IndexOutOfRangeException();

                if (errorCode != __HResults.COR_E_INDEXOUTOFRANGE)
                {
                    shouldDisplayHR = true;
                }

                break;

            case __HResults.COR_E_INVALIDCAST:
                exception = new InvalidCastException();
                break;

            case __HResults.COR_E_INVALIDCOMOBJECT:
                exception = new InvalidComObjectException();
                break;

            case __HResults.COR_E_INVALIDOLEVARIANTTYPE:
                exception = new InvalidOleVariantTypeException();
                break;

            case __HResults.COR_E_INVALIDOPERATION:
            case __HResults.E_ILLEGAL_STATE_CHANGE:
            case __HResults.E_ILLEGAL_METHOD_CALL:
            case __HResults.E_ILLEGAL_DELEGATE_ASSIGNMENT:
            case __HResults.APPMODEL_ERROR_NO_PACKAGE:
                exception = new InvalidOperationException();

                if (errorCode != __HResults.COR_E_INVALIDOPERATION)
                {
                    shouldDisplayHR = true;
                }

                break;

            case __HResults.COR_E_MARSHALDIRECTIVE:
                exception = new MarshalDirectiveException();
                break;

            case __HResults.COR_E_METHODACCESS:            // MethodAccessException
            case __HResults.META_E_CA_FRIENDS_SN_REQUIRED: // MethodAccessException
            case __HResults.COR_E_FIELDACCESS:
            case __HResults.COR_E_MEMBERACCESS:
                exception = new MemberAccessException();

                if (errorCode != __HResults.COR_E_METHODACCESS)
                {
                    shouldDisplayHR = true;
                }

                break;

            case __HResults.COR_E_MISSINGFIELD:     // MissingFieldException
            case __HResults.COR_E_MISSINGMETHOD:    // MissingMethodException
            case __HResults.COR_E_MISSINGMEMBER:
            case unchecked ((int)0x800A01CD):
                exception = new MissingMemberException();
                break;

            case __HResults.COR_E_MISSINGMANIFESTRESOURCE:
                exception = new System.Resources.MissingManifestResourceException();
                break;

            case __HResults.COR_E_NOTSUPPORTED:
            case unchecked ((int)0x800A01B6):
            case unchecked ((int)0x800A01BD):
            case unchecked ((int)0x800A01CA):
            case unchecked ((int)0x800A01CB):
                exception = new NotSupportedException();

                if (errorCode != __HResults.COR_E_NOTSUPPORTED)
                {
                    shouldDisplayHR = true;
                }

                break;

            case __HResults.COR_E_NULLREFERENCE:
                exception = new NullReferenceException();
                break;

            case __HResults.COR_E_OBJECTDISPOSED:
            case __HResults.RO_E_CLOSED:
                // No default constructor
                exception = new ObjectDisposedException(String.Empty);
                break;

            case __HResults.COR_E_OPERATIONCANCELED:
#if ENABLE_WINRT
                exception = new OperationCanceledException();
#endif
                break;

            case __HResults.COR_E_OVERFLOW:
            case __HResults.CTL_E_OVERFLOW:
                exception = new OverflowException();
                break;

            case __HResults.COR_E_PLATFORMNOTSUPPORTED:
                exception = new PlatformNotSupportedException(message);
                break;

            case __HResults.COR_E_RANK:
                exception = new RankException();
                break;

            case __HResults.COR_E_REFLECTIONTYPELOAD:
#if ENABLE_WINRT
                exception = new System.Reflection.ReflectionTypeLoadException(null, null);
#endif
                break;

            case __HResults.COR_E_SECURITY:
            case __HResults.CORSEC_E_INVALID_STRONGNAME:
            case __HResults.CTL_E_PERMISSIONDENIED:
            case unchecked ((int)0x800A01A3):
            case __HResults.CORSEC_E_INVALID_PUBLICKEY:
            case __HResults.CORSEC_E_SIGNATURE_MISMATCH:
                exception = new System.Security.SecurityException();
                break;

            case __HResults.COR_E_SAFEARRAYRANKMISMATCH:
                exception = new SafeArrayRankMismatchException();
                break;

            case __HResults.COR_E_SAFEARRAYTYPEMISMATCH:
                exception = new SafeArrayTypeMismatchException();
                break;

            case __HResults.COR_E_SERIALIZATION:
                exception = new System.Runtime.Serialization.SerializationException(message);
                break;

            case __HResults.COR_E_SYNCHRONIZATIONLOCK:
                exception = new System.Threading.SynchronizationLockException();
                break;

            case __HResults.COR_E_TARGETINVOCATION:
                exception = new System.Reflection.TargetInvocationException(null);
                break;

            case __HResults.COR_E_TARGETPARAMCOUNT:
                exception = new System.Reflection.TargetParameterCountException();
                break;

            case __HResults.COR_E_TYPEINITIALIZATION:
                exception = InteropExtensions.CreateTypeInitializationException(message);
                break;

            case __HResults.COR_E_TYPELOAD:
            case __HResults.RO_E_METADATA_NAME_NOT_FOUND:
            case __HResults.CLR_E_BIND_TYPE_NOT_FOUND:
                exception = new TypeLoadException();

                if (errorCode != __HResults.COR_E_TYPELOAD)
                {
                    shouldDisplayHR = true;
                }

                break;

            case __HResults.COR_E_UNAUTHORIZEDACCESS:
            case __HResults.CTL_E_PATHFILEACCESSERROR:
            case unchecked ((int)0x800A014F):
                exception = new UnauthorizedAccessException();

                shouldDisplayHR = true;

                break;

            case __HResults.COR_E_VERIFICATION:
                exception = new System.Security.VerificationException();
                break;

            case __HResults.E_NOTIMPL:
                exception = new NotImplementedException();
                break;

            case __HResults.E_OUTOFMEMORY:
            case __HResults.CTL_E_OUTOFMEMORY:
            case unchecked ((int)0x800A7919):
                exception = new OutOfMemoryException();

                if (errorCode != __HResults.E_OUTOFMEMORY)
                {
                    shouldDisplayHR = true;
                }

                break;

#if ENABLE_WINRT
            case __HResults.E_XAMLPARSEFAILED:
                exception = ConstructExceptionUsingReflection(
                    "Windows.UI.Xaml.Markup.XamlParseException, System.Runtime.WindowsRuntime.UI.Xaml, Version=4.0.0.0",
                    message);
                break;

            case __HResults.E_ELEMENTNOTAVAILABLE:
                exception = ConstructExceptionUsingReflection(
                    "Windows.UI.Xaml.Automation.ElementNotAvailableException, System.Runtime.WindowsRuntime.UI.Xaml, Version=4.0.0.0",
                    message);
                break;

            case __HResults.E_ELEMENTNOTENABLED:
                exception = ConstructExceptionUsingReflection(
                    "Windows.UI.Xaml.Automation.ElementNotEnabledException, System.Runtime.WindowsRuntime.UI.Xaml, Version=4.0.0.0",
                    message);
                break;

            case __HResults.E_LAYOUTCYCLE:
                exception = ConstructExceptionUsingReflection(
                    "Windows.UI.Xaml.LayoutCycleException, System.Runtime.WindowsRuntime.UI.Xaml, Version=4.0.0.0",
                    message);
                break;
#endif // ENABLE_WINRT
            case __HResults.COR_E_AMBIGUOUSMATCH:     // AmbiguousMatchException
            case __HResults.COR_E_APPLICATION:     // ApplicationException
            case __HResults.COR_E_APPDOMAINUNLOADED:          // AppDomainUnloadedException
            case __HResults.COR_E_CANNOTUNLOADAPPDOMAIN:      // CannotUnloadAppDomainException
            case __HResults.COR_E_CODECONTRACTFAILED:         // ContractException
            case __HResults.COR_E_CONTEXTMARSHAL:             // ContextMarshalException
            case __HResults.CORSEC_E_CRYPTO:                  // CryptographicException
            case __HResults.CORSEC_E_CRYPTO_UNEX_OPER:        // CryptographicUnexpectedOperationException
            case __HResults.COR_E_EXECUTIONENGINE:            // ExecutionEngineException
            case __HResults.COR_E_INSUFFICIENTEXECUTIONSTACK: // InsufficientExecutionStackException
            case __HResults.COR_E_INVALIDFILTERCRITERIA:      // InvalidFilterCriteriaException
            case __HResults.COR_E_INVALIDPROGRAM:             // InvalidProgramException
            case __HResults.COR_E_MULTICASTNOTSUPPORTED:      // MulticastNotSupportedException
            case __HResults.COR_E_REMOTING:                   // RemotingException
            case __HResults.COR_E_RUNTIMEWRAPPED:             // RuntimeWrappedException
            case __HResults.COR_E_SERVER:                     // ServerException
            case __HResults.COR_E_STACKOVERFLOW:              // StackOverflowException
            case __HResults.CTL_E_OUTOFSTACKSPACE:            // StackOverflowException
            case __HResults.COR_E_SYSTEM:                     // SystemException
            case __HResults.COR_E_TARGET:                     // TargetException
            case __HResults.COR_E_THREADABORTED:              // TargetException
            case __HResults.COR_E_THREADINTERRUPTED:          // ThreadInterruptedException
            case __HResults.COR_E_THREADSTATE:                // ThreadStateException
            case __HResults.COR_E_THREADSTART:                // ThreadStartException
            case __HResults.COR_E_TYPEUNLOADED:               // TypeUnloadedException
            case __HResults.CORSEC_E_POLICY_EXCEPTION:        // PolicyException
            case __HResults.CORSEC_E_NO_EXEC_PERM:            // PolicyException
            case __HResults.CORSEC_E_MIN_GRANT_FAIL:          // PolicyException
            case __HResults.CORSEC_E_XMLSYNTAX:               // XmlSyntaxException
            case __HResults.ISS_E_ALLOC_TOO_LARGE:            // IsolatedStorageException
            case __HResults.ISS_E_BLOCK_SIZE_TOO_SMALL:       // IsolatedStorageException
            case __HResults.ISS_E_CALLER:                     // IsolatedStorageException
            case __HResults.ISS_E_CORRUPTED_STORE_FILE:       // IsolatedStorageException
            case __HResults.ISS_E_CREATE_DIR:                 // IsolatedStorageException
            case __HResults.ISS_E_CREATE_MUTEX:               // IsolatedStorageException
            case __HResults.ISS_E_DEPRECATE:                  // IsolatedStorageException
            case __HResults.ISS_E_FILE_NOT_MAPPED:            // IsolatedStorageException
            case __HResults.ISS_E_FILE_WRITE:                 // IsolatedStorageException
            case __HResults.ISS_E_GET_FILE_SIZE:              // IsolatedStorageException
            case __HResults.ISS_E_ISOSTORE:                   // IsolatedStorageException
            case __HResults.ISS_E_LOCK_FAILED:                // IsolatedStorageException
            case __HResults.ISS_E_MACHINE:                    // IsolatedStorageException
            case __HResults.ISS_E_MACHINE_DACL:               // IsolatedStorageException
            case __HResults.ISS_E_MAP_VIEW_OF_FILE:           // IsolatedStorageException
            case __HResults.ISS_E_OPEN_FILE_MAPPING:          // IsolatedStorageException
            case __HResults.ISS_E_OPEN_STORE_FILE:            // IsolatedStorageException
            case __HResults.ISS_E_PATH_LENGTH:                // IsolatedStorageException
            case __HResults.ISS_E_SET_FILE_POINTER:           // IsolatedStorageException
            case __HResults.ISS_E_STORE_NOT_OPEN:             // IsolatedStorageException
            case __HResults.ISS_E_STORE_VERSION:              // IsolatedStorageException
            case __HResults.ISS_E_TABLE_ROW_NOT_FOUND:        // IsolatedStorageException
            case __HResults.ISS_E_USAGE_WILL_EXCEED_QUOTA:    // IsolatedStorageException
            case __HResults.E_FAIL:
            default:
                break;
            }

            if (exception == null)
            {
                if (createCOMException)
                {
                    exception = new COMException();
                    if (errorCode != __HResults.E_FAIL)
                    {
                        shouldDisplayHR = true;
                    }
                }
                else
                {
                    exception = new Exception();
                    if (errorCode != __HResults.COR_E_EXCEPTION)
                    {
                        shouldDisplayHR = true;
                    }
                }
            }

            bool shouldConstructMessage = false;
            if (hasErrorInfo)
            {
                // If there is a IErrorInfo/IRestrictedErrorInfo, only construct a new error message if
                // the message is not available and do not use the shouldDisplayHR setting
                if (message == null)
                {
                    shouldConstructMessage = true;
                }
            }
            else
            {
                // If there is no IErrorInfo, use the shouldDisplayHR setting from the big switch/case above
                shouldConstructMessage = shouldDisplayHR;
            }

            if (shouldConstructMessage)
            {
                //
                // Append the HR into error message, just in case the app wants to look at the HR in
                // message to determine behavior.  We didn't expose HResult property until v4.5 and
                // GetHRFromException has side effects so probably Message was their only choice.
                // This behavior is probably not exactly the same as in desktop but it is fine to append
                // more message at the end. In any case, having the HR in the error message are helpful
                // to developers.
                // This makes sure:
                // 1. We always have a HR 0xNNNNNNNN in the message
                // 2. Put in a nice "Exception thrown from HRESULT" message if we can
                // 3. Wrap it in () if there is an existing message
                //

                // TODO: Add Symbolic Name into Messaage, convert 0x80020006 to DISP_E_UNKNOWNNAME
                string hrMessage = String.Format("{0} 0x{1}", SR.Excep_FromHResult, errorCode.LowLevelToString());

                message = ExternalInterop.GetMessage(errorCode);

                // Always make sure we have at least the HRESULT part in retail build or when the message
                // is empty.
                if (message == null)
                {
                    message = hrMessage;
                }
                else
                {
                    message = message + " (" + hrMessage + ")";
                }
            }

            if (message != null)
            {
                // Set message explicitly rather than calling constructor because certain ctors would append a
                // prefix to the message and that is not what we want
                InteropExtensions.SetExceptionMessage(exception, message);
            }

            InteropExtensions.SetExceptionErrorCode(exception, errorCode);

            return(exception);
        }
コード例 #34
0
        /// <summary>
        /// 以指定的属性为基础,定义以自动属性模式实现的重写属性,并添加到当前类型。
        /// </summary>
        /// <param name="type">要定义属性的 <see cref="TypeBuilder"/> 对象。</param>
        /// <param name="baseProperty">作为基础的属性。</param>
        /// <param name="explicitOverride">指定是否以显式方式重写。</param>
        /// <returns>定义的自动属性与其对应的字段。</returns>
        /// <exception cref="ArgumentException">
        /// <paramref name="baseProperty"/> 是索引属性或无法在程序集外部重写。</exception>
        /// <exception cref="ArgumentNullException">存在为 <see langword="null"/> 的参数。</exception>
        public static KeyValuePair <PropertyBuilder, FieldBuilder> DefineAutoPropertyOverride(
            this TypeBuilder type, PropertyInfo baseProperty, bool explicitOverride = false)
        {
            if (type is null)
            {
                throw new ArgumentNullException(nameof(type));
            }
            if (baseProperty is null)
            {
                throw new ArgumentNullException(nameof(baseProperty));
            }
            if (baseProperty.GetIndexParameters().Length != 0)
            {
                var inner = new TargetParameterCountException();
                throw new ArgumentException(inner.Message, nameof(baseProperty), inner);
            }
            if (!baseProperty.GetAccessors().All(accessor => accessor.IsOverridable()))
            {
                var inner = new MemberAccessException();
                throw new ArgumentException(inner.Message, nameof(baseProperty), inner);
            }

            var propertyName = baseProperty.Name;

            if (explicitOverride)
            {
                var baseHandle = baseProperty.GetAccessors().First().MethodHandle;
                propertyName += $"#{baseHandle.Value.ToString()}";
            }

            var property = type.DefineProperty(
                propertyName, baseProperty.Attributes, baseProperty.PropertyType,
                Array.ConvertAll(baseProperty.GetIndexParameters(), param => param.ParameterType));

            var field = type.DefineField(
                propertyName, baseProperty.PropertyType, FieldAttributes.Private);

            if (baseProperty.CanRead)
            {
                var baseMethod = baseProperty.GetMethod !;

                var method = type.DefineMethodOverride(baseMethod, explicitOverride);

                var il = method.GetILGenerator();
                il.Emit(OpCodes.Ldarg_0);
                il.Emit(OpCodes.Ldfld, field);
                il.Emit(OpCodes.Ret);

                property.SetGetMethod(method);
            }

            if (baseProperty.CanWrite)
            {
                var baseMethod = baseProperty.SetMethod !;

                var method = type.DefineMethodOverride(baseMethod, explicitOverride);

                var il = method.GetILGenerator();
                il.Emit(OpCodes.Ldarg_0);
                il.Emit(OpCodes.Ldarg_1);
                il.Emit(OpCodes.Stfld, field);
                il.Emit(OpCodes.Ret);

                property.SetSetMethod(method);
            }

            return(new KeyValuePair <PropertyBuilder, FieldBuilder>(property, field));
        }
コード例 #35
0
        /// <summary>
        /// 以指定的事件为基础,定义以默认事件模式实现的重写事件,并添加到当前类型。
        /// </summary>
        /// <param name="type">要定义事件的 <see cref="TypeBuilder"/> 对象。</param>
        /// <param name="baseEvent">作为基础的事件。</param>
        /// <param name="explicitOverride">指定是否以显式方式重写。</param>
        /// <returns>定义的默认模式的事件与其对应的事件委托。</returns>
        /// <exception cref="ArgumentException">
        /// <paramref name="baseEvent"/> 的方法无法在程序集外部重写。</exception>
        /// <exception cref="ArgumentNullException">存在为 <see langword="null"/> 的参数。</exception>
        public static KeyValuePair <EventBuilder, FieldBuilder> DefineDefaultEventOverride(
            this TypeBuilder type, EventInfo baseEvent, bool explicitOverride = false)
        {
            if (type is null)
            {
                throw new ArgumentNullException(nameof(type));
            }
            if (baseEvent is null)
            {
                throw new ArgumentNullException(nameof(baseEvent));
            }
            if (!baseEvent.AddMethod !.IsOverridable())
            {
                var inner = new MemberAccessException();
                throw new ArgumentException(inner.Message, nameof(baseEvent), inner);
            }

            var eventName = baseEvent.Name;

            if (explicitOverride)
            {
                var baseHandle = baseEvent.AddMethod !.MethodHandle;
                eventName += $"#{baseHandle.Value.ToString()}";
            }

            var @event = type.DefineEvent(
                eventName, baseEvent.Attributes, baseEvent.EventHandlerType !);

            var field = type.DefineField(
                eventName, baseEvent.EventHandlerType !, FieldAttributes.Private);

            {
                var baseMethod = baseEvent.AddMethod !;

                var method = type.DefineMethodOverride(baseMethod, explicitOverride);

                var il        = method.GetILGenerator();
                var eventType = baseEvent.EventHandlerType !;
                var local0    = il.DeclareLocal(eventType);
                var local1    = il.DeclareLocal(eventType);
                var local2    = il.DeclareLocal(eventType);
                il.Emit(OpCodes.Ldarg_0);
                il.Emit(OpCodes.Ldfld, field);
                il.Emit(OpCodes.Stloc_0);
                var startLabel = il.DefineLabel();
                il.MarkLabel(startLabel);
                il.Emit(OpCodes.Ldloc_0);
                il.Emit(OpCodes.Stloc_1);
                il.Emit(OpCodes.Ldloc_1);
                il.Emit(OpCodes.Ldarg_1);
                il.Emit(OpCodes.Call,
                        typeof(Delegate).GetMethod(
                            nameof(Delegate.Combine),
                            new[] { typeof(Delegate), typeof(Delegate) }) !);
                il.Emit(OpCodes.Castclass, eventType);
                il.Emit(OpCodes.Stloc_2);
                il.Emit(OpCodes.Ldarg_0);
                il.Emit(OpCodes.Ldflda, field);
                il.Emit(OpCodes.Ldloc_2);
                il.Emit(OpCodes.Ldloc_1);
                il.Emit(OpCodes.Call, typeof(Interlocked).GetMethods().Where(
                            iMethod => iMethod.Name == nameof(Interlocked.CompareExchange) &&
                            iMethod.IsGenericMethod).Single().MakeGenericMethod(eventType));
                il.Emit(OpCodes.Stloc_0);
                il.Emit(OpCodes.Ldloc_0);
                il.Emit(OpCodes.Ldloc_1);
                il.Emit(OpCodes.Bne_Un_S, startLabel);
                il.Emit(OpCodes.Ret);

                @event.SetAddOnMethod(method);
            }

            {
                var baseMethod = baseEvent.RemoveMethod !;

                var method = type.DefineMethodOverride(baseMethod, explicitOverride);

                var il        = method.GetILGenerator();
                var eventType = baseEvent.EventHandlerType !;
                var local0    = il.DeclareLocal(eventType);
                var local1    = il.DeclareLocal(eventType);
                var local2    = il.DeclareLocal(eventType);
                il.Emit(OpCodes.Ldarg_0);
                il.Emit(OpCodes.Ldfld, field);
                il.Emit(OpCodes.Stloc_0);
                var startLabel = il.DefineLabel();
                il.MarkLabel(startLabel);
                il.Emit(OpCodes.Ldloc_0);
                il.Emit(OpCodes.Stloc_1);
                il.Emit(OpCodes.Ldloc_1);
                il.Emit(OpCodes.Ldarg_1);
                il.Emit(OpCodes.Call,
                        typeof(Delegate).GetMethod(
                            nameof(Delegate.Remove),
                            new[] { typeof(Delegate), typeof(Delegate) }) !);
                il.Emit(OpCodes.Castclass, eventType);
                il.Emit(OpCodes.Stloc_2);
                il.Emit(OpCodes.Ldarg_0);
                il.Emit(OpCodes.Ldflda, field);
                il.Emit(OpCodes.Ldloc_2);
                il.Emit(OpCodes.Ldloc_1);
                il.Emit(OpCodes.Call, typeof(Interlocked).GetMethods().Where(
                            iMethod => iMethod.Name == nameof(Interlocked.CompareExchange) &&
                            iMethod.IsGenericMethod).Single().MakeGenericMethod(eventType));
                il.Emit(OpCodes.Stloc_0);
                il.Emit(OpCodes.Ldloc_0);
                il.Emit(OpCodes.Ldloc_1);
                il.Emit(OpCodes.Bne_Un_S, startLabel);
                il.Emit(OpCodes.Ret);

                @event.SetRemoveOnMethod(method);
            }

            return(new KeyValuePair <EventBuilder, FieldBuilder>(@event, field));
        }