What is windows workflow

Общие сведения о Windows Workflow Windows Workflow Overview

Рабочий процесс — это набор элементов, которые называются действиями , которые хранятся в виде модели, описывающей реальный процесс. A workflow is a set of elemental units called activities that are stored as a model that describes a real-world process. Рабочие процессы позволяют описывать порядок выполнения этапов краткосрочных и долгосрочных работ, а также зависимости между этими этапами. Workflows provide a way of describing the order of execution and dependent relationships between pieces of short- or long-running work. Работа проходит по модели от начала и до конца, а действия могут выполняться как людьми, так и системными функциями. This work passes through the model from start to finish, and activities might be executed by people or by system functions.

Среда выполнения рабочих процессов Workflow Run-time Engine

Каждый работающий экземпляр рабочего процесса создается и обслуживается внутрипроцессной подсистемой среды выполнения, с которой ведущий процесс взаимодействует с помощью одного из следующих инструментов: Every running workflow instance is created and maintained by an in-process run-time engine that the host process interacts with through one of the following:

WorkflowInvoker, который вызывает рабочий процесс как метод. A WorkflowInvoker, which invokes the workflow like a method.

WorkflowApplication для явного управления выполнением одного экземпляра рабочего процесса. A WorkflowApplication for explicit control over the execution of a single workflow instance.

WorkflowServiceHost для взаимодействия с помощью сообщений в многоэкземплярных сценариях. A WorkflowServiceHost for message-based interactions in multi-instance scenarios.

Каждый из этих классов является оболочкой для среды выполнения основной операции, представленной как объект ActivityInstance, ответственный за выполнение операции. Each of these classes wraps the core activity runtime represented as a ActivityInstance responsible for activity execution. В домене приложения может быть несколько объектов ActivityInstance, работающих параллельно. There can be several ActivityInstance objects within an application domain running concurrently.

Каждый из трех предыдущих объектов взаимодействия узлов создается из дерева операций, называемого программой рабочего процесса. Each of the preceding three host interaction objects is created from a tree of activities referred to as a workflow program. Используя эти типы или пользовательский узел, который является оболочкой ActivityInstance , рабочие процессы могут выполняться внутри любого процесса Windows, включая консольные приложения, приложения на основе форм, службы Windows, веб-сайты ASP.NET и службы Windows Communication Foundation (WCF). Using these types or a custom host that wraps ActivityInstance, workflows can be executed inside any Windows process including console applications, forms-based applications, Windows Services, ASP.NET Web sites, and Windows Communication Foundation (WCF) services.


Компоненты рабочего процесса в хост-процессе Workflow components in the host process

Взаимодействие между компонентами рабочего процесса Interaction between Workflow Components

На следующей диаграмме показано взаимодействие компонентов рабочего процесса. The following diagram demonstrates how workflow components interact with one another.

На предыдущей диаграмме используется метод Invoke класса WorkflowInvoker для вызова нескольких экземпляров рабочего процесса. In the preceding diagram, the Invoke method of the WorkflowInvoker class is used to invoke several workflow instances. WorkflowInvoker используется для упрощенных рабочих процессов, не требующих управления с сервера. Рабочие же процессы, требующие управления с сервера (например, возобновление Bookmark), должны выполняться с помощью Run. WorkflowInvoker is used for lightweight workflows that do not need management from the host; workflows that need management from the host (such as Bookmark resumption) must be executed using Run instead. Чтобы вызвать экземпляр рабочего процесса, не обязательно ждать завершения другого. Среда выполнения допускает одновременное выполнение нескольких экземпляров рабочего процесса. It isn’t required to wait for one workflow instance to complete before invoking another; the runtime engine supports running multiple workflow instances simultaneously. Вызываются следующие рабочие процессы: The workflows invoked are as follows:

Действие Sequence, содержащее дочернее действие WriteLine. A Sequence activity that contains a WriteLine child activity. Переменная Variable родительского действия привязана к InArgument дочернего действия. A Variable of the parent activity is bound to an InArgument of the child activity. Дополнительные сведения о переменных, аргументах и привязке см. в разделе переменные и аргументы. For more information about on variables, arguments, and binding, see Variables and Arguments.

