Title: Introduction to Windows Workflow Foundation
1Introduction toWindows Workflow Foundation
- Matt Winkler
- Technical Evangelist, Windows Workflow Foundation
- http//blogs.msdn.com/mwinkle
- mwinkle_at_microsoft.com
2Agenda
- What is Windows Workflow Foundation?
- Architecture Core concepts
- Building Workflows
- Building Activities
- Runtime Services
- Workflow Communication
3Windows Workflow Foundation
Windows Workflow Foundation is the programming
model, engine and tools for quickly building
workflow enabled applications on Windows.
- 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
- Bring declarative workflow to any .NET developer
- Fundamental part of the Office 2007
- Strong workflow partner solution ecosystem
4Packaging
- Third foundational .NET Framework 3.0
- Windows Communication Foundation (Indigo)
- Windows Presentation Foundation (Avalon)
- Windows Workflow Foundation (WinOE/WinWS)
- Cardspace (Infocard)
- Support for Windows XP Windows Server 2003
- Licensed as part of Windows
- Released!
5What is a workflow?
A set of activities that coordinate people and /
or software...
EscalateToManager
CheckInventory
Example activities.
organized into some form of workflow.
Or a state diagram.
or based on rules.
Like a flowchart.
6Windows Workflow Foundation
Visual Designer
A Workflow
- Workflows are a set of Activities
- Workflows run within a Host Process any
application or server
- Developers can build their own Custom Activity
Libraries
An Activity
Custom Activity Library
Components
Windows Workflow Foundation
- Base Activity Library Out-of-box activities and
base for custom activities
Base Activity Library
- Runtime Engine Workflow execution and state
management
Runtime Engine
- Runtime Services Hosting flexibility and
communication
Runtime Services
- Visual Designer Graphical and code-based
construction
Host Process
7Building a Workflow
8Workflow Authoring Modes
Markup and Code
Application Generated
Markup Only Declarative
Code Only
App creates activity tree and serializes
XAML
XAML
- Code creates
- workflow
- in constructor
- XML defines
- workflow
- Code-beside
- defines extra logic
- XML defines
- workflow structure
- logic and data flow
XAML
Workflow Compiler wfc.exe
- .NET assembly
- ctor defines
- workflow
C/VB Compiler
9What are Activities?
- An activity is a step in a workflow
- Has properties and events that are programmable
within your workflow code - Has methods (e.g. Execute) that are only invoked
by the workflow runtime - Think of Forms Controls
- Activity Controls
- Workflows Forms
- Activities fall under two broad categories
- Basic steps that do work
- Composite manage a set of child activities
10Base Activity Library
- Base Activities get you started
- Designed for modeling control flow
communications - IfElse, Delay, While, State, etc.
- InvokeWebService, InvokeMethod, etc.
- Custom activities can derive from the Base
Activities - Base Activities have been built using the same
framework thats available to you as developers
11Activities An Extensible Approach
Custom ActivityLibraries
Base Activity Library
Out-of-Box Activities
- OOB activities,workflow types,base types
- General-purpose
- Activity libraries define workflow constructs
- Create/Extend/Compose activities
- App-specificbuilding blocks
- First-class citizens
12Why build custom activities?
- Activity is unit of
- Execution
- Reuse
- Composition
- Activities enable workflow modeling
- Custom activity examples
- SendEmail, FileSystemEvent, PurchaseOrderCreated,
AssignTask, etc. - Write custom activities for
- Reusing workflow logic
- Integrating with technologies
- Modeling advanced control flows
- Modeling various workflow styles
Workflow Execution Logic
Simplicity
Code Activity
InvokeWebService Activity
InvokeMethod EventSink
Custom Activities
Flexibility
13Example A SendMail Activity
using System.Workflow.ComponentModel public
partial class SendMail System.Workflow.Component
Model.Activity public SendMail()
InitializeComponent() protected override
Status Execute(ActivityExecutionContext context)
// my logic here to send the
email return Status.Closed public
partial class SendMail public string
subject public string Subject get return
subject set this.subject value
private void InitializeComponent() // designer
generated this.ID "SendMail"
14Activity Component Model
- Each activity has an associated set of components
- Components are associated through attributes on
the Activity Definition
Designer
Activity
Behaviors
Validator
// Companion classes Designer(typeof(MyDesigner))
CodeGenerator(typeof(MyCodeGen)) Validator(ty
peof(MyValidator)) // Behaviors SupportsTransac
tion public class MyActivity Activity ...
Serializer
Code Generator
Required
Optional (defaults provided)
15Activity Definition Class
- Class that defines the activitys properties,
events and conditions - Defines how the activity manages state
- Two types of state
- Instance state data is instance-specific
- Metadata state data remains the same across all
instances - State can be managed using fields,
variable-backed properties, or Dependency
Properties - Dependency Properties
- Used to support data binding
- Required for property promotion
- State is stored in a dictionary
- Used by the runtime to
- Serialize and manage state
- Intercept the state changes made during execution
16Activity Execution Status
- Returned by Execute() method
- Can be determined by a parent activity or
workflow - this.sendEmail1.Status
- Tracked by a Tracking Runtime Service
- Activity.Status Enumeration
- Initialized
- Executing
- Compensating
- Cancelling
- Closed
- Faulting
17Activity Execution
- Activity Execution Methods
- Initialize()
- Execute()
- Cancel()
- Compensate()
- HandleFault()
Transition Types
Runtime
Activity
18Custom Activity Designer
- Simplifies the development of custom activities
- Provides a visual way to create activities
- Targeted towards custom composite activities
- Can also be used to author basic activities
- Similar to the Windows Forms user control designer
19Advanced Composite Activity Execution
- Activities may need long-running execution
environments as a part of their execution - This opens up interesting possibilities of
modeling advanced control flows - Loops, Continuations, Dynamic Activities etc.
20Sequence Activity Execute()
protected override Status Execute(ActivityExecutio
nContext context) Activity childActivity
this.ExecutableActivities0 EventHandlerltActivi
tyExecutionStatusChangeEventArgsgt OnClosed
null OnClosed delegate childActivity.Clos
ed - OnClosed if(this.ExecutionStatus
ActivityExecutionStatus.Canceling)
context.CloseActivity() else if
(ExecutionStatus ActivityExecutionStatus.Execut
ing) this.index if
(this.ExecutableActivities.Count gt this.index)
childActivity this.ExecutableActi
vitiesthis.index
childActivity.Closed OnClosed
context.ExecuteActivity(childActivity )
else context.CloseActivity()
childActivity.Closed
OnClosed context.ExecuteActivity(childActivity)
return ActivityExecutionStatus.Executing
21ForEach Activity Execution Contexts
Template Activity
Context Owner Activities
Default Workflow Context
Context 1
Context 2
Context 3
Children Contexts of ForEach activity
22Building a Basic Activity
23Activity Summary
- An Activity is a key concept of Windows Workflow
Foundation - WF allows you to write custom activities to model
your application control flow explicitly - Activities are the fundamental unit of
- Execution, Reuse, Composition
- Two broad types of activities
- Basic Composite
- Activity Designer simplifies the development of
custom activities especially composites - System.Workflow.ComponentModel provides the
framework to build custom activities - Call to action Write Activities!
24Flexible Control Flow
State Machine Workflow
Sequential Workflow
External events drive processing order
Sequential structure prescribes processing order
Step1
Event
Step2
Event
- Prescriptive, formal
- Automation scenarios
- Flowchart metaphor
- Reactive, event-driven
- Skip/re-work, exception handling
- Graph metaphor
Rules-driven Activities
Rule1
Step1
Rules data state drive processing order
Data
Step2
Rule2
- Data-driven
- Simple Conditions, complex Policies
- Constrained Activity Group
25Benefits of State Machine Workflows
- Flexibility
- Ability to handle multiple business exceptions
- Ability to handle multiple paths leading to the
same goal - Visibility
- Ability to view the past, present and future of a
business process - Control
- Ability of the business end user to control the
flow of the process at run time
26State Machine Workflow Concepts
- The basic elements of a state machine workflow
- States
- Events
- Actions
- Transitions
- A state machine workflow is composed of a set of
states - In a given state a set of events can be received
- Based on the event received an action is
performed at the end of which a state transition
may or may not be made
27Activities in a State Machine Workflow
State Machine Workflow
- State Machine Workflow
- Root activity that is the container for a state
machine - State
- Represents the state of the state machine
- EventDriven
- Used to handle an event in a given state
- SetState
- Used to transition from one state to another
- StateInitialization
- Used for default action on entering a state
- StateFinalization
- Use for default action on leaving a state
Event Driven
State
State Initialization
Event Driven
Set State
State
State Finalization
28Order Processing Example
On Order Completed
On Order Processed
On Order Created
Waiting to Create Order
Order Created
Order Processed
On Order Completed
On Order Shipped
On Order Shipped
Order Shipped
Order Completed
On Order Completed
29Querying a State Machine Workflow
- Crucial in creating effective Business
Applications - Need to answer the question Where is the process
currently at? - StateMachineWorkflowInstance class to query and
interact with an instance of a state machine
workflow - Used to answer questions like
- What is the current state of the workflow?
- What transitions are possible from the current
state? - Enumerate all the states in the workflow?
30A State Machine Workflow
31Local 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 Runtime
ExternalDataExchangeService
Output
Input
32Local Communication ActivitiesModel sending and
receiving data
- HandleExternalEvent activity
- Model an event raised by a local
object(Application ? Workflow) - InvokeExternalMethod activity
- Model the invocation of a method on a local
object (Workflow ? Application)
OrderManager
WorkflowRuntime
33Local Communication ContractDefine pattern of
communication
- Write an interface that defines the contract for
communication with the workflow - Events for inbound data (to workflow)
- Methods for outbound data (from workflow)
- Mark as ExternalDataExchange
ExternalDataExchange public interface
IOrderManager // Create a workflow instance
to process the order event EventHandlerltOrderE
ventArgsgt OrderSubmitted // The workflow
instance will later call one of these methods
void Approve(string orderId) void
Reject(string orderId)
34Local Communication ServiceImplement class
- Implement the interface youve defined
- Singleton (will be shared by all workflow
instances) - Register with the runtime
public class OrderManager IOrderManager
// Create a workflow instance to process the
order public event EventHandlerltOrderEventArgs
gt OrderSubmitted // The workflow instance
will later call one of these methods public
void Approve(string orderId) public
void Reject(string orderId)
WorkflowRuntime runtime new WorkflowRuntime()
ExternalDataExchangeService dataService new
ExternalDataExchangeService() runtime.AddService(
dataService) dataService.AddService(new
OrderManager())
35Local Communication Event ArgsDefine event data
- The runtime intercepts events raised by the
registered local object, and delivers them to the
right workflow instances - Must derive from ExternalDataEventArgs and
include the workflow instanceId - Conceptually, the registered local object is
addressing a workflow instance when it raises an
event
public class OrderEventArgs ExternalDataEventArg
s public OrderEventArgs(Guid instanceId,
string orderId) base(instanceId)
36Local Communications
37Runtime 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
- DefaultWorkflowSchedulerService (asynchronous)
- ManualWorkflowSchedulerService (synchronous for
ASP.NET scenarios) - DefaultWorkflowTransactionService
- SqlWorkflowPersistenceService
38Runtime Services
Host Application
App Domain
Runtime
Services
Out of Box Services are provided that support SQL
Server 2000 2005
PersistenceService stores and retrieves instance
state.
SQL
PersistenceService
TrackingService
TrackingService manages profiles and stores
tracked information.
SchedulerService
TransactionService
Common resource services for managing threading,
timers and creating transactions
39Out-of-Box Services
40Workflow State Management
- Many workflows are long running
- A workflow instance is idle when it has no
runnable work - Persistence services determine whether to unload
the WF when idle - 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
- Closure of the workflow
41Enabling Workflow Persistence
- Persistence Support for Workflow Instances
- Create the SQL database with the
SqlWorkflowStatePersistence schema - Create a Workflow Runtime
- Define Connection String
- Register StatePersistenceService with Runtime
- Start the Workflow
- Loading and Unloading uses StatePersistenceService
private void RunWorkflow() WorkflowRuntime
wr new WorkflowRuntime() string
connectionstring "Initial CatalogPersistenceDa
ta SourcelocalhostIntegrated
SecuritySSPI" wr.AddService(new
SqlWorkflowStatePersistenceService(connectionstr
ing)) wr.CreateWorkflow(typeof(SimpleWorkflow
)).Start()
42Tracking
- 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
Tracking Service
Write
Store
Activities
Profile
Workflow Instance
Host Application
Query
43Enabling 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 CatalogTrackingData
SourcelocalhostIntegrated
SecuritySSPI" //Out of the Box Tracking
Service wr.AddService(new SqlTrackingService(c
onnectionstring)) wr.CreateWorkflow(typeof(Si
mpleWorkflow)).Start()
44Workflow 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
45Rehosting Workflow Designer
46Summary
- A single workflow technology for Windows
- Platform level workflow framework for use within
Microsoft products ISV applications - Will be used by BizTalk Server, Office 2007, MBS
other Microsoft client/server products - 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
2007 - Extensible platform for ISVs
47Windows Workflow Foundation Resources
- Community Site
- Subscribe to the RSS feed for news updates
- Find, download, register Activities
- Find blogs, screencasts, whitepapers, and other
resources - Download samples, tools, and runtime service
components - http//wf.netfx3.com
- MSDN Workflow Page
- Download 12 Hands-on Labs
- http//msdn.microsoft.com/workflow
- Forums
- Ask questions in the forums
- Go to the community site
48(No Transcript)