Windows Workflow Foundation Using C# - · PDF fileObject Innovations Course 4156 Student...

102
Object Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

Transcript of Windows Workflow Foundation Using C# - · PDF fileObject Innovations Course 4156 Student...

Page 1: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

Object Innovations Course 4156

Student Guide Revision 4.5

Windows Workflow Foundation Using C#

Evaluation Copy

Page 2: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

Rev. 4.5 Copyright ©2013 Object Innovations Enterprises, LLC ii All Rights Reserved

Windows Workflow Foundation Using C# Rev. 4.5 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 trademark of Object Innovations. Author: Robert J. Oberg Copyright ©2013 Object Innovations Enterprises, LLC All rights reserved. Object Innovations 877-558-7246 www.objectinnovations.com Published in the United States of America.

Evaluation Copy

Page 3: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

Rev. 4.5 Copyright ©2013 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.5 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

Evaluation Copy

Page 4: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

Rev. 4.5 Copyright ©2013 Object Innovations Enterprises, LLC iv All Rights Reserved

Directory Structure

• Install the course software by running the self-extractor Install_WfCs_45.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.

− The database uses the LocalDB version of SQL Server 2012, which is automatically installed with Visual Studio 2012.

− The command files are intended for use with SQL Server 2012 Express, which should be downloaded and installed separately. They are used in Chapter 9 on Persistence.

Evaluation Copy

Page 5: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

Rev. 4.5 Copyright ©2013 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 Windows Workflow Foundation 4.5................................................................................. 22 Summary ........................................................................................................................... 23

Chapter 2: Getting Started with WF 4.5 .......................................................................... 25 Workflow Structure .......................................................................................................... 27 Minimal Workflow Program............................................................................................. 28 Sequence Activity ............................................................................................................. 29 Visual Studio Workflow Projects ..................................................................................... 30 Workflow Designer Demo................................................................................................ 31 Variables ........................................................................................................................... 35 Assign Activity ................................................................................................................. 36 HelloAssign Workflow ..................................................................................................... 37 C# and Visual Basic Expressions ..................................................................................... 38 Arguments......................................................................................................................... 39 Argument Example ........................................................................................................... 40 Lab 2A .............................................................................................................................. 41 Control Flow Activities .................................................................................................... 42 While Activity................................................................................................................... 43 Lab 2B............................................................................................................................... 44 Summary ........................................................................................................................... 45

Evaluation Copy

Page 6: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

Rev. 4.5 Copyright ©2013 Object Innovations Enterprises, LLC vi All Rights Reserved

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

Chapter 4: Custom Activities............................................................................................. 95 Why Custom Activities? ................................................................................................... 97 Authoring Custom Activities ............................................................................................ 98 Arguments in Custom Activities....................................................................................... 99 Activity Class Hierarchy................................................................................................. 100 CodeActivity ................................................................................................................... 101 CodeActivityContext ...................................................................................................... 102 CodeActivity<TResult>.................................................................................................. 103 CodeActivity Demo ........................................................................................................ 104 Lab 4A ............................................................................................................................ 109 Composing Existing Activities ....................................................................................... 110 Demo: Composing Activities.......................................................................................... 111 Lab 4B............................................................................................................................. 115 Bonus Example ............................................................................................................... 116 Summary ......................................................................................................................... 117

Chapter 5: Workflow Hosting ......................................................................................... 129 WorkflowInvoker............................................................................................................ 131 Specifying Input to a Workflow ..................................................................................... 132 Using Dictionaries .......................................................................................................... 133 Output Argument ............................................................................................................ 134 Invoking a Generic Activity ........................................................................................... 135

Evaluation Copy

Page 7: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

Rev. 4.5 Copyright ©2013 Object Innovations Enterprises, LLC vii All Rights Reserved