Настраиваемое действие ReadLine . A custom activity called ReadLine . OutArgument действия ReadLine возвращается в вызывающий метод Invoke. An OutArgument of the ReadLine activity is returned to the calling Invoke method.

Настраиваемое действие, происходящее от абстрактного класса CodeActivity. A custom activity that derives from the CodeActivity abstract class. CodeActivity может обращаться к возможностям среды выполнения (например, к отслеживанию и свойствам) с помощью CodeActivityContext, доступного в качестве параметра метода Execute. The CodeActivity can access run-time features (such as tracking and properties) using the CodeActivityContext that is available as a parameter of the Execute method. Дополнительные сведения об этих функциях времени выполнения см. в разделе Отслеживание рабочего процесса и Свойства выполнения рабочего процесса. For more information about these run-time features, see Workflow Tracking and Tracing and Workflow Execution Properties.

Windows Workflow Foundation Windows Workflow Foundation

В этом разделе описывается модель программирования, примеры и средства Windows Workflow Foundation (WF). This section describes the programming model, samples, and tools of the Windows Workflow Foundation (WF).

в этом разделе In This Section

Руководство по документации по рабочему процессу Windows Набор предлагаемых тем для чтения, в зависимости от ваших знаний (новичков в работе) и требований. Guide to the Windows Workflow Documentation A set of suggested topics to read, depending upon your familiarity (novice to well-acquainted), and requirements.

Новые возможности Windows Workflow Foundation Обсуждаются изменения в нескольких парадигмах разработки из предыдущих версий. What’s New in Windows Workflow Foundation Discusses the changes in several development paradigms from previous versions.

Новые возможности Windows Workflow Foundation в .NET Framework 4,5 Описание новых возможностей в Windows Workflow Foundation в .NET Framework 4.6.1 .NET Framework 4.6.1 . What’s New in Windows Workflow Foundation in .NET Framework 4.5 Describes the new features in Windows Workflow Foundation in .NET Framework 4.6.1 .NET Framework 4.6.1 .

Особенности Windows Workflow Foundation компонентов Описание новых функций в Windows Workflow Foundation в .NET Framework 4. Windows Workflow Foundation Feature Specifics Describes the new features in Windows Workflow Foundation in .NET Framework 4.

Читайте также:  Как включить режим ide windows 10

Общие сведения о рабочем процессе Windows Набор разделов, в которых обсуждаются более крупные понятия Windows Workflow Foundation. Windows Workflow Conceptual Overview A set of topics that discusses the larger concepts behind Windows Workflow Foundation.

Учебник по начало работы Набор пошаговых руководств, посвященных программированию Windows Workflow Foundation приложений. Getting Started Tutorial A set of walkthrough topics that introduce you to programming Windows Workflow Foundation applications.

Windows Workflow Foundation программирование Набор разделов учебника, которые следует понимать, чтобы стать хорошо знакомым WF WF программистам. Windows Workflow Foundation Programming A set of primer topics that you should understand to become a proficient WF WF programmer.

Расширение Windows Workflow Foundation Набор разделов, в которых обсуждается расширение или Настройка Windows Workflow Foundation в соответствии со своими потребностями. Extending Windows Workflow Foundation A set of topics that discusses how to extend or customize Windows Workflow Foundation to suit your needs.

Примеры рабочих процессов Windows Содержит примеры приложений, демонстрирующие функции и сценарии WF. Windows Workflow Samples Contains sample applications that demonstrate WF features and scenarios.

Windows Workflow Overview

A workflow is a set of elemental units called activities that are stored as a model that describes a real-world process. Workflows provide a way of describing the order of execution and dependent relationships between pieces of short- or long-running work. This work passes through the model from start to finish, and activities might be executed by people or by system functions.

Workflow Run-time Engine

Every running workflow instance is created and maintained by an in-process run-time engine that the host process interacts with through one of the following:

A WorkflowInvoker, which invokes the workflow like a method.

