SharePoint WorkFlow Basics

Many developers are looking for information related to workflow and especially for SharePoint workflow. This article provides details about the SharePoint workflow, with the basics about workflow also. Later in this article we show how you can create a workflow in Visual Studio and deploy to your SharePoint site.

Windows Workflow Foundation is a new programming framework introduced in .NET 3.0 for creating reactive programs. A reactive program typically represents a set of procedures or instructions used to capture and automate a specific business process. For example, the processing of an insurance claim or the approval of a document such as purchase order. Reactive programs have a common characteristic. Once they start, they can't immediately run to completion. Instead, they run up until a point at which the are forced to pause in the middle of their exection and wait. They must wait for extra input from a human being or for some other external event to occur. The pause of a reactive program could be a matter of days or event months until it is able to resume its work. The reactive program must provide some listening mechanism so that it can wake up and continue its execution at the point where it left off when the desired event occures or input arrives.

     At a high level, developing a reactive program to catch business process involves managing the state of whatever data are involved and writing the control-of-flow logic. For example, a reactive program for purchase order approval might need to track the purchase order document name, approver, status of approval, due date and other data as well. When a user starts an approval process, the reactive program must show how send a notification to the approver about the event. Finally, the reactive program needs to provide some sort of mechanism so that it can react to the event when the approver either approves or rejects the document.

     Due to the episodic nature of a reactive program that automates long-running tasks, such a document approval, it is impractical to track its data in memory. It is necessary to write down the data associated with document approvals into some persistent store, such as a database. This is a very important and critical issue of reactive programs because without persistance, the approval data would be lost in the case of an application crash or machine reboot.

Windows Framework Foundation Architecture
          Microsoft created the Windows Workflow Foundation to provide a development platform and set of developer tools specifically for building reactive programs. In WF technology or terminology, these reactive programs are called WF programs. It is important that these WF programs run in a special environment known as the WF runtime., which is included in .NET 3.0 framework as one of its important parts.

          A WF program is a class definition that is usually designed and implemented to automate a business process. Each time you initiate a WF program, you are creating a workflow instance. You add control-of-logic to your WF program to move each workflow instance through its life cycle from step to step until it finishes or is terminated. Though the life cycle of a workflow instance are periods of inactivity in which its state must be serialized and stored out into some form of durable storage. As another step begins, this state must be restored so that a workflow instance can be deserialized back to its previous form. A WF runtime deals with the persistence and reloading of workflow instance in a manner that is transparent to your WF program.

         The CLR provides the plumbing needed to create objects in memory. However, these CLR objects are bound to the lifetime of the hosting process and disappear once the process has is shut down or recycled. The WF extends the CLR by adding support to persist and recreate CLR objects across process boundries and even across machine boundries as required within Web farm environment.

         The WF actually does more than just saving and reloading the state of the workflow instances. The WF must also provide a way to remember how much each instance processes within its life cycle. When any action occures and a new step begins, the WF runtime must determine not only which workflow instance to load, but also where to resume execution within the control-of-flow logic. The WF deals these scheduling by using atomic executable statements known as activities.

         Activities are the building bricks that developers use to construct WF programs. We can consider each activity as an atomic and reusable set of instructions that represents a single unit of work. As a developer building WF programs that target WSS and Microsoft Office SharePoint Server (MOSS), we can also reuse SharePoint-specific activities that are part of the WSS Activity Library. An activity is a class that inherits from the Activity class defined within the System.Workflow.ComponentModel assembly. The overridable method named Execute which is overridden by activity authors to give their behavior they require. The Execute method of an activity is always called by the WF runtime and never by programmers directly.

        Like ASP.NET server controls, activities are black boxes of reusable code that expose properties and events. The consumer of an activity can simply drag and drop it on a design surface within Visual Studio. The consumer of activity also generates event handlers for activities and write code behind these event handlers. In one aspecht, an activity is fundamentally different from an ASP.NET controls is that it is resumable. When the WF runtime loads a workflow instance into memory to begin another step, certain activities within the WF program provide possible points of re-entry into the flow of executable logic. Another important aspect of the WF programming model is that some types of activities can have child activities, which are known as composite activities.

