使用程式碼處理雲端流程

所有流程都會儲存在 Dataverse 中,您可以使用 Dataverse SDK for .Net 或 Web API 來管理它們。

本文包含管理納入在 Power Automate 解決方案索引標籤上的流程。 目前,程式碼不支援管理我的流程底下的流程。

與 Dataverse API 互動

Dataverse 使用 Dataverse SDK for .NET 或 WEB API 提供相同的功能。

我該使用哪種方法?

最好的方法取決於專案技術和您擁有的技能。

如果您的專案使用 .NET,我們建議使用 SDK。 SDK 透過提供類型化物件模型和驗證方法,來簡化您的開發體驗。

其他資訊:使用組織服務

如何連線?

連線方法取決於您使用的是 Dataverse SDK for .NET 或 Web API。

如果是 SDK,您必須與用戶端應用程式連線,才能存取 IOrganizationService 執行個體。 IOrganizationService 是一種介面,提供可用於與 Dataverse 互動的方法。

其他資訊:

工作流程資料表

雲端流程會儲存在程序 (工作流程) 資料表中,該表在 Web API 中表示為工作流程 EntityType

下表描述了工作流程資料表中的重要資料行:

邏輯名稱 類型​ 描述:
category 選擇 流程的類別。 以下是其他類別。
0 - 傳統 Dataverse 工作流程。
1 - 傳統 Dataverse 對話方塊。
2 - 商務規則。
3 - 傳統 Dataverse 動作。
4 - 商務程序流程。
5 - 新式流程 (自動化流程、即時流程或預定流程)。
6 - 桌面流程。
clientdata 字串 流程定義及其 connectionReferences 的字串編碼 JSON。
createdby 查閱 建立流程的使用者。
createdon 日期時間 流程的建立日期。
description 字串 使用者提供的流程描述。
ismanaged Bool 指出流程是否透過受控解決方案安裝。
modifiedby 查閱 最後更新流程的使用者。
modifiedon 日期時間 流程上次更新的時間。
name 字串 您為流程指定的顯示名稱。
ownerid 查閱 擁有流程的使用者或團隊。
statecode 選擇 流程的狀態。 狀態可以是:
0 - 草稿 (關閉)
1 - 已啟用 (開啟)
2 - 已暫停。
type 選擇 指出流程執行的是流程,或是可用來建立更多流程的範本。
1 - 定義,
2 - 啟用
3 - 範本。
workflowid GUID 雲端流程在所有匯入當中的唯一識別碼。
workflowidunique GUID 這項流程安裝的唯一識別碼。

注意

如果是 Web API 時,查詢值是單一值的導覽屬性,可以展開這些屬性以取得相關記錄的詳細資料。

查詢資料行也有對應的 GUID 查詢屬性,其可用於查詢中。 查詢屬性具有此命名慣例:_<logical name>_value。 對於 Web API 中的工作流程 EntityType,您可以參考以下查詢屬性:_createdby_value_modifiedby_value_ownerid_value

列出流程

若要擷取雲端流程清單,您可以查詢工作流程資料表。 以下查詢會傳回目前「開啟」的第一個自動化流程、即時流程或預定流程:

這種靜態 OutputFirstActiveFlow 方法需要經過驗證的用戶端來實施 IOrganizationService。 它使用 IOrganizationService.RetrieveMultiple 方法。