A WorkflowApplication for explicit control over the execution of a single workflow instance.

A WorkflowServiceHost for message-based interactions in multi-instance scenarios.

Each of these classes wraps the core activity runtime represented as a ActivityInstance responsible for activity execution. There can be several ActivityInstance objects within an application domain running concurrently.

Each of the preceding three host interaction objects is created from a tree of activities referred to as a workflow program. Using these types or a custom host that wraps ActivityInstance, workflows can be executed inside any Windows process including console applications, forms-based applications, Windows Services, ASP.NET Web sites, and Windows Communication Foundation (WCF) services.


Workflow components in the host process

Interaction between Workflow Components

The following diagram demonstrates how workflow components interact with one another.

In the preceding diagram, the Invoke method of the WorkflowInvoker class is used to invoke several workflow instances. WorkflowInvoker is used for lightweight workflows that do not need management from the host; workflows that need management from the host (such as Bookmark resumption) must be executed using Run instead. It isn’t required to wait for one workflow instance to complete before invoking another; the runtime engine supports running multiple workflow instances simultaneously. The workflows invoked are as follows:

A Sequence activity that contains a WriteLine child activity. A Variable of the parent activity is bound to an InArgument of the child activity. For more information about on variables, arguments, and binding, see Variables and Arguments.

A custom activity called ReadLine . An OutArgument of the ReadLine activity is returned to the calling Invoke method.

A custom activity that derives from the CodeActivity abstract class. The CodeActivity can access run-time features (such as tracking and properties) using the CodeActivityContext that is available as a parameter of the Execute method. For more information about these run-time features, see Workflow Tracking and Tracing and Workflow Execution Properties.

Windows Workflow Foundation Programming

This section contains a set of primer topics that you should understand to become a proficient Windows Workflow Foundation (WF) programmer.

In This Section

Designing Workflows
Topics that describe the flow-control paradigms used in workflow development.

Using and Creating Activities
Topics that describes the system-provided activities available in Windows Workflow Foundation (WF).

Windows Workflow Foundation Data Model
Topics that describe variables, arguments and expressions in WF.

Waiting for Input in a Workflow
Topics that describes how to use bookmarks and messaging activities.

Exceptions, Transactions, and Compensation
Topics that describe how to use exception handlers, transactions, and compensation to handle run-time errors.

Hosting Workflows
Topics that describe the details for writing workflow host applications.

Dynamic Update
Describes how to use dynamic update to update the workflow definition of a persisted workflow instance.

Workflow Services
Topics that describe the programming model that supports writing services declaratively.

Workflow Persistence
Topics that describe the options for automatically or manually persisting workflow data and unloading workflows from memory.

Migration Guidance
Topics that describe how to migrate workflows from previous versions of Windows Workflow Foundation (WF).

Workflow Tracking and Tracing
Topics that describe workflow tracking and tracing and how these features are used for monitoring workflow applications.

Workflow Security
Discusses how to keep your workflow secure when using SQL and Windows Communication Foundation (WCF).

Windows Workflow Foundation 4 Performance
Discusses Windows Workflow Foundation 4 performance and compares it to the previous version of WF.

What’s New in Windows Workflow Foundation in .NET Framework 4.5

Windows Workflow Foundation (WF) in .NET Framework 4.5 introduces many new features, such as new activities, designer capabilities, and workflow development models. Many, but not all, of the new workflow features introduced in .NET Framework 4.5 are supported in the re-hosted workflow designer. For more information about the new features that are supported, see Support for New Workflow Foundation 4.5 Features in the Rehosted Workflow Designer. For more information about migrating .NET Framework 3.0 and .NET Framework 3.5 workflow applications to use the latest version, see Migration Guidance. This article provides an overview of the new workflow features introduced in .NET Framework 4.5.

The new Windows Workflow Foundation features introduced in .NET Framework 4.5 are not available for projects that target previous versions of the framework. If a project that targets .NET Framework 4.5 is retargeted to a previous version of the framework, several issues can occur.

  • C# expressions will be replaced in the designer with the message Value was set in XAML.
  • Many build errors will occur, including the following error.

