You are on page 1of 47

Introduction to Windows

Workflow Foundation
Silvano Coriani

(silvano.coriani@microsoft.com)

Developer Evangelist
Microsoft

Agenda
What is Windows Workflow
Foundation?
Architecture & Core concepts
Building Workflows
Introduction to Activities
Workflow Styles
Workflow Authoring Tools
Runtime services
Workflow communications

Workflow Software Challenges


Real World Behavior

Software Challenges

Orders are
confirmed in
48 hours and shipped
within 30 days
Most suppliers
confirm our orders
but some forget and
we need to followup

Long Running and


Stateful
Workflows run for up to
30 days and must
maintain state
throughout
Flexible
Control Flow
Flexibility for people
to override or skip
steps in the workflow

What is the status of


this order and what is
the next step?

Transparency
Rendering runtime state
within a visualization of
the workflow control
flow

Why Workflow Technology?


Developer Productivity
Workflows technology provides abstractions
convenient to describe real world scenarios

Workflow software challenges


Workflows are long running and stateful

Workflows require flexible control flow


Workflows must provide transparency

For Example

to provide Windows
Workflow
Foundation as a
part of the
developer
framework for
Windows
and enterprise
applications that
build on top of
Windows Workflow
Foundation for

A ISV developer building


a line of business
application chooses to
use Windows Workflow
Foundation within the
business logic of their
application.

For Example

Microsofts Workflow Strategy is

An enterprise customer
uses BizTalk Server to
provide system workflow
across their existing line
of business applications
and trading partners to
reduce their cycle-times
and increase business
visibility in a high-volume
environment.

Windows Workflow Foundation


Deliver best-in-class workflow platform &
tools for Microsoft products and
partner/customer ecosystem
Single workflow technology for Windows

Available to all customers of Windows


Available for use across a broad range of scenarios

Redefining workflow

Extensible framework & API to build workflow centric


products
One technology for human and system workflow

Take workflow mainstream

Incremental learning for mainstream .NET


developer

Fundamental part of the Office 12 value proposition


Strong workflow partner & solution ecosystem

What is a workflow?
A set of activities that coordinate people
and / or software...
Example activities. EscalateToManager

CheckInventory

organized into some form of workflow.


Like a flowchart.

Or a state diagram.

Workflow Scenario Spectrum


Human Workflow

System Workflow

Participants: people, roles


Flow style: flexible,
dynamic
Data: unstructured,
Information
Information Worker
Worker
documents
Document Review
Review
Document

CRM

Participants: apps, services


Flow style: prescriptive,
protocols
Data: structured, transactional

Business
Business to
to Business
Business

Supply
Supply Chain
Chain Mgmt
Mgmt

Line
Line of
of Business
Business Apps
Apps

ERP

Quote to
to Cash,
Cash, Sales
Sales Automation
Automation
Quote

IT
IT Management
Management

New H
Hire
ire Provisioning,
Provisioning, Trouble
Trouble Ticket,
Ticket,
New
.NET
.NET Developer
Developer

Pageflow, Service
Service Coordination
Coordination
Pageflow,

Windows Workflow Foundation

Windows Workflow Foundation


Key Concepts
Workflows are a set of Activities
Workflows run within a Host
Process: any application or
Developers
can build their own
server
Custom Activity Libraries

Components
Base Activity Library: Out-of-

box activities and base for custom


activities Engine: Workflow
Runtime
execution and state management
Runtime Services: Hosting
flexibility and communication
Visual Designer: Graphical and
code-based construction

Visual Designer

A Workflow
An Activity
Custom Activity Library

Windows
Workflow Foundation
Base Activity Library
Runtime Engine
Runtime Services

Host Process

Workflow Basics
A workflow is a class
Imports System.Workflow.Activities
Public Class MyWorkflow
Inherits SequentialWorkflow

End Class

A workflow class may be defined in markup


<?Mapping XmlNamespace="Activities"
ClrNamespace="System.Workflow.Activities"
Assembly="System.Workflow.Activities" ?>
<SequentialWorkflow x:Class="MyWorkflow" xmlns="Activities"
xmlns:x="Definition">

