I am creating a plugin for Dynamics 365 in C#. I am trying to make request using fetchXML, however I am getting the following error: Object reference not set to an instance of an object.
Here is my code:
public void Execute(IServiceProvider serviceProvider)
{
// Obtain the tracing service
ITracingService tracingService =
(ITracingService)serviceProvider.GetService(typeof(ITracingService));
// Obtain the execution context from the service provider.
IPluginExecutionContext context = (IPluginExecutionContext)
serviceProvider.GetService(typeof(IPluginExecutionContext));
IOrganizationService svc = (IOrganizationService)serviceProvider.GetService(typeof(IOrganizationService));
try
{
var id = context.InputParameters["leadid"] as string;
var fetchXml = $@"<?xml version=""1.0"" encoding=""utf-16""?>
<fetch>
<entity name=""lead"">
<attribute name=""leadid"" />
<link-entity name=""new_sitecorevisit"" from=""new_new_parent_leadid"" to=""leadid"">
<attribute name=""new_visitduration"" />
<filter>
<condition attribute=""new_new_parent_leadid"" operator=""eq"" value=""{id}"" />
</filter>
</link-entity>
</entity>
</fetch>";
EntityCollection result = svc.RetrieveMultiple(new FetchExpression(fetchXml));
context.OutputParameters["data"] = result;
}
catch (Exception ex)
{
tracingService.Trace("Error: {0}", ex.ToString());
throw;
}
}
I believe that it is being thrown when this line is reached:
EntityCollection result = svc.RetrieveMultiple(new FetchExpression(fetchXml));
as removing this fixes the issue. However, I do not know why it is throwing this error. I have checked to see if it is an error with the fetchXml variable or the id variable, however these are passing as expected.
I have tested retrieving the data using JavaScript and the data is returned as expected, however, this is not useful for creating a .NET plugin.
Is there a mistake that I am making?