Click here to Skip to main content
Click here to Skip to main content

Jump start Windows Workflow Foundation

, 17 Apr 2007 CPOL
Rate this:
Please Sign up or sign in to vote.
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 Amazon.com, 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.

image001.jpg

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'.

image002.jpg

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()
    {
        InitializeComponent();
    }
    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()
    {
        InitializeComponent();

        //populate cities dictionary
        cities.Add(1,"medina");
        cities.Add(2,"london");
        cities.Add(3,"houston");
        cities.Add(4,"karachi");
        cities.Add(5,"tokyo");
        cities.Add(6,"singapore");
        cities.Add(7,"istanbul");
        cities.Add(8,"seattle");
    }

    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'.

!this.cities.ContainsValue(this.FromCity.ToLower())
== True &&

!this.cities.ContainsValue(this.ToCity.ToLower())
== 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!");
    Console.ReadKey();
}

Similarly, add following code for 'code activity3'.

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

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)
        {
            Console.WriteLine(e.Exception.Message);
            waitHandle.Set();             
        };

        WorkflowInstance instance = 
            workflowRuntime.CreateWorkflow(typeof(FirstWFProject.Workflow1));

        instance.Start();

        waitHandle.WaitOne();
    }
}

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

Conclusion

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.

License

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

Share

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 http://aliwriteshere.wordpress.com

Comments and Discussions

 
GeneralMy vote of 5 Pinmembercsharpbd3-Aug-14 19:39 
QuestionAnother example PinmemberRaja Chandrasekaran2-Aug-14 4:40 
GeneralMy vote of 5 PinprofessionalK K Kodoth9-Sep-13 6:17 
GeneralMy vote of 5 PinmemberSAHIBas2-Sep-13 21:48 
GeneralMy vote of 5 Pinmembertamarana tirumalesh8-Aug-13 19:48 
GeneralMy vote of 4 PinmemberLaurent Perzyk23-Mar-13 6:07 
GeneralMy vote of 5 PinmemberWilEpic4-Mar-13 13:20 
GeneralMy vote of 3 PinmemberPrasyee3-Feb-13 23:06 
GeneralNice Article PinmemberPratimaG28-Jan-13 7:19 
GeneralArticle PinmemberShivarajbk21-Dec-12 0:59 
GeneralMy vote of 5 PinmvpKanasz Robert5-Nov-12 1:44 
GeneralMy vote of 5 PinmemberArun_angel17-Sep-12 5:25 
QuestionExcellent Pinmemberidkfaa26-Aug-12 4:04 
GeneralMy vote of 5 PinmemberEzz Khayyat1-Aug-12 2:20 
QuestionGreat Pinmemberbhavisachin16-Feb-12 21:56 
QuestionIfElseBranchActivity2 condition PinmemberMember 327776027-Sep-11 22:15 
Hi, nice explanation. need have one change in IfElseBranchActivity2 condition. the condition should be as follows:
!this.cities.ContainsValue(this.FromCity.ToLower()) == True || !this.cities.ContainsValue(this.ToCity.ToLower()) == True
 
Thanks & Regards
Altaf
patel

AnswerRe: IfElseBranchActivity2 condition Pinmemberdjm041217-Apr-12 3:47 
GeneralMy vote of 5 PinmemberMember 327776027-Sep-11 22:13 
QuestionVisual C# Express 2008 support PinmemberWang Chun Hsun1-Sep-11 0:37 
GeneralWindows Workflow Foundation to be avoided at all costs ! Pinmemberdamnedyankee24-Feb-11 3:14 
GeneralRe: Windows Workflow Foundation to be avoided at all costs ! PinmemberChris Mankowski8-Mar-12 19:38 
GeneralThanks! Pinmembercs2data27-Jan-11 3:28 
GeneralGreat Example PinmemberJake Bautista22-Jul-10 14:50 
GeneralCute Example PinmemberGautamBSharma20-Apr-10 2:58 
GeneralNice Article Pinmembervinod satapara26-Mar-10 0:22 
Questionis the code right? Pinmemberhenu20-Jan-10 12:39 
GeneralGood Pinmemberrasheed197911-Jan-10 23:31 
GeneralGr8 PinmemberDev-Rama16-Dec-09 3:41 
GeneralI can not find 'Select Condition' dialog Box Pinmembere_yaghoobi29-Nov-09 0:21 
GeneralRe: I can not find 'Select Condition' dialog Box Pinmembernavi.milkyway1-Mar-10 19:41 
GeneralRe: I can not find 'Select Condition' dialog Box Pinmemberlohithrao26-Mar-13 20:18 
GeneralVery nice article PinmemberMember 15911276-Oct-09 0:39 
GeneralGeneric Workflow PinmembereOrdinary23-Sep-09 21:55 
GeneralThanks a ton! Pinmembershripadlale9-May-09 15:41 
GeneralDictionary Error PinmemberJames.Hastings27-Apr-09 4:37 
GeneralThanks Pinmembertoanlh18-Mar-09 19:15 
GeneralSeems too complex for me ^_^v Pinmembercairoso17-Mar-09 18:49 
GeneralExcellent Article Pinmemberjaydeepvishwakarma13-Mar-09 3:46 
GeneralThanks Pinmembersayedks00720-Dec-08 23:24 
Generalneed help for wwf exampls on webbased PinmemberSudarsanavarma_P28-Jul-08 0:10 
GeneralPlease I want to do a similar web application but not console Pinmembersohair zaki15-Jul-08 11:19 
GeneralThanks! PinmemberCy_Chosis26-Jun-08 13:52 
GeneralRe: Thanks! PinmemberE! Ray K4-Oct-08 7:18 
GeneralThanks for a simple article to get started with workflows PinmemberProjectRosari16-Nov-07 11:16 
GeneralWhen to use workflows PinmemberHazz Polo16-Jul-07 12:50 
GeneralDidn't need "FlightNotExists" condition Pinmembered_cartagena18-Jun-07 11:09 
GeneralRe: Didn't need "FlightNotExists" condition PinmemberE! Ray K4-Oct-08 6:47 
GeneralRe: Didn't need "FlightNotExists" condition Pinmemberlagdaemon4-Oct-08 16:55 
GeneralRe: Didn't need "FlightNotExists" condition Pinmembernavi.milkyway1-Mar-10 19:47 
GeneralGood simple article Pinmemberstandgale12-Jun-07 17:58 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.1411023.1 | Last Updated 17 Apr 2007
Article Copyright 2007 by Ali Iqbal Khan
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid