Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
119 views8 pages

Starting With Windows Workflow Foundation

This document provides an introduction and overview of Windows Workflow Foundation (WF), a technology included with .NET Framework 2.0 that allows defining and executing workflows. It discusses installing WF, why workflows are useful, basic concepts like layers and activities, and provides an example of creating a simple sequential workflow that greets a person differently based on their name and position. The workflow is run within a test console application that provides parameters to the workflow and retrieves the output greeting.

Uploaded by

sarascr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
119 views8 pages

Starting With Windows Workflow Foundation

This document provides an introduction and overview of Windows Workflow Foundation (WF), a technology included with .NET Framework 2.0 that allows defining and executing workflows. It discusses installing WF, why workflows are useful, basic concepts like layers and activities, and provides an example of creating a simple sequential workflow that greets a person differently based on their name and position. The workflow is run within a test console application that provides parameters to the workflow and retrieves the output greeting.

Uploaded by

sarascr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 8

Starting with Windows Workflow Foundation

Windows Workflow Foundation (from now, Windows WF) is


the less known part of the all-new WinFX Platform that
Microsoft is going to release along with Windows Vista, and
that also will be provided as an update for Windows XP and
Windows 2003 systems. This article, by Alejandro Serrano,
aims to serve as an introduction to this technology, its tools,
and why to use workflows.

Installing WinFX

A successful installation of .NET Framework 2.0 is the first thing we


