SlideShare a Scribd company logo
1 of 102
Download to read offline
Object Innovations Course 4156
Student Guide
Revision 4.5
Windows Workflow
Foundation Using C#
Evaluation
C
opy
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
C
opy
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
C
opy
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:OICWfCs.
− 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:OICData 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
C
opy
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
C
opy
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
C
opy
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
C
opy
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
C
opy
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
C
opy
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
C
opy
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
C
opy
Rev. 4.5 Copyright ©2013 Object Innovations Enterprises, LLC xii
All Rights Reserved
Evaluation
C
opy
WfCs Chapter 1
Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 1
All Rights Reserved
Chapter 1
Workflow Foundation
Conceptual Overview
Evaluation
C
opy
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
C
opy
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
C
opy
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
C
opy
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
C
opy
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
C
opy
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
C
opy
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
C
opy
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 Chap01OrderWorkflow. See the file Workflow1.xaml
in the OrderWorkflow project for a diagram of the
workflow.
Evaluation
C
opy
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
C
opy
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
C
opy
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:OICData 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
C
opy
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>mary@bar.com</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
C
opy
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
C
opy
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:OICWfCsChap01OrderWorkflowOrders1002.xml
OrderId = 1002
Verification message = OK
OrderId = 1002
CustomerName = Mary Smith
CustomerEmail = mary@bar.com
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:OICWfCsChap01OrderWorkflowOrders1003.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:OICWfCsChap01OrderWorkflowOrders1004.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
C
opy
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>bill@forest.net</CustomerEmail>
<Message>Description does not match</Message>
</Issue>
Evaluation
C
opy
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>mary@bar.com</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
C
opy
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
C
opy
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.
Windows
Presentation
Foundation
(WPF)
Windows
Communication
Foundation
(WCF)
Windows
Workflow
Foundation
(WF)
Windows
CardSpace
(WCS)
.NET Framework 2.0
Windows
Forms
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
C
opy
WfCs Chapter 1
Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 20
All Rights Reserved
Orders Workflow in WF 3Evaluation
C
opy
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
C
opy
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
C
opy
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
C
opy
WfCs Chapter 1
Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 24
All Rights Reserved
Evaluation
C
opy
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
C
opy
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
C
opy
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
C
opy
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
C
opy
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
C
opy
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
C
opy
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
C
opy
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
C
opy
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
C
opy
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
C
opy
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
C
opy
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
C
opy
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
C
opy
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
C
opy
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
C
opy
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
C
opy
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
C
opy
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
C
opy
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
C
opy
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
C
opy
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
C
opy
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: OICWfCs
Directories: LabsLab2A (do your work here)
Chap02CalculatorStep1 (answer to Part 1)
Chap02CalculatorStep2 (answer to Part 2)
Chap02CalculatorStep3 (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 binDebug 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
C
opy
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
C
opy
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
C
opy
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
C
opy
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: OICWfCs
Directories: LabsLab2B (do your work here)
Chap02ChristmasDoWhile (answer to Exercise 1)
Chap02ArrayWFStep1 (answer to Exercise 2)
Chap02ArrayWFStep2 (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
C
opy
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
C
opy
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
C
opy
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
C
opy
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
C
opy
WfCs Chapter 7
Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 215
All Rights Reserved
Chapter 7
More about Custom Activities
Evaluation
C
opy
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
C
opy
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
C
opy
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
C
opy
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
C
opy
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
C
opy
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
C
opy
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
C
opy
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
C
opy
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
C
opy
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
C
opy
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
C
opy
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
C
opy
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
C
opy
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
C
opy
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
C
opy
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
C
opy
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
C
opy
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
C
opy
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
C
opy
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
C
opy
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
C
opy
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
C
opy
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
C
opy
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
C
opy
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
C
opy
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
C
opy
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: OICWfCs
Directories: LabsLab7BookmarkGame (do your work here)
Chap04MathGameStep1 (backup of starter code)
Chap07BookmarkGameStep1 (solution to Part 1)
Chap07BookmarkGameStep2 (solution to Part 2)
Chap07BookmarkGameStep3 (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
C
opy
Windows workflow foundation using c#
Windows workflow foundation using c#
Windows workflow foundation using c#
Windows workflow foundation using c#
Windows workflow foundation using c#
Windows workflow foundation using c#
Windows workflow foundation using c#
Windows workflow foundation using c#

More Related Content

What's hot

F7 wc9 zu3701lsg_ai
F7 wc9 zu3701lsg_aiF7 wc9 zu3701lsg_ai
F7 wc9 zu3701lsg_aipiano_girl
 
1 z0 062 - oracle certification
1 z0 062 - oracle certification1 z0 062 - oracle certification
1 z0 062 - oracle certificationadam_jhon
 
16 define workforce profiles
16 define workforce profiles16 define workforce profiles
16 define workforce profilesmohamed refaei
 
Part 1 workbench basics
Part 1 workbench basicsPart 1 workbench basics
Part 1 workbench basicstechbed
 
Suse service virtualization_image_set up_guide_140214
Suse service virtualization_image_set up_guide_140214Suse service virtualization_image_set up_guide_140214
Suse service virtualization_image_set up_guide_140214Darrel Rader
 
Olm implementation steps
Olm implementation stepsOlm implementation steps
Olm implementation stepsFeras Ahmad
 
Jsp And Servlets
Jsp And ServletsJsp And Servlets
Jsp And ServletsAdil Jafri
 
Lab 2) develop a java application
Lab 2) develop a java applicationLab 2) develop a java application
Lab 2) develop a java applicationtechbed
 
