WF Tutorial, Part 3: Create and host Workflow services


16. February 2015 Workflow Foundation 4

This tutorial is the third part of Dispatcher Timer Windows Workflow Foundation tutorial series.

<< Create a simple Workflow

This tutorial demonstrates how to create a simple Workflow Service and host it in a Web Application. This sample is using Visual Studio 2013 with .NET 4.5.1. The example simply gets a value as the service parameter, squares it, and returns it to the service caller.

In this tutorial:

Create a Workflow service activity

Host the Workflow Service

Test the Workflow Service

Create a Workflow service activity

  • Open Visual Studio and create a New Class Library.

Remove the Class1.cs which Visual Studio creates by default, from the project.

  • Add a new Workflow Activity to the project and name it SquareActivityService.xaml

Note that the following references will be added to the project. These references are necessary for Workflow projects.

  • Open the SquareActivityService.xaml and from the Toolbox drag and drop the ReceiveAndSendReply Activity under Messaging group to the designer.

The following activities will be added to the designer.

  • Select the Sequence, open the variable tab, and add the following variables:

_number will be used as input to the service and after calculation the result will be stored in _result and will be returning to the service caller.

  • Drag and drop an Assign activity under Primitives in to the designer between the Receiveand SendReplyToReceiveactivities.

    In the To type: _result

    In the C# expression box type: _number * _number

  • Click on the Receive activity and change the OperationName to “Calculate”.

  • In the Receive activity click on the box next to Content. Expand the Parametersand Add a new parameter as below.

In this step we are defining our service parameters. In this case we create a parameter number on type Int32 and assigned it to the _number variable which we have created before. The same way other parameters can be added to the workflow service.

  • In the SendReplyToService activity click on the box next Content. Expand the parameter and Add a new parameter as below:

In this case we are defining the data which our service gonna return back to the caller. Here we have added a parameter called result of type Int32 which will be store the data from the variable _result.

  • Click on the Receive activity and open the Property Window (Press F4). Modify the properties as below.

  • Take note that the Operation Name is “Calculate”. This will be the same name as the operation in WCF. The caller will see this as a method so she can call it from the service proxy.
  • Change the ServiceContractName to “ISquareService”. This will be the service contract which is the same as WCF service contract. Make sure to put an “I” before the name as in WCF service contracts are an Interface (just to make our naming standard).
  • Check the CanCreateInstance check box. This is to enable the workflow service to be able to return the result through the proxy back to the caller.
  • That’s all J

Host the Workflow Service

  • In the same solution create a New ASP.NET Empty Web Application and name it “SquareService.Host”.

  • Add a reference to SquareService project.

The solution looks like below:

  • Open the Web.Config and modifies it as below

Take note of the highlighted sections:

  • The relative address in the service activation is the service address which we can access to the service.
  • The service section is the full qualified service name, which the same name as our activity name.
  • In the service endpoint section the contract name is the same name we have specified in the Receive activity properties.

Test the Workflow Service

  • Set the web application as startup project in the solution and run it (by either press F5, or pressing Ctrl+F5).
  • The service will be opened in a browser. Enter the service relative address in the browser.

You will see the service is up and available. You can also look in to the WSDL definition by click on the links provided in the page.

  • Open Visual Studio WCF Test Client to test the service. Add the service in the WCF Test Client.

You will see that the Calculate operation of our work flow service is available.

  • Double click on Calculate operation to open it. In the Request section enter any number and press the Invoke button. You will see the result of the calculation will be appearing in the Response section.

Take note that the variable name is the same as what we have define in the list of parameters in our Receive activity.


WF Tutorial, Part 2: Create a simple Workflow


15. December 2013 Workflow Foundation 13

This tutorial is the second part of Dispatcher Timer Windows Workflow Foundation tutorial series.
<< An Introduction to Windows Workflow Foundation
Create and host Workflow services >>

Download the sample project

In this tutorial I’m going to show you how you can create a very simple Workflow application to ask the user’s name and greets her using C#. Visual Studio 2013 and .NET 4.5 is used in this tutorial.

Task 1: Create a new Workflow Console Application Project.

  • Open Visual Studio
  • Choose File, New, Project and Select Workflow Console Application under Installed, Template, Visual C#, WorkFlow project type.

  • Choose any project name you want and press <OK>
  • The Visual Studio will be creating a Workflow1.xaml file for you. Simply remove the file from the solution explorer.

Task 2: Create a simple Workflow to display a message

