Thursday, December 28, 2023

Trigger power automate on Button click, Generate word document and Download file

How to Trigger power automate on Button click, Generate word document & Download file

In this blog, we will explore the following topics:
- Creating a custom button (e.g., Print Case) using Ribbon Work Bench
- Triggering a cloud flow upon clicking the Print Case button
- Enabling Developer mode and mapping Dynamics 365 case record fields in Microsoft Word
- Converting MS Word documents to PDF in Power Automate
- Integrating SharePoint with Dynamics 365
- Storing converted PDFs to both the case record and SharePoint
- Downloading the generated PDF document to the local system upon clicking the Print Case button

In the subsequent sections, we will delve into:

1. Selecting multiple case records and mapping, generating, and storing documents with a single button click by triggering the same flow multiple times.

2. Demonstrating the process of selecting multiple case records, mapping, generating, and storing documents with a single button click by triggering the same flow just once.

Prerequisites:
- SharePoint access
- Ribbon Workbench installed (Download link here)
- Power Automate access
- SharePoint integration with Dynamics 365 
Updating More details Soon...

Click here to download the code file

JavaScript code here
function callHTTPFlow(primaryControl, env_name, fileName, IDName) {
try {
"use strict";
debugger;
console.log(primaryControl, env_name, fileName, IDName);
Xrm.Utility.showProgressIndicator("Generating document...please wait...");
getEnvironmentVariable(env_name,
function (url) {
callHTTPFlowInternal(url, primaryControl, fileName, IDName);
},
function (error) {
handleError(error);
}
);
} catch (error) { console.error(error); }
}

function handleError(error) {
try {
Xrm.Utility.closeProgressIndicator();
showMessageDialog("Error", error);
} catch (error) { console.error(error); }
}

function callHTTPFlowInternal(url, primaryControl, fileName, IDName) {
try {
"use strict";
if (!fileName) { fileName = 'document.docx'; }
var guid = primaryControl.data.entity.getId();
var userSettings = Xrm.Utility.getGlobalContext().userSettings;
var currentuserid = userSettings.userId;
var userId = currentuserid.replace("{", "").replace("}", "");
primaryControl.data.save().then(function () {

guid = guid.replace("{", "").replace("}", "");
// url = url + "&id=" + documentId;
var data = {};
data["UserID"] = userId;

if (IDName) { data[IDName] = guid; }
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
}).then(response => {
Xrm.Utility.closeProgressIndicator();
if (response.status == 200) {
if (response.headers.get("content-type") === "application/json") {
response.json().then((data) => {
if (data && data.SiteAddress && data.ETag) {
const EncodeURIEtag = encodeURI(JSON.parse(data.ETag).split(',')[0]);
const onlineDocLink = data.SiteAddress + "/_layouts/15/Doc.aspx?sourcedoc=" + EncodeURIEtag;
window.open(onlineDocLink, "_blank");
}
else {
throw new Error("Unable to find document");
}
})
}
else {
response.blob().then(blob => {
downloadFile(blob, fileName);
closePopups(primaryControl);
});
}

} else {
response.text().then(body => {
handleError(body);
});
}
}).then(data => console.log(data))
.catch(function (error) {
handleError(error);
});
},
function (error) {
Xrm.Utility.closeProgressIndicator();
showMessageDialog("Error", error.message);
});
} catch (error) { console.error(error); }
}

function closePopups(formContext) {
try {
formContext.data.refresh(false);
Xrm.Utility.closeProgressIndicator();
} catch (error) { console.error(error); }
}

function downloadFile(blob, fileName) {
try {
debugger;
var blobType = blob.type;
var name = fileName.split('.')[0];
if (blobType.includes('officedocument')) { // Set Docx file name
fileName = name + '.docx';
} else if (blobType.includes('application/pdf')) { // Set pdf file name
fileName = name + '.pdf';
}
console.log(fileName);
if (navigator.msSaveBlob) { // IE 10+
navigator.msSaveBlob(blob, fileName);
} else {
var link = document.createElement("a");
if (link.download !== undefined) {
var url = URL.createObjectURL(blob);
link.setAttribute("href", url);
link.setAttribute("download", fileName);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
} catch (error) { console.error(error); }
}

function showMessageDialog(messageTitle, message) {
try {
var alertStrings = {
confirmButtonLabel: "OK",
text: message,
title: messageTitle
};
var alertOptions = {
height: 120,
width: 260
};
Xrm.Navigation.openAlertDialog(alertStrings, alertOptions);
} catch (error) { console.error(error); }
}

function getEnvironmentVariable(varName, onSuccess, onError) {
try {
"use strict";
Xrm.WebApi.retrieveMultipleRecords("environmentvariabledefinition", "?$select=defaultvalue,displayname&$expand=environmentvariabledefinition_environmentvariablevalue($select=value)&$filter=schemaname eq '" + varName + "'").then(
function success(result) {
var varValue = null;
for (var i = 0; i < result.entities.length; i++) {

if (typeof (result.entities[i]["environmentvariabledefinition_environmentvariablevalue"]) != "undefined"
&& result.entities[i]["environmentvariabledefinition_environmentvariablevalue"].length > 0) {
varValue = result.entities[i]["environmentvariabledefinition_environmentvariablevalue"][0].value;
}
else if (typeof (result.entities[i].defaultvalue) != "undefined") {
varValue = result.entities[i].defaultvalue;
}
else {
varValue = null;
}
}
onSuccess(varValue);
},
function (error) {
console.log(error.message);
onError(error);
}
);
} catch (error) { console.error(error); }
}


Monday, December 11, 2023

Power Automate - Populate Lookup field error

When using Power Automate to populate a lookup field, you might encounter a failure with the following error: "Error - URL was not parsed due to an ODataUnrecognizedPathException. Resource not found for the segment provided in the URL." 

This issue arises because mapping lookup fields requires extra attention. 

When mapping normal fields, simply use the value from dynamic content, as shown below:

But while mapping lookup values (dynamic), it involves placing the lookup field schema name within braces, like this: logicalname(GUID) 
Note- my lookup fieldd name is new_memo
and plural name of entity(suppose entity is contact then it should be contacts(Value) )

For lookup values, use either the field logicalname(GUID) or /logicalname/GUID


If you're populating a particular static lookup value, obtain the GUID of that record and input it accordingly.






Followers

Power Dynamix YouTube Videos