RE: Retrieve Business Process Flow Stagename in Dynamics 365
Hi MN,
Please keep in mind that with the latest changes of the BPF in CRM (whereby you get a new entity created for each Business Process Flow) it is no longer recommended to use the process stage fields on the entity.
Please see: [View:https://msdn.microsoft.com/en-us/library/dn481586.aspx:750:50]
"Manipulating process related attributes (such as ProcessId, StageId, and TraversedPath) on entities enabled for business process flows does not guarantee consistency of the business process flow state, and is not a supported scenario. The only exception to this is programmatically modifying the ProcessId attribute while creating an entity record to override the default application of the business process flow to the new record. More information: Apply business process flow while creating an entity record"
The processes stages are stored in the ProcessStageBase and the process stages part of the BFP Active path can be retrieved via RetrieveActivePathRequest.
These will be returned in the RetrieveActivePathResponse as part of the ProcessStages properties - https://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.retrieveactivepathresponse.aspx
You can use following code snippet to retrieve the data you are after:
// 1. Retrieve the Active Process Instance together with the ActiveStageId and also the unique name of the workflow
// The Workflow unique name will be needed at a later stage to, when updating the stage
RetrieveProcessInstancesRequest retrieveProcessInstancesRequest = new RetrieveProcessInstancesRequest
{
EntityId = entityId,
EntityLogicalName = "yourEntityLogicalName"
};
RetrieveProcessInstancesResponse retrieveProcessInstancesResponse =
(RetrieveProcessInstancesResponse)serviceProxy.Execute(retrieveProcessInstancesRequest);
Guid activeProcessInstaceId = new Guid(retrieveProcessInstancesResponse.Processes.Entities[0].Id.ToString());
//if you also want to get the workflow id - you can get it as well
EntityReference workflowReference =
(EntityReference)retrieveProcessInstancesResponse.Processes.Entities[0].Attributes["processid"];
Workflow instanceWorkflow = (Workflow)serviceProxy.Retrieve("workflow", workflowReference.Id, new ColumnSet(true));
// 2. Get the Active Path and the available stages that can be switched to in the BPF
RetrieveActivePathRequest retrieveActivePathRequest = new RetrieveActivePathRequest
{
ProcessInstanceId = activeProcessInstaceId
};
RetrieveActivePathResponse retrieveActivePathResponse =
(RetrieveActivePathResponse)serviceProxy.Execute(retrieveActivePathRequest);
Dictionary<String, Guid> processStages = new Dictionary<String, Guid>();
foreach(var processStage in retrieveActivePathResponse.ProcessStages.Entities)
{
processStages.Add(processStage["stagename"].ToString(), new Guid(processStage["processstageid"].ToString()));
}
Hope this helps,
Radu