Archive

Posts Tagged ‘Flow’

[Step by Step] Create and call Global Custom API from Canvas App using Power Automate with Error Handling

February 15, 2023 4 comments

In this article, lets learn how to create a Custom API and trigger using Power Automate Cloud Flow along with Error Handling from a Canvas App.

What is a Custom API:

  • Using Custom APIs we can create our own APIs in Dataverse.
  • We can consolidate one or more operations into a Custom API which can called from either code or from Power Automate.
  • For example, you can create a Custom API called “OnBoardNewCustomer’, where you can have following operations.
    • Create a new ‘Account’ record.
    • Create a new ‘Appointment’ record scheduled a week from now.
    • Send an Email notification.

Now lets get started with Custom API creation. I am going to use ‘Onboard Customer’ scenario to explain the Custom API creation. I will be using 2 operation in my Custom API.

  • Create an Account record by reading ‘Name’ as input parameter.
  • Create an Appointment record for the newly created Account and schedule at 7 days from now.

Create a Custom API:

There are several ways you can create a custom API documented here. In this article, I will be taking 2 step approach.

  • Write a C# plugin class file with logic and register using Plugin Registration Tool (PRT).
  • Create a Custom API using forms from Power Apps Maker portal and link the plugin created in previous step.

Steps to create Custom API in plugin class and register using PRT:
  • Open Visual Studio and create a plug-in project as detailed in this document here.
  • Add an .snk file to the project.
  • Create a new plugin class file with logic to create Account and Customer.

  • Final code in the class file looks as below.
        public void Execute(IServiceProvider serviceProvider)
        {
            var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

            if (context.MessageName.Equals("cat_onboardcustomer") && context.Stage.Equals(30))
            {
                try
                {
                    // Read the input parameter
                    string inputParamCustomerName = (string)context.InputParameters["cat_customername"];

                    if (!string.IsNullOrEmpty(inputParamCustomerName))
                    {
                        IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                        IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

                        // Create Account Record
                        var entAccount = new Entity("account");
                        entAccount["name"] = inputParamCustomerName;
                        var accountId = service.Create(entAccount);

                        // Create Appointment Record
                        var entAppointment = new Entity("appointment");
                        entAppointment["subject"] = $"Meeting with Customer {inputParamCustomerName}";
                        // Set the start and end times for the entAppointment 7 days fro now
                        entAppointment["scheduledstart"] = DateTime.Now.AddDays(7).AddHours(1);
                        entAppointment["scheduledend"] = DateTime.Now.AddDays(7).AddHours(2);
                        // Set the related account for the entAppointment
                        entAppointment["regardingobjectid"] = new EntityReference("account", accountId);
                        var appointmentId = service.Create(entAppointment);
                    }
                }
                catch (Exception ex)
                {
                    throw new InvalidPluginExecutionException("An error occurred in cat_onboardcustomer.", ex);
                }
            }
        }
  • Build the project and register the plugin assembly using PRT.
  • Post registration it should look as below from PRT.

Now that we completed the step 1 of creating and registering plug-in class file. Lets proceed with step 2 where we will create a Custom API entry.

Create a Custom API using forms from Power Apps Maker portal:
  • Connect to Power Apps maker portal.
  • Create a new solution or open any existing solution.
  • Click on New -> More -> Other -> Custom API
  • It opens up a new ‘Custom API’ form and fill the details.
    • To understand the columns in depth, refer here.
    • What is important for this example are:
      • Unique Name : Unique name for the custom API. (Its cat_onboardcustomer we used in our plug-in class)
      • Name : The primary name of the custom API.
      • Plugin Type : Plugin we registered in previous section.
  • Save and Close.
  • As we need to pass a parameter to our ‘Custom API’, next add a new ‘Custom API Request Parameter’.
  • Fill the details by selecting ‘Custom API’ we created in previous step and ‘Unique Name’ as cat_customername, which we used in our plugin class.
  • Save and Close.

With this we successfully created ‘Custom API’ along with an input parameter. Lets see how to trigger API using Power Automate Cloud Flow from a Canvas App.

