Search code examples
dynamics-crm

Access ProcessId and StageId in Dynamics CRM Plugin


I'm writing a plugin on Campaign which used a Business Process Flow. The fields ProcessId and StageId which are created by the Business Process Flow in Campaign Entity. I need to retrieve these values for a record in my plugin.

They don't appear in the Plugin Registration Tool's Step Image. They don't even appear in CRM workflows were I can populate them in some other field.

Is there a good alternative on how I can achieve this?


Solution

  • You should be able to retrieve this by passing the correct input parameters to a workflow activity in this business process flow.

    1) if you have these string inputs:

    [RequiredArgument]
    [Input("Process Name")]
    public InArgument Process { get; set; }
    
    [RequiredArgument]
    [Input("Process Stage Name")]
    public InArgument ProcessStage { get; set; }
    

    2) Execute code Get Process:

    using (var _context= new OrganizationServiceContext(service))
    {   
       // Get the processid using the name provided
       var process = (from p in _context.CreateQuery()
                      where
                      p.Name == Process.Get(executionContext)
                      &&
                      p.StateCode == WorkflowState.Activated
                      select new Workflow
                      {WorkflowId = p.WorkflowId}
                     ).FirstOrDefault();
       if (process==null)
           throw new InvalidPluginExecutionException(string.Format("Process '{0}' not found",Process.Get(executionContext)));
    

    Get the stage id using the name provided

    var stage = (from s in _context.CreateQuery()
                 where
                 s.StageName == ProcessStage.Get(executionContext)
                 &&
                 s.ProcessId.Id == process.WorkflowId
                 select new ProcessStage
                 {ProcessStageId = s.ProcessStageId}
                ).FirstOrDefault();
    if (stage == null)
        throw new InvalidPluginExecutionException(string.Format("Stage '{0}' not found", Process.Get(executionContext)));
    

    You can now Change Update the stage with your values retrieved ...

    Entity uStage = new Entity(context.PrimaryEntityName);
    uStage.Id = context.PrimaryEntityId;      //
    uStage["stageid"] = stage.ProcessStageId; //retrieved stage 
    uStage["processid"] = process.WorkflowId; //process id