15 maintain worker directories
15 maintain worker directories15 maintain worker directories
15 maintain worker directoriesmohamed refaei
 
Lab 7a) debug a web application
Lab 7a) debug a web applicationLab 7a) debug a web application
Lab 7a) debug a web applicationtechbed
 
Part 2 java development
Part 2 java developmentPart 2 java development
Part 2 java developmenttechbed
 

What's hot (18)

F7 wc9 zu3701lsg_ai
F7 wc9 zu3701lsg_aiF7 wc9 zu3701lsg_ai
F7 wc9 zu3701lsg_ai
 
1 z0 062 - oracle certification
1 z0 062 - oracle certification1 z0 062 - oracle certification
1 z0 062 - oracle certification
 
16 define workforce profiles
16 define workforce profiles16 define workforce profiles
16 define workforce profiles
 
Part 1 workbench basics
Part 1 workbench basicsPart 1 workbench basics
Part 1 workbench basics
 
Suse service virtualization_image_set up_guide_140214
Suse service virtualization_image_set up_guide_140214Suse service virtualization_image_set up_guide_140214
Suse service virtualization_image_set up_guide_140214
 
Olm implementation steps
Olm implementation stepsOlm implementation steps
Olm implementation steps
 
21 fbl integration-01
21   fbl integration-0121   fbl integration-01
21 fbl integration-01
 
jfx
jfxjfx
jfx
 
03 fsm
03 fsm03 fsm
03 fsm
 
Jsp And Servlets
Jsp And ServletsJsp And Servlets
Jsp And Servlets
 
Lab 2) develop a java application
Lab 2) develop a java applicationLab 2) develop a java application
Lab 2) develop a java application
 
11 define grades
11 define grades11 define grades
11 define grades
 
xCP 2.1 Developer Guide
xCP 2.1 Developer GuidexCP 2.1 Developer Guide
xCP 2.1 Developer Guide
 
15 maintain worker directories
15 maintain worker directories15 maintain worker directories
15 maintain worker directories
 
22 export
22 export22 export
22 export
 
Lab 7a) debug a web application
Lab 7a) debug a web applicationLab 7a) debug a web application
Lab 7a) debug a web application
 
Part 2 java development
Part 2 java developmentPart 2 java development
Part 2 java development
 
12 define jobs
12 define jobs12 define jobs
12 define jobs
 

Similar to Windows workflow foundation using c#

HOL-0419-01-PowerProtect_Data_Manager_-19.11.pdf
HOL-0419-01-PowerProtect_Data_Manager_-19.11.pdfHOL-0419-01-PowerProtect_Data_Manager_-19.11.pdf
HOL-0419-01-PowerProtect_Data_Manager_-19.11.pdfHua Chiang
 
Oracle9i application server oracle forms services
Oracle9i application server   oracle forms servicesOracle9i application server   oracle forms services
Oracle9i application server oracle forms servicesFITSFSd
 