need to use Windows WF. You need to have the latest version,
because older ones don't work with the latest bits. On
http://msdn.microsoft.com/winfx/, click Get the Beta. You need at
least, the WinFX Runtime Components along with the Visual Studio
2005 Extensions for Windows WF. Of course, for the latest item you
must have a running Visual Studio installation (Express editions
won't work). These extensions to the integrated development
environment (IDE) are necessary because, although it is possible to
create the workflow in code, it makes easier to manage the XML
and code-behing files Windows WF uses for its work.
Downloading the entire Windows SDK to check other new
technologies such asWindows Presentation or
CommunicationFoundations is also suggested (formerly known as
Avalon and Indigo, respectively).

Why Workflows?

Until now, flowcharts and process schemes were done separately


from code, just as a way to organize ideas before writing the actual
code. But when the task was finished, the scheme remained just as
documentation. Also, the capacity of older computers made
impossible to retain all the information of a workflow in memory,
and it was difficult totranslate from an easy-readable format for
human to machine code.

Windows WF tries to solve all these problems, making workflow


technology available to every single programmer that uses the .NET
Framework, and thereby making it general enough to be used in
different situations. That seems the natural step from the
interoperability concepts in the Framework; if it can execute code
written in a bunch of languages, then why not have a tool that
translates a conceptual idea of how a work is to be done in real,
compliable code? Windows WF can be used for document
management (for that special task it will be integrated into
Office12), business cycles, or page flow (by making use of
ASP.NET).

There are lots of reasons as to why a developer would choose


writing a workflow instead of writing the code. First of all, for
programmers, workflows are easier to understand than code,
because workflows provide a visual representation of the process.
Consequently, code becomes harder to maintain and adapt to new
areas. For example, adding a step in the middle of a scheme
because we need to have an additional agreement with the user
because of newer laws can be real pain for coders, but an easy step
forworkflow users. In addition, Windows WF provides a way to
extend existing workflows without need of recompiling, so general
frameworks can be developed and then customized to fit in
different areas.

Basic Concepts

Layers in Windows WF: The first one is the code that uses the
workflow, because a workflow is not an application, but instead a
set of actions that is executed asynchronously by the engine
provided by Windows WF. That's the key to being able to use a
workflow in such a variety of scenarios.

The interface that allows communication between that engine and


the executing process is called the Hosting Layer, which provides
some extra services apart from Communication (send an receive
events and data from and to the workflow), like Persistence (which
allows saving the state of the workflow in a storage media to
restore it later) or Tracking (so the actual code running the
workflow can log the execution of it).

Finally, we find the Runtime Layer, which actually executes the


workflow and manages the core services. One different with the
other two layers is that Runtime Layer is not extensible, while more
services can be added to the Hosting Service.

Apart from these layers, Windows WF comes with an integrated


designer that by default integrates smoothly in Visual Studio 2005,
but which can be used outside it, so any developer could add drag-
and-drop support to its own application.

Activities and the minimal units in Windows WF: Each activity


receives some parameters from the developer, executes it actions,
and then the flow is transferred to the next activity. Some
examples are Code or IfElse activities. As developers, we can create
new activities and use it in our own code or create an
ActivityLibrary for selling. We can get new activities at no cost on
its official website www.windowsworkflow.net.

There are two main kinds of workflows:

1. Sequential: Its actions are executed in some predefined


order with a beginning and an end. Examples of sequential
workflows may include installations.

2. State machines: These workflows don't have a path, but


it's represented as a set of states and transitions between
states. Examples are a web shop: you may need approval for
mailing, the user could pay via credit card or with a cheque,
and each user is in one state and may go to any order
depending on previous questions.

Creating Our First Workflow

In our first use of Windows WF, we will create an application that greets a person
depending on some parameters provided—the name and the position (chief or
employee). That will allow us to learn parameterization and conditional execution.

First of all, open a Visual Studio 2005 instance and create a new
project of type "Sequential Workflow Console Application". It will
generate the scheme along with a small program that will serve as
a test base for it (remember workflows are not directly executable,
instead you need some application as a host). Parameters are
added as properties, because workflows are just classes that inherit
from a standard base class. This is more or less the same that in
ASP.NET or Windows Forms. So go to theSolution Explorer, select
Workflow1.cs and then click the View Code button.
Figure 1: Sequential Workflow

string name;
string position;
string greeting;

publicstring Name
{
get {return name; }
set { name =value; }
}

publicstring Position
{
get {return position; }
set { position =value; }
}

publicstring Greeting
{
get {return greeting; }
}
Then return to the designview, and add IfElse and aCode activity in
each branch, as shown in Figure 1. Feel free to rename the
activities in your own workflow. You will notice that there are
several exclamation signs. The reason behind them is that some
additional information is required to make those activities work—
some condition forIfElse and some condition for the Code.
SelectchiefBranch and go to the Properties tab. In condition
property,
selectSystem.Workflow.Activities.Rules.RuleConditionReference,
expand it, set a new name (if you selected a new name that was
already used, the same condition would be used—that allows
condition reuse) and click the three-point button in the Expression
item. A new window will appear, named Rule Condition Editor,
where you can add the code that checks whether to take the
selected branch of not. In our case, it is as simple as:this.position
== "Chief".

Figure 2: Condition Editor provides IntelliSense

To finish our workflow, we will add code to both activities in each


branch that will set the greeting field of the workflow class, so it
can be retrieved when the workflow is completed. Just double
clickCode activities and write:
 Code for chiefGreeting:greeting = string.Format("¡Good
morning, 0!", name);

 Code for employeeGreeting:greeting = string.Format("¡Hi,


0!", name);

To be able to test our brand-new workflow, we need to change the


host application so it provides the parameters to the workflow
instance and also gets the Greeting output parameter back. Open
the Program.cs file, and change the last three lines of the Main
method so they look like:

Dictionary<string,object> parameters = new


Dictionary<string,object>();
parameters.Add("Name","Peter");
parameters.Add("Position","Chief");

WorkflowInstance instance = workflowRuntime.CreateWorkflow(


typeof(FirstWorkflowExample.Workflow1), parameters);
instance.Start();
waitHandle.WaitOne();

The first three lines of this code create a newDictionary object that
will contain all parameters. That seems an odd way to provide the
information (no compile-time check), but it is the only way to have
compatibility with any type of class (remember that in .NET all
classes inherit from Object). Then, we have to change the workflow
creation to take these parameters.

Workflows are always executed asynchronously within Windows WF


bounds. For that reason, a wait handle is used, so it tells the
program to finish when the workflow is completed. We will also
change the method in the WorkflowCompleted event (check the
fact that Windows WF designer is using anonymous delegates), so
it retrieves the Greeting parameter and shows the message via
console:

workflowRuntime.WorkflowCompleted +=delegate
(object sender, WorkflowCompletedEventArgs e)
{
Console.WriteLine(e.OutputParameters["Greeting"]);
Console.ReadKey();
waitHandle.Set();
};

Just click Run and then see the results. Of course, this application is
lots of magnitude slower than the same application written entirely
in code, because Windows WF needs to load all the services, create
a new thread, etc, but in bigger application this is unnoticeable.

Developing an Activity

To learn how to create a simple activity, we are going to continue


with this example. First of all, add a new project to the solution, of
type "Workflow Activity Library". We will create an activity that
shows a string in a message box, so we need a reference to the
System.Windows.Forms assembly. Open the Activity1.cs file and
change the base class to Activity instead ofSequenceActivity, as our
activity will be completely coded.

The way you add parameters to an activity is a bit different from adding them to a
workflow. Here's the code for adding a required parameter of nameMessage, add it
in the code file:

publicstatic DependencyProperty MessageProperty =


DependencyProperty.Register(
"Message",typeof(string),typeof(Activity1),
newPropertyMetadata("Your message here"));

[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible
)]
[ValidationOption(ValidationOption.Required)]
[Browsable(true)]
[Description("The string that will appear in the message box")]
[Category("General")]
publicstring Message
{
get {return (string)base.GetValue(MessageProperty); }
set {base.SetValue(MessageProperty,value); }
}
Dependency properties are used to centralize the changes to the
workflow instance, so the runtime can detect when getting or
setting a property is not allowed. These kinds of properties are also
treated in a special way by the runtime, increasing performance.
However, to make them appear in theProperties tab of Visual
Studio 2005, we have to add some custom attributes that control
its behavior. The most important of them are shown in our
example.

It's time to finish our custom activity by adding anExecute method:

protected override ActivityExecutionStatus Execute(


ActivityExecutionContext executionContext)
{
System.Windows.Forms.MessageBox.Show(Message);
return ActivityExecutionStatus.Closed;
}

You can add this activity to the previous example, in some branch,
to check it works correctly.

Since here we have seen just a little part of the possibilities of


Windows WF. With this new technology, you can get a deeper
integration between the host and the workflow using the
Communication service, and even have long-running workflows that
are automatically saved into same storage such a SQL server
database (dehydrated) and that come to life again when needed
(re-dehydrated). State machine workflows are another, very useful
kind of workflow, especially when user interaction is required, for
example, for creating ASP.NET page flows.

You might also like