Home Business & Other Programming Windows Workflow Foundation: Practical WF Techniques and Examples using XAML and C#

Programming Windows Workflow Foundation: Practical WF Techniques and Examples using XAML and C#

By Kenneth Scott Allen
books-svg-icon Book
eBook $28.99
Print $48.99
Subscription $15.99
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $28.99
Print $48.99
Subscription $15.99
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
About this book
Windows Workflow Foundation (WF) is a technology for defining, executing, and managing workflows. It is part of the .NET Framework 3.0 and will be available natively in the Windows Vista operating system. Windows Workflow Foundation might be the most significant piece of middleware to arrive on the Windows platform since COM+ and the Distributed Transaction Coordinator. The difference is, not every application needs a distributed transaction, but nearly every application does have a workflow encoded inside it. In this book, K Scott Allen, author of renowned .NET articles at www.odetocode.com, provides you with all the information needed to develop successful products with Windows Workflow. From the basics of how Windows Workflow can solve the difficult problems inherent in workflow solutions, through authoring workflows in code, learning about the base activity library in Windows Workflow and the different types of workflow provided, and on to building event-driven workflows using state machines, workflow communications, and finally rules and conditions in Windows Workflow, this book will give you the in-depth information you need. Throughout the book, an example "bug reporting" workflow system is developed, showcasing the technology and techniques used.
Publication date:
December 2006
Publisher
Packt
ISBN
9781904811213

 

Chapter 1. Hello, Workflow

…thoughts arrive like butterflies — Gossard / Vedder

Windows Workflow might be the most significant piece of middleware to arrive on the Windows platform since COM+ and the Distributed Transaction Coordinator. The difference is, not every application needs a distributed transaction, but nearly every application does have a workflow encoded inside. To understand the types of problems Windows Workflow is designed to solve, let's talk about workflow in a generic sense.

What is a workflow? A simple definition would say a workflow is the series of steps, decisions, and rules needed to complete a specific task. Think of the workflow that takes place when you order food at the local pizza shop. You tell the cashier the type of pizza you want. The cashier passes this information to the cook, who gathers ingredients and puts a pizza in the oven. The cook hands a finished pizza to the cashier, who collects payment and completes the workflow by handing over your pizza. The work flows, to the cashier, then to the cook, and then back again.

During each of these steps, all parties are also evaluating rules and making decisions. Before accepting the order, the cook has to compare the order against the ingredients in stock. The cashier has to validate and process any coupons you might present, and notify the manager if you pay with a counterfeit looking bill.

Not every workflow has to involve humans (which is good, because humans complicate even the simplest process). A workflow can take place between two distributed software applications. For example, two content management applications might need to follow a specific set of steps and rules when synchronizing content in the middle of the night.

Most workflows are stateful, and often run for a relatively long time. Hopefully, your pizza will be ready within 30 minutes. During those 30 minutes, state information about your order, like the toppings you selected, has to be available. A different workflow happens when the pizza shop orders cheese. The cheese supplier might not deliver the mozzarella for 30 hours, and the pizza shop may not pay the cheese supplier for 30 days. During those 30 days, something needs to maintain the state of the workflow for a purchase.

A workflow may spend a large portion of its lifetime waiting for events to happen in the world around it. A workflow may be idle when waiting for a delivery, or waiting for a payment, or waiting for a pizza to finish in the oven. During these wait times, the workflow is idle and no resources are required by the workflow.

A workflow, then, is a series of steps to finish a task. A workflow is often long running and stateful, and often needs to wait on events and interact with humans. You can see workflows everywhere you look in the world. As software developers, we often have to codify the workflows around us into software applications.

Building Workflow Solutions

