Базовое понимание
Помню, еще в университете перед реализацией любого алгоритма мы описывали его в виде блок схемы, и только после этого переходили непосредственно к кодированию. Workflow, как одна из парадигм программирования, на ряду с процедурным и объектно ориентированным подходами, как раз и позволяет нам визуально реализовать любой процесс, используя набор предопределенных функциональных блоков (Activity), при этом, избавляя от его последующего кодирования.
Библиотека WF, являясь одной из реализаций парадигмы Workflow, предоставляет следующие основные возможности:
— богатый набор функциональных блоков;
— расширение набора стандартных функциональных блоков пользовательскими;
— сохранение и возобновление экземпляров Workflow в процессе их исполнения;
— использование Workflow дизайнера в вашем приложении;
— интеграция с WCF;
— пошаговая диагностика непосредственно в Workflow дизайнере;
— и многое другое.
Критерии применения
Как известно, каждой технологии своя область применения. Для определения необходимости использования WF при реализации конкретного алгоритма/процесса я применяю 3 критерия:
1. Реализация алгоритма/процесса постоянно меняется.
В нашей компании мы разработали подсистему Workflow, которая является ядром всех продуктов. Имея, к примеру, десятки клиентов наших продуктов, у которых десятки процессов, получаем сотни разных изменяющихся процессов.
2. Процесс/алгоритм имеет длительный срок выполнения.
В наших продуктах жизненный цикл процессов исчисляется днями и неделями. При этом, в случае сбоя или перегрузки сервера, процессы должны корректно возобновить и продолжить выполнение.
3. Нужно предоставить возможность изменения алгоритма/процесса конечному пользователю без вмешательства программиста.
Мы разработали свой собственный дизайнер, чтобы максимально упростить и облегчить редактирование процессов конечному пользователю (бизнес-аналитику). Это позволяет снять нагрузку с разработчиков. А возможность видеть и самим с легкостью менять свои процессы очень привлекательна для клиентов.
Таким образом, если актуально хотя бы одно из выше перечисленных требований, следует рассмотреть WF как возможный вариант реализации алгоритма/процесса.
Ознакомительный пример
В качестве ознакомительного примера использования WF я как раз и реализую Workflow процесс, который ответит на вопрос о целесообразности использования WF.
1. Создаю новый проект IsWWFUsefullSample используя шаблон Blank Solution:
2. Добавляю новый проект IsWWFUsefullSample.Activities используя шаблон Activity Designer Library:
3. Удаляю сущеcтвующий файл ActivityDesigner1.xaml и добавляю новый элемент используя шаблон Activity:
4. Открываю Activity в дизайнере и добавляю необходимые параметры типа Boolean:
— три входящих параметра соответствующих нашим критериям: IsLongRunning, IsChangeable, IsDesignerNecessary;
— один исходящий параметр для возврата результата: Result.
Стоит упомянуть, что на данный момент для описания выражений и типов внутри Workflow Activity можно использовать только синтаксис VB.Net. Обещают добавить поддержку С#.
5. Для анализа входящих праметров использую три вложенных If Activities (Toolbox -> Control Flow -> If), хотя конечно можно обойтись и одним. Для присвоения результата использую Assign Activity (Toolbox -> Primitives -> Assign). В итоге получается следующий алгоритм:
6. Workflow процесс готов. Для его использования добавляю новое приложение IsWWFUsefullSample.TestClient на основании шаблона Workflow Console Application:
7. Удаляю файл Workflow1.xaml.
8. Добавляю ссылку на проект IsWWFUsefullSample.Activities.
9. Реализую Main метод. Он предлагает пользователю ответить на три вопроса, запускает процесс Workflow с полученными исходными данными и выводит результат вычисления.
// ==============================================================
// <copyright file="Program.cs" company="The World as a Workflow">
// Copyright (c) The World as a Workflow. All rights reserved.
// </copyright>
// <author>Alexander Nechyporenko</author>
// <date>2011-07-12</date>
// ==============================================================
namespace IsWWFUsefullSample.TestClient
{
using System;
using System.Activities;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IsWWFUsefullSample.Activities;
/// <summary>
/// Console program class.
/// </summary>
public class Program
{
/// <summary>
/// Program starting point.
/// </summary>
/// <param name="args">Program parameters.</param>
public static void Main(string[] args)
{
// Question answers
const string Yes = "yes";
const string No = "no";
var answers = new List<string> { Yes, No };
// Create new activity instance
var activity = new IsWWFUsefull();
var parameters = new Dictionary<string, object>();
do
{
Console.WriteLine("Please, answer following questions to determine necessity of using WWF.");
Console.WriteLine();
// Read activity input parameters
parameters["IsLongRunning"] = ReadAnswer("Is process/algorithm long running?", answers) == Yes;
parameters["IsChangeable"] = ReadAnswer("Is process/algorithm frequently changed?", answers) == Yes;
parameters["IsDesignerNecessary"] =
ReadAnswer("Do you need a visual designer for your process/algorithm?", answers) == Yes;
// Execute activity
var result = WorkflowInvoker.Invoke(activity, parameters);
// Show result
Console.WriteLine();
if ((bool)result["Result"])
{
Console.WriteLine("Use WWF!");
}
else
{
Console.WriteLine("You don't need WWF but still can use it if you like it :).");
}
Console.WriteLine("---------------------------------------------------------------------");
Console.WriteLine();
}
while (ReadAnswer("Do you want to proceed?", answers) == Yes);
return;
}
/// <summary>
/// Read answer from console.
/// </summary>
/// <param name="question">Question text.</param>
/// <param name="answers">A list of posible</param>
/// <returns>Answer text.</returns>
private static string ReadAnswer(string question, IList<string> answers)
{
// Prepare answers prompting string
var answersString = new StringBuilder();
for (var i = 0; i < answers.Count; i++)
{
answersString.AppendFormat(i == 0 ? "{0}" : "/{0}", answers[i]);
}
// Read and validate the answer
var text = string.Empty;
var answer = string.Empty;
do
{
if (!string.IsNullOrEmpty(text))
{
Console.WriteLine(
string.Format("'{0}' doesn't belong to list of posible answers: '{1}'.", text, answersString));
}
Console.Write(string.Format("{0} ({1}): ", question, answersString));
text = Console.ReadLine();
answer = answers.Where(a => a == text.ToLower()).FirstOrDefault();
}
while (answer == null);
return answer;
}
}
}
10. Запускаю и тестирую приложение:
Исходники проекта можно загрузить здесь.
Всем удачных архитектурных решений и приятного кодирования!
This subsystem is a part of .NET Framework 3.0
Windows Workflow Foundation (WF) is a Microsoft technology for defining, executing, and managing workflows. This technology was first released in November 2006 as a part of .NET Framework 3.0. The current version (4.0) was released as part of .NET Framework 4.0. The major refinement of the new version is the tighter integration of WF with Windows Communication Foundation.
A workflow based program is like traditional programs that allow you to coordinate work and perform operations but has some important differences:
- Workflows use a declarative model (see Declarative programming) of writing programs by linking together pre-defined activities rather than an imperative programming model of writing each line of code
- Workflows can handle long-running work by persisting themselves to a durable store, such as a database, when idle and loading again once there is work to be performed
- Workflows can be modified dynamically while running when new conditions require a workflow to behave differently than when it was created
- Workflows provide a distinct separation of business rules and host application code making it easier to modify the business rules
- Workflows support sequential workflows for systems with sequential logic and state machine workflows for systems with event-based logic
- Workflows usually have a visual counterpart that allows a flowchart-like description of their logic
Microsoft has indicated that WF is going to be a cornerstone of their future Service Oriented Architecture platform announced in October 2007 with the codename Oslo.
There are two types of workflow, «Sequential» and «State Machine» Template:Vague. A Sequential workflow runs from beginning to end, with the workflow engine initiating each step. A State Machine workflow is driven by external events and user interaction, and simply constrains or interacts with those events, so it stores state between events. Both types can have branches and loops.
The .NET Framework 4.0 introduces a significant amount of change from the previous versions.
[]
Workflows are defined in XAML, but are usually edited graphically in Visual Studio. However, the workflow may also be expressed in code using any .NET-targeted language (VB.NET, C#, C++/CLI, etc.).
WF provides .NET developers with the ability to separate the business logic of their application from the underlying execution components. This provides a clearer and more manageable representation of an application. This approach lends credence to the growing process-driven application methodology which aims to separate an application’s logical flow from its executable components at an enterprise level.
Each workflow consists of one or more activities that each perform a separate and discrete piece of logic. Developers can write their own custom activities and then use them in workflows. WF also provides a set of general-purpose activities that cover several control flow constructs such as if-else logic, parallel processing, looping logic, etc.
Windows Workflow Foundation is supported by a companion set of extensions to Visual Studio 2005. These extensions contain a visual workflow designer which allows users to design workflows, a visual debugger which enables the users to debug the workflow designed, and a project system which enables the user to compile their workflows inside Visual Studio 2005. In Visual Studio 2008 the WF functionality is included without any extensions to install.
Moving data through Workflows[]
Activities that require or provide data can use properties to access or set this data. This is performed by binding the properties to a dependency property on a per activity basis.
The WF Runtime[]
Starting with .NET Framework 3.0 a WF Runtime is provided that includes common facilities for running and managing the workflows, providing feedback on the progress of workflow execution, and hosting individual workflow instances.
The WF Runtime can be hosted in any CLR application domain, be it a Windows Service, a Console, GUI or Web Application.
WF Runtime Services[]
The Workflow Runtime provides the ability to register services to be run inside it. The WF Runtime provides a set of core services that handle thread scheduling, persistence, transaction handling, queueing, and tracking. All of these except for the queueing service can be overridden.
Microsoft provides built-in persistence and tracking services. Both of these will write to a SQL Server database.
WF Runtime Local Services[]
The Workflow Runtime allows user-created services to be run inside it; these are called local services. A local service can serve just about any purpose, such as providing runtime communication between the workflow instance and the host application, which is the most commonly used purpose.
Every local service is implemented as a C# interface that is decorated with the ExternalDataExchange
attribute.
Calling a local service is a multi-step process:
- First use the
GetService
function to retrieve a reference to the local service. - Next use the
CallExternalMethodActivity
activity to call the local service.
Communicating with Workflows[]
WF provides several ways to communicate with a running instance of a Workflow:
- A Windows Communication Foundation approach to workflow communication was added in .NET Framework 3.5. This functionality comes in the form of two activities, SendActivity and ReceiveActivity, which send and receive WCF messages respectively. Workflows which include a ReceiveActivity expose a selected interface method as a WCF service. This could allow external code to, for example, make a Web Services call to a running workflow instance. The WF Runtime provides infrastructure to ensure that if a WCF call is made to a workflow instance that is in a persisted state (i.e. waiting for some external event like a WCF call or a timer event), then the instance will be reloaded into memory so that the message can be delivered to the workflow instance. Workflows which include a SendActivity are able to call external services via WCF.
- When a workflow instance is created, the host application can provide arguments as Dictionary objects. These objects can be treated as both an input and an output to the workflow.
- WF also allows the workflow to update the host application through the WF Runtime of the progress of the workflow’s execution. This is done by raising events in the WF Runtime to which the host application will subscribe. This includes the starting and ending of each workflow instance or moving into an idle or persisted state.
Types of Workflows[]
Using the WF foundation, three different types of Workflow can be created:
- Sequential Workflow (Typically Flow Chart based, progresses from one stage to next and does not step back)
- State Machine Workflow (Progress from ‘State’ to ‘State’, these workflows are more complex and return to a previous point if required)
- Rules-driven Workflow (Implemented based on Sequential/StateMachine workflow. The rules dictate the progress of the workflow)
Products Using Workflow Foundation[]
- Microsoft Office SharePoint Server from the 2007 release. Versions prior to 2007 did not use WF.
- Microsoft Speech Server from the 2007 release. Versions prior to 2007 did not use WF.
- Microsoft Dynamics CRM from the 4.0 release. Versions prior to 4.0 did not use WF.
- Microsoft Dynamics AX from the 2009 release. Versions prior to 2009 did not use WF.
- Laserfiche Workflow from the Laserfiche Workflow 8.0 release.
- PowerWF — converts PowerShell Scripts into workflows, and vice-versa. Built in support for PowerShell v1.0 and v2.0 and VMWare PowerCLI.
- Team Build from the 2010 release, for the definition of build processes
- FRENDS Iron — Hosts, schedules, monitors and manages Window Workflows
- JAMS Scheduler Designs, schedules, and monitors Windows Workflows.
[]
- empty workflow project
- sequential workflow library
- sharepoint 2007 state machine workflow
- state machine workflow library
- sequential workflow console application
- sharepoint 2007 sequential workflow
- state machine workflow console application
- WorkFlow activity library
- Activities like(Delay Activity)
Books[]
- Dharma Shukla, Bob Schmidt: Essential Windows Workflow Foundation, Addison-Wesley Professional, 13 October 2006, ISBN 0-321-39983-8
- Michael Stiefel: Building Applications with Windows Workflow Foundation (WF): Basics of Windows Workflow Foundation (Digital Short Cut), June 5, 2007, Kindle, ISBN 0-321-51454-8
- Brian Noyes: Developing Applications with Windows Workflow Foundation (WF) (Video Training), June 7, 2007, Brian Noyes, ISBN 0-321-50313-9
- Brian R. Myers: Foundations of WF, Apress, 23 October 2006, ISBN 1-59059-718-4
- Bruce Bukovics: Pro WF: Windows Workflow in .NET 3.0, Apress, 19 February 2007, ISBN 1-59059-778-8
- Todd Kitta: Professional Windows Workflow Foundation, Wrox, 12 March 2007, ISBN 0-470-05386-0
- Kenn Scribner: Microsoft Windows Workflow Foundation Step by Step, Microsoft Press, 28 February 2007, ISBN 0-7356-2335-X
Localised links[]
- Hands On Lab: Introduction To WF4
- MSDN Library: Windows Workflow Foundation
- Workflow Foundation blog Template:Sv
- A Developer’s Introduction to Windows Workflow Foundation (WF4) in .NET 4 Beta 1
- REDIRECT Template:.NET
Microsoft APIs and frameworks |
|
---|---|
Graphics |
|
Audio |
|
Multimedia |
|
Web |
|
Data access |
|
Networking |
|
Communication |
|
Administration and |
|
Component model |
|
Libraries |
|
Device drivers |
|
Security |
|
.NET |
|
Software factories |
|
IPC |
|
Accessibility |
|
Text and multilingual |
|
ko:윈도 워크플로 파운데이션
ja:Windows Workflow Foundation
sv:Windows Workflow Foundation
tr:Windows Workflow Foundation
How can Uninstall Microsoft Windows Workflow Foundation Completely from Computer
Microsoft Windows Workflow Foundation removal has been a tough problem on your PC? Do you need an effective way to uninstall Microsoft Windows Workflow Foundation quickly with simple steps? Don’t worry, you will be able to solve the problem via the following removing instructions of the program.
Get Bloatware Uninstaller Now
Microsoft Windows Workflow Foundation may be great in providing its specific function for the users, but it also can turn out to be a problem when the program get some running issues or you don’t want to keep it on your computer any more. In this case, removing Microsoft Windows Workflow Foundation will be the common and also effective means to resolve the problem, and the real difficulty just come out when people try to uninstall Microsoft Windows Workflow Foundation from their PCs.
What usually make people to remove Microsoft Windows Workflow Foundation
- Microsoft Windows Workflow Foundation is not compatible with other installed applications
- Program gets a corrupted issue unexpectedly
- Microsoft Windows Workflow Foundation is not as good as the user expected, and need to be erased from the computer
- Microsoft Windows Workflow Foundation should be uninstalled first and reinstalled on the PC
- The application is regarded by the user and some websites as a suspect malware
Most common problems of removing the software
- Microsoft Windows Workflow Foundation program is not available on the Windows uninstall panel
- Microsoft Windows Workflow Foundation can’t be removed from the Windows and always receive a notification
- Nothing happen when click on the uninstall button on Windows
- Microsoft Windows Workflow Foundation or the related process still keep running on the computer after removing it
- Some files and traces of the program still can be found
- Removing process running for a long time and does not come to the end
If must be a headache if encountering such a problem on the computer, and there are still many other problems people might come across when perform the program removal on their own computers. Therefore, you should know the right way about how to uninstall Microsoft Windows Workflow Foundation from PC, or the way to fix/avoid the removing issue on the computer. Here are just several options that can support you to remove the application well.
How can uninstall Microsoft Windows Workflow Foundation well on PC? Check these guides
Option 1: Use the product’s uninstall tool
There are many applications in nowadays provides an uninstall process on the program’s installation folder, or the publisher gets an uninstaller which is specifically used to remove its own products. To remove Microsoft Windows Workflow Foundation in this way, please refer to the following uninstall instructions:
- 1. Right-click on Microsoft Windows Workflow Foundation icon on the desktop, and select «Open file location»
- 2. Scroll down the list of files and find the uninstall process, usually named «uninst000», «Uninstall», or «Uninstaller»
- 3. Double click on the uninstall process to start the removal
- 4. Follow the uninstall wizard to finish the removal, and restart your computer
- 5. Open the directory of the installation folder again, and make sure everything has been cleared well
- 6. Click on the Windows button on the bottom-left-corner, and enter «regedit» on the search box
-
- 7. Click to open «regedit» or Registry Editor on the search result
-
- 8. Unfold the registry group inside, and find out those registry keys or entries which contains the program’s name
- 9. Back up these files, and then remove them from your computer system
Note: once problems occur after deleting the registry, please restore the back-up registry to Registry Editor.
When using the publisher’s uninstaller, you should download and install the uninstall application additionally, and choose to uninstall Microsoft Windows Workflow Foundation from its interface. Similar to the above removal, you should restart your computer after finish the uninstall process, and clear its remnants again which are still staying on the PC.
Things you need to know about Registry Editor
Registry Editor is a place that stores many important registry keys and entries which closely related to the system operation and program’s performance on the computer, removing a wrong file inside usually cause serious problem for the system, so you should be very careful when you have to manually delete some registries inside.
Get Bloatware Uninstaller Now
Option 2:Remove it with Windows uninstall feature
Windows system provide an uninstall feature in Control Panel that support the user to remove unwanted program on the PC, to access this applet in different operating system, you can follow these instructions:
- 1. Open the uninstall panel on Windows system
- 2. Select Microsoft Windows Workflow Foundation on the programs list, click on Remove/Uninstall button
-
- 3. Confirm the program removal, and complete the removing steps with guides
- 4. When finish, reboot the computer
- 5. The same to the removing steps in Option 1, you should clear the leftovers in the installation folder as well as Registry Editor
Option 3:Uninstall Microsoft Windows Workflow Foundation with Bloatware Uninstaller
If you want to totally avoid the risky manual removal of registry, and handle Microsoft Windows Workflow Foundation uninstall more easily and quickly, taking a professional uninstall tool will be a great help for you, because it can count all of the files (including registry keys and temporary files) and provide a complete and automatic removal, thus, many risky and annoying manual steps could be skipped can you can totally remove Microsoft Windows Workflow Foundation on the PC more quickly.
Bloatware Uninstaller is an advanced uninstall utility that can give a good example about how uninstall Microsoft Windows Workflow Foundation well:
- 1. Install and launch the uninstaller on PC
- 2. Find and select Microsoft Windows Workflow Foundation from the programs list, and click on Scan button
-
- 3. When all of files being detected, click on the uninstall or remove button
-
- 4. Follow the uninstall wizard to remove all of components from the computer
-
- 5. Exit the uninstaller when finish, and reboot the computer system
Get Bloatware Uninstaller Now
This is a very effective way to uninstall Microsoft Windows Workflow Foundation and other applications, while the manual removal usually resulted in an unsuccessful removal, and the most important point is it is much easier for the common user to take and get rid of the program they want. So it is currently the best way we found and would like to recommend you to remove unneeded programs with a good app uninstaller.
Мы продолжаем знакомство с технологиями Visual Studio 2005 и Windows Vista. Сегодня речь пойдет еще об одном нововведении, претендующем на революционность, – это Windows Workflow Foundation (WWF).
Вячеслав Колдовский
koldovsky@mail.ru
Мы продолжаем знакомство с технологиями Visual Studio
2005 и Windows Vista. Сегодня речь пойдет еще об одном нововведении,
претендующем на революционность, – это Windows Workflow Foundation (WWF).
Полная реализация WWF планируется в следующем поколении среды .NET
Framework – WinFX, которая положена в основу Windows Vista, однако она
будет доступна и для нынешних операционных систем Microsoft. Текущая
бета-версия WWF (msdn.microsoft.com/windowsvista/building/workflow)
предназначена для использования с Visual Studio 2005.
После написания первой программы «Hello, world!» в дальнейшем
обучении будущих разработчиков обычно применяются блок-схемы, которые
очень наглядно отображают логику программ. Но, к сожалению, блок-схемы
исчезают сразу после того, как усвоены циклы и условные переходы. А ведь
сложные программные конструкции напрочь лишены наглядности, что
порождает множество проблем, с которыми вынуждены бороться все участники
процесса создания ПО.
Существует, конечно, множество инструментов и методик, поддерживающих
«визуализацией» различные этапы разработки, – от конструкторов кода до
UML и RAD-сред, даже не предполагающих программирования. Но большинство
из них не являются столь простыми и наглядными, как обычные блок-схемы.
Нередко, однако, возвращение к старым идеям на более современном уровне
дает весьма интересные результаты.
Так, среди значительного числа других нововведений WinFX Microsoft
предлагает и свой взгляд на то, каким образом визуальная разработка на
основе блок-схем может быть использована при создании приложений. Для
этих целей рекомендуется применять некую интерпретацию понятия «workflow»,
реализованную в WWF.
Определимся с терминологией
Термин «workflow» достаточно распространен в IT-индустрии и
воспринимается прежде всего в контексте систем электронного
документооборота. Однако, как это часто происходит в том случае, когда
вначале формируется рынок, а лишь потом согласовывается терминология,
существует несколько различных толкований данного понятия, каждое из
которых имеет определенное право на существование. Здесь мы не будем их
анализировать, поскольку, как это станет ясно ниже, в случае WWF в
«workflow» вкладывается смысл, несколько отличающийся от принятого в
бизнес-системах.
В наиболее широком понимании термин workflow означает упорядоченную
последовательность действий (или работ), призванных решать какую-либо
задачу. В такой трактовке достаточно прозрачно определена суть понятия,
однако нет даже намека на ту форму, в которой оно предстанет перед
потребителем. Здесь мы вполне можем принять точку зрения, наверное,
самой авторитетной в данной области международной организации Workflow
Management Coalition (WfMC, wfmc.org). Не вдаваясь в нюансы, отметим,
что WfMC предусматривает ряд требований к workflow-системам, включая
наличие специального инструментария для определения моделей процессов,
«движка», который будет их исполнять, средств для мониторинга,
управления и составления отчетности.
При этом, как правило, подразумевается, что инструментарий
workflow-моделирования обладает возможностями визуального
проектирования, достаточными для создания сложных бизнес-систем
фактически без программирования в традиционном понимании (т. е. без
написания кода вручную).
Однако если рассматривать программирование в широком смысле – как
создание набора инструкций, предусматривающих обратную связь и
возможность повторного использования, то станет ясно, что под это
определение вполне попадает моделирование любых рабочих процессов, так
или иначе укладывающихся в модели workflow. Именно от этого
отталкивалась Microsoft, разрабатывая WWF.
Важно понимать, что WWF не является ни реализацией какого-либо
стандарта workflow вроде тех, которые определены WfMC, ни инструментом
сугубо делового применения. Так что попытки сравнивать WWF с
существующими на рынке workflow-систем готовыми бизнес-продуктами лишены
всякого смысла, поскольку это универсальная и гибкая платформа,
ориентированная прежде всего на визуальное
программирование. И поэтому конструирование workflow-диаграмм с
помощью WWF в той же мере программирование, в какой и создание
блок-схем.
Соответственно, очень важная особенность WWF – универсальность.
Поскольку визуальное программирование отличается от традиционных
подходов к разработке программных систем только внешне, но никак не
своей сутью, то WWF практически равноценна самой платформе .NET
Framework 2.0, на основе которой она реализована. Это, впрочем, ни в
коей мере не означает, что WWF может полностью заменить традиционные
подходы, однако для определенного круга задач (в том числе, пожалуй, и
для реализации workflow-систем в обычном понимании) данное решение
действительно может оказаться предпочтительным.
Архитектура
Архитектурно Windows Workflow Foundation состоит из нескольких
уровней (таблица). На нижнем находится родительский процесс (Host
Process). Характерно, что WWF работает не изолированно, а выполняется
именно в рамках родительского процесса, который посредством
стандартизированных интерфейсов предоставляет набор сервисов,
определяющих функциональность WWF. Похожий подход применяется в
Microsoft Windows Scripting Host (WSH) для обеспечения доступа к
внутренним объектам.
Архитектура WWF
Уровень | Задача |
Workflow Model | Поддержка предопределенных типов моделей, действий (activities) и соответствующего API |
Runtime Layer | Исполнение модели и поддержка управления ее жизненным циклом |
Hosting Layer | Интеграция с родительским процессом, предоставление интерфейсов для ключевых процессов WWF, реализация которых зависит от родительского процесса |
Host Process | Обеспечение объектов и функциональности, которые полностью или частично доступны в WWF |
Взаимодействие с родительским процессом осуществляется посредством
родительского уровня (Hosting Layer). Его интерфейсы для ключевых
процессов уровня исполнения WWF должны реализовать разработчики,
интегрирующие WWF в свои приложения. Microsoft также собирается
реализовать Hosting Layer для своих ключевых платформ, в частности
ASP.NET 2.0, SQL Server 2005 и Microsoft Office 12, соответственно,
вскоре в их рамках можно будет использовать workflow-модели.
Ядром технологии WWF является уровень исполнения (Runtime Layer),
который отвечает непосредственно за workflow-моделирование и содержит
необходимые для этого службы. Он же управляет жизненным циклом
(менеджмент состояний и активация) моделей, что позволяет исполнять
значительное количество моделей, не расходуя понапрасну системные
ресурсы в том случае, если часть из них находится в режиме ожидания.
На самом верху архитектуры WWF – уровень workflow-модели (Workflow
Model Layer). Он отвечает за поддержку различных типов моделей, содержит
предопределенные действия (activities) и реализует соответствующий API.
Также WWF включает встроенный визуальный редактор, благодаря которому
можно конструировать модели без программирования. Хотя при необходимости
они могут быть реализованы исключительно посредством программного кода,
поскольку фактически представляют собой обычные классы. Кроме того,
поддерживается возможность хранения описания моделей в XML-файлах, что
позволит применять разнообразный инструментарий.
Сама технология WWF изначально ориентирована на расширения. Отдельные
элементы workflow-модели – действия (activities) – выполнены в виде
компонентов, которые могут создаваться сторонними поставщиками с помощью
Visual Studio и WWF SDK. Помимо этого, WWF поддерживает динамическое
обновление моделей во время исполнения, а также позволяет встраивать
редактор моделей в собственные приложения.
Использование на практике
На текущий момент создавать и исполнять workflow-модели можно с
помощью соответствующего расширения для Visual Studio 2005, доступного
на сайте Microsoft.
|
После установки Visual Studio 2005 Extensions for Windows Workflow Foundation в среде Visual Studio появляется возможность создавать новые проекты на основе WWF |
WWF стандартно поддерживает два типа моделей – последовательные
(sequential) и конечные автоматы (state machine). Первые представляют
собой набор последовательно исполняемых действий и в наибольшей мере
соответствуют классическим блок-схемам. Вторые позволяют моделировать
переходы между несколькими предопределенными состояниями, что особенно
актуально при конструировании сложных программных систем, например
управления бизнес-процессами.
Эти два типа в определенной мере взаимозаменяемы – последовательная
модель может быть преобразована в конечный автомат и наоборот. Однако
каждый из них в наибольшей степени подходит лишь для определенного типа
задач. Например, при большом количестве ветвлений и исключений
последовательная модель может оказаться слишком запутанной и потерять
наглядность, что сведет на нет все преимущества графического
представления.
В стандартной поставке WWF идет обширный набор доступных действий для создания моделей разного уровня сложности |
Несмотря на то что стандартно поддерживаются только два типа моделей,
разработчики могут самостоятельно создавать дополнительные.
Конструирование новых моделей на основе существующих не вызовет больших
сложностей даже у относительно неподготовленного пользователя,
обладающего лишь общими навыками описания алгоритмов. Для этого
предназначен визуальный режим, в котором достаточно выбирать доступные
действия (activities) и указывать их свойства и взаимосвязи. Их набор
довольно обширен в стандартной поставке и включает возможности
управления исполнением, построения циклов, распараллеливания, работу с
исключениями, подсоединение к источникам данных, связывание с
Web-службами и др. Создание же полностью оригинальных моделей требует
весьма профессиональной работы.
Для построения условий система предлагает визуальный конструктор,
позволяющий без программирования работать с бинарными операторами. Если
же требуется создать более сложное условие, то применяются традиционные
возможности одного из языков программирования – на уровне метода класса,
реализующего модель.
Несмотря на то что workflow-модели можно создавать и исполнять сами
по себе, полностью их потенциал раскрывается только при интеграции с
приложением, обеспечивающим объекты для манипуляции. Для того чтобы
модель получила доступ к внутреннему устройству родительского процесса,
как уже говорилось, необходимо реализовать определенные интерфейсы,
описанные в документации к WWF.
Модели также поддерживают режим отладки. Несмотря на определенные
проблемы в текущей версии, Microsoft обещает, что будут доступны точки
прерывания и пошаговое исполнение как в графическом представлении, так и
в виде программного кода.
|
Модели конечных автоматов хорошо подходят для решения |
Даже такое поверхностное описание позволяет очертить некоторые сферы
применения WWF. Данная технология хорошо подходит для решения задач
управления бизнес-процессами и документооборотом, поскольку дает
возможность наглядно представить их алгоритмику. Это может быть
согласование условий контракта и обеспечение его выполнения или принятие
заказов и их реализация с учетом индивидуальных особенностей и пожеланий
каждого заказчика.
Также WWF хорошо подходит для формализации взаимодействия различных
исполняющих устройств, и даже человека и машины. Эта особенность
пригодится не только в бизнес-системах, но и в бытовой сфере. К примеру,
посредством WWF можно создать некий «конструктор», предназначенный для
управления логикой работы составляющих «умного дома» – от включения
нагревательных приборов до алгоритма уборки помещений с помощью
роботизированного пылесоса.
|
Последовательные модели в наибольшей степени схожи с обычными блок-схемами |
Не исключено, что WWF найдет применение и в самых обычных
приложениях. К примеру, многих пугала необходимость изучать скриптовые
языки для того, чтобы автоматизировать часто выполняемые рутинные
операции. Наглядность и простота создания моделей в WWF может изменить
отношение пользователей к несложному программированию и заметно повысить
эффективность их труда.
Одно из первых «показательных» применений WWF будет реализовано в
грядущей двенадцатой версии Microsoft Office. До сих пор для организации
полноценного корпоративного документооборота с помощью этого пакета
приходилось либо применять сторонние продукты, либо инвестировать
значительные усилия в разработку решений на базе Exchange и/или
SharePoint. Теперь базовые возможности обеспечения документооборота
войдут в стандартную поставку Microsoft Office, а создавать новые
сценарии движения документов опытные пользователи смогут самостоятельно
без привлечения программистов.
Реальные преимущества
Попробуем выделить некоторые достоинства новой технологи.
Во-первых, использование WWF обеспечивает наглядность и прозрачность
программной логики. Графическое представление, в отличие от кода,
доступно для понимания не только разработчикам, но и другим участникам
процесса создания ПО, в том числе, что особенно важно, заказчикам. WWF
позволяет гораздо эффективнее по сравнению с альтернативными подходами
отделить интерфейс пользователя и бизнес-логику приложений, упрощая
коллективную разработку, модификацию решений и их портирование под новые
платформы и разные типы клиентских устройств.
Во-вторых, наличие среды исполнения WWF и визуального дизайнера
моделей во многих случаях поднимет на качественно новый уровень
встроенные средства автоматизации/адаптации приложений. На наш взгляд,
наглядное конструирование алгоритмов значительно удобнее и доступнее,
чем, к примеру, аналогичные решения на базе скриптов.
В-третьих, WWF становится новым стандартным элементом платформы
Windows с унифицированным интерфейсом и едиными правилами применения,
что существенно упрощает задачу разработчиков по продвижению продуктов
на его основе. Пример показывает сама Microsoft, использующая WWF в
будущей версии Microsoft Office.
В-четвертых, следует отметить, что Microsoft заложила в архитектуру
WWF очень важную функциональную особенность, которой могут похвастаться
далеко не все поставщики нынешних workflow-систем, а именно, возможность
динамически изменять выполняющиеся модели.
Перспективы
На наш взгляд, WWF имеет все шансы на успех и признание. Благодаря
активной поддержке Microsoft эта технология обещает стать стандартом (на
платформе Windows) при решении любых задач, требующих графического
представления логики исполнения и гибкой ее модификации. Естественно,
WWF не претендует на то, чтобы заменить привычное программирование, но
разнообразить и дополнить его сможет вполне.
Не исключено также, что некоторые из существующих поставщиков
откажутся от своих частных технологий и перейдут на использование ядра и
дизайнера WWF. Это может стать стимулом развития рынков, в том числе и
ПО автоматизации документооборота, за счет популяризации и унификации
подходов.
Расширяемость платформы подразумевает появление значительного числа
компонентов, реализующих действия (activities), которые позволят
применять WWF для взаимодействия с широким спектром
аппаратно-программных решений – от составляющих «умного дома» до сложных
корпоративных платформ. Уже сейчас на официальном сайте WWF (windowsworkflow.net)
доступно для загрузки больше десятка различных компонентов от сторонних
поставщиков, и это несмотря на то, что сама технология WWF находится в
стадии разработки.
Встраивание скриптовых языков совсем не превратило большинство
расширяемых программных продуктов в среды разработки, доступные даже
домохозяйкам. Возможно, визуальный подход WWF сумеет исправить эту
ситуацию. Однако какой бы ни была конечная цель Microsoft, ясно одно –
технология WWF займет достойное место в ряду инструментов, которые
применяют современные разработчики, и станет серьезным подспорьем в
руках опытных пользователей.
Источник: Компьютерное обозрение, 7 февраля 2006
In this FAQ we will quickly run through and get a feel of how WWF (Windows Workflow foundation) will help you in making custom work flows in your project.
Title: Windows workflow foundation FAQ Author: Shivprasad Koirala Email: shiv_koirala@yahoo.com Language: C# Level: Beginner Description: Windows workflow foundation FAQ
Windows workflow foundation FAQ
Introduction
In this FAQ we will quickly run through and get a feel of how WWF (Windows Workflow foundation) will help you in making custom work flows in your project.
In case you like the article or your think I need improvements please send me a message at http://www.questpond.com . I am sure every one needs improvements. Enjoy…
What is Windows Workflow Foundation?
WWF is a programming model for building workflow-enabled applications on windows. System. Workflow namespace has all the necessary modules to develop any type of workflow.
What is a Workflow?
A Workflow is a set of activities, which is stored as model and they depict a process. Below figure depicts clearly the difference between Workflow and Activity. Every task is an activity and group of activity depicts a complete workflow. Workflow is run by the Workflow runtime engine.
Figure 1: — Work Flow Foundation Architecture
Workflow model can be written in pure .NET code, pure XAML or Mix of XAML and .NET Code. A workflow model is compiled and can execute under windows, ASP.NET, Web services or windows services application.
What are different types of Workflow in Windows Workflow foundation?
There are two basics type of workflow Sequential Workflow and State machines workflow.
A sequential workflow has clear start and finish boundaries. Workflow controls execution in Sequential workflow. In sequential execution, one task is executed after other. Sequential workflow is more rigid in format and execution path has a determistic nature.
A State machine workflow is more dynamic in nature. Workflow has states and the state waits for events to help it move to next state. In State machine execution path is undetermestic nature.
Below figure shows visual conceptualization of fundamentals. You can see in Sequential workflow the execution path is very determent. Shiv performs the entire task sequentially and these tasks are very determent. Now have a look at the second workflow. Every state goes to other state when it receives some external events. For instance when Shiv is seeing star trek there is an event of flashing news which triggers him to see the flashing new.
Figure 2: — Sequential and State machine workflow
when should we use a sequential workflow and when should we use state machines?
If the workflow is very rigid then you go for sequential workflow and if the workflow is dynamic then go for State machine workflow. For instance you have placed an order and the order will not pass until your supervisor approves is a rigid flow. Because your order has to be approved by, a supervisor or else it will not be approved. But what if your order moves from one place to other place. For instance, it moves from approval to waiting and then clarification a state machine workflow model is more appropriate.
Below is a simple code snippet which shows practically how to use sequential workflow. Let try to understand step by step as marked in the figure:-
1 — First you need to select System. Workflow namespace.
2, 3, and 4 — In these three steps we created code object and linked them with activity.
5, 6, 7, and 8 — We start the workflow and create workflow instance object to run the sequential workflow. You can see the output in 8. Depending on how you add the activity in section 3, it executes sequentially. Because we have added codeactivity1, first it executes the first activity first. The sequence on how you add the activity to the activities collection the activities are run.
Figure: — 3 Code snippet for workflow
Note: — The above code snippet was developed with out using designer. The whole point was to make you understand what happens behind the scenes. In real projects you will be dependent on designer rather than coding manually. You can find the above code in SimpleWorkFlowSampleManual folder.
How do we create workflows using designer?
As said previously it is very easy to design workflows using designer. So we will answer this question by actually doing a small sample. Below is the code snippet and image snapshot which shows how we can use the designer to create workflows. So lets understand all the below numbered snapshot.
1 — First select a sequential workflow project. In this case, we have selected Sequential workflow console application to keep the sample simple.
2 — When you are done with creating the project you will see the solution explorer as shown in the second snapshot. There are two files one the WorkFlow1.cs and the other Workflow1.designer.cs.If you click on the WorkFlow1.cs you will get a designer pane as shown in snapshot 3. If you double click on Workflow1.designer.cs, you will get behind code as shown in snapshot 4.
3 — So let us drag drop a code activity on the workflow designer and associate this activity with a method called as MyActivity1. This association is done by entering the method name in Execute Code property. In MyActivity1, we have just displayed in the console that this is my first activity. Again, we have added one more code activity, which points to MyActivity2. If you see the designer pane we have sequenced code1 first and code2 next. So in short, code1 will execute first and the code2. This is clear from the output displayed below.
4 — This is the behind code of the workflow.
Figure 4 Sequential workflow using designer
How do we specify conditions in Work flow?
Yes, you can define conditions in workflow by using conditionedActivitygroup. Below is the numbered snapshot, which shows how to use conditionedActivitygroup.
1 — You can see in this snapshot we have defined a conditionedActivitygroup with two conditions. The two boxes inside the group define two conditions.
2 — You can select one of the condition box and define the condition using the When Conditions property. If this condition is true you need to specify in the execute code which method to execute. For instance in the current snapshot we have said that old1 method should execute if age > 21. The same procedure we need to follow for the second condition box. In the second condition box we have specified to execute young1 method if age < 21. Currently the second condition is not visible in the below snapshot.
3 — Workflow editor also provides a cool interface called as Rule Condition Editor, which can be used to specify conditions. Age is a public property in the behind code. You can also get the Age in the intelligence of rule condition editor.
4 — Both the condition will execute inside the condition activity group. We need to also specify when this conditionactivitygroup should exit. Therefore, we have made a function called as exit. If the user inputs age as -1 it will exit from the loop or else it will take inputs from user and continue evaluating depending on the two conditions.
Figure 5:- Sequential workflow with conditions
How do you handle exceptions in workflow?
Exception handling in Workflow is somewhat different than how we do in normal .NET application. Below is the numbered snapshot of how we can handle exceptions in Workflow.
1 — We have small tab, which says view exceptions. If you click on view exception, you will be redirected to a workflow design only for exception as shown in numbered snapshot 2.
2 — This is the workflow which will execute incase we have exceptions. We have put a code activity, which points to a method called as raise Exception. Incase of exception in the workflow this path will be followed.
Figure 6:- Workflow with exception handling
What is the use of XOML files.
Twist: — How can we serialize workflows?
Windows Workflow Foundation gives developers a declarative way to create workflows by using XAML. See WPF chapter for more details about XAML. These markup files are Stored with XOML (Extensible Object Markup Language) extension. In the below snapshot you can see Workflow1.xoml file created by designer. Markup file can also have code behind. The whole concept of having code behind for XOML file is to separate the presentation from logic files.
In the below code snapshot we have made a simple XOML sample. Below is the explanation number wise:-
1 – In order to create a XOML file you need to add sequential workflow with separation. Which means that XOML file will be created with a behind code.
2 – Currently we have two activity code3 and code1. Below is the XOML file contents
<?Mapping XmlNamespace="ComponentModel" ClrNamespace="System.Workflow.ComponentModel" Assembly="System.Workflow.ComponentModel" ?>
<?Mapping XmlNamespace="Compiler" ClrNamespace="System.Workflow.ComponentModel.Compiler" Assembly="System.Workflow.ComponentModel" ?>
<?Mapping XmlNamespace="Activities" ClrNamespace="System.Workflow.Activities" Assembly="System.Workflow.Activities" ?>
<?Mapping XmlNamespace="RuleConditions" ClrNamespace="System.Workflow.Activities.Rules" Assembly="System.Workflow.Activities" ?>
<SequentialWorkflow x:Class="WorkflowSeq.Workflow1" x:CompileWith="Workflow1.xoml.cs" ID="Workflow1" xmlns:x="Definition" xmlns="Activities">
<Code ExecuteCode="Mycode3" ID="code3" />
<Code ExecuteCode="Mycode1" ID="code1" />
</SequentialWorkflow>
See the above snippet of the XOML file. You can see how the behind code is linked using the Compile With attribute. Code forms the element of the Sequential Workflow tag. One of the best thing with Markup is we can change the sequence just by changing the XOML file we do not need to compile the whole application again.
Figure 7:- XOML in action
In the above snapshot, one of the things to now is 3, 4, and 5 numbered sections. These sections are not linked with the sample. But just to make you aware you can create serialize any workflow and deserialize them again using the text writer object.
How can we pass parameters to workflow?
When you call the start workflow function, you can pass as name / value pairs using the dictionary object.
Figure 8:- Passing value to workflow