The file format is not compatible with current targeting framework. To convert the file format, please explicitly save the file. This error message will go away after you save the file and reopen the designer.

Workflow Versioning

.NET Framework 4.5 introduced several new versioning features based around the new WorkflowIdentity class. WorkflowIdentity provides workflow application authors a mechanism for mapping a persisted workflow instance with its definition.

Developers using WorkflowApplication hosting can use WorkflowIdentity to enable hosting multiple versions of a workflow side-by-side. Persisted workflow instances can be loaded using the new WorkflowApplicationInstance class, and then the DefinitionIdentity can be used by the host to provide the correct version of the workflow definition when instantiating the WorkflowApplication. For more information, see Using WorkflowIdentity and Versioning and How to: Host Multiple Versions of a Workflow Side-by-Side.

Читайте также:  File windows system32 config system error code 0xc000014c

WorkflowServiceHost is now a multi-version host. When a new version of a workflow service is deployed, new instances are created using the new service, but existing instances complete using the previous version. For more information, see Side by Side Versioning in WorkflowServiceHost.

Dynamic update is introduced which provides a mechanism for updating the definition of a persisted workflow instance. For more information, see Dynamic Update and How to: Update the Definition of a Running Workflow Instance.

A SqlWorkflowInstanceStoreSchemaUpgrade.sql database script is provided to upgrade persistence databases created using the .NET Framework 4 database scripts. This script updates .NET Framework 4 persistence databases to support the new versioning capabilities introduced in .NET Framework 4.5. The persisted workflow instances in the database are given default versioning values, and can participate in side-by-side execution and dynamic update. For more information, see Upgrading .NET Framework 4 Persistence Databases to Support Workflow Versioning.

Activities

The built-in activity library contains new activities and new features for existing activities.

NoPersist Scope

NoPersistScope is a new container activity that prevents a workflow from being persisted when the NoPersistScope’s child activities are executing. This is useful in scenarios where it is not appropriate for the workflow to be persisted, such as when the workflow is using machine-specific resources such as file handles, or during database transactions. Previously, to prevent persistence from occurring during an activity’s execution, a custom NativeActivity that used a NoPersistHandle was required.

New Flowchart Capabilities

Flowcharts are updated for .NET Framework 4.5 and have the following new capabilities:

The DisplayName property of a FlowSwitch or FlowDecision activity is editable. This will let the activity designer show more information about the activity’s purpose.

Flowcharts have a new property called ValidateUnconnectedNodes; the default for this property is False . If this property is set to True , then unconnected flowchart nodes will produce validation errors.

Support for Partial Trust

Workflows in .NET Framework 4 required a fully trusted application domain. In .NET Framework 4.5, workflows can operate in a partial trust environment. In a partial trust environment, third-party components can be used without granting them full access to the resources of the host. Some concerns about running workflows in partial trust are as follows:

Using legacy components (including Rules) contained in the Interop activity is not supported under partial trust.

Running workflows in partial trust in WorkflowServiceHost is not supported.

Persisting exceptions in a partial-trust scenario is a potential security threat. To disable persisting of exceptions, an extension of type ExceptionPersistenceExtension must be added to the project in order to opt out of persisting exceptions. The following code example demonstrates how to implement this type.

If exceptions are not to be serialized, ensure that exceptions are used within a NoPersistScope.

Activity authors should override CacheMetadata to avoid having the workflow runtime automatically execute reflection against the type. Arguments and child activities must be non-null, and Bind must be called explicitly. For more information on overriding CacheMetadata, see Exposing data with CacheMetadata. Also, instances of arguments that are of a type that is internal or private must be explicitly created in CacheMetadata to avoid being created by reflection.

Types will not use ISerializable or SerializableAttribute for serialization; types that are to be serialized must support DataContractSerializer.

Expressions cannot be compiled using TextExpressionCompiler or the Visual Basic hosted compiler in partial trust, but previously compiled expressions can be run.

A single assembly that uses Level 2 Transparency cannot be used in .NET Framework 4, .NET Framework 4.6.1 in full trust, and .NET Framework 4.6.1 in partial trust.