We've all been involved with software projects that try to improve a business process. The process might have involved pizza orders, or financial transactions, or health care. Invariably, the word workflow will arise as we talk about these projects. While the workflow might sound simple, we know the devil is always in the details. We'll need database tables and data access classes to manage the workflow state. We'll need components to send emails and components to wait for messages to arrive in a queue. We will also need to express the workflow itself for the computer to execute. Let's look at a theoretical implementation of a workflow:

// The workflow for a newly submitted Purchase Order
class PurchaseOrderWorkflow
{
public void Execute(PurchaseOrder order)
{
WaitForManagerApproval(order);
NotifyPurchaseManager(order);
WaitForGoods(order);
}
…
}

Assuming we have definitions for the three methods inside of Execute, can a workflow really look this simple? The answer is no. We'll have to add code for exception handling, logging, and diagnostics. We'll need to raise events and provide hooks to track and cancel a running workflow. Also, this workflow will be idle and waiting for an external event to occur, like the arrival of the purchased goods, for the majority of the time. We can't expect to block a running application thread for days or weeks while waiting for a delivery. We'll need to provide a mechanism to save the workflow's state of execution to a persistent data store and remove the running workflow instance from memory. When a significant event occurs, we'll need to restore the workflow state and resume execution.

Unfortunately, we will have so much code in and around the workflow that we will lose sight of the workflow itself. All the supporting code will hide the process we are trying to model. A non-technical businessperson will never be able to look at the code and see the workflow. A developer will need to dig through the code to find the workflow inside.

An improved workflow design will try to separate the definition of a workflow from the engine and supporting code that executes the workflow. This type of approach allows a developer, or even a businessperson, to express what the workflow should be, while the workflow engine takes care of how to execute the workflow. These days, many workflow solutions define workflows inside the loving embrace of angled brackets. Let's look at some theoretical XML for a workflow definition:

<Workflow Name="PurchaseOrderWorkflow">
<Steps>
<WaitForTask Event="ManagerApproval"/>
<NotifyTask Target="PurchaseManager"/>
<WaitForTask Event="Delivery"/>
</Steps>
<Parameters>
<Parameter Type="PurchaseOrder" Name="order"/>
</Parameters>
</Workflow>

Let's ask the question again — can a workflow really look this simple? The answer is yes; what we will need is a workflow engine that understands this XML, and can transform the XML into instructions for the computer. The engine will include all the required features like exception handling, tracking, and enabling cancellations.

Note

The C# code we saw earlier is an example of imperative programming. With imperative programming, we describe how to perform a task by providing a series of instructions to execute. The XML markup above is an example of declarative programming. With declarative programming, we describe what the task looks like, and let other software determine the steps required to complete the task. Most of the commercial workflow solutions on the market allow a declarative definition of workflow, because the declarative approach doesn't become cluttered with exception handling, event raising, and other lower-level details.

One of the benefits to using XML is the large number of tools with the ability to read, modify, create, and transform XML. XML is tool-able. Compared to parsing C# code, it would be relatively easy to parse the XML and generate a visualization of the workflow using blocks and arrows. Conversely, we could let a business user connect blocks together in a visual designer, and generate XML from a diagram.

Let's think about what we want in a workflow solution. We want to specify workflows in a declarative manner, perhaps with the aid of a visual designer. We want to feed workflow definitions into a workflow engine. The engine will manage errors, events, tracking, activation, and de-activation.

Enter Windows Workflow Foundation.

 

Building Workflow Solutions


We've all been involved with software projects that try to improve a business process. The process might have involved pizza orders, or financial transactions, or health care. Invariably, the word workflow will arise as we talk about these projects. While the workflow might sound simple, we know the devil is always in the details. We'll need database tables and data access classes to manage the workflow state. We'll need components to send emails and components to wait for messages to arrive in a queue. We will also need to express the workflow itself for the computer to execute. Let's look at a theoretical implementation of a workflow:

// The workflow for a newly submitted Purchase Order
class PurchaseOrderWorkflow
{
public void Execute(PurchaseOrder order)
{
WaitForManagerApproval(order);
NotifyPurchaseManager(order);
WaitForGoods(order);
}
…
}