Result Output Argument ................................................................................................. 136 Reusing a Workflow ....................................................................................................... 137 Workflow Timeout.......................................................................................................... 138 Timeout with Idle Time .................................................................................................. 139 Long Computation without Idle Time ............................................................................ 141 Invoking the Long Computation..................................................................................... 143 Long Computation with Timeout.................................................................................... 144 Lab 5A ............................................................................................................................ 145 Hosting a Workflow in Windows ................................................................................... 146 Windows Host Code ....................................................................................................... 147 WorkflowInvoker Instance Methods .............................................................................. 148 WorkflowInvoker Asynchronous Methods..................................................................... 149 Asynchronous Demonstration......................................................................................... 150 HelloAsync Code (Invoker)............................................................................................ 152 Example Workflow......................................................................................................... 154 Effect of Sleep................................................................................................................. 155 WorkflowApplication ..................................................................................................... 156 WorkflowApplication Demo .......................................................................................... 157 Thread Synchronization.................................................................................................. 161 Arguments....................................................................................................................... 162 WorkflowApplication Async Demo ............................................................................... 163 HelloAsync Code (Application) ..................................................................................... 165 WorkflowApplication Delegates .................................................................................... 166 Manual Control of Workflows........................................................................................ 167 Stopping Workflow Execution ....................................................................................... 168 Workflow Manual Control Example .............................................................................. 169 Enqueue Workflow ......................................................................................................... 170 Dequeue Workflow......................................................................................................... 171 Host Code for Enqueue Workflow ................................................................................. 172 Host Code for Dequeue Workflow ................................................................................. 173 Lab 5B............................................................................................................................. 174 Hosting a Workflow in ASP.NET .................................................................................. 175 ASP.NET Workflow Host .............................................................................................. 176 Lab 5C............................................................................................................................. 177 Summary ......................................................................................................................... 178

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

Evaluation Copy

Page 8: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

Rev. 4.5 Copyright ©2013 Object Innovations Enterprises, LLC viii All Rights Reserved

Using ForEach<T> ......................................................................................................... 198 Using ParallelForEach<T> ............................................................................................. 199 Using AsyncCodeActivity .............................................................................................. 200 Example Code................................................................................................................. 201 Host Code........................................................................................................................ 202 Asynchronous Activities in WF...................................................................................... 203 Factor.cs .......................................................................................................................... 204 FactorNumber.cs............................................................................................................. 205 Async Coding: BeginExecute ......................................................................................... 206 Async Coding: EndExecute ............................................................................................ 207 Lab 6 ............................................................................................................................... 208 Summary ......................................................................................................................... 209

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

Chapter 8: Flowchart and State Machine ...................................................................... 251 Workflow Modeling Styles............................................................................................. 253 Flowchart Activities........................................................................................................ 254 Flowchart Activity Designer........................................................................................... 255 Demo: Absolute Value Flowchart .................................................................................. 256 Auto-Connect.................................................................................................................. 261 Using FlowDecision ....................................................................................................... 262

Evaluation Copy

Page 9: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

Rev. 4.5 Copyright ©2013 Object Innovations Enterprises, LLC ix All Rights Reserved

Flowchart and Custom Activities ................................................................................... 265 Lab 8A ............................................................................................................................ 266 State Machine Workflows in WF 4.5 ............................................................................. 267 State Machine Workflow Modeling ............................................................................... 268 State Machine Workflow Example................................................................................. 269 Power On Transition ....................................................................................................... 270 TransitionCommand Trigger .......................................................................................... 271 Warming State ................................................................................................................ 272 Heated Transition............................................................................................................ 273 Host Program .................................................................................................................. 274 State Machine Activity Designer.................................................................................... 275 Demo: Timer State Machine........................................................................................... 276 Timer in the Math Game................................................................................................. 281 Do Problem State ............................................................................................................ 282 TimeUp Transition.......................................................................................................... 283 Time Out State ................................................................................................................ 284 Complete Transition ....................................................................................................... 285 Threading Issue............................................................................................................... 286 Threading Issue Resolved............................................................................................... 288 Shared Trigger ................................................................................................................ 289 Echo Transition............................................................................................................... 290 Quit Transition................................................................................................................ 291 Lab 8B............................................................................................................................. 292 Summary ......................................................................................................................... 293

