4156 contents 40 · windows workflow foundation • windows workflow foundation (wf) is a framework...

87
Object Innovations Course 4156 Student Guide Revision 4.0 Windows Workflow Foundation Using C#

Upload: others

Post on 22-Mar-2020

11 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

Object Innovations Course 4156

Student Guide Revision 4.0

Windows Workflow Foundation Using C#

Page 2: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

Rev. 4.0 Copyright ©2011 Object Innovations Enterprises, LLC ii All Rights Reserved

Windows Workflow Foundation Using C# Rev. 4.0 Student Guide Information in this document is subject to change without notice. Companies, names and data used in examples herein are fictitious unless otherwise noted. No part of this document may be reproduced or transmitted in any form or by any means, electronic or mechanical, for any purpose, without the express written permission of Object Innovations. Product and company names mentioned herein are the trademarks or registered trademarks of their respective owners.

® is a registered trademark of Object Innovations. Author: Robert J. Oberg Copyright ©2011 Object Innovations Enterprises, LLC All rights reserved. Object Innovations 877-558-7246 www.objectinnovations.com Published in the United States of America.

Page 3: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

Rev. 4.0 Copyright ©2011 Object Innovations Enterprises, LLC iii All Rights Reserved

Table of Contents (Overview) Chapter 1 Workflow Foundation Conceptual Overview Chapter 2 Getting Started with WF 4 Chapter 3 Primitive and Control Flow Activities Chapter 4 Custom Activities Chapter 5 Workflow Hosting Chapter 6 Collection and Parallel Activities Chapter 7 More about Custom Activities Chapter 8 Flowchart and State Machine Chapter 9 Persistence Chapter 10 Workflow Services Chapter 11 Debugging and Error Handling Appendix A Learning Resources

Page 4: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

Rev. 4.0 Copyright ©2011 Object Innovations Enterprises, LLC iv All Rights Reserved

Directory Structure

• Install the course software by running the self-extractor Install_WfCs_40.exe.

• The course software installs to the root directory C:\OIC\WfCs.

− Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02 and so on.

− The Labs directory contains one subdirectory for each lab, named after the lab number. Starter code is frequently supplied, and answers are provided in the chapter directories.

− The Demos directory is provided for performing in-class demonstrations led by the instructor.

• The directory C:\OIC\Data contains a sample database and command files for creating and removing a SQL Server instance store for persistence of workflows.

Page 5: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

Rev. 4.0 Copyright ©2011 Object Innovations Enterprises, LLC v All Rights Reserved

Table of Contents (Detailed)

Chapter 1: Workflow Foundation Conceptual Overview................................................. 1 What Is Workflow?............................................................................................................. 3 Windows Workflow Foundation......................................................................................... 4 Workflows........................................................................................................................... 5 Activities ............................................................................................................................. 6 Standard Activities.............................................................................................................. 7 Runtime Services ................................................................................................................ 8 Workflow Business Scenario.............................................................................................. 9 High Level Workflow....................................................................................................... 10 Details of While Activity .................................................................................................. 11 Structure of the Solution ................................................................................................... 12 Orders Folder .................................................................................................................... 13 Manual Step in the Verification........................................................................................ 14 Main Console Display ...................................................................................................... 15 Issues Folder ..................................................................................................................... 16 Invoices Folder ................................................................................................................. 17 Learning Microsoft’s WF ................................................................................................. 18 Windows Workflow Foundation 3.................................................................................... 19 Orders Workflow in WF 3 ................................................................................................ 20 Windows Workflow Foundation 4.................................................................................... 21 Summary ........................................................................................................................... 22

Chapter 2: Getting Started with WF 4 ............................................................................. 23 Workflow Structure .......................................................................................................... 25 Minimal Workflow Program............................................................................................. 26 Sequence Activity ............................................................................................................. 27 Visual Studio Workflow Projects ..................................................................................... 28 Workflow Designer Demo................................................................................................ 29 Variables ........................................................................................................................... 33 Assign Activity ................................................................................................................. 34 HelloAssign Workflow ..................................................................................................... 35 Visual Basic Expressions.................................................................................................. 36 Arguments......................................................................................................................... 37 Argument Example ........................................................................................................... 38 Lab 2A .............................................................................................................................. 39 Control Flow Activities .................................................................................................... 40 While Activity................................................................................................................... 41 Lab 2B............................................................................................................................... 42 Summary ........................................................................................................................... 43

Chapter 3: Primitive and Control Flow Activities........................................................... 53 Built-In Primitive Activities ............................................................................................. 55 InvokeMethod (Static) ...................................................................................................... 56

Page 6: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

Rev. 4.0 Copyright ©2011 Object Innovations Enterprises, LLC vi All Rights Reserved

Workflow (Static InvokeMethod)..................................................................................... 57 Variables in the Workflow................................................................................................ 58 InvokeMethod (Instance) .................................................................................................. 59 Workflow (Instance InvokeMethod) ................................................................................ 60 Invoking .NET Framework Library.................................................................................. 61 Input in Workflows ........................................................................................................... 62 Prompt Example Workflow .............................................................................................. 63 Delay Activity................................................................................................................... 64 Lab 3A .............................................................................................................................. 65 Control Flow Activities .................................................................................................... 66 Parallel .............................................................................................................................. 67 Parallel Activity Example................................................................................................. 68 If........................................................................................................................................ 69 If … Else ........................................................................................................................... 70 While................................................................................................................................. 71 DoWhile............................................................................................................................ 72 Switch<T> ........................................................................................................................ 73 Switch<T> Example ......................................................................................................... 74 Lab 3B............................................................................................................................... 77 Summary ........................................................................................................................... 78

Chapter 4: Custom Activities............................................................................................. 91 Why Custom Activities? ................................................................................................... 93 Authoring Custom Activities ............................................................................................ 94 Arguments in Custom Activities....................................................................................... 95 Activity Class Hierarchy................................................................................................... 96 CodeActivity ..................................................................................................................... 97 CodeActivityContext ........................................................................................................ 98 CodeActivity<TResult>.................................................................................................... 99 CodeActivity Demo ........................................................................................................ 100 Lab 4A ............................................................................................................................ 105 Composing Existing Activities ....................................................................................... 106 Demo: Composing Activities.......................................................................................... 107 Lab 4B............................................................................................................................. 111 Summary ......................................................................................................................... 112 Bonus Example ............................................................................................................... 124

Chapter 5: Workflow Hosting ......................................................................................... 125 WorkflowInvoker............................................................................................................ 127 Specifying Input to a Workflow ..................................................................................... 128 Using Dictionaries .......................................................................................................... 129 Output Argument ............................................................................................................ 130 Invoking a Generic Activity ........................................................................................... 131 Result Output Argument ................................................................................................. 132 Reusing a Workflow ....................................................................................................... 133 Workflow Timeout.......................................................................................................... 134

Page 7: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

Rev. 4.0 Copyright ©2011 Object Innovations Enterprises, LLC vii All Rights Reserved

Timeout with Idle Time .................................................................................................. 135 Long Computation without Idle Time ............................................................................ 137 Invoking the Long Computation..................................................................................... 139 Long Computation with Timeout.................................................................................... 140 Lab 5A ............................................................................................................................ 141 Hosting a Workflow in Windows ................................................................................... 142 Windows Host Code ....................................................................................................... 143 WorkflowInvoker Instance Methods .............................................................................. 144 WorkflowInvoker Asynchronous Methods..................................................................... 145 Asynchronous Demonstration......................................................................................... 146 HelloAsync Code (Invoker)............................................................................................ 148 Example Workflow......................................................................................................... 150 Effect of Sleep................................................................................................................. 151 WorkflowApplication ..................................................................................................... 152 WorkflowApplication Demo .......................................................................................... 153 Thread Synchronization.................................................................................................. 157 Arguments....................................................................................................................... 158 WorkflowApplication Async Demo ............................................................................... 159 HelloAsync Code (Application) ..................................................................................... 161 WorkflowApplication Delegates .................................................................................... 162 Manual Control of Workflows........................................................................................ 163 Stopping Workflow Execution ....................................................................................... 164 Workflow Manual Control Example .............................................................................. 165 Enqueue Workflow ......................................................................................................... 166 Dequeue Workflow......................................................................................................... 167 Host Code for Enqueue Workflow ................................................................................. 168 Host Code for Dequeue Workflow ................................................................................. 169 Lab 5B............................................................................................................................. 170 Hosting a Workflow in ASP.NET .................................................................................. 171 ASP.NET Workflow Host .............................................................................................. 172 Lab 5C............................................................................................................................. 173 Summary ......................................................................................................................... 174

