Click here to Skip to main content
14,978,528 members
Articles / Programming Languages / C#
Posted 27 Mar 2007


227 bookmarked

Jump start Windows Workflow Foundation

Rate me:
Please Sign up or sign in to vote.
4.81/5 (139 votes)
17 Apr 2007CPOL10 min read
Windows Workflow Foundation tutorial

Jump Start Windows Workflow Foundation

Once a veteran programmer was asked to define his professional developer's career in as few words as possible. His answer was "passion", "excitement" and "learning". And that's absolutely true as new, bleeding edge, exciting technologies/frameworks/languages keep flooding the technology limelight; we programmers fuel our passion of we-can-do-anything by mastering them.

One of the newest buzz phrases in the industry is "Windows Workflow Foundation" (WF). This article is aimed at getting a jump start into it to fuel excitement and pump up passion. Basic knowledge of .NET Framework is the only prerequisite for marching on with this jump-start tutorial. Examples are in C#, but VB.NET lovers are also invited to the show as this is all about framework, and if they can understand the pseudo code, programming it in VB.NET must be trivial.

What is Workflow?

Dissecting the keyword (Windows Workflow Foundation), the first question that strikes the mind is "what exactly is workflow?" To answer this, let's consider the following scenarios.

  1. Simon needs a loan to purchase a new Ferrari to impress his new girlfriend.
    1. He goes to bank and explains his need.
    2. Bank checks his credit history.
    3. Based on credit history, Simon was offered multiple loan options.
    4. Simon selects one of options.
    5. Bank approves loan, money gets transferred to Simon's account.
  2. I want to be the first one in whole world to read new Harry Potter book.
    1. Supposing I don't have online access / I don't trust, I will go to my local book shop.
    2. Ask the salesperson if I can have an early booking for the new Harry Potter book.
    3. If she says "yes", she will ask me to fill out the "form for early booking".
    4. I will enter my name, address and other details.
    5. The salesperson will check my details on form, save it in file and promise me I will get my copy as soon as book reaches the store.

What is common in these two entirely different, but still relevant, example scenarios? A similarity lies in the number of 'steps' to complete an 'action'. The desired action (getting a loan / reserving a new book) is dependent on the number of steps: their output and sequence. Looking around makes us realize everything around us follows a certain pattern/sequence of steps in order to achieve the desired result. Now this very realization leads us to the definition of workflow.

Workflow: Series of steps, decisions and rules needed to complete a specific task.

What is Activity?

We know what is workflow is, right? So what do we call those 'steps' that constitute a workflow? Your guess is correct. Those are activities.

Activities: Tasks/steps that define the workflow, these are basic building blocks of workflow.

Welcome to Workflow Foundation

Windows Workflow Foundation is a technology for defining, executing and managing workflows. This is one of three major frameworks (the other two are related to presentation and communication) that .NET 3.0 introduced. Critics have speculated about WF as being one of the major changes in middle-tier since the arrival of COM+ / DTC, and since Microsoft has plans for supporting it for current (Windows XP, 2003) and future (Vista) Windows releases, the use and popularity of WF is only going to increase.

Workflow Foundation consists of runtime, workflow library, services and a programming model. Workflow projects are not applications themselves, rather they constitute an application, so 'host' is needed for workflow runtime. As in the running loan-request workflow, a banking application will act like a 'host'. The host can be a: smart-client, ASP.NET worker thread, service, or a simple console application.

'Runtime' manages workflows, managing means creating workflow and responding to events like resuming, suspending, terminating, unloading etc.. As we have noticed, many business processes consist of similar activities but are used in different contexts. For example: conditional loops, parallel activities, and calling a web service are common activities that could be part of a different multitude of applications, so Microsoft has provided a base activity library that has a common set of usable activities. Of course, one can write their own custom activity or extend existing ones.

Services are another part of WF that help runtime perform various operations on workflow; again services can be extended / customized as needed. A few services that come with WF are: scheduling, transaction, persistence, tracking services.

