1. Trang chủ
  2. » Công Nghệ Thông Tin

pro wf.4.5 v413hav

638 2,1K 1
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Windows Workflow Foundation (WF) in .NET Framework 4.5
Tác giả Apress
Trường học Microsoft Corporation
Chuyên ngành Software Development
Thể loại Sách kỹ thuật
Năm xuất bản 2012
Thành phố Redmond
Định dạng
Số trang 638
Dung lượng 15,8 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Chapter 1Why Workflows This chapter explains why workflows are important for developing software, how they can provide a visual understanding of user requirements and design blueprints,

Trang 2

For your convenience Apress has placed some of the front matter material after the index Please use the Bookmarks and Contents at a Glance links to access them

Trang 3

Contents at a Glance

About the Author ���������������������������������������������������������������������������������������������������������������� xv

About the Technical Reviewer ������������������������������������������������������������������������������������������ xvii

Trang 4

Now that you have picked up this book and are curious enough to read this introduction, let me share with you how Windows Workflow Foundation (WF) can help you to be a better developer WF is a Microsoft NET technology that provides a fascinating way to develop software by defining workflows instead of writing conventional code

Building workflows is an exercise in which visual models or diagrams represent how logic will flow The first chapter quickly explains why workflows are important and walks through different ways of modeling scenarios outside of WF Since building workflows is quite different from writing code, this chapter will give you a visual

grounding in modeling processes if you are new to modeling

My passion for Windows Workflow (WF) started when I watched it being demoed (for the very first time) by Microsoft Hopefully that passion will infect you too, as you begin to understand how WF fits within your development toolbox

With the appearance of Visual Studio 2012 and NET Framework 4.5, a new version of WF has been released, referred to as WF4.5 Whether you are familiar with WF or not, this book will help you understand the new features in WF4.5 and how they can be used in real-world scenarios I have taken pains to make sure that this book does not leave

WF beginners in the dark, while showing experienced developers how to use its very latest features to accomplish practical tasks

Trang 5

Chapter 1

Why Workflows

This chapter explains why workflows are important for developing software, how they can provide a visual

understanding of user requirements and design blueprints, and the benefits of using workflow technology like Windows Workflow Foundation (WF)

Different types of workflows used for modeling

Business Processes

A process is a series of steps that must be completed to perform a desired unit of work and can be modeled using workflows Modeling processes as workflows is nothing new: in fact, humans have been modeling processes for centuries It seems that as our ancestors learned how to think, they also learned how to model their ideas Models provide a representation for an existing artifact or concept After a model is built it can be used for studying and collecting valuable information about the artifact it represents

Without modeling, what would the world be like today? We would not have airplanes or be able to cross over large bodies of water via bridges or ships Medical science would not be quite as far advanced as it is today without people like Leonardo Da Vinci, who drew the first concepts of human anatomy

Trang 6

ChapTeR 1 ■ Why WoRkFloWS

Mathematical equations are also considered models Consider equations that model supply and demand in economics, or the stock market Models are the transport for learning more about everyday life, and this simple concept

is what makes modeling processes within businesses so natural Transitioning from concepts around the laws of physics and biology, models are also used to learn about how businesses process everyday work as well By studying how processes are built we can make recommendations for making inefficient processes more efficient

Modeling business processes has become so important that many process management strategies have stemmed from it Because time is money, organizations rely on process management strategies that help them improve their processes for effectively doing business The Industrial Revolution pioneered the concept of displacing raw human labor with automation The methodology used to drive automation gave birth to industrial engineering (IE), which

is an example of a process management strategy that uses modeling techniques to optimize complex processes around managing time, energy, and resources Industrial engineers mainly focus on supply-chain manufacturing and distribution operations and use mathematical equations to optimize one or more department’s processes for managing and processing work more effectively

One example of how industrial engineering has made an impact is in the entertainment world of amusement parks, particularly in managing how customers wait in line for rides The concept is called a “Fast Pass” at some amusement parks and is constructed around queuing customers On certain days, an amusement park may have so many visitors that waiting lines for a certain ride can take a couple of hours Fortunately, a solution was developed to reduce the wait time for really popular rides: they set appointments for people who are interested in the ride but are

ok with experiencing it at a later time in the day

Waiting in line for an amusement ride models the same characteristics around First In, First Out (FIFO), which

is a concept around queuing This means that the customers who have waited the longest get to ride before the other customers who have been waiting less time By scheduling an appointment for a ride, customers can choose not to wait in line, therefore allowing them to enjoy other rides; this also dramatically reduces the wait time for the customers who actually choose to wait in line

Today, workflow technologies like WF are available for aligning process management methodologies A workflow technology should support the following behavioral characteristics:

• Process parameters: Information required for starting a process Processes sometimes require

information to be entered so it has data to process by making decisions

• Business rules: These rules drive how a process makes decisions Being able to manage

business rules while a process is running is important for implementing changes and

improving overall optimization over time

• Data-driven: Data sometimes drives the decisions for a business process because of the

state of the data An example of a data-driven process are extract, transform, and load (ETL)

processes that make decisions on where to load extracted data from a source

• Event-driven: Events drive processes by providing actions that a process can use for making

decisions An event can be fired externally or internally within a process

• State machine: These are processes that rely on external events for transitioning between

states for making decisions State machine processes provide a mechanism for receiving

external events usually fired by human decisions

Process agility: The flexibility within processes to adapt to continually changing environment of an

organization as it adapts to new trends and goals for processing business

Once these behavior characteristics are understood, software can be written to target functionality around closing the gap between the technical side of programming and the requirements software is created to fulfill, thereby providing a level

of abstraction and automation within business processes This has sparked the birth of additional process management methodologies that also focus on modeling business processes within organizations

Business process management (BPM) has been a significant player as a methodology within the business process and technology scene BPM helps manage business processes within an organization that affect one or more divisions

or departments and focuses on building effective business processes with the aid of technology There are other

Trang 7

