Recently, I had a scenario wherein based on the review of user (an option set field), the record should get deactivated. That's a pretty easy stuff, ain't it? A simple OOB Worklfow / Power Automate Flow will suffice our purpose.
But the entity I was dealing with was enabled for BPF, so I not only had to deactivate the record but also need to make sure that the BPF is aborted automatically and that's where I got hit up with the concept of aborting a BPF using C# Code.
P.S.: I have used the Update Request
instead of SetStateRequest
as the latter is now deprecated. Reference is available on MS Docs.
OrganizationServiceContext objOrgServiceContext = new OrganizationServiceContext(objService); // objService is the IOrganizationService object
string sMainEntityLogicalName = "new_application";
string sBPFEntityLogicalName = "new_applicationbpf";
string sMainEntityLookupOnBPF = "bpf_new_applicationid"; // Logical name of lookup field of Main Entity in BPF Entity
// You can have "erApplication" from Target or any other source of trigger/retrieval
EntityReference erApplication = new EntityReference(sMainEntityLogicalName, new Guid("00aa00bb-00aa-00bb-00aa-00aa00bb00aa"));
OptionSetValue objInactiveStateCode = new OptionSetValue(1);
OptionSetValue objAbortStatusReason = new OptionSetValue(3);
// We will first retrieve the BPF instance currently activated on Record
var objBPF =
(from eBPF in objOrgServiceContext.CreateQuery(sBPFEntityLogicalName)
where eBPF.GetAttributeValue<EntityReference>(sMainEntityLookupOnBPF).Equals(erApplication)
select new
{
Id = eBPF.Id,
LogicalName = eBPF.LogicalName
}).FirstOrDefault();
if (objBPF != null)
{
Entity eBPFToUpdate = new Entity(objBPF.LogicalName, objBPF.Id);
eBPFToUpdate.Attributes.Add("statecode", objInactiveStateCode);
eBPFToUpdate.Attributes.Add("statuscode", objAbortStatusReason);
objService.Update(eBPFToUpdate);
}
Happy CRM-ing! Ciao.