Chapter 9: Persistence...................................................................................................... 309 Long Running Workflows .............................................................................................. 311 Persistence and Bookmarks ............................................................................................ 312 Long-Running Workflow Example ................................................................................ 313 Persistent Term Life Example ........................................................................................ 314 Workflow Persistence in WF 4.5 .................................................................................... 315 SQL Server Persistence Database................................................................................... 316 Host Code to Enable Persistence .................................................................................... 317 Persistence Demo............................................................................................................ 318 AutoResetEvent .............................................................................................................. 322 PersistableIdle Event....................................................................................................... 324 How to Persist a Workflow............................................................................................. 326 Loading a Persisted Workflow........................................................................................ 327 Unload and Load Example.............................................................................................. 328 StartAndUnloadInstance() .............................................................................................. 329 LoadAndCompleteInstance().......................................................................................... 330 Stopping and Starting the Host ....................................................................................... 331 StartWorkflow................................................................................................................. 332 StartWorkflow................................................................................................................. 333 Loading After Data Available......................................................................................... 334 InitNames........................................................................................................................ 335

Evaluation Copy

Page 10: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

Rev. 4.5 Copyright ©2013 Object Innovations Enterprises, LLC x All Rights Reserved

GetString......................................................................................................................... 336 String Commands............................................................................................................ 337 Host Program .................................................................................................................. 339 Lab 9 ............................................................................................................................... 340 Summary ......................................................................................................................... 341

Chapter 10: Workflow Services....................................................................................... 347 What Is WCF?................................................................................................................. 349 WCF Services ................................................................................................................. 350 WCF = ABC ................................................................................................................... 351 Address, Binding, Contract............................................................................................. 352 Workflow Services.......................................................................................................... 353 Messaging Activities....................................................................................................... 354 Messaging Activity Templates ....................................................................................... 355 Demo – Creating a Workflow Service............................................................................ 356 WCF Test Client ............................................................................................................. 360 Demo – Workflow Services Client ................................................................................. 362 Multiple Operations ........................................................................................................ 365 Multiple Operations via Parallel ..................................................................................... 366 Hosting a Workflow Service........................................................................................... 367 Configuration File........................................................................................................... 368 WorkflowServiceHost Example ..................................................................................... 369 Program.cs ...................................................................................................................... 370 Startup Configuration ..................................................................................................... 372 Lab 10 ............................................................................................................................. 373 Summary ......................................................................................................................... 374

Chapter 11: Debugging and Error Handling ................................................................. 385 Debugging Workflows.................................................................................................... 387 Control Flow and Flowchart ........................................................................................... 388 Breakpoint Example........................................................................................................ 389 Breakpoint in XAML...................................................................................................... 390 Exceptions....................................................................................................................... 391 Exception Demonstration ............................................................................................... 392 Account and Bank Classes.............................................................................................. 393 Use of Dictionary............................................................................................................ 394 Deposit and Withdraw .................................................................................................... 395 Code Activities ............................................................................................................... 396 Composite Activities....................................................................................................... 397 Top-Level Workflow ...................................................................................................... 398 Host Program .................................................................................................................. 399 Unhandled Exceptions .................................................................................................... 400 Using WorkflowApplication........................................................................................... 401 Sample Output ................................................................................................................ 402 TryCatch Activity ........................................................................................................... 403 TryCatch Demo............................................................................................................... 404

Evaluation Copy

Page 11: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

Rev. 4.5 Copyright ©2013 Object Innovations Enterprises, LLC xi All Rights Reserved

Transactions .................................................................................................................... 409 Compensation ................................................................................................................. 410 No Compensation............................................................................................................ 411 Using Compensation....................................................................................................... 412 Transfer.xaml .................................................................................................................. 413 Compensable Withdrawal............................................................................................... 414 Compensation Token ...................................................................................................... 415 Canceling the Workflow................................................................................................. 416 Exceptions and Compensation........................................................................................ 417 Compensation Not Performed......................................................................................... 418 Lab 11 ............................................................................................................................. 419 Summary ......................................................................................................................... 420

Appendix A: Learning Resources.................................................................................... 429

Evaluation Copy

Page 12: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

Rev. 4.5 Copyright ©2013 Object Innovations Enterprises, LLC xii All Rights Reserved

Evaluation Copy

Page 13: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 1

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 1 All Rights Reserved

Chapter 1

Workflow Foundation Conceptual Overview

Evaluation Copy

Page 14: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 1

Rev. 4.5 Copyright © 2013 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/4.5.

Evaluation Copy

Page 15: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 1

Rev. 4.5 Copyright © 2013 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.

Evaluation Copy

Page 16: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 1

Rev. 4.5 Copyright © 2013 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.

Evaluation Copy