There is a class named CompositeActivity in WF programming model which inherits from Activity. This class has an Activities property that exposes a collection used to add and track child activities. Each composite activity manages the execution of its child activities, which allows composite activities to provide control-of-flow constructs within a WF program. An example of composite activity is a Replicator activity, that take a flow of one of more child activities and replicate the flow so that it can be executed multiple times with different parameters. For example, imagine that you have created a flow of activities to assign a task to a user who needs to approve a document and then to wait on that user to either approve or reject the document. However, what would you do if you need three different users to approve a document in a particular business scenario? You can add the flow of approval-related activities withing the Replicator activity and configure it to execute the flow three different times.


Creating WF Programs
     A WF program is a composite activity that contains child activities. The WF program's child activities can also be composite activities with children of their own and so on.

     Every activity within a WF program has a Name property, which represents important metadata that the WF runtime uses to identify continuation points in WF program's logic. This Name property can't be changed at run time. Every activity has a Parent property that references the composite acitivity in which it is contained. The root activity that represents the WF program itself has Parent proeprty value equal to null.

     The WF programming model provides support for creating two different styles of WF programs. The first style is a sequential WF program that typically has several predicable paths of execution that can be modeled in the form of a flowchart, as shown on the below image titled "Sequential WF Program". When you create a sequential WF program to model a business process, you can commonly use composite activities such as While, IfElse and Replicator to design the control of flow and can get conditional branching.

When a business process has many possible paths of execution then the sequential WF programs are difficult to model. At that time a state machine WF program models as shown in the above image titled "State Machine WF Program". A state macine WF program models the different states that a business process goes through on its way toward completion.

The WF programming model provides a base class for each type of WF program. The SequentialWorkflowActivity class is used to create sequential WF programs, while the StateMachineWorkflowActivity class is used to create state machine WF program.

Workflow Designer in Visual Studio

     After discussing the concepts of composing the WF program by using activities, let us see how it's actually done. The first thing you need the .NET 3.0 Framework installed on your development machine so that the WF runtime and WF assembly libraries are present. As the WSS 3.0 depends on the WF, so if you have already successfully installed WSS 3.0, then the WF is already present on the machine. You also need to install Visual Studio Extensions for Windows Workflow Foundation. This is the add-in created by the WF team and it installs the workflow designer into Visual Studio. As the add-in has been installed, you should see everal new Visual Studio project types, such as Sequential Workflow Library and State Machine Workflow Library for creating WF programs. When you work with workflow designer it is helpful for you to create small test projects by using Visual Studio project template named Sequential Workflow Console Application. Doing this makes it possible for you to create a WF program and experience using the workflow designer as shown in the below image.

The WF programming model allows for activities with data-bound properties. The main idea behind data-bound properties is that they facilitate the declarative flow of data across activities. We will see about this later in the article while implementing the Custom Workflow Templates for document approval process in WSS.

WF Runtime

It is important to remember that the WF doesn't provide an application server or any type of hosting process. Instead, the WF is a general purpose runtime environment that can be loaded into the process for any application you would like. The following code snippet shows you an example of firing up WF runtime in console application and then uses the workflow named Workflow1 to start a workflow instance.

using System;
using System.Workflow.Runtime;
using System.Workflow.Runtime.Hosting;

namespace HelloWorkflowConsoleApplication {
  
class Program {
    
static void Main() {

      
// start WF runtime
      WorkflowRuntime wfRuntime =
new WorkflowRuntime();
      wfRuntime.StartRuntime();

      
// create and start workflow instance
      WorkflowInstance workflowInstance1;
      workflowInstance1 = wfRuntime.CreateWorkflow(typeof(Workflow1));
       workflowInstance1.
Start();

      
// pause until test workflow instance completes
    
Console.ReadLine();

      
// stop WF runtime
      wfRuntime.StopRuntime();
       wfRuntime.Dispose();
    }
  }
}

