WithArgumentsForConstructor() extension method calls constructor - c#

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.

Related

Parameter Count Mismatch CreateEndSessionUrl - IdentityModel

I'm new to C#. I'm using .NET IdentityModel with AWS Cognito User Pools and attempting to get logout to work. CreateEndSessionUrl sets post_logout_redirect_uri but Cognito requires logout_uri. I'm attempting to use the extra parameter but getting a Parameter Count Mismatch.
Here is my code:
StringDictionary cognitoParameters = new StringDictionary();
cognitoParameters.Add("client_id", OAuthConfiguration.ClientId);
cognitoParameters.Add("logout_uri", OAuthConfiguration.EndsessionEndpointPath);
var endsessionEndpoint = OAuthConfiguration.Authority.TrimEnd('/') + "/" + OAuthConfiguration.EndsessionEndpointPath;
var requestUrl = new RequestUrl(endsessionEndpoint);
var endSessionUrl = requestUrl.CreateEndSessionUrl(
idTokenHint: HttpContext.Current.GetToken(OidcConstants.ResponseTypes.IdToken),
postLogoutRedirectUri: OAuthConfiguration.Host,
state: null,
extra: cognitoParameters
);
The CreateEndSessionUrl documentation says "The extra parameter can either be a string dictionary or an arbitrary other type with properties. In both cases the values will be serialized as keys/values." I assume I'm creating the string dictionary incorrectly somehow.
The error I get is:
Message: Parameter count mismatch.
Exception type: System.Reflection.TargetParameterCountException
Stack trace:
at System.Reflection.RuntimeMethodInfo.InvokeArgumentsCheck(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture)
at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, Object[] index)
at IdentityModel.Internal.ValuesHelper.ObjectToDictionary(Object values)
at IdentityModel.Client.RequestUrlExtensions.CreateEndSessionUrl(RequestUrl request, String idTokenHint, String postLogoutRedirectUri, String state, Object extra)
at Indice.Kentico.Oidc.EndSessionOidcHandler.EndSession()
at Indice.Kentico.Oidc.EndSessionOidcHandler.ProcessRequest(HttpContext context)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step)
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Can someone help me understand how to properly format and include the extra parameter? I actually don't need the idTokenHint, postLogoutRedirectUri, or state if they can be excluded.
I figured out that I needed to create a Dictionary instead of a StringDictionary:
IDictionary cognitoParameters = new Dictionary<string,string>() {
{ "client_id", OAuthConfiguration.ClientId },
{ "logout_uri", OAuthConfiguration.Host.TrimEnd('/') + "/SignOut.ashx" }
};
It is working now.

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

Cannot cast Outlook object to ReportItem

I am trying to enumerate the different mail items in an Outlook folder.
Some of the mail items are ReportItems ... I can tell this because their Class = 46. However, when I try to cast the __ComObject to a ReportItem using ((Outlook.ReportItem)item) I get this exception:
AutoResolvedWinner {System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Runtime.InteropServices.COMException: The operation failed.
--- End of inner exception stack trace ---
at System.RuntimeType.InvokeDispMethod(String name, BindingFlags invokeAttr, Object target, Object[] args, Boolean[] byrefModifiers, Int32 culture, String[] namedParameters)
at System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams)
at System.Dynamic.IDispatchComObject.GetMembers(IEnumerable`1 names)} System.Reflection.TargetInvocationException
If it helps, the MessageClass property of the object is "REPORT.IPM.Note.NDR"
Help would be appreciated.

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

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.

Categories

Resources