ChapTeR 1 ■ Why WoRkFloWS

business process methodologies that also focus on optimizing business processes, but BPM stands out because it primarily relies on using technology when recommending solutions Just like software development, BPM has its own life cycle it uses to optimize processes within an organization (see Table 1-1)

Table 1-1 Business Process Management Life Cycle

Design Defining the stakeholder’s goals and requirements for effectiveness around how processes should

be executed within an organization

Model Building a representation of a business process to visually understand and recommend changes

for how it should process This usually includes recommendations for the logical flow, external/internal events, tracking metrics, and human interaction

Execute Physically adding a new process into an organization’s environment so the changes to the process

can be evaluated

Monitor Tracking metrics for a process while it is executing to evaluate the logic and performance

Optimize Making modifications to business processes based on provided metrics and environmental

changes

An important observation based on Figure 1-1 is that the lifecycle never ends This pattern is a reminder that business processes are continuously changing and always have room for improvement The pattern is called continual process improvement and it is not only important for ever-changing business processes, but also promotes the adoption of innovative ideas around technology that increase process effectiveness and quality

Design

ExecuteMonitor

Figure 1-1 BPM phase order

Workflow Activities

At the beginning of this chapter I mentioned that a workflow is a list of predefined steps that are executed in a specific order to perform an outcome and that you can use them to model processes Each step of a workflow is called an

activity and one or more activities makes up a workflow Just as the atom plays a role as the building block of the

universe, activities are considered the basic building blocks that define a workflow To demonstrate how activities are

Trang 8

ChapTeR 1 ■ Why WoRkFloWS

used and to show how easy it is to model as a workflow using activities, let’s look at an example of a simple process, such as going to the movies When planning to go to a movie, the first steps are as follows:

1 Check the times when the movie is showing

2 Order tickets, either at the theater or online

3 Pick up the tickets in order to enter the theater to see the movie

Figure 1-2 models each of these steps as activities within a workflow These are the basic steps that need to be taken for seeing a movie By following them, you execute a workflow every time you want to see a movie All workflows have

a starting and ending point, and within this workflow each activity must be processed in sequential order However, to maintain a level of flexibility for modeling processes, this is not a requirement for all workflows A major benefit of the workflow is that others can also use it for seeing a movie, too The concept of reuse does not have any real significance

in this example, but the familiar analogy of movie-going helps to illustrate the principle of reusing code, where a workflow can be built once and used by other processes

Check Movie Times

Order Tickets

Gain Admission

Figure 1-2 Workflow for going to a movie

Trang 9

ChapTeR 1 ■ Why WoRkFloWS

Defining Requirements

Another benefit gained by modeling a process as a workflow is transparency, which grants the ability to see a process

as a two dimensional model, illustrating the logic within the process Have you ever heard that a picture is worth

a thousand words? It’s the easiest way to communicate a process to others Let’s look at modeling a workflow for a business process that transfers money from one bank account to another In this case, there are no other requirements available for how this business process should work other than past experiences of transferring money Figure 1-3

represents a workflow for transferring funds from a saving account to a checking account

Trang 10

ChapTeR 1 ■ Why WoRkFloWS

Figure 1-3 demonstrates that funds will be transferred from a savings account (once it is determined that more than one dollar is available within the account) into a checking account If there is less than one dollar in the savings account, the transfer of funds activity will not execute within the workflow

Workflows can also be used to flush out additional requirements by gaining transparency into a business process For example, the bank might have additional rules around a mandatory minimal account balance that must be met before a certain amount of money can be transferred Also, what credentials must be authenticated against before gaining access to the savings account?

I learned the importance of using workflows as a way to communicate requirements the first time I lead a team of developers on a project We decided as a team that we would use workflows as way to communicate requirements not only to each other but with the client, too This way we could make sure that the team had a clear understanding of what the client needed

This became a real world exercise one day when I hit a brick wall while trying to understand the requirements being communicated to me from the client For whatever reason, communicating verbally with the client was not working, so I finally drew what I thought were the requirements By drawing the steps and decisions around the logic that the client and I were struggling to communicate verbally, we were able to finally understand each other

The most important part of creating software is not actually writing the code, as most developers tend to think Sometimes requirement gathering takes a back seat in software projects, but this is a recipe for disaster Decisions for architecting a solution and designing how it will function can only be made after understanding what needs to be built There is nothing more frustrating than trying to write software without knowing the full extent of the requirements It’s no better than setting out to build a house when you don’t have the blueprints

Sometimes a software project’s sponsors (those who drive the initiative and the direction of the software project) fail to recognize the importance of writing requirements Sometimes they overlook the time that should be allocated for gathering requirements in their enthusiasm to reduce cost or save money within the project Other times the omission

is because of bad experiences in the past, where the process became unproductive and drawn out, putting a squeeze

on project deadlines However, if gathering requirements was not important, it would not be included within the software development life cycle (SDLC), the software industry standard of phases that should be followed when developing software

The best practice for developing software enlists the SDLC to guide the process of development Table 1-2

represents the phases that are most commonly used within a SDLC Each phase of the cycle is equally important and depends on the previous phase Therefore, the success for a software project primarily relies on how well each phase

is executed

Table 1-2 System Development Life Cycle

Planning Building a case for initiating a software project to exceed the goals for project sponsors

Discovery Understanding the stakeholder’s business requirements so the project can be successful.Analysis Gathering and documenting user requirements around how the software should work and

Trang 11

ChapTeR 1 ■ Why WoRkFloWS

The first two phases, Planning and Discovery, focus on understanding stakeholder goals and how goals will be met or even exceeded for the overall project

The next phase, Analysis, focuses on gathering the requirements based on the stakeholder’s goals and how the software will function and perform Many development teams struggle with the Analysis phase Projects fail because development teams cannot communicate effectively or understand the process for defining requirements

A development team can have the best engineers on it, but a failure to explain to them what needs to be built can be catastrophic