/// <summary>
/// Outputs the first active flow
/// </summary>
/// <param name="service">Authenticated client implementing the IOrganizationService interface</param>
public static void OutputFirstActiveFlow(IOrganizationService service)
{
   var query = new QueryExpression("workflow")
   {
         ColumnSet = new ColumnSet("category",
                                    "createdby",
                                    "createdon",
                                    "description",
                                    "ismanaged",
                                    "modifiedby",
                                    "modifiedon",
                                    "name",
                                    "ownerid",
                                    "statecode",
                                    "type",
                                    "workflowid",
                                    "workflowidunique"),
         Criteria = new FilterExpression(LogicalOperator.And)
         {
            Conditions = {
            {  new ConditionExpression(
               "category",
                     ConditionOperator.Equal,
                     5) }, // Cloud Flow
            {  new ConditionExpression(
                     "statecode",
                     ConditionOperator.Equal,
                     1) } // Active
         }
         },
         TopCount = 1 // Limit to one record
   };

   EntityCollection workflows = service.RetrieveMultiple(query);

   Entity workflow = workflows.Entities.FirstOrDefault();

   Console.WriteLine($"category: {workflow.FormattedValues["category"]}");
   Console.WriteLine($"createdby: {workflow.FormattedValues["createdby"]}");
   Console.WriteLine($"createdon: {workflow.FormattedValues["createdon"]}");
   // Description may be null
   Console.WriteLine($"description: {workflow.GetAttributeValue<string>("description")}");
   Console.WriteLine($"ismanaged: {workflow.FormattedValues["ismanaged"]}");
   Console.WriteLine($"modifiedby: {workflow.FormattedValues["modifiedby"]}");
   Console.WriteLine($"modifiedon: {workflow.FormattedValues["modifiedon"]}");
   Console.WriteLine($"name: {workflow["name"]}");
   Console.WriteLine($"ownerid: {workflow.FormattedValues["ownerid"]}");
   Console.WriteLine($"statecode: {workflow.FormattedValues["statecode"]}");
   Console.WriteLine($"type: {workflow.FormattedValues["type"]}");
   Console.WriteLine($"workflowid: {workflow["workflowid"]}");
   Console.WriteLine($"workflowidunique: {workflow["workflowidunique"]}");
}

若要擷取更多的記錄,請移除 TopCount 限制。

輸出

category: Modern Flow
createdby: SYSTEM
createdon: 5/20/2020 9:37 PM
description:
ismanaged: Unmanaged
modifiedby: Kiana Anderson
modifiedon: 5/6/2023 3:37 AM
name: When an account is updated -> Create a new record
ownerid: Monica Thomson
statecode: Activated
type: Definition
workflowid: d9e875bf-1c9b-ea11-a811-000d3a122b89
workflowidunique: c17af45c-10a1-43ca-b816-d9cc352718cf

其他資訊:

建立雲端流程

自動化流程、即時流程和預定流程的必要屬性有:categorynametypeprimaryentityclientdata。 對於這些類型的流程,請在 primaryentity 使用 none

這種靜態方法需要經過驗證的用戶端來實施 IOrganizationService。 它使用 IOrganizationService.Create 方法。

/// <summary>
/// Creates a cloud flow
/// </summary>
/// <param name="service">Authenticated client implementing the IOrganizationService interface</param>
/// <returns>The workflowid</returns>
public static Guid CreateCloudFlow(IOrganizationService service)
{
   var workflow = new Entity("workflow")
   {
         Attributes = {
            {"category", new OptionSetValue(5) }, // Cloud flow
            {"name", "Sample flow name"},
            {"type", new OptionSetValue(1) }, //Definition
            {"description", "This flow reads some data from Dataverse." },
            {"primaryentity", "none" },
            {"clientdata", "{\"properties\":{\"connectionReferences\":{\"shared_commondataserviceforapps\":{\"impersonation\":{},\"runtimeSource\":\"embedded\",\"connection\":{\"name\":\"shared-commondataser-114efb88-a991-40c7-b75f-2693-b1ca6a0c\",\"connectionReferenceLogicalName\":\"crdcb_sharedcommondataserviceforapps_109ea\"},\"api\":{\"name\":\"shared_commondataserviceforapps\"}}},\"definition\":{\"$schema\":\"https://schema.management.azure.com/providers/Microsoft.Logic/schemas/2016-06-01/workflowdefinition.json#\",\"contentVersion\":\"1.0.0.0\",\"parameters\":{\"$connections\":{\"defaultValue\":{},\"type\":\"Object\"},\"$authentication\":{\"defaultValue\":{},\"type\":\"SecureObject\"}},\"triggers\":{\"manual\":{\"metadata\":{\"operationMetadataId\":\"76f87a86-89b3-48b4-92a2-1b74539894a6\"},\"type\":\"Request\",\"kind\":\"Button\",\"inputs\":{\"schema\":{\"type\":\"object\",\"properties\":{},\"required\":[]}}}},\"actions\":{\"List_rows\":{\"runAfter\":{},\"metadata\":{\"operationMetadataId\":\"9725b30f-4a8e-4695-b6fd-9a4985808809\"},\"type\":\"OpenApiConnection\",\"inputs\":{\"host\":{\"apiId\":\"/providers/Microsoft.PowerApps/apis/shared_commondataserviceforapps\",\"connectionName\":\"shared_commondataserviceforapps\",\"operationId\":\"ListRecords\"},\"parameters\":{\"entityName\":\"accounts\",\"$select\":\"name\",\"$top\":1},\"authentication\":\"@parameters('$authentication')\"}}}}},\"schemaVersion\":\"1.0.0.0\"}" }
         }
   };

   return service.Create(workflow);
}

