在 Service Manager Authoring Tool 中建立自訂活動的指導方針Guidelines for creating custom activities in the Service Manager Authoring Tool

重要

此版本的 Service Manager 已達到終止支援,建議您 升級至 Service Manager 2019This version of Service Manager has reached the end of support, we recommend you to upgrade to Service Manager 2019.

Service Manager 將各種不同的資訊技術 () 處理常式。Service Manager automates a variety of information technology (IT) processes. 例如,在事件管理程式中,Service Manager 包含各種自動化步驟,例如在建立或解決事件時自動通知使用者,以及根據分類自動將事件路由傳送至各種佇列。For the Incident Management process, for example, Service Manager includes various automated steps, such as automated notifications to users when incidents are created or resolved and automatic routing of incidents to various queues, based on categorization. 這項自動化的實作是利用針對各種解決方案定義的工作流程,並使用 Windows Workflow Foundation (WF) 功能來描述、執行與追蹤自動化作業。This automation is implemented by using workflows that are defined for the various solutions, and it uses Windows Workflow Foundation (WF) capabilities to describe, execute, and track the automated operations.

客戶和合作夥伴可以透過定義並將新工作流程加入程序中,以擴充其包含的自動化功能。Customers and partners can extend the included automation by defining new workflows and adding them into a process. 工作流程可以設定成按照固定排程執行,或是在資料庫中發生指定的狀況時執行,例如在建立事件時,或是當事件變更為指定的狀態 (如 [作用中] **** 或 [已解決] ****) 時。Workflows can be set to occur on a fixed schedule or on a specified condition occurring in the database, for example, when an incident is created or when it changes to a specified state, such as Active or Resolved.

Service Manager Authoring Tool 提供簡單易用的方法來建立新的工作流程。The Service Manager Authoring Tool provides an easy-to-use method of creating new workflows. 它提供一個程式庫,內含不同的工作流程活動,例如建立事件或更新事件,還有一個拖放式圖形設計工具,讓您用來將這些工作流程活動編排成工作流程順序。It provides a library of different workflow activities, such as creating an incident or updating an incident, and a drag-and-drop graphical designer that you can use to arrange these workflow activities into a workflow sequence. Authoring Tool 接著會將新的工作流程編譯成一組定義、程式碼和管理元件內容。The Authoring Tool then compiles the new workflow into a set of definitions, code, and management pack content. 當這項資訊匯入 Service Manager 時,會將新的工作流程整合到指定的解決方案中。When this information is imported into Service Manager, it integrates the new workflow into the specified solution.

瞭解 Authoring Tool 幕後的進展,可讓更多的使用者受益。Understanding what is going on behind the scenes of the Authoring Tool can benefit more advanced users. 首先,客戶和合作夥伴可以使用這項資訊,利用適用于其特定進程的工作流程活動,在 Service Manager 中擴充工作流程活動程式庫。First, customers and partners can use this information to extend the workflow activity library in Service Manager with workflow activities that apply to their specific processes. 其次,開發人員可以使用這項資訊,利用其選擇的開發工具(例如 Microsoft Visual Studio 開發系統),建立與 Service Manager 相容的自訂或 advanced 工作流程。Secondly, developers can use this information to build custom or advanced workflows that are compatible with Service Manager by using their development tool of choice, such as the Microsoft Visual Studio development system.

工作流程活動和 WorkflowActivityBase 類別Workflow activities and the WorkflowActivityBase class

Service Manager 工作流程使用 WF 活動。Service Manager workflows use WF activities. 為了順利使用 Authoring Tool,這些活動會衍生自基類 WorkflowActivityBase,其屬於 microsoft.enterprisemanagement。 Common 命名空間。To work smoothly with the Authoring Tool, these activities derive from the base class WorkflowActivityBase, which belongs to the Microsoft.EnterpriseManagement.Workflow.Common namespace. WorkflowActivityBase 基底類別引進了 WF 活動的一般 Activity 基底類別並未提供的內容和方法。The WorkflowActivityBase base class introduces properties and methods that are not available in the generic Activity base class for WF activities. 如需如何使用一般 活動 基類定義 WF 活動的詳細資訊,請參閱 活動類別For more information about how to define WF activities by using the generic Activity base class, see Activity Class.

使用 WorkflowActivityBase 類別的優點Benefits of using the WorkflowActivityBase class