Page 17: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 1

Rev. 4.5 Copyright © 2013 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.

Evaluation Copy

Page 18: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 1

Rev. 4.5 Copyright © 2013 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.

Evaluation Copy

Page 19: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 1

Rev. 4.5 Copyright © 2013 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.

Evaluation Copy

Page 20: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 1

Rev. 4.5 Copyright © 2013 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.

Evaluation Copy

Page 21: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 1

Rev. 4.5 Copyright © 2013 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.

Evaluation Copy

Page 22: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 1

Rev. 4.5 Copyright © 2013 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.

Evaluation Copy

Page 23: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 1

Rev. 4.5 Copyright © 2013 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.

Evaluation Copy

Page 24: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 1

Rev. 4.5 Copyright © 2013 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 uses the LocalDB version of SQL Server 2012, which is automatically installed with Visual Studio 2012.

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

Evaluation Copy

Page 25: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 1

Rev. 4.5 Copyright © 2013 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.

Evaluation Copy

Page 26: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 1

Rev. 4.5 Copyright © 2013 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.

Evaluation Copy

Page 27: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 1

Rev. 4.5 Copyright © 2013 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

Evaluation Copy

Page 28: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 1

Rev. 4.5 Copyright © 2013 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>

Evaluation Copy

Page 29: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 1

Rev. 4.5 Copyright © 2013 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>

Evaluation Copy

Page 30: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 1

Rev. 4.5 Copyright © 2013 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.

Evaluation Copy

Page 31: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 1

Rev. 4.5 Copyright © 2013 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.

Evaluation Copy

Page 32: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 1

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 20 All Rights Reserved

Orders Workflow in WF 3

Evaluation Copy

Page 33: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 1

Rev. 4.5 Copyright © 2013 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.

Evaluation Copy

Page 34: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 1

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 22 All Rights Reserved

Windows Workflow Foundation 4.5

• Windows Workflow Foundation in .NET 4.5 and Visual Studio 2012 contains new activities, designer capabilities, and a new workflow development model.

− Some of this capability was available in the Service Pack and Platform Update to Visual Studio 2010.

• A major enhancement for C# programmers is C# expressions.

− Prior to .NET 4.5 expressions in workflows had to be written in Visual Basic.

• .NET 4.5 provides for a state machine development model out-of-the box.

− WF 3 supported state machines but WF 4 did not. The state machine development model was provided in the Platform Update to Visual Studio 2010.

• There are a number of new designer capabilities:

− Auto-surround with Sequence: Dragging a second activity into a block expecting a single activity will cause the designer to automatically insert a Sequence.

− There is an auto-connect feature in flowcharts.

− Breakpoints can be set on states in state machines.

• Consult MSDN documentation for other enhancements in WF 4.5.

Evaluation Copy

Page 35: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 1

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 23 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.

• WF 4.5 contains new activities, designer capabilities, and a new state machine development model. C# expressions are supported in workflows.

Evaluation Copy

Page 36: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 1

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 24 All Rights Reserved

Evaluation Copy

Page 37: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 2

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 25 All Rights Reserved

Chapter 2

Getting Started with WF 4.5

Evaluation Copy

Page 38: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 2

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 26 All Rights Reserved

Getting Started with WF 4.5

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

• 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 C# expressions in workflow programs.

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

Evaluation Copy

Page 39: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 2

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 27 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().

Evaluation Copy

Page 40: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 2

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 28 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.

Evaluation Copy

Page 41: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 2

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 29 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." } } };

Evaluation Copy

Page 42: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 2

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 30 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.

Evaluation Copy

Page 43: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 2

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 31 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.

Evaluation Copy

Page 44: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 2

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 32 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.

Evaluation Copy

Page 45: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 2

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 33 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()); } }

Evaluation Copy

Page 46: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 2

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 34 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.

Evaluation Copy

Page 47: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 2

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 35 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”.

Evaluation Copy

Page 48: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 2

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 36 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 expression1.

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

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

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

"Hello, " + Name

1 In WF 4.5 you use C# expression for C# Workflow projects. Previously VB expressions were used.

Evaluation Copy

Page 49: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 2

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 37 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 . . .

Evaluation Copy

Page 50: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 2

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 38 All Rights Reserved

C# and Visual Basic Expressions

