TargetParameterCountException when using event Raise with Moq - c#

I have a class with following event:
event Func<ApplicationMessageProcessedEventArgs, Task> ApplicationMessageProcessedAsync;
I would like to test the handler for an event, I am using Moq and have following code
mqttClient.Mock.Raise(client => client.ApplicationMessageReceivedAsync += null, eventArg);
I am getting exception:
System.Reflection.TargetParameterCountException: Parameter count mismatch.
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Delegate.DynamicInvokeImpl(Object[] args)
at System.Delegate.DynamicInvoke(Object[] args)
at Moq.Extensions.InvokePreserveStack(Delegate del, IReadOnlyList`1 args) in C:\projects\moq4\src\Moq\Extensions.cs:line 158
at Moq.Mock.RaiseEvent(Mock mock, LambdaExpression expression, Stack`1 parts, Object[] arguments) in C:\projects\moq4\src\Moq\Mock.cs:line 745
at Moq.Mock.RaiseEvent[T](Mock mock, Action`1 action, Object[] arguments) in C:\projects\moq4\src\Moq\Mock.cs:line 695
at Moq.Mock`1.Raise(Action`1 eventExpression, EventArgs args) in C:\projects\moq4\src\Moq\Mock`1.cs:line 1366
at MqttChannel.MqttChannelTest.MqttChannel_ProcessNewMessage() in C:\Development\Shared\OT.Test\MqttChannel\MqttChannelTest.cs:line 298
at Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.ThreadOperations.ExecuteWithAbortSafety(Action action)
Any idea how to solve this?

Related

ArgumentOutOfRange exception on ConfigureAwait(false)

I've the following function:
var handlerType = typeof(IQueryHandler<,>).MakeGenericType(query.GetType(), typeof(string));
dynamic handler = _c.Resolve(handlerType);
var test1 = await handler.Run(query);
var test2 = await handler.Run(query).ConfigureAwait(false);
The first await statement runs fine but the second statement gives me an ArgumentOutOfRange exception. I've really no idea why this is happening.
I'm using Autofac for resolving the my services.
Can you guys please help me with this?
EDITED:
at System.String.Substring(Int32 startIndex, Int32 length)
at Microsoft.CSharp.RuntimeBinder.Syntax.NameTable.Add(String key, Int32 length)
at Microsoft.CSharp.RuntimeBinder.Syntax.NameManager.Add(String key, Int32 length)
at Microsoft.CSharp.RuntimeBinder.SymbolTable.GetName(Type type)
at Microsoft.CSharp.RuntimeBinder.SymbolTable.LoadSymbolsFromType(Type originalType)
at Microsoft.CSharp.RuntimeBinder.SymbolTable.AddMethodToSymbolTable(MemberInfo member, AggregateSymbol callingAggregate, MethodKindEnum kind)
at Microsoft.CSharp.RuntimeBinder.SymbolTable.AddNamesInInheritanceHierarchy(String name, List`1 inheritance)
at Microsoft.CSharp.RuntimeBinder.SymbolTable.PopulateSymbolTableWithName(String name, IEnumerable`1 typeArguments, Type callingType)
at Microsoft.CSharp.RuntimeBinder.RuntimeBinder.PopulateSymbolTableWithPayloadInformation(SymbolTable symbolTable, ICSharpInvokeOrInvokeMemberBinder callOrInvoke, Type callingType, ArgumentObject[] arguments)
at Microsoft.CSharp.RuntimeBinder.CSharpInvokeMemberBinder.PopulateSymbolTableWithName(SymbolTable symbolTable, Type callingType, ArgumentObject[] arguments)
at Microsoft.CSharp.RuntimeBinder.RuntimeBinder.BindCore(ICSharpBinder payload, Expression[] parameters, DynamicMetaObject[] args, DynamicMetaObject& deferredBinding)
at Microsoft.CSharp.RuntimeBinder.RuntimeBinder.Bind(DynamicMetaObjectBinder payload, Expression[] parameters, DynamicMetaObject[] args, DynamicMetaObject& deferredBinding)
at Microsoft.CSharp.RuntimeBinder.BinderHelper.Bind(DynamicMetaObjectBinder action, RuntimeBinder binder, DynamicMetaObject[] args, IEnumerable`1 arginfos, DynamicMetaObject onBindingError)
at Microsoft.CSharp.RuntimeBinder.CSharpInvokeMemberBinder.FallbackInvokeMember(DynamicMetaObject target, DynamicMetaObject[] args, DynamicMetaObject errorSuggestion)
at System.Dynamic.DynamicMetaObject.BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args)
at System.Dynamic.InvokeMemberBinder.Bind(DynamicMetaObject target, DynamicMetaObject[] args)
at System.Dynamic.DynamicMetaObjectBinder.Bind(Object[] args, ReadOnlyCollection`1 parameters, LabelTarget returnLabel)
at System.Runtime.CompilerServices.CallSiteBinder.BindCore[T](CallSite`1 site, Object[] args)
at System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,TRet](CallSite site, T0 arg0)
at Kairos.Services.ImportService.ImportService.<RunAsync>d__4.MoveNext() in F:\Sources\BZ\Kairos\Services\Kairos.Services.ImportService\ImportService.cs:line 61

MethodInfo.Invoke (Object reference not set to an instance of an object.) on calling static method in abstract class

I am trying to replicate a functionality with reflection but end up getting
createFormatMethod.Invoke(typDbFormatClass, null)' threw an exception of type 'System.Reflection.TargetInvocationException' object {System.Reflection.TargetInvocationException}
Inner Exception Shows Object reference not set to an instance of an object.
System.NullReferenceException
InnerException null
Stacktrace
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
at AB.INIT.stringToValue(String valueInUnits, String dimension, String sourceUnit, String destinationUnit)
I am trying to access a static method of abstract class here. Below is the direct reference code that works perfectly .
Binit.Core.Database.DbFormat format;
format = Binit.Core.Database.DbFormat.Create();
format.Dimension = DbDoubleDimension.GetDimension(
(DbDimension)Enum.Parse(typeof(DbDimension), dimension));
format.Units = DbDoubleUnits.GetUnits(
(DbUnits)Enum.Parse(typeof(DbUnits), destinationUnit));
Reflection Code which fails and shows targetinvocationexception
Assembly CoreDatabaseAssembly =
Assembly.LoadFrom(Path.Combine(APath, #"Binit.Core.Database.dll"));
Type typDbFormatClass = CoreDatabaseAssembly.GetType("Binit.Core.Database.DbFormat");
MethodInfo createFormatMethod = typDbFormatClass.GetMethod("Create",
BindingFlags.Static | BindingFlags.Public, null, new Type[] { }, null);
object objDbFormat = createFormatMethod.Invoke(typDbFormatClass, null);
Can someone help me understand what i could be doing wrong with invoke method

Having an issue publishing from Sitecore

I'm getting this error when trying to publish any item from Sitecore to the web. Was working fine the other day, not sure what I did to crash this.
Job started: Publish to 'web'|#Exception:
System.Reflection.TargetInvocationException: Exception has been thrown
by the target of an invocation. --->
System.Reflection.TargetInvocationException: Exception has been thrown
by the target of an invocation. ---> System.InvalidOperationException:
Root item is not defined at
Sitecore.Diagnostics.Assert.IsNotNull(Object value, String message)
at Sitecore.Search.Crawlers.DatabaseCrawler.Initialize(Index index)
at Sitecore.Search.Index.AddCrawler(ICrawler crawler) --- End of
inner exception stack trace --- at
System.RuntimeMethodHandle.InvokeMethod(Object target, Object[]
arguments, Signature sig, Boolean constructor) at
System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj,
Object[] parameters, Object[] arguments) at
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags
invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.MethodBase.Invoke(Object obj, Object[]
parameters) at
Sitecore.Configuration.Factory.AssignProperties(Object obj, Object[]
properties) at
Sitecore.Configuration.Factory.AssignProperties(XmlNode configNode,
String[] parameters, Object obj, Boolean assert, Boolean deferred,
IFactoryHelper helper) at
Sitecore.Configuration.Factory.CreateObject(XmlNode configNode,
String[] parameters, Boolean assert, IFactoryHelper helper) at
Sitecore.Configuration.Factory.GetInnerObject(XmlNode paramNode,
String[] parameters, Boolean assert) at
Sitecore.Configuration.Factory.AssignProperties(XmlNode configNode,
String[] parameters, Object obj, Boolean assert, Boolean deferred,
IFactoryHelper helper) at
Sitecore.Configuration.Factory.CreateObject(XmlNode configNode,
String[] parameters, Boolean assert, IFactoryHelper helper) at
Sitecore.Configuration.Factory.CreateObject(String configPath,
String[] parameters, Boolean assert) at
Sitecore.Search.SearchManager.get_SearchConfiguration() at
Sitecore.Data.Managers.IndexingManager.UpdateIndexAsync(Database
database) at Sitecore.MainUtil.RaiseEvent[T](EventHandler1
subscribers, Object sender, T eventArgs) at
Sitecore.Data.Engines.HistoryEngine.RegisterItemSaved(Item item,
ItemChanges changes) at System.EventHandler1.Invoke(Object sender,
TEventArgs e) at
Sitecore.Data.Engines.EngineCommand2.RaiseEvent[TArgs](EventHandler1
handlers, Func2 argsCreator) at
Sitecore.Data.Engines.EngineCommand2.Execute() at
Sitecore.Data.Engines.DataEngine.SaveItem(Item item) at
Sitecore.Data.Managers.ItemProvider.SaveItem(Item item) at
Sitecore.Data.Items.ItemEditing.AcceptChanges(Boolean
updateStatistics, Boolean silent) at
Sitecore.Data.Items.EditContext.Dispose() at
Sitecore.Publishing.PublishHelper.CopyToTarget(Item sourceVersion)
at Sitecore.Publishing.PublishHelper.PublishVersionToTarget(Item
sourceVersion, Item targetItem, Boolean targetCreated) at
Sitecore.Publishing.Pipelines.PublishItem.PerformAction.ExecuteAction(PublishItemContext
context) at
Sitecore.Publishing.Pipelines.PublishItem.PerformAction.Process(PublishItemContext
context) at (Object , Object[] ) at
Sitecore.Pipelines.CorePipeline.Run(PipelineArgs args) at
Sitecore.Publishing.Pipelines.PublishItem.PublishItemPipeline.Run(PublishItemContext
context) at
Sitecore.Publishing.Pipelines.Publish.ProcessQueue.ProcessEntries(IEnumerable1
entries, PublishContext context) at
Sitecore.Publishing.Pipelines.Publish.ProcessQueue.ProcessEntries(IEnumerable1
entries, PublishContext context) at
Sitecore.Publishing.Pipelines.Publish.ProcessQueue.ProcessEntries(IEnumerable1
entries, PublishContext context) at
Sitecore.Publishing.Pipelines.Publish.ProcessQueue.ProcessEntries(IEnumerable1
entries, PublishContext context) at
Sitecore.Publishing.Pipelines.Publish.ProcessQueue.Process(PublishContext
context) at (Object , Object[] ) at
Sitecore.Pipelines.CorePipeline.Run(PipelineArgs args) at
Sitecore.Publishing.Pipelines.Publish.PublishPipeline.Run(PublishContext
context) at Sitecore.Publishing.Publisher.PublishWithResult()
--- End of inner exception stack trace --- at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[]
arguments, Signature sig, Boolean constructor) at
System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj,
Object[] parameters, Object[] arguments) at
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags
invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.MethodBase.Invoke(Object obj, Object[]
parameters) at (Object , Object[] ) at
Sitecore.Pipelines.CorePipeline.Run(PipelineArgs args) at
Sitecore.Jobs.Job.ThreadEntry(Object state)
It looks like the index configuration is corrupted.
Go to /sitecore/admin/showconfig.aspx page and find:
<locations hint="list:AddCrawler">
Check every location under that node - they all should have <Root> tag with the proper location root specified.
You can check Sitecore logs. As per my finding it is occurred because I've specified wrong username/password in connectionstrings.config. Please make sure username and password is correct.

RestSharp Moq Object Null Exception C# REST Unit Test

I'm having difficulties trying to figure this out. Any help is greatly appreciated. My restClient.Object gets a null exception. When I inspect the .Object of the restClient I get
Message: Exception has been thrown by the target of an invocation.
Inner Exception: Value cannot be null.Parameter name: source
Stack Trace:
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, StackCrawlMark& stackMark)
at System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)
at System.Activator.CreateInstance(Type type, Object[] args)
at Castle.DynamicProxy.ProxyGenerator.CreateClassProxyInstance(Type proxyType, List`1 proxyArguments, Type classToProxy, Object[] constructorArguments)
at Castle.DynamicProxy.ProxyGenerator.CreateClassProxy(Type classToProxy, Type[] additionalInterfacesToProxy, ProxyGenerationOptions options, Object[] constructorArguments, IInterceptor[] interceptors)
at Moq.Proxy.CastleProxyFactory.CreateProxy(Type mockType, ICallInterceptor interceptor, Type[] interfaces, Object[] arguments)
at Moq.Mock`1.<InitializeInstance>b__2()
at Moq.PexProtector.Invoke(Action action)
at Moq.Mock`1.InitializeInstance()
at Moq.Mock`1.OnGetObject()
at Moq.Mock.GetObject()
at Moq.Mock.get_Object()
at Moq.Mock`1.get_Object()
Btw, I'm referring to this line of code:
var client = new IncidentRestClient(**restClient.Object**);
Am I mocking the object incorrectly?
[Test]
public void Insert_Method_Throws_exception_if_response_StatusCode_is_not_Created()
{
//Arrange
var restClient = new Mock<RestClient>();
restClient.Setup(x => x.Execute<RootObject>(It.IsAny<IRestRequest>()))
.Returns(new RestResponse<RootObject>
{
StatusCode = HttpStatusCode.BadRequest
});
var client = new IncidentRestClient(restClient.Object);
Assert.Throws<Exception>(() => client.CreateNewIncident(insertIncidentRequest));
}
Uninstalling and reinstalling Moq did not work for me. Instead, setting the CallBase property on the Mock object to true did the trick:
var restClientMock = new Mock<RestClient> { CallBase = true };
Issue has been resolved. I had to uninstall and reinstall Moq with nuget.

Why is EventInfo.RemoveEventHandler throwing a NullReferenceException?

I've got some code that is using reflection to install .NET event handlers on MSHTML objects in an Internet Explorer BHO, and it appears to be working fine. I'm running into trouble, however, when I try to remove the event handlers.
This is what the code for event handler installation and removal looks like:
public class HandlerExample {
private static void Handler(IHTMLEventObj e) { ... }
private static Delegate handlerDelegate;
public static void InstallHandler(IHTMLElement target, string eventName)
{
// FindInterface() finds the correct event interface for the particular subclass of
// IHTMLElement that target really is
Type eventInterface = FindInterface(target);
EventInfo eInfo = eventInterface.GetEvent(eventName);
Type tHandler = eInfo.EventHandlerType;
handlerDelegate = Delegate.CreateDelegate(tHandler, typeof(HandlerExample), "Handler");
eInfo.AddEventHandler(target, handlerDelegate);
}
public static void RemoveHandler(IHTMLElement target, string eventName)
{
Type eventInterface = FindInterface(target);
EventInfo eInfo = eventInterface.GetEvent(eventName);
eInfo.RemoveEventHandler(target, handlerDelegate); // THIS LINE CRASHES
}
}
The call to InstallEventHandler works fine, and Handler then gets called when the event is triggered in the browser. When I call RemoveEventHandler with the same arguments as the InstallEventHandler call, the last line throws a TargetInvocationException, with an inner exception of NullReferenceException. I can't figure out what I'm doing wrong here, and the stack trace is not much help.
EDIT: I've stepped through the code in the debugger, and none of the object variables I directly reference are null.
I've also tried calling both AddEventHandler and RemoveEventHandler in the InstallHandler method, and that works correctly.
Stack trace follows:
System.Reflection.TargetInvocationException occurred
Message="Exception has been thrown by the target of an invocation."
Source="mscorlib"
StackTrace:
at System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
at System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.EventInfo.RemoveEventHandler(Object target, Delegate handler)
at RemoveHandler(IHTMLElement target, String eventName)
InnerException: System.NullReferenceException
Message="Object reference not set to an instance of an object."
Source="Microsoft.mshtml"
StackTrace:
at mshtml.HTMLTextContainerEvents2_EventProvider.remove_onclick(HTMLTextContainerEvents2_onclickEventHandler )
at mshtml.HTMLTextAreaElementClass.HTMLTextContainerEvents2_Event_remove_onclick(HTMLTextContainerEvents2_onclickEventHandler )
InnerException:
What could be causing this, and how can I fix it?
Well it looks like your handlerDelegate is null when you are calling the RemoveHandler.
I am not sure why this would happen, but have you tried instantiating the handlerDelegate right before calling RemoveEventHandler?

Categories

Resources