Chapter 6: Collection and Parallel Activities................................................................. 183 Collection Activities ....................................................................................................... 185 Collection Activities Example ........................................................................................ 186 Top-Level Workflow ...................................................................................................... 187 Process Command Activity............................................................................................. 188 Add and Show................................................................................................................. 189 Remove and Clear........................................................................................................... 190 ForEach<T> Activity...................................................................................................... 191 ParallelForEach<T>........................................................................................................ 192 Factor Workflow Example.............................................................................................. 193 Using ForEach<T> ......................................................................................................... 194 Using ParallelForEach<T> ............................................................................................. 195 Using AsyncCodeActivity .............................................................................................. 196

Page 8: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

Rev. 4.0 Copyright ©2011 Object Innovations Enterprises, LLC viii All Rights Reserved

Example Code................................................................................................................. 197 Host Code........................................................................................................................ 198 Asynchronous Activities in WF...................................................................................... 199 Factor.cs .......................................................................................................................... 200 FactorNumber.cs............................................................................................................. 201 Async Coding: BeginExecute ......................................................................................... 202 Async Coding: EndExecute ............................................................................................ 203 Lab 6 ............................................................................................................................... 204 Summary ......................................................................................................................... 205

Chapter 7: More about Custom Activities ..................................................................... 211 Waiting for Input............................................................................................................. 213 Bookmarks ...................................................................................................................... 214 NativeActivity................................................................................................................. 215 Bookmark Example ........................................................................................................ 216 GetTwoInt Custom Activity ........................................................................................... 217 Host Program .................................................................................................................. 218 Passing Data on Resume................................................................................................. 219 Bookmark Options .......................................................................................................... 220 Bookmarks and Threads ................................................................................................. 221 Threads in Host Code ..................................................................................................... 222 Threads in Workflow ...................................................................................................... 223 Sample Threading Output ............................................................................................... 224 Lab 7 ............................................................................................................................... 225 A Compute Intensive Workflow..................................................................................... 226 EnqueueLoop .................................................................................................................. 227 DequeueLoop.................................................................................................................. 228 FactorQueueBookmark Solution .................................................................................... 229 FactorConsoleWF ........................................................................................................... 230 More Experiments........................................................................................................... 232 Pick Activity ................................................................................................................... 233 Pick Example .................................................................................................................. 234 Get and Check Answer ................................................................................................... 235 Set Timer......................................................................................................................... 236 Summary ......................................................................................................................... 237

Chapter 8: Flowchart and State Machine ...................................................................... 247 Workflow Modeling Styles............................................................................................. 249 Flowchart Activities........................................................................................................ 250 Flowchart Activity Designer........................................................................................... 251 Demo: Absolute Value Flowchart .................................................................................. 252 Auto-Connect.................................................................................................................. 256 Using FlowDecision ....................................................................................................... 257 Flowchart and Custom Activities ................................................................................... 260 Lab 8A ............................................................................................................................ 261 State Machine Workflows in WF 4 ................................................................................ 262

Page 9: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

Rev. 4.0 Copyright ©2011 Object Innovations Enterprises, LLC ix All Rights Reserved

State Machine Workflow Modeling ............................................................................... 263 State Machine Workflow Example................................................................................. 264 Power On Transition ....................................................................................................... 265 TransitionCommand Trigger .......................................................................................... 266 Warming State ................................................................................................................ 267 Heated Transition............................................................................................................ 268 Host Program .................................................................................................................. 269 State Machine Activity Designer.................................................................................... 270 Demo: Timer State Machine........................................................................................... 271 Timer in the Math Game................................................................................................. 276 Do Problem State ............................................................................................................ 277 TimeUp Transition.......................................................................................................... 278 Time Out State ................................................................................................................ 279 Complete Transition ....................................................................................................... 280 Threading Issue............................................................................................................... 281 Threading Issue Resolved............................................................................................... 283 Shared Trigger ................................................................................................................ 284 Echo Transition............................................................................................................... 285 Quit Transition................................................................................................................ 286 Lab 8B............................................................................................................................. 287 Summary ......................................................................................................................... 288

Chapter 9: Persistence...................................................................................................... 303 Long Running Workflows .............................................................................................. 305 Persistence and Bookmarks ............................................................................................ 306 Long-Running Workflow Example ................................................................................ 307 Persistent Term Life Example ........................................................................................ 308 Workflow Persistence in WF 4 ....................................................................................... 309 SQL Server Persistence Database................................................................................... 310 Host Code to Enable Persistence .................................................................................... 311 Persistence Demo............................................................................................................ 312 AutoResetEvent .............................................................................................................. 316 PersistableIdle Event....................................................................................................... 318 How to Persist a Workflow............................................................................................. 320 Loading a Persisted Workflow........................................................................................ 321 Unload and Load Example.............................................................................................. 322 StartAndUnloadInstance() .............................................................................................. 323 LoadAndCompleteInstance().......................................................................................... 324 Stopping and Starting the Host ....................................................................................... 325 StartWorkflow................................................................................................................. 326 StartWorkflow................................................................................................................. 327 Loading After Data Available......................................................................................... 328 InitNames........................................................................................................................ 329 GetString......................................................................................................................... 330 String Commands............................................................................................................ 331 Host Program .................................................................................................................. 333

Page 10: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

Rev. 4.0 Copyright ©2011 Object Innovations Enterprises, LLC x All Rights Reserved

Lab 9 ............................................................................................................................... 334 Summary ......................................................................................................................... 335

Chapter 10: Workflow Services....................................................................................... 341 What Is WCF?................................................................................................................. 343 WCF Services ................................................................................................................. 344 WCF = ABC ................................................................................................................... 345 Address, Binding, Contract............................................................................................. 346 Workflow Services.......................................................................................................... 347 Messaging Activities....................................................................................................... 348 Messaging Activity Templates ....................................................................................... 349 Demo – Creating a Workflow Service............................................................................ 350 WCF Test Client ............................................................................................................. 354 Demo – Workflow Services Client ................................................................................. 356 Hosting a Workflow Service........................................................................................... 359 Configuration File........................................................................................................... 360 WorkflowServiceHost Example ..................................................................................... 361 Program.cs ...................................................................................................................... 362 Startup Configuration ..................................................................................................... 364 Multiple Operations ........................................................................................................ 365 Multiple Operations via Parallel ..................................................................................... 366 Lab 10 ............................................................................................................................. 367 Summary ......................................................................................................................... 368

Chapter 11: Debugging and Error Handling ................................................................. 377 Debugging Workflows.................................................................................................... 379 Control Flow and Flowchart ........................................................................................... 380 Breakpoint Example........................................................................................................ 381 Breakpoint in XAML...................................................................................................... 382 Exceptions....................................................................................................................... 383 Exception Demonstration ............................................................................................... 384 Account and Bank Classes.............................................................................................. 385 Use of Dictionary............................................................................................................ 386 Deposit and Withdraw .................................................................................................... 387 Code Activities ............................................................................................................... 388 Composite Activities....................................................................................................... 389 Top-Level Workflow ...................................................................................................... 390 Host Program .................................................................................................................. 391 Unhandled Exceptions .................................................................................................... 392 Using WorkflowApplication........................................................................................... 393 Sample Output ................................................................................................................ 394 TryCatch Activity ........................................................................................................... 395 TryCatch Demo............................................................................................................... 396 Transactions .................................................................................................................... 400 Compensation ................................................................................................................. 401 No Compensation............................................................................................................ 402

Page 11: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

Rev. 4.0 Copyright ©2011 Object Innovations Enterprises, LLC xi All Rights Reserved