• In WF 4.5 new workflows created with C# use C# expression syntax and workflows created with Visual Basic use VB syntax.

− In WF 4 expressions always used VB syntax.

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

• For long expressions, click the button to bring up the Expression Editor.

Evaluation Copy

Page 51: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 2

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 39 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.

Evaluation Copy

Page 52: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 2

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 40 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.

Evaluation Copy

Page 53: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 2

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 41 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

Evaluation Copy

Page 54: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 2

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 42 All Rights Reserved

Control Flow Activities

• The Built-In Activity Library provides a number of activities to support a variety of control flow patterns.

− The simplest is Sequence, which provides for the sequential execution of activities.

− Looping behavior can be implemented with While, DoWhile and ForEach activites.

− Conditional execution can be implemented with If and Switch activities.

− These and other control flow activities are discussed in Chapter 3.

• Let’s illustrate control flow using While.

− See FactorialWhile in the chapter folder, which calculates the factorial of a positive integer N.

− Here is the top-level workflow:

Evaluation Copy

Page 55: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 2

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 43 All Rights Reserved

While Activity

• The logic for calculating the factorial of N can be expressed in this C# code:

int N = 5; int Fact = 1; while (N > 1) { Fact = Fact * N; N = N - 1; }

• Our workflow program implements the same logic using the While activity.

− Expand the first activity of the Sequence.

Evaluation Copy

Page 56: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 2

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 44 All Rights Reserved

Lab 2B

Exercises Using While and DoWhile

In this lab you will implement several exercises using the While and DoWhile activities.

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

Suggested time: 45 minutes

Evaluation Copy

Page 57: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 2

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 45 All Rights Reserved

Summary

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

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

• It is possible to implement workflows using only C# code.

• Visual Studio 2012 has several templates for creating workflow applications.

• You can implement workflows declaratively in XAML by using the Visual Studio Workflow Designer.

• With the Sequence activity you can implement workflows consisting of multiple activities.

• There are a number of primitive built-in activities, including WriteLine and Assign.

• WF 4.5 has a clear model for data flow using variables, arguments and expressions.

• There are a number of built-in Control Flow activities such as While and If.

Evaluation Copy

Page 58: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 2

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 46 All Rights Reserved

Lab 2A

A Calculator Workflow

Introduction 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. Some hints are provided after the statements of the exercises. Suggested Time: 30 minutes Root Directory: OIC\WfCs Directories: Labs\Lab2A (do your work here) Chap02\Calculator\Step1 (answer to Part 1) Chap02\Calculator\Step2 (answer to Part 2) Chap02\Calculator\Step3 (answer to Part 3) Part 1 Create a Workflow Console Application Calculator with the following features:

• A Sequence that contains two Assign and two WriteLine activities. • Integer variables X and Y with default values. • Integer variables Sum and Diff • Calculate the sum and difference in the two Assigns and display them in the two

WriteLines. The finished workflow is shown on the following page. Part 2 Modify your program so that X and Y are now arguments rather than variables. The values you previously used as default values should now be passed in a dictionary that is used as a second parameter. These values are hardcoded in Program.cs. Part 3 Modify your program so that instead the values to use for X and Y are passed as command-line parameters. You can then start a command prompt from Windows, navigate to the bin\Debug folder, and enter a command such as this: Calculator 13 8 As a final touch, change the DisplayName of your activities to be more descriptive.

Evaluation Copy

Page 59: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 2

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 47 All Rights Reserved

Hints for Part 1 Here is the workflow:

Here are the definitions of the variables:

Here are the C# expressions for the two WriteLines: String.Format("{0} + {1} = {2}", X, Y, Sum) String.Format("{0} - {1} = {2}", X, Y, Diff)

Evaluation Copy

Page 60: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 2

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 48 All Rights Reserved

Hints for Part 2 X and Y are deleted from the list of Variables and are now in the list of Arguments.