使用者可以從 Visual Studio 活動程式庫匯入 WF 活動,並且可以在 Authoring Tool撰寫 窗格中使用這些活動。Users can import WF activities from the Visual Studio activity library, and they can work with those activities in the Authoring ToolAuthoring pane. 不過,這些活動的行為表現與在 Visual Studio 設計環境中一樣。However, those activities behave in the same way as they do in the Visual Studio Design environment. 它們沒有內建于 Service Manager 活動程式庫中的自訂專案。They do not have the customizations that are built into the Service Manager activity library.

注意

並非所有的 Visual Studio WF 活動都已測試過 Authoring Tool 的相容性,而某些 Visual Studio WF 活動可能無法在 Authoring Tool 中正確執行。Not all Visual Studio WF activities have been tested for compatibility with the Authoring Tool, and some Visual Studio WF activities might not run correctly in the Authoring Tool.

下表列出以 WorkflowActivityBase 基底類別為基礎的 WF 活動與以一般 Activity 基底類別為基礎的 WF 活動,其行為上的不同之處。The following table lists the differences in behavior between WF activities that are based on the WorkflowActivityBase base class and WF activities that are based on the generic Activity base class.

案例Scenario Authoring Tool WF 活動 (WorkflowActivityBase 基類) Authoring Tool WF activity (WorkflowActivityBase base class) Visual Studio WF 活動 (Activity 基底類別)Visual Studio WF activity (Activity base class)
使用者會將活動屬性 (系結至 Service Manager 物件屬性,或) 其他活動的屬性。User binds activity properties (to Service Manager object properties or to properties from other activities). 呼叫針對 Service Manager 使用者自訂的 [系結] 屬性Calls the Bind property to dialog box that is customized for Service Manager users. 呼叫適用於開發人員的 [繫結內容至] **** 對話方塊。Calls the Bind property to dialog box that is intended for developers.
使用者會將活動新增到 [For-Each 迴圈] **** 活動。User adds the activity to a For-Each Loop activity. 新增內容 Propertytobind (迴圈索引) 和 CurrentItem,亦即參與迴圈特定作業所需的內容 (CurrentItem 是內部內容)。Adds the properties Propertytobind (the loop index) and CurrentItem, which are required to take part in loop-specific operations (CurrentItem is an internal property). 迴圈每一次反覆運算時都會表現相同的行為,而且不會與編製迴圈索引的內容互動。Behaves in the same way for each iteration of the loop, and does not interact with the property that indexes the loop.

重要

由於 Authoring Tool 工作流程設計工具所需的自訂,以 WorkFlowActivityBase 類別為基礎的活動在 Visual Studio 工作流程設計環境中無法如預期般運作。Because of the customizations that are required for the Authoring Tool workflow designer, activities that are based on the WorkFlowActivityBase class do not function as expected in the Visual Studio workflow design environment.

使用者可以在 Visual Studio 中建立自訂 WF 活動,以便在 Authoring Tool 中使用。Users can build custom WF activities in Visual Studio for use in the Authoring Tool. 不過,若要利用 Authoring Tool 的自訂設計階段行為,自訂活動必須以 WorkflowActivityBase 類別(而非 活動 類別)為基礎。However, to take advantage of the custom design-time behavior of the Authoring Tool, custom activities must be based on the WorkflowActivityBase class instead of the Activity class.

工作流程活動和 Service Manager 自動化活動Workflow activities and Service Manager automated activities

WF 活動可以與不同類型的活動互動,也就是 Service Manager 工作專案所使用的 Service Manager 活動。WF activities can interact with a different type of activity, the Service Manager activities that are used by Service Manager work items. 工作專案 是 Service Manager 使用的其中一種主要物件類型。Work items are one of the main types of objects that Service Manager uses. 工作項目會追蹤工作單位,例如 [事件] ****、[服務要求] ****、[變更要求] ****,以及其他工作單位。Work items track units of work, such as Incidents, Service Requests, Change Requests, and other units of work. 大部分的工作專案都包含一或多個 Service Manager 活動。Most work items comprise one or more Service Manager activities. 例如,[變更要求] **** 通常包括至少兩個活動:[檢閱] **** 活動和 [變更執行] **** 活動。For example, a Change Request typically includes at least two activities: a Review activity and a Change Execution activity. 工作項目通常會依序執行這些活動。The work item typically executes these activities in order.

