public static void Ctor_String() { string message = "Created MissingMemberException"; var exception = new MissingMemberException(message); Assert.Equal(message, exception.Message); Assert.Equal(COR_E_MISSINGMEMBER, exception.HResult); }
/// <summary> /// Starts monitoring the value of a property on an object. /// </summary> /// <param name="reference">A weak reference to the object.</param> /// <param name="propertyName">The property name.</param> /// <param name="changed">A function to call when the property changes.</param> /// <returns> /// An <see cref="IPropertyAccessor"/> interface through which future interactions with the /// property will be made. /// </returns> public IPropertyAccessor Start( WeakReference reference, string propertyName, Action <object> changed) { Contract.Requires <ArgumentNullException>(reference != null); Contract.Requires <ArgumentNullException>(propertyName != null); Contract.Requires <ArgumentNullException>(changed != null); var instance = reference.Target; var o = (PerspexObject)instance; var p = PerspexPropertyRegistry.Instance.FindRegistered(o, propertyName); if (p != null) { return(new Accessor(new WeakReference <PerspexObject>(o), p, changed)); } else if (instance != PerspexProperty.UnsetValue) { var message = $"Could not find PerspexProperty '{propertyName}' on '{instance}'"; var exception = new MissingMemberException(message); return(new PropertyError(new BindingError(exception))); } else { return(null); } }
public static void Ctor_Empty() { var exception = new MissingMemberException(); Assert.NotEmpty(exception.Message); Assert.Equal(COR_E_MISSINGMEMBER, exception.HResult); }
// 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 MissingMemberException."); try { string expectValue = "HELLO"; MissingMemberException myException = new MissingMemberException(expectValue); if (myException == null) { TestLibrary.TestFramework.LogError("001.1", "MissingMemberException instance can not create correctly."); retVal = false; } if (myException.Message != expectValue) { TestLibrary.TestFramework.LogError("001.2", "the Message should return " + expectValue); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("001.0", "Unexpected exception: " + e); retVal = false; } return retVal; }
// 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(); MissingMemberException myException = new MissingMemberException(expectValue, dpoExpection); if (myException == null) { TestLibrary.TestFramework.LogError("002.1", "MissingMemberException 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 MissingMemberException."); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002.0", "Unexpected exception: " + e); retVal = false; } return(retVal); }
// 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 MissingMemberException."); try { string expectValue = "HELLO"; ArgumentException notFoundException = new ArgumentException(); MissingMemberException myException = new MissingMemberException(expectValue, notFoundException); if (myException == null) { TestLibrary.TestFramework.LogError("001.1", "MissingMemberException 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); }
public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: Create a new MissingMemberException instance,string is empty."); try { string expectString = string.Empty; //Create the application domain setup information. MissingMemberException myMissingMemberException = new MissingMemberException(expectString); if (myMissingMemberException.Message != expectString) { TestLibrary.TestFramework.LogError("002.1", "the MissingMemberException ctor error occurred.the message should be " + expectString); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002.2", "Unexpected exception: " + e); retVal = false; } return(retVal); }
public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: Create a new MissingMemberException instance,string is empty."); try { string expectString = string.Empty; //Create the application domain setup information. MissingMemberException myMissingMemberException = new MissingMemberException(expectString); if (myMissingMemberException.Message != expectString) { TestLibrary.TestFramework.LogError("002.1", "the MissingMemberException ctor error occurred.the message should be " + expectString); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002.2", "Unexpected exception: " + e); retVal = false; } return retVal; }
public IPropertyAccessor Start(WeakReference reference, string methodName) { Contract.Requires <ArgumentNullException>(reference != null); Contract.Requires <ArgumentNullException>(methodName != null); var instance = reference.Target; var method = instance.GetType().GetRuntimeMethods().FirstOrDefault(x => x.Name == methodName); if (method != null) { if (method.GetParameters().Length + (method.ReturnType == typeof(void) ? 0 : 1) > 8) { var exception = new ArgumentException("Cannot create a binding accessor for a method with more than 8 parameters or more than 7 parameters if it has a non-void return type.", nameof(method)); return(new PropertyError(new BindingNotification(exception, BindingErrorType.Error))); } return(new Accessor(reference, method)); } else { var message = $"Could not find CLR method '{methodName}' on '{instance}'"; var exception = new MissingMemberException(message); return(new PropertyError(new BindingNotification(exception, BindingErrorType.Error))); } }
/// <summary> /// Starts monitoring the value of a property on an object. /// </summary> /// <param name="reference">A weak reference to the object.</param> /// <param name="propertyName">The property name.</param> /// <returns> /// An <see cref="IPropertyAccessor"/> interface through which future interactions with the /// property will be made. /// </returns> public IPropertyAccessor?Start(WeakReference <object?> reference, string propertyName) { _ = reference ?? throw new ArgumentNullException(nameof(reference)); _ = propertyName ?? throw new ArgumentNullException(nameof(propertyName)); if (!reference.TryGetTarget(out var instance) || instance is null) { return(null); } var o = (AvaloniaObject)instance; var p = LookupProperty(o, propertyName); if (p != null) { return(new Accessor(new WeakReference <AvaloniaObject>(o), p)); } else if (instance != AvaloniaProperty.UnsetValue) { var message = $"Could not find AvaloniaProperty '{propertyName}' on '{instance}'"; var exception = new MissingMemberException(message); return(new PropertyError(new BindingNotification(exception, BindingErrorType.Error))); } else { return(null); } }
// 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; MissingMemberException myException = new MissingMemberException(expectValue); if (myException == null) { TestLibrary.TestFramework.LogError("002.1", "MissingMemberException 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; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002.0", "Unexpected exception: " + e); retVal = false; } return retVal; }
public static void Ctor_String_String() { string className = "class"; string memberName = "member"; var exception = new MissingMemberException(className, memberName); Assert.True(exception.Message.Contains(className)); Assert.True(exception.Message.Contains(memberName)); }
public static void Ctor_String_String() { string className = "class"; string memberName = "member"; var exception = new MissingMemberException(className, memberName); Assert.Contains(className, exception.Message); Assert.Contains(memberName, exception.Message); Assert.Equal(COR_E_MISSINGMEMBER, exception.HResult); }
public static void Ctor_String_Exception() { string message = "Created MissingMemberException"; var innerException = new Exception("Created inner exception"); var exception = new MissingMemberException(message, innerException); Assert.Equal(message, exception.Message); Assert.Equal(COR_E_MISSINGMEMBER, exception.HResult); Assert.Same(innerException, exception.InnerException); Assert.Equal(innerException.HResult, exception.InnerException.HResult); }
/// <summary>Creates an instance of T using m_valueFactory in case its not null or use reflection to create a new T()</summary> /// <returns>An instance of Boxed.</returns> private Boxed CreateValue() { Boxed boxed = null; LazyThreadSafetyMode mode = Mode; if (m_valueFactory != null) { try { // check for recursion if (mode != LazyThreadSafetyMode.PublicationOnly && m_valueFactory == ALREADY_INVOKED_SENTINEL) { throw new InvalidOperationException("Should not try to create the value more than once"); } Func <T> factory = m_valueFactory; if (mode != LazyThreadSafetyMode.PublicationOnly) // only detect recursion on None and ExecutionAndPublication modes { m_valueFactory = ALREADY_INVOKED_SENTINEL; } else if (factory == ALREADY_INVOKED_SENTINEL) { // Another thread raced to successfully invoke the factory. return(null); } boxed = new Boxed(factory()); } catch (Exception ex) { if (mode != LazyThreadSafetyMode.PublicationOnly) // don't cache the exception for PublicationOnly mode { m_boxed = new LazyInternalExceptionHolder(ex); } throw; } } else { try { boxed = new Boxed((T)Activator.CreateInstance(typeof(T))); } catch (MissingMethodException) { Exception ex = new MissingMemberException(string.Format("The type {0} does not have parameterless constructor", typeof(T).FullName)); if (mode != LazyThreadSafetyMode.PublicationOnly) // don't cache the exception for PublicationOnly mode { m_boxed = new LazyInternalExceptionHolder(ex); } throw ex; } } return(boxed); }
private static void InternalSetter(object myObject, string name, object value, BindingFlags invokeAttr) { try { try { Type t = myObject.GetType(); t.InvokeMember(name, invokeAttr, null, myObject, new object[] { value }); return; } catch (MissingMemberException ex) { Debug.WriteLine("Try 1: " + ex.Message); } int count = 1; Type baseT = myObject.GetType().BaseType; while (baseT != null) { count++; try { Type t = baseT; t.InvokeMember(name, invokeAttr, null, myObject, new object[] { value }); return; } catch (MissingMemberException ex) { Debug.WriteLine(string.Format("Try {0}: {1}", count, ex.Message)); } baseT = baseT.BaseType; } } catch (Exception ex) { if (ex.InnerException != null) { throw ex.InnerException; } throw ex; } // -------------------------------------------------------------- // if all fails, throw an exception. // -------------------------------------------------------------- { var ex = new MissingMemberException("Unable to set property/field name: " + name); DebuggerTool.AddData(ex, "name", name); DebuggerTool.AddData(ex, "value", value); DebuggerTool.AddData(ex, "value.GetType()", value.GetType().FullName); throw ex; } }
/// <summary>Creates an instance of T using valueFactory in case its not null or use reflection to create a new T()</summary> /// <returns>An instance of Boxed.</returns> private async Task <Boxed> CreateValue() { Boxed localBoxed = null; LazyThreadSafetyMode mode = Mode; if (valueFactory != null) { try { // check for recursion if (mode != LazyThreadSafetyMode.PublicationOnly && valueFactory == alreadyInvokedSentinel) { throw new InvalidOperationException("Recursive call to Value property"); } Func <Task <T> > factory = valueFactory; if (mode != LazyThreadSafetyMode.PublicationOnly) // only detect recursion on None and ExecutionAndPublication modes { valueFactory = alreadyInvokedSentinel; } else if (factory == alreadyInvokedSentinel) { // Another thread ----d with us and beat us to successfully invoke the factory. return(null); } localBoxed = new Boxed(await factory()); } catch (Exception ex) { if (mode != LazyThreadSafetyMode.PublicationOnly) // don't cache the exception for PublicationOnly mode { boxed = new LazyInternalExceptionHolder(ex); } throw; } } else { try { localBoxed = new Boxed((T)Activator.CreateInstance(typeof(T))); } catch (MissingMethodException) { Exception ex = new MissingMemberException("Missing parametersless constructor"); if (mode != LazyThreadSafetyMode.PublicationOnly) // don't cache the exception for PublicationOnly mode { boxed = new LazyInternalExceptionHolder(ex); } throw ex; } } return(localBoxed); }
internal static MissingMemberException MethodNotFoundError(string methodName) { MissingMemberException missingMemberException = new MissingMemberException(SyncResource.FormatString("MethodNotFound", new object[1] { (object)methodName })); SyncTracer.Warning("{0}", new object[1] { (object)missingMemberException }); return(missingMemberException); }
private IDataMapper GetMapper(string item) { if (this._dataMappers.ContainsKey(item)) { return(this._dataMappers[item]); } else { MissingMemberException exception = new MissingMemberException($"Missing Mapper {item}"); this._logger.Log("Missing or Invalid Mapper", EventLevel.Error, exception); throw exception; } }
protected override void StartListeningCore(WeakReference <object> reference) { reference.TryGetTarget(out object target); IPropertyAccessorPlugin plugin = null; foreach (IPropertyAccessorPlugin x in ExpressionObserver.PropertyAccessors) { if (x.Match(target, PropertyName)) { plugin = x; break; } } var accessor = plugin?.Start(reference, PropertyName); // We need to handle accessor fallback before handling validation. Validators do not support null accessors. if (accessor == null) { reference.TryGetTarget(out object instance); var message = $"Could not find a matching property accessor for '{PropertyName}' on '{instance}'"; var exception = new MissingMemberException(message); accessor = new PropertyError(new BindingNotification(exception, BindingErrorType.Error)); } if (_enableValidation && Next == null) { foreach (var validator in ExpressionObserver.DataValidators) { if (validator.Match(reference, PropertyName)) { accessor = validator.Start(reference, PropertyName, accessor); } } } if (accessor is null) { throw new AvaloniaInternalException("Data validators must return non-null accessor."); } _accessor = accessor; accessor.Subscribe(ValueChanged); }
public void Test_MethodInvoker_Basic() { var viewModel5 = new TestViewModel5(); var canMethodInvoker = new MethodInvoker(new BindContext(viewModel5, "TestViewModel"), "CanAddAge", null); var methodInvoker = new MethodInvoker(new BindContext(viewModel5, "TestViewModel"), "AddAge", null); bool value = canMethodInvoker.CanInvoke(); Assert.IsFalse(value); methodInvoker.Invoke(); viewModel5.TestViewModel = new TestViewModel(); value = canMethodInvoker.CanInvoke(); Assert.IsTrue(value); methodInvoker.Invoke(); Assert.AreEqual(1, viewModel5.TestViewModel.Age); var canMethodInvoker2 = new MethodInvoker(new BindContext(viewModel5, "TestViewModel"), "AddAge", null); MissingMemberException exception = null; try { canMethodInvoker2.CanInvoke(); } catch (MissingMemberException e) { exception = e; } Assert.IsNotNull(exception); var vm = new TestViewModel(); var canMethodInvoker3 = new MethodInvoker(new BindContext(viewModel5, "TestViewModel"), "CanSetAge", new[] { new BindContext(vm, "Age") }); var methodInvoker2 = new MethodInvoker(new BindContext(viewModel5, "TestViewModel"), "SetAge", new[] { new BindContext(vm, "Age") }); Assert.IsTrue(canMethodInvoker3.CanInvoke()); vm.Age = 6; Assert.AreNotEqual(6, viewModel5.TestViewModel.Age); methodInvoker2.Invoke(); Assert.AreEqual(6, viewModel5.TestViewModel.Age); }
/// <summary>Creates an instance of T using m_valueFactory in case its not null or use reflection to create a new T()</summary> /// <returns>An instance of Boxed.</returns> private Lazy <T> .Boxed CreateValue() { Lazy <T> .Boxed result = null; LazyThreadSafetyMode mode = this.Mode; if (this.m_valueFactory != null) { try { if (mode != LazyThreadSafetyMode.PublicationOnly && this.m_valueFactory == Lazy <T> .PUBLICATION_ONLY_OR_ALREADY_INITIALIZED) { throw new InvalidOperationException("ValueFactory attempted to access the Value property of this instance."); } Func <T> valueFactory = this.m_valueFactory; if (mode != LazyThreadSafetyMode.PublicationOnly) { this.m_valueFactory = Lazy <T> .PUBLICATION_ONLY_OR_ALREADY_INITIALIZED; } result = new Lazy <T> .Boxed(valueFactory()); return(result); } catch (Exception ex) { if (mode != LazyThreadSafetyMode.PublicationOnly) { this.m_boxed = new Lazy <T> .LazyInternalExceptionHolder(ex); } throw; } } try { result = new Lazy <T> .Boxed((T)((object)Activator.CreateInstance(typeof(T)))); } catch (MissingMethodException) { Exception ex2 = new MissingMemberException("The lazily-initialized type does not have a public, parameterless constructor."); if (mode != LazyThreadSafetyMode.PublicationOnly) { this.m_boxed = new Lazy <T> .LazyInternalExceptionHolder(ex2); } throw ex2; } return(result); }
// Test the MissingMemberException class. public void TestMissingMemberException() { ExceptionTester.CheckMain(typeof(MissingMemberException), unchecked ((int)0x80131512)); #if !ECMA_COMPAT && CONFIG_SERIALIZATION MissingMemberException e; e = new MissingMemberException("x", "y"); SerializationInfo info = new SerializationInfo(typeof(MissingMemberException), new FormatterConverter()); StreamingContext context = new StreamingContext(); e.GetObjectData(info, context); AssertEquals("MissingMemberException (1)", "x", info.GetString("MMClassName")); AssertEquals("MissingMemberException (2)", "y", info.GetString("MMMemberName")); #endif }
private Lazy <T> .Boxed CreateValue() { Lazy <T> .Boxed result = null; LazyThreadSafetyMode mode = this.Mode; if (this.m_valueFactory != null) { try { if (mode != LazyThreadSafetyMode.PublicationOnly && this.m_valueFactory == Lazy <T> .PUBLICATION_ONLY_OR_ALREADY_INITIALIZED) { throw new InvalidOperationException(Environment2.GetResourceString("Lazy_Value_RecursiveCallsToValue")); } Func <T> valueFactory = this.m_valueFactory; if (mode != LazyThreadSafetyMode.PublicationOnly) { this.m_valueFactory = Lazy <T> .PUBLICATION_ONLY_OR_ALREADY_INITIALIZED; } return(new Lazy <T> .Boxed(valueFactory())); } catch (Exception ex) { if (mode != LazyThreadSafetyMode.PublicationOnly) { this.m_boxed = new Lazy <T> .LazyInternalExceptionHolder(ex); } throw; } } try { result = new Lazy <T> .Boxed((T)((object)Activator.CreateInstance(typeof(T)))); } catch (MissingMethodException) { Exception ex2 = new MissingMemberException(Environment2.GetResourceString("Lazy_CreateValue_NoParameterlessCtorForT")); if (mode != LazyThreadSafetyMode.PublicationOnly) { this.m_boxed = new Lazy <T> .LazyInternalExceptionHolder(ex2); } throw ex2; } return(result); }
/// <summary> /// Starts monitoring the value of a property on an object. /// </summary> /// <param name="reference">The object.</param> /// <param name="propertyName">The property name.</param> /// <returns> /// An <see cref="IPropertyAccessor"/> interface through which future interactions with the /// property will be made. /// </returns> public IPropertyAccessor Start(WeakReference reference, string propertyName) { Contract.Requires <ArgumentNullException>(reference != null); Contract.Requires <ArgumentNullException>(propertyName != null); var instance = reference.Target; var p = instance.GetType().GetRuntimeProperties().FirstOrDefault(_ => _.Name == propertyName); if (p != null) { return(new Accessor(reference, p)); } else { var message = $"Could not find CLR property '{propertyName}' on '{instance}'"; var exception = new MissingMemberException(message); return(new PropertyError(new BindingNotification(exception, BindingErrorType.Error))); } }
protected override void StartListeningCore(WeakReference <object> reference) { reference.TryGetTarget(out object target); IPropertyAccessorPlugin plugin = null; foreach (IPropertyAccessorPlugin x in ExpressionObserver.PropertyAccessors) { if (x.Match(target, PropertyName)) { plugin = x; break; } } var accessor = plugin?.Start(reference, PropertyName); if (_enableValidation && Next == null) { foreach (var validator in ExpressionObserver.DataValidators) { if (validator.Match(reference, PropertyName)) { accessor = validator.Start(reference, PropertyName, accessor); } } } if (accessor == null) { reference.TryGetTarget(out object instance); var message = $"Could not find a matching property accessor for '{PropertyName}' on '{instance}'"; var exception = new MissingMemberException(message); accessor = new PropertyError(new BindingNotification(exception, BindingErrorType.Error)); } _accessor = accessor; accessor.Subscribe(ValueChanged); }
/// <summary> /// Starts monitoring the value of a property on an object. /// </summary> /// <param name="reference">The object.</param> /// <param name="propertyName">The property name.</param> /// <returns> /// An <see cref="IPropertyAccessor"/> interface through which future interactions with the /// property will be made. /// </returns> public IPropertyAccessor Start(WeakReference <object> reference, string propertyName) { Contract.Requires <ArgumentNullException>(reference != null); Contract.Requires <ArgumentNullException>(propertyName != null); reference.TryGetTarget(out object instance); var p = GetPropertyWithName(instance.GetType(), propertyName); if (p != null) { return(new Accessor(reference, p)); } else { var message = $"Could not find CLR property '{propertyName}' on '{instance}'"; var exception = new MissingMemberException(message); return(new PropertyError(new BindingNotification(exception, BindingErrorType.Error))); } }
public void RemoveCosmetics(IProduct cosmetics) { Validator.CheckIfNull(cosmetics); try { if (this.collection.Remove(cosmetics)) { // item is removed from the collection } else { MissingMemberException missingMember = new MissingMemberException(string.Format("Product {0} does not exist in category {1}!", cosmetics.Name, this.Name)); throw missingMember; } } catch (MissingMemberException m) { Console.WriteLine(m.Message); } }
// 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 MissingMemberException."); try { MissingMemberException myException = new MissingMemberException(); if (myException == null) { TestLibrary.TestFramework.LogError("001.1", "MissingMemberException instance can not create correctly."); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("001.0", "Unexpected exception: " + e); retVal = false; } return(retVal); }
protected override void BeginQuery() { Exception error = null; object result = null; if (_objectType == null) { error = new InvalidOperationException("ObjectType is not set."); } else if (String.IsNullOrEmpty(_propertyName)) { error = new InvalidOperationException("PropertyName is not set."); } else { PropertyInfo prop = _objectType.GetProperty(_propertyName, BindingFlags.Static | BindingFlags.Public); if (prop == null) { error = new MissingMemberException(_objectType.FullName, _propertyName); } else { try { result = prop.GetValue(null, null); } catch (MethodAccessException e) { error = e; } catch (TargetInvocationException e) { error = e; } } } base.OnQueryFinished(result, error, null, null); }
/// <summary> /// Starts monitoring the value of a property on an object. /// </summary> /// <param name="reference">A weak reference to the object.</param> /// <param name="propertyName">The property name.</param> /// <returns> /// An <see cref="IPropertyAccessor"/> interface through which future interactions with the /// property will be made. /// </returns> public IPropertyAccessor Start(WeakReference reference, string propertyName) { Contract.Requires <ArgumentNullException>(reference != null); Contract.Requires <ArgumentNullException>(propertyName != null); var instance = reference.Target; var o = (AvaloniaObject)instance; var p = AvaloniaPropertyRegistry.Instance.FindRegistered(o, propertyName); if (p != null) { return(new Accessor(new WeakReference <AvaloniaObject>(o), p)); } else if (instance != AvaloniaProperty.UnsetValue) { var message = $"Could not find AvaloniaProperty '{propertyName}' on '{instance}'"; var exception = new MissingMemberException(message); return(new PropertyError(new BindingNotification(exception, BindingErrorType.Error))); } else { return(null); } }
public static bool RelatesTo(this MissingMemberException source, Type type, string memberNameIfAny) { if (source == null) { throw new ArgumentNullException("source"); } if (type == null) { throw new ArgumentNullException("type"); } // If a default member is requested, then a number of things may happen. If the request comes from VBScript then it will likely be requested as "[DISPID=0]", // in which case that string will appear in the exception message. If a request is made through an IReflect.InvokeMember call then the member may appear blank. // If a request is made through a Type.InvokeMember call then the blank string may be replaced with the member identified by the DefaultMemberAttribute that // the type has (if it has one) - eg. typeof(string) will specify "Chars" as the target member (since that is what the DefaultMemberAttribute specifies). // - So first, try the simplest match case, where there is no funny business if (source.Message.Contains("'" + type.FullName + "." + memberNameIfAny + "'")) { return(true); } // If that doesn't succeed, and it looks like the request was for the default member, then try the various default member options if (string.IsNullOrWhiteSpace(memberNameIfAny) || (memberNameIfAny == "[DISPID=0]")) { var defaultMemberNameOfTargetType = type.GetCustomAttribute <DefaultMemberAttribute>(inherit: true); if (defaultMemberNameOfTargetType != null) { // TODO: I don't even know if this is correct any more return (source.Message.Contains("'" + type.FullName + "." + defaultMemberNameOfTargetType.MemberName + "'") || source.Message.Contains("'" + type.FullName + ".[DISPID=0]'") || source.Message.Contains("'" + type.FullName + ".'")); } } return(false); }
// Test the MissingMemberException class. public void TestMissingMemberException() { ExceptionTester.CheckMain(typeof(MissingMemberException), unchecked((int)0x80131512)); #if !ECMA_COMPAT && CONFIG_SERIALIZATION MissingMemberException e; e = new MissingMemberException("x", "y"); SerializationInfo info = new SerializationInfo(typeof(MissingMemberException), new FormatterConverter()); StreamingContext context = new StreamingContext(); e.GetObjectData(info, context); AssertEquals("MissingMemberException (1)", "x", info.GetString("MMClassName")); AssertEquals("MissingMemberException (2)", "y", info.GetString("MMMemberName")); #endif }
/// <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); }