HDinsight Workshop - Prerequisite Activity
HDinsight Workshop - Prerequisite ActivityHDinsight Workshop - Prerequisite Activity
HDinsight Workshop - Prerequisite ActivityIdan Tohami
 
Practical web services for RPG lab exercises
Practical web services for RPG lab exercisesPractical web services for RPG lab exercises
Practical web services for RPG lab exercisesCOMMON Europe
 
Ensure Optimal Performance and Scalability: Implementing a Robust and Reliabl...
Ensure Optimal Performance and Scalability: Implementing a Robust and Reliabl...Ensure Optimal Performance and Scalability: Implementing a Robust and Reliabl...
Ensure Optimal Performance and Scalability: Implementing a Robust and Reliabl...Steve Feldman
 
Spring data jpa are used to develop spring applications
Spring data jpa are used to develop spring applicationsSpring data jpa are used to develop spring applications
Spring data jpa are used to develop spring applicationsmichaelaaron25322
 
O365 Developer Bootcamp NJ 2018 - Material
O365 Developer Bootcamp NJ 2018 - MaterialO365 Developer Bootcamp NJ 2018 - Material
O365 Developer Bootcamp NJ 2018 - MaterialThomas Daly
 
Exploratory Testing As Code Eurostar23
Exploratory Testing As Code Eurostar23Exploratory Testing As Code Eurostar23
Exploratory Testing As Code Eurostar23Brendan Connolly
 
Exploratory Testing As Code
Exploratory Testing As CodeExploratory Testing As Code
Exploratory Testing As CodeBrendan Connolly
 
Simplifying RCP Update and Install
Simplifying RCP Update and InstallSimplifying RCP Update and Install
Simplifying RCP Update and Installsusanfmccourt
 
Best practices for implementing CI/CD on Salesforce
Best practices for implementing CI/CD on SalesforceBest practices for implementing CI/CD on Salesforce
Best practices for implementing CI/CD on SalesforceAIMDek Technologies
 
Oracle formstutorial
Oracle formstutorialOracle formstutorial
Oracle formstutorialphamdanhvu
 
Oracle formstutorial
Oracle formstutorialOracle formstutorial
Oracle formstutorialbhanu_mca
 
TDD Painkillers
TDD PainkillersTDD Painkillers
TDD PainkillersBen Hall
 
Vce vdi reference_architecture_knowledgeworkerenvironments
Vce vdi reference_architecture_knowledgeworkerenvironmentsVce vdi reference_architecture_knowledgeworkerenvironments
Vce vdi reference_architecture_knowledgeworkerenvironmentsItzik Reich
 
Application Express - A web development environment for the masses - and for ...
Application Express - A web development environment for the masses - and for ...Application Express - A web development environment for the masses - and for ...
Application Express - A web development environment for the masses - and for ...Sage Computing Services
 
Ibm urban code_deploy_v6_lab-workbook
Ibm urban code_deploy_v6_lab-workbookIbm urban code_deploy_v6_lab-workbook
Ibm urban code_deploy_v6_lab-workbookBalipalliGayathri
 

Similar to Windows workflow foundation using c# (20)

Ado.net
Ado.netAdo.net
Ado.net
 
Learning selenium sample
Learning selenium sampleLearning selenium sample
Learning selenium sample
 
HOL-0419-01-PowerProtect_Data_Manager_-19.11.pdf
HOL-0419-01-PowerProtect_Data_Manager_-19.11.pdfHOL-0419-01-PowerProtect_Data_Manager_-19.11.pdf
HOL-0419-01-PowerProtect_Data_Manager_-19.11.pdf
 
Oracle9i application server oracle forms services
Oracle9i application server   oracle forms servicesOracle9i application server   oracle forms services
Oracle9i application server oracle forms services
 
Combined Project
Combined ProjectCombined Project
Combined Project
 
HDinsight Workshop - Prerequisite Activity
HDinsight Workshop - Prerequisite ActivityHDinsight Workshop - Prerequisite Activity
HDinsight Workshop - Prerequisite Activity
 
Practical web services for RPG lab exercises
Practical web services for RPG lab exercisesPractical web services for RPG lab exercises
Practical web services for RPG lab exercises
 
