420 likes | 747 Views
Introduction to Windows Workflow Foundation . Matt Winkler Technical Evangelist, Windows Workflow Foundation http://blogs.msdn.com/mwinkle mwinkle@microsoft.com. Agenda. What is Windows Workflow Foundation? Architecture & Core concepts Building Workflows Building Activities
E N D
Introduction toWindows Workflow Foundation Matt Winkler Technical Evangelist, Windows Workflow Foundation http://blogs.msdn.com/mwinkle mwinkle@microsoft.com
Agenda • What is Windows Workflow Foundation? • Architecture & Core concepts • Building Workflows • Building Activities • Runtime Services • Workflow Communication
Windows 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
Packaging • 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!
What 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….
Windows Workflow Foundation Visual Designer KeyConcepts 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
What 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
Base 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 that’s available to you as developers
Domain-SpecificWorkflow Packages Compliance CRM Extend activity Compose activities RosettaNet Author new activity IT Mgmt • Vertical-specificactivities & workflows • Best-practice IP &Knowledge Activities: 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
Why 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
Example: A SendMail Activity 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"; } }
Activity 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(typeof(MyValidator))] // Behaviors [SupportsTransaction] public class MyActivity: Activity {...} Serializer Code Generator Required Optional (defaults provided)
Activity 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
Executing Canceled Initialized Faulted Closed Compensating Activity Execution • Activity Execution Methods • Initialize() • Execute() • Cancel() • Compensate() • HandleFault() Transition Types Runtime Activity
Advanced 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.
Sequence Activity – Execute() 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; }
ForEach Activity Execution Contexts Template Activity Context Owner Activities Default Workflow Context Context 1 Context 2 Context 3 Children Contexts of ForEach activity
Activity 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!
Benefits 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
State 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
Activities 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
Order 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
Querying 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?
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 • DefaultWorkflowSchedulerService (asynchronous) • ManualWorkflowSchedulerService (synchronous; for ASP.NET scenarios) • DefaultWorkflowTransactionService • SqlWorkflowPersistenceService
Runtime 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
Workflow 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
Enabling 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 Catalog=Persistence;Data Source=localhost;Integrated Security=SSPI;"; wr.AddService(new SqlWorkflowStatePersistenceService(connectionstring)); wr.CreateWorkflow(typeof(SimpleWorkflow)).Start(); }
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 Tracking Service Write Store Activities Profile Workflow Instance Host Application Query
Enabling Workflow Tracking • Tracking Support for Workflow Instances • Define tracking profiles • Create workflow runtime • Define connection string • Register one or more TrackingService’s with the WorkflowRuntime • Start the workflow • Query tracking database – instance and activity information private void RunWorkflow() { WorkflowRuntime wr = newWorkflowRuntime(); string connectionstring = "Initial Catalog=Tracking;Data Source=localhost;Integrated Security=SSPI;"; //Out of the Box Tracking Service wr.AddService(new SqlTrackingService(connectionstring)); wr.CreateWorkflow(typeof(SimpleWorkflow)).Start(); }
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