Click here to Skip to main content
15,169,140 members
Articles / Programming Languages / C#
Posted 20 Sep 2007


21 bookmarked

Windows Workflow Foundation - State Machine Workflow Example

Rate me:
Please Sign up or sign in to vote.
3.07/5 (16 votes)
20 Sep 2007CPOL5 min read
An article describing how to program with Windows Workflow Foundation which comes with .NET Framework 3.0


This article describes how to create and run a State Machine Workflow in Windows Workflow Foundation (formerly WWF, or just WF) which comes bundled with .NET Framework 3.0 and above.

Before we get started, if you are new to WF and .NET Framework 3.0, I think you'd better take a look at some articles about WF. Here are some useful links:


In order to create WF applications, you need to install some required packages/tools.

These are:

  1. .NET Framework 3.0 Runtime
  2. Visual Studio 2005 Professional Edition
  3. Windows Workflow Foundation extensions for Visual Studio 2005
  4. Windows Communication Foundation (WCF,formerly Indigo) & Windows Presentation Foundation (WPF,formerly Avalon)

The fourth one is optional in fact. However, there may be some troubles and you may get some weird error if you don't have WCF and WPF installed on your development computer. So, I suggest you have WCF and WPF installed too.

Now, I want to demonstrate a daily life example. Assume that you want to lock something (A file, a safe, a door,...etc.). This locker has exactly 2 different states: LOCKED and UNLOCKED. And you change its state by opening and closing. In our application, we call some methods to change workflows state; from/to LOCKED to/from UNLOCKED.

Using the Code

Let's dig in the code.

First we open .NET Visual Studio 2005. In the Start Page window, click Project from Create row. In the New Project window, extend Visual C# node, then select Workflow. There are many applications but we will create a state machine application so we select State Machine Workflow Library and name it FirstStateMachineWorkflow. Then click OK.

Screenshot - 1.jpg

After creating the application, your designer window should look like this:

Screenshot - 2.jpg

NOTE: If you can't see Workflow1.cs[Design] or if there is something wrong with the steps above, go check the requirements. Probably you missed some of them or they are not installed properly.

Now, we need an interface to declare the events. Right click the project -> Add -> New Item -> Select Interface and name it ILocker.cs. Write the code below to the interface.

using System;
using System.Collections.Generic;
using System.Text;
using System.Workflow.Activities;

namespace FirstStateMachineWorkflow
    public interface ILocker
        event EventHandler<ExternalDataEventArgs> Lock;
        event EventHandler<ExternalDataEventArgs> Unlock;

Lock and Unlock are our events which make the workflow change its state. Now we need a class implementing this interface and having the methods to fire the events. Right click the project -> Add -> New Item -> Select Class and name it Locker.cs. Write the code given below to the class:

using System;
using System.Collections.Generic;
using System.Text;
using System.Workflow.Activities;

namespace FirstStateMachineWorkflow
    public class Locker : ILocker
        public event EventHandler<ExternalDataEventArgs> Lock;
        public event EventHandler<ExternalDataEventArgs> Unlock;

        public bool lockerState = false;

        public bool LockIt(Guid InstanceID)
            if (this.Lock != null)
                    new System.Workflow.Activities.ExternalDataEventArgs(InstanceID));
                return true;
                return false;

        public bool UnlockIt(Guid InstanceID)
            if (this.Unlock != null)
                    new System.Workflow.Activities.ExternalDataEventArgs(InstanceID));
                return false;
                return true;

As you see Locker class uses events to change the workflows state. These two methods (LockIt and UnlockIt) are going to be used by the host application.

Now, we go back to our workflow designer window. Open Workflow1.cs[Designer]. Click the state and in the properties window, change its name as Unlocked. On the right-hand side tool box, drag and drop EventDrivenActivity on the state. Change its name as LockEvent and double-click. This will open a new design window. On the toolbox, drag and drop HandleExternalEventActivity and change its name to HandleLockEvent. This will help us to handle the event fired by the host application. While HandleLockEvent is selected, in the properties window, click the InterfaceType property. A new window will open, there, select ILocker. This is needed to define which events are handled by which event handler. Now, above in the properties window, select Lock in the EventName combo-box. So far, we made the Lock event to be handled by this handler. But after handling, we want to write a message to the console stating which event is handled. To do this, drag and drop a CodeActivity from toolbox, name it LockedCode, double click it. You will go to Code View. There in the LockedCode_ExecuteCode method, write the code below:

private void WriteState_ExecuteCode(object sender, EventArgs e)

So, we handled the event, wrote the message, what next? Now we must do something to change the current state. From toolbox drag and drop a new StateActivity to Workflow1.cs[Design] and name it as Locked. Now in HandleLockedEvent view, drag and drop SetStateActivity under code activity. Name it as SetLocked and in the properties window, set TargetStateName as Locked.

Do the same steps for Locked state reversed and properly. Drag drop HandleUnlockEvent, add UnlockedCode and SetUnlocked to Unlocked.

After all these changes, your Workflow1.cs[Designer] should look like this :

Screenshot - 4.jpg

Now it is time to add a host application to the solution.

NOTE : Remember, Windows Workflows (be it State Machine or Sequential Workflow) cannot run by themselves. They need an external host application. The application may be a Windows application, Console Application or Web Application (ASP.NET).

Right click solution -> Add -> New Project. In the New Project window, select Visual C# and select Console Application , name it Test.

