Click here to Skip to main content
15,867,308 members
Articles / Programming Languages / C#
Article

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 399.3K   4.2K   228   72
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.

C#
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:

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

C#
!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.

C#
private void codeActivity2_ExecuteCode(object sender, EventArgs e)
{
    Console.WriteLine("Flight Booking Confirmed!");
    Console.ReadKey();
}

Similarly, add following code for 'code activity3'.

C#
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.

C#
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)


Written By
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

 
GeneralError Pin
God_15-Apr-07 13:16
God_15-Apr-07 13:16 
GeneralRe: Error Pin
Ali Iqbal Khan15-Apr-07 21:07
Ali Iqbal Khan15-Apr-07 21:07 
GeneralRe: Error Pin
God_16-Apr-07 6:54
God_16-Apr-07 6:54 
GeneralRe: Error Pin
Ali Iqbal Khan17-Apr-07 9:50
Ali Iqbal Khan17-Apr-07 9:50 
AnswerRe: Error Pin
ProjectRosari16-Nov-07 10:10
ProjectRosari16-Nov-07 10:10 
Generalvery goog Pin
mnaveed10-Apr-07 0:15
mnaveed10-Apr-07 0:15 
GeneralRe: very good Pin
Ali Iqbal Khan10-Apr-07 21:21
Ali Iqbal Khan10-Apr-07 21:21 
GeneralA couple of notes... Pin
fooguru9-Apr-07 5:39
fooguru9-Apr-07 5:39 
A couple of things...

- It is not immediately apparent that to get the "Select Condition" window you need to click on the ellipsis next to "ConditionName" with an IfElseBranchActivity selected.

- The expression / rule condition for "FlightNotExists" should use an or instead of an and, otherwise a fall through condition exists when choosing a flight from a known from city to an unknown to city.

Great introductory article!
GeneralRe: A couple of notes... Pin
Ali Iqbal Khan9-Apr-07 21:08
Ali Iqbal Khan9-Apr-07 21:08 
GeneralRe: A couple of notes... Pin
ProjectRosari16-Nov-07 10:12
ProjectRosari16-Nov-07 10:12 
QuestionCan you give some advice about customize workflow Pin
alantu5-Apr-07 4:22
alantu5-Apr-07 4:22 
AnswerRe: Can you give some advice about customize workflow Pin
Ali Iqbal Khan8-Apr-07 18:43
Ali Iqbal Khan8-Apr-07 18:43 
GeneralRe: Can you give some advice about customize workflow Pin
alantu9-Apr-07 16:40
alantu9-Apr-07 16:40 
QuestionMohammad to medina - yes,John to Singapor -no [modified] Pin
dooskoobi3-Apr-07 2:41
dooskoobi3-Apr-07 2:41 
AnswerRe: Mohammad to medina - yes,John to Singapor -no Pin
Farrukh_53-Apr-07 4:35
Farrukh_53-Apr-07 4:35 
AnswerRe: Mohammad to medina - yes,John to Singapor -no Pin
Ali Iqbal Khan3-Apr-07 5:19
Ali Iqbal Khan3-Apr-07 5:19 
GeneralRe: Mohammad to medina - yes,John to Singapor -no Pin
dooskoobi3-Apr-07 8:37
dooskoobi3-Apr-07 8:37 
GeneralAmazing !!! Pin
Sidhartha Shenoy2-Apr-07 21:51
Sidhartha Shenoy2-Apr-07 21:51 
GeneralRe: Amazing !!! Pin
Ali Iqbal Khan2-Apr-07 22:07
Ali Iqbal Khan2-Apr-07 22:07 
GeneralMaybe Part II Pin
NormDroid28-Mar-07 4:24
professionalNormDroid28-Mar-07 4:24 

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.