建立工作專案時,第一個 Service Manager 活動會變成作用中狀態,並在 Service Manager (或使用者) 執行活動所代表的任何工作時維持作用中狀態。When a work item is created, the first Service Manager activity becomes active and remains active while Service Manager (or the user) carries out whatever work the activity represents. 當該工作完成時,Service Manager 會將第一個活動標示為 已完成 ,並啟用序列中的下一個活動。When that work finishes, Service Manager marks the first activity as Completed and activates the next activity in the sequence. 當序列中的最後一個活動標示為 已完成時,Service Manager 會將整個工作專案標示為 已完成When the final activity in the sequence is marked as Completed, Service Manager marks the entire work item as Completed.

某些 Service Manager 活動可以手動執行,例如變更要求審核活動。Some Service Manager activities can be executed manually, such as the Review activity of a Change Request. 其他 Service Manager 活動可以自動化,例如將電子郵件傳送給使用者的活動。Other Service Manager activities can be automated, such as an activity that sends an email to a user. 變更要求變更執行 活動可以自動化。The Change Execution activity of a Change Request can be automated. Service Manager 使用 WF 工作流程將 Service Manager 活動自動化。Service Manager uses WF workflows to automate Service Manager activities.

範例:將活動狀態設定為已完成活動Example: The Set Activity Status to Completed activity

Service Manager 中的 WF 工作流程活動範例會使用「已完成的 wf 活動」 設定活動狀態This example of a WF workflow activity in Service Manager uses the Set Activity Status to Completed WF activity. 此 WF 活動通常代表工作流程中的最後一個步驟,此步驟會執行自動化的 Service Manager 活動,並將該活動的狀態設定為 [ 已完成]。This WF activity typically represents the last step in a workflow that implements an automated Service Manager activity, and it sets the status of that activity to Completed. 設定這個狀態會促使系統移到工作項目中的下一個活動,而且這個程序會不斷重複,直到工作項目中的最後一個活動完成為止。Setting this status triggers the system to move to the next activity in the work item, and this process repeats until the last activity in the work item is completed.

[ 將活動狀態設定為已完成 ] 活動會採用一個輸入 [ 活動識別碼],以識別要採取行動的 Service Manager 活動。然後,WF 活動會連接到 Service Manager management server、從資料庫抓取指定的 Service Manager 活動、將其狀態設定為 [ 已完成],然後將它儲存回資料庫。The Set Activity Status to Completed activity takes one input, Activity ID, which identifies the Service Manager activity on which to act. The WF activity then connects to the Service Manager management server, retrieves the specified Service Manager activity from the database, sets its status to Completed, and then saves it back to the database. 本範例中包含的程式碼範例大多來自 SetActivityStatusToCompleted.cs 檔案,亦即描述 [將 [活動狀態] 設定為「已完成」] **** 活動的基礎檔案。Most of the code samples that are included in this example come from the SetActivityStatusToCompleted.cs file, an underlying file that describes the Set Activity Status to Completed activity.

初始化範例 WF 活動Initialize the example WF activity

SetActivityStatusToCompleted.cs 檔案的第一個區段包含宣告和初始化陳述式。The first section of the SetActivityStatusToCompleted.cs file contains the declaration and initialization statements. 這個活動是以 WorkflowActivityBase 類別為基礎,並使用驗證類別 SetActivityStatusToCompletedValidator 和設計工具類別 WorkflowActivityBaseDesignerThis activity is based on the WorkflowActivityBase class, and it uses the validator class SetActivityStatusToCompletedValidator and the designer class WorkflowActivityBaseDesigner.

WorkflowActivityBaseDesigner 類別包含前一節<使用 WorkflowActivityBase 類別的優點>所述的自訂。The WorkflowActivityBaseDesigner class contains the customizations that are described in the previous section, "Benefits of Using the WorkflowActivityBase Class." 您可以進一步擴充並自訂這個類別。You can further extend and customize this class.

此範例活動之活動定義的第一個區段包含下列程式碼:The first section of the activity definition for this example activity includes the following code:

namespace Microsoft.ServiceManager.WorkflowAuthoring.ActivityLibrary
{
    // ---------------------------------------------------------------------
    /// <summary>
    /// Activity to set an activity's status to complete
    /// </summary>
    // ---------------------------------------------------------------------
    [ToolboxItem(typeof(ActivityToolboxItem))]
    [ActivityValidator(typeof(Validators.SetActivityStatusToCompletedValidator))]
    [Designer(typeof(WorkflowActivityBaseDesigner))]
    public sealed partial class SetActivityStatusToCompleted : WorkflowActivityBase
    {

範例 WF 活動的輸入屬性Input properties for the example WF activity

此程式碼會將一個內容 ( ActivityId) 宣告為相依性內容。The code declares one property, ActivityId, as a dependency property. 這表示這個內容可以繫結到在工作流程層級定義的參數。This means that this property can be bound to parameters that are defined at the workflow level. 在此情況下,Service Manager 活動的識別碼會傳入工作流程作為工作流程參數,而且會流入此活動做為輸入。In this case, the ID of the Service Manager activity is passed in to the workflow as a workflow parameter, and it flows into this activity as an input.

  // --------------------------------------------------------------------------------
  /// <summary>
  /// Dependency Property for ActivityId property
  /// </summary>
  // --------------------------------------------------------------------------------
  public static DependencyProperty ActivityIdProperty =
      DependencyProperty.Register("ActivityId", typeof(String), typeof(SetActivityStatusToCompleted));