Assuming we have definitions for the three methods inside of Execute, can a workflow really look this simple? The answer is no. We'll have to add code for exception handling, logging, and diagnostics. We'll need to raise events and provide hooks to track and cancel a running workflow. Also, this workflow will be idle and waiting for an external event to occur, like the arrival of the purchased goods, for the majority of the time. We can't expect to block a running application thread for days or weeks while waiting for a delivery. We'll need to provide a mechanism to save the workflow's state of execution to a persistent data store and remove the running workflow instance from memory. When a significant event occurs, we'll need to restore the workflow state and resume execution.

Unfortunately, we will have so much code in and around the workflow that we will lose sight of the workflow itself. All the supporting code will hide the process we are trying to model. A non-technical businessperson will never be able to look at the code and see the workflow. A developer will need to dig through the code to find the workflow inside.

An improved workflow design will try to separate the definition of a workflow from the engine and supporting code that executes the workflow. This type of approach allows a developer, or even a businessperson, to express what the workflow should be, while the workflow engine takes care of how to execute the workflow. These days, many workflow solutions define workflows inside the loving embrace of angled brackets. Let's look at some theoretical XML for a workflow definition:

<Workflow Name="PurchaseOrderWorkflow">
<Steps>
<WaitForTask Event="ManagerApproval"/>
<NotifyTask Target="PurchaseManager"/>
<WaitForTask Event="Delivery"/>
</Steps>
<Parameters>
<Parameter Type="PurchaseOrder" Name="order"/>
</Parameters>
</Workflow>

Let's ask the question again — can a workflow really look this simple? The answer is yes; what we will need is a workflow engine that understands this XML, and can transform the XML into instructions for the computer. The engine will include all the required features like exception handling, tracking, and enabling cancellations.

Note

The C# code we saw earlier is an example of imperative programming. With imperative programming, we describe how to perform a task by providing a series of instructions to execute. The XML markup above is an example of declarative programming. With declarative programming, we describe what the task looks like, and let other software determine the steps required to complete the task. Most of the commercial workflow solutions on the market allow a declarative definition of workflow, because the declarative approach doesn't become cluttered with exception handling, event raising, and other lower-level details.

One of the benefits to using XML is the large number of tools with the ability to read, modify, create, and transform XML. XML is tool-able. Compared to parsing C# code, it would be relatively easy to parse the XML and generate a visualization of the workflow using blocks and arrows. Conversely, we could let a business user connect blocks together in a visual designer, and generate XML from a diagram.

Let's think about what we want in a workflow solution. We want to specify workflows in a declarative manner, perhaps with the aid of a visual designer. We want to feed workflow definitions into a workflow engine. The engine will manage errors, events, tracking, activation, and de-activation.

Enter Windows Workflow Foundation.

 

A Windows Workflow Tour


Microsoft's Windows Workflow Foundation is one piece of the new .NET 3.0 platform. The other major additions in .NET 3.0 include Windows Presentation Foundation, or WPF, and Windows Communication Foundation, or WCF. Microsoft will support Windows Workflow (WF) on Windows XP, Windows Server 2003, and Windows Vista.

Support for current and future Microsoft platforms means WF could reach near ubiquity over time. We can use WF in smart client applications, and in simple console-mode programs. We can also use WF in server-side applications, including Windows services, and ASP.NET web applications and web services. WF will make an appearance in several of Microsoft's own products, including Windows SharePoint Services and Microsoft Biztalk Server. We will now look at an overview of the essential features of Windows Workflow.

Activities

The primary building block in Windows Workflow is the activity. Activities compose the steps, or tasks in a workflow, and define the workflow. We can arrange activities into a hierarchy and feed activities to the workflow engine as instructions to execute. The activities can direct workflows involving both software and humans.

