Gain Architectural Control with Windows Workflow Foundation

icrosoft Windows Workflow Foundation (WF) consists of a programming model, an engine, and several tools for building workflow-enabled applications. The programming model resides in the System.Workflow namespace of Microsoft’s .NET framework 3.0, and has three major classes: Workflow.Activities, Workflow.ComponentModel, and Workflow.Runtime. You can host the workflow engine in any .NET Framework process.

WF Availability and Tools
WF is part of .NET Framework 3.0, which used to be called WinFX. As such, it is currently undergoing a public beta test, for which a GoLive license is available. You only need to sign a GoLive license if you want to deploy your WF application prior to the production release, but you can develop and test applications with the betas without a license. You can download WF from Microsoft’s Web site; links to the latest download can be found on the Windows Workflow Foundation home page.

To use WF from Visual Studio 2005, you’ll need the Microsoft Visual Studio 2005 Extensions for Windows Workflow Foundation, which is a separate download from Windows Workflow Foundation itself. The extensions include graphical workflow and custom activity designers for C# and Visual Basic as well as workflow debugger extensions.

In addition to the Visual Studio Extensions, WF has two command-line tools. Wca.exe is the workflow communication activity command line utility, and Wfc.exe is the workflow command line compiler, which compiles both workflows and activities.

Flowcharts and workflows
You can think of WF workflows as executable flowcharts. Historically, systems analysts created flowcharts of system logic using standard symbols (see Figure 1), which programmers would use for guidance when coding the logic manually.

?
Figure 1. A Simple Flowchart: This Visio flowchart illustrates several common programming design symbols.
?
Figure 2. Classic Invoice Workflow Diagram: The diagram shows the flow of an invoice through a typical business.

Modern practice often combines the roles of systems analyst and programmer. Experienced programmers in this dual role often skip the flowcharting step entirely and write directly in code, or create planning documents that are more closely related to the design methodology in use at their shop. Even when designers or developers do create flowcharts at the beginning of a project, the flowcharts often fall out of synch with the actual code during the course of development, as programmers rarely have time to update what often seems to be irrelevant documentation.

Historically, program designers used workflow diagrams similar to the one in Figure 2 to describe the “flow of control” of a business process. For example, you can easily represent the following common business process in a workflow diagram:

  1. A contractor provides an invoice for the accounts payable (AP) department.
  2. AP verifies that the invoice is against a valid purchase order (PO) issued by the purchasing department.
  3. AP submits the invoice to the approver for the PO.
  4. If the invoice is approved, AP pays the invoice on the schedule specified in the PO.

Flowcharts do a good job of modeling sequential programs with decision logic, but they don’t do a good job of modeling complex event-driven systems?such as the payment workflow just described. Note that the diagram shows only the most common flow?it doesn’t take into account either failure at any point during the process, nor does it model the time involved, which might be as little as a day, or as long as several months. For modeling complex event-driven processes people often use state machines. To model the business process above as a state machine, one would list the possible states and the events that trigger state transitions. These states might be Waiting for Invoice, Invoice Pending, Invoice Rejected, Invoice Approved, Invoice Payable, Payment Sent, and Invoice Paid. The events might be On Invoice Presented, On PO Valid, On PO Invalid, On Invoice Approved, On Invoice Not Approved, On Insufficient Funds, On Invoice Aged, and On Payment Cleared.

As you’ll see, Windows Workflow Foundation is capable of modeling both sequential flows and state machines.

Reasons to Use Workflows
Why would you want to use workflows for programming? One answer is: You might not. For simple programs that run for a brief time, there may be no good reason to use workflows. However, as the complexity of programs increases, code usually becomes correspondingly harder to understand and maintain. Workflow diagrams are typically much easier to understand than source code. If you extend the idea one step further, and make the diagrams executable artifacts rather than mere documentation, you gain not only the advantages of a simpler format and easier maintenance, but?unlike old-fashioned flow charts?you can rely on executable diagrams to be current.

State machines can be quite complex to program by hand. Furthermore, there’s a disconnect between “application time” and “human time.” Machines typically process instructions extremely quickly, but in a business process controlled by humans, the various states involved in the application may persist unchanged for days or weeks. Moreover, state transitions typically require human input and approval. A workflow engine that automatically saves and restores persistent states as needed and solicits human input and approval automatically and securely can save a tremendous amount of programming time and make the entire process more reliable.

Other Workflow Languages and Engines
The Business Process Execution Language (BPEL) is a widely supported standard for workflow description at the “orchestration” level, meaning that it is for “programming in the large.” About 30 vendors, including Microsoft, IBM, Oracle, SAP, and Sun, have implementations of BPEL. Microsoft’s current BPEL product is BizTalk Server 2006. A future version of BizTalk Server will incorporate Windows Workflow Foundation.