As it has been mentioned in the introduction to this WF tutorial series everything in Workflow is an activity. Activities are functional units of a Workflow. They can perform a simple task like displaying massage to the user or more complicated tasks made from combination of different other activities. We are going to use the WriteLine Activity to simply display a message.

  • Right click on the Project; Add, New Item, and select Activity from Installed, Visual C# Items, Workflow Item type.
  • Name the activity HelloLiza.xaml and Press <OK>

  • The workflow designer will be opened.
  • From the Toolbox (Ctrl + Alt + x) drag and drop a WriteLine Activity under Primitives category into the Workflow designer.

    WriteLine activity is used to display a string in a console the same way as Console.WriteLine() method.

    The Text attribute of the WriteLine Activity gets a string or you can enter a C# statement.

  • Select the Text box and enter “Hello Liza”.

Let’s run our application and see how it works. Before build the application we need to modify the Program.cs to run our new Workflow.

  • Double click on Program.cs
  • Modify the code as below

Take note that we have changed the Workflow1 initializer class to HelloLiza. For every new Workflow, we are actually creating a class. On the 5th line we are creating an Activity object based on our Workflow. WorkflowInwoker is a simple class which its Invoke
method is used to invoke a Workflow. Why I said simple class because System.Acitivities provides different methods to invoke a workflow. WorkflowInvoker is useful for synchronous execution of workflows. For long-running Workflows or Workflows which use PersistenceStores you need to use WorkflowApplication class.

To execute the Workflow:

  • Build your solution (Ctrl + Shift + B) and run your application (Ctrl + F5)

Task 3: Extend the WorkFlow to accept an input from user

We are going to extend our example and ask the user for her name and to greets her using her name and showing her the current time. To do this we need add Variables to our workflow.

  • Open the HelloLiza.xaml
  • From the Toolbox drag and drop an Assign activity above the WriteLine activity which we have added previously.

    Notice that when you drop that activity WF designer will automatically be creating a SequenceActivity for you.

You can see a small blue exclamation mark on the top-right side of the Assign and Sequence activities. This is the WF’s way to tells you that there is an error in the workflow.

  • Opens the Variables tab at the bottom-left side the Workflow Designer

Initially there is no variable in the list and you cannot even add any. You need to select the activity (the scope) which you want to add the variable to.

  • Select the Sequence activity in the designer.
  • In the Variables tab click on Create variable and type “name” for the Variable Name.
  • In the Variable Type column you can select any type. The default is String which is what we want.

Modify the Assign Activity to accept the user’s input. The Assign part of the activity accepts a variable which will be assigned the value provided on the on the textbox on the right side of the equal sign. Any C# expression can be entered to be assigned to the variable.

  • Type the variable’s name which we’ve just created (i.e. name) in the To textbox

    Notice that by typing the variable name Visual Studio provides you with intellisense same as you are writing a C# code

  • Type the following code in the Expression textbox

Take note that you can modify the attributes of an activity from the Properties window too. Especially when you are writing a pretty long C# code in the Expression text box which is so small in the WF designer. To do so just click on the activity you want to change its attribute and in the properties window click on the Browse button […] of the Value attribute. It will open a textbox which is pretty bigger than the designer so you can enter your C# expression there.

To show the entered name by user let’s modify the WriteLine activity.

  • Enter the following line in the Expression textbox (or alternatively in the Properties window)

You can see we can concatenate a string in the Expression textbox. In the line we are showing a greeting message along with the today’s date.

The last task is adding another WriteLine activity above the Assign activity asking the user to enter her name:

  • Drag and drop a WriteLine activity above the Assign activity
  • Enter the following line in the Expression textbox:

The final workflow should be the same as bellow:

  • Build the solution (Ctrl + Shift + B) and run the application (Ctrl + F5)
  • Enter your name and press enter

That’s all for this tutorial.

<< An Introduction to Windows Workflow Foundation

WF Tutorial, Part 1: An Introduction to Windows Workflow Foundation


08. December 2013 Workflow Foundation 0

This tutorial is the first part of Dispatcher Timer Windows Workflow Foundation tutorial series.

Part 2: Create a simple Workflow >>

In this article I am going to explain what Windows Workflow Foundation is and what its building blocks are. The contents of this article is mostly based on MSDN articles on WF, the book Professional C# 2012 and .NET 4.5 by Christian Nagel, and my own works and experiences on WF.


WF provides a model to define and execute processes using a set of building blocks called activities. As a workflow executes, it may need to access the outside world, as well as a workflow may need to save and restore its state.