</SequentialWorkflow>

Workflow Execution
My Application

Create instance

rt.StartWorkflow(typeof(WF1));
WF1 Instance
Sequence

WF1

OnEvent1
Execute

MyWF.dll

Invoke1

1 App calls StartWorkflow()


2

Instance Manager:
Loads workflow type
Creates instance
Enqueues WF1 with Scheduler

Execute until idle

3 Scheduler dequeues WF1 and call

Base
Activity
Library
Runtime
Engine

Runtime
Services

SequentialWorkflow

Execute

Sequence

Execute
Save

Activity

Persist to disk

Instance Manager
Scheduler

Executor (SequentialWorkflow base


which enqueues Sequence
4 Dequeue Sequence and call
Executor
enqueues
OnEvent1
Dequeue
OnEvent1
and call
5 which
Executor
which subscribes to event

Sequence
WF1
OnEvent1

7
Persistence

WF1

InstanceMgr calls Save() on


WF1 (Activity base class) to
serialize instance and gets back
stream
Instance Mgr call Persistence
service passing serialized
stream - Persistence service
saves to disk

Activity Basics
Activities are the building blocks of workflows
The unit of execution, re-use and composition
Basic activities are steps within a workflow
Composite activities contains other activities
EG: Sequence
Base Activity Library provides out-of-the-box activity set
Partners and customers author custom activities
EG: ApproveOrder

Activities are classes:


Properties and events are defined by the activity
author and programmable from workflows
Has methods that are coded by the activity author
but invoked by the workflow runtime (EG: Execute) or
designer
Can be built into workflow assemblies or deployed as
re-usable libraries

Activities: Optional Features


Companion Classes
[Designer(typeof(MyDesigner))]

Designer

[Validator(typeof(MyValidator))]

Validator

[CodeGenerator(typeof(MyCodeGen))]

Serializer

[Serializer(typeof(MySerializer))]

Code Generator

[ToolboxItem(typeof(MyToolboxItem))]

ToolboxItem

Behaviors
[SupportsTransaction]
[SupportsExceptionHandlers]
public class MyActivity: Activity
{ ...
}

Transactions

Activities: An Extensible Approach


Base Activity
Library

Custom Activity
Libraries

Domain-Specific
Workflow Packages

Compliance
Compose
activities
Out-of-Box
Activities
OOB activities,
workflow types,
base types
General-purpose
Activity libraries define
workflow constructs

CRM

Extend
activity

Author new
activity
Create/Extend/
Compose activities
App-specific
building blocks
First-class citizens

RosettaNet
IT Mgmt
Vertical-specific
activities & workflows
Best-practice IP &
Knowledge

Sequencing engine driven by activities (no fixed language

Flexible Control Flow


State Machine Workflow

Sequential Workflow
Step1

Step2

Sequential
structure
prescribes
processing order

Prescriptive, formal
Automation scenarios
Flowchart metaphor

Event

State1

Event

State2

Reactive, event-driven
Skip/re-work, exception handling
Graph metaphor

Rules-driven Activities
Rule1

Step1

Data
Rule2

External
events drive
processing
order

Step2

Rules + data state


drive processing
order

Data-driven
Simple Conditions, complex Policies
Constrained Activity Group

Spectrum of Workflow
Authoring
Tools
Line of Business
Manager / End users
Wizards

Business Analyst
Visio Like

Script Developers or VARs


Script Like

Code Developers or ISVs


Windows Workflow Foundation Designer

Commonality between Tools:


Support a common object model for describing
Workflow information
The object model needs to be exchangeable
between tools

Take Workflow Mainstream: Design

Sequential
Designer

State Machine
Designer

Activity Designer

Workflow Designers
( la ASP.NET Designer)
Create new workflows
Visual (/code) authoring
Seamlessly integrate .NET
code with round-tripping
Visual debugging
Themes support
Designer re-hosting
Activity Designer
( la UserControl Designer)
Create new activities
Visual (/code) authoring
Inherit from base activities or
start from scratch
Black-box/Gray-box
composition support

Consistent and Familiar Experience for Workflow Developme


Developm

Workflow Authoring Modes


Markup Only Markup and
Declarative Code
XAML

XAML C#/V
B

XML defines
XML defines
workflow structure workflow
logic and data flow Code-beside
defines extra
logic

Code Only
C#/V
B
Code creates

Code creates
workflow
in constructor

Application
Generated
App creates
activity
tree and
serializes

XAML C#/V
B

Workflow Compiler
wfc.exe
assembly
ctor defines
workflow

.NET

C#/VB Compiler

Take Workflow Mainstream: Office 12


Office 12 Workflow
Vision
Provide document
centric workflow as an
integrated part of the
Office experience
Empower information
workers with common
workflow solutions and
activities out of the box
Empower organizations
to build sophisticated
workflow using the full
functionality of the
broader platform

Workflow Enabled Office

OutLook:
Receive
notifications
and track tasks

SharePoint:
Start/participate
, customize, and
track workflows

Word, PowerPoint,
FrontPage:
Excel, InfoPath:
Create and
Start/participate in
customize
SharePoint workflo
workflows
Workflows run inside SharePoint
and are accessible across the
Office System

Runtime Engine And Services


My workflow
Windows Workflow Foundation
Base Activity Library

Runtime Engine

Provides intrinsic behaviors to activities


Workflow
State
Tracking
Dynamic
Execution Management Infrastructure
Update

Runtime Services

Hosting flexibility - pluggable implementations (with defaults)

Persistence

Communication

Tracking

Host Process

Runtime Services
The workflow runtime is lightweight
Depends on a set of services
Only Threading is required
Often you also want Transactions and Persistence

Add services programmatically or using a config


file
What ships in System.Workflow.Runtime.Hosting?
Abstract service definitions
Concrete service implementations
DefaultThreadingService (asynchronous)
ManualThreadingService (synchronous; for ASP.NET
scenarios)
DefaultTransactionService
SqlPersistenceService

Runtime Services

Host Application
App Domain
Runtime

TimerService
manages timers
e.g. Delay activity.
PersistenceService
stores and
retrieves instance
state.
TrackingService
manages profiles
and stores tracked
information.
Common resource
services for
managing
threading and
creating
transactions

Services
TimerService
PersistenceService
TrackingService
ThreadingService
TransactionService

Out of Box Services


are provided that
support SQL Server
2000 & 2005

SQL

Out-of-Box Services
ASPNetThreadingService

Synchronous threading service used for inline execution; used by ASP module for web
services

DefaultThreadingService

Used for asynchronous execution of


workflows; uses default .Net thread pool

DefaultWorkflowTransactionSer Creates .NET transactions


vice
SharedConnectionWorkflowTra
ns-actionService

Sql* services share connection to SqlServer

InMemoryTimerService

Stores timer information in-memory, i.e. for


Delay activity

SqlTimerService

Stores timer information in SqlServer/MSDE;


i.e. for Delay activity

SqlStatePersistenceService

Stores workflow instance state information in


SqlServer/MSDE

SqlTrackingService

Stores tracking information in


SqlServer/MSDE

Workflow State Management


Many workflows are long running
A workflow instance is idle when it has no
runnable work
WF unloads-on-idle by default, but the host
can take full control
Loading/unloading is not a concern of the
workflow developer or the application
developer

Persistence points are checkpoints


Transactions
Enable crash recovery
Persistence occurs at:
Closure of a transaction
Closure of any activity marked [PersistOnClose]

Enabling Workflow Persistence


Persistence Support for Workflow Instances
Create the SQL database with the SqlStatePersistence
schema
Create a Workflow Runtime
Define Connection String
Register StatePersistenceService with Runtime
Register TimerService with Runtime
Start the Workflow
Loading
and Unloading uses StatePersistenceService
private
void RunWorkflow()
{
WorkflowRuntime wr = new WorkflowRuntime();
string connectionstring = "Initial Catalog=Persistence;Data
Source=localhost;Integrated Security=SSPI;";
wr.AddService(new SqlStatePersistenceService(connectionstring));
wr.AddService(new SqlTimerService(connectionstring));
wr.StartWorkflow(typeof(SimpleWorkflow));
}

Tracking
Track all state changes and data within the workflow
Emit tracking info from code
Dynamic changes
Profile
XML file that specifies what to track
Includes and excludes, state changes, data context, types
Object model to create
Tracking
Information

Activities
Workflow
Instance

Profile

Tracking
Service

Write

Host
Applicatio
n

Query

Store

Tracking Architecture
Workflow Runtime
Workflow Instance
Profile
SqlTrackingService

Listener

Execution

FileTrackingService
Profile

Listener asks each


services for their
profile(s)
Service only gets called
based on what is
specified in the profile(s)
Multiple tracking
services can be loaded
per the applications
requirements
SqlTrackingService
Channel
FileTrackingService
Channel

Enabling Workflow Tracking


Tracking Support for Workflow Instances
Define tracking profiles
Create workflow runtime
Define connection string
Register one or more TrackingServices with the
WorkflowRuntime
Start the workflow
Query tracking database instance and activity information
private void RunWorkflow()
{
WorkflowRuntime wr = new WorkflowRuntime();
string connectionstring = "Initial Catalog=Tracking;Data
Source=localhost;Integrated Security=SSPI;";
//Out of the Box Tracking Service
wr.AddService(new SqlTrackingService(connectionstring));
wr.StartWorkflow(typeof(SimpleWorkflow));
}

Workflow & Communications


The purpose of a workflow is often to
coordinate work performed outside of its
boundaries
Many workflows are long-running programs
Communication is an inherent need

The communication may be local (intraprocess)


To and from your hosting application code

The communication may be remote


Web services
Windows Communication Foundation (Indigo)

Communication Architecture
Local Application

Custom
Host

Local App Object


Local
LocalApp
AppObject
Object

Remote Application

ASP.NET
Web Service
Local
LocalApp
AppObject
Object

Workflow Runtime

Communication
Services
Proxy management
Correlation
Runtime
Scheduling

Workflow Instances
InvokeMethod
EventSink

WebServiceReceive
WebServiceResponse
InvokeWebService

Activities
Model sending and
receiving of data

Local Communication Architecture


.NET object managed by the runtime acts as a
communication intermediary between the host and the
workflow instances
Raises events into the workflow
Proxy for outbound method calls

Four components:
Local Communication Activities
Contract
Local Service
EventArgs

Application

Workflow
Workflow Runtime
Output
Input

Method

DataExchangeService
Event

Local Communication Activities


Model sending and receiving data

EventSink activity
Model an event raised by a local object
(Application Workflow)

InvokeMethod activity

OrderManager

WorkflowRuntime

Model the invocation of a method on a local


object
(Workflow Application)

Local Communication Contract


Define pattern of communication

Write an interface that defines the


contract for communication with the
workflow
Events for inbound data (to workflow)
[DataExchangeService]
Methods for outbound data (from
public interface IOrderManager
{
workflow)
// Create a workflow instance to process the order
event
EventHandler<OrderEventArgs>
OrderSubmitted;
Mark
as [DataExchangeService]
// The workflow instance will later call one of these methods
void Approve(string orderId);
void Reject(string orderId);
}

Local Communication Service


Implement class

Implement the interface youve defined


Singleton (will be shared by all workflow
publicinstances)
class OrderManager : IOrderManager
{

// Create a workflow instance to process the order


public event EventHandler<OrderEventArgs> OrderSubmitted;
// The workflow instance will later call one of these methods
public void Approve(string orderId) { }
public void Reject(string orderId) { }
}

Register with the runtime

WorkflowRuntime runtime = new WorkflowRuntime();


OrderManager orderManager = new OrderManager();
runtime.AddService(orderManager);

Local Communication Event Args


Define event data

The runtime intercepts events raised


by the registered local object, and
delivers them to the right workflow
instances
Must derive from
WorkflowMessageEventArgs and include
publicthe
class workflow
OrderEventArgs :instanceId
WorkflowMessageEventArgs
{
public
OrderEventArgs(Guidthe
instanceId,
string orderId)
Conceptually,
registered
local object
: base(instanceId)
{ is addressing a workflow instance when

} it raises an event
}

Coordinating Services
Workflows are an excellent way to coordinate services
Service interaction becomes:
Declarative modeled using activities in a workflow
Transparent - to the outside world
Visual for designing, debugging, and monitoring
Composable - Data can be flowed from activities/services
Simplified - Workflows simplify message exchange patterns
Flexible - Easily be modified and dynamically changed
Workflow

Services

Implementing Services using


Workflow
Challenges developing services today
Services are often used together as part of a business process,
but are not explicitly associated
Services often front-end, long-running business processes

Workflows are an excellent way to implement service logic


State management across multiple service interactions
Services are explicitly associated in a workflow model
Implementation can be transparent
Enables runtime visibility into the state of the service
Runtime behavior is configurable
Tracking, persistence, etc.

Services

Workflow

Web Services Activities


InvokeWebService
Like Visual Studio Add Web Reference
Session-aware
Can manipulate the proxy before the call
For example, to set credentials

Parameter binding

WebServiceReceive, WebServiceResponse
Model 1-way and 2-way requests to the workflow
Define web service contract as an interface
Parameter binding
Generate default web service project plus artifacts
with a single click in Visual Studio

Web Services Hosting


WorkflowWebHostingModule
ASP.Net 2.0 IHttpModule
Session-based request routing
Not required to use this (replaceable)

WorkflowWebService
Default base class for published workflows
Not a required base class for your web services

Workflow Runtime Services


ASPNetThreadingService
Uses request thread to process workflow

WebTimerService
Persistent timer service

Web Services
ASP.NET

WorkflowWebService
WorkflowWebHostingModule

Build transparent,
flexible, longrunning web
services
Model all data entry
and exit points

Workflow Runtime
Workflow

Receive
Response

Invoke

Host the workflow


runtime in ASP.NET

Runtime Services
Threading Service
Timer Service
Persistence Service

Session
Timers
Workflow State

Why Workflow & Services?


Services make workflow more
accessible
Workflows make services more
composable
Services

Workflow

Services

Workflow & Communications


Foundation

Declarative control flow


Simplified programming
model
Process visualization
Dynamic execution
Configurable runtime
behavior

Secure, reliable,
transactional services
Unified API for
communications
Transport selection
Multiple Message
Exchange Patterns

WCF Activities
Prototype activities designed for direct
communications using WCF
SendMessage
ReceiveMessage
SendReceive
ReceiveSend

Enables explicit asynchronous and


sophisticated message exchange patterns
Workflows wire up communications to
services by configuring these activities
Not provided with Windows Workflow
Foundation

WCF with Local Services


Service Request
WCF
Service
OrderManager
Local Service

Service Request
WCF
Service

Workflow and BizTalk Server


BizTalk Server
Desig
n
Tools

Accelerators
Orchestratio
Workflow
n
Messaging
Transformati
on
Adapters

Busine
ss
Activity
Monito
r
And
Admin
Tools

Visual Studio Designer

Windows
Workflow
Foundation
WinFX

Premium BPM server


Distinct server product
Use in B2B, EAI, BPM scenarios
Deployable solutions
Manageability, Scale-out
Future version will migrate to
Windows Workflow Foundation
for orchestration

Workflow framework

Exposed via WinFX


Broad set of scenarios
Used to build solutions
Enables manageability
and scale-out in solutions
Use for building workflow
into apps or workflow-enabled
servers

Summary
A single workflow technology for Windows

Platform level workflow framework for use within Microsoft


products & ISV applications

Will be used by BizTalk Server, Office12, and Dynamics


Available to all Windows customers

Microsoft is redefining workflow

Unified technology for System & Human workflow


Multiple styles: sequential, rules-based, state machine
Supports dynamic interaction

Microsoft is taking workflow mainstream

Consistent and familiar programming model for reaching


mainstream application developer
Available to millions of end-users through Office 12
Extensible platform for ISVs

2006 Microsoft Corporation. All rights reserved.


This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.

You might also like