Workflow
Set Item State and Executes actions in that state
public void MoveToStateAndExecuteActions(Item item, ID workflowStateId)
{
Sitecore.Workflows.IWorkflowProvider workflowProvider = Item.Database.WorkflowProvider;
Sitecore.Workflows.IWorkflow workflow = workflowProvider.GetWorkflow(item);
// if item is in any workflow
if (workflow != null)
{
using (new Sitecore.Data.Items.EditContext(item))
{
// update item's state to the new one
item[Sitecore.FieldIDs.WorkflowState] = workflowStateId.ToString();
}
Item stateItem = ItemManager.GetItem(workflowStateId,
Language.Current, Sitecore.Data.Version.Latest, item.Database, SecurityCheck.Disable);
// if there are any actions for the new state
if (!stateItem.HasChildren)
return;
WorkflowPipelineArgs workflowPipelineArgs = new WorkflowPipelineArgs(item, null, null);
// start executing the actions
Pipeline pipeline = Pipeline.Start(stateItem, workflowPipelineArgs);
if (pipeline == null)
return;
WorkflowCounters.ActionsExecuted.IncrementBy(pipeline.Processors.Count);
}
}
Thanks to this thread
Executing workflow command to change the workflow state
Thanks to this great post
If we want to mimic the Sitecore UI behavior and execute the command which will change the workflow state, we need to use WorkflowProvider to get an instance of the workflow assigned to the given item and call Execute method with a chosen command ID. This will fire all the actions which are defined under the command item node, change the state of the item and fire all the auto-actions defined below the new state item node:
public static WorkflowResult ExecuteCommand(Item item, string commandName, string comment)
{
IWorkflow workflow = item.Database.WorkflowProvider.GetWorkflow(item);
if (workflow == null)
{
return new WorkflowResult(false, "No workflow assigned to item");
}
WorkflowCommand command = workflow.GetCommands(item[FieldIDs.WorkflowState])
.FirstOrDefault(c => c.DisplayName == commandName);
if (command == null)
{
return new WorkflowResult(false, "Workflow command not found");
}
return workflow.Execute(command.CommandID, item, comment, false, new object[0]);
}