All activities in WF derive from an Activity base class. The Activity class defines operations common to all activities in a workflow, like Execute and Cancel. The class also defines common properties, like Name and Parent, as well as common events like Executing and Closed (the Closed event fires when an Activity is finished executing). The screenshot below shows the Activity class in the Visual Studio 2005 class designer:

WF ships with a set of ready-made activities in the base activity library. The primitive activities in the library provide a foundation to build upon, and include control‑flow operations, like the IfElseActivity and the WhileActivity. The base activity library also includes activities to wait for events, to invoke web services, to execute a rules engine, and more.

Custom Activities

Windows Workflow allows developers to extend the functionality of the base activity library by creating custom activities to solve problems in their specific domain. For instance, pizza delivery workflows could benefit from custom activities like SendOrderToKitchen or NotifyCustomer.

All custom activities will also ultimately derive from the base Activity class. The workflow engine makes no special distinction between activities written by Microsoft and custom activities written by third parties.

We can use custom activities to create domain‑specific languages for building workflow solutions. A domain‑specific language can greatly simplify a problem space. For instance, a SendOrderToKitchen custom activity could encapsulate a web service call and other processing logic inside. This activity is obviously specific to the restaurant problem domain. A developer will be more productive working with this higher-level abstraction than with the primitive activities in the base activity library. Even a restaurant manager will understand SendOrderToKitchen and might arrange the activity in a visual workflow designer. It will be difficult to find a restaurant manger who feels comfortable arranging WhileActivity and InvokeWebServiceActivity objects in a workflow designer.

Note

C#, VB.NET, and XML are general-purpose languages and have the ability to solve a wide array of different problems. We can use C# to develop solutions for pizza restaurants as well as hospitals, and the language works equally well in either domain. A domain-specific language excels at solving problems in a particular area. A domain-specific language for restaurant workflow would boost productivity when writing software for a restaurant, but would not be as effective when writing software for a hospital.

Visual Studio 2005 Extensions

Microsoft also provides the Microsoft Visual Studio 2005 Extensions for Windows Workflow. These extensions plug into Visual Studio to provide a number of features, including a visual designer for constructing workflows. A screenshot of the visual designer is shown on the next page.

The designer uses the same windows we've come to love as Windows and web form developers. The Toolbox window will list the activities available to drag onto the design surface. We can add our own custom activities to the Toolbox. Once an activity is on the design surface, the Properties window will list the activity's properties that we can configure, and the events we can handle. The Toolbox window is shown below:

Windows Workflow and XAML

The WF designer can generate C# and Visual Basic code to represent our workflow. The designer can also read and write eXtensible Application Markup Language (XAML, pronounced zammel). XAML files are valid XML files. XAML brings a declarative programming model to Windows Workflow. Here is the XAML generated by the designer for the workflow we saw earlier:

<SequentialWorkflowActivity
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/workflow"
x:Class="HelloWorld.HellowWorldWorkflow"
>
<CodeActivity
x:Name="codeActivity1"
ExecuteCode="codeActivity1_ExecuteCode_1" />
</SequentialWorkflowActivity>

Our workflow is trivial and contains only a single activity inside—a CodeActivity. When the workflow engine executes the CodeActivity, the CodeActivity will invoke a method specified by the ExecuteCode attribute. Our XML also includes special XML namespace directives. We'll cover XAML and these namespaces in Chapter 2.

XAML is not a technology specific to Windows Workflow. As an "extensible application" markup language, XAML is also present in Microsoft's presentation framework—Windows Presentation Foundation (WPF). In WPF, XAML declaratively constructs a rich user interface consisting of not only buttons and labels, but also animation storyboards and data templates.

One important capability of declarative XAML is the ability to join forces with imperative code in a partial class. Partial classes, introduced in .NET 2.0, are a feature available to both Visual Basic and C# developers. Partial classes allow the definition of a class to span more than one file. The XAML above will transform into a partial class by the name of HelloWorldWorkflow. We control the name of the class from XAML with the x:Name attribute in the root node. We can add members to the generated class by defining a class with the same name and with the partial keyword.

