Andy Neillans
Andy Neillans

Reputation: 368

How to execute workflows in code?

Scenario:

The code I have so far is:

Database db = Factory.GetDatabase("master");
if (Request.QueryString["_id"] != null)
{
  var itm = db.GetItem(new ID(Request.QueryString["_id"]));
  WorkflowCommand[] availableCommands = wf.GetCommands(itm.Fields["__Workflow state"].Value);   
  wf.Execute(Request.QueryString["command"], itm, "Testing working flow new screens", false, new object[] { }); // Execute the workflow step.
}

However, I get a Object not set to an instance error on the wf.Execute line - but with no meaningful stack trace or anything :(

I've put in the wf.GetCommands line just to check that things are actually where I expect them, and availableCommands is populated with a nice list of commands that exist.

I've checked the commandId is valid, and exists.

Itm is not null, and is the Content Item that the workflow is associated to (that I want the workflow to run in context with).

I've checked that the user context etc is valid, and there are no permission issues.

The only difference is that I am running this code within an .aspx page that is executing within sitecore - hopeever, I wouldn't have expected this to cause a problem unless there is a context item that isn't being set properly.

Upvotes: 1

Views: 1643

Answers (1)

nickwesselman
nickwesselman

Reputation: 6890

Workflow needs to be run within a SiteContext that has a ContentDatabase and workflow enabled. The easiest way to do this within your site is to use a SiteContextSwitcher to change to the "shell" site.

using (new SiteContextSwitcher(SiteContextFactory.GetSiteContext("shell")))
{
    wf.Execute(Request.QueryString["command"], itm, "Testing working flow new screens", false, new object[] { }); // Execute the workflow step.
}

An example of this can be found within the code for the WeBlog Sitecore module.

http://svn.sitecore.net/WeBlog/Trunk/Website/Pipelines/CreateComment/WorkflowSubmit.cs

Upvotes: 4

Related Questions