Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to Windows Workflow Foundation Matt Winkler Technical Evangelist, Windows Workflow Foundation

Similar presentations


Presentation on theme: "Introduction to Windows Workflow Foundation Matt Winkler Technical Evangelist, Windows Workflow Foundation"— Presentation transcript:

1 Introduction to Windows Workflow Foundation Matt Winkler Technical Evangelist, Windows Workflow Foundation http://blogs.msdn.com/mwinkle mwinkle@microsoft.com

2 Agenda What is Windows Workflow Foundation? Architecture & Core concepts Building Workflows Building Activities Runtime Services Workflow Communication

3 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 is the programming model, engine and tools for quickly building workflow enabled applications on Windows.

4 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!

5 What is a workflow? A set of activities that coordinate people and / or software... EscalateToManager Example activities…. CheckInventory Like a flowchart…. …organized into some form of workflow. Or a state diagram….or based on rules.

6 Windows Workflow Foundation Key Concepts Host Process Windows Workflow Foundation Runtime Engine A Workflow An Activity Runtime Services Base Activity Library Custom Activity Library Visual Designer 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

7 Building a Workflow

8 Workflow Authoring Modes.NET assembly ctor defines workflow Markup Only “Declarative” XAML Markup and Code C#/VB Code Only Application Generated XAML C#/VB XML defines workflow structure logic and data flow XML defines workflow Code-beside defines extra logic Code creates workflow in constructor XAML C#/VB App creates activity tree and serializes Workflow Compiler wfc.exe C#/VB Compiler

9 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

10 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

11 Activities: An Extensible Approach OOB activities, workflow types, base types General-purpose Activity libraries define workflow constructs Create/Extend/ Compose activities App-specific building blocks First-class citizens Base Activity Library Custom Activity Libraries Author new activity Out-of-Box Activities Extend activity Compose activities Vertical-specific activities & workflows Best-practice IP & Knowledge Domain-Specific Workflow Packages Compliance RosettaNet CRM IT Mgmt

12 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 Simplicity Flexibility Code Activity InvokeMethod & EventSink Custom Activities InvokeWebService Activity Workflow Execution Logic

13 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"; }

14 Activity Component Model 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 Code Generator Designer Validator Serializer Behaviors

15 Activity Definition Class 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

16 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

17 Activity Execution Activity Execution Methods Initialize() Execute() Cancel() Compensate() HandleFault() Transition Types Activity Runtime Initialized Executing Closed Canceled Compensating Faulted

18 Custom 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

19 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.

20 Sequence Activity – Execute() protected override Status Execute(ActivityExecutionContext context) { Activity childActivity = this.ExecutableActivities[0]; EventHandler OnClosed = null; OnClosed = delegate { childActivity.Closed -= OnClosed; if(this.ExecutionStatus == ActivityExecutionStatus.Canceling) context.CloseActivity(); context.CloseActivity(); else if (ExecutionStatus == ActivityExecutionStatus.Executing) { this.index++; this.index++; if (this.ExecutableActivities.Count > this.index) if (this.ExecutableActivities.Count > this.index) { childActivity = this.ExecutableActivities[this.index]; childActivity = this.ExecutableActivities[this.index]; childActivity.Closed += OnClosed; childActivity.Closed += OnClosed; context.ExecuteActivity(childActivity ); context.ExecuteActivity(childActivity ); } } else else context.CloseActivity(); context.CloseActivity();}}; childActivity.Closed += OnClosed; context.ExecuteActivity(childActivity); return ActivityExecutionStatus.Executing; }

21 ForEach Activity Execution Contexts Template Activity Context Owner Activities Children Contexts of ForEach activity Context 1 Context 2 Context 3 Default Workflow Context

22 Building a Basic Activity

23 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!

24 Flexible Control Flow Rules-driven Activities Step2 Step1 Rule1 Rule2 Data Rules + data state drive processing order Data-driven Simple Conditions, complex Policies Constrained Activity Group State Machine Workflow State2 State1 Event External events drive processing order Reactive, event-driven Skip/re-work, exception handling Graph metaphor Sequential Workflow Step1 Step2 Sequential structure prescribes processing order Prescriptive, formal Automation scenarios Flowchart metaphor

25 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

26 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

27 Activities in a 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 Machine Workflow Event Driven State Initialization State Set State State State Finalization

28 Order Processing Example On Order Created On Order Processed Order Created Order Processed Order Shipped On Order Shipped On Order Completed On Order Completed Waiting to Create Order On Order Completed On Order Shipped Order Completed

29 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?

30 A State Machine Workflow

31 Workflow Method Event 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 ExternalDataExchangeService Workflow Runtime Output Input

32 Local Communication Activities Model 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

33 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) Methods for outbound data (from workflow) Mark as [ExternalDataExchange] [ExternalDataExchange] public interface IOrderManager { // Create a workflow instance to process the order event EventHandler OrderSubmitted; // The workflow instance will later call one of these methods void Approve(string orderId); void Reject(string orderId); }

34 Local Communication Service Implement 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 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());

35 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 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) { … }

36 Local Communications

37 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

38 Runtime Services Host Application App Domain SQL Out of Box Services are provided that support SQL Server 2000 & 2005 Common resource services for managing threading, timers and creating transactions PersistenceService stores and retrieves instance state. TrackingService manages profiles and stores tracked information. Runtime Services PersistenceService TrackingService SchedulerService TransactionService

39 Out-of-Box Services ManualWorkflowSchedulerS ervice Synchronous threading service used for in-line execution; used by ASP module for web services DefaultWorkflowSchedulerS ervice Used for asynchronous execution of workflows; uses default.Net thread pool DefaultWorkflowTransaction Service Creates.NET transactions SharedConnectionWorkflow CommitWorkBatchService Sql services share connection to SqlServer SqlWorkflowPersistenceServ ice Stores workflow instance state information in SqlServer/MSDE SqlTrackingServiceStores tracking information in SqlServer/MSDE

40 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

41 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(); }

42 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 Host Application Store Activities Workflow Instance Query Write Profile

43 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 = 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.CreateWorkflow(typeof(SimpleWorkflow)).Start(); }

44 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

45 Rehosting Workflow Designer

46 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

47 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 Windows Workflow Foundation Resources

48


Download ppt "Introduction to Windows Workflow Foundation Matt Winkler Technical Evangelist, Windows Workflow Foundation"

Similar presentations


Ads by Google