Using Compensation....................................................................................................... 403 Transfer.xaml .................................................................................................................. 404 Compensable Withdrawal............................................................................................... 405 Compensation Token ...................................................................................................... 406 Canceling the Workflow................................................................................................. 407 Exceptions and Compensation........................................................................................ 408 Compensation Not Performed......................................................................................... 409 Lab 11 ............................................................................................................................. 410 Summary ......................................................................................................................... 411

Appendix A: Learning Resources.................................................................................... 421

Page 12: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

Rev. 4.0 Copyright ©2011 Object Innovations Enterprises, LLC xii All Rights Reserved

Page 13: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 1

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 1 All Rights Reserved

Chapter 1

Workflow Foundation Conceptual Overview

Page 14: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 1

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 2 All Rights Reserved

Workflow Foundation Conceptual Overview

Objectives

After completing this unit you will be able to:

• Explain what a workflow is and how Windows Workflow Foundation supports workflow applications.

• Describe a typical business scenario for workflow and illustrate with a WF application.

• Explain the concepts of workflows and activities.

• Describe runtime services provided in WF.

• Discuss the differences between WF 3 and WF 4.

Page 15: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 1

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 3 All Rights Reserved

What Is Workflow?

• In general terms, a workflow can be thought of as a flow of processes or tasks that produce some result.

• Workflows are often concerned with documents that flow through various activities and may spawn other documents as they are processed.

• Workflows can be manual, with paper documents being transmitted among people working at different desks in an office, each person performing defined tasks according to specified rules.

• We are concerned with workflows as software systems that define the flow of work, the activities performed, and the rules that are employed.

− Rules can be expressed declaratively or in code.

− Activities may be entirely automated or may involve human interaction.

− Workflows may be distributed among multiple computers in diverse locations.

− Workflows are typically represented in a graphical manner.

Page 16: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 1

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 4 All Rights Reserved

Windows Workflow Foundation

• Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms.

− WF consists of a programming model, an engine, and tools.

− The tools include designers for Visual Studio.

• WF provides a consistent development experience with other .NET 4.0 technologies, including WCF and WPF.

• The WF API contains support for both C# and Visual Basic, a special workflow compiler, workflow debugging support, and a visual workflow designer.

• Workflows can be developed completely in code or created in conjunction with XAML markup.

• The WF model and designer are extensible, enabling developers to create custom activities that encapsulate particular workflow functionality.

Page 17: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 1

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 5 All Rights Reserved

Workflows

• A workflow is a set of activities that are stored in a model describing a business (or other real-world) process.

• A workflow describes the order of execution and relationships between units of work.

− The units of work may run for a short time or a long time.

− Activities may be performed by people or the computer.

• A workflow instance is created and maintained by the workflow runtime engine.

− There can be several workflow engines within an application domain.

− Each instance of the engine can support multiple workflow instances.

• A compiled workflow model can be hosted inside any Windows process, including a console application, a Windows Forms application, a WPF application, a Windows service, an ASP.NET Web application, and a Web service.

Page 18: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 1

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 6 All Rights Reserved

Activities

• The units of work of a workflow are called activities.

• When a workflow instance starts, activities are executed in an order as defined by the workflow model.

− Both parallel and sequential orders of execution are supported.

− Conditional and looping behavior of activities is supported.

− Execution continues until the last activity completes, and the workflow then terminates.

• Activities can be reused within a workflow and in other workflows.

• Activities usually have properties that are configurable.

• WF provides many standard activities out-of-the box, and custom activities can be created.

Page 19: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 1

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 7 All Rights Reserved

Standard Activities

• The Visual Studio Toolbox contains many standard activities that can be dragged onto the surface of the Workflow Designer.

− These are arranged in groups, such as Control Flow, Flowchart, State Machine, Messaging, and so on.

− Custom activities can be provided in activity libraries.

Page 20: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 1

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 8 All Rights Reserved

Runtime Services

• WF provides a number of out-of-the box runtime services that are available in the workflow engine.

• Persistence services enable a developer to easily save a WF instance to external storage, such as a database or XML file.

− This capability enables workflow applications to maintain state and be long-running, surviving application restarts.

• Transaction services enable you to maintain transactional integrity in workflow applications.

• Tracking services support monitoring and recording workflow execution.

• Scheduling services enable you to control how the WF runtime manages threads in your application.

Page 21: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 1

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 9 All Rights Reserved

Workflow Business Scenario

• To illustrate workflows consider the following business scenario:

− As orders are created they are specified in XML files placed in the folder Orders.

− Each order in the Orders folder is processed, beginning with getting the order information from the XML file.

− The order is verified, which is done by a person who checks each item in the order for consistency (description furnished by customer matches the description in the vendor database or has a trivial error such as a misspelling). The system also does some verification, making sure that the item ID is found in the database.

− If the order is valid, it is processed and an invoice is created. The invoice is specified in an XML, stored in the Invoices folder.

− If the order is not valid, the issue with the order is specified in another XML file, stored in the Issues folder. (A customer service representative can follow up on such orders by emailing or calling the customer.)

• This scenario is implemented by a workflow application.

− See Chap01\OrderWorkflow. See the file Workflow1.xaml in the OrderWorkflow project for a diagram of the workflow.

Page 22: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 1

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 10 All Rights Reserved

High Level Workflow

• Open up the file Workflow1.xaml.

− The Workflow Designer opens up, showing a diagram of the workflow1.

− Examine the workflow at a high level by collapsing the While More Orders activity.

1 You must build the solution before the Workflow1.xaml file will load properly in the visual designer.

Page 23: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 1

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 11 All Rights Reserved

Details of While Activity

• The heart of the workflow is a loop that gets and verifies orders.

− If order is valid, it is processed.

− If order is not valid, an issue is processed.

Page 24: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 1

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 12 All Rights Reserved

Structure of the Solution

• The solution consists of three projects:

− OrderLibrary is an activity library that defines custom activities such as InitializeOrders, GetOrder, and so on.

− OrLib is an ordinary class library defining the classes that are used in the implementation of the custom activities. This includes code to access a database.

− OrderWorkflow is a console application that contains the workflow itself. It has a graphical representation specified in the XAML file Workflow1.xaml.

• Three folders are provided for XML data files:

− The Orders folder contains orders to be processed.

− The Invoices folder contains invoices that are created for valid orders.

− The Issues folder contains files describing issues for orders that are not valid.

• A database of products is provided in the SQL Server database file Product.mdf in the C:\OIC\Data folder.

− The database access code is encapsulated within the OrLib class library.

− On Windows 7 you should run Visual Studio as Administrator for the database programs.

Page 25: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 1

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 13 All Rights Reserved

Orders Folder

• The Orders folder contains XML files representing orders. The loop goes through all the files in this folder.

− As an example, consider 1002.xml. This order is basically valid, but one of the items is slightly questionable.

<?xml version="1.0" encoding="utf-8" standalone="yes"?> <Order> <OrderId>1002</OrderId> <Customer> <Name>Mary Smith</Name> <Email>[email protected]</Email> </Customer> <Item> <ItemId>104</ItemId> <Description>Sofa</Description> <Quantity>1</Quantity> </Item> <Item> <ItemId>102</ItemId> <Description>Tabel</Description> <Quantity>2</Quantity> </Item> <Item> <ItemId>103</ItemId> <Description>Lamp</Description> <Quantity>2</Quantity> </Item> </Order>

• An automated verification might reject item 102 because of the misspelling of the description.

Page 26: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 1

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 14 All Rights Reserved

Manual Step in the Verification

• As is typical in workflow applications, steps in the workflow can be carried out either by the computer or a person.

• As part of the processing of the VerifyOrder activity a message box will be displayed for a human to verify each item.

• Build and run the solution.

− OrderWorkflow is the startup project, so this console application will run.

− As orders are verified, a message box will pop up for each item of each order.

• Here is the message box for item 102 of order 1002.

• The person viewing this will clearly see that this is benign and will click Yes to approve this item.

Page 27: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 1

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 15 All Rights Reserved

Main Console Display

• As the workflow is executed, a running report on each item is displayed on a main console.