Other workflow languages include Workflow OSID , Job Definition Format , YAWL , BPML , SWSL , and XPDL . Several of these are based on Petri nets. Workflow languages remain an active research and development area, especially for scientific applications in areas like bioinformatics and particle physics.

Defining Windows Workflow Foundation
Windows Workflow Foundation is a development framework that enables you to embed workflows in .NET Framework applications. It’s not a language, per se, as much as a framework. It directly supports a workflow markup language based on XML, as well as C# and Visual Basic. Other .NET languages can be used as well, but currently the Visual Studio designer supports only C# and Visual Basic.

Goals and Characteristics of WWF
WF was designed to meet four major goals. It should:

  • Provide one workflow execution engine for any application that runs on Windows.
  • Support a wide range of workflow scenarios.
  • Add workflow to the .NET Framework in a natural, easily learned way.
  • Enable reusable workflow component development.

WF, unlike BizTalk, is an in-process workflow engine. It manages the flow of a .NET program, which lets any .NET AppDomain host WF, whether it’s a console application, a Windows application, or an ASP.NET Web application. The basic unit in a workflow is called an activity. WF has about 40 built-in activities and full support for custom activities. Some of the built-in activities provide the equivalents of a programming language’s control flow statements: Sequence, Parallel, IfElse, While, Conditioned Activity Group, Replicator, and Delay. Other built-in activities support interactions with the host program, such as listening for events, or invoking Web services.

WF has several built-in runtime services that support running workflows, including scheduling, compensating transactions, persistence, and tracking operations. WF also has a plug-in model that allows you to extend the existing base services or create your own new custom services.

Types of Workflows
The three major types of WF workflows are sequential, state machine, and data-driven. In a sequential workflow, as in the flowchart shown in Figure 1, the workflow is in control.

In a state machine workflow, events cause transitions between states, so the workflow is not in control. Instead, the external environment is in control, which often means that users determine the flow by their actions. For example, in the accounts payable example described earlier, users make decisions that affect the process flow, so that’s a natural candidate for a state machine.

In a data-driven workflow, some data controls the flow; this often happens within some part of a larger sequential or state-machine workflow, using a Constrained Activity Group, and/or a Policy activity. For example, the Accounts Payable example would check whether the invoice is connected to a valid purchase order and perform a check for sufficient funds, both of which would typically be database lookups.

How Windows Workflow Foundation Works
The WF engine architecture has three layers: hosting, runtime, and a workflow model. Workflow designers help prepare workflows and custom activities. For example, in Microsoft Office 2007, a workflow engine embedded in SharePoint integrates with Word, Excel, Outlook, and other Office applications to support document workflow activities.

Hosting
The WF hosting layer contains the standard pluggable WF runtime services and any custom services that the programmer includes. The standard services are:

  • Communications, for example with the host application and Web services.
  • Persistence, the storage of state for long periods of time.
  • Tracking, the interface to the instrumentation of workflows.
  • Timers, which are durable clocks for managing potentially long delays.
  • Threading, which manages the host thread pool for the workflow.
  • Transactions, which implement compensating transactions so that operations can fail gracefully without corrupting the durable state of an application.

Runtime
The WF runtime layer contains its core services, which are not pluggable. These are the execution service, the core tracking service, the state management service, the low-level scheduler, and the rules service.

Workflow Model
The WF workflow model layer supports two basic models: sequential workflows, and state machine workflows. Both types can have data-driven sections. In addition, developers can inherit from the workflow model classes to create customized models, or even create completely new model classes from scratch.

The basic difference between WF and a typical workflow engine is that WF is not tied to any underlying language. Instead, it consists of a set of simple and composite activities that it chains together and executes according to the model. You might think that the XAML markup for a workflow constitutes an XML-based language, but Microsoft views this more as data or serialized workflow state than as code.

Workflow Design
The Visual Studio 2005 Extensions for Windows Workflow Foundation turns workflow design into a simple drag-and-drop exercise. In Figure 3, I dragged a code activity into a sequential workflow, then filled in one line of code in the code activity’s handler, which prints “Hello, World!” If you build and run this application, it does indeed print “Hello, World!” in a console window, possibly setting a new world’s record for the largest amount of tooling used to design this particular application.

Writing Hello World as a workflow possibly sets a new world’s record for the largest amount of tooling ever used to design this particular application.
?
Figure 3. Hello World as a Workflow: The figure shows the world’s simplest example application written as a workflow.
?
Figure 4. Adding an IfElse Activity: Here’s a sequential workflow in the designer after adding an IfElse activity.

The three tabs at the bottom left of the Sequential Workflow pane select the view: the workflow activity, the workflow’s cancellation handler, and the workflow’s fault handlers.

The workflow gets more interesting as you add more activities. Figure 4 shows the designer after I dragged an IfElse activity onto the design pane, but have not yet defined the decision criteria or what the branches will do.