  // --------------------------------------------------------------------------------
  /// <summary>
  /// Activity ID
  /// </summary>
  // --------------------------------------------------------------------------------
  [Browsable(true)]
  [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
  public string ActivityId
  {
      get
      {
          return (string)this.GetValue(ActivityIdProperty);
      }
      set
      {
          this.SetValue(ActivityIdProperty, value);
      }
}

範例 WF 活動中的執行行為Execution behavior in the example WF activity

Execute 方法會執行這個 WF 活動的實際工作。The Execute method does the actual work of this WF activity. Execute 方法的範圍內,WF 活動會執行下列工作:Within the scope of the Execute method, the WF activity does the following:

  • 偵測它是否在 [For-Each 迴圈] **** 活動內運作,如果是,則設定適當的 WF 活動內容。Detects whether it is operating within a For-Each Loop activity, and, if so, sets the appropriate WF activity properties.

  • 連接到指定的 Service Manager 管理伺服器並建立 EnterpriseManagementGroup 物件。Connects to the specified Service Manager management server and creates an EnterpriseManagementGroup object.

  • 使用 ActivityId 屬性,從資料庫取得識別的 Service Manager 活動。Uses the ActivityId property to get the identified Service Manager activity from the database.

  • 尋找 Service Manager 活動的類別定義,取得所抓取 Service Manager 活動的 Status 屬性,並將屬性設定為 已完成 的列舉清單值。Finds the class definition of the Service Manager activity, gets the Status property of the retrieved Service Manager activity, and sets the property to the Completed enumeration list value.

  • 認可 Service Manager 活動的變更。Commits the changes to the Service Manager activity.

  • 使用 TrackData 方法 (WF 基礎結構的一部分) 記錄有關 WF 活動之執行和狀態的追蹤資訊。Uses the TrackData method (part of the WF infrastructure) to log tracking information about the execution and status of the WF activity.

        // --------------------------------------------------------------------------------
        /// <summary>
        /// The execute method will have the implementation to set the activity status to complete.
        /// </summary>
        // --------------------------------------------------------------------------------
        protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
        {
            try
            {
                // Initialize the current item if the activity contained within the For-Each loop
                base.Execute(executionContext);

                // Validate Parameters
                if (String.IsNullOrEmpty(ActivityId))
                {
                    throw new ArgumentNullException("ActivityId");
                }

                string SMServer = "localhost";

                Guid TaskGuid = new Guid(ActivityId);
                EnterpriseManagementGroup _mg = new EnterpriseManagementGroup(SMServer);

                EnterpriseManagementObject Activity = _mg.EntityObjects.GetObject
                    <EnterpriseManagementObject>(TaskGuid, ObjectQueryOptions.Default);

                ManagementPack SystemMP = _mg.ManagementPacks.GetManagementPack(
                    SystemManagementPack.System);
                ManagementPack ActivityMP = _mg.ManagementPacks.GetManagementPack(
                    Resources.ActivityManagementMP, SystemMP.KeyToken, SystemMP.Version);

                ManagementPackClass activityClass = _mg.EntityTypes.GetClass(
                    Resources.WorkItemActivityClass, ActivityMP);

                ManagementPackProperty status = activityClass.PropertyCollection["Status"];
                ManagementPackEnumeration Completed =
                    _mg.EntityTypes.GetEnumeration("ActivityStatusEnum.Completed", ActivityMP);

                Activity[status].Value = Completed;
                Activity.Commit();
            }
            catch (ArgumentNullException argNullException)
            {
                // Log to Tracking Service
                TrackData(argNullException.ToString());

                throw;
            }
            catch (EnterpriseManagementException mgmtException)
            {
                TrackData(mgmtException.ToString());
                throw;
            }

            return ActivityExecutionStatus.Closed;
        }
    }
}

範例 WF 活動中的驗證行為Validation behavior in the example WF activity

SetActivityStatusToCompletedValidator.cs 檔案可定義 WF 活動的驗證行為。The SetActivityStatusToCompletedValidator.cs file defines the validation behavior of the WF activity. 這項行為定義設計工具如何指出此 WF 活動是否已完整定義或是仍需要定義一或多項輸入。This behavior defines how the designer indicates whether this WF activity is fully defined or if it still requires one or more inputs to be defined. Authoring Tool 表示類似于 Visual Studio 的驗證錯誤,方法是在撰寫窗格中的工作流程活動上使用紅色驚嘆號 () 圖示。The Authoring Tool indicates a validation error similarly to Visual Studio by using a red exclamation point (!) icon on the workflow activity in the Authoring pane.

namespace Microsoft.ServiceManager.WorkflowAuthoring.ActivityLibrary.Validators
{
    // --------------------------------------------------------------------------------
    /// <summary>
    /// Validator for the SetActivityStatusToCompleted activity
    /// </summary>
    // --------------------------------------------------------------------------------
    internal class SetActivityStatusToCompletedValidator : ActivityValidator
    {
        // --------------------------------------------------------------------------------
        /// <summary>
        /// Validator for the SetActivityStatusToCompleted activity
        /// </summary>
        // --------------------------------------------------------------------------------
        public override ValidationErrorCollection Validate(ValidationManager manager, object obj)
        {
            // Performing default validation
            ValidationErrorCollection errorColl = base.Validate(manager, obj);

            SetActivityStatusToCompleted setActivityStatusToCompletedObj =
                (SetActivityStatusToCompleted)obj;

            // Check if validation is happening during compilation of activity and
            // not during the hosting of an activity
            if (setActivityStatusToCompletedObj.Parent == null)
            {
                return errorColl;
            }

            string propertyName = Common.GetPropertyName(setActivityStatusToCompletedObj);

            // Add validation error if ActivityId is null or empty
            if (setActivityStatusToCompletedObj.ActivityId == null
                &&
                setActivityStatusToCompletedObj.GetBinding(SetActivityStatusToCompleted.ActivityIdProperty) == null
                &&
                String.Compare(propertyName, "ActivityId", false, CultureInfo.InvariantCulture) != 0)
            {
                errorColl.Add(new ValidationError(
                    Resources.SetActivityStatusToCompleted_ActivityId_DesignTimeValidation, 10, false));
            }

            return errorColl;
        }
    }
}

在工作流程中使用範例 WF 活動Use the example WF activity in a workflow

[ 將活動狀態設定為已完成 ] 活動會包含在 [Authoring Tool 預設 活動工具箱 ] 窗格中。The Set Activity Status to Completed activity is included in the Authoring Tool default Activities Toolbox pane. 如需將自訂活動新增至 [ 活動工具箱 ] 窗格的詳細資訊,請參閱 如何安裝自訂活動元件For more information about adding custom activities to the Activities Toolbox pane, see How to Install a Custom Activity Assembly.

您可以使用 Authoring Tool 的 [撰寫中] 窗格,以類似于使用 Visual Studio 工作流程設計介面的方式來撰寫工作流程。You can use the authoring pane of the Authoring Tool to author workflows in a manner that is similar to using the Visual Studio workflow design interface. 不過,Authoring Tool 提供下列優點:However, the Authoring Tool offers the following benefits:

  • 沒有開發技能的使用者可以建置工作流程,而不需要直接處理程式碼。Users without development skills can build workflows; they do not have to work with code directly.