• Here is the display for order 1002: C:\OIC\WfCs\Chap01\OrderWorkflow\Orders\1002.xml OrderId = 1002 Verification message = OK OrderId = 1002 CustomerName = Mary Smith CustomerEmail = [email protected] ItemId Description Quantity ... Price Extension 104 Sofa 1 ... $500.00 $500.00 102 Tabel 2 ... $200.00 $400.00 103 Lamp 2 ... $50.00 $100.00 Total = $1,000.00 File 1002.xml has been created in folder Invoices

• And here is the display for orders 1003 and 1004 for which there were genuine issues.

file = 1003.xml C:\OIC\WfCs\Chap01\OrderWorkflow\Orders\1003.xml OrderId = 1003 Verification message = Description does not match Create issue: Description does not match File 1003.xml has been created in folder Issues file = 1004.xml C:\OIC\WfCs\Chap01\OrderWorkflow\Orders\1004.xml OrderId = 1003 Verification message = Item Not Found Create issue: Item Not Found File 1004.xml has been created in folder Issues Press Enter to exit

Page 28: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 1

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 16 All Rights Reserved

Issues Folder

• The Issues folder will contain an XML file for each order having genuine issues.

• Our example illustrates two kinds of problems.

− The item is not found in the database, a problem that can be detected automatically, illustrated in order 1004.

− The item’s description indicates a genuine question, such as an ambiguity that should be verified with the customer, illustrated in order 1003.

− The human verifier will reject this item, because the company has several bookshelves having different numbers of shelves, and the customer should be queried to make sure she gets the desired bookshelf.

− Here is the generated issue file 1003.xml: <?xml version="1.0" encoding="utf-8" standalone="yes"?> <Issue> <OrderId>1003</OrderId> <CustomerName>Bill Jones</CustomerName> <CustomerEmail>[email protected]</CustomerEmail> <Message>Description does not match</Message> </Issue>

Page 29: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 1

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 17 All Rights Reserved

Invoices Folder

• For valid orders an XML file is created from which an invoice can be generated.

− The actual invoice that will be sent to the printer is created by a separate subsystem, which could be another workflow, whose input is the files in the Invoices folder.

• As an example, here is the invoice XML file for order 1002.

<?xml version="1.0" encoding="utf-8" standalone="yes"?> <Invoice> <OrderId>1002</OrderId> <CustomerName>Mary Smith</CustomerName> <CustomerEmail>[email protected]</CustomerEmail> <LineItem> <ItemId>104</ItemId> <Description>Sofa</Description> <Quantity>1</Quantity> <Price>500.0000</Price> <Extension>500.0000</Extension> </LineItem> <LineItem> <ItemId>102</ItemId> <Description>Table</Description> <Quantity>2</Quantity> <Price>200.0000</Price> <Extension>400.0000</Extension> </LineItem> <LineItem> <ItemId>103</ItemId> <Description>Lamp</Description> <Quantity>2</Quantity> <Price>50.0000</Price> <Extension>100.0000</Extension> </LineItem> <Total>1000.0000</Total> </Invoice>

Page 30: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 1

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 18 All Rights Reserved

Learning Microsoft’s WF

• There are two main challenges in learning to use Windows Workflow Foundation.

• The first challenge is to understand the nature of workflow applications, which are quite different in structure from conventional applications.

− For this purpose studying a miniature example illustrating an actual business scenario is invaluable.

− The program OrderWorkflow is such an example. (By contrast, a conventional console application is provided in OrderConsole in the chapter folder.)

• The second challenge is to understand the classes and tools in the actual framework.

− For this purpose studying small standalone examples, divorced from the complexities of a business situation, will be most helpful.

− We’ll largely follow this second approach in the remainder of the course, beginning with a simple “Hello Workflow” example in Chapter 2.

Page 31: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 1

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 19 All Rights Reserved

Windows Workflow Foundation 3

• Windows Workflow Foundation was introduced as part of .NET Framework 3.0 (formerly called WinFX).

• .NET Framework 3.0 layers on top of .NET Framework 2.0 and has the components shown in the diagram.

WindowsPresentationFoundation

(WPF)

WindowsCommunication

Foundation(WCF)

WindowsWorkflow

Foundation(WF)

WindowsCardSpace

(WCS)

.NET Framework 2.0

WindowsForms ASP.NET ADO.NET

Base Class Libraries

Common Language Runtime

• .NET Framework 3.5 added some important new features, notably Language Integrated Query or LINQ, but remained layered on top of .NET 2.0.

− WF 3.5 used the same Workflow programming model as WF 3.0.

− OrderWF3 illustrates the same order processing workflow implemented using WF 3.5. The graphical representation of the workflow looks different, as can be seen on the next page.

Page 32: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 1

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 20 All Rights Reserved

Orders Workflow in WF 3

Page 33: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 1

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 21 All Rights Reserved

Windows Workflow Foundation 4

• .NET 4.0 is a major revision of the .NET Framework, and the WinFX technologies are no longer layered on top of .NET 3.0.

• Windows Workflow Foundation in .NET 4.0 is a complete re-architecting of WF.

− WF 4 has a completely new set of assemblies: System.Activities.* that are used in place of the System.Workflow.* assemblies from WF 3.

− But WF 4 retains the System.Workflow.* assemblies, so WF 3 workflows will run unchanged in WF 4 (as illustrated by the OrderWF3 example).

• Major changes in WF 4 include:

− A new visual designer, built with WPF, supports the ability to work with much larger workflows.

− Data flows, which were opaque in WF 3, can now be clearly specified as variables and arguments with familiar typing and scoping.

− A new Flowchart activity is provided.

− The programming model has been revamped, making Activity a core base type used for both workflows and activities. The model is now fully declarative, expressible in XAML, with no code-beside.

− Integration with WCF has been improved, with new messaging activities, and fully declarative service definition.

Page 34: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 1

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 22 All Rights Reserved

Summary

• A workflow can be thought of as a flow of processes or tasks that produce some result.

• Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms.

• The units of work of a workflow are called activities.

• Workflows can be defined using a visual designer.

• Standard activities are provided in a Toolbox, and custom activities can be created in an activity library, also made available in the Toolbox.

• Workflow Foundation 4 is a complete re-architecting of WF.

Page 35: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 2

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 23 All Rights Reserved

Chapter 2

Getting Started with WF 4

Page 36: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 2

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 24 All Rights Reserved

Getting Started with WF 4

Objectives

After completing this unit you will be able to:

• Describe the overall structure of workflow programs.

• Implement workflows using C# code.

• Use the Sequence activity to implement workflows consisting of multiple activities.

• Create Workflow projects using Visual Studio 2010.

• Implement workflows declaratively in XAML by using the Visual Studio Workflow Designer.

• Use the WriteLine and Assign activities in your workflow programs.

• Describe the use of variables, arguments and expressions in workflow programs.

• Describe the Control Flow activities and illustrate using the While activity.

Page 37: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 2

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 25 All Rights Reserved

Workflow Structure

• The fundamental unit of work in a workflow application is called an activity.

− In WF an activity is represented by a class that derives ultimately from the class Activity.

− Activities can be composed together to form larger activities.

• An activity that is used as a top-level entry point is called a workflow.

• A workflow is executed by a runtime engine.

− The simplest way to invoke the runtime engine is through the WorkflowInvoker class.

− This will start the workflow at the top-level activity, just as a CLR program will start at the top-level entry point Main().

Page 38: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 2

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 26 All Rights Reserved

Minimal Workflow Program

• See Minimal in the chapter folder. using System; using System.Activities; using System.Activities.Statements; namespace HelloCode { class Program { static void Main(string[] args) { Activity wf = new WriteLine { Text = "Hello, world" }; WorkflowInvoker.Invoke(wf); } } }

− This workflow consists of a single activity WriteLine.

− The activity is instantiated, its Text property initialized, and passed as a parameter to the static Invoke() method of the WorkflowInvoker class.

Page 39: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 2

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 27 All Rights Reserved

Sequence Activity

• In most cases a top-level activity will act as a container of other activities.

− Examples of such container activities include Sequence, Parallel and Flowchart.

• A Sequence activity, as its name suggests, executes its contained activities sequentially.

− An illustration is provided by the Sequence example.

Activity wf = new Sequence { Activities = { new WriteLine { Text = "Hello, world" }, new WriteLine { Text = "Goodbye." } } };

Page 40: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 2

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 28 All Rights Reserved

