RestSharp Moq Object Null Exception C# REST Unit Test - c#

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.

Related

TargetParameterCountException when using event Raise with Moq

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?

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.

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.

Assign custom object into Object type variable in SSIS

I'm writing SSIS that scans a SQL table, create an object from each record values and need to move it next to other SSIS flow elements.
I created object type variable (MyObject) and script task.
In my script task I wrote the next code:
RequestObject reqObj = new RequestObject();
reqObj.building = Dts.Variables["reqObj_Building"].Value.ToString();
reqObj.ID = Convert.ToInt32(Dts.Variables["reqObj_DeviceID"].Value);
//...
Now I tried to write the next code in order to assin reqObj into myObject.
Dts.Variables["myObject"].Value = new RequestObject();
Dts.Variables["myObject"].Value = reqObj;
but those lines throws the next run time exception :
Error: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> Microsoft.SqlServer.Dts.Runtime.DtsRuntimeException: The element cannot be found in a collection. This error happens when you try to retrieve an element from a collection on a container during execution of the package and the element is not there.
---> System.Runtime.InteropServices.COMException (0xC0010009): The element cannot be found in a collection. This error happens when you try to retrieve an element from a collection on a container during execution of the package and the element is not there.
at Microsoft.SqlServer.Dts.Runtime.Wrapper.IDTSVariables100.get_Item(Object Index)
at Microsoft.SqlServer.Dts.Runtime.Variables.get_Item(Object index)
--- End of inner exception stack trace ---
at Microsoft.SqlServer.Dts.Runtime.Variables.get_Item(Object index)
at ST_a3e0b574a8964ffb8af6f9fee31d5afd.csproj.ScriptMain.Main()
--- End of inner exception stack trace ---
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.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams)
at System.Type.InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args, CultureInfo culture)
at Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTATaskScriptingEngine.ExecuteScript()
How can I assign custom object into SSIS Object type variable ?
It it possible?
Thanks
I don't have enough reputation to comment so I'm adding an answer instead. I did the below steps to try and replicate your problem:
Created a new script task
Created a new class in the namespace of that script
Created a variable of type Object and added to script task as Read/Write variable
Initialised the new class and assigned that value to the Object variable.
Below is my code which ran successfully. Can you please explain if there is any thing I am missing/understanding wrong?
using System;
using System.Data;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
namespace ST_8eab6a8fbc79431c8c9eb80339c09d1d.csproj
{
public class myclass
{
int a, b;
public myclass()
{
a = 0;
b = 0;
}
}
[System.AddIn.AddIn("ScriptMain", Version = "1.0", Publisher = "", Description = "")]
public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
{
#region VSTA generated code
enum ScriptResults
{
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
};
#endregion
public void Main()
{
Dts.TaskResult = (int)ScriptResults.Success;
myclass m = new myclass();
Dts.Variables["myObject"].Value = m;
}
}
}

Categories

Resources