A workflow is constructed from a number of activities, and these activities are executed at runtime. A number of built-in activities can be used for general-purpose work, and you can also create your own custom activities and plug these into the workflow as necessary.


A workflow models a production process as a set of activities applied to work in progress. As such, workflows describe the order of execution and dependency relationships between activities as the work progresses through the model from start to finish, as activities are performed by people or system functions.

Workflow Runtime Engine

Every running workflow instance is created and maintained by an in-process runtime engine that is commonly referred to as the workflow runtime engine. There can be several workflow runtime engines within an application domain, and each instance of the runtime engine can support multiple workflow instances running concurrently.

When a workflow model is compiled, it can be executed inside any Windows process including:

  • console applications,
  • forms-based applications,
  • Windows Services,
  • ASP.NET Web sites, and
  • Web services.

Because a workflow is hosted in process, a workflow can easily communicate with its host application.


Activities are the elemental unit of a workflow. Everything in a workflow is an activity, including the workflow itself. The term workflow is actually a synonym for a collection of activities. They are added to a workflow programmatically in a manner similar to adding XML DOM child nodes to a root node. When all the activities in a given flow path are finished running, the workflow instance is completed.

There are different types of activities which derived from the base class Activity:

  • NativeActivity
  • CodeActivity
  • AsyncCodeActivity
  • ActivityWithResult
    • Activity<T>
      • NativeActivity<T>
      • CodeActivity<T>
      • AsyncCodeActivity<T>

An activity can perform a single action, such as writing a value to a database, or it can be a composite activity and consist of a set of activities.

Activities deriving from CodeActivity and AsyncCodeActivity can do far less with their container compare to NativeActivity. For example, the WriteLine activity needs to write only to the console. Therefore, it doesn’t need access to its runtime environment. A more complex activity might need to schedule other child activities or communicate with other systems, in which case you must derive from NativeActivity to access the full runtime.

Activities have two types of behavior:

  • runtime: specifies the actions upon execution.
  • design
    time: controls the appearance of the activity and its interaction while being displayed within the designer.


The workflow runtime engine uses many services when a workflow instance runs. Windows Workflow Foundation provides default implementations of the runtime services that meet the needs of many types of applications, such as a persistence service, which stores the execution details of a workflow instance in a SQL database. These service components are pluggable, which allows applications to provide these services in ways that are unique to their execution environment. Other types of services used by the runtime engine include scheduling services, transaction services, and tracking services.

Custom services can be created to extend the Windows Workflow Foundation platform by deriving from the base service classes. An example of this would be a persistence service that uses an XML file instead of a database for storage.

Compensation Overview

Compensation is the act of undoing any actions that were performed by a successfully completed compensable activity because of an exception that occurred elsewhere in a workflow.

Local Communication and Correlation

Host processes can communicate with workflows by exchanging data through custom local communication services. These local communication services implement user-defined interfaces that define methods and events that will be passed between the workflow and the host process.

Host processes can also interact with a specific activity in a specific workflow instance by using a unique ID that is passed between the host process and the workflow as an event argument. This is known as correlation.


Windows Workflow Foundation simplifies the process of creating stateful, long-running, persistent workflow applications. The workflow runtime engine manages workflow execution and enables workflows to remain active for long periods of time and survive application restarts. This durability is a key tenet of Windows Workflow Foundation. It means that workflows can be unloaded from memory while awaiting input and serialized into a persistent store, such as a SQL database or XML file. Whenever the input is received, the workflow runtime engine loads the workflow state information back into memory and continues execution of the workflow.

Windows Workflow Foundation provides the SqlWorkflowPersistenceService that integrates well with Microsoft SQL Server to persist workflow information easily and efficiently. You can also create your own persistence service to store workflow state information anywhere you want by deriving from the WorkflowPersistenceService base class.


Tracking is the ability to specify and capture information about workflow instances and store that information as the instances execute. Windows Workflow Foundation provides the SqlTrackingService, which is a tracking service that uses a SQL database to store the collected tracking information. You can also write your own tracking service to collect and store this information in any format that your application requires.

When a new workflow is created, the tracking service requests a tracking channel to be associated with that workflow. All of the tracking information from the workflow is then sent to this tracking channel.

The tracking service can track three types of events:

  • Workflow instance events,
  • Activity events, and
  • User events.

You can configure the type and amount of information that your service wants to receive for a particular workflow instance or types of workflow by providing a tracking profile.