It is important to understand the types of requirements needed for architecting and developing a solution Software requirements can be broken up into four areas

• Business requirements: Goals defined by project sponsors against which the success of the

project can be measured

• User requirements: Functionality that must be implemented, allowing users to accomplish

their objectives

• Functional requirements: Detailed representation usually provided by the technical leadership

to provide guidance through models and serve as the blueprints for how the software should

be developed collectively by the team

• Quality of service: Standards agreed upon for how developed software should scale and

perform based on predefined metrics These requirements are important when determining

the overall architecture for the solution

The key objective gained through modeling a process is to understand and learn more about the process while building a visual representation Workflows are a natural tool for defining the different types of requirements

previously mentioned

Model Driven Development

If you are consistently building models for the requirements gathered before writing any code for the software projects you develop, you are applying model-driven engineering (MDE) or model-driven development (MDD)1 The models created are then used to drive the business logic that is written as code

If you prefer a more agile approach, there is also agile model-driven development (AMDD) It builds models but applies an iterative approach for driving features of prioritized requirements to a deeper level, with iteration until all functionality is flushed out Critics of MDD feel that the models generated become stale or obsolete as processes change; however, this is where BPM comes to the rescue by always adapting to changes within processes

There are many tools available to model processes as workflows, and these give developers and architects the comfort of easily building diagrams without having to leave Visual Studio Before the rich diagramming features released with Visual Studio 2010 (VS2010) Ultimate, developers had to look outside of Visual Studio for other tools for modeling workflows Most used Microsoft Visio (and rightfully so as Visio’s templates cover just about every possible workflow) However, VS2010 Ultimate supports many diagrams, and these are covered in the next sections

Component Diagrams

Component diagrams illustrate the tiers included within the physical architecture for a solution Figure 1-4 illustrates

a rental service and the components that make up the rental service’s architecture It also illustrates how the

components interact with each other For instance, the ClientBrowser component’s HTTP interface requires services from the rental site to be able to use the rental service

1 Model-driven architecture (MDA) is an industry standard maintained by the Object Management Group (OMG)

Trang 12

ChapTeR 1 ■ Why WoRkFloWS

Use Case Diagrams

Use cases model interaction between users (referred to as actors) and a logical grouping of functionality, sometimes referred to as a subsystem Figure 1-5 illustrates a Jeep parts web site where customers can order parts for their car First a customer must either create a profile or log in; then the customer gets extended functionality for creating

an order Creating the order includes processing the order, which also includes processing payment and later even refunding money if a customer wants to return part or all of an order

Figure 1-4 Component diagram for a rental service

Trang 13

ChapTeR 1 ■ Why WoRkFloWS

Class Diagrams

Class diagrams model relationships for objects defined with code Entities defined within a business domain are usually modeled in code to closely relate their role within the business Figure 1-6 illustrates three classes that make up a part order There is a composite relationship between the order and the order line item because an order contains an order line item An order line item shows it has a relationship with an auto part based on the part’s ID and indicates that there can only be one part ordered per line item; however, many order line items can have the same part ordered

ProcessPayment

IssueRefunds

CreateProfile

Figure 1-5 Component diagram for a rental service

Trang 14

ChapTeR 1 ■ Why WoRkFloWS

Sequence Diagrams

Sequence diagrams show how processes interact within a system Sequence diagrams can illustrate a deeper representation than a use case because they represent a full sequence for a process from beginning to end and provide clarity regarding the interaction of the participants involved Figure 1-7 illustrates four participants and how they interact with each other when creating and processing a parts order

Trang 15

ChapTeR 1 ■ Why WoRkFloWS

Activity Diagrams

Activity diagrams model business logic and work well for discovering additional user requirements that might not have been considered or thought through completely Since activity diagrams can be used for modeling, they are a great tool for building workflows Table 1-3 explains the symbols that are available within Visual Studio for diagraming activity diagrams

Figure 1-7 Processing a parts order

Trang 16

ChapTeR 1 ■ Why WoRkFloWS

Building an Activity Diagram

To build diagrams in Visual Studio you will need Visual Studio 11 Ultimate Here are the steps for building diagrams in Visual Studio 11 Ultimate

1 Open a new instance of VS11 and create a new project by clicking File ➤ New ➤ Project

Name the project “Apress.Example” and the solution “Apress.” It is common practice for the

solution and project names to be different so the hierarchy from solution to project is easily

recognized By default the “Create directory for solution” checkbox is checked, which means

that the file directory for the solution will automatically be created Within the Installed

Templates directory is a template called Modeling Projects This is the type of project you will

use to building diagrams (see Figure 1-8)

Table 1-3 Activity Diagram Symbols

Diagraming Symbols Description

Initial Node Indicates the beginning of the workflow

Activity Final Node Indicates the end of the workflow

Action A step within a workflow that is primarily used to model activity

Object Node Used to demonstrate transmission, buffering, filtering, and transformation of

objects

Comment Used for commenting on the flow of the workflow

Decision Node Indicates more than one flow driven by a decision within the workflow

Merge Node Merges more than one flow into one outgoing flow

Fork Node Divides one thread into more than one concurrent thread

Join Node Joins concurrent threads into one outgoing thread

Send Signal Action Sends a signal to another system or activity

Accept Event Action Waits for a signal or event

Call Behavior Action Action that calls another activity

Call Operation Action Action that calls an operation

Input Pin Allows data to flow into an action

Output Pin Allows data to flow out of an action

Activity Parameter Node Parameters used to push data in and out of an activity

Connector Connects the flow between activities

Trang 17

ChapTeR 1 ■ Why WoRkFloWS

2 Add a new diagram to the project by right-clicking Apress.Example.Diagramming within

the Solution Explorer Add a new diagram by clicking Add ➤ New Item Figure 1-9 shows all of the diagrams that can be added to the project Since activity diagrams are closely related to the type of workflows you will be building using WF, select UML Activity Diagram as the type of diagram to build Change the name for the new activity diagram to