The preceding code is easy to understand. A hosting application simply needs to start the runtime and then create and start workflow instance from any WF program. Though this process is relatively simple to write and test, this console application doesn't provide support for the most required and valuable aspect of WF - the capability to save the workflow instance into durable storage so that it's not tied to the lifetime of the hosting process. An application implemented to use the WF must often interact with an external entity, like backend database server to save the serialized data for its workflow instances. The WF was designed so that all these types of interaction with external entities is delegated to WF runtime services. The main aspect of this design is that each WF runtime service is modeled using an abstract class such that different developers and companies can create their own pluggable versions when required.

Let's discuss a workflow instance that is created to automate a document approval process for a document within a WSS site. When it's time to persist the serialized data for the workflow it obviousliy saved to the WSS content database. The WF programming model defines an abstract base class ned WorkflowPersistanceService that defines a set of abstract methods called by the WF runtime whant it's time to load or save workflow instance state. The WSS team created a class named SPWinOePersistanceService that inherits from WorkflowPersistanceService and implements the methods requird to load and save workflow instance from the content database. The WSS runtime also provides the initialization logic required within the IIS worker process to load and start up the WF runtime and initialize it by using the SPWinOePersistanceService class as a WF runtime service. The below image shows the working of WSS WF system.

The above discussion concludes the brief introduction to the WF. Now let's move ahead and begin discussion of the layers that WSS and MOSS add on the top of WF.

SharePoint Workflows

     When the Microsoft Office team began to integrate WF support into WSS and MOSS, their primary design goal was to attach business logic to documents and list items using WF programs. Another critical design goal was to add a human dimension of responsibility and accountability because, many business processes are reliant on humans and their actions. For example, to provide input in the form of an approval, a signature or feedback. So, it was important to add support so that WF programs could assign tasks to users who were responsible for driving the business processes being automated. It is also important for users and their organizations to have access to information about the status of a business process that was being automated by a workflow instance. So, the the idea of log entries in to a workflow history list came up that would keep users up to date on workflow status. When the WF support was integrated in WSS, the importance of site owners and users to be able to administrate and run WF programs without involvement from the IT department was also considered. WSS made many other aspects of administration within a site collection accessible to users and it was essetianl for the Microsoft Office team to make the administration of WF program equally accessible. Microsoft Office team had taken care  for developers and their need to build custom WF programs which are targetd to SharePoint. The final biggest design goal was to provide several valuable out-of-box Wf programs to automate common business processes, such as document approval and signature collection. However, majority of out-of-the-box workflows created by the Microsoft Office team are included with MOSS and not with WSS.

SharePoint Workflow Fundamentals

WSS extends the WF by introducing the concept of a workflow template. The main purpose of the workflow template is to integrate WF programs into WSS so that they can be installed, configured and parameterized for use. A workflow template is created by adding a Workflow element to a feature that is scoped to the level of the site collection. The workflow definition must point to a specific WF program and can optionally contain reference to one or more input forms for additional information from users. When deploying the workflow template, you must first intall the assembly DLL containing the WF program in the Global Assembly Cache (GAC). Next, install the featuer that defines the workflow temlate as you would install any other feature with WSS. Finally, activate the feature within any site collection in which you want to use that workflow template.

     WSS does not allow you to run workflow template directly on any list items, rather you must need to create a middle layer known as workflow association. A workflow association is a named set of parameterization data that is userd to bind a workflow template to a specific list.

     Once the feature with a workflow template is activated within the current site collection, a privileged user, such as the site or list owner, creates a new workflow association on any list or document library. This can be done by clicking the Workflow settings link on the List Settings page to navigate to a standard application page named AddWrkfl.aspx that’s used to create a workflow association, as shown in the below image.

A primary function of workflow association is to hold parameterization data for the workflow template that is used to initialize workflow instances. You can create for one specific list or document library in WSS site two different workflow associations from the same workflow template and parameterize them in different ways.