The tracking framework also provides the ability to extract information about activities or the workflow during an event. If a specific property or field in your activity or workflow needs to be tracked, you can provide this information in the extracts section of the tracking profile, and that information will be extracted during the specified event.


Workflows, activities, and rules can be serialized and deserialized. This enables you to persist them, use them in workflow markup files, and view their properties, fields, and events in a workflow designer.

Windows Workflow Foundation provides default serialization capabilities for standard activities, or you can create your own for custom activities. For example, with a custom activity serializer, you can decide which members are serialized and how they are serialized. This determines if those members are visible or hidden in a workflow designer.

Workflow Changes

Windows Workflow Foundation enables you to dynamically update your workflow instance and declarative rules during run time. Before activities are scheduled for execution, you can change expected behaviors, flow control, and so on. This ability enables you to modify business processing logic without having to recompile and restart your workflow.

Rules and Conditions

Windows Workflow Foundation can implement business logic as either rules or conditions.


Conditions are used by IfElseBranchActivity, ConditionedActivityGroup, WhileActivity, and ReplicatorActivity activities to control activity execution. Conditions can be expressed as declarative, or defined in code. Declarative conditions are created as code DOM statements in the rules’ XML file. Code-based conditions reference a method in the workflow’s code file that returns its result through the Result property.


Rules, like conditions, are expressed as code DOM statements, and are collected in the rules XML file. Rules include a condition statement and collections of actions that are performed based on the result of the condition. Rules are collected into rule sets, which support both simple sequential execution of rules, and sophisticated forward-chaining of rules. Rule sets are executed by the PolicyActivity activity.

A key advantage of defining your logic with rules and declarative conditions is that they can be modified at run time by doing dynamic updates using workflow changes. In addition, rules let you separate your business logic from a workflow in order to share those rules with other workflows. Finally, defining business logic in rules allows for advanced tools, such as dependency visualization and impact analysis tools, to be built on top of the object model.

Fault Handling

Exceptions that occur in activities are handled asynchronously by the workflow runtime engine in a process called fault handling. Exceptions are scheduled in a queue to be handled later. If the exception type matches the one that is handled by a particular FaultHandlerActivity activity, that activity will handle the exception. If the exception cannot be handled, it is bubbled up through parent activities until it ultimately causes the termination of the workflow instance.

Workflow Markup

Workflow markup, which is based on Extensible Application Markup Language (XAML), enables developers and designers to model business logic declaratively and separate it from lower-level implementation details that are modeled by code-beside files. Because workflows can be modeled declaratively, it is possible to activate a workflow by directly loading a workflow markup file into the workflow runtime engine at run time.


Correlation is the mechanism for relating workflow service messages to each other or to the application instance state, such as a reply to an initial request, or a particular order ID to the persisted state of an order-processing workflow.

Types of Correlation

Correlation can be protocol-based or content-based. Protocol-based correlations use data provided by the message delivery infrastructure to provide the mapping between messages. Messages that are correlated using protocol-based correlation are related to each other using an object in memory, such as a RequestContext, or by a token provided by the transport protocol. Content-based correlations relate messages to each other using application-specified data. Messages that are correlated using content-based correlation are related to each other by some application-defined data in the message, such as a customer number.

Activities that participate in correlation use a CorrelationHandle to tie the messaging activities together. For example, a Send that is used to call a service and a subsequent Receive that is used to receive a callback from the service, share the same CorrelationHandle. This basic pattern is used whether the correlation is content based or protocol based. The correlation handle can be explicitly set on each activity or the activities can be contained in a CorrelationScope activity. Activities contained in a CorrelationScopehave their correlation handles managed by the CorrelationScope and do not require the CorrelationHandle to be explicitly set. A CorrelationScope scope provides CorrelationHandlemanagement for a request-reply correlation and one additional correlation type. Workflow services hosted using WorkflowServiceHost have the same default correlation management as the CorrelationScopeactivity. This default correlation management generally means that in many scenarios, messaging activities in a CorrelationScope or a workflow service do not require their CorrelationHandle set unless multiple messaging activities are in parallel or overlap, such as two Receive activities in parallel, or two Send activities followed by two Receive activities.

Part 2: Create a simple Workflow >>

Further readings

Integrating a persisted WF4.0 Workflow with MVC

[Originally posted on]:

Integrating a persisted WF4.0 Workflow with MVC


