MS Power Automate : Act on Approvals directly from Dynamics CRM on column value change/Button click

What is Issue?

There are lots of business scenarios where the approval requires on the records before proceeding or pushing it to next levels or complete the process. For these scenarios now we have the Power Automate Approvals. When approvals are triggered, it goes to the approvers mailbox to approve it, then approver can happily act on it without navigating to the other systems. But in some cases, Approver gets lots of the approval requests and he need to check each request by navigating to the system. After checking the approval again he need to switch the screen and approve it from mailbox. Now the frustrated approver says, “I can see all my requested records in system directly, I don’t want to go back to the mailbox again!!” and he/she will ask you “is it possible to approve the request from the system only?”

The Reason-

It is easier to act on approval from email which is very quick and easy process. But how the approval action works in power automate is something not explored. So I can say less exposure to the Approval tables in Dataverse.

Solution-

Power Automate provides Approval actions. Once you add it on your flow, system automatically installs some solutions containing approval tables and components in your selected environment(instance).

First lets have look at these tables-

  1. Approval – contains the Approval details
  2. Approval Request – contains the information of who requested and who is approver
  3. Approval response – contains the information about approval responses
  4. Flow Approval – contains the Approval action details which is used in actual power automate flow

In the case where you have to mark the approvals complete and resume the approval flow, you have to look for Approval table and Flow Approval table.

Lets see an example of flow-

I am using column on Account form to act (approve/reject) the approval for the account without using my mailbox to approve the request.

On change of Approval Status column value my approval action should be tracked and flow should be proceed as per my response. On completion of the request I should receive the mail saying approval succeeded or approval rejected.

This is how my approval flow looks like- I am manually triggering the approval for the demo purpose.

When I ran this create Approval Flow I received below approval request on my mailbox with the account URL in link in it.

Let’s see the another flow which will trigger when I update Approval Status column value.

Next step will be finding the correct approval record based on Account ID. So as I mentioned I have added the Item Link to the approval with record id, so I can query the approval where Item Link contains the account id for which flow is triggered. Just for the information you can see the Approval table column which I am using for this purpose-

So next step on my flow is to list the rows from Approval table where linked item contains account id and pending for approval-

Once I got the response then I can find the Flow approvals associated with the Approval record and from this Flow Approval row “Flow Notification URI” column value is the useful URL for me to send the response to the approval request.

Before sending the response to Approval flow using Flow Notification URL, I am making sure the my Approval is completed, so that it will not keep waiting for my response even we completed the approval flow. So I am setting status reason to Completed, Stage to Complete, Result with the Approval status label value(optional) and Status as inactive.

Before sending response to the Approval using “Flow Notification URI”, we need to prepare some json body. It accepts any key value pair, but I am making sure that I am preparing the response similar to the json structure when we approve the request from email request. Once response body is prepared, I am sending the post request to the “Flow Notification URI” with composed json body.

So my completed flow looks like below-

My flow is ready for testing-

When I am approving/ rejecting the request , My approval flow is resumed and completed, and I received mail as per my action –

When I navigated to the Approval request in my mailbox, It is showing that Others have already completed this request. Yay!!!… it worked.

So that’s it.

You can change the trigger of flows according to your requirement. For button click – change it to HTTP trigger and pass the required information on click of buttons.

Hope this will help…
Enjoy Ms CRM!!!

Follow on Facebook- FB: MSCRM16Tech

MS Power Automate : Exception handling with Try-Catch-Finally

What is Issue?

MS providing all new ways to develop the application and moving to the less-code implementations. For implementing quick asynchronous logics, MS introduced Power Automate for more than hundred of the products. With traditional coding, developer knows how to implement exception handling. But what about power automate?

The Reason-

Every complex logic is exception prone and implementing it with traditional coding way, it is easy to handle with try-catch-finally in code. We need to understand the exception handling in Power Automate.

Solution-

Power Automate provides many actions and configurations, which we can use to implement Try-Catch-Finally. Lets see-

Example- I am using Account field to check how many times account name is updated. Every time when account is updated, need to send the email notification, in both the cases when name update is failed or success.

We need 3 control -> Scope, each with name – Try, Catch and Finally

Add business logic into the Try block. Variable initialization is not allowed in the Scope control, so you need to initialize all variables at the top of the Try block only.

Configure Catch block to run after “Try” only if “Try” block Failed, or Timed-out.

Configure Finally block to run after “Catch” if “Catch” block Failed, Successful, Timed-out or Skipped

Add logic in Catch block – how to read the exact errors and send it to any user/Team or stored in any record, if some thing fails in Try block?

Use the result from Try block and filter it with only failed or Timed out actions-so use the Filtered Array and iterate through each item from filtered array-

Some useful expressions –

Filtered array From result of Try :

result('Try')

Filter only failed and timed out results using advanced mode in Filtered array –

@contains(createArray('Failed', 'TimedOut'), item()['status'])

Read action name which is failed-

@{items('Apply_to_each_result')['name']}

