/// <summary> /// Find the method which best matches the given arguments. /// </summary> /// <param name="methods">Methods to search through</param> /// <param name="targetType">The type of <c>this</c>, for instance methods. If looking for a static method, use null.</param> /// <param name="argTypes">Types. argTypes.Length == number of method parameters. argTypes[i] may be null to allow any type, or typeof(Nullable) to mean "any nullable type".</param> /// <param name="conversionOptions">Specifies which conversions are allowed</param> /// <param name="binding">Modified to contain the generic type arguments and argument conversions needed for calling the method</param> /// <param name="exception">Exception created on failure</param> /// <returns>A non-null MethodBase.</returns> /// <exception cref="ArgumentException">The best matching type parameters did not satisfy the constraints of the generic method.</exception> /// <exception cref="MissingMethodException">No match was found.</exception> public static MethodBase GetBestMethod(MethodBase[] methods, Type targetType, Type[] argTypes, ConversionOptions conversionOptions, out Binding binding, out Exception exception) { Type[] instance_actuals = argTypes; Type[] static_actuals = argTypes; if (targetType != null) { static_actuals = AddFirst(argTypes, targetType); } else if (argTypes.Length > 0) { // targetType == null instance_actuals = ButFirst(argTypes); } exception = new MissingMethodException("The arguments (" + PrintTypes(argTypes) + ") do not match any overload of " + methods[0].Name); binding = null; MethodBase bestMethod = null; foreach (MethodBase method in methods) { Binding b = Binding.GetBestBinding(method, (method.IsStatic || method.IsConstructor) ? static_actuals : instance_actuals, conversionOptions, out exception); if (b != null && b < binding) { binding = b; bestMethod = method; } } if (bestMethod == null) { return(null); } // If the method is generic, specialize on the inferred type parameters. return(binding.Bind(bestMethod)); }
public void UnableToConstructHandler(string commandName, string command, MissingMethodException exception) { "Given I have a command whose handler cannot be constructued" .Given(() => { commandName = "UnconstructableCommandHandlerTest"; command = "{A:1,B:2}"; }); "When I issue an HTTP request" .When(() => { try { Server.PutCommand("/commands", commandName, command); } catch (MissingMethodException ex) { exception = ex; } }); "Then an exception is thrown" .Then(() => { exception.Should().NotBeNull(); }); }
// 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(); MissingMethodException myException = new MissingMethodException(expectValue, dpoExpection); if (myException == null) { TestLibrary.TestFramework.LogError("002.1", "MissingMethodException 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 MissingMethodException."); 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 MissingMethodException."); try { string expectValue = "HELLO"; ArgumentException notFoundException = new ArgumentException(); MissingMethodException myException = new MissingMethodException(expectValue, notFoundException); if (myException == null) { TestLibrary.TestFramework.LogError("001.1", "MissingMethodException 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 static void MissingMethodException_Ctor2() { MissingMethodException i = new MissingMethodException("Created MissingMethodException"); Assert.Equal("Created MissingMethodException", i.Message); Assert.Equal(COR_E_MISSINGMETHOD, i.HResult); }
public static void MissingMethodException_Ctor1() { MissingMethodException i = new MissingMethodException(); //Assert.Equal("Attempted to access a missing method.", i.Message, "TestCtor1_001 failed"); Assert.Equal(COR_E_MISSINGMETHOD, i.HResult); }
TryToInitializeTypeInstance(out T instance) { instance = default(T); Type type = typeof(T); if (HasPublicContructors(type)) { MethodAccessException exception = GetPublicConstructorsFoundError(type); return(status : false, exception : exception); } MethodInfo parametrizedTypeInitializator = type.GetMethod("InitializeInstance", BindingFlags.IgnoreCase | BindingFlags.NonPublic | BindingFlags.Static); if (parametrizedTypeInitializator == null) { MissingMethodException exception = GetMissingMethodError(type); return(status : false, exception : exception); } try { instance = (T)parametrizedTypeInitializator.Invoke(null, new object[] { }); return(status : true, exception : null); } catch (Exception e) { return(status : false, exception : e); } }
public static void Ctor_Empty() { var exception = new MissingMethodException(); Assert.NotEmpty(exception.Message); Assert.Equal(COR_E_MISSINGMETHOD, 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 MissingMethodException."); try { string expectValue = "HELLO"; ArgumentException notFoundException = new ArgumentException(); MissingMethodException myException = new MissingMethodException(expectValue, notFoundException); if (myException == null) { TestLibrary.TestFramework.LogError("001.1", "MissingMethodException 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 MissingMethodException instance,string is empty."); try { string expectString = string.Empty; //Create the application domain setup information. MissingMethodException myMissingMethodException = new MissingMethodException(expectString); if (myMissingMethodException.Message != expectString) { TestLibrary.TestFramework.LogError("002.1", "the MissingMethodException 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); }
// 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(); MissingMethodException myException = new MissingMethodException(expectValue, dpoExpection); if (myException == null) { TestLibrary.TestFramework.LogError("002.1", "MissingMethodException 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 MissingMethodException."); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002.0", "Unexpected exception: " + e); retVal = false; } return retVal; }
protected virtual object CreateModel( ControllerContext controllerContext, ExtensibleModelBindingContext bindingContext ) { // If the Activator throws an exception, we want to propagate it back up the call stack, since the application // developer should know that this was an invalid type to try to bind to. try { return(Activator.CreateInstance(bindingContext.ModelType)); } catch (MissingMethodException exception) { // Ensure thrown exception contains the type name. Might be down a few levels. MissingMethodException replacementException = ModelBinderUtil.EnsureDebuggableException( exception, bindingContext.ModelType.FullName ); if (replacementException != null) { throw replacementException; } throw; } }
public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: Create a new MissingMethodException instance,string is empty."); try { string expectString = string.Empty; //Create the application domain setup information. MissingMethodException myMissingMethodException = new MissingMethodException(expectString); if (myMissingMethodException.Message != expectString) { TestLibrary.TestFramework.LogError("002.1", "the MissingMethodException 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 static void Ctor_String() { string message = "Created MissingMethodException"; var exception = new MissingMethodException(message); Assert.Equal(message, exception.Message); Assert.Equal(COR_E_MISSINGMETHOD, exception.HResult); }
public static void Ctor_String_String() { string className = "class"; string memberName = "member"; var exception = new MissingMethodException(className, memberName); Assert.Contains(className, exception.Message); Assert.Contains(memberName, exception.Message); }
public static void MissingMethodException_Ctor3() { Exception ex = new Exception("Created inner exception"); MissingMethodException i = new MissingMethodException("Created MissingMethodException", ex); Assert.Equal("Created MissingMethodException", i.Message); Assert.Equal(COR_E_MISSINGMETHOD, i.HResult); Assert.Equal(i.InnerException.Message, "Created inner exception"); Assert.Equal(i.InnerException.HResult, ex.HResult); }
private static MethodInfo GetMethodFromType(Type type, string methodName) { MethodInfo method = type.GetMethod(methodName); if (method != null) return method; // Not support pregen. Workaround SecurityCritical required for assembly.CodeBase api. MissingMethodException missingMethod = new MissingMethodException(type.FullName + "::" + methodName); throw missingMethod; }
public static void Ctor_String_String() { string className = "class"; string memberName = "member"; var exception = new MissingMethodException(className, memberName); Assert.Contains(className, exception.Message); Assert.Contains(memberName, exception.Message); Assert.Equal(COR_E_MISSINGMETHOD, exception.HResult); }
public static void Ctor_String_Exception() { string message = "Created MissingMethodException"; var innerException = new Exception("Created inner exception"); var exception = new MissingMethodException(message, innerException); Assert.Equal(message, exception.Message); Assert.Equal(COR_E_MISSINGMETHOD, exception.HResult); Assert.Same(innerException, exception.InnerException); Assert.Equal(innerException.HResult, exception.InnerException.HResult); }
public void Throw_MissingMethodException_WhenShouldThrowOnMissingIsTrueAndMethodNotFound_WhenMethod() { // Arrange TestPerson instance = this.fixture.Create <TestPerson>(); Mock <IFunkyFactory> factoryMock = TestHelper.GetMockedFunkyFactory(); Indexed sut = new Indexed(instance, true, factoryMock.Object); // Act & Assert MissingMethodException ex = Assert.Throws <MissingMethodException>(() => sut.Get(TestConst.InvalidPropertyName)); StringAssert.Contains(TestConst.InvalidPropertyName, ex.Message); }
private static object ReflectIn(StageElement element) { object obj; object obj1; object obj2; string str = element.AttributeValueOrDefault <string>("type", null); if (str == null) { throw new SerializationException("Invalid structure detected, missing type info."); } Type type = Type.GetType(str, true); try { obj = Activator.CreateInstance(type, true); } catch (MissingMethodException missingMethodException1) { MissingMethodException missingMethodException = missingMethodException1; throw new SerializationException(string.Format("Unable to create type {0}, ensure it has a parameterless constructor", type.Name), missingMethodException); } IInitializeAfterDeserialization initializeAfterDeserialization = obj as IInitializeAfterDeserialization; if (initializeAfterDeserialization != null) { if (SerializationMaster._requiresInit == null) { throw new InvalidOperationException("An entity requires initialization but was unable to register, call UnstageAndInitialize instead."); } SerializationMaster._requiresInit.Add(initializeAfterDeserialization); } foreach (PropertyInfo serializedProperty in SerializationMaster.GetSerializedProperties(type)) { StageItem stageItem = element.Item(serializedProperty.Name); if (stageItem == null || !SerializationMaster.TryUnstage(stageItem, serializedProperty.PropertyType, out obj1)) { continue; } serializedProperty.SetValue(obj, obj1, null); } foreach (FieldInfo serializedField in SerializationMaster.GetSerializedFields(type)) { StageItem stageItem1 = element.Item(serializedField.Name); if (stageItem1 == null || !SerializationMaster.TryUnstage(stageItem1, serializedField.FieldType, out obj2)) { continue; } serializedField.SetValue(obj, obj2); } return(obj); }
public void LogExceptionReceivedEvent_NonMessagingException_LoggedAsError() { var ex = new MissingMethodException("What method??"); var e = new ExceptionReceivedEventArgs("TestHostName", "TestAction", "TestPartitionId", ex); EventHubExtensionConfigProvider.LogExceptionReceivedEvent(e, _loggerFactory); string expectedMessage = "EventProcessorHost error (Action='TestAction', HostName='TestHostName', PartitionId='TestPartitionId')."; var logMessage = _loggerProvider.GetAllLogMessages().Single(); Assert.AreEqual(LogLevel.Error, logMessage.Level); Assert.AreSame(ex, logMessage.Exception); Assert.AreEqual(expectedMessage, logMessage.FormattedMessage); }
/// <summary> /// Find the method which best matches the given arguments. /// </summary> /// <param name="type"></param> /// <param name="memberName"></param> /// <param name="flags"></param> /// <param name="targetType">The type of <c>this</c>, for instance methods. If looking for a static method, use null.</param> /// <param name="argTypes">Types. argTypes.Length == number of method parameters. argTypes[i] may be null to allow any type, or typeof(Nullable) to mean "any nullable type".</param> /// <param name="exception">Exception created on failure</param> /// <returns>null on failure.</returns> /// <exception cref="ArgumentException">The best matching type parameters did not satisfy the constraints of the generic method.</exception> /// <exception cref="MissingMethodException">No match was found.</exception> public static MethodBase GetBestMethod(Type type, string memberName, BindingFlags flags, Type targetType, Type[] argTypes, out Exception exception) { MethodInfo[] methods = type.GetMethods(flags); methods = Array.FindAll <MethodInfo>(methods, delegate(MethodInfo method) { return(method.Name == memberName); }); if (methods.Length == 0) { exception = new MissingMethodException(type.Name + " does not have any methods named " + memberName + " under the binding flags " + flags); return(null); } else { return(GetBestMethod(methods, targetType, argTypes, out exception)); } }
public void ProcessNameFromId_GetProcessByIdReturnsProcess_ReturnsName() { Process currentProcess = Process.GetCurrentProcess(); Exception expectedException = new MissingMethodException(); _processAbstractionMock.Setup(x => x.GetProcessById(TestProcessId)) .Returns(currentProcess); ProcessHelper helper = new ProcessHelper(_processAbstractionMock.Object); var processName = helper.ProcessNameFromId(TestProcessId); Assert.AreEqual(currentProcess.ProcessName, processName); _processAbstractionMock.VerifyAll(); }
private static MethodInfo GetMethodFromType(Type type, string methodName, Assembly assembly) { MethodInfo method = type.GetMethod(methodName); if (method != null) { return method; } MissingMethodException innerException = new MissingMethodException(type.FullName, methodName); if (assembly != null) { throw new InvalidOperationException(Res.GetString("XmlSerializerExpired", new object[] { assembly.FullName, assembly.CodeBase }), innerException); } throw innerException; }
public void LogExceptionReceivedEvent_NonMessagingException_LoggedAsError() { var ex = new MissingMethodException("What method??"); ProcessErrorEventArgs e = new ProcessErrorEventArgs(ex, ServiceBusErrorSource.Complete, "TestEndpoint", "TestEntity", CancellationToken.None); ServiceBusExtensionConfigProvider.LogExceptionReceivedEvent(e, _loggerFactory); var expectedMessage = $"Message processing error (Action=Complete, EntityPath=TestEntity, Endpoint=TestEndpoint)"; var logMessage = _loggerProvider.GetAllLogMessages().Single(); Assert.AreEqual(LogLevel.Error, logMessage.Level); Assert.AreSame(ex, logMessage.Exception); Assert.AreEqual(expectedMessage, logMessage.FormattedMessage); }
public void LogExceptionReceivedEvent_NonMessagingException_LoggedAsError() { var ex = new MissingMethodException("What method??"); ExceptionReceivedEventArgs e = new ExceptionReceivedEventArgs(ex, "TestAction", "TestEndpoint", "TestEntity", "TestClient"); ServiceBusExtensionConfigProvider.LogExceptionReceivedEvent(e, _loggerFactory); var expectedMessage = $"MessageReceiver error (Action=TestAction, ClientId=TestClient, EntityPath=TestEntity, Endpoint=TestEndpoint)"; var logMessage = _loggerProvider.GetAllLogMessages().Single(); Assert.Equal(LogLevel.Error, logMessage.Level); Assert.Same(ex, logMessage.Exception); Assert.Equal(expectedMessage, logMessage.FormattedMessage); }
public void ProcessNameFromId_GetProcessByIdReturnsThrowsException_ThrowsParamterException() { Exception expectedException = new MissingMethodException(); _processAbstractionMock.Setup(x => x.GetProcessById(TestProcessId)) .Throws(expectedException); ProcessHelper helper = new ProcessHelper(_processAbstractionMock.Object); ParameterException e = Assert.ThrowsException <ParameterException>( () => helper.ProcessNameFromId(TestProcessId)); Assert.AreEqual("Unable to find process with id -123", e.Message); Assert.AreEqual(expectedException, e.InnerException); _processAbstractionMock.VerifyAll(); }
public void LogExceptionReceivedEvent_NonMessagingException_LoggedAsError() { var ex = new MissingMethodException("What method??"); var ctor = typeof(ExceptionReceivedEventArgs).GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance).Single(); var e = (ExceptionReceivedEventArgs)ctor.Invoke(new object[] { "TestHostName", "TestPartitionId", ex, "TestAction" }); EventHubExtensionConfigProvider.LogExceptionReceivedEvent(e, _loggerFactory); string expectedMessage = "EventProcessorHost error (Action=TestAction, HostName=TestHostName, PartitionId=TestPartitionId)"; var logMessage = _loggerProvider.GetAllLogMessages().Single(); Assert.Equal(LogLevel.Error, logMessage.Level); Assert.Same(ex, logMessage.Exception); Assert.Equal(expectedMessage, logMessage.FormattedMessage); }
public void LogExceptionReceivedEvent_NonMessagingException_LoggedAsError() { var ex = new MissingMethodException("What method??"); ExceptionReceivedEventArgs e = new ExceptionReceivedEventArgs(ex, "TestAction", "TestEndpoint", "TestEntity", "TestClient"); ServiceBusTriggerAttributeBindingProvider.LogExceptionReceivedEvent(e, "TestFunction", _loggerFactory); var expectedMessage = $"Message processing error (Action=TestAction, ClientId=TestClient, EntityPath=TestEntity, Endpoint=TestEndpoint)"; var logMessage = _loggerProvider.GetAllLogMessages().Single(); Assert.Equal(LogLevel.Error, logMessage.Level); Assert.Same(ex, logMessage.Exception); Assert.Equal(expectedMessage, logMessage.FormattedMessage); Assert.True(logMessage.Category.Contains("TestFunction")); }
public static MissingMethodException EnsureDebuggableException(MissingMethodException originalException, string fullTypeName) { MissingMethodException result = null; if (!originalException.Message.Contains(fullTypeName)) { string message = string.Format(CultureInfo.CurrentCulture, Resource.TypeHelpers_CannotCreateInstance, new object[] { originalException.Message, fullTypeName }); result = new MissingMethodException(message, originalException); } return(result); }
protected virtual object CreateModel( ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType ) { // fallback to the type's default constructor Type typeToCreate = modelType; // we can understand some collection interfaces, e.g. IList<>, IDictionary<,> if (modelType.IsGenericType) { Type genericTypeDefinition = modelType.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(IDictionary <,>)) { typeToCreate = typeof(Dictionary <,>).MakeGenericType( modelType.GetGenericArguments() ); } else if ( genericTypeDefinition == typeof(IEnumerable <>) || genericTypeDefinition == typeof(ICollection <>) || genericTypeDefinition == typeof(IList <>) ) { typeToCreate = typeof(List <>).MakeGenericType(modelType.GetGenericArguments()); } } try { return(Activator.CreateInstance(typeToCreate)); } catch (MissingMethodException exception) { // Ensure thrown exception contains the type name. Might be down a few levels. MissingMethodException replacementException = TypeHelpers.EnsureDebuggableException( exception, typeToCreate.FullName ); if (replacementException != null) { throw replacementException; } throw; } }
public void CreateModelThrowsIfModelTypeHasNoParameterlessConstructor() { // Arrange TestableMutableObjectModelBinder testableBinder = new TestableMutableObjectModelBinder(); ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext { ModelMetadata = GetMetadataForType(typeof(NoParameterlessCtor)), }; // Act & Assert, confirming type name and full stack are available in Exception MissingMethodException exception = Assert.Throws <MissingMethodException>( () => testableBinder.CreateModelPublic(null, bindingContext), "No parameterless constructor defined for this object. Object type 'Microsoft.Web.Mvc.ModelBinding.Test.MutableObjectModelBinderTest+NoParameterlessCtor'."); Assert.Contains("System.Activator.CreateInstance(", exception.ToString()); }
// 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 MissingMethodException."); try { MissingMethodException myException = new MissingMethodException(); if (myException == null) { TestLibrary.TestFramework.LogError("001.1", "MissingMethodException instance can not create correctly."); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("001.0", "Unexpected exception: " + e); retVal = false; } return retVal; }
// Test the MissingMethodException class. public void TestMissingMethodException() { ExceptionTester.CheckMain(typeof(MissingMethodException), unchecked((int)0x80131513)); #if !ECMA_COMPAT && CONFIG_SERIALIZATION MissingMethodException e; e = new MissingMethodException("x", "y"); SerializationInfo info = new SerializationInfo(typeof(MissingMethodException), new FormatterConverter()); StreamingContext context = new StreamingContext(); e.GetObjectData(info, context); AssertEquals("MissingMethodException (1)", "x", info.GetString("MMClassName")); AssertEquals("MissingMethodException (2)", "y", info.GetString("MMMemberName")); #endif }
static MethodInfo GetMethodFromType(Type type, string methodName, Assembly assembly) { MethodInfo method = type.GetMethod(methodName); if (method != null) return method; MissingMethodException missingMethod = new MissingMethodException(type.FullName, methodName); if (assembly != null) { throw new InvalidOperationException(Res.GetString(Res.XmlSerializerExpired, assembly.FullName, assembly.CodeBase), missingMethod); } throw missingMethod; }