其他資訊: 使用組織服務建立資料表資料列

以這種方式建立之所有流程的 statecode 都會設定為 0 (「草稿」或「關閉」)。 必須先啟用該流程才能使用。

最重要的屬性是 clientdata,其中包含流程所使用的 connectionReferences,以及流程的定義connectionReferences 是流程所使用的各連線對應。

{
  "properties": {
    "connectionReferences": {
      "shared_commondataserviceforapps": {
        "runtimeSource": "embedded",
        "connection": {},
        "api": { 
         "name": "shared_commondataserviceforapps" 
         }
      }
    },
    "definition": {
      "$schema": "https://schema.management.azure.com/providers/Microsoft.Logic/schemas/2016-06-01/workflowdefinition.json#",
      "contentVersion": "1.0.0.0",
      "parameters": {
        "$connections": { "defaultValue": {}, "type": "Object" },
        "$authentication": { "defaultValue": {}, "type": "SecureObject" }
      },
      "triggers": {
        "manual": {
          "metadata": {},
          "type": "Request",
          "kind": "Button",
          "inputs": {
            "schema": { "type": "object", "properties": {}, "required": [] }
          }
        }
      },
      "actions": {
        "List_rows": {
          "runAfter": {},
          "metadata": {},
          "type": "OpenApiConnection",
          "inputs": {
            "host": {
              "apiId": "/providers/Microsoft.PowerApps/apis/shared_commondataserviceforapps",
              "connectionName": "shared_commondataserviceforapps",
              "operationId": "ListRecords"
            },
            "parameters": {
              "entityName": "accounts",
              "$select": "name",
              "$top": 1
            },
            "authentication": "@parameters('$authentication')"
          }
        }
      }
    }
  },
  "schemaVersion": "1.0.0.0"
}

更新雲端流程

若要更新流程,請只設定要變更的屬性。

這種靜態方法需要經過驗證的用戶端來實施 IOrganizationService。 它會使用 IOrganizationService.Update 方法來更新流程描述,並設定負責人。

/// <summary>
/// Updates a cloud flow
/// </summary>
/// <param name="service">Authenticated client implementing the IOrganizationService interface</param>
/// <param name="workflowid">The ID of the flow to update.</param>
/// <param name="systemuserid">The id of the user to assign the flow to.</param>
public static void UpdateCloudFlow(IOrganizationService service, Guid workflowid, Guid systemuserid) {

   var workflow = new Entity("workflow",workflowid)
   {
         Attributes = {

            {"description", "This flow will ensure consistency across systems." },
            {"ownerid", new EntityReference("systemuser",systemuserid)},
            {"statecode", new OptionSetValue(1) } //Turn on the flow.
         }
   };

   service.Update(workflow);
}

其他資訊:使用組織服務 > 基本更新更新與刪除資料表資料列

刪除雲端流程