The code in Program.cs is modified to create a dictionary of input arguments. This dictionary is passed as a second parameter to the WorkflowInvoker.Invoke() method. class Program { static void Main(string[] args) { WorkflowInvoker.Invoke(new Workflow1(), new Dictionary<string, object> { {"X", 13}, {"Y", 8} }); } } Hints for Part 3 In place of hardcoding values for “X” and “Y”, we now obtain the values from the command line. Since the Main() method receives arguments as strings, we must parse these arguments to obtain integers. Here is the code in Program.cs: class Program { static void Main(string[] args) { int x = Int32.Parse(args[0]); int y = Int32.Parse(args[1]); WorkflowInvoker.Invoke(new Workflow1(), new Dictionary<string, object> { {"X", x}, {"Y", y} }); } } The workflow with more descriptive DisplayNames is shown on the next page.

Evaluation Copy

Page 61: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 2

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 49 All Rights Reserved

You can run the program at the command line and provide arguments then, or you may specify command line arguments in the Debug options of the project properties.

Evaluation Copy

Page 62: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 2

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 50 All Rights Reserved

Lab 2B

Exercises Using While and DoWhile

Introduction In this lab you will implement several exercises using the While and DoWhile activities. Suggested Time: 45 minutes Root Directory: OIC\WfCs Directories: Labs\Lab2B (do your work here) Chap02\ChristmasDoWhile (answer to Exercise 1) Chap02\ArrayWF\Step1 (answer to Exercise 2) Chap02\ArrayWF\Step2 (answer to Exercise 3) Exercise 1 Create a Workflow Console Application Christmas that will display the number of gifts giving each day in the “twelve days of Christmas” and the total number of gifts given in all. Recall from the song that On day 1 there is 1 gift On day 2 there are 1 + 2 = 3 gifts On day 3 there are 1 + 2 + 3 = 6 gifts And so on. Use variables Day, Gifts and Total. Use a DoWhile activity. The logic can be expressed in this C# code: int Day = 0; int Gifts = 0; int Total = 0; do { Day += 1; Gifts += Day; Total += Gifts; Console.WriteLine("On day {0} number of gifts = {1}", Day, Gifts); } while (Day < 12); Console.WriteLine("Total number of gifts = {0}", Total); The finished workflow is shown on the following page.

Evaluation Copy

Page 63: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 2

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 51 All Rights Reserved

Exercise 2 Create a Workflow Console Application ArrayWF that will calculate the sum and product of all numbers in an integer array. Your logic should handle the case of an empty array as well as an array with several integers. Hints for Exercise 1 The heart of the workflow is this DoWhile activity:

Within the loop this C# expression displays number of gifts given on a day: String.Format("On day {0} number of gifts = {1}", Day, Gifts) After the loop this C# expression displays the total number of gifts given:

Evaluation Copy

Page 64: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 2

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 52 All Rights Reserved

String.Format("Total number of gifts = {0}", Total) Hints for Exercise 2 The logic is expressed in this C# code. Commented out is initialization of an empty array. Since we want to allow for the possibility of going through the loop zero times, we should use a while loop rather than a do while. int[] arr = { 2, 3, 5 }; //int[] arr = { }; int sum = 0; int prod = 1; int i = 0; while (i < arr.Length) { sum += arr[i]; prod *= arr[i]; i += 1; } Console.WriteLine("Sum = {0}", sum); Console.WriteLine("Product = {0}", prod); Here are suitable variables, scoped to the top-level Sequence. The syntax for the array initialization is a little tricky.

Here is the top-level workflow:

Evaluation Copy

Page 65: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 2

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 53 All Rights Reserved

Here is the workflow of the While activity:

Exercise 3 (Optional) Modify your program to test via passing array elements in at the command line. Your Program.cs should allow for both empty and non-empty argument lists. Hint for Exercise 3 You need to initialize an array in Program.cs and pass this array to the workflow as an argument in a dictionary. You could first initialize the array by simple assignment: int[] arr = { 2, 3, 5 }; Here is the code to pass the array to the workflow via an argument in a dictionary:

Evaluation Copy

Page 66: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 2

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 54 All Rights Reserved

WorkflowInvoker.Invoke(new Workflow1(), new Dictionary<string, object> { {"Arr", arr} }); You also have to create a String argument Arr in Workflow1.xaml.

When this is working, you can create the C# code to build the array from arguments entered at the command line. int[] arr; if (args.Length > 0) { arr = new int[args.Length]; for (int i = 0; i < args.Length; i++) { arr[i] = Int32.Parse(args[i]); } } else arr = new int[] {};

Evaluation Copy

Page 67: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 7

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 215 All Rights Reserved

