What WorkflowUtility.ExecuteWorkflowCommandIfAvailable does?

This will be a short post about why the method above is tricky. As its name says ExecuteWorkflowCommandIfAvailable, but what “available” means in this context?

It means it checks if the user has rigths to execute the given workflow command even if you use SecurityDisabler, because Sitecore uses SecurityEnabler inside this method.

So the following code wont work if you are using it from out of Sitecore Context (e.g. a processor) because the current user is sitecore\Anonymous in that case.

using (new SecurityDisabler())
{
WorkflowUtility.ExecuteWorkflowCommandIfAvailable(item, commandItem, commentFields);
}

So instead of using SecurityDisabler what you can do in this case? Use UserSwitcher instead but be careful with this, read about it first. It is not a good practice in all cases.

using (new UserSwitcher("sitecore\yourDedicatedUser"))
{
WorkflowUtility.ExecuteWorkflowCommandIfAvailable(item, commandItem, commentFields);
}

If you don’t want to create a specific real user in Sitecore you can use virtual user which is maybe more clean, because you don’t need to setup a password and roles in Sitecore but you can create this temporary user in your processor.

var virtualUser = AuthenticationManager.BuildVirtualUser("sitecore\\myProcessorUser", false);
virtualUser.RuntimeSettings.IsAdministrator = true;
virtualUser.RuntimeSettings.Save();
using (new UserSwitcher(virtualUser))
{
WorkflowUtility.ExecuteWorkflowCommandIfAvailable(item, commandItem, commentFields);
}

I did not know that you can omit SecurityDisabler with SecurityEnabler, but good to know for the future.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s