The final of my PDF Automation series covers how to use the custom connector for
Dynamics 365 to automate generating a PDF and attach to an outbound email. Refer
to the following as a prerequisite to what the previous two WTF episodes covered
which will be reference in this finale of my PDF Automation series.
**I'd like to make it clear that as of today, Convert to PDF is configured
and supported in the Dynamics 365 Sales Hub app**
In this WTF episode I will cover the flow in Power Automate that references
the Document Template record from Part 1 and the custom connector for
Dynamics 365 from Part 2.
Use Case
Before we jump into the How To's, a reminder that the use case for this
series will be
As a customer,
I want to receive a Tax Receipt of my purchase in an email,
so that I have confirmation of my purchase.
The life cycle of the process will be
A Dynamics 365 Invoice record is updated to paid.
My flow in Power Automate is triggered that handles all the magic.
The customer associated to the Invoice will receive an email with a PDF
attached that represents their Tax Receipt.
What my flow in Power Automate looks like
My flow uses the custom connector and both actions that you would have
read/seen in Part 2: How to create a custom connector for Dynamics 365. The flow is created in a solution and I'm using the CDS current environment
connector.
1.0 Trigger - When an Invoice is updated to Paid
The trigger is when the status reason is Updated to Paid where the end user in
the Dynamics 365 Sales Hub App clicks on Invoice Paid in the ribbon.
I have also configured two filters for the trigger
Only trigger if the Status Reason field has been updated
And if the Status Reason field equals Paid
1.1 Retrieve queues
Using the CDS List records action I am retrieving a Queue with the name of "No
Reply" as defined in my Filter Query field. To learn more about the
configuration required to be able to send from a Queue, refer to
Episode 23 - Sending an email from a Queue with Power
Automate.
1.2 Create a new email activity record
Using the CDS Create a record action an email activity will be created where
the sender will be the Queue from 1.1 Retrieve queues and the To recipient is
the customer of the Invoice.
I've cut out area of the action as some it is not used otherwise it would have
been a long screenshot 😅 The other configuration is providing a Description,
setting the Regarding value to the Invoice and the Subject of the email.
1.3 Retrieve Document Template record
Using the CDS List records action I am retrieving a Document Template record
where I had uploaded a Word Template I created. This would be Document
Template record from
Part 1. This will be the template used to generate the PDF for an a paid Invoice
where it includes information such as the customer, the bill to address, the
invoice items and so forth.
The filter query is the name of the Document Template record.
1.4 Generate PDF
Woo hoo! This is where the action created in the custom connector is used. The
Generate PDF action is used where the values are provided for the JSON payload
of the API request. I covered this in
Part 2.
The EntityTypeCode represents the entity that the PDF will be generated
against. In my use case it is the Invoice entity where the value is 1090.
The @odata.type is Microsoft.Dynamics.CRM.documenttemplate
The documenttemplateid is the GUID of a Document Template record. Refer to
Part 1. My expression since the CDS List record action is used to retrieve the
Document Template record is the following to
avoid the Apply to Each from appearing
The SelectedRecords property is the GUID of the Invoice record from the
trigger that the PDF will be generated against. I included the additional
characters the API request expects which I explained in Part 2.
1.5 Create Email Attachment
The other custom action used is creating an activitymimeattachment record
by
binding to an email message which is from 1.2 Create a new email activity
record action
referencing "email" as the objecttypecode
using the base64 PdfFile property in the JSON response of 1.4 Generate PDF
action
using the Invoice ID from the trigger as the file name and subject
note that for the file name ".pdf" is used as the file format
1.6 Perform a bound action
The last step is the CDS Perform a bound action using the SendEmail action.
Simply reference the email message from 1.2 Create a new email activity
record and set the IssueSend value to Yes.
Power Automate in action
Update an existing Invoice to Paid and refresh to see the email activity
created with a PDF that represents a Tax Receipt.
Unit testing
The following are screenshots to confirm the attachment record was correctly
created. I mentioned in
Part 2
that I learnt from
this forum post
of how the activitymimeattachment should be created first where Dynamics 365
will then create the corresponding attachment record.
This was the Invoice that was updated to Paid.
Here's the activitymimeattachment response from the custom connector. The
activitymimeattachment was successfully created.
I queried the activitymimeattachment API to retrieve the record details.
The activitymimeattachmentid matches the id from the response.
I can see the corresponding attachment record was created too.
I can also see the activitymimeattachment record was binded to the created
email activity.
I queried the attachment API to retrieve the record details. I can see the
attachmentid matches the property value from the activitymimeattachment
record and the filename and subject matches the Invoice ID.
Lastly, I queried the emails API to retrieve the record details. I can see
that the activityid value matches the _objectid_value from the
activitymimeattachment and that the Invoice ID referenced in the email subject
matches the paid Invoice. It all ties together nicely 👍
Another handy blog post
Another blog post you can refer to that has a different flow in Power Automate
but achieves the same result is by another Microsoft MVP in our community,
Aric Levin
which you can read
here. What I like about Aric's blog post is that it would be an option for
customers who use CDS but not Dynamics 365 as the Convert to PDF functionality
as of today resides in the Dynamics 365 Sales Hub app. Aric also uses the
Office 365 action to send the email with the generated PDF file which means
the
storage consumption
of CDS will not be impacted. The exception is if the App for Outlook is
installed and tracking is enabled which means the sent email from Outlook may
be created as an email activity based on the configuration of tracked emails
for the user.
Summary
Automating generating PDFs from the Dynamics 365 Sales Hub app is achievable
with Power Automate through
A Word Template uploaded against a Document Template record
A custom connector for Dynamics 365 that calls the ExportPdfDocument API
and the activitymimeattachment API
A flow that references the Document Template from No.1 and use the custom
actions created in the custom connector for Dynamics 365 from No.2
I hope you enjoyed my PDF Automation series 🙂
Your Vote Counts!
If you want Convert to PDF across custom entities then vote for
this Dynamics 365 Idea
to gain momentum. I would love to see this functionality across the Dynamics
365 platform so let's do our part by voting for it.
In
Part 1: How to create a Word template in Dynamics 365
of my PDF automation series I covered how to create a Word Template in Dynamics
365 as a Document Template record is referenced in the API request that will
generate the PDF based on the entity defined in the Word Template.
In
this episode, Part 2 will cover how to create a custom connector for Dynamics
365 in Power Automate. In the custom connector two actions will be created where
there will be
An action that calls the ExportPdfDocument Dynamics 365 API request - this
will generate a PDF based on a Document Template record that has a defined
Word Template
An action that calls the activitymimeattachments Dynamics 365 API request
- this will attach the PDF file generated from the previous action to an
email activity record
Prior to creating a custom connector, a prerequisite task is to create an
App Registration in Azure Portal which I will cover.
**I'd like to make it clear that as of today, Convert to PDF is configured
and supported in the Dynamics 365 Sales Hub app**
Use Case
Before we jump into the How To's, a reminder that the use case for this
series will be
As a customer,
I want to receive a Tax Receipt of my purchase in an email,
so that I have confirmation of my purchase.
The life cycle of the process will be
A Dynamics 365 Invoice record is updated to paid.
My flow in Power Automate is triggered that handles all the magic.
The customer associated to the Invoice will receive an email with a PDF
attached that represents their Tax Receipt.
Why is a custom connector needed?
This PDF Automation series stemmed from my curiosity of whether we can
automate the Convert to PDF functionality. As mentioned in my vlog, as of
today the Convert to PDF is what we refer to as "on-demand" where it requires
an end user to select a Document Template before creating or emailing the
converted Word Template associated to the Document Template record as a
PDF.
Stefan Strube
another Microsoft MVP in our community published
this blog post
where he shared how to automatically generate a PDF which is fundamental to my
PDF Automation series. Thanks Stefan and hello! 😄 The action used in Stefan's blog post is the Invoke an
HTTPs request which works.
If there is a use case for an end user
to trigger the automation on selection of a record the following experience
will appear where they are prompted to provide the configuration information
for the Invoke an HTTPs request action. Chances are the end user may not
know this information and it's not a smooth end user experience. The
workaround is to use a custom connector that has the authentication configured
to prevent the end user from having to enter in details regarding the Dynamics
365 instance for the Sales Hub app.
How to create an App Registration in Azure Portal for your Dynamics 365
instance
An App Registration is required to allow the custom connector to use Azure AD
as a way of authentication to the Dynamics 365 instance. Whenever connectors
are used in flows within Power Automate, a connection using credentials to the
service is needed. For example when using a SharePoint action you have the
ability to select a connection. Same concept applies to a custom connector. A
couple of material you can read,
This
docs.microsoft.com article
clearly explains the steps required to create an App Registration in Azure
portal.
The following are the steps that I showed in my WTF vlog.
Log into Azure portal and search for App Registration.
Click on +New Registration.
Enter a Name and select whether you want a single tenant or multiple tenant
followed by the register button. We'll come back to the Redirect URI
configuration after the customer connector has been created.
There will be a message that indicates the App Registration is being
created.
Once created you'll see details of the App Registration which will be
referenced when the custom connector for Dynamics 365 is created.
A couple of things need to be configured afterwards. The first one I showed in
my vlog was to enable
API permissions
for Dynamics 365. The custom connector will access with the Dynamics 365 API
using the connection configured for the selected custom action (this will make
sense in Part 3 of my PDF Automation series). Head over to API permissions and
click on +Add a permission and select the Dynamics CRM option.
Tick the checkbox for the permission that is displayed and click Add
permissions.
A message will appear that confirms the permissions has been added and it will
be listed.
The other configuration is to create a Client Secret which will be for the
security of the custom connector for Dynamics 365. Head to Certificates &
secrets, click +New client secret and provide a name for the Client Secret.
Select the option Never for the expiry setting and then click add.
The Client Secret will be created. Copy the Client Secret value and
saveit some where as this will be used for the
security of the custom connector for Dynamics 365.
How to create a custom connector for Dynamics 365 in Power Automate
Once the App Registration for Dynamics 365 has been created a custom connector
can be created in Power Automate. Head to the Power Automate maker site and
select Custom connectors. Click on +New custom connector and select the option
to Create from blank.
Name the custom connector and click continue.
An icon can be selected to identify the custom connector. In my vlog I was
using a Pineapple icon from
icons8. A
background colour can also be defined. For the Scheme value, leave it as
HTTPS.
The Host value will be the organisation part of the Dynamics 365 instance URL.
Click Create connector to create the custom connector before moving on to the
Security configuration step.
How to configure the security for the custom connector
Next security for the custom connector needs to be configured. Click Edit and
then select the option of OAuth 2.0.
For the Client ID and Client Secret values, copy and paste from the App
Registration in Azure Portal. You would have saved your Client Secret some
where from the earlier step. Copy and paste the full organisation URL of the
Dynamics 365 instance including the HTTPS for the Resource URL value
Remember that Redirect URI configuration field in the App Registration when
the App Registration was created? The Redirect URI configuration field in the
App Registration needs to be updated with the Redirect URL generated in the
Security configurations of the custom connector for Dynamics 365.
Before moving on to creating the custom actions in the Definition step
of the custom connector, click Update connector. Always click this whenever
you apply any configuration.
How to create Actions for the custom connector
When we use connectors available today in flow within Power Automate, we have
the ability to select either a trigger or an action for the connector.
Now that the custom connector has been created, the next step is to create
actions which involve providing the API request and JSON Payload of that API
request.
1. Creating an action that will generate a PDF
As seen in
Stefan Strube's blog post, the Dynamics 365 API request to call that is used by the Dynamics 365 Sales
Hub app is the ExportPdfDocument using the POST method. I am using the same
JSON payload that Stefan shared but with one adjustment where I am excluding
the following highlighted in Red. When I was putting this all together earlier
this year I found that it would fail if I included these character references.
The EntityTypeCode represents the entity that the PDF will be generated
against. In my use case it is the Invoice entity.
The SelectedTemplate block represents the Document Template record with
the Word Template that the API request will use to generate the PDF.
This will be the Document Template record from Part 1: How to create a
Word template in Dynamics 365.
The SelectedRecords property represents the Invoice record the PDF will
be generated against.
To retrieve the EntityTypeCode value of the record for the JSON Payload you
can call the EntityDefinition API Request with some filters to obtain the
value.
Once the connector has been updated you'll see that your action has been
created.
One of the things I love about the custom connector in Power Automate is the
ability to test the API request directly within the custom connector
configuration. Click on Test and create a new connection to authenticate with
the request using your credentials.
Here comes the fun part, the testing! Enter in the property values for the
JSON payload. A reminder from earlier what the properties represent,
The EntityTypeCode represents the entity that the PDF will be generated
against. In my use case it is the Invoice entity where the value is 1090.
The SelectedTemplate block represents the Document Template record with
the Word Template that the API request will use to generate the PDF. This
will be the Document Template record from Part 1: How to create a Word
template in Dynamics 365.
The SelectedRecords property represents the Invoice record the PDF will be
generated against.
To retrieve the Document Template ID value, open the Document Template
record of the Word Template to be referenced. Copy the GUID at the end of
the record URL.
To retrieve the Invoice ID value of an Invoice record to be referenced, open
an existing Invoice record. Copy the GUID at the end of the record URL.
If you test the operation right now it will fail. Remember how we didn't
include the extra characters when creating the Request of the action? We need
to include some of those characters in the SelectedRecords field. The
characters to include is the following highlighted in yellow.
[{"21ce9319-22a3-ea11-a812-000d3a7981c5"}]
[ ] Means make it an array, " " means make it a string, so this is saying make
it an array of strings. I interpreted this as the API request likely needs an
array of all the GUIDs that you want to generate a PDF for.
Once the SelectedRecords property value has been updated, it's ready to test!
The status response should be 200 and you'll see the JSON returned where there
is a PdfFile property with a base64 value that represents the encoded PDF file
that was generated.
2. Creating an action that will create the PDF as an activitymimeattachment
record
Activitymimeattachment is the entity record which will contain information of
the attachment such as the encoded base64 value.
This forum post
explains it well.
The reason why we are using an API request to create the
activitymimeattachment record is because today if we attempt to use the Create
action from the CDS current environment connector and select the second
attachments option when searching for the entity (from memory) the following
error will be thrown,
The 'Create' method does not support entities of type 'attachment'.
If you then try the other attachments option you'll still come across a
problem as the Item ID is required which can't really be provided since the
attachment record has not been created. Therefore I thought of calling the
activitymimeattachments API request
instead as I learnt from
this forum post
that the activitymimeattachment should be created first where Dynamics 365
will then create the corresponding attachment record.
Side note: Linn Zaw Win did write a
blog post
that shows you how to send an email which uses a combination of the CDS
standard connector and CDS CE standard connector.
Same steps as before, create a new action, provide a name and operation id
value and lastly the JSON payload request. Make sure you click Update
connector once the Request has been created.
I worked out the JSON Payload request from
this blog post
where the following properties are
objectid_activitypointer@odata.bind
The email activity record to bind the activitymimeattachment
objecttypecode
The value is email since the activitymimeattachment will be associated
to an email activity record
body
This is the encoded base64 value of what would be the generated PDF.
In my WTF vlog I was using
this site
to generate an encoded sample of "Hello World. This is a demo"
filename
This is the file name. It is important in this step to include a
reference to the file type. In my WTF vlog I was using a .txt
subject
This is a descriptive subject for the attachment. In my WTF vlog I
used "Hello World" as an example
The next part is testing it out again. To bind the activitymimeattachment
to an email open an existing record and copy the GUID from the email
record URL.
For the encoded base64 value I used
this site to
generate a sample value.
Once all the property values have been entered, click test
operation. The status response should be 204 and you'll see the JSON
returned. Open the email activity record in the Dynamics 365 Sales Hub to
double check the file was created and attached to the email activity
record 👍
Check the custom connector is visible when creating a new flow in Power
Automate
Now that we've learnt how to do an App Registration and create a custom
connector with actions for Dynamics 365 we can now check it out in flow!
Head to the Power Automate maker site and create a new flow. Once the
trigger has been defined add a new action and click on the Custom tab. The
two actions created will be displayed and can be selected to add to the
flow. Awesome sauce 🙌😄💙
Summary
It's pretty cool that we can create a custom connector for Dynamics 365 if
the actions available in the CDS current environment connector will not
suffice what needs to be achieved. The beauty of Dynamics 365 and CDS is
that the APIs have existed for years and with flow in Power Automate it's
now even more easier to perform API requests as the authentication can be
configured directly in Power Automate. For PDF automation all it requires
is
An App Registration through Azure Portal for the Dynamics 365 instance
of the Sales Hub App
Create a custom connector using the App Registration details with
custom actions using the Dynamics 365/CDS APIs
Once this is all fine tuned, the custom connector will be available to use
in the environment for you to continue making flows in Power Automate.
Thanks
for reading this detailed blog post of Part 2 of my automation series. Part 3 will cover all of this in action using actions I've covered in
previous WTF episodes.
Your Vote Counts!
If you want Convert to PDF across custom entities then vote for
this Dynamics 365 Idea
to gain momentum. I would love to see this functionality across the Dynamics
365 platform so let's do our part by voting for it.
If you're a new comer to Dynamics 365, Part 1 covers how to create a Word Template in Dynamics 365.
The API that the Dynamics 365 product team released in 2019 references a
Document Template record which has a Word Template associated to it which acts
as the backbone of a PDF generated from Dynamics 365. For more information
about Convert to PDF refer to
this docs.microsoft.com
article.
**I'd like to make it clear that as of today, Convert to
PDF is configured and supported in the Dynamics 365 Sales Hub app**
In this WTF episode I will cover
A brief overview of the Convert to PDF functionality
How to create a Word Template from scratch
How to update an existing Word Template
Use Case
Before we jump into the How To's, the use case for this series will be
As
a customer,
I want to receive a Tax Receipt of my purchase in an email,
so that I have confirmation of my purchase.
The life cycle of the process will be
A Dynamics 365 Invoice record is updated to paid.
A flow in Power Automate is triggered that handles all the magic.
The customer associated to the Invoice will receive an email with a PDF
attached that represents their Tax Receipt.
Overview of the Convert to PDF functionality
The Convert to PDF functionality that exists today in Dynamics 365 Sales Hub
can be used against the following entities
Account
Contact
Lead
Opportunity
Quote
Order
Invoice
This is what it will look like to an end user when viewing a record in the
Dynamics 365 Sales Hub app,
Regardless of what option the end user chooses, the end user is required to
select a Word Template that has been created for that particular entity. In
my case it is the Invoice entity. This is due the Dynamics 365 API request,
ExportPdfDocument, as it will generate a PDF based on a Word Template that
is associated to a Document Template record. More details regarding the
Dynamics 365 ExportPdfDocument API request in Part 2 😉
In order for the Convert to PDF functionality to appear in the Dynamics 365
Sales Hub app they need to be enabled for the desired entities. Head to App
Settings and you'll see the Convert to PDF configuration, click Manage.
Enable the entities you'd like and hit that Save button. Refresh your
browser and you should now see the Convert to PDF functionality in Dynamics
365 Sales Hub.
Cool on to the How To's.
How to create a Word Template from scratch
Any Word Template or Excel Template created and uploaded into Dynamics 365
will be associated to a Document Template record. This functionality has
existed for a few years now and
this is the official docs.microsoft.com
article.
In my vlog I misbehaved by not showing you how to navigate to Document
Templates from the Power Platform Admin Centre - my bad 😅 Old habits since I
started with Dynamics CRM 4.0. The following steps will reference the Power
Platform Admin Centre.
Head over to the Power Platform admin center
and select Settings.
Expand the Templates settings and select Document Templates.
A new browser tab will appear where you click +NEW to create a new Document
Template.
Select Word Template and the entity of your choice. In my use case it is the
Invoice entity. Click Select entity
Next, the entity relationships are required to be selected in order for data
to be displayed in the generated Word document using the Word Template. Since
I'm going to be generating a Tax Receipt from a paid Invoice I'll be
referencing the Invoice Line Items and information about the customer so I
have selected the Invoice Product, Account and Contact entity
relationships. Once you're ready click the Download Template button.
Enable Editing on the Word Template and head over to File > Options and in
the Customize Ribbon tab enable the Developer command.
Head to the Developer tab and select the XML Mapping Pane from the ribbon.
This is where we can define the XML Mapping to the Invoice entity in Dynamics
365. Select the Custom XML Part drop down field and there should be a
reference to the Dynamics 365 entity that was defined when the Word Template
was downloaded from Dynamics 365.
Once the XML Mapping is pointing to Dynamics 365 reference the fields for the
Invoice entity will be displayed.
If you scroll down the entities based on the entity relationships defined for
the Word Template will also be visible which will allow you to select the
fields from those entities.
You can start creating your desired Word Template by selecting a field from
the entity relationships. For example to select the Invoice Number field from
the Invoice record,
Scroll down to the Invoice Number field.
Right click and select Insert Content Control.
Select Plain Text.
This will display your select field where you have positioned it in the Word
document.
Continue to build the rest of your Word Template to your requirements. If
there will be a table in your Word Template, you'll want to display the rows
of that related data. In my use case this will the Invoice Line Items.
Previously we were selecting fields but since we're dealing with rows for a
table the content control is sightly different.
Create a table and
in your first row select the content controls for the fields. Then highlight
your first row, select the entity from the related entities and right click to
select insert content control followed by "Repeating."
When the Word Template has been defined it can be uploaded into Dynamics 365.
Save your Word Template and head back to the Document Templates view to create
a new Document Template record.
Select your Word Template file to upload.
Click on Upload.
A new window will appear with the newly created Document Template record. By
default the file name will be the value in the Name field. This can be updated
to whatever value you like.
To check out your newly created Word Template, open an existing Invoice record
and select the Word Template to see it in action.
How to update an existing Word Template
If you were to open a Word Template record in Dynamics 365 you won't see
anything that indicates a way of updating the previously uploaded Word
Template.
The solution? XrmToolBox. Microsoft MVP Tanguy Touzard
is the legend behind
XrmToolBox and there
are many people in the Microsoft community who have contributed their time by
creating and adding tools to XrmToolBox. One of these souls is Microsoft
MVP James Novak
who created and shared his tool called "Document Template Manager" which allows you to download existing Word templates and edit them.
When you open XrmToolBox head over to the Tool Library and select Document
Template Manager to install.
Once it has been installed and select the Document Template Manager Tool which
will connect to the environment that you were last connected to.
If you are not connected to an environment already you can select an existing
environment or create a new environment in the "Connected To" settings of
XrmToolBox which will be at the bottom on the left.
To load all the templates available in the Dynamics 365 instance you are
connected to click on the Load Templates button. To update one of the
out-of-the-box Word Templates such as Invoice Summary, select the document and
click on Download Templates.
Once the Word Template has been downloaded you can open the file and view the
existing template with the references to the content controls that have been
defined. If you want to add any additional content controls, head to the XML
Mapping Pane in the Developer tab of the ribbon. Select the Custom XML Part
drop down field and there should be a reference to the Dynamics 365 entity
that was defined fro the Word Template.
When you're ready to upload the Word Template document you can do this
directly from Jim's Document Template Manager tool as well. Select the Word
Template you want to overwrite with your updated template and select Single
Upload. A warning message will appear to inform you that the file uploaded
will overwrite the document template for that select Document Template record.
Once it has completed you can then navigate to your Invoice record and select
the updated Document Template record.
Summary
You can either create a Word Template from scratch or create a Word Template
based on an existing template by downloading it through
XrmToolBox using
Jim's
Document Template Manager
tool.
A Document Template record will be referenced in my flow in
Power Automate that will generate a PDF of an Invoice automatically. Stay
tuned for Part 2 where I will share how to create a custom Dynamics 365 custom
connector to handle the API request to generate the PDF.
Your Vote Counts!
If you want Convert to PDF across custom entities then vote for
this Dynamics 365 Idea
to gain momentum. I would love to see this functionality across the Dynamics
365 platform so let's do our part by voting for it.