After creating the console application, right click on the console application and select Set As StartUp Project. We must add reference to use workflow methods. To do that, right click References -> Add Reference -> In .NET tab, select System.Workflow.Activities, System.Workflow.Runtime, System.Workflow.ComponentModel.

Screenshot - 6.jpg

We need FirstStateMachineWorkflow reference also. References -> Add Reference -> In Projects tab, select FirstStateMachineWorkflow and click OK.

Screenshot - 5.jpg

In Program.cs, write the code given below to run the workflow:

using System;
using System.Collections.Generic;
using System.Text;
using System.Workflow;
using System.Workflow.Activities;
using System.Workflow.Runtime;
using FirstStateMachineWorkflow;

namespace Test
    class Program
        static void Main(string[] args)
            WorkflowRuntime workflowruntime = new WorkflowRuntime();
            Locker locker = new Locker();
            Guid locker_ID = Guid.NewGuid();
            Dictionary<string,object> Params = new Dictionary<string,object>();
            ExternalDataExchangeService ExDateExchService =
                    new ExternalDataExchangeService();
            WorkflowInstance wfinstance = workflowruntime.CreateWorkflow(
                typeof(Workflow1) , Params , locker_ID );





Here, WorkflowRuntime object is used to configure workflow properties, Locker is our class implementing interface. Dictionary is to pass parameters to workflow. However, we don't have any parameters in our example.

WorkflowInstance wfinstance = workflowruntime.CreateWorkflow(
      typeof(Workflow1) , Params , locker_ID );

WorkflowInstance is used to create an instance of our Workflow1 workflow and then it is started with the wfinstance.Start method.

After running this application, you should get this console window:

Screenshot - 7.jpg

Points of Interest

As I mentioned before, WF itself is not enough to create WF applications. You may have WCF and WPF installed as well as WF.

And to summarize the steps again:

  1. Create a workflow statemachine application.
  2. Write an Interface for transitions between states (Write events).
  3. Write the [Serializable] class implementing the interface events and calling them
    in functions.
  4. Create a host application which uses the class and starts workflow.


20th September, 2007: First release


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


About the Author

Olgun Cengiz
Turkey Turkey
Software Developer

Ege University
Computer Engineering Department

Comments and Discussions

GeneralPerfect Example Pin
ArchAngel12327-Oct-14 6:37
MemberArchAngel12327-Oct-14 6:37 
QuestionEventHandler is always null :( can u give me any clues? Pin
Member 279212320-Aug-10 12:51
MemberMember 279212320-Aug-10 12:51 
AnswerRe: EventHandler is always null :( can u give me any clues? Pin
Member 368888627-Aug-10 1:43
MemberMember 368888627-Aug-10 1:43 
GeneralGood Starter for simple state WF Pin
Ashutosh Phoujdar26-Mar-10 9:34
MemberAshutosh Phoujdar26-Mar-10 9:34 
I would like to hear if you have any example for persisting WF state data into database Smile | :)

Generaltebrikler Pin
moguzalp116-Feb-10 1:58
Membermoguzalp116-Feb-10 1:58 
GeneralMy vote of 1 Pin
Corey Fournier13-Jan-10 11:38
MemberCorey Fournier13-Jan-10 11:38 
GeneralMy vote of 1 Pin
Thiagarajan Rajendran11-Dec-09 12:46
MemberThiagarajan Rajendran11-Dec-09 12:46 
GeneralAn unhandled exception of type 'System.Workflow.Activities.EventDeliveryFailedException' occurred Pin
jnilson_9920-Aug-09 9:57
Memberjnilson_9920-Aug-09 9:57 
GeneralRe: An unhandled exception of type 'System.Workflow.Activities.EventDeliveryFailedException' occurred Pin
zzmharbison25-Aug-09 10:28
Memberzzmharbison25-Aug-09 10:28 
GeneralRe: An unhandled exception of type 'System.Workflow.Activities.EventDeliveryFailedException' occurred Pin
Anand Innani24-Sep-09 5:16
MemberAnand Innani24-Sep-09 5:16 
Questionhow can i get the sourcecode Pin
yojing3-Aug-09 18:17
Memberyojing3-Aug-09 18:17 
GeneralMy vote of 1 Pin
Umesh Toranagatti31-Mar-09 21:11
MemberUmesh Toranagatti31-Mar-09 21:11 
QuestionNo Code?? Pin
Aziz ur Rahman27-Aug-08 7:08
MemberAziz ur Rahman27-Aug-08 7:08 
Questionhow do u called locked and unlocked event handlers defined in ILocker interface????? Pin
User-Rock13-May-08 2:29
MemberUser-Rock13-May-08 2:29 
AnswerRe: how do u called locked and unlocked event handlers defined in ILocker interface????? Pin
Member 279212320-Aug-10 13:42
MemberMember 279212320-Aug-10 13:42 
GeneralThis works Pin
Joel Palmer26-Mar-08 12:44
MemberJoel Palmer26-Mar-08 12:44 
Generalso confused Pin
Rasha Ali11-Mar-08 2:53
MemberRasha Ali11-Mar-08 2:53 
GeneralStatemachine workflow with tracking service Pin
Member 421342530-Dec-07 6:32
MemberMember 421342530-Dec-07 6:32 
Generalbad link Pin
vojtan121-Dec-07 4:24
Membervojtan121-Dec-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.