New Designer Capabilities

To make larger workflows more manageable, workflows can now be searched by keyword. This feature is only available in Visual Studio; this feature is not available in a rehosted designer. There are two kinds of searches available:

Quick Find, initiated with either Ctrl+F or Edit, Find and Replace, Quick Find.

Find in Files, initiated with either Ctrl+Shift+F or Edit, Find and Replace, Find in Files.

Note that Replace is not supported.

Quick Find

Keywords searched in workflows will match the following designer items:

Properties of Activity objects, FlowNode objects, State objects, Transition objects, and other custom flow-control items.

Quick Find is performed on the designer’s ModelItem tree. Quick Find will not locate namespaces imported in the workflow definition.

Find in Files

Keywords searched in workflows will match the actual content of the workflow files. The search results will be shown in Visual Studio Find Results view pane. Double-clicking the result item will navigate to the activity which contains the match in workflow designer.

Delete context menu item in variable and argument designer

In .NET Framework 4, variables and arguments could only be deleted in the designer using the keyboard. Starting with .NET Framework 4.5, variables and arguments can be deleted using the context menu.

The following screenshot shows the variable and argument designer context menu.

Auto-surround with Sequence

Since a workflow or certain container activities (such as NoPersistScope) can only contain a single body activity, adding a second activity required the developer to delete the first activity, add a Sequence activity, and then add both activities to the sequence activity. Starting with .NET Framework 4.5, when adding a second activity to the designer surface, a Sequence activity will be automatically created to wrap both activities.

The following screenshot shows a WriteLine activity in the Body of a NoPersistScope .

The following screenshot shows the automatically created Sequence activity in the Body when a second WriteLine is dropped below the first.

Pan Mode

To more easily navigate a large workflow in the designer, pan mode can be enabled, allowing the developer to click and drag to move the visible portion of the workflow, rather than needing to use the scroll bars. The button to activate pan mode is in the lower right corner of the designer.

The following screenshot shows the pan button which is located at the bottom right corner of the workflow designer.

The middle mouse button or space bar can also be used to pan the workflow designer.

Multi-select

Multiple activities can be selected at one time, either by dragging a rectangle around them (when pan mode is not enabled), or by holding down Ctrl and click the desired activities one by one.

Multiple activity selections can also be dragged and dropped within the designer, and can also be interacted with using the context menu.

Outline view of workflow items

In order to make hierarchical workflows easier to navigate, components of a workflow are shown in a tree-style outline view. The outline view is displayed in the Document Outline view. To open this view, from the top menu, select View, Other Windows, Document Outline, or press Ctrl W,U. Clicking on a node in outline view will navigate to the corresponding activity in the workflow designer, and the outline view will be updated to show activities that are selected in the designer.

Читайте также:  Internet explorer для windows 10 x64 rus

The following screenshot of the completed workflow from the Getting Started Tutorial shows the outline view with a sequential workflow.

C# Expressions

Prior to .NET Framework 4.5, all expressions in workflows could only be written in Visual Basic. In .NET Framework 4.5, Visual Basic expressions are only used for projects created using Visual Basic. Visual C# projects now use C# for expressions. A fully functional C# expression editor is provided which capabilities such as grammar highlighting and intellisense. C# workflow projects created in previous versions that use Visual Basic expressions will continue to work.

C# expressions are validated at design-time. Errors in C# expressions will be marked with a red wavy underline.

For more information about C# expressions, see C# Expressions.

More control of visibility of shell bar and header items

In a rehosted designer, some of the standard UI controls may not have meaning for a given workflow, and may be turned off. In .NET Framework 4, this customization is only supported by the shell bar at the bottom of the designer. In .NET Framework 4.5, the visibility of shell header items at the top of the designer can be adjusted by setting WorkflowShellHeaderItemsVisibility with the appropriate ShellHeaderItemsVisibility value.

Auto-connect and auto-insert in Flowchart and State Machine workflows

