コードを使用してクラウド フローを使用する

すべてのフローは 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 で workflow EntityType として表される プロセス (Workflow) テーブル に格納されます

次の表では、ワークフロー テーブルの重要な列について説明します:

論理名 タイプ Description
category 選択肢 フローのカテゴリ。 さまざまなカテゴリがあります。
0 - クラシック Dataverse ワークフロー。
1 - クラシック Dataverse ダイアログ。
2 - ビジネス ルール。
3 - クラシック Dataverse アクション。
4 - ビジネス プロセス フロー。
5 - モダン フロー (自動化フロー、インスタント フロー、予定フロー)。
6 - デスクトップ フロー。
clientdata String フロー定義とその connectionReferences の文字列エンコードされた JSON。
createdby 参照 フローを作成したユーザー。
createdon DateTime フローが作成された日付。
description String ユーザーが指定したフローの説明。
ismanaged Bool フローが管理ソリューションを介してインストールされたかどうかを示します。
modifiedby 参照 フローを最後に更新したユーザー。
modifiedon DateTime フローの最終更新日時。
name String フローに付けた表示名。
ownerid 参照 フローを所有するユーザーまたはチーム。
statecode 選択肢 フローの状態。 ステータスは、次のいずれかになります:
0 - 下書き (オフ)
1 - アクティブ化 (オン)
2 - 中断。
type 選択肢 フローが実行中のフローか、さらにフローを作成するために使用できるテンプレートかを示します。
1 - 定義
2 - アクティブ化
3 - テンプレート。
workflowid GUID すべてのインポート全体でのクラウド フローの一意識別子。
workflowidunique GUID フローのこのインストールの一意識別子。

注意

Web API では、検索値は 単一値のナビゲーション プロパティ で、関連レコードから詳細を取得するために展開することができます。

検索列には、クエリで使用できる、対応する GUID 検索プロパティ もあります。 検索プロパティには、次の命名規則があります: _<logical name>_value。 Web API の workflow EntityType については、次の検索プロパティを参照できます: _createdby_value_modifiedby_value_ownerid_value

フローの一覧表示

クラウド フローのリストを取得するには、ワークフロー テーブルをクエリできます。 次のクエリは、現在 'on' である最初の自動化フロー、インスタント フロー、または予定フローを返します。

この静的 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 制限を削除します。

Output

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);
}

詳細: 組織サービスを使用したテーブル行の作成

この方法で作成されたすべてのフローの statecode0 (下書き、または 'オフ') に設定されます。 フローは使用する前に、有効にする必要があります。

最も重要なプロパティは、フローが使用する connectionReferences が含まれている clientdata と、フローの 定義 です。 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 Class クラス を使用し、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 メッセージを使用してインポートできます。

フローをインポートするときは、次のパラメーターを設定する必要があります:

プロパティ名 Description
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 を使用してソリューションを操作する