WSS extens the WF with a human dimension by providing every workflow instance with access to a workflow task list and workflow history list. The workflow task list allows workflow instance to assign tasks to users involved in different business process. The workflow history list allows workflow instances to log their actions so that uses can know their status. When a user creates a new workflow association through the standard WSS UI, that user is given a choice of selecting an existing task list / history list or to create new ones. The key requirement is that any workflow association must have a task list and a history list that are accessible to WF programs and their users. A workflow association can also be created on content type that exists within the Content Type Gallery for the current site. You can also create a workflow association for one of the content types defined within a list as well.

In summary, there are three different levels at which you can create a workflow assocation:

  • At the level of a list or document library

  • At the level of a content type defined at site scope

  • At the level of a content type defined at list scope

Initiating Workflow Instances on Items and Documents

Once the association of workflow is created, you an then begin to create a workflow intance that represents a running instance of a WF program. Each workflow instance must be associated with one specific list item or document. When a privileged user creates a workflow association, this user configures how workflow instances should be started. A user has two options which are 1. Automatically start a workflow instance anytime a new item or document is created and 2. Users are given the ability to start workflow instance on demand through the standard WSS user interface.

WSS provides standard elements within the UI to give users the ability to initiate and manage workflow instances as well as to see their status. The workflow menu item [below image] in the standard ECB menu for list items and documents, provies uses with the ability to navigate to an application page named workflow.aspx that allows a user to see, initiate and manage workflow instances for a specific list item or document.

A view of workflow.aspx is show in the blow image. As you can see, this page provides a builtin facility in WSS that displays the workflow associations available to initiate new workflow instance. This page lists an aggregation of the workflow associations that are created on the list as well as on the content type with the current item. The page also displays a list of workflow instances that are still running as well as those which have completed. The page also displays the list of history of a particular workflow instance.

WSS displays the Workflow Status page named WrkStat.aspx when uses want to drill down and examine the history of a particular workflow instance. This page is shown as below.

Workflow Input Forms

Now that we have seen the high-level concepts involved with workflow templates, workflow assocations, and workflow instances, so let's have look at workflow input forms. Developers can design and implement a custom workflow template that interacts with uses to solicit data to parameterize workflow associations and workflow instance using these input forms.

     When you design a new workflow template, you can create four different types of input forms which are as follows. You can add any one of these form types to a workflow template and omit other three.

    A custom workflow association form enables the developer to prompt the user for parameterization data when a new workflow association is created. This form is presented as the final step to the user when creating a workflow association. This form is also used by the users who want to make modifications to parameterization data within an existing workflow association.

A custom workflow initiation form allows the developer to prompt the user for parameterization data when a new workflow instance is created from a workflow association. These forms are used only when it is allowed to user to craete workflow instance manually. For automatic workflow instance creation, these forms are not likely to be prompted to users.

Once the workflow has been started there might be a need for the user to change some of its proeprties. The workflow modification form is intended for this purpose. A developer can add a link to the Windows Status page to navigate to the modification form for a particular workflow instance.

     Each workflow assocation is configured with a task list that makes it possible for workflow instance to create tasks and assign them to he users. WSS supplies a special content type named WorkflowTask with an ID of 0x010801. So if you create your own custom content type, you must inherit it from the standard WorkflowTask content type. One advantage of creating a custom content type for workflow tasks is that you can add extra fields apart from provided standard WorkflowTask content type. Sencond advantage is that you can create custom Task Edit Form. This allows the developer to take over the user experience when a user need to edit a task.

Developing Custom Workflow Templates

Now let's see how to create a custom workflow template for WSS and MOSS by using Visual Studio 2008. As you will see you can use the workflow designer within Visual Studio to develop a WF program for each workflow template you want to implemente. However, the project for a custom workflow template contains other source files, such as Collaborative Application Markup Language (CAML)-based XML files, to define the project feature that will be used to deploy the workflow template.

Once you successfully install WSS 3.0 on your development workstation, you already have all of the runtime support required to run workflows within WSS sites because installation of the .NET 3.0 framework is a prerequisite to installing WSS 3.0.

As mentioned earlier, you need to install the Visual Studio Extensions for Windows Workflow Foundation before you begin to develop custom WF programs. This is the add-in created by the WF team, and it installs the workflow designer to Visual Studio. You can use this workflow designer to create WF programs whether your development efforts are targeting WSS or not.