Chapter 7

More about Custom Activities

Evaluation Copy

Page 68: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 7

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 216 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.

Evaluation Copy

Page 69: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 7

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 217 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.

Evaluation Copy

Page 70: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 7

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 218 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.

Evaluation Copy

Page 71: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 7

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 219 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().

Evaluation Copy

Page 72: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 7

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 220 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.

Evaluation Copy

Page 73: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 7

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 221 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; } } }

Evaluation Copy

Page 74: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 7

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 222 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(); }

Evaluation Copy

Page 75: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 7

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 223 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);

Evaluation Copy

Page 76: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 7

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 224 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.)

Evaluation Copy

Page 77: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 7

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 225 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); } ... }

Evaluation Copy

Page 78: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 7

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 226 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"); }

Evaluation Copy

Page 79: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 7

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 227 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); }

Evaluation Copy

Page 80: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 7

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 228 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.

Evaluation Copy

Page 81: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 7

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 229 All Rights Reserved

Lab 7

Bookmark in a Math Game

In this lab you will modify the math game from Chapter 4 to use a bookmark. The user is prompted to answer multiplication problems. You will compare the original solution that does not use a bookmark 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: 60 minutes

Evaluation Copy

Page 82: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 7

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 230 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 FactorQueueBookmark1.

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

1 This example was originally created using .NET 4.0 and recompiled in Visual Studio 2012. It uses Visual Basic expressions.

Evaluation Copy

Page 83: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 7

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 231 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); } ...

Evaluation Copy

Page 84: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 7

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 232 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.

Evaluation Copy

Page 85: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 7

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 233 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.

− To run this program, make FactorGui the startup project.

Evaluation Copy

Page 86: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 7

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 234 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.

Evaluation Copy

Page 87: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 7

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 235 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.

Evaluation Copy

Page 88: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 7

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 236 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!

Evaluation Copy

Page 89: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 7

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 237 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.

Evaluation Copy

Page 90: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 7

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 238 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.

Evaluation Copy

Page 91: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 7

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 239 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.

Evaluation Copy

Page 92: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 7

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 240 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.

Evaluation Copy

Page 93: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 7

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 241 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.

Evaluation Copy

Page 94: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 7

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 242 All Rights Reserved

Lab 7

Bookmark in a Math Game

Introduction In this lab you will modify the math game from Chapter 4 to use a bookmark. The user is prompted to answer multiplication problems. You will compare the original solution that does not use a bookmark with other versions that do use a bookmark. Suggested Time: 60 minutes Root Directory: OIC\WfCs Directories: Labs\Lab7\BookmarkGame (do your work here) Chap04\MathGame\Step1 (backup of starter code) Chap07\BookmarkGame\Step1 (solution to Part 1) Chap07\BookmarkGame\Step2 (solution to Part 2) Chap07\BookmarkGame\Step3 (solution to Part 3) Part 1. A Single Problem (Using a 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. You are also given 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 are between 1 and 20. Modify the 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.

Evaluation Copy

Page 95: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 7

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 243 All Rights Reserved

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

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.

Evaluation Copy

Page 96: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 7

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 244 All Rights Reserved

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.

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

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

Evaluation Copy

Page 97: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 7

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 245 All Rights Reserved

// Obtain the input the workflow is expecting and resume the // bookmark string strNum = Console.ReadLine(); int num = Int32.Parse(strNum); wfApp.ResumeBookmark("GetNumber", num); // Wait for workflow completion sync.WaitOne(); } And here is the complete workflow:

Part 2. 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.

Evaluation Copy

Page 98: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 7

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 246 All Rights Reserved

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.

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

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

Evaluation Copy

Page 99: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 7

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 247 All Rights Reserved

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. You will also need to import the ActivityLibrary1 namespace.

using ActivityLibrary1; ... 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 2.

Evaluation Copy

Page 100: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 7

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 248 All Rights Reserved

Part 3. 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.

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 as shown at the top of the next page.

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

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

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

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

Evaluation Copy

Page 101: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 7

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 249 All Rights Reserved

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));

Evaluation Copy

Page 102: Windows Workflow Foundation Using C# -  · PDF fileObject Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation Copy

WfCs Chapter 7

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 250 All Rights Reserved

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.

Evaluation Copy