public partial class HelloWorldWorkflow
: SequentialWorkflowActivity
{
private void codeActivity1_ExecuteCode_1(object sender,
EventArgs e)
{
// ...
}
Windows WorkflowVisual Studio 2005 Extensions}

In this example, we are adding the codeActivity1_ExecuteCode_1 method as a member of the same class (HelloWorldWorkflow) produced by the XAML.

WF Validation and Debugging

Another job of the workflow designer is to provide validation feedback for the activities in a workflow. Each activity can define its own design-time and run-time validation. The designer will flag an activity with a red exclamation point if the activity raises validation errors. For example, a CodeActivity will display a red exclamation point until we set the ExecuteCode property. Without a method to invoke, the CodeActivity is useless, but the validation catches this problem early and provides visual feedback.

The designer also provides debugging features. We can set breakpoints on an activity in the workflow designer. When execution stops, we can look at the Call Stack window to see the activities previously executed in the workflow instance. The debugger commands Step In, Step Out, and Step Over all work intuitively; for instance, the Step In command will move to the first activity inside a composite activity, while Step Over executes the entire composite activity and moves to the next sibling.

Designer Looks

The workflow designer allows customization of its design surface via themes. A theme defines the background colors, fonts, grid lines, and border styles to use on the design surface. We can even specify color and border styles for specific activity types. Through Visual Studio, we can create new themes, or modify existing themes.

All this styling ability isn't just to make the designer look pretty in Visual Studio, however. The WF designer is a component we can host inside our own applications. The ability to host the designer opens a number of interesting possibilities. First, we can host the designer and allow the non-developer types (a.k.a. business people) to design and edit workflows. By providing custom activities, we can match the vocabulary needed to build a workflow with a vocabulary the business people will understand (a domain-specific language). By providing custom themes, we can match the designer look with the look of our application.

The Windows Workflow Runtime

One perspective for Window Workflow is to view the workflow activities as instructions, or opcodes, for a workflow processor to execute. In Windows Workflow, the processor is in the WF runtime. To start a workflow party, we first need a host for the runtime and workflow services.

Hosting the Windows Workflow Runtime

Windows Workflow is not a stand-alone application. Like ASP.NET, WF lives inside a handful of assemblies (most notably for this topic, the System.Workflow.Runtime.dll assembly). Like the ASP.NET runtime, WF needs a host process to load, initialize, and start its runtime before anything interesting can happen. Unlike the traditional server-side usage of ASP.NET, however, WF will be useful in a variety of different hosts. We can host WF in a smart client application, a console application, or a Windows service, for instance.

The class diagram in the screenshot below features the primary classes we use to execute workflows in WF.

Creating an instance of the WorkflowRuntime class and calling StartRuntime is all we need to spin up the workflow execution environment. WorkflowRuntime defines methods that allow customization of the execution environment. The class also defines events we can listen for during execution. The runtime will fire an event when workflows finish execution, abort, turn idle, and more.

Once we've created an instance of the runtime, we can create workflows with the CreateWorkflow method. The CreateWorkflow method returns an object of type WorkflowInstance. The WorkflowInstance class represents an individual workflow. The Start method on the workflow instance object will begin the execution of a workflow. If an exception occurs, the workflow will invoke the Terminate method (which leads to the runtime raising a WorkflowTerminated event). A typical sequence of calls is shown in the screenshot next.

The WorkflowRuntime and WorkflowInstance classes are arguably the most important classes needed at run time, but they are not the only classes available. Other classes inside the WF assemblies provide important services to the workflow runtime. Chapter 5 will cover these services in detail, but the following provides a brief introduction.

Runtime Services