  • 當使用者在 Authoring Tool 中儲存工作流程時,此工具會產生對應的 Visual c # 和 XOML 程式碼,並將其編譯為 .dll 檔案。When a user saves a workflow in the Authoring Tool, the tool generates the corresponding Visual C# and XOML code and compiles it into a .dll file. 此工具也會將工作流程與可直接與 Service Manager 互動的管理元件整合。The tool also integrates the workflow with a management pack that can interact directly with Service Manager.

工作流程的 Visual c # 程式碼Visual C# Code for the workflow

下列範例會顯示 Authoring Tool 針對使用「 將活動狀態設定為已完成 」活動的範例工作流程所產生的 Visual c # 程式碼。The following sample shows the Visual C# code that the Authoring Tool generates for an example workflow that uses the Set Activity Status to Completed activity. 此程式碼會宣告簡單的循序工作流程, SetActivityStatusToCompleteWF;這個工作流程具有一個工作流程參數,也就是相依性內容 ActivityIdThis code declares a simple sequential workflow, SetActivityStatusToCompleteWF, that has one workflow parameter, the dependency property ActivityId. ActivityID 的值是由本範例後面顯示的管理組件定義決定。The value of ActivityID is determined by the management pack definitions that are shown later in this example. 當工作流程執行時,Service Manager 會識別該值,並將其傳遞至工作流程。When the workflow runs, Service Manager identifies the value and passes it into the workflow.

namespace WorkflowAuthoring
{
    using System;
    using System.ComponentModel;
    using System.ComponentModel.Design;
    using System.Workflow.ComponentModel.Design;
    using System.Workflow.ComponentModel;
    using System.Workflow.ComponentModel.Serialization;
    using System.Workflow.ComponentModel.Compiler;
    using System.Drawing;
    using System.Collections;
    using System.Workflow.Activities;
    using System.Workflow.Runtime;

    public partial class SetActivityStatusToCompleteWF : System.Workflow.Activities.SequentialWorkflowActivity
    {

        public static DependencyProperty ActivityIdProperty = DependencyProperty.Register("ActivityId", typeof(string), typeof(SetActivityStatusToCompleteWF));

        [System.ComponentModel.DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Visible)]
        [System.ComponentModel.BrowsableAttribute(true)]
        [System.ComponentModel.CategoryAttribute("Misc")]
        public string ActivityId
        {
            get
            {
                return ((string)(this.GetValue(ActivityIdProperty)));
            }
            set
            {
                this.SetValue(ActivityIdProperty, value);
            }
        }
    }
}

工作流程的 XOML 程式碼XOML code for the workflow

WF 使用 XOML 格式處理某些工作流程定義。WF uses the XOML format for some of the workflow definitions. 在範例工作流程的案例中,Authoring Tool 會使用下列內容來建立 SetActivityStatusToCompleteWF xoml 檔案:In the case of the example workflow, the Authoring Tool creates the file SetActivityStatusToCompleteWF.xoml with the following content:

<SequentialWorkflowActivity x:Class="WorkflowAuthoring.SetActivityStatusToCompleteWF" x:Name="SetActivityStatusToCompleteWF" xmlns:ns0="clr-namespace:Microsoft.ServiceManager.WorkflowAuthoring.ActivityLibrary;Assembly=Microsoft.ServiceManager.WorkflowAuthoring.ActivityLibrary, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml" xmlns="https://schemas.microsoft.com/winfx/2006/xaml/workflow">
<ns0:SetActivityStatusToCompleted ActivityId="{ActivityBind SetActivityStatusToCompleteWF,Path=ActivityId}" x:Name="setActivityStatusToCompleted1" PropertyToBind="{x:Null}" />
</SequentialWorkflowActivity>

SetActivityStatusToCompleteWF.xoml 會宣告工作流程, SetActivityStatusToCompleteWF,執行一個工作流程活動,[將 [活動狀態] 設定為「已完成」] ****。SetActivityStatusToCompleteWF.xoml declares that the workflow, SetActivityStatusToCompleteWF, runs one workflow activity, Set Activity Status To Completed. 該活動具有一個輸入參數, ActivityId,而這個參數會從工作流程的 ActivityId 內容取得值。That activity has one input parameter, ActivityId, which gets its value from the ActivityId property of the workflow.

在管理元件中宣告工作流程及其觸發條件Declare the workflow and its trigger condition in a management pack

