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
Related
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?
According to the FakeItEasy tutorial here the WithArgumentsForConstructor() extension method does not call the class constructor:
// Specifying arguments for constructor using expression. This is refactoring friendly!
// The constructor seen here is never actually invoked. It is an expression and it's purpose
// is purely to communicate the constructor arguments which will be extracted from it
var foo = A.Fake<FooClass>(x => x.WithArgumentsForConstructor(() => new FooClass("foo", "bar")));
However, the breakpoint in my Person class constructor is triggered in my test below. How so? Am I using WithArgumentsForConstructor() incorrectly?
[Test]
public void Constructor_With_Arguments()
{
var driver = A.Fake<Person>(x => x.WithArgumentsForConstructor(() => new Person("Jane", 42)));
var age = driver.GetAge();
Assert.AreEqual(42, age);
}
Stack trace:
MyStuff.Tests.Domain.dll!MyStuff.Tests.Domain.Driver.Person(string name, int age) Line 61 C#
DynamicProxyGenAssembly2!Castle.Proxies.DriverProxy.DriverProxy(Castle.DynamicProxy.IInterceptor[] value, string value, int value) Unknown
[Native to Managed Transition]
[Managed to Native Transition]
mscorlib.dll!System.RuntimeType.CreateInstanceImpl(System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, object[] args, System.Globalization.CultureInfo culture, object[] activationAttributes, ref System.Threading.StackCrawlMark stackMark) Unknown
mscorlib.dll!System.Activator.CreateInstance(System.Type type, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, object[] args, System.Globalization.CultureInfo culture, object[] activationAttributes) Unknown
mscorlib.dll!System.Activator.CreateInstance(System.Type type, object[] args) Unknown
FakeItEasy.dll!Castle.DynamicProxy.ProxyGenerator.CreateClassProxyInstance(System.Type proxyType, System.Collections.Generic.List<object> proxyArguments, System.Type classToProxy, object[] constructorArguments) Unknown
FakeItEasy.dll!Castle.DynamicProxy.ProxyGenerator.CreateClassProxy(System.Type classToProxy, System.Type[] additionalInterfacesToProxy, Castle.DynamicProxy.ProxyGenerationOptions options, object[] constructorArguments, Castle.DynamicProxy.IInterceptor[] interceptors) Unknown
FakeItEasy.dll!FakeItEasy.Creation.CastleDynamicProxy.CastleDynamicProxyGenerator.GenerateClassProxy(System.Type typeOfProxy, System.Collections.Generic.IEnumerable<object> argumentsForConstructor, Castle.DynamicProxy.IInterceptor interceptor, System.Collections.Generic.IEnumerable<System.Type> allInterfacesToImplement) Unknown
FakeItEasy.dll!FakeItEasy.Creation.CastleDynamicProxy.CastleDynamicProxyGenerator.DoGenerateProxy(System.Type typeOfProxy, System.Collections.Generic.IEnumerable<System.Type> additionalInterfacesToImplement, System.Collections.Generic.IEnumerable<object> argumentsForConstructor, Castle.DynamicProxy.IInterceptor interceptor) Unknown
FakeItEasy.dll!FakeItEasy.Creation.CastleDynamicProxy.CastleDynamicProxyGenerator.CreateProxyGeneratorResult(System.Type typeOfProxy, System.Collections.Generic.IEnumerable<System.Type> additionalInterfacesToImplement, System.Collections.Generic.IEnumerable<object> argumentsForConstructor, FakeItEasy.Core.IFakeCallProcessorProvider fakeCallProcessorProvider) Unknown
FakeItEasy.dll!FakeItEasy.Creation.CastleDynamicProxy.CastleDynamicProxyGenerator.GenerateProxy(System.Type typeOfProxy, System.Collections.Generic.IEnumerable<System.Type> additionalInterfacesToImplement, System.Collections.Generic.IEnumerable<object> argumentsForConstructor, FakeItEasy.Core.IFakeCallProcessorProvider fakeCallProcessorProvider) Unknown
FakeItEasy.dll!FakeItEasy.Creation.CastleDynamicProxy.CastleDynamicProxyGenerator.GenerateProxy(System.Type typeOfProxy, System.Collections.Generic.IEnumerable<System.Type> additionalInterfacesToImplement, System.Collections.Generic.IEnumerable<object> argumentsForConstructor, System.Collections.Generic.IEnumerable<System.Reflection.Emit.CustomAttributeBuilder> customAttributeBuilders, FakeItEasy.Core.IFakeCallProcessorProvider fakeCallProcessorProvider) Unknown
FakeItEasy.dll!FakeItEasy.Creation.ProxyGeneratorSelector.GenerateProxy(System.Type typeOfProxy, System.Collections.Generic.IEnumerable<System.Type> additionalInterfacesToImplement, System.Collections.Generic.IEnumerable<object> argumentsForConstructor, System.Collections.Generic.IEnumerable<System.Reflection.Emit.CustomAttributeBuilder> customAttributeBuilders, FakeItEasy.Core.IFakeCallProcessorProvider fakeCallProcessorProvider) Unknown
FakeItEasy.dll!FakeItEasy.Creation.FakeObjectCreator.GenerateProxy(System.Type typeOfFake, FakeItEasy.Creation.FakeOptions fakeOptions, System.Collections.Generic.IEnumerable<object> argumentsForConstructor) Unknown
FakeItEasy.dll!FakeItEasy.Creation.FakeObjectCreator.CreateFake(System.Type typeOfFake, FakeItEasy.Creation.FakeOptions fakeOptions, FakeItEasy.Creation.IDummyValueCreationSession session, bool throwOnFailure) Unknown
FakeItEasy.dll!FakeItEasy.Creation.DefaultFakeAndDummyManager.CreateFake(System.Type typeOfFake, FakeItEasy.Creation.FakeOptions options) Unknown
FakeItEasy.dll!FakeItEasy.Creation.DefaultFakeCreatorFacade.CreateFake<SysSurge.DynMock.Tests.Domain.Driver>(System.Action<FakeItEasy.Creation.IFakeOptionsBuilder<SysSurge.DynMock.Tests.Domain.Driver>> options) Unknown
...
You're using it right.
But you understand it wrong.
// The constructor seen here is never actually invoked...
It means that it won't call the constructor exactly in this place. It will parse this expression and use the parameters to invoke the constructor somewhere inside. But it will invoke the constructor.
You can check this to put the breakpoint right inside the expression.
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.
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.
I would like to parse some JSON:
void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(e.Result)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(STMsgObj));
STMsgObj[] messages = (STMsgObj[])serializer.ReadObject(stream);
foreach(STMsgObj aMsg in messages){
MessageBox.Show(aMsg.body, "Data Passed", MessageBoxButton.OK);
}
}
}
How can I convert e.Result into a stream?
Exception:
System.InvalidCastException was unhandled
Message=InvalidCastException
StackTrace:
at StockTwits.ViewModels.StreamPage.webClient_DownloadStringCompleted(Object sender, DownloadStringCompletedEventArgs e)
at System.Net.WebClient.OnDownloadStringCompleted(DownloadStringCompletedEventArgs e)
at System.Net.WebClient.DownloadStringOperationCompleted(Object arg)
at System.Reflection.RuntimeMethodInfo.InternalInvoke(RuntimeMethodInfo rtmi, Object obj, BindingFlags invokeAttr, Binder binder, Object parameters, CultureInfo culture, Boolean isBinderDefault, Assembly caller, Boolean verifyAccess, StackCrawlMark& stackMark)
at System.Reflection.RuntimeMethodInfo.InternalInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, StackCrawlMark& stackMark)
at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
at System.Delegate.DynamicInvokeOne(Object[] args)
at System.MulticastDelegate.DynamicInvokeImpl(Object[] args)
at System.Delegate.DynamicInvoke(Object[] args)
at System.Windows.Threading.DispatcherOperation.Invoke()
at System.Windows.Threading.Dispatcher.Dispatch(DispatcherPriority priority)
at System.Windows.Threading.Dispatcher.OnInvoke(Object context)
at System.Windows.Hosting.CallbackCookie.Invoke(Object[] args)
at System.Windows.Hosting.DelegateWrapper.InternalInvoke(Object[] args)
at System.Windows.RuntimeHost.ManagedHost.InvokeDelegate(IntPtr pHandle, Int32 nParamCount, ScriptParam[] pParams, ScriptParam& pResult)
Try the following:
using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(e.Result)))
{
// Your code here, using stream.
}
Call DownloadDataAsync instead.
You can then pass new MemoryStream(e.Result) from the DownloadDataCompleted event.
If you really want to stick with DownloadStringAsync, you can pass XmlReader.Create(new StringReader(e.Result)).
Given that WebClient wraps an API that is already stream based means there are a number of unnecessary conversions. You might want to consider swapping your WebClient for plain old HttpWebRequest, which hands you a stream out of the box.
HttpWebRequest req=(HttpWebRequest)WebRequest.Create(myUrl);
using(var resp=req.GetResponse())
using(var stream=resp.GetResponseStream())
{
...
}
Your JSON data isn't an array.