HOW TO: Programmatically set/pass WorkflowContext from a Visual Studio workflow to a custom workflow action in SharePoint 2010

This post is a contribution from Himani Sharma, an engineer with the SharePoint Developer Support team.

Scenario:

You have a workflow custom action that you’d like to be used in SharePoint 2010 workflow.  This activity uses Microsoft.SharePoint.WorkflowActions.WorkflowContext to obtain WorkflowContext and hence use the workflow instance specific properties like ItemId, ListId, TaskListGuid, WorkflowInstanceId etc.,

Analysis:

In order to use this workflow custom action in SharePoint designer workflow, we create a custom workflow actions file.  The WorkflowContext parameter expected by the custom action is passed like this:

Excerpt from a sample file workflow actions file:

 <Parameters>
         <Parameter Name="__Context" Type="Microsoft.SharePoint.WorkflowActions.WorkflowContext,Microsoft.SharePoint.WorkflowActions" Direction="In" />
 </Parameters>

But how do we pass the WorkflowContext from within a Visual Studio workflow?

Here are the steps:

1. This is how the workflow context is defined in the workflow custom action class.

 #region workflow context
  
 public static DependencyProperty __ContextProperty = DependencyProperty.Register("__Context", typeof(WorkflowContext), typeof(ESPTaskActivity));
  
 public WorkflowContext __Context
 {
   get { return (WorkflowContext)GetValue(__ContextProperty); }
   set { SetValue(__ContextProperty, value); }
 }
  
 #endregion

2. This is how you can set or pass the value from a Visual Studio workflow that uses this workflow custom action.

image

a. Define a public variable within the workflow class file.

 public WorkflowContext wfContext { get; set; }

b. Set the value from within OnWorkflowActivated event in the workflow class file. NOTE: As long as you’ve access to SPWorkflowActivationProperties, you can set it from anywhere within the workflow.

 private void onWorkflowActivated1_Invoked(object sender, ExternalDataEventArgs e)
 {
   //Initialize workflowcontext using SPWorkflowActivationProperties
   wfContext.Initialize(workflowProperties);
             
   //initialize task properties.
   CustomTaskActivity1.__Context = wfContext;
 }

You are all set!  Hope this post was helpful.