Service Manager 無法使用隔離的工作流程 .dll 檔案;工作流程必須與管理元件整合。Service Manager cannot use an isolated workflow .dll file; the workflow must be integrated with a management pack. 管理組件會定義工作流程應執行的時機,以及所要使用的輸入值。The management pack defines when the workflow should run and what input values to use. 當它產生工作流程程式碼並編譯工作流程 .dll 檔案時,Authoring Tool 會將工作流程相關資訊新增至管理元件。At the same time that it generates the workflow code and compiles the workflow .dll file, the Authoring Tool adds the workflow-related information to a management pack.

範例工作流程 SetActivityStatusToCompleteWF與範例管理組件相關聯,名為 Woodgrove.AutomatedActivity.AddComputerToGroupMP.xml。The example workflow, SetActivityStatusToCompleteWF, is associated with an example management pack, named Woodgrove.AutomatedActivity.AddComputerToGroupMP.xml. 此管理元件會以新的自動化 Service Manager 活動擴充 變更管理 流程。This management pack extends the Change Management process with a new automated Service Manager activity. 當新活動在變更管理作業中變成作用中時,它會觸發 SetActivityStatusToCompleteWF 工作流程。When the new activity becomes active during a change management operation, it triggers the SetActivityStatusToCompleteWF workflow.