The WorkflowRuntime class provides only the basic features for executing workflows. Earlier, we mentioned important features we'd like to see in a workflow engine, like the ability to track active workflows and deactivate idle workflows. Don't worry, these features are available through an extensibility mechanism of WorkflowRuntime— the AddService method.

AddService allows us to make one or more services available to the runtime. These services might be custom services we've written specifically for our domain, like a custom scheduling service, or they might be services already written by Microsoft and included with WF. Let's continue our tour by looking at the services already available.

Scheduling Services

A scheduling service controls threads the runtime needs to execute workflows. The DefaultWorkflowSchedulerService creates new threads to execute workflows. Because the threads are separate from the host application, the workflows do not block any application threads and execute asynchronously. The maximum number of simultaneously executing workflows is configurable.

A second scheduling service, the ManualWorkflowSchedulerService, is available when the host application is willing to donate threads to the workflow runtime. Donating a thread to the runtime is a useful technique in server‑side applications, like ASP.NET web applications and web services. Server-side applications typically pull a thread from a pool to service each client request. It makes sense to loan the thread to the WF runtime, and let the runtime execute the workflow synchronously on the existing request thread instead of using two threads per request, which could reduce scalability.

As with all services in Windows Workflow, you can define your own scheduling service if the built-in services do not fit your requirements.

Transaction Services

A transaction service, as the name might imply, allows the runtime to keep the internal state of a workflow consistent with the state in a durable store, like a relational database. The default transactional service is an instance of the DefaultWorkflowTransactionService class. Activities inside a running instance of a workflow, and the services operating on the same instance, can all share the same transaction context.

WF relies on the implementation of transactions in .NET's System.Transactions namespace. The Transaction class offers a lightweight, auto-enlisting, and promotable transaction. The transaction can start as a local transaction, and later the runtime can promote the transaction to a heavyweight, distributed transaction if needed.

Persistence Services

A persistence service is responsible for saving the state of a workflow to a durable store. The SqlWorkflowPersistenceService service saves the state of a workflow into a SQL Server database. Persistence is required for long‑running workflows, because we can't have an invoice-processing workflow in memory for 30 days till the customer's payment arrives. Instead, the runtime can persist the state of the workflow to a durable store and unload the instance from memory. In 30 days (or hopefully, less), the runtime can reload the workflow instance and resume processing. The WF runtime will automatically persist a workflow that is idle or suspended when a persistence service is present.

The SqlWorkflowPersistenceService will work with SQL Server 2000 or any later version of Microsoft SQL Server, including the free MSDE and Express editions. Of course, we'll need a database schema that the persistence service understands. In Chapter 5 we will see how to use the T-SQL installation scripts provided by the .NET 3.0 installation.

Tracking Services

While a scheduling service is responsible for selecting threads for a workflow to run on, a tracking service is responsible for monitoring and recording information about the execution of a workflow. A tracking service will tell the runtime the type of information it wants to know about workflows using a tracking profile. Once the service establishes a profile, the service can open a tracking channel to receive events and data. Chapter 5 includes more details on tracking profiles and channels.

WF includes a SqlTrackingService class that stores tracking data into a SQL Server database. The service will use the previously discussed transactional service to ensure the tracking data for a workflow is consistent with the state of the workflow it's tracking. The runtime does not start a tracking service by default, but we can programmatically add a tracking service (or configure a tracking service with an application configuration file) for the runtime to use.

Now we've covered all the basic features of WF, so let's put the software to work.

 

Our First Workflow


Maybe you've had one of those product managers who is always at your desk, asking "are you done, yet?" In this section, we will replace the annoying project manager with a trivial Windows Workflow program. The sample isn't meant to demonstrate all the capabilities of the platform, but give a general feel for creating and running a workflow with WF.