Ensure Optimal Performance and Scalability: Implementing a Robust and Reliabl...
Ensure Optimal Performance and Scalability: Implementing a Robust and Reliabl...Ensure Optimal Performance and Scalability: Implementing a Robust and Reliabl...
Ensure Optimal Performance and Scalability: Implementing a Robust and Reliabl...
 
Spring data jpa are used to develop spring applications
Spring data jpa are used to develop spring applicationsSpring data jpa are used to develop spring applications
Spring data jpa are used to develop spring applications
 
O365 Developer Bootcamp NJ 2018 - Material
O365 Developer Bootcamp NJ 2018 - MaterialO365 Developer Bootcamp NJ 2018 - Material
O365 Developer Bootcamp NJ 2018 - Material
 
Exploratory Testing As Code Eurostar23
Exploratory Testing As Code Eurostar23Exploratory Testing As Code Eurostar23
Exploratory Testing As Code Eurostar23
 
Exploratory Testing As Code
Exploratory Testing As CodeExploratory Testing As Code
Exploratory Testing As Code
 
Simplifying RCP Update and Install
Simplifying RCP Update and InstallSimplifying RCP Update and Install
Simplifying RCP Update and Install
 
Best practices for implementing CI/CD on Salesforce
Best practices for implementing CI/CD on SalesforceBest practices for implementing CI/CD on Salesforce
Best practices for implementing CI/CD on Salesforce
 
Oracle formstutorial
Oracle formstutorialOracle formstutorial
Oracle formstutorial
 
Oracle formstutorial
Oracle formstutorialOracle formstutorial
Oracle formstutorial
 
TDD Painkillers
TDD PainkillersTDD Painkillers
TDD Painkillers
 
Vce vdi reference_architecture_knowledgeworkerenvironments
Vce vdi reference_architecture_knowledgeworkerenvironmentsVce vdi reference_architecture_knowledgeworkerenvironments
Vce vdi reference_architecture_knowledgeworkerenvironments
 
Application Express - A web development environment for the masses - and for ...
Application Express - A web development environment for the masses - and for ...Application Express - A web development environment for the masses - and for ...
Application Express - A web development environment for the masses - and for ...
 
Ibm urban code_deploy_v6_lab-workbook
Ibm urban code_deploy_v6_lab-workbookIbm urban code_deploy_v6_lab-workbook
Ibm urban code_deploy_v6_lab-workbook
 

Recently uploaded

10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024Mind IT Systems
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfayushiqss
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...Shane Coughlan
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfonteinmasabamasaba
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfonteinmasabamasaba
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...kalichargn70th171
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfVishalKumarJha10
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech studentsHimanshiGarg82
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfryanfarris8
 
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxBUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxalwaysnagaraju26
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesVictorSzoltysek
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
ManageIQ - Sprint 236 Review - Slide Deck
ManageIQ - Sprint 236 Review - Slide DeckManageIQ - Sprint 236 Review - Slide Deck
ManageIQ - Sprint 236 Review - Slide DeckManageIQ
 
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456KiaraTiradoMicha
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park masabamasaba
 

Recently uploaded (20)

10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxBUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
ManageIQ - Sprint 236 Review - Slide Deck
ManageIQ - Sprint 236 Review - Slide DeckManageIQ - Sprint 236 Review - Slide Deck
ManageIQ - Sprint 236 Review - Slide Deck
 
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 