Once you install the Visual Studio Extensions for Windows Workflow Foundation, your next step is to install one of the workflow starter kits created by the Microsoft Office team to assist with creating SharePoint-targeted workflow templates. Which SDK and workflow starter kit you download depends on whether you are developing workflow templates for WSS or for MOSS. The following items are what you need to consider.

If you want to develop custom workflow templates that run in a WSS environment whether MOSS is installed or not, you should download the Windows SharePoint Services 3.0: Software Development Kit (SDK), which includes the Workflow Developer Starter Kit. This SDK contains two Visual Studio Project Templates for WSS-targeted WF programs titled Sequential Workflow Library and State Machine Workflow Library. In addition to these two project templates, the SDK also includes a single sample project named ASPXCollectFeedback, which demonstrates how to build a custom workflow template that includes workflow input forms built using .aspx pages
.

Creating the "SimpleWorkflow" Workflow Template

At this point, I assume that you have already installed the Visual Studio Extensions for Windows Workflow Foundation as well as the WSS SDK that includes the Workflow Developer Starter Kit. During this initial walkthrough, we will follow the guidelines for creating a classic Simple Workflow sample.

Open the Visual Studio 2005 and create new project. In the  New Project dialog box select the SharePoint folder under the Visual C# node. Within the SharePoint folder, you should see two Visual Studio project templates named Sequential Workflow Library and State Machine Workflow Library. In this walk-through, we are going to create a new C# project named SampleWorkflow by using the Sequential Workflow Library project template.

Once you create a new Visual Studio project based on the SharePoint Sequential Workflow Library project template, you are provided with several different source files as a starting point. These source files include feature.xml, workflow.xml, install.bat, Workflow1.cs, and Workflow1.designer.cs, as shown in below image.

The two files named feature.xml and workflow.xml are important when it’s time to deploy your workflow template. These two files are used to define a feature that makes it possible to install the workflow template so that it is recognized by WSS. The provided install.bat file contains command-line instructions to copy the required source files into the TEMPLATE directory of WSS and install the feature containing the workflow template by using the stsadm.exe utility.

The
two files Workflow1.cs and Workflow1.designer.cs are used together to define the WF program that is at the heart of your workflow template. This WF program is named as Workflow1. You can see that it inherits from the standard base class named SequentialWorkflowActivity from the WF programming model. Also note that Workflow1 is defined as a partial class that is spread out across both Workflow1.cs and Workflow1.designer.cs.

As the author of a custom workflow template, you are required to work with WF program files, such as Workflow1.cs, in both Designer view and Code view. When you are working in Designer view, the WF workflow designer provides you with the convenience of dragging and dropping activities from the Toolbox onto the design surface of Workflow1.cs, which is how you compose the flow of activities for your WF program. Designer view also makes it possible to modify an activity by selecting it and then modifying its properties using a standard property sheet.

Let's start working on Workflow1.cs to begin development of a WF program. You should start by double-clicking Workflow1.cs within the project explorer, which opens Workflow1.cs in Designer view as shown in the above image.

Working with Activities

When you open Workflow1.cs in Designer view, you notice that it already contains an existing activity named onWorkflowActivated1 that was created using the onWorkflowActivated activity type. This is an important requirement for any WF program targeting WSS or MOSS. More specifically, the first activity within the WF program running in WSS must be of the OnWorkflowActivated activity type. For this reason, you should never remove the activity instance named onWorkflowActivated1, nor should you add any other activities in front of it.

Below is the default code generated by the project template. The class named Workflow1 is defined as a partial class because the other half of the class definition for Workflow1 exists within Workflow1.designer.cs.

// using statements omitted for clarity
namespace SimpleWorkflow {
  
public sealed partial class Workflow1 : SequentialWorkflowActivity {
    
public Workflow1() {
      InitializeComponent();
    }
    
public Guid workflowId = default(System.Guid);
    
public SPWorkflowActivationProperties workflowProperties;
    workflowProperties =
new SPWorkflowActivationProperties();
  }
}