Visual Studio Workflow Projects

• While it is certainly possible to create workflow applications using only C# code, it is much more productive to use Visual Studio and the Workflow Designer.

• Visual Studio provides several workflow project templates:

− Activity Designer Library

− Activity Library

− WCF Workflow Service Application

− Workflow Console Application

• We’ll begin with Workflow Console Applications.

• Let’s use Visual Studio to create a “Hello” application, and we’ll use the visual Workflow Designer after our project has been created.

Page 41: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 2

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 29 All Rights Reserved

Workflow Designer Demo

1. Create a new Workflow Console Application Hello in the Demos folder.

2. Examine the files of your new project in Solution Explorer. The workflow will be defined declaratively in the file Workflow1.xaml. It is open in the visual Workflow Designer.

Page 42: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 2

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 30 All Rights Reserved

Workflow Designer Demo (Cont’d)

3. There is a Toolbox containing a palette of built-in activities. Expand the Control Flow group.

4. Drag a Sequence activity onto the center of the design canvas.

5. Expand the Primitives group in the Toolbox.

Page 43: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 2

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 31 All Rights Reserved

Workflow Designer Demo (Cont’d)

6. Drag two WriteLine activities onto the Sequence activity. Specify the Text property as “Hello, world” and “Goodbye”.

7. Build and run (without debugging). You’ll see this output:

Hello, world Goodbye Press any key to continue . . . 8. Examine the C# code in Program.cs.

class Program { static void Main(string[] args) { WorkflowInvoker.Invoke(new Workflow1()); } }

Page 44: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 2

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 32 All Rights Reserved

Workflow Designer Demo (Cont’d)

9. The workflow has been specified declaratively in the file Workflow1.xaml. Normally you will work with the visual representation. If you want to see the XAML, right-click over the file in Solution Explorer and choose View Code … from the context menu. To go back to the visual representation, choose View Designer.

10. You have created a simple workflow without writing any C# code! The program is saved in HelloXaml in the chapter folder.

Page 45: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 2

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 33 All Rights Reserved

Variables

• You can use variables in workflow programs.

− Define variables using the Workflow Designer. See the Variables tab at the bottom of the design surface.

− You can assign values to variables using the Assign activity, which is part of the Primitives group.

• Let’s illustrate by creating another version of our Hello program. Continue your work in the Demos folder.

1. Click on the Variables tab.

2. Note that in WF variables have scope as in programming languages. Click on the Sequence activity to specify a scope of the whole sequence, including the contained WriteLine activities.

3. You can now create a variable. Call it Name, with type String and Default value of “world”.

Page 46: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 2

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 34 All Rights Reserved

Assign Activity

• Another useful primitive activity is Assign.

− This activity assigns a value to a variable.

− The semantics of the Assign activity require that the To (left-hand side) must be a variable, but the right-hand side may be a variable, a literal, or an expression.

4. Drag an Assign activity from the Toolbox to the top of the Sequence.

5. Specify Name for the To and “Workflow” for the VB expression.

6. Edit the following WriteLine activity to provide this expression for the Text argument:

"Hello, " & Name

Page 47: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 2

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 35 All Rights Reserved

HelloAssign Workflow

• The completed demo is saved as HelloAssign in the chapter folder.

− Here is the final workflow:

• Build and run (without debugging): Hello, Workflow Goodbye Press any key to continue . . .

Page 48: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 2

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 36 All Rights Reserved

Visual Basic Expressions

• Note that in WF 4 all expressions use VB syntax.

− A future version might allow C# syntax when the programming language is C#, but currently VB syntax is used.

• Besides using the special interface provides by the Workflow Designer for the WriteLine activity, you could enter the expression via the Expression Editor.

− This is accessed from the button of the Properties window.

• Click the button to bring up the Expression Editor.

Page 49: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 2

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 37 All Rights Reserved

Arguments

• Besides variables and expressions, the data flow model in Workflow Foundation uses arguments.

• Arguments specify the inputs and outputs of activities.

• For example, the Assign activity has input argument Value and output argument To.

− There is also a DisplayName property that is used by the Designer in the visual display of the activity.

• You can also define your own arguments for a workflow in the Designer.

− Click the Arguments tab at the bottom of the Designer window.

− We are creating an argument aName whose direction is In.

Page 50: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 2

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 38 All Rights Reserved

Argument Example

• Modifying our “Hello” example, we delete the Assign activity and the variable Name. Instead we will use the argument aName in the first WriteLine activity.

• We pass the argument in a Dictionary in a second parameter to the Invoke() method in Program.cs.

class Program { static void Main(string[] args) { WorkflowInvoker.Invoke(new Workflow1(), new Dictionary<string, object> { {"aName", "Argument demo"} }); } }

− Note that the Dictionary class is in the namespace System.Collections.Generic.

• Build and run: Hello, Argument demo Goodbye

• Our example program is HelloArgument in the chapter folder.

Page 51: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 2

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 39 All Rights Reserved

Lab 2A

A Calculator Workflow

In this lab you will implement a very simple calculator workflow that will add and subtract two integers. As a variation, you will allow the user of the program to enter the integers at the command line, and the results will be passed back by arguments.

Detailed instructions are contained in the Lab 2A write-up at the end of the chapter.

Suggested time: 30 minutes

Page 52: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 7

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 211 All Rights Reserved

Chapter 7

More about Custom Activities

Page 53: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 7

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 212 All Rights Reserved

More about Custom Activities

Objectives

After completing this unit you will be able to:

• Explain the need for an activity to wait for input without holding onto a workflow thread.

• Describe the use of bookmarks to enable a workflow to wait for input.

• Describe the NativeActivity base class and use it to implement activities with bookmarks.

• Use the Pick activity to model multiple event triggers in parallel.

Page 54: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 7

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 213 All Rights Reserved

Waiting for Input

• In our examples we’ve implemented several custom activities to read input from the console.

− These custom activities, such as ReadInt and ReadStringActivity, were derived from CodeActivity.

• While easy to implement, they are not a good model for real workflows.

• The problem is that the workflow thread goes idle while waiting for input.

− In general we would like for the workflow to be able to do other useful work while waiting.

• Workflow Foundation provides the concept of bookmarks for precisely this purpose.

− This chapter will discuss bookmarks and the NativeActivity base class, which must be used for implementing a custom activity with bookmarks.

Page 55: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 7

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 214 All Rights Reserved

Bookmarks

• Bookmarks are the mechanism provided by Workflow Foundation to allow an activity to wait for input without blocking the workflow thread.

• When an activity needs input (or some other processing that may be time consuming), it can create a bookmark.

− A bookmark represents a point at which execution can be resumed.

− Needed data can then be delivered to the activity.

• The bookmark mechanism consists of these elements:

− When a bookmark is created a BookmarkCallback delegate is specified.

− The bookmark is given a name by which it is known in external code, typically host code.

− This external code is responsible for resuming the bookmark and supplying the needed data.

− When the bookmark is resumed, the workflow runtime schedules the associated BookmarkCallback delegate.

Page 56: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 7

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 215 All Rights Reserved

NativeActivity

• The following base classes are available for creating custom activities:

− Activity: used in the Workflow Designer to create composite activities consisting of other activities.

− CodeActivity: used to implement custom functionality by overriding the Execute() method. But there is only limited access to runtime features.

− AsyncCodeActivity: adds the capability of asynchronous execution, required to take advantage of the asynchronous scheduling of activities provided by the Parallel activity.

− NativeActivity: provides access to the most features of the workflow runtime, including create bookmarks, respond to cancel and abort, and flow in transactions.

• In order to implement bookmarks, a class derived from NativeActivity should override these methods:

− Execute()

− CanInduceIdle()

• It should also implement a delegate method that is specified in the call to CreateBookmark().

Page 57: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 7

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 216 All Rights Reserved

Bookmark Example

• The example workflow receives the input of two integers, calculates the quotient and displays the result.

− See SimpleBookmark in the chapter folder.

• GetTwoInt is a custom activity that creates a bookmark and goes idle.

− When input is ready, the callback method obtains two integers from the input string and passes them as output arguments.

Page 58: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 7

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 217 All Rights Reserved