Read Status-

@{items('Apply_to_each_result')['status']}

Read exact error Message-

@{items('Apply_to_each_result')['error/message']}

Set the Subject line and body in the Try and Catch both, so that in Finally we can send the success or failure email. Now, my Try-Catch-Finally blocks looking like this->

Now testing Time-

On successful run, it will skip Catch Block but will hit the Finally->

Email received on successful flow run-

On Error in Try, it will hit the Catch block and capture the failure details. It will hit Finally to send email on failure with error details-

Email received on failed flow run-

In failure- You can add the current flow run log url, so that any developer can easily track the log and find out the exact issues for failure.

We can use the below syntax to get current flow run log url-

concat('https://us.flow.microsoft.com/manage/environments/', workflow()?['tags']['environmentName'], '/flows/', workflow()?['name'], '/runs/', workflow()?['run']['name'])

That’s it!! You learnt the Exception handling in MS Power Automate.

Hope this will help…
Enjoy Ms CRM!!!

Follow on Facebook- FB: MSCRM16Tech

Download File : Power Automate and JavaScript

What is Issue?

When working on D365 CRM, Some time user wants to download file from SharePoint, OneDrive or CRM Notes itself. So how you will do it in shortest way?

The Reason-

Downloading file from SharePoint or any other cloud location it will be time consuming process if you choose Web service or any WCF service.

Solution-

Now Power Automate provides less code and quick solutions. Power Automate has all the connectors and Actions which help you to connect these cloud locations and process on the files.

Let’s see a scenario, I want to download a file on button click on my CRM Account form. The file is located in my account record Timeline Notes.

Let’s go step by step.

First of all, as this is action on click of button on form, we can choose “When Http Request Received” trigger in Power Automate. And in HTTP request we need record id i.e. accountid to retrieve specific Note attachment i.e. “CustomerInfoDoc”-

Now from above step we will get the Document – File name and Document body (base64) content.

So we need a variable to store files in array and another variable for document content-

Setting the variables from the Notes list which we got from “List rows” action-

We need to append array with below json-

{
“Name”: @{items(‘Apply_to_each’)?[‘filename’]},
“ContentBytes”: @{items(‘Apply_to_each’)?[‘documentbody’]}
}

We will use Name and ContentBytes in JavaScript Code which will be in the response of HttpRequest.

Now once file we got file content we need to send them in response-