Steps to trigger Custom API from Canvas App:

  • Create a new Canvas App.
  • Go to Flows tab and click on ‘Create new flow’ and choose ‘Create from blank’.
  • In the flow designer, add ‘Initialize Variable’ action and rename to ‘varCustomerName’. In the ‘Value’ select ‘Ask in PowerApps’.
  • Next add Dataverse ‘Perform an unbound action‘ action which helps us to trigger our ‘Global’ custom API.
    • Select ‘Action Name’ as our Custom API name cat_onboardcustomer
    • In the cat_customername pass ‘Customer Name’ which was the variable declared in above step.
  • If you dont want exception handling, you can save the flow which can trigger the cat_onboardcustomer.

Exception Handling:

Lets learn a basic error handling. Please note that you can use ‘Scope’ for more complex scenarios but for basic exception handling following process should suffice.

  • Add another ‘Initialize Variable’ action and rename it to ‘varExceptionDetails’ and set Type as ‘String’.
  • Rename the ‘Perform an unbound action’ to ‘InvokeOnboardAPI’
  • Add a ‘Set Variable’ action ‘setExceptionDetails’ to capture the exception.
  • Select the Name as ‘ExceptionDetails‘ and click on ‘Configure run after’. (This is needed as we want this ‘setExceptionDetails’ to execute even the above ‘InvokeOnboardAPI’ action fails or timeout.
  • Select following options.
  • In the ‘Value’ select ‘Expression’ and paste following expression.
    • actions(‘InvokeOnboardAPI’)?[‘outputs’]?[‘body’]?[‘error’]
  • Finally to send the response from flow to Canvas app, add ‘Respond to a PowerApp of flow’ action and click on ‘Configure run after’, select following options and click ‘Done’.
  • and define an output variable OnboardflowResponse and set the value as ExceptionDetails.
  • Save the flow and you should see the flow in your Canvas App.
  • To trigger the flow, add a button to the screen and OnSelect write following formula.
Notify("Triggering User Onboard...");
UpdateContext({ResponseOnBoardFlow: CustomerOnboardFlow.Run("Rajeev Pentyala").onboardflowresponse});
If(
    ResponseOnBoardFlow = "Success",
    Notify("Customer onboarded successfully."),
    Notify("Error while onboarding. Details - " & ResponseOnBoardFlow)
)

  • Run the App and click the button.
  • Open Dataverse and you should see the new Account and Appointment records. You can also check the flow run history.

🙂

Advertisement

Power Apps | Change App Owner using Power Automate Flow

November 4, 2022 2 comments

Assume that you have a canvas app with Owner as ‘User 1’ and you would want to make ‘User 2’ as Owner of the App.

We have couple of options.

In this article lets see how to use Power Automate Flow to change the Owner. Following is how the completed flow looks like.

Key in this flow is ‘Set App Owner’ Action and following are the parameters.

NameKeyRequiredTypeDescription
Environment NameenvironmentTruestringName field of the Environment.
PowerApp NameappTruestringName field of the PowerApp.
API Versionapi-versionstringThe date value of the API version.
Content TypeContent-TypestringThe content type of the API request.
Role For Old App OwnerroleForOldAppOwnerstringThe role name for the old app owner. Choose from CanView, CanViewWithShare, or CanEdit.
New PowerApp OwnernewAppOwnerstringThe principal object ID of the new owner.

Lets see step by step process to build the flow.

Step by Step budling flow:

  • Create a new flow as shown below.
  • As mentioned, key component of this flow is ‘Set App Owner’ Action and in the next steps, we will see how to pass parameters to ‘Set App Owner’ Action.
  • First we need to capture the ‘New PowerApp Owner’ parameter which is ‘Principal object ID’ of the User.
    • Note: ‘Principal object ID’ is not GUID of ‘System User’ in Dataverse. Its Azure Active Directory ID.
  • Add a ‘Get user profile (V2)’ action of Office 365 Users connector to capture the ‘Principal object ID’ of the User.
  • Rename the ‘Get user profile (V2)’ to ‘GetUserProfile’. (Optional Step)
  • Set “User (UPN)” as the User Id of the new Owner.
  • Now add ‘Set App Owner’ action.
  • Set ‘New PowerApp Owner’ as ‘Id’ from the output of previous ‘GetUserProfile’ action.
  • For ‘Environment Name‘ parameter, go to Power Apps maker portal, open ‘Settings -> Developer resources’.
  • Copy ‘Environment ID’ and paste in ‘Environment Name‘ parameter of ‘Set App Owner’ action.
  • For ‘PowerApp Name‘ parameter, go to Power Apps maker portal, open ‘App -> Details’.
  • Copy the ‘App ID‘ and paste in ‘PowerApp Name’ parameter of ‘Set App Owner’ action.
  • For ‘Role For Old App Owner‘ parameter, either you can leave or provide ‘CanView’.
  • Leave ‘API Version‘ and ‘Content Type‘ as default.
  • You should see the flow as below once you follow all mentioned steps.
  • That’s all needed!. Run the flow and you should see the owner of the App to the new user mention in the flow.

🙂

Power Platform – Pass external API collection from Power Automate to Canvas App

February 9, 2020 2 comments

In this article, lets see how to pass an external API’s json collection from Power Automate(Formerly ‘Microsoft Flow’) to a Canvas application.

For this example, I am going to use ESRI  mapping service API, in my Power Automate Flow. Refer here to know more about ESRI. You may also use other APIs as per your convenience.

ESRI API is url based and returns the ‘Address Suggestions’ in json format.

Flow_Json_3

Before we start lets make sure to meet all the prerequisites.

Prerequisites:

  • Subscribe to 30 days trial and get Office 365 account.
  • Connect to Power Automate portal using Office 365 account to build Power Automate flow.
  • Connect to Power Apps maker portal using Office 365 account to build the Canvas App.
  • ESRI api URL – Refer my previous article on the usage of ESRI or you can simply use this url

Once all prerequisites are met, here is the high level design:

  • Create a new Power Automate flow and call ESRI API to fetch Address Suggestions.
    • You can take any open API which returns json collection.
  • Parse the ESRI API Response to json collection.
  • Create a new Canvas app
  • Trigger Power automate flow from Canvas App and read the collection.

Lets get started.

Steps to configure the Power Automate Flow:

  • Connect to Power Automate portal
  • Create a new ‘Instant flow’ by selecting the right Environment.

Flow_Json_1

  • Provide a name ‘GetAddressSuggestions’ and select trigger as ‘PowerApps’

Flow_Json_2

  • To call ESRI api, add a new ‘HTTP’ action.

Flow_Json_4

  • Choose Method as ‘GET’ and in URI paste the ESRI url as mentioned in prerequisite section.

Flow_Json_5

  • Next, we need to parse the response from ESRI api. As the ESRI results would be in json format, add ‘Parse JSON’ action.

Flow_Json_6

  • In ‘Parse JSON’ action,
    • set Content as ‘Body’ from HTTP action.
    • Next we need to provide the json schema of ESRI response. To do that, click on ‘Generate from sample’.
    • Flow_Json_9
    • Now copy the response from ESRI API (Copy the browser’s output using ctrl+a+copy)
    • Flow_Json_7
    • Paste in the ‘Insert a sample JSON Payload’ window and click ‘Done’.
    • Flow_Json_8
    • If no warnings, your ‘Parse JSON’ pane should look as below.
    • Flow_Json_10
  • As we completed the ESRI response capture and parsing to json, now we need to pass the captured json response to Power App.
  • To pass the json response to Power App, add a new ‘Response’ action.

Flow_Json_11

  • In the ‘Response’ pane,
    • Set the ‘Body’ to ‘Body’ from ‘Parse JSON’.
    • Flow_Json_12
    • Expand ‘Show advanced options’ and click on ‘Generate from sample’.
    • Copy the response from ESRI API and paste in the ‘Insert a sample JSON Payload’ window and click ‘Done’. (Same step like we did in ‘Parse JSON’ pane).
    • ‘Response’ pane should look as below with no warnings.
    • Flow_Json_13
  • Run the flow and make sure it ran successfully.

Flow_Json_18

Steps to configure the Canvas App:

As we completed the Power Auto Flow, now its time to consume the Power Automate flow response from Canvas App by following the steps below

  • Connect to Power Apps maker portal using the same Office 365 account.
  • Create a new Canvas App.
    • Note: Make sure the same Environment used for Power Automate is selected.
  • Add a new button.
  • Select the button, from the ribbon menu, click on ‘Action -> Power Automate’.
  • From the pane select the ‘GetAddressSuggestions’ Power app flow.

Flow_Json_14

  • After few seconds, you would see the Run() command auto populated as below.

Flow_Json_15

  • As we going to get json collection from flow, lets capture the json collection to a collection variable ‘collAddress’ using ‘ClearCollect()’. Refer article to know more about ‘ClearCollect()’.
  • With the ClearCollect() and Run() functions, the final ‘OnSelect’ statement should look as below.

Flow_Json_16

  • Lets run the App and click on the button. Application takes couple of minutes to complete the run.

Flow_Json_17

  • Post run, check the collection returned from flow by going to ‘File -> Collections’ tab.

Flow_Json_19

  • You can also add a ‘Data table’ control and display the results returned from flow as below

Flow_Json_20

🙂

 

D365 – Shifting from Dynamics Workflow to Power Automate flow

December 11, 2019 Leave a comment

First things first, Microsoft Flow is now Power Automate.

If you are either a dynamics developer or administrator, off late you might have noticed a flashing banner while creating new Process from Dynamics instance.

Flow_Scope_4

From the banner, its clear that Microsoft recommends ‘Power automate flows’ over conventional ‘Process’.

In this article, I am going to cover basics of following items, which helps you in decision making to some extent.

Lets get in to the details.

CDS connector vs Dynamics connector:

When you are creating a flow, you need to choose b/w CDS and Dynamics connector.

The key differentiation when switching from Dynamics ‘Process’ to ‘Flow’ is,

  • With CDS connector you can set ‘Scope’ and ‘Filter Attributes’ but not with Dynamics connector.

Lets understand this with an example.

Create a flow with CDS connector:

  • Connect to your Power automate portal
  • Click on ‘+ Create’ tab and choose ‘Automated flow’

Flow_Scope_16

  • In the new window, choose the ‘Common Data Service’ connector.

Flow_Scope_0

  • Under the ‘Triggers’, select ‘When a record is updated’ trigger.

Flow_Scope_2

  • If you notice, under ‘When a record is updated’, there are ‘Scope’ and ‘Attribute Filter’ options.
    • Scope : Scope decides the affected records up on flow execution. Get more details here.
    • Flow_Scope_1
    • Attribute Filter: If no filtering attributes are set flow will execute on every field updates. Add attribute filters to minimize flow execution, only on specified field updates.
    • Flow_Scope_3
  • Now add an action from the ‘Actions’ list. I’ve added a ‘Create a new record’ action.

Flow_Scope_17

Create a flow with Dynamics 365 connector:

  • Connect to your Power automate portal
  • Click on ‘+ Create’ tab and choose ‘Automated flow’
  • In the new window, choose the ‘Dynamics 365’ connector.

Flow_Scope_13

  • Under the ‘Triggers’, select ‘When a record is updated’ trigger.

Flow_Scope_14

  • This time, under ‘When a record is updated’ there are NO ‘Scope’ and ‘Attribute Filter’ options.

Flow_Scope_15

  • Which means, the flow will trigger on all field updates and there is no provision of ‘Attribute Filter’ in Dynamics 365 Connector.

Automated flow vs Instant flow (i.e., On-demand process):

One of the common questions from Admins is, how can they create an ‘On-demand’ power automate flow similar to conventional ‘On-demand’ workflow. The answer is Instant flow.

Lets see how to create a simple on-demand flow and run.

Create an Instant Flow:

  • Connect to your Power automate portal
  • Click on ‘+ Create’ tab and choose ‘Instant flow’
    • Note: You can also create ‘Instant flow’ from Dynamics application.
    • Go to the entity, from ‘Flow’ menu, click on ‘Create a flow’.

Flow_Scope_18

  • In the new window, choose the ‘Common Data Service’ connector.
  • Under the ‘Triggers’, select ‘When a record is selected’ trigger.
  • Select the ‘Environment’ and ‘Entity Name’
    • Environment: If you want your flow to always trigger based on an event in a specific environment, select that environment or Choose (Default), which will always use the database within the environment in which Power Automate runs.
  • Now add an action from the ‘Actions’ list. I’ve added a ‘Create a new record’ action.

Flow_Scope_8

  • In above screen, I am setting ‘Transaction Audit’ entities ‘Name’ field with concatenating ‘Transactions’ entities ‘Name’ and current date (i.e., utcNow()).
    • Use ‘Dynamic content’ window, to refer the values from Previous step.

Trigger Instant Flow:

  • Connect to Dynamics instance and open the record for which you have flow registered. In my case, my flow registered on ‘Transaction’ Entity.
  • From the ‘Flow’ menu, select your flow.

Flow_Scope_5.PNG

  • Click on ‘Run flow’

Flow_Scope_7

  • Make sure you got the success screen as below.

Flow_Scope_9

  • Now check whether the Action executed. In my example, I am creating a child record (i.e., Transaction Audit)

Flow_Scope_10

Formatting Dates:

If you would have noticed the previous screen, the ‘Name’ field of the ‘Transaction Audit’ was set to UTC date format.

To format the date to your choice, use formatDateTime function in your flow’s ‘Expression’.

Flow_Scope_11

Save and run the flow, you should see the formatted date as below.

Flow_Scope_12

Notes:

  • One more edge CDS connector over Dynamics connector is in terms of execution speed. More details

🙂

 

 

 

 

 

 

 

 

PowerApps – Create an ‘Account’ in Dynamics 365 from App using Flow

August 13, 2018 1 comment

If you are new to PowerApps, please go through my previous blog

In this post, lets build an App with an Account Form and create the record in Dynamics 365.

PA_Flow_5

Prerequisite:

  • You must have a PowerApps account. Refer blog for details.
  • Create a Microsoft Flow with logic to create an Account record in Dynamics 365
  • Build an App and trigger Flow

Steps to create Flow:

  • Login to PowerApps Portal
  • Navigate to Business Logic -> Flows -> Create from blank

PA_Flow_1

  • In the new Flow screen, Choose Action, select ‘Dynamics 365’

PA_Flow_7

  • Select ‘Create a new record’ from Actions.
  • Now we need to put place holders in the fields which we pass data from PowerApp.
  • To add a place holder to ‘Account Name’ field, select the field, in ‘Dynamics content’ window, click on ‘Ask in PowerApps‘ button.
    • A new place holder will get added to ‘Account Name’ field.

PA_Flow_2

  • I repeated the above step for ‘Main Phone’ and ‘Description’ fields.

PA_Flow_3

  • Rename the Flow to CreateAccount and Save

Invoke Flow from PowerApp:

  • To know, how to create a new App and add controls to form, refer my earlier blog
  • To trigger the Flow, select the ‘Create’ button, go to ‘Action -> Flows’
  • From the ‘Data’ window, select the flow created in above section (i.e.,CreateAccount)

PA_Flow_4

  • On ‘OnSelect’ event of button, trigger the Flow ‘CreateAccount’ by calling ‘Run’ method and passing the 3 placeholder parameters.
    • CreateAccount.Run(txtName.Text,txtDesc.Text,txtMobile.Text)
  • Thats it, now its time to test the App

Test the App:

  • Press F5
  • Set the values and click ‘Create’

PA_Flow_5

  • Open the D365 App and you should see new ‘Account’ record.

PA_Flow_6

Refer my earlier article to build an App using Excel as Data Source.

🙂