SharePoint 2007 and the WorkFlow Foundation: Integrating Divergent Worlds
Introduction
Windows SharePoint Services (WSS) 2007 is the first Microsoft server that has native support for the Windows WorkFlow Foundation (WF). The integration between WF and the 2007 release of SharePoint provides an infrastructure that drives processes around SharePoint's strong suit: collaboration and sharing of information. This release focuses on document-centric workflows; procedures that a particular document goes through in its lifecycle: be that reviewing, editing or approval. In the new edition, it's possible to attach and run a process directly in a SharePoint document or list item. Additionally, the WorkFlows within SharePoint spotlight "human-based" endeavors; tasks driven by human interaction as opposed to static automated programmatic steps.
The Workflows within Sharepoint spotlight “human-based endeavors; task driven by human interaction
To examine the process, we will follow a report that needs to be approved before publication: a document containing a report can automatically generate an Approval workflow or the author can initialize it manually and select the individuals who need to approve it; the workflow assigns approval tasks to those people and they are notified of their tasks via email; they can assign their choice by clicking 'approve' or 'reject' on a special form provided by the workflow; when all approvals are completed, the author receives notification that the report has been approved (or rejected) and it is ready for publication.
SharePoint Server 2007 provides various out-of-the-box WorkFlows requiring no additional attention before using. These workflows include Approval (routes a document for approval), Collect Feedback (routes a document for review), Collect Signatures (gathers signatures), Disposition Approval (manages document expiration and retention), Group Approval (similar to the Approval workflow, but designed specifically for East Asian Markets), Translation Management (manages document translation), and Issue Tracking (manages the issue tracking process by creating tasks for Active issues assigned to users).
Many processes are very specific to an individual company's needs; therefore the WorkFlow Foundation provides an extensible infrastructure that can be used to create sophisticated workflows. WF provides a powerful platform with a unified programming model and works with familiar developmental tools such as Visual Studio 2005. Less powerful SharePoint workflows can also be created with SharePoint Designer (formally FrontPage), a web design and customization tool which allows users to create workflows without writing any code.
The basics; using the right tools
A standard Visual Studio installation lacks the necessary tools to work with the WorkFlow Foundation so to put things in motion it's necessary to install the "Visual Studio 2005 extensions for .NET Framework 3.0 (Windows Workflow Foundation)" (http://www.microsoft.com/downloads/details.aspx?familyid=5D61409E-1FA3-48CF-8023-E8F38E709BA6&displaylang=en). The Extension provides the required references to the Foundation assemblies, the essential Activities needed, as well as the WorkFlow designer within Visual Studio and a number of project templates. Keep in mind that it is obligatory to install DotNet FrameWork 3.0 (http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=10CC340B-F857-4A14-83F5-25634C3BF043) as a prerequisite to working with WF.
There is a Visual Studio 2005 Extension which is compatible with the WorkFlow Foundation to work with SharePoint but, at the time of writing, it was in a Beta stage ("Workflow Developer Starter Kit for Windows SharePoint Services 3.0", http://www.microsoft.com/downloads/details.aspx?familyid=5ddf902d-95b1-4640-b9e4-45440dc388d9&displaylang=en). Note that this Extension is not required if developing workflows for SharePoint (the Extension makes a new template to initialize a project).
To create a WorkFlow for SharePoint, the first step is craft a new project in Visual Studio 2005, based in the "Sequential Workflow Library" (or in the "State Machine Workflow Library", if you are making a State Machine Workflow), and assign it a name. Visual Studio will generate the necessary code and configuration files. Add a reference to "Windows SharePoint Services" (Microsoft.SharePoint.dll) and, if you need to work with Microsoft Office SharePoint Server, also a reference to "Microsoft Office SharePoint Server component" (microsoft.sharepoint.portal.dll). In this way, there are references to the Object Model of SharePoint, opening the door to interacting with it. Although it's not compulsory, it simplifies coding if you write directives to the next Namespaces in the code behind file; for example:
using Microsoft.SharePoint;
using Microsoft.SharePoint.Workflow;
using Microsoft.SharePoint.WorkflowActions;
Finally, we need to add an Activity to the Visual Studio Toolbox: using the context menu (right click into the Toolbox), select "Choose items" and in the ".NET Framework Components" tab, check the "OnWorkflowActivated" Activity to activate it in the Toolbox. This activity is indispensable for running WorkFlows in SharePoint.
As an example, we will build a simple WorkFlow that illustrates the lifecycle of a WF within SharePoint: initializing the workflow, transporting information from SharePoint, processing it and feeding it back to WSS. We initialize the process by creating the WorkFlow using the WorkFlow Designer in Visual Studio. The opening activity is always the "OnWorkflowActivated" for WorkFlows in SharePoint; then install a "While" activity with a "Code Activity" inside to process the information, and finally, another "Code Activity" to return information to SharePoint. Bear in mind that this is not a functional WorkFlow to be used in a business application, but a demonstration of each part of the interaction between WF and SharePoint.

Fig. 1. The example WorkFlow in the Visual Studio WorkFlow Designer
Extracting information from the external world: SharePoint to the WorkFlow
The first stage in the codification of the WorkFlow involves defining some variables in the code behind page to be used later.
public SPWorkflowActivationProperties FlowProperties
= new SPWorkflowActivationProperties();
private string _myDocument = string.Empty;
private int _CounterLetters = 0;
private int _CounterVowels = 0;
The activation properties will be stored in the variable "FlowProperties" and extra global variables for the internal work are defined.
As you can see in figure 1, each activity has a red mark at the right corner indicating that the configuration is incomplete. Returning to the Designer, it is now possible to configure the "OnWorkflowActivated" activity using the defined variables. In the Properties panel, create the subsequent configurations:
- Correlation Token: Choose a distinctive name ("FlowToken", for example); after the name configuration, a plus symbol will appear where the "OwnerActivityName" can be selected ("Workflow1" in the example)
- Click the ellipse button of "WorkFlowProperties" and, in the new window, choose the code defined previously in "FlowProperties"

Fig. 2: Configuration panel of the "OnWorkflowActivated" activity
If the configuration parameters are correct, the red mark in the activity will disappear.
As with all Visual Studio projects, if you double click on an activity, Visual Studio will fashion the correspondent Event Handler. After a double click on the "OnWorkflowActivated" activity, Visual Studio will write the Event Handler method automatically and the user writes the correspondent logic inside:
private void onWorkflowActivated1_Invoked(
object sender, ExternalDataEventArgs e)
{
SPListItem myActivator = FlowProperties.Item;
_myDocument = myActivator.Name.ToLower();
_CounterLetters = _myDocument.Length;
}
Using this activity, all the relevant information from the SharePoint context can be found; the flow is initialized by an element of a List (of the SharePoint type "SPListITem"), and from the object that contains the element information, one can find its name (located in the variable "_myDocument") and the number of letters of the document name (stored in the variable "_CounterLetters").
In the object "FlowProperties" it is possible to find all the necessary information from the SharePoint context. The SharePoint Web Object, Site Object and List Object are present, as well as the Task List that generates 'alerts' for other users: everything that can be used for later processing is present in the variable.
Processing the information: the WorkFlow in action
Once the information from SharePoint has been captured, the next step is to process it. With a double click on the activity inside the While loop, Visual Studio generates the correspondent Event Handler, where the business logic can be written:
private void codeActivity1_ExecuteCode(
object sender, EventArgs e)
{
_CounterLetters--;
char[] AllVowels = new char[]
{ 'a', 'e', 'i', 'o', 'u' };
Array.Sort(AllVowels);
if (Array.BinarySearch(AllVowels,
_myDocument[_CounterLetters]) >= 0)
_CounterVowels++;
}
The procedure for the example will count the number of vowels in the name of the document. The algorithm is not optimal for a large number of instances of the WorkFlow, but sufficient for the example (the method "IndexOf" of the array may be a more effective way to calculate the number of vowels).
At this point it is important to construct the configuration of the "While" activity. From the Properties panel, compose the next configurations:
- Condition: Choose "Declarative Rule Condition"
- ConditionName (expanding the Condition property): Give a recognizable name
- Expression: In the "Rule Condition Editor", which can be activated using the ellipse button, write the condition necessary to remain in the loop (for the example, "this._CounterLetters > 0": as long as not all the letters have been examinate, the loop statement will stay turning around)
This step is essential to the overall WorkFlow as it implements the flow's logic. In the example, only one code activity inside a loop activity has been used, but in an actual situation it will be composed of many different kinds of activities.
Taking information back to the external world: from the WorkFlow to SharePoint
The second Code activity in the example controls returning the processed information from the WorkFlow engine to the SharePoint context. Using the Event Handler of the activity, it is possible to write information back into SharePoint:
private void codeActivity2_ExecuteCode(
object sender, EventArgs e)
{
SPListItem myActivator = FlowProperties.Item;
myActivator["Title"] = _myDocument + " has " +
_CounterVowels.ToString() + " vowels";
myActivator.Update();
}
Initially, the code crafts an object of the type Microsoft.SharePoint.SPListItem calling the Item method of the SharePoint properties, and then changes the title of the element that has begun the WorkFlow, appending a string and the calculated number of vowels in the name of the document.
Because the Workflow has access to the complete context of SharePoint, it can perform internally any authorized modification: write to Lists and Libraries, change properties and create, edit and delete elements. Everything, that is, within the authorization and authentication context of the user who has initialized the WorkFlow.
An additional method of interaction with users is to employ ASP.NET forms that you apply with your Windows SharePoint Services workflow. These forms are then displayed in the SharePoint user interface at the appropriate stages in the workflow. There can be four types of forms:
- Association: This form will be displayed to administrators when they first add or associate the WorkFlow with a particular List or document Library
- Initialization: A user starting the WorkFlow manually will be confronted with this form; at this point the user may override or append the association parameters
- Modification: The form that enables users to alter the WorkFlow while it is running
- Task: Assigns jobs to the flow participants
Deploying and using the WorkFlow
Because the assembly of the WorkFlow generated by the compilation in Visual Studio must be installed in the Global Assembly Cache (GAC), it needs to be signed. You can use the standard Visual Studio 2005 infrastructure to sign it or the "sn" tool with the parameter "-T". After the compilation is complete, you can use the "gacutil" tool to install the assembly in the GAC.
Workflows are deployed in SharePoint using Features
WorkFlows are deployed in SharePoint using Features. As a new paradigm in SharePoint 2007, Features was created as a way to encapsulate solutions and functionality for ease of deployment. Additionally, it provides a mechanism by which developers can package the files needed for a solution (as a WorkFlow) intended for distribution.
Each Feature must include a WorkFlow definition template (a XML file) that contains the information SharePoint requires to instantiate and run the WorkFlow, as well as a Feature definition (also a XML file) with information concerning the Feature. To install the example WorkFlow, create a new Feature.xml file with the next code:
Title="JupiterMediaWorkFlow"
Description="Example WorkFlow"
Version="12.0.0.0"
Scope="Site"
xmlns="http://schemas.microsoft.com/sharepoint/">
The "Feature Id" parameter is a Windows GUID that can be fashioned with the GUID Generator component included in Visual Studio. A second file called Flow.xml, with the next code, defines the WorkFlow for SharePoint:
xmlns="http://schemas.microsoft.com/sharepoint/">
Name="JupiterMediaWorkFlow"
Description="Example WorkFlow"
Id="B2196C5B-1579-4bb7-B23E-01DC6A898ABC"
CodeBesideClass="JupiterMediaWF.Workflow1"
CodeBesideAssembly="JupiterMediaWF,
Version=1.0.0.0, Culture=neutral,
PublicKeyToken=99ca3967f3ef49e3">
_layouts/WrkStat.aspx
Copy both files to a new directory under the hive:
C:\Program Files\Common Files\Microsoft Shared\
web server extensions\12\TEMPLATE\FEATURES\JupiterWF
And install and activate the WorkFlow using the SharePoint Administrators tool "stsadm", with the following syntax
- To install the WorkFlow:
C:\Documents and Settings\Administrator>
"C:\Program Files\Common Files\Microsoft Shared\
web server extensions\12\BIN\STSADM.EXE"
-o installfeature -name JupiterWF -force
- To activate the WorkFlow:
C:\Documents and Settings\Administrator>
"C:\Program Files\Common Files\Microsoft Shared\
web server extensions\12\BIN\STSADM.EXE"
-o activatefeature -name JupiterWF -force
At this point it is necessary to link the WorkFlow with the document Library where it will operate. From the "Document Library Settings" page, proceed to "Workflow Settings", and using the page "Add a Workflow", select the workflow from the ComboBox, give it a name, decide on a List to be used for its tasks and another one for the History (an existing list can be used, or a new one can be created) and select the start options (can be started manually or automatically):

Fig. 3: Set up of the Workflow in a Document Library
After creating a new document in the Library, the user can utilize the context menu of the element to proceed to the page where one can select and activate the WorkFlow:

Fig. 4: Activating a WorkFlow for a document
Multiple WorkFlows can run simultaneously on the same item, but only one instance of a specific WorkFlow can run on a specific item at any given time. At the end of the working process of the flow, the result can be seen in the properties page of the document:

Fig. 5: Properties of the document after completing the WorkFlow
Note that in the properties page the WorkFlow has made a count of the document's vowels in its name and has altered its Title to include the counter.
Conclusion: Integrating divergent worlds
The interaction between the Windows WorkFlow Foundation and Microsoft SharePoint 2007 offers an excellent way to attach business processes to items, and provides the opportunity to control almost any aspect of its lifecycle and user interaction within SharePoint. WorkFlows can be as simple or complex as your business processes require, and can be initiated by users or automatically based on some event.
The architecture of the Foundation and its implementation in SharePoint allows for substantial flexibility to make changes in the business layers. It provides the option of reuse without having to alter the Portal's deep infrastructure and unlocks new prospects for software architects, developers and system administrators.
Sources
De sources die bij dit artikel horen kun je downloaden via Velez_SharepointAnd_WFF_SRC.zip.