當新的 Service Manager 活動變更狀態) 時,管理元件會定義工作流程 (的觸發程式,並定義要用於 ActivityId 屬性的值 (新 Service Manager 活動) 的唯一識別碼。The management pack defines the trigger of the workflow (when the new Service Manager activity changes state), and it defines the value to use for the ActivityId property (the unique identifier of the new Service Manager activity). 當工作流程執行時,它會將新 Service Manager 活動的狀態變更為 [ 已完成]。When the workflow runs, it changes the status of the new Service Manager activity to Completed. 請注意,在一般工作流程中,這會是工作流程中其他 WF 活動執行的其他某項工作後的最後一個步驟。Note that in a normal workflow, this would be the last step following some other task that is performed by other WF activities in the workflow.

管理組件的 Monitoring 區段包含工作流程的 Rule 定義,The Monitoring section of the management pack contains the Rule definition for the workflow. Rule 定義具有兩個組件: DataSource 元素和 WriteAction 元素。In turn, the Rule definition has two parts, the DataSource element and the WriteAction element.

在範例工作流程的案例中, DataSource 元素包含 訂閱 專案,這個專案會指定當 addcomputertogroup.mpb 類別的實例 (自訂 Service Manager 類別時應執行的工作流程) 會將狀態變更為 [ 作用中]。In the case of the example workflow, the DataSource element contains a Subscription element, which specifies that the workflow should run when an instance of the AddComputerToGroup class (a custom Service Manager class) changes state to Active.

<Monitoring>
    <Rules>
        <Rule ID="SetActivityToCompleteRule" Enabled="true" Target="SystemCenterLibrary!Microsoft.SystemCenter.SubscriptionWorkflowTarget" ConfirmDelivery="false" Remotable="true" Priority="Normal" DiscardLevel="100">
            <Category>Notification</Category>
            <DataSources>
                <DataSource ID="DS" TypeID="Subscriptions!Microsoft.SystemCenter.CmdbInstanceSubscription.DataSourceModule">
                    <Subscription>
                        <InstanceSubscription Type="$MPElement[Name='AddComputerToGroup']$">
                            <UpdateInstance><Criteria><Expression><SimpleExpression>
                                <ValueExpression>
                                    <Property State="Post">$Context/Property[Type='Activity!System.WorkItem.Activity']/Status$</Property>
                                </ValueExpression>
                                <Operator>Equal</Operator>
                                <ValueExpression>
                                    <Value>$MPElement[Name='Activity!ActivityStatusEnum.Active']$</Value>
                                </ValueExpression>
                            </SimpleExpression></Expression></Criteria></UpdateInstance>
                        </InstanceSubscription>
                        <StartWatermark>1</StartWatermark>
                        <PollingIntervalInSeconds>60</PollingIntervalInSeconds>
                        <BatchSize>100</BatchSize>
                    </Subscription>
                </DataSource>
            </DataSources>
        </Rule>
    </Rules>
</Monitoring>

WriteAction 元素 (即 Microsoft.EnterpriseManagement.SystemCenter.Subscription.WindowsWorkflowTaskWriteAction) 定義符合觸發條件時應執行的工作。The WriteAction element (specifically, Microsoft.EnterpriseManagement.SystemCenter.Subscription.WindowsWorkflowTaskWriteAction) defines what to do when the trigger condition is met. 在此元素內, Subscription 元素可識別所要執行的工作流程組件 (SetActivityStatusToCompleteWF.dll),以及此組件中代表工作流程 WorkflowTypeName的類別。Within this element, a Subscription element identifies the workflow assembly file to run (SetActivityStatusToCompleteWF.dll) and the class in the assembly that represents the workflow, WorkflowTypeName.

用帳戶元素也包含WorkflowParameter專案,它會定義ActivityId屬性,並使用語法 $Data/basemanagedentityid $,將它系結至DataSource元素中所記錄之 Service Manager 活動的唯一識別碼。The Subscription element also includes a WorkflowParameter element, which defines the ActivityId property and, using the syntax $Data/BaseManagedEntityId$, binds it to the unique identifier of the Service Manager activity that is recorded in the DataSource element.

WriteAction 元素也會儲存工作流程的選擇性設定詳細資料,例如工作流程失敗時的重試次數、重試的頻率,以及工作流程關閉前執行的時間上限 (秒數)。The WriteAction element also stores optional configuration details for the workflow, such as how many retries to perform if the workflow fails, how frequently to retry, and the maximum time in seconds that a workflow should run before it is shut off.

<WriteActions>
    <WriteAction ID="WA" TypeID="Subscriptions!Microsoft.EnterpriseManagement.SystemCenter.Subscription.WindowsWorkflowTaskWriteAction">
        <Subscription>
            <WindowsWorkflowConfiguration>
                <AssemblyName>SetActivityStatusToCompleteWF</AssemblyName>
                <WorkflowTypeName>WorkflowAuthoring.SetActivityStatusToCompleteWF</WorkflowTypeName>
                <WorkflowParameters>
                    <WorkflowParameter Name="ActivityId" Type="string">
                        $Data/BaseManagedEntityId$
                    </WorkflowParameter>
                </WorkflowParameters>
                <RetryExceptions></RetryExceptions>
                <RetryDelaySeconds>60</RetryDelaySeconds>
                <MaximumRunningTimeSeconds>300</MaximumRunningTimeSeconds>
            </WindowsWorkflowConfiguration>
        </Subscription>
    </WriteAction>
</WriteActions>

匯入管理元件Import the management pack

若要讓工作流程在特定 Service Manager 管理伺服器上執行,與工作流程相關的所有檔案都必須位於該伺服器上。For the workflow to run on a particular Service Manager management server, all of the files that are related to the workflow must reside on that server. 這些檔案包括下列各項:These files include the following:

  • WF 活動組件檔。The WF activity assembly files. 如果您只使用 Service Manager WF 活動,預設會安裝適當的檔案。If you are using only the Service Manager WF activities, by default, the appropriate files are installed. 如果您使用自訂活動,請參閱 如何安裝自訂活動元件If you are using custom activities, see How to Install a Custom Activity Assembly.

  • 工作流程組件檔,即本案例中的 SetActivityStatusToCompleteWF.dll。The workflow assembly file, in this case, SetActivityStatusToCompleteWF.dll. 您必須手動將這個檔案複製到 Service Manager management server。You must manually copy this file to the Service Manager management server.

  • 管理組件檔案,即本案例中的 Woodgrove.AutomatedActivity.AddComputerToGroupMP.xml。The management pack file, in this case, Woodgrove.AutomatedActivity.AddComputerToGroupMP.xml. 您必須手動將這個檔案複製到 Service Manager management server。You must manually copy this file to the Service Manager management server.

當所有檔案都已準備就緒後,請將管理元件匯入 Service Manager。When all of the files are in place, import the management pack into Service Manager. 您可以使用 mpimport.exe 命令列工具或 Service Manager 主控台來完成這項作業。You can do this by using the mpimport.exe command-line tool or the Service Manager console. 匯入管理組件之後,工作流程便已準備就緒,只要符合其定義的觸發條件,工作流程就會執行。After you have imported the management pack, the workflow is ready to run whenever the condition that is defined as its trigger is met.

後續步驟Next steps