Windows Workflow Foundation как инструмент в автоматизации тестирования
Introduction to Windows Workflow Foundation Matt Winkler Technical Evangelist, Windows Workflow...
-
date post
18-Dec-2015 -
Category
Documents
-
view
238 -
download
1
Transcript of Introduction to Windows Workflow Foundation Matt Winkler Technical Evangelist, Windows Workflow...
Introduction toWindows Workflow Foundation
Introduction toWindows Workflow Foundation Matt WinklerTechnical Evangelist, Windows Workflow Foundationhttp://blogs.msdn.com/[email protected]
AgendaAgenda
What is Windows Workflow Foundation?Architecture & Core conceptsBuilding WorkflowsBuilding ActivitiesRuntime ServicesWorkflow Communication
Windows Workflow FoundationWindows Workflow Foundation
Single workflow technology for WindowsAvailable to all customers of WindowsAvailable for use across a broad range of scenarios
Redefining workflowExtensible framework & API to build workflow centric productsOne technology for human and system workflow
Take workflow mainstreamBring declarative workflow to any .NET developerFundamental part of the Office 2007Strong workflow partner & solution ecosystem
Windows Workflow Foundation is the programming model, engine and tools for quickly building workflow enabled applications on Windows.
PackagingPackaging
Third foundational .NET Framework 3.0Windows Communication Foundation (“Indigo”)Windows Presentation Foundation (“Avalon”)Windows Workflow Foundation (“WinOE/WinWS”)Cardspace (“Infocard”)
Support for Windows XP & Windows Server 2003Licensed as part of Windows Released!
What is a workflow?What is a workflow?
A set of activities that coordinate people
and / or software...EscalateToManagerExample activities…. CheckInventory
Like a flowchart….
…organized into some form of workflow.
Or a state diagram…. or based on rules.
Windows Workflow FoundationWindows Workflow Foundation
Key Concepts
Host Process
WindowsWorkflow 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 ActivitiesWorkflows run within a Host Process: any application or serverDevelopers 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
Building a WorkflowBuilding a Workflow
What are Activities?What are Activities?
An activity is a step in a workflowHas properties and events that are programmable within your workflow codeHas methods (e.g. Execute) that are only invoked by the workflow runtime
Think of Forms & ControlsActivity == ControlsWorkflows == Forms
Activities fall under two broad categoriesBasic – steps that “do work”Composite – manage a set of child activities
Base Activity LibraryBase 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 ActivitiesBase Activities have been built using the same framework that’s available to you as developers
Activities: An Extensible ApproachActivities: 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
Why build custom activities?Why build custom activities?
Activity is unit of:ExecutionReuseComposition
Activities enable workflow modelingCustom activity examples
SendEmail, FileSystemEvent, PurchaseOrderCreated, AssignTask, etc.
Write custom activities forReusing workflow logicIntegrating with technologiesModeling advanced control flowsModeling various workflow styles
Simplicity
Flexibility
Code Code ActivityActivity
InvokeMethod InvokeMethod &&EventSinkEventSinkCustom Custom ActivitiesActivities
InvokeWebService InvokeWebService ActivityActivity
Workflow Execution LogicWorkflow Execution Logic
Example: A SendMail ActivityExample: A SendMail Activityusing 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 ModelActivity Component Model
Each activity has an associated set of componentsComponents 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 {...}
ActivityActivity
Code Code GeneratorGenerator
DesignerDesigner
ValidatorValidator
SerializerSerializer
BehaviorsBehaviors
Activity Execution StatusActivity Execution Status
Returned by Execute() methodCan be determined by a parent activity or workflow
this.sendEmail1.Status
Tracked by a Tracking Runtime ServiceActivity.Status Enumeration
InitializedExecutingCompensatingCancellingClosedFaulting
Activity ExecutionActivity Execution
Activity Execution MethodsInitialize()Execute()Cancel()Compensate()HandleFault()
Transition Types
ActivityRuntime
InitializedInitialized
ExecutingExecuting
ClosedClosed
CanceledCanceled CompensatingCompensating
FaultedFaulted
Advanced Composite Activity ExecutionAdvanced Composite Activity Execution
Activities may need long-running execution environments as a part of their executionThis opens up interesting possibilities of modeling advanced control flowsLoops, Continuations, Dynamic Activities etc.
Sequence Activity – Execute()Sequence Activity – Execute()protected override Status Execute(ActivityExecutionContext context)protected override Status Execute(ActivityExecutionContext context){{
Activity Activity childAchildActivity = this.ExecutableActivities[0];ctivity = this.ExecutableActivities[0];EventHandler<ActivityEventHandler<ActivityExecutionExecutionStatusChangeEventArgs> OnClosed = null;StatusChangeEventArgs> OnClosed = null;OnClosed = delegateOnClosed = delegate{{
childAchildActivity.Closed -= OnClosed;ctivity.Closed -= OnClosed;if(this.if(this.ExecutionExecutionStatus == Status == ActivityExecutionActivityExecutionStatus.Canceling)Status.Canceling) context.CloseActivity();context.CloseActivity();else if (else if (ExecutionExecutionStatus == Status == ActivityExecutionActivityExecutionStatus.Executing)Status.Executing){{ this.index++;this.index++; if (this.ExecutableActivities.Count > this.index)if (this.ExecutableActivities.Count > this.index) {{
childAchildActivityctivity = this.ExecutableActivities[this.index];= this.ExecutableActivities[this.index];
childAcchildActivity.Closed += OnClosed;tivity.Closed += OnClosed; context.ExecuteActivity(childActivity );context.ExecuteActivity(childActivity );
}} elseelse context.CloseActivity();context.CloseActivity();}}
};};childActivitychildActivity.Closed.Closed += OnClosed; += OnClosed;context.ExecuteActivity(childActivity);context.ExecuteActivity(childActivity);return return ActivityExecutionActivityExecutionStatus.Executing;Status.Executing;
}}
ForEach Activity Execution ContextsForEach Activity Execution Contexts
Template Activity
Context Owner Activities
Children Contexts of ForEach activity
Context 1
Context 2
Context 3
Default Workflow Context
Building a Basic ActivityBuilding a Basic Activity
Activity SummaryActivity Summary
An Activity is a key concept of Windows Workflow FoundationWF allows you to write custom activities to model your application control flow explicitlyActivities are the fundamental unit of:
Execution, Reuse, & Composition
Two broad types of activities:Basic & Composite
Activity Designer simplifies the development of custom activities – especially compositesSystem.Workflow.ComponentModel provides the framework to build custom activitiesCall to action: Write Activities!
Benefits of State Machine WorkflowsBenefits of State Machine Workflows
FlexibilityAbility to handle multiple business exceptionsAbility to handle multiple paths leading to the same goal
VisibilityAbility to view the past, present and future of a business process
ControlAbility of the business end user to control the flow of the process at run time
State Machine Workflow ConceptsState Machine Workflow Concepts
The basic elements of a state machine workflow
StatesEventsActionsTransitions
A state machine workflow is composed of a set of statesIn a given state a set of events can be receivedBased 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 WorkflowActivities in a State Machine Workflow
State Machine WorkflowRoot activity that is the container for a state machine
StateRepresents the state of the state machine
EventDrivenUsed to handle an event in a given state
SetStateUsed to transition from one state to another
StateInitializationUsed for default action on entering a state
StateFinalizationUse for default action on leaving a state
Event Driven
State Machine Workflow
Event Driven
State Initialization
StateState
Set State
State
State Finalization
Order Processing ExampleOrder Processing Example
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
Querying a State Machine WorkflowQuerying 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 workflowUsed 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?
A State Machine WorkflowA State Machine Workflow
Runtime ServicesRuntime Services
The workflow runtime is lightweightDepends on a set of services
Only Threading is requiredOften you also want Transactions and Persistence
Add services programmatically or using a config file What ships in System.Workflow.Runtime.Hosting?
Abstract service definitionsConcrete service implementations
DefaultWorkflowSchedulerService (asynchronous)ManualWorkflowSchedulerService (synchronous; for ASP.NET scenarios)DefaultWorkflowTransactionServiceSqlWorkflowPersistenceService
Runtime ServicesRuntime ServicesHost 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
Out-of-Box ServicesOut-of-Box ServicesManualWorkflowSchedulerService
Synchronous threading service used for in-line execution; used by ASP module for web services
DefaultWorkflowSchedulerService
Used for asynchronous execution of workflows; uses default .Net thread pool
DefaultWorkflowTransactionService
Creates .NET transactions
SharedConnectionWorkflowCommitWorkBatchService
Sql services share connection to SqlServer
SqlWorkflowPersistenceService
Stores workflow instance state information in SqlServer/MSDE
SqlTrackingService Stores tracking information in SqlServer/MSDE
Workflow State ManagementWorkflow State Management
Many workflows are long runningA workflow instance is idle when it has no runnable workPersistence services determine whether to unload the WF when idleLoading/unloading is not a concern of the workflow developer or the application developer
Persistence points are checkpointsTransactionsEnable crash recoveryPersistence occurs at:
Closure of a transactionClosure of any activity marked [PersistOnClose]Closure of the workflow
Enabling Workflow PersistenceEnabling Workflow PersistencePersistence Support for Workflow Instances
Create the SQL database with the SqlWorkflowStatePersistence schemaCreate a Workflow RuntimeDefine Connection StringRegister StatePersistenceService with RuntimeStart the WorkflowLoading 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();}
TrackingTracking
Track all state changes and data within the workflowEmit tracking info from codeDynamic changesProfile
XML file that specifies what to trackIncludes and excludes, state changes, data context, typesObject model to create
TrackingInformation Tracking
Service
Host Application
StoreActivities
WorkflowInstance Query
WriteProfile
Enabling Workflow TrackingEnabling Workflow Tracking
Tracking Support for Workflow InstancesDefine tracking profilesCreate workflow runtimeDefine connection stringRegister one or more TrackingService’s with the WorkflowRuntimeStart the workflowQuery 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();}
Workflow Authoring ToolsWorkflow Authoring Tools
Line of Business Manager / End usersWizards
Business AnalystVisio Like
Script Developers or VARsScript Like
Code Developers or ISVsWindows Workflow Foundation Designer
Commonality between Tools:Support a common object model for describing Workflow informationThe object model needs to be exchangeable between tools
Rehosting Workflow DesignerRehosting Workflow Designer
SummarySummaryA single workflow technology for Windows
Platform level workflow framework for use within Microsoft products & ISV applicationsWill be used by BizTalk Server, Office 2007, MBS & other Microsoft client/server productsAvailable to all Windows customers
Microsoft is redefining workflowUnified technology for System & Human workflowMultiple styles: sequential, rules-based, state machineSupports dynamic interaction
Microsoft is taking workflow mainstreamConsistent and familiar programming model for reaching mainstream application developerAvailable to millions of end-users through Office 2007Extensible platform for ISVs
Community SiteSubscribe to the RSS feed for news & updatesFind, download, & register ActivitiesFind blogs, screencasts, whitepapers, and other resourcesDownload samples, tools, and runtime service componentshttp://wf.netfx3.com
MSDN® Workflow PageDownload 12 Hands-on Labshttp://msdn.microsoft.com/workflow
ForumsAsk questions in the forumsGo to the community site
Windows Workflow Foundation ResourcesWindows Workflow Foundation Resources