Before we can begin, we'll need to download and install the .NET 3.0 framework. The installation program is available from http://netfx3.com. Supported development tools for the .NET 3.0 framework include all editions of Visual Studio 2005. We'll also need to download and install Visual Studio 2005 Extensions for Windows Workflow Foundation. The extensions are also available from http://netfx3.com. The extensions are not compatible with the Express editions of Visual Studio 2005.

First, we'll use Visual Studio to create a new Workflow project (File | New Project). We'll choose C# as our language and select the Sequential Workflow Console Application template (see the screenshot on the next page). The template gives us a project with references to all the correct WF assemblies, an empty workflow, and a Program.cs file to drive the workflow. Right-click the workflow and select Delete so we can start a workflow from scratch.

We can now right-click the project file in the Solution Explorer window and select Add New Item. From the list of items we'll choose Sequential Workflow (with code separation) and give the item the name of workflow1.xoml (see screenshot below). This XOML file will contain the XAML definition of our workflow.

If we click to expand the node containing Workflow1.xoml, we will find a C# code-beside file (Workflow1.xoml.cs) containing a partial class. As we mentioned earlier, the partial class will combine with the class generated from the XAML to produce a single type. Let's modify the class in Workflow1.xoml.cs by adding an IsFixed property with a backing field, as shown below:

public partial class Workflow1 : SequentialWorkflowActivity
{
private bool _isFixed;
public bool IsFixed
{
get { return _isFixed; }
set { _isFixed = value; }
}
}

If we double-click the .xoml file, the designer will appear. At this point we would want to open the Toolbox window if is not open (Ctrl+Alt+X). We can drag a While activity from the Toolbox and drop the activity between the start and end point of our workflow. The While Activity executes a child task until some condition is met. Our next step is to drag a Code activity from the Toolbox into the center of the While activity. At this point, our designer should resemble the following screenshot:

Notice both activities display a red exclamation point. The activities are failing their validation checks. We can hover the mouse cursor over the exclamation points and open a smart tag to view the validation error. If we tried to compile the program we'd see these same validation errors as compilation errors. We'll fix these errors now.

The Code activity requires us to assign an event handler for the ExecuteCode event. We can set the event by opening the Properties window (F4) and clicking the Code activity to set focus. Double-clicking in the empty space beside the ExecuteCode property will send us into the code-beside file and generate a new event handler. We can place the following code into the event handler. This code will ask the user if a bug is fixed, and then read a key press. If the user presses the 'y' key, the code will set the _isFixed field to true.

private void codeActivity1_ExecuteCode(object sender, EventArgs e)
{
Console.WriteLine("Is the bug fixed?");
Char answer = Console.ReadKey().KeyChar;
answer = Char.ToLower(answer);
if (answer == 'y')
{
_isFixed = true;
}
else
{
Console.WriteLine();
Console.WriteLine("Get back to work!");
Console.WriteLine();
}
}

The Code activity should now pass validation, so we can turn our attention to the While activity. A While activity requires a valid Condition property. Several activities in the base activity library work with conditions, including the IfElse, ConditionedActivityGroup, and Replicator activities. Chapter 9 will cover conditions and rules in more detail.

We can set the Condition property of our activity by opening the drop‑down list beside the Condition property in the Properties window. We have the choice of selecting a CodeCondition or a RuleConditionReference. These choices represent the two techniques available to express a condition, the first being with code (a method that returns a Boolean value), the second being with a rule. Let's select the RuleConditionReference. A rule condition is a named expression that evaluates to true or false, and can live in an external .rules file for easy maintenance. A plus sign appears beside the Condition property, and we can click the sign to expand the property editor.

When the Condition property expands, the Property window gives us the ability to set a ConditionName and an Expression. Clicking on the ellipsis (…) button in the Condition name will launch a Select Condition dialog box.

Clicking the New Condition... button will launch the Rule Condition Editor.

We want the While activity to loop until the bug is fixed. Our rule is !this.IsFixed. Once we've entered the condition (notice the editor provides IntelliSense), we can click OK. When we return to the Select Condition dialog box, we can see the editor has given our condition the name of Condition1. We should select Condition1 and press OK. The While activity should now have a ConditionName and Expression set, and pass validation.