The public fields workflowId and workflowProperties need to be initialized by the OnWorkflowActivated activity whenever a new workflow instance is created from the WF program named Workflow1. The Visual Studio project template that you used to create the current project has already added what is needed to initialize the workflowProperties field.

Initialization of the workflowProperties field is accomplished through data binding. The activity named onWorkflowActivated1 contains a data-binding–enabled property named WorkflowProperties. While in Designer view, select onWorkflowActivated1 and see the property named WorkflowProperties in the Visual Studio property grid. You should be able to verify that the value of this property is preconfigured with the following property value, which constitutes a data-binding expression that is evaluated at run time.

Activity=Workflow1, Path=workflowProperties

As mentioned earlier, the entire idea behind data binding within a WF program is to facilitate the declarative flow of data across activities. In this case, the WorkflowProperties property of the activity named onWorkflowActivated1 is data bound to the workflowProperties field of Workflow1. When the WF runtime creates the activity instance named onWorkflowActivated1, this child activity initializes the new workflow instance. After onWorkflowActivated1 completes its work, the workflowProperties field in Workflow1 references a fully initialized SPWorkflowActivationProperties object that can then be used in any event handler to retrieve information about the current workflow instance.

Switch Workflow1.cs back to Designer view and then right-click the activity named onWorkflowActivated1. Select the Generate Handlers menu item, which creates an event handler method inside Workflow1.cs named onWorkflowActivated1_Invoked. Note that this event handler executes as part of the initialization sequence for any workflow instance created from this WF program.

It’s important to understand that the event handler for an activity of type onWorkflowActivated runs after the activity has completed its work, which means that the event handler runs after the data binding has initialized the workflowProperties field in Workflow1. Therefore, you can initialize the workflowId field by using the workflowProperties field.

private void onWorkflowActivated1_Invoked(...) {
  workflowId =
this.workflowProperties.WorkflowId;
}

To complete the first phase of our Hello World sample, let’s add a second activity to Workflow1 that writes a message into the workflow history table. Navigate to Designer view. In the Toolbox, locate the activity type LogToHistoryListActivity. Drag this activity type onto the designer surface to create a new activity instance immediately after onWorkflowActivated1. After you create this activity, select it and examine its properties in the Visual Studio property grid.

The new activity is named logToHistoryListActivity1. You can leave the name of this activity as is or change it to something more descriptive, such as logActivated. You should also note that two other properties are visible within the property sheet named HistoryDescription and HistoryOutcome. Whenever an activity of type LogToHistoryListActivity writes an entry into the workflow history table, it writes the values of these two properties so that users can see them.

While it is possible to assign static values for the HistoryDescription and HistoryOutcome properties directly inside the property sheet, it is more flexible if you create two new string properties inside the Workflow1 class and then data-bind them to the HistoryDescription and HistoryOutcome properties. Start by adding two properties to the Workflow1 class named HistoryDescription and HistoryOutcome.

public sealed partial class Workflow1: SequentialWorkflowActivity
{
         
private string _historyDescription;
        
public string HistoryDescription
        {
            get {
return _historyDescription; }
            set { _historyDescription = value; }
         }
        
private string _historyOutcome;
        
public string HistoryOutcome
        {
            get {
return _historyOutcome; }
            set { _historyOutcome = value; }
         }
}


To configure data binding for a property, click the little blue circle to the right of its name, which causes the workflow designer to invoke a special dialog box that makes it possible to data-bind property value to public fields or public properties exposed by another activity, such as Workflow1.

Once you successfully added the LogToHistoryListActivity activity and data-bind its properties, it’s time to add another event handler. Right-click the LogToHistoryListActivity activity and click Generate Handlers. This creates an event handler that fires just before the LogToHistoryListActivity activity writes its entry into the workflow history table. Therefore, you can write code in this event handler to assign a value to each of the two fields before data binding takes place. Write the event handler using the following code:

