20080529 windows workflow foundation
DESCRIPTION
TRANSCRIPT
Windows Workflow Foundation
David [email protected]
What is a Workflow?
A set of activities that coordinate peopleand / or software...
EscalateToManagerExample activities…. CheckInventory
Like a flowchart….
…organized into some form of workflow.
Or a state diagram…. or based on rules.
Why Workflow?
“Orders are confirmed in 48 hours and shipped within 30 days.”
“Most suppliers confirm our orders but some forget and we need to follow up.”
“What are the next steps in handling this order?”
Long Running and Stateful
Workflows run for up to 30 days and maintain state throughout
Flexible Control Flow
Flexibility for people to override or skip steps in the workflow
Transparency
Rendering a visualization of next steps based on defined control flow
Real-World Examples Workflow Value-Add
Windows Workflow Foundation
• 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
Windows Workflow Foundation (WF) is the programming model, engine and tools for quickly
building workflow enabled applications on Windows.
Windows Workflow FoundationSingle Workflow Technology for Windows
Windows Workflow Foundation
Key Concepts
Visual Designer: Graphical and code-based construction
Workflows are a set of Activities
Workflows run within a Host Process:any application or server
Developers can build their own Custom Activity Libraries
Components
Base Activity Library: Out-of-box activities and base for custom activities
Runtime Engine: Workflow execution and state management
Runtime Services: Hosting flexibility and communication
Host Process
WindowsWorkflow Foundation
Runtime Engine
Workflows
Activity
Runtime Services
Base Activity Library
Custom Activity Library
Visual DesignerArchitecture
Windows Workflow Foundation
Host Application
Workflow Runtime
Runtime Services
XAML
Workflow Instance
PersistenceLoader
Idle!
Workflow Instance
Workflow Execution
Activities
• Activities are the building blocks of workflows• The unit of execution, re-use and composition
• Basic activities are steps within a workflow
• Composite activities contain other activities
• Base Activity Library provides out-of-box activity set
• Developers author custom activities
• 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
– OOB activities,workflow types, base types
– General-purpose– Activity libraries define
workflow constructs
– Create/Extend/Compose activities
– App-specificbuilding blocks
– First-class citizens
Out-of-Box Activities
– Vertical-specificactivities & workflows
– Best-practice IP &Knowledge
Compliance
RosettaNet
CRM
IT Mgmt
Compose activities
Extend activity
Author new activity
Base Activity Library Custom Activity Libraries Domain-SpecificWorkflow Packages
Extensibility
Workflow AuthoringWorkflow Designer hosted in Visual Studio
XAML
Markup Only
XAML C#/VB
Markup + Code
C#/VB
Code only
Workflow Compiler
C#/VB Compiler
XAML
Markup Only
NET Assembly
Workflow Runtime
Workflow Instance
Workflow AuthoringMultiple Modes
Unified System & Human WorkflowsPeople - Roles
• Flow style: Flexible, Dynamic
• Data: Unstructured, Documents
• Human workflows / interactions
• Ad-hoc, dynamic interactions between people
• Unpredictable & event-driven
Information WorkerDocument Review…
Business to BusinessSupply Chain Mgmt…
Applications - Services
• Flow style: Prescriptive, Protocols
• Data: Structured, Transactional
• System workflows / orchestrations
• Automated, repeatable interactions between systems
• Predictable & relatively static
Unified System & Human Workflows
Rules + data state drive processing order
Rules-driven Activities
• Data-driven
• Simple Conditions,
complex Policies
• Constrained Activity
Group
State Machine Workflow
External events drive processing order
• Reactive, event-driven
• Skip/re-work,
exception handling
• Graph metaphor
Sequential Workflow
Sequential structure Prescribes processing order
• Prescriptive, formal
• Automation scenarios
• Flowchart metaphor
Step1
Step2
State2
State1Event
Event
Rule1
Rule2
Data
Step2
Step1
Flexible Control Flow
Unified System & Human Workflows
• Intended for activities executed in a well-defined, prescriptive order
• Order is executed exactly as defined (begin, wait, end, etc.)
• Base activities include:
IfElse, While, Sequence, Parallel, Code, Compensation Handler, Listen, Delay, CallExternalMethod, HandleExternalEvent, InvokeWorkflow, InvokeWebService, TransactionScope, Terminate
• Similar to BPEL (Business Process
Execution Language)
Sequential Workflows
Unified System & Human WorkflowsState Machine Workflows
• Organizes activities into a finite state machine, defined by group of states and events
• Events trigger transitions between states (event-driven reactive mode)
• Suitable for dynamic workflows
• Allows ad-hoc manipulation of workflows (skip, cancel, etc.)
• Base activities include:
State, EventDriven, SetState, StateInitialization, StateFinalization
Unified System & Human WorkflowsRules-Driven Activities
• Reactive to changes in data (data-driven)
• Rules engine – Policy activity• Set of conditions evaluated as a unit to produce an answer
• Defined as set of rules defined to evaluate various parameters
• Each rule has the IF <condition> THEN <action> ELSE <action> form
• “Forward Chaining” recursively executes affected/dependent rules in the rule set until no new rules become true or a predefined limit is reached
• Not a based activity; code-based implementation
• Constrained Activity Group (CAG)• Set of activities where each activity is associated with a rule/condition
• All grouped conditions evaluated, then associated actions in parallel
• Transitions defined implicitly as rules (as opposed to explicit states)
Hosting Workflows In Applications
• Workflow Integration into Existing Applications
• Create Workflow Runtime
• [Start the Workflow Runtime]
• Create a WorkflowInstance
• Start the Workflow
using System.Workflow.Runtime;
class ExampleHost {static void Main() {
WorkflowRuntime runtime = new WorkflowRuntime();WorkflowInstance instance =
runtime.CreateWorkflow(typeof(ExampleWorkflow));instance.Start();...
}}
Workflow
Method
Event
Communicating with Applications
• .NET object managed by the runtime acts as a communication intermediary between the host and the workflow instances• Raises events into the workflow (HandleExternalEvent)
• Proxy for outbound method calls (CallExternalMethod)
• Four components:• Local Communication Activities
• Contract
• Local Service
• EventArgs
Application
ExternalDataExchangeService
Workflow RuntimeOutput
Input
Local Process Communication
Workflow Runtime
Communicating with Applications
ServiceHost
ServiceDescription
ServiceBehavior
OperationBehavior
Workflow.cs orWorkflow.xoml
App.config
Service Runtime
OperationInvoker
OperationSelector
InstanceProvider
MessageInspector
ListenerChannel
Service Instance
Operation 1
Operation 2Workflow
ServiceHost
WorkflowServiceBehavior
WorkflowOperationBehavior
WorkflowOperationInvoker
DurableInstanceProvider
MessageContextInspector
ContextChannel
Workflow Instance
ReceiveActivity 1
ReceiveActivity 2
WF Persistence DB
Service.cs
WCF Integration
Communicating with Applications
• Service implemented as Workflow• Leverage Workflow development experience
• Enforces application protocol by default
• Allows long-running, durable Services
• Workflow hosted as Service• ServiceContract provides typed interface for integrating
with the Workflow
• Messages enforce by-value, serializable data
• Workflows can be message-activated
Workflow Services
Runtime ServicesHost Application
App Domain
SQL
Out of Box Services are provided that support SQL Server
Common resource services for managing threading, timers and creating transactions
PersistenceServicestores and retrieves instance state.
TrackingServicemanages profiles and stores tracked information.
Runtime
Services
PersistenceService
TrackingService
SchedulerService
TransactionService
Runtime Services
• 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
Workflow State Management
Runtime Services
• 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
TrackingInformation
TrackingService
Host Application
StoreActivities
WorkflowInstance Query
Write
Profile
Tracking
Workflow Foundation and BizTalk
MessagingDesignTools
BusinessActivityMonitorAndAdminTools
Orchestration
Transformation
Adapters
Accelerators BizTalk Server:Enterprise application integration (B2B, EAI, BPM, SOA scenarios)
System workflows
Manageability, high-availability, scalability
User-oriented tracking and monitoring facilities (e.g., BAM)
Workflow
.NET 3.0
Visual Studio Designer
Windows Workflow Foundation
Workflow Foundation:Application-hosted workflows
Human workflows (state machine, dynamic update, etc.)
Client-based deployment scenarios
Developer-oriented tracking API’s
© 2008 Microsoft Corporation. All rights reserved. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.
Thank you
blogs.msdn.com/dachou
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
State Machine Workflows
• 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
Concepts
State Machine Workflows
• 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 Machine Workflow
Event Driven
State Initialization
State
Set State
State
State Finalization
Activities
State Machine Workflows
On Order CreatedOn Order Processed
OrderCreated Order
Processed
OrderShipped
On Order Shipped
On Order Completed
On Order Completed
Waiting toCreate Order
On Order Completed
On Order Shipped
OrderCompleted
Order Processing Example
State Machine Workflows
• 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?
Querying
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
Activities
• 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 that’s available to you as developers
Base Activity Library
Activities: An Extensible Approach
OOB activities,workflow types,base typesGeneral-purposeActivity libraries define workflow constructs
Create/Extend/Compose activitiesApp-specificbuilding blocksFirst-class citizens
Base ActivityLibrary
Custom ActivityLibraries
Author new activity
Out-of-Box Activities
Extend activity
Compose activities
Vertical-specificactivities & workflowsBest-practice IP &Knowledge
Domain-SpecificWorkflow Packages
Compliance
RosettaNet
CRM
IT Mgmt
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
Simplicity
Flexibility
Code Activity
InvokeMethod &EventSink
Custom Activities
InvokeWebServiceActivity
Workflow Execution LogicCustom Activities
Activities
using System.Workflow.ComponentModel;
public partial class SendMail : System.Workflow.ComponentModel.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";
}
}
SendMail Example
Behaviors
Activities
• Each activity has an associated set of components
• Components are associated through attributes on the Activity Definition
Required
Optional (defaults provided)
// Companion classes
[Designer(typeof(MyDesigner))]
[CodeGenerator(typeof(MyCodeGen))]
[Validator(typeof(MyValidator))]
// Behaviors
[SupportsTransaction]
public class MyActivity: Activity {...}
Activity
Designer
Validator
Serializer
CodeGenerator
Component Model
Activities
• Class that defines the activity’s 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
Definition Class
Activities
• 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
Execution Status
Activity: Execution
• Activity Execution Methods
• Initialize()
• Execute()
• Cancel()
• Compensate()
• HandleFault()
Transition Types
Activity
Runtime
Executing Canceled Compesating
Initialized FaultedClosed
Activities
• 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
Custom Activity Designer
Activities
• 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.
Advanced Composite Execution
Activities
protected override Status Execute(ActivityExecutionContext context)
{
Activity childActivity = this.ExecutableActivities[0];
EventHandler<ActivityExecutionStatusChangeEventArgs> OnClosed = null;
OnClosed = delegate
{
childActivity.Closed -= OnClosed;
if(this.ExecutionStatus == ActivityExecutionStatus.Canceling)
context.CloseActivity();
else if (ExecutionStatus == ActivityExecutionStatus.Executing)
{
this.index++;
if (this.ExecutableActivities.Count > this.index)
{
childActivity = this.ExecutableActivities[this.index];
childActivity.Closed += OnClosed;
context.ExecuteActivity(childActivity );
}
else
context.CloseActivity();
}
};
childActivity.Closed += OnClosed;
context.ExecuteActivity(childActivity);
return ActivityExecutionStatus.Executing;
}
Sequence Activity – Execute()
Activities
Template Activity
Context Owner Activities
Children Contexts of ForEach activity
Context 1
Context 2
Context 3
Default Workflow
Context
ForEach Activity Execution Contexts
Activities
• 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!
Summary
Local 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
Wo
rkfl
ow
Ru
nti
me
Local 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 EventHandler<OrderEventArgs> OrderSubmitted;
// The workflow instance will later call one of these methods
void Approve(string orderId);
void Reject(string orderId);
}
Local Communication ServiceImplement class• Implement the interface you’ve 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 EventHandler<OrderEventArgs> 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());
Local 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 : ExternalDataEventArgs
{
public OrderEventArgs(Guid instanceId, string orderId)
: base(instanceId)
{
…
}
}
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
Summary• 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
Windows 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