Writing this as lately I’ve been interested in WF4.0 (it’s always pronounced “dub-F” in my head) and saw a post about using WF with MVC to handle a site registration wizard. Thetutorial it linked to used a state machine (WF only supports Sequential OOB) workflow without persistence, which made me think that you could easily use a normal workflow with persistence to do a lot of other things inside a web application. WF which is part of .NET4.0 allows you to easily create and call workflow processes, small or large, from anywhere inside .NET code and it’s been drastically improved since .NET3.5. That ease makes it practical to use workflow in places which it was previously too complicated to integrate, places where we normally manually code a process into business or web logic making it difficult to maintain and add standard features like tracing/auditing.

To run the sample or try this yourself you will need .NET4.0 and Visual Studio 2010, the instructions below are a simple overview and do not include all code or references.

1. Creating the WF SQL Persistence store

WF4.0 supports using a default SQL Persistence store, using a DB created using scripts in the .NET4.0 framework directory. Simply create a new DB (call it whatever you like) on your server and run the following scripts:

  1. C:WindowsMicrosoft.NETFrameworkv4.0.21006SQLenSqlWorkflowInstanceStoreSchema.sql
  2. C:WindowsMicrosoft.NETFrameworkv4.0.21006SQLenSqlWorkflowInstanceStoreLogic.sql

Multiple workflows can share the same DB or you can separate them out if you want.

2. Creating the MVC site and Workflow Activity Library


In Visual Studio, create a new MVC Web Application and add another project of type “Activity Library” (under templates Workflow) to hold your workflow. I also added a console application to test the workflow independently but this is not necessary.

3. Creating the Workflow


Delete the existing workflow activity and create a new one with the name WizardActivity, in the activity drag and drop a Flowchart from the toolbox onto the workflow (using this instead of a state machine) and add a variable “Outcome” to the Flow chart scope (used to store the outcome Next/Back of the steps). In the Activtiy project add a new Class, WizardStep, which will be generic custom activity used for all the steps in the workflow. This activity contains the bookmark code which is used to halt and persist the workflow at the steps. Add the code and compile the project, this will update the workflow toolbox adding WizardStep and allowing you to drag and drop it onto the workflow. Add three Wizard steps to the workflow, setting the Name to “StepN“, Bookmark Name to “StepN” and Input to “Outcome” (this is an output parameter which will set Outcome to the value supplied when resuming the Bookmark in the custom activity). Add a custom Complete activity (which does nothing) and link up the workflow using Decision controls (set condition to “Outcome.Equals(“Next”)”) and arrows as per image. Lastly add a new Class WizardHostHelper (copy code from sample), which acts as the host for the workflow; creating the Workflow application object, setting instance store values, starting/resuming the workflow, actioning the bookmarks.

4. Update the MVC application to use the Workflow

Now to integrate the workflow into the website.

  1. Add a new class WizardModels, to hold the model logic for the wizard steps and workflow service (wrapper to WizardHostHelper).
  2. Add a new controller WizardController, for controller logic used in the wizard.
  3. Add four new views under Wizard, Step1-3 and final, for the views used in the Wizard.
  4. Update AccountModel, add a Guid parameter workflowKey to the MembershipService.CreateUser method, this will store the Workflow Instance key in the standard ASP user security providerUserKey. Also add a method GetUserWorkflowKey to return the key for a username.
  5. Update AccountController, changing Register method to start a workflow instance for the user using the WizardModels.WorkflowService and supply the workflow key into CreateUser. Update both Register and Logon to redirect action to the Wizard index.
  6. Update the web.config to set the instance store connection string.

And that should be it, registering a new user will now start the workflow process and redirect to the first step. Next/Back buttons on the step views cause the controller to action the steps, progressing the workflow. The workflow is persisted to the DB at each step, so even if the website goes down the current step of the user in the workflow is maintained. The workflow, rather than the controller, decides which step the website should display, separating the process logic from the controller logic.

There is very little code involved, just small service/host classes used to access the workflow and integrate with the website. To add persistence it only really took two lines of code in the host class (setting the workflow application instance store and telling it to persist when idle at the bookmarks), compared to the tutorial sample host. The workflow used could be much more complicated, branching to different steps depending on user response (e.g. redirecting to a different address screen if the user isn’t based in the UK) without adding complexity to the controller logic. As the workflow is separated from the website it can be tested independently (no website needed! automated testing!) and updated without large changes needed in the website. It’s also a very light weight (and cheap) way to add workflow, which is something we may need going forward. I’m currently looking at ways now to use WF with persistence in Azure cloud (without the upcoming Azure AppFabric) for simple workflow solutions, as right now we can’t use our current workflow applications like K2.

Attached sample inside word doc as Posterous won’t accept zips.