GetTwoInt Custom Activity

public sealed class GetTwoInt : NativeActivity { public OutArgument<int> aX { get; set; } public OutArgument<int> aY { get; set; } protected override void Execute( NativeActivityContext context) { context.CreateBookmark("GetTwoInt", Resumed); } // The callback method private void Resumed( NativeActivityContext context, Bookmark bookmark, object value) { string line = value as string; string[] nums = line.Split(' '); if (nums.Length == 2) { aX.Set(context, int.Parse(nums[0])); aY.Set(context, int.Parse(nums[1])); } else throw new Exception( "Supply two numbers separated by a space"); } protected override bool CanInduceIdle { get { return true; } } }

Page 59: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 7

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 218 All Rights Reserved

Host Program

• The host program gathers the input and passes it to the workflow by resuming the bookmark.

static void Main(string[] args) { AutoResetEvent sync = new AutoResetEvent(false); // Create WorkflowApplication and handle // lifecycle events DivideWorkflow wf = new DivideWorkflow(); WorkflowApplication wfApp = new WorkflowApplication(wf); wfApp.Completed = delegate( WorkflowApplicationCompletedEventArgs e) { // Signal that workflow has completed sync.Set(); }; // Start the workflow wfApp.Run(); // Collect user input and resume the bookmark. // Resume only occurs when the workflow is idle. // ResumeBookmark blocks until then. Console.WriteLine( "Enter two integers separated by space"); string line = Console.ReadLine(); wfApp.ResumeBookmark("GetTwoInt", line); // Wait for workflow completion sync.WaitOne(); }

Page 60: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 7

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 219 All Rights Reserved

Passing Data on Resume

• The BookmarkCallback delegate has a third parameter which can be used to receive data when the bookmark is resumed.

public delegate void BookmarkCallback( NativeActivityContext context, Bookmark bookmark, Object value )

• This value can then be used in the callback method. private void Resumed( NativeActivityContext context, Bookmark bookmark, object value) { string line = value as string; string[] nums = line.Split(' '); if (nums.Length == 2) { aX.Set(context, int.Parse(nums[0]));

• The data comes from the host program via the call to ResumeBook().

wfApp.ResumeBookmark("GetTwoInt", line);

Page 61: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 7

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 220 All Rights Reserved

Bookmark Options

• An optional parameter in CreateBookmark() is the BookmarkOptions enumeration.

− Bitwise combination of member values is allowed.

None Default options

MultipleResume Bookmark can be resumed multiple times. (By default, the workflow runtime removes a bookmark from its bookmarks table when the bookmark is resumed, and the bookmark cannot be resumed again.)

NonBlocking The bookmark does not block the workflow. (By default, the workflow runtime does not allow an activity to complete if it has pending bookmarks. But an activity can complete if it has pending NonBlocking bookmarks, provided no other work is pending.)

Page 62: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 7

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 221 All Rights Reserved

Bookmarks and Threads

• In working with bookmarks you should be aware that the host program and the workflow run on separate threads.

• Hence for signaling between the host and the workflow you may use thread synchronization classes, such as AutoResetEvent.

• To illustrate threading, we have instrumented our simple bookmark example to display the current thread with each line of output.

− See SimpleBookmarkThreads in the chapter folder.

− The class Util in the Activity Library has some utility methods to help in displaying the current thread.

public class Util { public static string GetThreadId() { Thread t = Thread.CurrentThread; int threadId = t.ManagedThreadId; return threadId.ToString(); } public static void WriteLine(string msg) { Console.WriteLine("[Thread {0}] {1}", GetThreadId(), msg); } ... }

Page 63: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 7

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 222 All Rights Reserved

Threads in Host Code

static void Main(string[] args) { Util.WriteLine("Host starting"); AutoResetEvent sync = new AutoResetEvent(false); // Create WorkflowApplication and handle // lifecycle events DivideWorkflow wf = new DivideWorkflow(); WorkflowApplication wfApp = new WorkflowApplication(wf); wfApp.Completed = delegate( WorkflowApplicationCompletedEventArgs e) { Util.WriteLine("Workflow has completed"); sync.Set(); }; wfApp.Idle = delegate( WorkflowApplicationIdleEventArgs e) { Util.WriteLine("Workflow is idle"); }; // Start the workflow wfApp.Run(); // Collect user input and resume the bookmark. // Resume only occurs when the workflow is idle. // ResumeBookmark blocks until then. Util.WriteLine( "Enter two integers separated by space"); string line = Console.ReadLine(); wfApp.ResumeBookmark("GetTwoInt", line); // Wait for workflow completion sync.WaitOne(); Util.WriteLine("Host exiting"); }

Page 64: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 7

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 223 All Rights Reserved

Threads in Workflow

• We’ve instrumented the custom activity GetTwoInt. protected override void Execute(NativeActivityContext context) { Util.WriteLine("Entering GetTwoInt"); context.CreateBookmark("GetTwoInt", Resumed); } // The callback method private void Resumed(NativeActivityContext context, Bookmark bookmark, object value) { Util.WriteLine("Resuming GetTwoInt"); ...

• And we’ve instrumented the WriteLine in Workflow1.xaml.

− ShowLine() is another utility method, which returns a string

rather than write it out to the console.

public static string ShowLine(string msg) { return string.Format( "[Thread {0}] {1}", GetThreadId(), msg); }

Page 65: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 7

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 224 All Rights Reserved

Sample Threading Output

• Here is a sample run of the program: [Thread 1] Host starting [Thread 1] Enter two integers separated by space [Thread 3] Entering GetTwoInt [Thread 3] Workflow is idle 45 9 [Thread 3] Resuming GetTwoInt [Thread 3] Quotient = 5 [Thread 3] Workflow has completed [Thread 1] Host exiting

• In this example the host runs on Thread 1 and the workflow on Thread 3.

• Notice that the handlers for the life cycle delegates Completed and Idle run on the workflow thread, although the code is contained in the host program.

− It is the workflow that invokes these callbacks.

Page 66: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 7

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 225 All Rights Reserved

Lab 7

Bookmark in a Math Game

In this lab you will implement a simple math game in which the user is prompted to answer multiplication problems. The first solution will not use a bookmark. You will compare this solution with other versions that do use a bookmark.

Detailed instructions are contained in the Lab 7 write-up at the end of the chapter.

Suggested time: 75 minutes

Page 67: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 7

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 226 All Rights Reserved

A Compute Intensive Workflow

• Our first example of using a bookmark was deliberately kept very simple.

− The goal was to illustrate the basic bookmark mechanism with a minimum of clutter.

− But our simple example does not illustrate the reason you might want to employ the bookmark mechanism.

• Another example attempts to illustrate this with a compute intensive workflow.

− There is much work to be done, and we want the workflow to remain active while it is waiting for user input.

• The example is FactorQueueBookmark.

− The solution contains a Workflow Console Application whose workflow has two parallel activities.

− EnqueueLoop gets 64-bit integers from the user and places them in a queue. While waiting for input, this activity goes idle, letting the other activity get work done.

− DequeueLoop dequeues integers from the queue, factors these numbers, and displays the results at the console.

Page 68: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 7

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 227 All Rights Reserved

EnqueueLoop

• GetNumber is a custom activity that obtains the long integer via the bookmark mechanism.

public sealed class GetNumber : NativeActivity { public OutArgument<long> aNumber { get; set; } protected override void Execute( NativeActivityContext context) { context.CreateBookmark("GetNumber", Resumed); } private void Resumed( NativeActivityContext context, Bookmark bookmark, object value) { long number = (long) value; aNumber.Set(context, number); } ...

Page 69: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 7

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 228 All Rights Reserved

DequeueLoop

− This activity dequeues a number. If successful, it factors it

and displays the factors in a console window.

− The custom activities used are ordinary Code Activities with no bookmarks used.

Page 70: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 7

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 229 All Rights Reserved

FactorQueueBookmark Solution

• The solution has four projects:

− FactorConsoleWF, a Workflow Console Application.

− ActivityLibrary1, an Activity Library.

− QueueLib, a class library contains methods encapsulating a ConcurrentQueue, which is a thread-safe class provided by the .NET Framework. It also contains the math routines to factor large integers.

− FactorGui, a GUI program that lets you exercise the methods to generate large random integers, enqueue them, dequeue them, and factor them.

− The Factor button removes one number from the queue, factors it, and displays the results in a console window.

Page 71: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 7

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 230 All Rights Reserved

FactorConsoleWF

• Make FactorConsoleWF the startup project, build and run.

• Enter “help” as your first command. [Thread 1] Starting ... [0] 45245041251673587 [1] 122537386780440943 [2] 1305896203876302545 [3] 3324171020112998633 [4] 1386056018187898741 [5] 810633088717946101 [6] 2044887599291695669 [7] 424551056398671491 [8] 1195881354633593251 [9] 2814910814311209661 Enter a command or index/number for the queue > help Not a number; legal commands are: new show prime quit >

• A batch of 10 random 64-bit integers is generated.

− “show” displays the numbers in the queue

− A number less then 10 places the large integer indexed by that number on the queue.

− A number 10 or greater places that number itself on the queue.

− “new” generates a new batch of 10 numbers.

Page 72: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 7

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 231 All Rights Reserved

FactorConsoleWF (Cont’d)

• Type “quit”and run again.

− This time type “prime” several times followed by “show” and then “quit”. The “prime” command retrieves a large prime, which will probably take a relatively long time to factor, enabling you to see some entries in the queue.

[Thread 1] Starting ... [0] 2677945999832193553 [1] 1558753636871737873 [2] 351113869589826241 [3] 620588150615962211 [4] 1152802649870113589 [5] 444918551390703024 [6] 922702771038278553 [7] 962160379227504483 [8] 3891016550760494541 [9] 133404444910131601 Enter a command or index/number for the queue > prime > prime > prime > show 363262619323823377 159557671709310733 > [Thread 3] 135811970017876387 [Thread 4] 363262619323823377 [Thread 4] 159557671709310733 quit [Thread 1] Workflow is stopping ... [Thread 11] Workflow has completed

− The first prime was immediately dequeued and factoring began. The other two primes remain in the queue until the first prime completes.

Page 73: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 7

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 232 All Rights Reserved

More Experiments

• Try entering a couple of specific numbers to factor. You should see an almost instantaneous response, since these numbers are fairly small and can be factored quickly.

Enter a command or index/number for the queue > 1001 > [Thread 4] 7 11 13 1000001 > [Thread 5] 101 9901

• Now try entering several indices between 0 and 9.

− The corresponding number is large and will take longer to factor. (But depending on what random number it is, it may still factor quite quickly.)

0 > [Thread 15] 2 5 7 13 17 4259 9787 504473 1 > [Thread 16] 2 2 11 17 9649 451859 535679 2 > [Thread 19] 257 1523 55661 10505981

• Have fun!

− And please examine the code!

Page 74: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 7

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 233 All Rights Reserved

Pick Activity

• Pick is a built-in activity in the Control Flow group.

− Like the C# switch statement, it causes the execution of one of several branches.

− Each branch, called a PickBranch, contains a trigger and an action.

− When Pick begins execution, all the trigger activities from all the branches are scheduled to be executed.

− When the first trigger activity completes, its action is scheduled. The other trigger activities are canceled.

Page 75: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 7

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 234 All Rights Reserved

Pick Example

• We illustrate the Pick activity with a variation of our MathGame example.

− See SimplePick in the chapter folder.

− The user is presented with a multiplication problem, and given a time limit of 5 seconds to supply an answer.

Page 76: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 7

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 235 All Rights Reserved

Get and Check Answer

• The first branch gets and checks an answer.

− The trigger is GetNumber, a custom activity that creates a

bookmark and then goes idle, waiting for the user to supply an answer.

Page 77: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 7

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 236 All Rights Reserved

Set Timer

• The second branch sets a 5 second timer, using the Delay activity.

− The trigger is the Delay, which immediately goes idle.

− If the first branch completes, with the user having supplied an answer, the second branch is canceled.

− But if the user has not supplied an answer in 5 seconds, the second branch displays a message “Time’s up”, and the first branch is canceled.

Page 78: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 7

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 237 All Rights Reserved

Summary

• A workflow application can achieve greater throughput by allowing for an activity to wait for input without holding onto a workflow thread.

• Bookmarks enable a workflow to wait for input, after which the activity can be resumed.

• The NativeActivity base class is used to implement activities with bookmarks.

• You can use the Pick activity to model multiple event triggers in parallel.

Page 79: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 7

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 238 All Rights Reserved

Lab 7

Bookmark in a Math Game

Introduction In this lab you will implement a simple math game in which the user is prompted to answer multiplication problems. The first solution will not use a bookmark. You will compare this solution with other versions that do use a bookmark. Suggested Time: 75 minutes Root Directory: OIC\WfCs Directories: Labs\Lab7\MathGame (do your work here) Chap07\MathGame\Step0 (backup of starter code) Chap07\MathGame\Step1 (solution to Part 1) Chap07\MathGame\Step2 (solution to Part 2) Chap07\MathGame\Step3 (solution to Part 3) Chap07\MathGame\Step4 (solution to Part 4) Part 1. A Single Problem (No Bookmark) For starter code you are provided an Activity Library with the following custom activities:

• A Code Activity GetNumber.cs that reads an integer from the console. • A Code Activity RandomPair.cs that generates a random pair of integers. • A Composite Activity TestMultiplication.xaml that tests whether the answer to a

multiplication problem is correct. Create a Workflow Console Application MathGame that prompts the user for a single random multiplication problem and tests whether the user’s answer is correct. The numbers to be multiplied together should be between 1 and 20. Optional detailed instructions: 1. Examine the starter code in the class library. In particular, examine the arguments for

the custom activities; you will need to use these when you invoke the activities from the workflow you create. For TestMultiplication.xaml click on the Arguments tab in the Workflow Designer. Built the solution.

2. Add a new Workflow Console Application project MathGame to the solution.

3. Add a reference to the Activity Library.

4. Drag a Sequence onto the design surface of Workflow1.xaml.

Page 80: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 7

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 239 All Rights Reserved

5. Create variables X, Y, Max and Answer of type Int32. Assign a default value of 20 to Max. Create a variable IsCorrect of type Boolean.

6. Drag a RandomPair activity onto the Sequence. Change the DisplayName to “Generate Problem”. Associate properties aX, aY and aMax with the corresponding variables.

7. Drag a WriteLine activity onto the Sequence. Change the DisplayName to “Display Problem”. Specify Text as shown:

String.Format("What is {0} * {1}?", X, Y) 8. Make MathGame the startup project. Build and run. You should see a random

multiplication problem displayed.

9. Drag a GetNumber activity onto the Sequence. Change the DisplayName to “Get User Answer”. Associate property aNumber with the variable Answer.

10. Drag a TestMultiplication activity onto the Sequence. Change the DisplayName to “Check If Correct”. Associate properties tstX, tstY, tstAnswer and aIsCorrect with the corresponding variables.

11. Drag an If activity onto the Sequence. Change the DisplayName to “Tell User Whether Correct”. For condition specify IsCorrect.

12. Drag a WriteLine onto the Then block. For Text specify “Correct!”.

13. Drag a WriteLine onto the Else block. For Text specify “InCorrect!”.

14. Build and run several times. Try entering both correct and incorrect answers to make sure your workflow is behaving properly. You are now at Step 1.

Part 2. A Single Problem (Using a Bookmark) Modify your solution to create a bookmark when the user is asked to enter an answer to the multiplication problem. The host program will now do the actual input of data and then will resume the workflow. Optional detailed instructions: 1. In the activity library modify GetNumber to be a Native Activity that uses a

bookmark. You will need to do the following:

a. The class GetNumber should derive from NativeActivity.

b. The Execute() method, which now receives as a parameter a NativeActivityContext, should create a bookmark, specifying a callback method.

Page 81: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 7

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 240 All Rights Reserved

c. Implement a callback method to perform the work of the previous Execute() method. Now, instead of reading the data from the console and parsing it, the data is retrieved from the third parameter of the callback and cast to an int.

d. Provide an override of the CanInduceIdle property to return true.

public sealed class GetNumber : NativeActivity { public OutArgument<int> aNumber { get; set; } protected override void Execute(NativeActivityContext context) { context.CreateBookmark("GetNumber", Resumed); } private void Resumed(NativeActivityContext context, Bookmark bookmark, object value) { int number = (int)value; aNumber.Set(context, number); } protected override bool CanInduceIdle { get { return true; } } } 2. Rebuild the Activity Library project.

3. The rest of the work will be in the MathGame project. In Workflow1.xaml delete the old GetNumber activity (with display name “Get User Answer”) and replace it with the new GetNumber activity. Reassign the properties as they were before.

4. You can now get a clean compile of the whole solution, but it will not run properly, as you have made a fundamental change in the behavior of the workflow. We will now have to modify the host code, which before was the original code using the WorkflowInvoker class. You will now need to use WorkflowApplication instead.

static void Main(string[] args) { Workflow1 wf = new Workflow1(); WorkflowApplication wfApp = new WorkflowApplication(wf); 5. Initialize an AutoResetEvent, which you will use for thread synchronization. You

will need to import the System.Threading namespace.

AutoResetEvent sync = new AutoResetEvent(false); 6. Handle the Completed lifecycle event (which runs on a different thread than the host

code) to signal the host that the workflow has completed.

Page 82: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 7

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 241 All Rights Reserved

wfApp.Completed = delegate( WorkflowApplicationCompletedEventArgs e) { sync.Set(); }; 7. Start the workflow.

wfApp.Run(); 8. From our knowledge of the workflow, we know that it will generate and display a

problem and invoke the GetNumber custom activity, which creates a bookmark, making the workflow idle. Thus host code is responsible for obtaining the number from the console, and then resuming the workflow.

string strNum = Console.ReadLine(); int num = Int32.Parse(strNum); wfApp.ResumeBookmark("GetNumber", num); 9. Build and run. The program will run, generate a problem and accept user input. But

the main thread will immediately exit, before the workflow has had a chance to complete.

10. So, as a final step, the host code should wait on the AutoResetEvent.

11. Build and run several times. The program should behave as before, but the mechanism of waiting for input is entirely different! You are now at Step 2.

Here is the complete host code:

static void Main(string[] args) { // Create the Workflow and the WorkflowApplication Workflow1 wf = new Workflow1(); WorkflowApplication wfApp = new WorkflowApplication(wf); // Initialize AutoResetEvent for thread synchronization AutoResetEvent sync = new AutoResetEvent(false); // Handle the completed event to signal the host that // the workflow has completed wfApp.Completed = delegate(WorkflowApplicationCompletedEventArgs e) { sync.Set(); }; // Start the workflow wfApp.Run(); // Obtain the input the workflow is expecting and resume the // bookmark string strNum = Console.ReadLine(); int num = Int32.Parse(strNum); wfApp.ResumeBookmark("GetNumber", num);

Page 83: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 7

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 242 All Rights Reserved

// Wait for workflow completion sync.WaitOne(); } And here is the complete workflow:

Part 3. Multiple Problems Modify the workflow and host program to present the user with multiple problems to answer. Don’t worry at this point about synchronizing termination of the workflow and the host. You can have an infinite loop in each, and the user can manually close the console window to quit. Optional detailed instructions: 1. Change the filename Workflow1.xaml to MathProblem.xaml.

2. Right-click over MathProblem.xaml and choose View Code from the context menu.

Page 84: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 7

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 243 All Rights Reserved

3. In the XAML file, change the name of the class to MathGame.MathProblem.

<Activity mc:Ignorable="sap" x:Class="MathGame.MathProblem" ... 4. Add a new Activity Workflow1.xaml to your project.

5. Build the solution.

6. Drag a Sequence onto the design surface of Workflow1.xaml.

7. Drag a MathProblem onto the Sequence. (In the Toolbox, the MathProblem activity will show up under the MathGame group.)

8. Build and run. The program should behave the same as before, presenting you with one multiplication problem at a time.

9. Now drag a second MathProblem onto the Sequence.

10. Build and run. The first problem will work completely, and you will be presented with the second problem. But you won’t be able to enter an answer for the second problem. We will need to make some further modifications, allowing the workflow to signal the host when it has created a bookmark and is looking for the host to gather data. We’re going to implement a very simple solution in which the host will keep looping, waiting for a notification to gather data and then resume the workflow. The user will terminate simply by closing the console window in which the program is running.

11. To allow the workflow to signal the host that it needs data, modify the GetNumber activity to define a public static AutoResetEvent object syncNeedData. You will need to import the System.Threading namespace.

12. At the end of the Execute() method call syncNeedData.Set().

public sealed class GetNumber : NativeActivity { public static AutoResetEvent syncNeedData = new AutoResetEvent(false); public OutArgument<int> aNumber { get; set; } protected override void Execute(NativeActivityContext context) { context.CreateBookmark("GetNumber", Resumed); syncNeedData.Set(); } 13. In the host program move the code to gather input and resume the bookmark into an

infinite while loop. At the top of the loop wait for syncNeedData to be signaled.

Page 85: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 7

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 244 All Rights Reserved

while (true) { GetNumber.syncNeedData.WaitOne(); // Obtain the input the workflow is expecting and resume // the bookmark string strNum = Console.ReadLine(); int num = Int32.Parse(strNum); wfApp.ResumeBookmark("GetNumber", num); } 14. Similarly, modify Workflow1.xaml so that MathProblem is invoked within an

infinite loop.

15. Build and run. Try entering both correct and incorrect answers. Here is some typical output.

What is 7 * 9? 63 Correct! What is 3 * 19? 27 Incorrect What is 5 * 19? 95 Correct! What is 10 * 8? 16. To terminate the program, simply close the console window. You are now at Step 3.

Part 4. Synchronize the Host with the Workflow (Extra Credit) Modify the workflow and host program to allow the user to quit by entering an answer of zero or a negative number. Optional detailed instructions: 1. In MathProblem.xaml create a Boolean output argument aEOF.

Page 86: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 7

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 245 All Rights Reserved

2. Drop an If activity immediately after the Get User Answer activity. Make the display name “Check for EOF”.

3. For Condition enter Answer > 0.

4. Drop a Sequence onto the Then block.

5. Drop an Assign onto the Sequence. The value False should be assigned to aEOF.

6. Drag the remaining two activities onto this Sequence in order.

7. Drop an Assign onto the Else block. The value True should be assigned to aEOF. This portion of the workflow should now look like this:

8. In Workflow1.xaml create a Boolean variable EOF scoped to the DoWhile.

9. The MathProblem activity should now have a property aEOF. Bind it to EOF.

10. Change the Condition of the DoWhile to Not EOF.

Page 87: 4156 Contents 40 · Windows Workflow Foundation • Windows Workflow Foundation (WF) is a framework that supports creating and running workflow applications on Windows platforms

WfCs Chapter 7

Rev. 4.0 Copyright © 2011 Object Innovations Enterprises, LLC 246 All Rights Reserved

11. Drop a WriteLine above the DoWhile. For Text enter “Answer with zero or a negative number to quit.”

12. Build and run. Unfortunately, the program hangs when you enter a zero or negative number.

13. You will need to perform the loop to gather input and resume the bookmark in a separate thread. You can do this conveniently by using the thread pool. Define a static method GetInput().

static void GetInput(object stateinfo) { while (true) { GetNumber.syncNeedData.WaitOne(); string strNum = Console.ReadLine(); int num = Int32.Parse(strNum); wfApp.ResumeBookmark("GetNumber", num); } } 14. For this to compile, wfApp needs to be defined as a static variable outside of Main().

class Program { static WorkflowApplication wfApp; static void Main(string[] args) { // Create the Workflow and the WorkflowApplication Workflow1 wf = new Workflow1(); wfApp = new WorkflowApplication(wf); ... 15. Next, remove the infinite loop from Main() and replace it by code to queue the user

work item GetInput on the thread pool.

// Obtain the input the workflow is expecting and resume the bookmark // Do this on a separate thread so we can exit when workflow ends ThreadPool.QueueUserWorkItem(new WaitCallback(GetInput)); 16. Build and run. The program should now work. You can keep on doing multiplication

problems and terminate by supplying an answer of zero or a negative number.