Hi,
I have written a pre-operation plugin that gets triggered whenever a 'resource requirement' record gets deleted. My goal is to obtain the Project GUID associated with the resource requirement, so that I can access all Project related details, in a cloud flow. I have used pre-images to store column values of 'resource requirement', just before the record is deleted.
Here is the source code I have used:
using Microsoft.Xrm.Sdk;
using System;
namespace CompanyAbc.Client1.Plugin.PracticePlugins
{
public class resourcerequirement_ObtainProject : IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
IPluginExecutionContext context = (IPluginExecutionContext)
serviceProvider.GetService(typeof(IPluginExecutionContext));
if(context.InputParameters.Contains("Target") &&
context.InputParameters["Target"] is EntityReference)
{
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)
serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service =
serviceFactory.CreateOrganizationService(context.UserId);
EntityReference targetEntity = (EntityReference)context.InputParameters["Target"];
try
{
Entity projectTemporary = new Entity("tanm_projecttemporary");
Entity preImage = context.PreEntityImages["preImageResourceRequirement"];
string rrCountry = preImage.Attributes["msdyn_country"].ToString();
Guid rrGuid = targetEntity.Id;
Guid projectGuid = (Guid)preImage.Attributes["msdyn_projectid"]; // error
string projectGuidType = "msdyn_project";
projectTemporary["tanm_project"] = new EntityReference(projectGuidType, projectGuid);
service.Create(projectTemporary);
}
catch (Exception ex)
{
throw new InvalidPluginExecutionException("Error: "+ex);
}
}
}
}
}
Note: Project Temporary is a custom table I have created to store the Project GUID, so that even if the Resource Requirement record gets deleted, I will still be able to access the project GUID, when my cloud flow gets triggered, on the creation of 'Project Temporary' record.
The issue is that I cannot retrieve the Project GUID, since the field is of GUID data type. It says that I have used an Invalid Cast. However, I am able to retrieve the pre-image, if it is of 'string' data type. My guess is that I have used an incorrect syntax to obtain the Guid.
The only GUID I am able to access in the C# code, is the resource requirement ID.
I've tried using Retrieve() method and ColumnSet to retrieve the fields but at the time of profiling, it said that the record has already been deleted.
I even changed the message of the plugin to 'Update', and used the GetAttributeValue() method, and then converted the GUID to a string, but instead of getting the GUID, the value returned is 'Microsoft.Xrm.Sdk.EntityReference'.
Would be really helpful if anyone could share the correct syntax to retrieve the pre-image of a GUID field.
Or if there's a better way to go about approaching the problem.
Thanks!