“CustomerOrder” and leave the extension as activitydiagram

Figure 1-8 Creating a new modeling project

V413HAV

Trang 18

ChapTeR 1 ■ Why WoRkFloWS

Before you start building the workflow for processing a customer order, let’s walk through the logic of processing a customer’s order First, make sure the product ordered is in stock by checking the inventory

When a customer orders a product, there are two inventories that need to be checked

do so in this case because its extension is descriptive enough.)

3 Click the Initial Node symbol within the toolbox (see Figure 1-10), and then click the

canvas for the activity diagram to add it as part of the diagram

Figure 1-9 Adding a UML Activity Diagram

Trang 19

ChapTeR 1 ■ Why WoRkFloWS

4 Click the Action symbol and then click the canvas of the activity diagram to add an action

Double-click within the Action symbol so the name can be changed to “Check Store

Inventory.”

5 To connect the two symbols placed on the canvas, click the Connector symbol and then

hover the mouse over the Initial Node that was already added to the canvas While the

mouse is hovering over the Initial Node, the mouse icon will change so the connection can

be anchored Click once to anchor the connection arrow and then click the Check Store

Inventory action to add the connection

6 Follow step 4 and add two more steps to the workflow Name them “Check Warehouse

Inventory” and “Check External Supplier.” At this point the diagram should look like

Figure 1-11

Figure 1-10 Activity diagraming activities

Trang 20

ChapTeR 1 ■ Why WoRkFloWS

7 Next, add the logic that models the decisions for the workflow Click the Decision Node symbol and then click the canvas between the Check Store Inventory and Check Warehouse Inventory steps Follow the same steps to add a Decision Node between the Check Store Inventory and Check External Supplier steps

8 Logic and decisions can now be added between the existing steps by using the Connector symbols The connectors can be added quickly by clicking a Connector symbol and then clicking the step and decision that should be connected (see Figure 1-12)

Trang 21

ChapTeR 1 ■ Why WoRkFloWS

9 Descriptions for a Connector symbol can be added by clicking a connector arrow within

the workflow Add the description, “Not In Inventory” for the Connector arrow between

the Decision symbol and the Action symbol Check Warehouse Inventory This indicates

that if inventory can’t be found for a customer order, the next available inventory should

be checked

10 If there is inventory from one of the locations in the workflow, based on the order for

checking inventory, the order gets processed This type of logic can be modeled using the

Merge Node symbol Add a Merge symbol to the workflow and place it on the right side of

the workflow

11 Add connections between the existing Decision symbols and the Merge Node Add one

more Connector symbol between the Check External Supplier step and the Merge Node

symbol

12 Add the description “Inventory Exists” for each connection to the Merge Node symbol

13 Now that you have a flow for processing a customer’s order when inventory exists, add

another Action symbol to the workflow and change its name to “Process Order.” Add

another Connector symbol between the Merge Node symbol and Process Order step This

logic indicates that it is ok to process the order when the inventory exists The finished

workflow should now resemble the complete business logic represented in Figure 1-13

Trang 22

ChapTeR 1 ■ Why WoRkFloWS

Tip

■ Symbols can also be added to the workflow by right-clicking in the canvas of the workflow and selecting add

a list of symbols will appear Clicking any of them will automatically add them to the canvas.

Workflow Technology

There is much to gain when applying workflows with a software development methodology, but the real power of workflows is building software from workflows Technically workflow logic can still be done just by writing code, and sometimes simply using code is the best solution, but there are obstacles that a workflow technology like WF can help developers address

Once a software project has completed the Analysis phase and has entered the Design phase, important decisions have to be made about the technologies and architecture of the solution This is why understanding the requirements

of a project are so important Once developers understand the requirements, educated decisions can be made about the technologies that will help the project be successful and the architecture the team will use together to implement the solution

WF was built to address certain requirements that were painstakingly complicated to implement

Long-running processes can be extremely complicated and may require to be executed

continuously or within a certain schedule An example of a long-running process is ordering

something over the Internet and having the item shipped to a home address Another example is

the service maintenance required for hardware that can span over years

Trang 23

ChapTeR 1 ■ Why WoRkFloWS

• Declarative workflows allow developers to build workflows visually that perform complicated

conditional logic and actions to reduce the amount of code and the complications for how

code is implemented

Business domain activities are custom activities that are built to focus on an organization’s

proprietary business

Rules-driven logic can also be added within the workflow or even modeled in a workflow

It can be modified during runtime or while the workflow is being processed by an

application

Human automation can integrate within the workflow so humans can make decisions for

how the logic of the workflow should flow

Service-oriented architecture can be applied by building services from workflow rather

than complex code

• Workflow persistence provides the mechanism for releasing processing memory from

workflows that are idle from either waiting for events or by logic that dictates that the workflow

should go idle

• Business processes monitoring provides automation for how information is gathered and

stored, about the logic being processed, and for pertinent data being monitored

Summary

Workflows are great for modeling business processes However, to really gain value from using them, they should be applied with a methodology like business process management that helps guide the steps for modeling workflows and focuses on continuously making improvement to processes so they do not become stagnant

As developers model business processes with workflows, they come to understand requirements quicker and can thus plan architecture and write code that is efficiently designed to meet or exceed the goals of stakeholders Workflows also provide the transparency for the complicated business logic needed within software Tools like Visio and Visual Studio ease the experience of designing and documenting workflows By using a workflow technology like WF, code can be represented as business logic that is abstracted through declaratively building workflows that can be executed as code Workflows running within an application can also be consistently changed at runtime and throughout the lifespan of the business processes they model

Now that you understand why it is important to use workflows during software development, the rest of the book digs deeper into WF to show you how to gain the aforementioned benefits Using WF within applications is truly a more effective way of architecting and developing software The next chapter will focus on the components that make

up the WF

Trang 24

Chapter 2

Introducing Windows

Workflow Foundation

Before jumping into how WF is used, it is important to understand the capabilities that it provides This chapter gives