Windows workflow foundation using c#

  • 1. Object Innovations Course 4156 Student Guide Revision 4.5 Windows Workflow Foundation Using C# Evaluation C opy
  • 2. 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 C opy
  • 3. 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 C opy
  • 4. 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:OICWfCs. − 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:OICData 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 C opy
  • 5. 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 C opy
  • 6. 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 C opy
  • 7. 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 C opy
  • 8. 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 C opy
  • 9. 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 C opy
  • 10. 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 C opy
  • 11. 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 C opy
  • 12. Rev. 4.5 Copyright ©2013 Object Innovations Enterprises, LLC xii All Rights Reserved Evaluation C opy
  • 13. WfCs Chapter 1 Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 1 All Rights Reserved Chapter 1 Workflow Foundation Conceptual Overview Evaluation C opy
  • 14. 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 C opy
  • 15. 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 C opy
  • 16. 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 C opy
  • 17. 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 C opy
  • 18. 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 C opy
  • 19. 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 C opy
  • 20. 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 C opy
  • 21. 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 Chap01OrderWorkflow. See the file Workflow1.xaml in the OrderWorkflow project for a diagram of the workflow. Evaluation C opy
  • 22. 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 C opy
  • 23. 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 C opy
  • 24. 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:OICData 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 C opy
  • 25. 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>mary@bar.com</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 C opy
  • 26. 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 C opy
  • 27. 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:OICWfCsChap01OrderWorkflowOrders1002.xml OrderId = 1002 Verification message = OK OrderId = 1002 CustomerName = Mary Smith CustomerEmail = mary@bar.com 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:OICWfCsChap01OrderWorkflowOrders1003.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:OICWfCsChap01OrderWorkflowOrders1004.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 C opy
  • 28. 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>bill@forest.net</CustomerEmail> <Message>Description does not match</Message> </Issue> Evaluation C opy
  • 29. 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>mary@bar.com</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 C opy
  • 30. 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 C opy
  • 31. 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. Windows Presentation Foundation (WPF) Windows Communication Foundation (WCF) Windows Workflow Foundation (WF) Windows CardSpace (WCS) .NET Framework 2.0 Windows Forms 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 C opy
  • 32. WfCs Chapter 1 Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 20 All Rights Reserved Orders Workflow in WF 3Evaluation C opy
  • 33. 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 C opy
  • 34. 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 C opy
  • 35. 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 C opy
  • 36. WfCs Chapter 1 Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 24 All Rights Reserved Evaluation C opy
  • 37. 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 C opy
  • 38. 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 C opy
  • 39. 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 C opy
  • 40. 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 C opy
  • 41. 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 C opy
  • 42. 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 C opy
  • 43. 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 C opy
  • 44. 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 C opy
  • 45. 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 C opy
  • 46. 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 C opy
  • 47. 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 C opy
  • 48. 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 C opy
  • 49. 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 C opy
  • 50. 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 C opy
  • 51. 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 C opy
  • 52. 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 C opy
  • 53. 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 C opy
  • 54. 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 C opy
  • 55. 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 C opy
  • 56. 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 C opy
  • 57. 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 C opy
  • 58. 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: OICWfCs Directories: LabsLab2A (do your work here) Chap02CalculatorStep1 (answer to Part 1) Chap02CalculatorStep2 (answer to Part 2) Chap02CalculatorStep3 (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 binDebug 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 C opy
  • 59. 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 C opy
  • 60. 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 C opy
  • 61. 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 C opy
  • 62. 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: OICWfCs Directories: LabsLab2B (do your work here) Chap02ChristmasDoWhile (answer to Exercise 1) Chap02ArrayWFStep1 (answer to Exercise 2) Chap02ArrayWFStep2 (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 C opy
  • 63. 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 C opy
  • 64. 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 C opy
  • 65. 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 C opy
  • 66. 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 C opy
  • 67. WfCs Chapter 7 Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 215 All Rights Reserved Chapter 7 More about Custom Activities Evaluation C opy
  • 68. 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 C opy
  • 69. 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 C opy
  • 70. 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 C opy
  • 71. 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 C opy
  • 72. 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 C opy
  • 73. 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 C opy
  • 74. 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 C opy
  • 75. 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 C opy
  • 76. 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 C opy
  • 77. 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 C opy
  • 78. 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 C opy
  • 79. 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 C opy
  • 80. 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 C opy
  • 81. 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 C opy
  • 82. 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 C opy
  • 83. 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 C opy
  • 84. 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 C opy
  • 85. 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 C opy
  • 86. 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 C opy
  • 87. 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 C opy
  • 88. 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 C opy
  • 89. 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 C opy
  • 90. 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 C opy
  • 91. 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 C opy
  • 92. 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 C opy
  • 93. 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 C opy
  • 94. 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: OICWfCs Directories: LabsLab7BookmarkGame (do your work here) Chap04MathGameStep1 (backup of starter code) Chap07BookmarkGameStep1 (solution to Part 1) Chap07BookmarkGameStep2 (solution to Part 2) Chap07BookmarkGameStep3 (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 C opy