以下範例說明如何刪除代表雲端流程的工作流程記錄。

靜態 DeleteCloudFlow 方法會刪除工作流程記錄。

/// <summary>
/// Deletes a workflow
/// </summary>
/// <param name="service">Authenticated client implementing the IOrganizationService interface</param>
/// <param name="workflowId">The id of the cloud flow to delete.</param>
public static void DeleteCloudFlow(IOrganizationService service, Guid workflowId) { 

service.Delete(entityName:"workflow",id: workflowId);

}

其他資訊:使用 SDK 刪除記錄

取得共用雲端流程的所有使用者

使用 RetrieveSharedPrincipalsAndAccess 訊息來取得與雲端流程共用的所有使用者清單。

如果是 SDK,請使用 RetrieveSharedPrincipalsAndAccessRequest 類別,如果是 Web API,則使用 RetrieveSharedPrincipalsAndAccess 函式

其他資訊:取得有權存取記錄的主體

共用或取消共用雲端流程

使用 GrantAccess 訊息,像其他 Dataverse 記錄一樣共用雲端流程。 如果是 SDK,請使用 GrantAccessRequest 類別,如果是 Web API,則使用 GrantAccess 動作。 其他資訊:GrantAccess 範例

如果您想要在共用記錄時變更所授與的存取權限,請使用 ModifyAccess 訊息。 如果是 SDK,請使用 ModifyAccessRequest 類別,如果是 Web API,則使用 ModifyAccess 動作。 其他資訊:ModifyAccess 範例

若要取消共用記錄,請使用 RevokeAccess 訊息。 如果是 SDK,請使用 RevokeAccessRequest 類別,如果是 Web API,則使用 RevokeAccess 動作。 其他資訊:撤銷存取權

匯出流程

當流程是解決方案的一部分時,您可以透過使用 ExportSolution 訊息匯出包含流程的解決方案來匯出它。

下方的靜態 ExportSolution 範例方法使用 ExportSolutionRequest 擷取包含具有指定 UniqueName 的非受控解決方案 ZIP 檔案的 byte[]

/// <summary>
/// Exports an unmanaged solution
/// </summary>
/// <param name="service">Authenticated client implementing the IOrganizationService interface</param>
/// <param name="solutionUniqueName">The uniquename of the solution.</param>
/// <returns></returns>
public static byte[] ExportSolution(
   IOrganizationService service, 
   string solutionUniqueName) 
{
   ExportSolutionRequest request = new() { 
         SolutionName = solutionUniqueName,
         Managed = false
   };

   var response = (ExportSolutionResponse)service.Execute(request);

   return response.ExportSolutionFile;
}

匯入流程

當您有解決方案 ZIP 檔案時,可以使用 ImportSolution 訊息將其匯入。

當您匯入流程時,應設定下列參數:

屬性名稱 描述:
OverwriteUnmanagedCustomizations 如果 Dataverse 中的流程已經有執行個體,則必須將此旗標設定為 true,才能將其匯入。 否則,將不會進行覆寫。
PublishWorkflows 指出傳統 Dataverse 工作流程是否會在匯入時啟用。 這項設定不適用於其他類型的流程。
CustomizationFile base 64 編碼的 zip 檔案,包含解決方案。

靜態 ImportSolution 範例方法說明如何使用 ImportSolutionRequest 類別匯入解決方案檔案

/// <summary>
/// Imports a solution.
/// </summary>
/// <param name="service">Authenticated client implementing the IOrganizationService interface</param>
/// <param name="solutionFile">The byte[] data representing a solution file. </param>
public static void ImportSolution(
   IOrganizationService service, 
   byte[] solutionFile) {

   ImportSolutionRequest request = new() { 
         OverwriteUnmanagedCustomizations = true,
         CustomizationFile = solutionFile
   };

   service.Execute(request);
}

另請參閱

使用組織服務的實體類別作業
使用 Web API 執行作業
共用與指派
驗證程式程式碼中的存取
使用 Dataverse SDK 使用解決方案