There can be two major types of workflows:

  • Sequential: a series of activities are called in order.
  • State machine: activities are called on the basis of the 'state' of different parameters.

Both kinds of workflow solutions can be created in WF and since workflows are state-based, WF provides wonderful support like: if workflow has reached a state where it would remain untouched for few minutes/hours/days/months, then it would be 'persisted' and can then be restored on any different computer/platform without any hassle. This and many other features are part of WF.

Enough of theory and introduction; lets jump-start the party. But wait, we need to prepare our system for WF.

Preparing your PC for WF

You only need to have:

  1. .NET Framework 3.0
  2. Visual Studio 2005
  3. Visual Studio 2005 Extensions

All of the above can be downloaded via the internet. Just type in Google (something like'.NET framework 3.0 download') and click on the first link.

Lets start the show – First Workflow Solution

We will be creating a simple solution for flight booking system. It will be so rudimentary, I would not mind if you called it stupid. All it will do is:

  1. Ask for passenger name.
  2. Ask for city from where passenger wants to fly.
  3. Ask for destination city.
  4. Project will have list of cities in a dictionary. It will search city names in same.
  5. If it finds both cities in dictionary, it will display 'Booking confirmed'. (Assuming there is unlimited space in airplane and everyone can get a window seat!)
  6. Otherwise, apologize with passenger.

I forewarned you; this is an extremely simple scenario, but my objective is to show you how WF eases your job when you are working on this these kinds of workflow-based applications.

Now we're starting. Open up Visual Studio 2005 IDE and click on 'New Project'.

Select 'Sequential Workflow Console Application' as project type. As pointed out earlier, there are two types of workflows: sequential and state machine. Our chosen scenario follows a particular sequence and doesn't have any state machine involved in it, hence the selection.


Select an appropriate project name, mine is 'FirstWFProject'. Check the 'Location' of the project on disk drive and click 'OK'.

This will open up 'Workflow Designer'.


Workflow is currently empty and you can drag-drop any number of activities from the 'toolbox window' into it. But first we need to ask the user to input passenger name, the city from which they will depart, and the city in which they will arrive. So we will select 'Code Activity' and drop it on Workflow Designer.

Screenshot - image003.jpg

You can see from the 'properties' window that this new activity is named as 'codeActivity1'. To define what this code activity will do, we will click the 'Generate Handlers' hyperlink in 'properties' window. This will generate the default handler 'ExecuteCode' for this activity.

The following code will be produced after performing all of these steps.

public sealed partial class Workflow1: SequentialWorkflowActivity
    public Workflow1()
    private void codeActivity1_ExecuteCode(object sender, EventArgs e)

We will now add code for asking user input and declare a dictionary object that will have a list of city names that passengers can travel to/from. Since this crude console application, 'Console.ReadLine' will be used for input. After these modifications, the code will look like:

public sealed partial class Workflow1:SequentialWorkflowActivity
    public Dictionary<int, string>cities =
        new Dictionary<int, string>();

    public string FromCity;
    public string ToCity;

    public Workflow1()

        //populate cities dictionary

    private void codeActivity1_ExecuteCode(object sender, EventArgs e)
        Console.WriteLine("Enter Passenger Name : ");
        string passengerName = Console.ReadLine();

        Console.WriteLine("Enter Departure City :");
        this.FromCity = Console.ReadLine();
        Console.WriteLine("Enter Destination City :");
        this.ToCity = Console.ReadLine();          

