Share via


코드를 사용하여 클라우드 흐름 작업

모든 흐름은 Dataverse에 저장되며 .NET용 Dataverse SDK 또는 웹 API를 사용하여 흐름을 관리할 수 있습니다.

이 문서에서는 Power Automate의 솔루션 탭에 포함된 흐름을 관리하는 방법을 다룹니다. 현재 내 흐름 아래의 흐름 관리는 코드에서 지원되지 않습니다.

Dataverse API와 상호 작용

Dataverse는 .NET용 Dataverse SDK 또는 웹 API를 사용하여 동등한 기능을 제공합니다.

어떤 방법을 사용해야 합니까?

가장 좋은 방법은 프로젝트 기술과 보유한 기술에 따라 다릅니다.

프로젝트에서 .NET을 사용하는 경우 SDK를 사용하는 것이 좋습니다. SDK는 형식화된 개체 모델과 인증 방법을 제공하여 개발 환경을 단순화합니다.

추가 정보: 조직 서비스 사용

어떻게 연결하나요?

연결 방법은 .NET용 Dataverse SDK 또는 웹 API 중 어떤 것을 사용하는지에 따라 다릅니다.

SDK를 사용하여 IOrganizationService 인스턴스에 액세스하려면 클라이언트 애플리케이션과 연결해야 합니다. IOrganizationService는 Dataverse와 상호 작용하는 데 사용할 수 있는 메서드를 제공하는 인터페이스입니다.

추가 정보:

워크플로 테이블

클라우드 흐름은 웹 API에서 워크플로 EntityType으로 표시되는 프로세스(워크플로) 테이블에 저장됩니다

다음 표에서는 워크플로우 테이블의 중요한 열에 대해 설명합니다.

논리적 이름 Type Description
category 선택 항목 흐름의 범주입니다. 다음은 다양한 카테고리입니다.
0 - 클래식 Dataverse 워크플로.
1 - 클래식 Dataverse 대화 상자.
2 - 비즈니스 규칙.
3 - 클래식 Dataverse 작업.
4 - 비즈니스 프로세스 흐름.
5 - 최신 흐름(자동화된, 인스턴트 또는 예약된 흐름).
6 - 데스크톱 흐름.
clientdata String 흐름 정의 및 해당 connectionReferences의 문자열 인코딩 JSON입니다.
createdby Lookup 흐름을 만든 사용자입니다.
createdon 날짜/시간 흐름이 만들어진 날짜입니다.
description String 흐름의 사용자가 제공한 설명입니다.
ismanaged Bool 관리 솔루션을 통해 흐름을 설치했는지를 나타냅니다.
modifiedby Lookup 흐름을 업데이트한 마지막 사용자입니다.
modifiedon 날짜/시간 흐름을 마지막으로 업데이트한 시간입니다.
name String 사용자가 흐름을 지정한 표시 이름입니다.
ownerid Lookup 흐름을 담당하는 사용자 또는 팀입니다.
statecode 선택 항목 흐름의 상태입니다. 상태는 다음과 같습니다.
0 - 초안(끄기)
1 - 활성화됨(켜기)
2 - 일시 중단됨.
type 선택 항목 흐름이 실행되는 흐름인지 아니면 추가 흐름을 만드는 데 사용할 수 있는 템플릿인지를 나타냅니다.
1 - 정의,
2 - 활성화
3 - 템플릿.
workflowid GUID 모든 가져오기에서 클라우드 흐름에 대한 고유 식별자입니다.
workflowidunique GUID 흐름을 설치하기 위한 고유 식별자입니다.

노트

웹 API에서 조회 값은 관련 레코드에서 세부 정보를 가져오도록 확장할 수 있는 단일 값 탐색 속성입니다.

조회 열에는 쿼리에 사용할 수 있는 해당 GUID 조회 속성도 있습니다. 조회 속성에는 _<logical name>_value와 같은 명명 규칙이 있습니다. 웹 API의 워크플로 엔터티 유형에 대해 _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

추가 정보:

클라우드 흐름 만들기

자동화된, 인스턴트 및 예약된 흐름에 대한 필수 속성은 category, name, type, primaryentityclientdata입니다. 이러한 유형의 흐름에 대해 primaryentitynone을 사용합니다.

이 정적 메서드에는 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 클래스를 사용하고 웹 API에서는 RetrieveSharedPrincipalsAndAccess 함수를 사용합니다.

추가 정보: 레코드에 액세스할 수 있는 보안 주체 가져오기

흐름 공유 또는 공유 해제

GrantAccess 메시지를 사용하여 다른 Dataverse 레코드와 같은 클라우드 흐름을 공유합니다. SDK에서는 GrantAccessRequest 클래스를 사용하고 웹 API에서는 GrantAccess Action을 사용합니다. 추가 정보: GrantAccess 예시

레코드를 공유할 때 부여한 액세스 권한을 변경하려면 ModifyAccess 메시지를 사용하십시오. SDK에서는 ModifyAccessRequest 클래스를 사용하고 웹 API에서는 ModifyAccess Action을 사용합니다. 추가 정보: ModifyAccess 예시

레코드 공유를 해제하려면 RevokeAccess 메시지를 사용하십시오. SDK에서는 RevokeAccessRequest 클래스를 사용하고 웹 API에서는 RevokeAccess Action을 사용합니다. 추가 정보: 액세스 취소

흐름 내보내기

흐름이 솔루션의 일부인 경우 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 메시지를 사용하여 가져올 수 있습니다.

흐름을 가져올 때 다음 매개 변수를 설정해야 합니다.

Property name Description
OverwriteUnmanagedCustomizations Dataverse에 이러한 흐름의 기존 인스턴스가 없으면 이 플래그를 true로 설정하여 가져와야 합니다. 그렇지 않으면 덮어쓰지 않습니다.
PublishWorkflows 클래식 Dataverse 워크플로를 가져오기에서 활성화했는지 나타냅니다. 이 설정은 다른 형식의 흐름에 적용되지 않습니다.
CustomizationFile 솔루션을 포함하는 기본 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);
}

참조 항목

조직 서비스를 사용하는 엔터티 클래스 작업
웹 API를 사용하여 작업 수행
공유 및 할당
코드에서 액세스 확인
Dataverse SDK를 사용하여 솔루션 작업