private void logActivated_MethodInvoking(object sender, EventArgs e)
         {
             
// Generate message using information of current item
            SPListItem item = workflowProperties.Item;
             
// determine whether workflow is running on a standard item or a document
            
if (item.File == null)
            {
                HistoryDescription =
"Workflow started on item " + item.Title + " at " + DateTime.Now.ToString();
             }
             
else
                HistoryDescription =
"Workflow started on document " + item.File.Name + " at " + DateTime.Now.ToString();
            HistoryOutcome =
"Workflow activation completed.";
        }

The previous example demonstrates a few important things about writing code within the event handler for a WF program targeting WSS. First, you see it’s very simple to program against the item or the document on which the workflow is running because the workflowProperties field exposes an Item property that, in turn, exposes a File property. The code in this example checks to see whether the File property is null to determine whether the workflow instance started on a standard list item or on a document.

The second important observation about this example is that the event handler assigns values to fields that are data bound to properties within the LogToHistoryListActivity activity. The timing is important here because the LogToHistoryListActivity activity does its work of evaluating its data-bound expressions and writing its entry into the workflow history after the event handler fires. This is the opposite of the timing involved with the onWorkflowActivated activity, which fires its event handler after completing its work of initializing the new workflow instance and assigning values back to the workflowProperties field in the Workflow1 class as a result of a data-bound property setting.

In the previous simple example, you saw the declarative data flow controlled through data binding that worked in both directions. The first example shows how data-binding the WorkflowProperties property of the onWorkflowActivated activity enables the flow of data from a child activity to the top-level activity named Workflow1. The second example shows you how to assign values to fields within Workflow1 that flow to a child activity.

Deploying a Workflow Template for Testing

At this point, the WF program named Workflow1 with the HelloWorkflow project has enough functionality that we can move through the steps of deployment to test our work. This section walks you through the details of installing the workflow template, creating an association, and initiating a workflow instance.

Note that WSS requires that an assembly DLL containing WF programs associated with a workflow template be installed in the GAC prior to use. That means that you must add a signing key to your assembly project so that its output assembly DLL is built with a strong name. Go ahead and add a strong name key file to the HelloWorkflow project so that the output assembly HelloWorkflow.dll is built with a strong name that makes it possible to deploy it in the GAC.

Next, you need to modify the two files named feature.xml and workflow.xml to define an installable feature that contains a Workflow element used to define a workflow template. After you complete this step, you should be able to install the feature with WSS by using stsadm.exe. Begin by opening the file named feature.xml, which is initially empty of content. Add the following CAML-based content to define the high-level feature attributes.

<Feature
  
Id="{CC3B59E9-E687-45a7-B0D6-62FA70869674}"
  
Title="Simple Workflow Template Feature"
  
Description="This feature installs our Simple Workflow Template"
  
Version="12.0.0.0"
  
Scope="Site"
  
xmlns="http://schemas.microsoft.com/sharepoint/">

  
<ElementManifests>
    
<ElementManifest Location="workflow.xml" />
  
</ElementManifests>

</Feature>

Within the Feature element, you can see it has typical attribute settings, such as a new unique GUID for its Id attribute along with a Title and Description. You should take note that the Scope attribute has a value of Site, which means that this feature is scoped at the site collection level as opposed to the site level. This is important because workflow templates can be defined only within features that are defined at Site Collection scope.

Next, open the workflow.xml file. You can see that this file is also initially empty of content. You need to add a Workflow element that defines a workflow template. Add the following XML-based content into workflow.xml:

<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  
<Workflow
    
Id="56FD3334-FC81-45b1-B5D4-A5FDA96B683C"
    
Name="Simple Workflow Template"
    
Description="This workflow templates has simple functionality"
     
CodeBesideClass="SimpleWorkflow.Workflow1"
    
CodeBesideAssembly="SimpleWorkflow, Version=1.0.0.0, Culture=neutral, PublicKeyToken=97370fefc8d8e862" >

    
<Categories/>
    <!-- no catagories needed -->
     
<MetaData />
    <!-- no metadata needed -->

   
</Workflow>
</Elements>

As you add this Workflow element into workflow.xml to define a workflow template, you must create a new GUID and assign it the Id attribute. Note that this GUID is different from the GUID used to identify the feature itself. You should also note that you are not limited to one workflow template per feature.