The first activity of our workflow is complete. Now as per scenario specified above, we will 'check' the user's entered city names in our dictionary collection to ascertain do we have flights available as per user's requirement, and on the basis of this 'condition check', we will either display 'flight confirmed' or 'booking not available' on screen. So, since we are in need of a 'condition check' activity, we will drag/drop 'IfElseActivity' on our Workflow Designer. Then, (since we're after the condition check) we want to display a message on user console, so we will drag/drop two activities in each branch of 'IfEleseActivity'. This should look like:

Screenshot - image004.jpg

By default, IfElseActivity has only two branches, but right-clicking it and selecting 'Add Branch' will add more branches on it. Since we have only two possible outcomes of our condition check (the user's input cities will be in our dictionary collection or they won't be) two branches are enough for us.

Now we will have to add a condition for each branch condition. For that, click on the first branch and in the properties window, select 'Declarative Rule Condition' as 'Condition' (other option is to add condition in code). Give this condition a proper name (like 'FlightExists') and then click on Expression. This should bring up 'Select Condition' box. Click on 'Edit' to open up following 'Rule Condition Editor'.

Screenshot - image005.jpg

We have specified simple conditions to check whether both to and from cities are present in our dictionary collection. Now follow similar procedures to add conditions in another branch of 'IfElseActivity'. Name condition as 'FlightNotExists' and add the following condition in 'Rule Condition Editor'.

== True &&

== True &&

Note that we have only added '!' before condition to check user inputted city doesn't exists in our cities dictionary collection. 'Select Condition' dialog should look like following now.

Screenshot - image006.jpg

Now we only need to add code in 'code activities' inside 'IfElseActivity' to display appropriate message on the console. So select 'code activity2' in first branch, click 'Generate Handlers' in the properties window and add the following code.

private void codeActivity2_ExecuteCode(object sender, EventArgs e)
    Console.WriteLine("Flight Booking Confirmed!");

Similarly, add following code for 'code activity3'.

private void codeActivity3_ExecuteCode(object sender, EventArgs e)
    Console.WriteLine("Sorry, No Such Flight Exists!");

Our workflow completes here, now we need to 'run' it from runtime. Open up Program.cs and add following code in it.

static void Main(string[] args)
    using(WorkflowRuntime workflowRuntime = new WorkflowRuntime())
        AutoResetEvent waitHandle = new AutoResetEvent(false);
        workflowRuntime.WorkflowCompleted += delegate(object sender, 
            WorkflowCompletedEventArgs e){waitHandle.Set();};

        workflowRuntime.WorkflowTerminated += delegate(object sender, 
            WorkflowTerminatedEventArgs e)

        WorkflowInstance instance = 



There is not much science here. We created a new runtime object, provided two event handlers for 'Completed' and 'Terminated' statuses for Workflow. Then 'Create Workflow' is called to get an instance of our workflow and 'Start' is called to launch it.

Since the runtime engine will execute our workflow asynchronously, we need to block our thread on AutoResetEvent object and wait for workflow to complete (otherwise even before user could enter passenger name, the program will exit). Now, using AutoResetEvent means thread will be blocked until it is 'set' in complete event handler.

That's it buddies! Compile the application and run it. Console window will open up and based on user's input will display the appropriate message. The following are screen shots for both conditions (user inputted cities found / not found in dictionary collection).

Screenshot - image007.jpg

Screenshot - image008.jpg


We developed a simple 'sequential workflow' application with the help of 'code activity' and 'IfElseActivity'. The purpose of the article was to provide a launching pad to explore Window Workflow Foundation (WF), which I hope it did. We did very rudimentary examples in the article, but the point was to give an idea of how workflow-based business can be easily modeled, designed and implemented using WF.

Now as was already highlighted at the beginning of article, WF is the biggest thing in middle-tier since COM, so opportunities are endless and thankfully, we have a number of very good books/web casts available. Therefore, all I can say is "Good Luck with your Workflow Foundation cruise!"

What we learned in this article

The following were covered in this tutorial.

  • Basic introduction to Windows Workflow Foundation
  • How to prepare your computer for WF
  • Sequential Workflow
  • Code Activity
  • If Else Activity

Where to find more information

A Number of good resources are available on the subject. I personally would recommend reading:

  • Programming Workflow Foundation – Practical WF Techniques and Examples using XAML and C# by K. Scott Allen
  • Essential Windows Workflow Framework by DharmaShukla, BobSchmidt.
  • Apart from this, numbers of blogs/web casts are available in web space; you can easily find them using Google.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Ali Iqbal Khan
Software Developer (Senior) ITIM Systems
Pakistan Pakistan
Ali is Development Lead at ITIM Systems. He has got engineering degree in computer systems and likes to write about his experiences with Microsoft technologies. Ali's blog address is

Comments and Discussions

GeneralMy vote of 5 Pin
csharpbd3-Aug-14 18:39
professionalcsharpbd3-Aug-14 18:39 
QuestionAnother example Pin
Raja Chandrasekaran2-Aug-14 3:40
MemberRaja Chandrasekaran2-Aug-14 3:40 
GeneralMy vote of 5 Pin
KK Kod9-Sep-13 5:17
MemberKK Kod9-Sep-13 5:17 
GeneralMy vote of 5 Pin
SAHIBas2-Sep-13 20:48
MemberSAHIBas2-Sep-13 20:48 
GeneralMy vote of 5 Pin
tamarana tirumalesh8-Aug-13 18:48
Membertamarana tirumalesh8-Aug-13 18:48 
GeneralMy vote of 4 Pin
Laurent Perzyk23-Mar-13 5:07
MemberLaurent Perzyk23-Mar-13 5:07 
GeneralMy vote of 5 Pin
WilEpic4-Mar-13 12:20
MemberWilEpic4-Mar-13 12:20 
GeneralMy vote of 3 Pin
Prasyee3-Feb-13 22:06
MemberPrasyee3-Feb-13 22:06 
GeneralNice Article Pin
PratimaG28-Jan-13 6:19
MemberPratimaG28-Jan-13 6:19 
GeneralArticle Pin
Shivarajbk20-Dec-12 23:59
MemberShivarajbk20-Dec-12 23:59 
GeneralMy vote of 5 Pin
Kanasz Robert5-Nov-12 0:44
professionalKanasz Robert5-Nov-12 0:44 
GeneralMy vote of 5 Pin
Arun_angel17-Sep-12 4:25
MemberArun_angel17-Sep-12 4:25 
QuestionExcellent Pin
idkfaa26-Aug-12 3:04
Memberidkfaa26-Aug-12 3:04 
GeneralMy vote of 5 Pin
Ezz Khayyat1-Aug-12 1:20
professionalEzz Khayyat1-Aug-12 1:20 
QuestionGreat Pin
IndiaMH16-Feb-12 20:56
MemberIndiaMH16-Feb-12 20:56 
QuestionIfElseBranchActivity2 condition Pin
Altaf N Patel27-Sep-11 21:15
MemberAltaf N Patel27-Sep-11 21:15 
AnswerRe: IfElseBranchActivity2 condition Pin
djm041217-Apr-12 2:47
Memberdjm041217-Apr-12 2:47 
GeneralMy vote of 5 Pin
Altaf N Patel27-Sep-11 21:13
MemberAltaf N Patel27-Sep-11 21:13 
QuestionVisual C# Express 2008 support Pin
superfly7131-Aug-11 23:37
professionalsuperfly7131-Aug-11 23:37 
GeneralWindows Workflow Foundation to be avoided at all costs ! Pin
damnedyankee24-Feb-11 2:14
Memberdamnedyankee24-Feb-11 2:14 
GeneralRe: Windows Workflow Foundation to be avoided at all costs ! Pin
Chris Mankowski8-Mar-12 18:38
MemberChris Mankowski8-Mar-12 18:38 
GeneralThanks! Pin
cs2data27-Jan-11 2:28
Membercs2data27-Jan-11 2:28 
GeneralGreat Example Pin
Jake Bautista22-Jul-10 13:50
MemberJake Bautista22-Jul-10 13:50 
GeneralCute Example Pin
GautamBSharma20-Apr-10 1:58
MemberGautamBSharma20-Apr-10 1:58 
GeneralNice Article Pin
Vinod Satapara25-Mar-10 23:22
MemberVinod Satapara25-Mar-10 23:22 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.