In .NET Framework 4, connections between nodes in a Flowchart workflow had to be added manually. In .NET Framework 4.5, Flowchart and State Machine nodes have auto-connect points that become visible when an activity is dragged from the toolbox onto the designer surface. Dropping an activity on one of these points automatically adds the activity along with the necessary connection.

The following screenshot shows the attachment points that become visible when an activity is dragged from the toolbox.

Activities can also be dragged onto connections between flowchart nodes and states to auto-insert the node between two other nodes. The following screenshot shows the highlighted connecting line where activities can be dragged from the toolbox and dropped.

Designer Annotations

To facilitate developing larger workflows, the designer now supports adding annotations to help keep track of the design process. Annotation can be added to activities, states, flowchart nodes, variables and arguments. The following screenshot shows the context menu used to add annotations to the designer.

Debugging states

In .NET Framework 4, non-activity elements could not support debug breakpoints since they were not units of execution. This release provides a mechanism for adding breakpoints to State objects. When a breakpoint is set on a State, execution will break when the state is transitioned to, before its entry activities or triggers are scheduled.

Define and consume ActivityDelegate objects in the designer

Activities in .NET Framework 4 used ActivityDelegate objects to expose execution points where other parts of the workflow could interact with a workflow’s execution, but using these execution points usually required a fair amount of code. In this release, developers can define and consume activity delegates using the workflow designer. For more information, see How to: Define and consume activity delegates in the Workflow Designer.

Build-time validation

In .NET Framework 4, workflow validation errors weren’t counted as build errors during the build of a workflow project. This meant that building a workflow project could succeed even when there were workflow validation errors. In .NET Framework 4.5, workflow validation errors cause the build to fail.

Design-time background validation

In .NET Framework 4, workflows were validated as a foreground process, which could potentially block the UI during complex or time-consuming validation processes. Workflow validation now takes place on a background thread, so that the UI is not blocked.

View state located in a separate location in XAML files

In .NET Framework 4, the view state information for a workflow is stored across the XAML file in many different locations. This is inconvenient for developers who want to read XAML directly, or write code to remove the view state information. In .NET Framework 4.5, the view state information in the XAML file is serialized as a separate element in the XAML file. Developers can easily locate and edit the view state information of an activity, or remove the view state altogether.

Expression extensibility

In .NET Framework 4.5, we provide a way for developers to create their own expression and expression authoring experience that can be plugged into the workflow designer.

Opt-in for Workflow 4.5 features in rehosted designer

To preserve backward compatibility, some new features included in .NET Framework 4.5 are not enabled by default in the rehosted designer. This is to ensure that existing applications that use the rehosted designer are not broken by updating to the latest version. To enable new features in the rehosted designer, either set TargetFrameworkName to «.NET Framework 4.5», or set individual members of DesignerConfigurationService to enable individual features.

New Workflow Development Models

In addition to flowchart and sequential workflow development models, this release includes State Machine workflows, and contract-first workflow services.

State machine workflows

State machine workflows were introduced as part of the .NET Framework 4, version 4.0.1 in the Microsoft .NET Framework 4 Platform Update 1. This update included several new classes and activities which allowed developers to create state machine workflows. These classes and activities have been updated for .NET Framework 4.5. Updates include:

The ability to set breakpoints on states

The ability to copy and paste transitions in the workflow designer

Designer support for shared trigger transition creation

Activities used to create State Machine workflows, including: StateMachine, State, and Transition

The following screenshot shows the completed state machine workflow from the Getting Started Tutorial step How to: Create a State Machine Workflow.

For more information on creating state machine workflows, see State Machine Workflows.

Contract-first workflow development

The contract-first workflow development tool allows the developer to design a contract in code first, then, with a few clicks in Visual Studio, automatically generate an activity template in the toolbox representing each operation. These activities are then used to create a workflow that implements the operations defined by the contract. The workflow designer will validate the workflow service to ensure that these operations are implemented and the signature of the workflow matches the contract signature. The developer can also associate a workflow service with a collection of implemented contracts. For more information on contract-first workflow service development, see How to: Create a workflow service that consumes an existing service contract.

Оцените статью