Microsoft Office 2007 Workflow Integration
SharePoint 2007 Server hosts WF server, so that Office 2007 applications can use (and be used by) workflows. For example, a Word 2007 document might kick off a SharePoint workflow that sends an email requesting an approval to another user through Outlook, then resumes only when that user grants or denies the approval on a SharePoint page created for that purpose. Reviews, approvals, and document expiration are all standard 2007 Office workflows.

Office SharePoint Designer 2007, the successor to FrontPage, can design workflows, and developers can also use the 30-odd custom Office 2007 activities to design Office workflows in Visual Studio 2005. The InfoPath 2007 designer supports binding form elements to workflows.

The use of SharePoint 2007 makes developing people-based workflows much easier than it has been, since it combines workflow with the Office applications that people use daily.

Applying Windows Workflow Foundation
There are a number of scenarios that lend themselves to solutions that involve workflows; to help you determine when to use workflows, here are some guidelines. Consider using a workflow when you need to:

  • Model a long-running process
  • Model a process that has multiple states with complicated relationships
  • Coordinate work where some portions are done by people and some by software
  • Coordinate multiple processes based on their outcomes
  • Compensate for cancelled processes automatically
  • Track and audit multiple processes

Automating a Simple Approval Process
Approval processes often need to coordinate work done both by people and by software, and so lend themselves to solution with a workflow. For example, as discussed in the preceding section, Office 2007 already includes a rather sophisticated Approval workflow that involves sending email through Outlook and getting secure approvals via SharePoint, which I won’t go into here.

But consider a very basic Approval workflow that needs only one IfElse activity, with two branches, as in Figure 5.

?
Figure 5. Basic Approval Workflow: The figure shows the process of debugging a simple workflow with Visual Studio 2005.

This happens to be a standard Microsoft workflow sample, called SimpleSequentialWorkflow. It’s unrealistic because the code behind the IfElse activity always sets the result to true and forces the result to the Yes branch:

   private void IsUnderLimit(object sender, ConditionalEventArgs e)   {       e.Result = true;   }

A somewhat more realistic example could obtain the yes/no result from a user, employing a dialog to retrieve the result, either in a console window or in a pop-up message box or form. For even more realism, you might use the XML result of an emailed InfoPath form to determine the result, or go whole hog and invoke a workflow that generates a secure Web page for the approver, sends an email approval request, listens for the approval or rejection, and then deletes the generated Web page.

Dynamic User Interfaces
One of the more interesting uses of workflows is to present the best user interface for the current state of a complex event-driven application dynamically. For example, a customer support representative may take incoming telephone calls for multiple products. For each product, there can be dozens of possible symptoms, and there will be a possibly complex fault diagnosis tree for each symptom.

While it’s possible to code this application as a series of menu picks, scripts to read to the customer, and collections of radio buttons and checkboxes, the application would tend to be difficult to use and difficult to maintain, and the agent would have to do quite a bit of screen-switching. A backward-chaining expert system might be another alternative, but it might be even more flexible to model the diagnosis process as a state machine workflow. At each state, the user interface presented would take into account the knowledge gathered so far and the possible choices, which would trigger transitions to more refined states.

One of the major car rental companies has done exactly that, implementing a dynamic user interface system controlled by workflows for its rental agents. Depending on the information and goals presented by the customer, the system looks up what data it needs from the corporate database, presents the agent with the appropriate form to gather the additional information needed from the customer, and eventually triggers the correct printed contract. This saves the agent quite a bit of time, and makes the company look good to the customer.

?
Figure 6. Accounts Payable State Machine: Here’s one possible state machine workflow to handle the process of paying an invoice.

Modeling a Business Process
Earlier, I introduced the classic Accounts Payable business process for handling an invoice. Figure 6 shows one possible state machine workflow to handle this.

This is merely a first cut at the model. One obvious refinement would be to automatically invoke a new workflow to listen for the next invoice whenever the InvoiceArrives event fires. Another would be for the RequestApproval initializer in the InvoicePending state to generate an email and secure Web page specifically intended for the approver or approvers, as discussed earlier. Still another might be to combine the InvoiceApproved and InvoicePayable states, and have the AgePayable and SendPayment steps be an internal sequence inside the InvoiceApproved state.

It might also be useful to add additional steps in certain cases. For example, if the process reaches the InvoiceRejected state, there might be reasons for the rejection that require taking other actions. For example, if the invoice was rejected because the PO has insufficient funds, but the contract supporting the PO has funds, the InvoiceRejected state could invoke a workflow to ask for an extension to the PO.

I have discussed how Microsoft Windows Workflow Foundation works, when you might want to use it, and how you might choose different types of workflow?but I have only touched the surface in showing you its capabilities; I hope that you’ll follow up by downloading the product and trying it yourself.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Related Posts