In addition to the Id, the Workflow element used to define a workflow template requires a Name, a Description, and two other attributes named CodeBesideClass and CodeBesideAssembly that should be configured to point to a class name of a WF program that has been compiled into an assembly DLL and installed in the GAC.

Now that we are finished editing feature.xml and workflow.xml, you should open the install.bat file and examine what’s inside. You need to make some edits to the install.bat file so that it contains the proper command-line instructions required to copy the feature files to the correct location and install the feature with the stsadm.exe utility. The install.bat file should also be written to install HelloWorkflow.dll into the GAC. Comments found inside install.bat provide instructions on what needs to be done. In most cases, all you really need to do is find and replace the text “MyFeature” with the name of your feature. This find and replace operation will take place about 14 different times. You’ll need to do more only if you change the default file names for your XML files or deploy to a non-root site collection.

After editing install.bat, you are now ready to deploy the workflow template for testing. First, build the HelloWorkflow project to ensure that the assembly DLL is up to date. Next, run install.bat from the command line or by double-clicking it within Windows Explorer. Note that installation of the assembly DLL in the GAC fails if you have not compiled HelloWorkflow.dll with a strong name. However, if install.bat runs successfully, you can then move to the next step of the workflow template test.

Testing the Simple Workflow Template

Once you have installed the feature that contains the Simple Workflow template, you should be able to activate it with a site collection for testing. Create or navigate to a test site collection that you can use to test your work. Once you get to the top-level site of the site collection, go to the Site Settigns page and click the Site Collection Features link. At the Site Collection Features page, you sould see the feature that defines your workflow template. Activating the features makes your workflow template available to create workflow associations on lists, document libraries and other content types throughout the site collection.

It’s now time to create a workflow association. Create or navigate to a list. Go to the List Settings page for the list and click the Workflow Settings link. If there are no existing workflow associations on the list, clicking the Workflow Settings link should take you to a page named AddWrkfl.aspx, which allows you to create new workflow associations. If there are already existing workflow associations on the list, clicking the Workflow Settings link should take you to the standard Workflow Settings page named WrkSetng.aspx. The WrkSetng. aspx.page displays existing workflow associations and provides a link that redirects you to a page that allows you to create a new workflow association.

Click the Add A Workflow link, which takes you to the Add A Workflow page named AddWrkfl.aspx. On this page, you can see all of the workflow templates that are activated with the current site collection, including your Simple workflow template. Select the Simple workflow template and use it to create a new workflow association named Simple Workflow Association. When you click the OK button, it creates the new association and returns you to the Workflow Settings page.

Now that the workflow association is created, it’s time to create a workflow instance on an item within the list. Return to the main page for the list named AllItems.aspx so that you can create a new list item. Once you create the new item, drop down the ECB menu for that list item and click the ECB menu item titled Workflows. Clicking the Workflow ECB menu item should take you to the Workflow.aspx page, where you should have the option of starting a new workflow instance by using your Hello World workflow association. Start a new workflow instance by clicking Simple Workflow Association.

After starting the workflow instance, return to the AllItems.aspx page for the list and look at the item for which you just started the new workflow instance. There should be a new column for the workflow association and a Completed link indicating that the workflow ran and was able to complete. Click this link so that you can drill down into the workflow status page named WrkStat.aspx. You should see information about the workflow instance, including the entry written to the workflow history table by the LogToHistoryListActivity activity that you added to your workflow. If you followed all of the steps correctly, the workflow status page should look like the page as shown in the below image.


We have now walked through the steps for creating, deploying and testing a very simple workflow template. However, a real world workflow template does not run to completion as soon as it initiated. Instead, it performs one or mote tasks and then uses events to go to sleep until the user(s) responsible for modifying those tasks performs additonal work.

Summary

Hope you have enjoyed the article which explains the Workflow structure and also walks through the steps for creating a simple workflow. You can download the working example created in Visual Studio 2005 and using Visual Studio Extensions for Window Workflow Foundation from below link.

Sample Workflow Example

By Jatin Prajapati   Popularity  (13620 Views)