We need the only file from Notes, In List Row action we can add row count =1, but still in response we can set formula in body first(variable(‘ContentArray’). As this is document in response add headers “Content-type”:”multipart/form-data”

Now our complete flow is ready and it looks like –

So now remaining part is calling the flow from button to download the file-

Add the below javascript and call “callPowerAutomateFlow” function on button click. Below is complete code for download –

function callPowerAutomateFlow(formContext) { 
    id = formContext.data.entity.getId().replace("{", "").replace("}", ""); 
    var account = '{ "accountid": "' + id + '"'+ '}'; 
    var flowUrl = "https://prod-04.centralindia.logic.azure.com:443/workflows/xxxxxxxxxxxxxxxxxxxxxxxxxx/triggers/manual/paths/invoke?api-version=2016-06-01&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=xxxxxxxxxxxx"; 
 
    var req = new XMLHttpRequest(); 
    req.open("POST", flowUrl, true); 
    req.setRequestHeader("Accept", "application/json"); 
    req.setRequestHeader("Content-Type", "application/json; charset=utf-8"); 
    req.onreadystatechange = function () { 
        if (this.readyState === 4) { 
            req.onreadystatechange = null; 
            if (this.status === 200) { 
                    var result = JSON.parse(this.response); 
                    var fileName = result.Name; 
                    var fileCont = result.ContentBytes; 
                    var filebyte = base64ToBufferArray(fileCont); 
                    downloadFile(fileName, [filebyte]); 
            } else { 
                Xrm.Utility.alertDialog(this.responseText); 
            } 
        } 
    }; 
    req.send(account); 
} 
 
function base64ToBufferArray(base64content) { 
    var binaryString = window.atob(base64content); 
    var binaryLen = binaryString.length; 
    var bytes = new Uint8Array(binaryLen); 
    for (var i = 0; i < binaryLen; i++) { 
        var ascii = binaryString.charCodeAt(i); 
        bytes[i] = ascii; 
    } 
    return bytes; 
} 
 
function downloadFile(name,data) { 
        var blob = new Blob(data, { type: "octet/stream" }), 
            url = window.URL.createObjectURL(blob); 
        if (window.navigator && window.navigator.msSaveOrOpenBlob) { 
            window.navigator.msSaveOrOpenBlob(blob, name); 
        } else { 
            const url = window.URL.createObjectURL(blob); 
            const a = document.createElement('a'); 
            document.body.appendChild(a); 
            a.href = url; 
            a.download = name; 
            a.click(); 
            window.URL.revokeObjectURL(url); 
            document.body.removeChild(a); 
        } 
}

That’s it!! when I am clicking on Download button in CRM Account record, it is downloading my Attachment file from Notes which is with title “CustomerInfoDoc”.

Hope this will help…
Enjoy Ms CRM!!!

Follow on Facebook- FB: MSCRM16Tech

Get SharePoint Document details for particular record in MS CRM using FetchXML

What is Issue?

There are many cases while implementing MS CRM where clients ask to perform some operation in MS CRM based on the document uploaded in SharePoint. But how to get SharePoint document details in MS CRM other than “Documents” associated view? If you try to fetch records using advanced find or querying sharepointdocument entity directly, it will show you error. So how we can query and get the document details using code either from client side or server side?

The Reason-

MS CRM Supports only the associated view for Document i.e. sharepointdocument entity. MS CRM do not support direct querying on all sharepointdocument.

Solution-

There is a way to fetch SharePoint document details for particular record in MS CRM.

If you try to query on Document entity in MS CRM using Advanced find you will get the error-” SharePoint document entity does not support any view other than associated view”.

Now this seems trouble to get sharepoint document details. Don’t worry, as error itself says, the sharepoint document does not support any view other than associated view, We can keep building query in advance find itself.

Suppose I want to get documents details for one of my Opportunity in MS CRM , So I am building the query in the following way-
1. Look for : Document
2.Use Saved View :All Sharepoint Documents
3.If you want, you can edit the columns
4. Select Regarding(Opportunity) contains data
5. Select sub query for opportunity record(for which you want to get details)

If you click on results, it will still show you same error. Don’t worry, download the fetchXML for the query we built.

<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="false">
  <entity name="sharepointdocument">
    <attribute name="documentid" />
    <attribute name="fullname" />
    <attribute name="relativelocation" />
    <attribute name="sharepointcreatedon" />
    <attribute name="filetype" />
    <attribute name="absoluteurl" />
    <attribute name="modified" />
    <attribute name="sharepointmodifiedby" />
    <attribute name="title" />
    <attribute name="readurl" />
    <attribute name="editurl" />
    <attribute name="author" />
    <attribute name="sharepointdocumentid" />
    <attribute name="ischeckedout" />
    <attribute name="locationid" />
    <attribute name="iconclassname" />
    <order attribute="relativelocation" descending="false" />
    <link-entity name="opportunity" from="opportunityid" to="regardingobjectid" link-type="inner" alias="ad">
      <filter type="and">
        <condition attribute="opportunityid" operator="eq" value="{83779C3E-xxxx-xxxx-xxxx-0CD3BEAFE160}" />
      </filter>
    </link-entity>
  </entity>
</fetch>

When I tried to use the fetchXML in Javascript query, I got the Sharepoint Document details in json as below-

As sharepoint document entity supports only associated view, it requires regarding object to query. So if you try to remove and link-entity tag from fetchXML, it will not return any record in response.

Now we have fetchXML which we can utilize in Javascript or C# based on requirement.

Hope this will help…
Enjoy Ms CRM!!!

Follow on Facebook- FB: MSCRM16Tech

ReadOnly Subgrids in MS CRM

What is Issue?

While working on MS CRM projects I had requirement of readOnly subgrids in MS CRM. You can achieve this to some extent by hiding buttons on subgrids. But if the requirement is like links should not be clickable for some of the security roles or for some conditions, it is not possible using out-of-box subgrids. That time we had no other option than going with html and JavaScript web resources for this.

The Reason-

This can not be achieve using out-of-box subgrids controls.

Solution-

There are 2 solution for this-
1. Go with HTML webresource.
2. Create Your own Custom Control using PCF (PowerApps Control Framework)

I created the completely read-only subgrid with pagination functionality similar to out-of-box subgrid.

Taking my current scenario-
I have to make subgrid completely read-only if the “More Contact Required?”= NO
Or else the subgrid will be normal subgrid.

So what I did –

  1. On form I added 2 similar subgrids with different Names.
  2. Added script on change of “More Contact Required?” field to show required subgrid.
  3. Changed the control for subgrid which is visible when “More Contacts Required?”= NO
    Open Form Editor -> Select Subgrid -> Change Properties -> Controls Tab ->Add Control -> Selected my own custom Control ->ReadOnlySubgridPage -> Click Add
  4. Save Form and Publish.

Now I found it so simple as I can make any subgrid readonly with my custom control.

You can download the Solution from here and import in Dynamics 365 to use the control.

If you want to check source code download from here.

To work with source code you need some of the basic setup in your computer-
1. Nodejs installed
2. VS or Visual Studio Code installed
3.Understanding of below commands-

pac pcf init --namespace yourNamespace --name yourControlName --template dataset
npm install
npm run build
npm start
pac solution init --publisher-name yourPubliserName --publisher-prefix yourPrefix
pac solution add-reference --path "pcfproj folder path"
msbuild /t:restore
msbuild

Hope this will help…
Enjoy Ms CRM!!!

Follow on Facebook- FB: MSCRM16Tech