Now we need to open the Program.cs file, which contains the method Main—the entry point for our Console application. We need to host the WF runtime and ask the runtime to execute our workflow. The item template for a workflow project provides all the boilerplate code we need. Let's review the code:

class Program
{
static void Main(string[] args)
{
WorkflowRuntime workflowRuntime = new WorkflowRuntime();
workflowRuntime.WorkflowCompleted +=
new EventHandler<WorkflowCompletedEventArgs>
(workflowRuntime_WorkflowCompleted);
workflowRuntime.WorkflowTerminated +=
new EventHandler<WorkflowTerminatedEventArgs>
(workflowRuntime_WorkflowTerminated);
WorkflowInstance instance;
instance = workflowRuntime.CreateWorkflow(typeof(Workflow1));
instance.Start();
waitHandle.WaitOne();
}
static void workflowRuntime_WorkflowTerminated(object sender,
WorkflowTerminatedEventArgs e)
{
Console.WriteLine(e.Exception.Message);
waitHandle.Set();
}
static void workflowRuntime_WorkflowCompleted(object sender,
WorkflowCompletedEventArgs e)
{
waitHandle.Set();
}
static AutoResetEvent waitHandle = new AutoResetEvent(false);
}

The first step is to instantiate a WorkflowRuntime instance. The code wires up event handlers to the runtime so we know if a workflow terminates (because of an exception), or completes successfully. The code instantiates our bug-fixing workflow using the CreateWorkflow method, passing the type of our workflow. Since the workflow engine executes our workflow asynchronously, we need to block our thread on an AutoResetEvent object and wait for the workflow to complete (otherwise, the console mode program would exit before the workflow gets an opportunity to run). An AutoResetEvent object will block a thread until the object is in a signaled state, which we do with the Set event in the event handlers.

We can now build our workflow solution and run the executable from the command line.

 

Summary


Software developers have been implementing workflows to model business processes since the beginning of time. During this time, we've learned that workflows can be long-running and often require input from humans. Building a robust workflow to meet these challenges is a daunting task. An ideal paradigm for building workflows is to separate the workflow definition from the engine that executes the workflow.

Once we've separated workflow definitions from the execution engine, we can go on to build workflow components to create a domain‑specific language. A businessperson has the ability to understand the domain‑specific language, and can understand a workflow without seeing the clutter of exception handling and workflow tracking.

Windows Workflow brings a workflow engine and workflow development tools to Microsoft platforms. The instructions for the WF engine are activities, and we can arrange these activities using a graphical designer, XAML, code, or a combination of the three. WF provides the services we need for a workflow engine, including persistence, threading, and transaction services. The future looks bright for building workflow solutions.

About the Author
  • Kenneth Scott Allen

    K. Scott Allen is the Chief Software Architect for Medisolv, Inc and holds MCP and MCSD certifications. In 12 years of software development Scott has worked on everything from real time firmware in 8 bit embedded devices to highly scalable Internet applications connecting COM+ and J2EE components with web services. Living in Hagerstown, Maryland, Scott tries to play as much softball as possible during the summer. Scott is a cofounder of the site http://www.OdeToCode.com, a .NET developer resource built using the Community Starter Kit. Contact K. Scott Allen

    Browse publications by this author
Latest Reviews (2 reviews total)
The books I have purchased are "MICROSOFT WINDOWS WORKFLOW FOUNDATION 4.0 COOKBOOK" and "Programming Windows Workflow Foundation: Practical WF Techniques and Examples using XAML and C#" worth reading for beginners.
I think it is not a begginers book as It seems to be.
Programming Windows Workflow Foundation: Practical WF Techniques and Examples using XAML and C#
Unlock this book and the full library FREE for 7 days
Start now