a brief introduction to WF and how it has changed over the years Important components of WF will be introduced, such as some of the out-of-box activities that model coding constructs and how activities use the workflow designer for workflow orchestration or arranging activities within a workflow for modeling business logic Next, WF data modeling will be covered; this is how workflows receive, store, and return data Each of the WF components covered

in this chapter will contribute to building a foundation of how WF works; if you’re already familiar with WF, this chapter will serve as a review of important concepts

WF establishes a software framework so developers can model code declaratively as workflows for supporting event-driven and long-running processes Although many developers consider WF to be solely a workflow engine technology because of its built-in functionality for processing workflows, it is actually a software framework That is,

it comprises a set of reusable code “building blocks” that can be assembled and extended to build custom software When a developer uses a software framework, he does not need to write software from scratch Another example

of a software framework you are probably familiar with is the Microsoft NET Framework; it contains a collection of runtime libraries that can be used to develop software that is compiled to run within the Microsoft NET runtime Just

as with any new technology, the goal for WF is to address strategic shortcomings that were difficult to meet using a

“code only” approach

As developers, we develop software by writing code However, the code itself is not an ideal reference for

understanding its functionality because it is written in a special format and uses syntax that usually only developers understand If there is a lack of standards in documenting the code, it has to be “reverse engineered,” which is the process of using code to understand what functionality it performs This makes software code difficult to maintain, depending on how many programmers were involved in developing the code and the different technologies and architectures they used

For example, with the release of ASP.NET Model View Controller (MVC), which introduced a completely different architecture compared to ASP.Net and web forms, web applications can now combine both technologies, making them harder to manage Another example is the overlapping of data access technologies like ADO.NET, LINQ to SQL, and Entity Framework It is quite common to see applications that utilize all three of these technologies, making the code very hard to manage WF provides a natural interpretation of code by representing it through transparent workflows as an alternative to just viewing code alone

Most software is developed to process information quickly Users create, read, update, and delete data through manual events and the data is immediately processed However, there are times when business processes execute over days, months, and even years These are defined as long-running processes, and implementing them through software poses unique challenges WF provides a framework (which would otherwise have to be custom built)

to address common design goals and characteristics associated with implementing long-running processes WF functionality includes memory management for persisting the current state or snapshot of a process and tracking custom events for the duration of a process

Trang 25

Chapter 2 ■ IntroduCIng WIndoWs WorkfloW foundatIon

Finally, because business processes usually change many times over the period of an application’s life span, it

is hard to make changes to the logic within an application to adapt to business process changes Traditionally, it is a good practice for developers to implement an architectural pattern called “layering” that promotes the segregation

of code into designated layers For example, code that performs data access is usually separated out into its own

“Data Access” layer Business logic is separated out into a “Business” layer By separating out related code by its functional role, managing code becomes easier because changes are isolated within the layer; this reduces the number of regression bugs WF takes the layering approach further because it layers business logic through workflows and reduces the responsibility for the application down to simply hosting the workflows so the workflow can execute The biggest gain from this architecture is that the workflows can then be managed during the runtime of the

application that is hosting the workflows

As WF has matured over the years, so has the integration of workflows and Windows Communication Services (WCF) While WCF has been making headlines for itself as the developer’s tool of choice for implementing services within Microsoft environments, Microsoft started getting creative by looking at how to combine the power of WF for declaratively building code that could run as long running processes, and providing services using WCF, that no longer had to use Internet Information Services (IIS) for hosting across greater boundaries Pretty soon developers were able to use workflows they had previously built for the logic used to power services for subscribers that could run over long periods of time In WF3.x, it was quite painful at first, but things started to get easier when implementing

WF services using NET 3.5 The next questions focused on how the services would be hosted Internet Information Services (IIS) seemed like the best solution but there were still limitations; these were eventually solved using the latest version of IIS, knownn as Windows Server AppFabric, which I will explain in more detail in another chapter.Today we see another trend emerging where industry leaders like Microsoft and Amazon provide the hardware and software infrastructure that is strategically located within geographic locations around the world, so the same infrastructure does not have to be provided locally within data centers, nor does it require leasing hardware for

running software applications This trend is called cloud computing and the advantage of subscribing to cloud

computing is that you only have to pay for the memory space for holding data and processing utilization for the software applications running within the cloud Microsoft’s cloud solution is a technology called Azure Azure

provides the infrastructure and server technology so developers can focus on what they do best, which is developing the business logic When developing for the cloud, developers no longer have to worry about setting up, configuring, and supporting servers Instead, cloud computing providers extend service level agreements (SLAs) for handling the managing the infrastructure and providing a level of uptime for the servers so developers can focus on deploying software and configuring how applications will perform and run Since cloud computing was a new concept,

most developers felt that it seemed a great place to host small applications but not intense line-of-business (LOB) applications After all, what businesses were going to allow their LOB applications to be run remotely, without the protection of a local or remote private data center?

At first, the most seasoned developers were concerned that they would have a hard time or even fail trying to move or write custom software for clients in the cloud The fear receded as Microsoft provided more resources for Azure, not only for its infrastructure but also its technology So today we can take advantage of quickly building workflows that run for long periods of time and expose them as services that are pushed out to the cloud via WCF, without first having to worry about setting up the hardware or configuring the servers used to host them

WF History

Windows Workflow Foundation made its first appearance in September of 2005 at a Microsoft-hosted event called Professional Developers Conference (PDC) It was announced as an extension of the next release of Microsoft’s

Trang 26

Chapter 2 ■ IntroduCIng WIndoWs WorkfloW foundatIon

.NET Runtime 2.0 Over the years there have been two other releases within the NET Framework: 3.0 and 3.5

We commonly refer to these releases as WF3.x Microsoft was planning for the next release of WF within the NET Framework 4.0, but they ultimately decided to do a complete planning overhaul of WF However, the retooling of WF4 was not as painful as expected On the contrary, it was much easier than originally learning WF3.x, but there was much confusion around the why Microsoft decided to do a complete rewrite for such a young technology as WF Below are the main factors that Microsoft considered important enough to rewrite in WF4:

Feedback from developers struggling with the complexity for building and hosting workflows

“acceptable” caveats around interopting WF4.0 with existing implementations of WF3.x

Many developers questioned the rewrite of WF4.0 and felt the pain for retooling from WF3.x However,

after cracking open the WF4.0 box, they quickly discovered that the WF Team did a great job in listening to the development community and built a much leaner WF for better performance gains and richer functionality for building workflow solutions, plus an easier learning curve for a better developer experience

Microsoft NET Framework 4 Platform Update 1 (KB2478063), which loads the runtime files

for the platform update

Multi-Targeting Pack (KB2495638, which loads reference assemblies and IntelliSense files for

the platform update

Design-time Package for Visual Studio 2010 SP1, which installs the other packages and

configures Visual Studio 2010 SP1 with the new targeting profiles and IntelliSense, plus it loads

state-machine activities

Trang 27

Chapter 2 ■ IntroduCIng WIndoWs WorkfloW foundatIon

Once Platform Update 1 is installed, the next time VS 2010 is opened to create a new workflow project, there will

be two new choices for frameworks that a project can be compiled against (see Figure 2-2)

Figure 2-1 Installing Platform Update 1

Figure 2-2 Configuring Platform Update 1 for a new project

Trang 28

Chapter 2 ■ IntroduCIng WIndoWs WorkfloW foundatIon

If a workflow solution already exists, after loading the workflow solution in VS2010, right-click on the solution and change the properties for the Application tab, as shown in Figure 2-3

Figure 2-3 Configuring Platform Update 1 for an existing project

The only difference between NET Framework 4 Platform Update 1 and NET Framework 4 Client Profile Platform Update 1 is the Client Profile is a smaller set of assemblies than what NET 4.0 provides, so it is much leaner when running within client applications

Once Platform Update 1 is chosen for the project to be compiled against, a new category of out-of-box activities is included for building state-machine workflows (see Figure 2-4)

Figure 2-4 State machine activities

Trang 29

Chapter 2 ■ IntroduCIng WIndoWs WorkfloW foundatIon

Now that workflows are making their way into Azure, another key feature that was released with the platform update was support for the database that handles persistence for workflows and its compatibility when running within SQL Azure SQL Azure is a relational database that runs within Azure’s cloud for storing data

Obviously, with the release of WF4.5 and the new NET Framework 4.5, this platform update is irrelevant because all the capabilities it provides are already included within WF4.5; however, I wanted to make sure it was covered as part of the complete history of WF

The WF runtime is considered the heart of WF; without the WF runtime, workflows cannot be executed The role

of the WF runtime is to schedule and coordinate workflows asynchronously or within its own process Compared

to the WF runtime in WF3.5, there are significant changes that are focused around improving the WF runtime’s performance Also, for WF3.5, the WF runtime was required to be hosted within a NET executable This changed with WF4 because it was not practical for some scenarios For instance, setting up the WF runtime within testing environments was challenging In WF4, directly calling the WF runtime for hosting workflows is no longer necessary

Workflow Hosts

There are now better options for hosting workflows, ones that are tailored around the characteristics of the solutions hosting the workflows Here is a list of some additional options for managing the WF runtime at an abstracted level

in WF4:

• WorkflowApplication: Used for hosting workflows within NET applications that take full

advantage of the workflow runtime for managing a workflow instance asynchronously

WorkflowApplication allows applications that host workflows to manage the execution like

persisting or cancelling of a workflow and subscribe to notifications on a workflow instance

lifecycle A NET application can kick off a workflow using WorkflowApplication and then

continue processing on a different thread

• WorkflowServiceHost: Used for managing endpoints and configuration for hosting workflows

as WCF services

• WorkflowInvoker: A sought-after change from the community for easily hosting workflows

synchronously, just like a call to a method Workflows can be spun up quickly and processed on

the same thread as the hosting application WorkflowInvoker is a great way to unit test activities

and workflows before they are implemented; however, it can also be used to run asynchronously

Trang 30

Chapter 2 ■ IntroduCIng WIndoWs WorkfloW foundatIon

One of the main functions that the WF runtime performs is managing a workflow’s life cycle When a

workflow is spun up within the WF runtime, it creates an instance of that workflow called a WorkflowInstance

A WorkflowInstance is a single instance of a workflow running within the WF runtime So if an e-commerce site uses

WF to process its orders, each order that is created will create a WorkflowInstance As workflow instances are created one right after the next, it is important to know the state they are in at any given time while they are being processed This is done by subscribing to events through the WF runtime as the lifecycle of the WorkflowInstance changes over time The events the WF runtime provides are shown in Table 2-1

Table 2-1 WorkflowInstance Events

WorkflowCreated Occurs when workflow instance is created

WorkflowStarted Occurs when workflow instance is started

WorkflowLoaded Occurs when workflow instance is loaded into memory

WorkflowAborted Occurs when a workflow instance is aborted

WorkflowIdled Occurs when workflow instance enters the idle state, like waiting on an external event.WorkflowUnLoaded Occurs when workflow instance is unloaded into memory

WorkflowSuspended Occurs when a workflow instance is suspended

WorkflowResumed Occurs when execution of a workflow instance is resumed following a suspension.WorkflowTerminated Occurs when workflow instance is terminated

WorkflowPersisted Occurs when the state of a workflow instance is persisted, removing it from memory.WorkflowCompleted Occurs when workflow instance is completed

Activities

WF activities are the basic unit of work and are used to execute code within a workflow Understanding the

functionality that each activity provides within WF is half the learning curve By getting to know each activity, the skill for building efficient workflows becomes easier WF4.x activities are categorized into 10 areas:

• Control Flow: Models how business processes can flow within a workflow.

• Flowchart: Provides the most transparency for modeling decision-making processes

Flowchart activities were introduced in WF4

• State-machine: Models possible transitions between the states of a workflow indicating human

interaction and events within workflows

• Messaging: Provides communication functionality for building workflows that are exposed as

services and communicate over transport protocols

• Runtime: Provides instructions to the WF runtime for how to manage workflow behavior.

• Primitives: Provides general functionality around execution.

• Transaction: Provides functionality for allowing activities to execute within a transaction so

unwanted results can be reversed

• Collection: Provides basic functionality for managing data represented as collections

within a workflow

Trang 31

Chapter 2 ■ IntroduCIng WIndoWs WorkfloW foundatIon

• Error Handling: Provides functionality for hardening workflows by providing logic for

managing unanticipated exceptions

• Migration: Provides functionality for allowing workflows built using WF3.x to execute in WF4.

Tables 2-2 through 2-11 list the activities included in each of these areas

Table 2-2 Control Flow Activities

DoWhile Keeps executing child activities until the conditional expression is met

ForEach Executes child activities for each iteration of an enumerable collection

If Executes child activities within a single branch based on a condition

Parallel Executes more than one branch of child activities at the same time asynchronously.ParallelForEach<T> Executes child activities for each iteration of an enumerable collection and processes logic

asynchronously within each iteration

Pick Used to receive events outside of a workflow and serves as the trigger for when events

occur Usually a delay is used to wait for an external event for a given time

PickBranch Branches for a Pick activity that contain a trigger for handing external events and an Action

activity for processing logic

Sequence Holds a collection of child activities that are executed sequentially

Switch Executes child activities based on a predetermined expression

While Continuously executes child activities while a condition is met

Table 2-3 Flowchart Activities

Flowchart Provide the canvas for modeling a flowchart workflow

FlowDecision Occurs when workflow instance is started

FlowSwitch<T> Executes child activities based on a predetermined expression

Table 2-4 State Machine Activities

StateMachine Provides the canvas and a default state for a state-machine workflow

State States represent the transitions that can be made within a state-machine workflow

Child activities can be added to the state activity when a state activity becomes active and when there is a transition to another state

FinalState Represents the last state for a state-machine workflow Its icon is different from the other

state’s icons, so that it how you identify it as the final state

Trang 32

Chapter 2 ■ IntroduCIng WIndoWs WorkfloW foundatIon

Table 2-5 Messaging Activities

CorrelationScope Provides correlation management for child activities Correlation is way to relate

messaging activities

InitializeCorrelation Usually correlation is established when messages are sent or received; however,

sometimes correlation needs to be established before actually sending or receiving

a message

Receive Receives incoming messages sent to a workflow

ReceiveAndSendReply Follows the same pattern as a common web service that receives an incoming

message and produces a reply that is sent back

Send Sends an outgoing message to a service

SendAndReceiveReply Correlation is used to send an outgoing message to a service and anticipates

receiving a reply from the external service

TransactionReceiveScope Allows message received to be processed within transactions

Table 2-7 Primitives Activities

Activity Description

Assign Assigns values to objects within a workflow

Delay Temporary pauses execution of a workflow based on a predetermined amount of time

InvokeMethod Allows existing code that was written outside of the workflow to be executed within a workflow.WriteLine Writes a defined string of text that is written to a console window

Table 2-8 Transaction Activities

CancellationScope Allows cancellation logic to be executed to reverse unwanted execution results

CompensableActivity Defines work that needs to be done during normal execution of logic and work that

needs to be done to compensate or reverse completed execution logic

Compensate Allows the workflow to start compensation

Confirm Allows confirmation to occur for normal or compensated work

TransactionScope Allows work that is executed within child activities to be executed within a transaction so

it can be rolled back if needed

Table 2-6 Runtime Activities

Persist Tells the WF runtime that the workflow should be persisted and removed from memory.TerminateWorkflow Tells the WF runtime that the workflow should terminate

Trang 33

Chapter 2 ■ IntroduCIng WIndoWs WorkfloW foundatIon

Table 2-10 Error Handling

Rethrow Rethrows or raises an exception that occurs within a workflow

Throw<T> Throws or raises an exception that occurs within a workflow

TryCatch Allows unanticipated exceptions to be trapped and handled

Table 2-11 Migration

Activity Description

Interop Provides a place for WF3.x child activities to execute within a workflow built in WF4

Table 2-9 Collection Activities

AddToCollection<T> Adds objects within a predefined collection

ClearToCollection<T> Clears all objects within a predefined collection

ExistsInCollection<T> Checks to see if an object is contained within a predefined collection

RemoveFromCollection<T> Removes an object contained within a predefined collection

Let’s get a little more familiar with the out-of-box activities that are most commonly used Since workflows are

a visualization tool, I included a simple visual representation for the out-of-box activities used the most for building workflows You will see that the logic patterns follow the same coding patterns used in writing code—except with

WF you can declaratively build the logic, rather than using code Therefore, there is a common pattern for each implementation of a workflow that makes managing workflows much easier than managing code Activities in WF4.5 also allow C# expressions so the expressions used within the book will focus on using C# instead of VB expressions

WriteLine Activity

The WriteLine activity works well for pushing text to readable sources like the console window to notify users of a workflows progress The WriteLine activity can also be used for debugging other activities and workflows, which will

be demonstrated while walking through some of the out-of-box activities (see Figure 2-5)

Figure 2-5 Simple WriteLine activity for displaying text

DoWhile Activity

This activity models the code statement DoWhile and has a Condition property that must use an expression resulting

in either a True or False value Expressions used in WF4 must be VB expressions, so instead of using a C# expression like 1==1, a VB expression expressed as 1=1 is required Figure 2-6 illustrates a DoWhile activity that uses

Trang 34

Chapter 2 ■ IntroduCIng WIndoWs WorkfloW foundatIon

the C# expression 1==1 While the Condition property of the DoWhile activity is met, the WriteLine activity that is contained within the DoWhile activity will write “Execute Me” to the console window as an infinite loop because 1==1 will always result in True The DoWhile activity is guaranteed to execute its child activities as least once and thereafter until the condition results to False

Figure 2-7 ForEach activity

Figure 2-6 DoWhile activity

ForEach<T> Activity

The ForEach activity models the code statement ForEach It iterates through an object that implements the interface IEnumerable and executes child activities for each iteration Figure 2-7 shows the activity iterating through a collection of customers and using the WriteLine child activity with its Text property set to

cust.FirstName for writing each customer’s FirstName to the console window The TypeArgument property defines the type of object that will hold the value for each iteration Figure 2-7 has its TypeArgument set to Customer

Trang 35

Chapter 2 ■ IntroduCIng WIndoWs WorkfloW foundatIon

If Activity

The If activity models the code statement If and uses an expression condition to decide the workflow’s flow

Figure 2-8 uses the condition 1==1, and since this will always result to True, the WriteLine child activity will write

“Condition Met” to the console window each time

Figure 2-9 Parallel activity

Figure 2-8 If activity

Parallel Activity

The Parallel activity provides a standard way of implementing a logical pattern for scheduling more than one workflow activity or more than one sequence of activities of flow to occur As long as there only synchronous activities are used within the Parallel activity, the workflow activities will be executed on the same thread as the workflow Workflow activities within a Parallel activity are scheduled to execute, and multiple activities can

be scheduled in sequence The WF runtime schedules the execution of activities within a Parallel activity, so the activities will execute in an order from left to right When a sequence of workflow activities are used within branches

of a Parallel activity, the first activity within the Sequence activity for each branch is executed from left to right and then the same pattern is used for each activity thereafter Figure 2-9 shows two WriteLine activities that will be executed, so “Execute 1” will be written first and then “Execute 2” will be written next to the console window If execution needs to stop during the execution of the Parallel activity, there is also a CompletionCondition property that accepts an expression for when the activity should stop executing

ParallelForEach<T> Activity

The ParallelForEach<T> activity models the code statement ForEach and iterates through an object that implements the interface IEnumerable and executes child activities for each iteration, except it processes each iteration asynchronously However, unless the InvokeMethod activity, messaging activities, or workflow activities that are built using the base object AsyncCodeActivity are used within the Body section of the ParallelForEach activity,

Trang 36

Chapter 2 ■ IntroduCIng WIndoWs WorkfloW foundatIon

the same thread processing the workflow will be used for processing the ParallelForEach activity This pattern is appropriate when an iteration could cause the workflow to go idle; however, iterations after it can’t wait and still need to be processed Figure 2-10 shows the workflow activity iterating through a customers collection and using one WriteLine child activity with the expression "Started " + cust.FirstName to indicate the start of an iteration

A Delay activity is used to cause the workflow to go idle and another WriteLine activity with the expression “Finished” +cust.FirstName is used to indicate to the console window when each of the iterations finishes When the Delay activity is hit and the iteration goes idle, another iteration is then executed

Figure 2-10 ParallelForEach activity

Trang 37

Chapter 2 ■ IntroduCIng WIndoWs WorkfloW foundatIon

PickBranch Activity

Additional PickBranch activities can be added to the Pick activity for handling additional external events, as illustrated in Figure 2-12

Figure 2-11 Pick activity

Figure 2-12 PickBranch activity

Sequence Activity

The Sequence activity is considered a composite activity, which means it is used as a container for holding child activities Each child activity within a Sequence activity executes in sequence and is primarily used as the base for

Trang 38

Chapter 2 ■ IntroduCIng WIndoWs WorkfloW foundatIon

sequential style of workflows The Sequence activity in Figure 2-13 has three WriteLine child activities, and each one executes in the order from top down, writing “Process 1”, “Process 2”, “Process 3” to the console

Figure 2-13 Sequence activity

Switch<T> Activity

The Switch activity models the code statement Switch and uses an object type as a prescribed condition to decide the workflow’s flow In Figure 2-14, the condition is a integer value of a CustomerType When the Case statement is matched, child activities within the Case are executed If a Case cannot be matched, there is also a Default flow that executes its child activities For example, if CustomerType=1, the WriteLine child activity will write “Executing Case 1”

to the console window If there is no match, another WriteLine activity writes “No Cases match”

Figure 2-14 Switch activity

Trang 39

Chapter 2 ■ IntroduCIng WIndoWs WorkfloW foundatIon

The Flowchart activity sets the canvas for modeling detailed decision-making flows After adding a Flowchart activity

to the workflow, it sets the stage for modeling a flowchart workflow by providing a starting point (see Figure 2-16)

Figure 2-16 Flowchart activity

FlowDecision Activity

The FlowDecision activity provides the magic for building flowchart workflows by providing a rich visualization for deciding conditional flow of a workflow After adding the Flowchart activity, an expression condition can be built that results in true or false The FlowDecision activity in Figure 2-17 shows that if the condition is false, a WriteLine activity is executed that writes “Condition is False” to the console window; if true, another WriteLine activity writes “Condition is True” to the console window When adding a FlowDecision activity, make sure to connect it to the Start activity

Trang 40

Chapter 2 ■ IntroduCIng WIndoWs WorkfloW foundatIon

FlowSwitch<T> Activity

The FlowSwitch activity is much like the Switch<T> activity; however, it represents the visual flow much better and can only be used within the canvas of flowchart workflows After adding a Flowchart activity, an object type is used

as a prescribed condition that is matched to execute a single flow If the predefined condition can’t be met, it also has

a Default flow that is executed Figure 2-18 shows that if the condition matches “0” or “1”, the WriteLine activity is executed and writes to the console window; if the condition does not match, the Default flow is executed and writes

to the console window

Figure 2-17 FlowDecision activity

Figure 2-18 FlowSwitch<T> activity

Ngày đăng: 31/03/2014, 16:43

Xem thêm

TỪ KHÓA LIÊN QUAN

w