2
votes

If I create a Workflow from a template in code in Dynamics CRM, is it possible to change the values for the workflow step properties?

I have a custom workflow step, that is part of a workflow template, but for each workflow I create from this, I want to pass in different values to the step.

I'm creating the workflows from C# as part of a powershell cmdlet. I've tried creating the workflow from scratch with xaml but it's causing more problems that it solves.

I can create and retrieve the workflow with the following code, but I can't see anything to point me to the steps on the Workflow object I retrieve.

using (var proxy = auth.GetOrganizationProxy())
        {
            // This statement is required to enable early-bound type support.
            proxy.EnableProxyTypes();

            OrganizationServiceContext _orgContext = new OrganizationServiceContext(proxy);

            CreateWorkflowFromTemplateRequest request = new CreateWorkflowFromTemplateRequest()
            {
                WorkflowName = "(" + EntityLogicalName + ") Migrate Notes to SharePoint",
                WorkflowTemplateId = new Guid(ProcessTemplateId)
            };

            var response = (CreateWorkflowFromTemplateResponse)proxy.Execute(request);

            ColumnSet cols = new ColumnSet(true);
            Workflow newWorkflow = (Workflow)proxy.Retrieve(Workflow.EntityLogicalName, response.Id, cols);

            newWorkflow.PrimaryEntity = EntityLogicalName;
        }
1

1 Answers

1
votes

When archiving workflow XAML, then creating a new workflow from scratch with this xaml (with values replaced) I got an error, CRM thought the XAML was produced externally and failed to work, wouldn't let me delete the workflow, and it failed to run.

My solution was to create a workflow as a template, then in code, create a workflow from that template using a "CreateWorkflowFromTemplateRequest". This produces a workflow with the same base entity as the template, and the "CreateWorkflowFromTemplateResponse" contains this workflow's ID

I then looked this workflow up by ID, altered the base entity, replaced my values in it's XAML property and saved it as a new Workflow (with a new ID), then deleted the original workflow I created from the template.

Resulting in my code creating a new workflow, based on a template, but regarding a different entity.

You can't edit the entity of an existing workflow, hence the lookup, alter, re-save. I could probably have looked up the Template by name, altered it, but I am unsure how CRM handles templates vs workflows and chose to clone an actual workflow produced from the template.