In our previous blog post we covered how to create a custom Microsoft Word template to generate Customer Ready Quote using Document Generation feature introduced in Dynamics CRM 2016.

In this blog post, we will see how to auto generate Word Template and most importantly, how we can send auto generated Word Template as an attachment in Email.

Why Auto Generate Word Templates:

The one purpose of auto generating the Word Template in Dynamics CRM is to save some user clicks. For example when a campaign is mark as completed, user has to generate campaign summary ( Word Template) and send it to owner of the campaign. If user has to do it manually, he has to generate the Word Template first then create an email and send it to the owner. Instead of, one’s need is to automate this process. Whenever the status of campaign is set as completed, generate the campaign summary and email to owner.

Our Approach:

To achieve the functionality, we will have to create two workflows.

  • First Workflow will run on Status Reason field change, It will generate word template and save in Notes entity as attachment.
  • Second Workflow will be a custom workflow, that will create an Email record, get document from Notes entity, attach in email and send the email at the end.

Below is step by step guide to auto generate Word Template and attach in Email.

Step 1: Auto Generate Word Template:

  • From the Settings page. Go to Settings > Processes.
  • Create a new process of type Workflow” on the Campaign entity.
  • Set scope to run for Organization.
  • Configure the workflow so it is set to execute on “When Record fields change” and select field as “Status Reason”.

 

Auto Generate Word Template 1

  • Click on Add Step > Check Condition  to add the first clause where we will check if the Status Reason of campaign is completed.

Auto Generate Word Template 2

 

Auto Generate Word Template 3

  • Select the row and click on Add Step > Perform Action.

Auto Generate Word Template 4

 

  • Select Action as “SetWordTemplate” from the dropdown and click on “Set Properties”.

Auto Generate Word Template 5

  • Select “Selected Template”  as the template you want to be auto-generated. In our case we will choose “Campain Summary”.
  • Select Target  (the entity record you want the template to be attached to) to be your Campaign. This should be automatically selected when you click in this field and you can just select “OK” on the right hand side to place the mapping in the field like the picture below.

Auto Generate Word Template 6

 

  • First Workflow is complete, save and activate the workflow.

What this workflow will do is when the Status Reason of Campaign record is changed to Completed, it will auto-generate the Word Template (Campaign Summary) and attach it as notes.

Auto Generate Word Template 7

Step 2: Custom Workflow to Send Campaign Summary as Email Attachment

As we have to get the attachment from Notes, and send in Email as attachment. There is no OOB way to access attachment from notes. So we have to write custom workflow where we will get attachment (Word Template) from annotation entity and will create activitymimeattachment record. After that we need to create email and associate with it.

After creating the custom workflow, we will run it from our main workflow that we have created above.

Build the assembly using the code provided below and register in Plugin-Registration Tool.

Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Activities;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Workflow;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Crm.Sdk.Messages;
namespace CustomWorkFlow
{
 public class CustomWorkFlowClass : CodeActivity
 {

 [Input("SourceCompaign")]
 [ReferenceTarget("campaign")]
 public InArgument<EntityReference> SourceCompaign { get; set; }
 protected override void Execute(CodeActivityContext executionContext)
 {
 //Create the context
 IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();
 IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();
 IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);</pre>
// Get the target entity from the context
Entity regCampaign = (Entity)service.Retrieve("campaign", context.PrimaryEntityId, new ColumnSet(new string[] { "name","ownerid" }));
string campaignName = (string)regCampaign.Attributes["name"];
EntityReference ownerid = (EntityReference)regCampaign.Attributes["ownerid"];

Entity emailEntity = new Entity("email");

Entity fromParty = new Entity("activityparty");
fromParty.Attributes["partyid"] = new EntityReference("systemuser", context.InitiatingUserId);
EntityCollection from = new EntityCollection();
from.Entities.Add(fromParty);

Entity toParty = new Entity("activityparty");
toParty.Attributes["partyid"] = new EntityReference("systemuser", ownerid.Id);
EntityCollection to = new EntityCollection();
to.Entities.Add(toParty);

EntityReference regarding = new EntityReference("campaign", context.PrimaryEntityId);

emailEntity["to"]=to;
emailEntity["from"] = from;
emailEntity["subject"] = "Campain Summary of " + campaignName;
emailEntity["regardingobjectid"] = regarding;
Guid EmailID= service.Create(emailEntity);

EntityReference abc = SourceCompaign.Get<EntityReference>(executionContext);
AddAttachmentToEmailRecord( service,EmailID , SourceCompaign.Get<EntityReference>(executionContext));
}
private void AddAttachmentToEmailRecord( IOrganizationService service, Guid SourceEmailID, EntityReference CompaignID)
{

//create email object
Entity emailCreated = service.Retrieve("email", SourceEmailID, new ColumnSet(true));
QueryExpression QueryNotes = new QueryExpression("annotation");
QueryNotes.ColumnSet = new ColumnSet(new string[] { "subject", "mimetype", "filename", "documentbody" });
QueryNotes.Criteria = new FilterExpression();
QueryNotes.Criteria.FilterOperator = LogicalOperator.And;
QueryNotes.Criteria.AddCondition(new ConditionExpression("objectid", ConditionOperator.Equal, CompaignID.Id));
EntityCollection MimeCollection = service.RetrieveMultiple(QueryNotes);
if (MimeCollection.Entities.Count > 0)
{ //we need to fetch first attachment
Entity NotesAttachment = MimeCollection.Entities.First();
//Create email attachment
Entity EmailAttachment = new Entity("activitymimeattachment");
if (NotesAttachment.Contains("subject"))
EmailAttachment["subject"] = NotesAttachment.GetAttributeValue<string>("subject");
EmailAttachment["objectid"] = new EntityReference("email", emailCreated.Id);
EmailAttachment["objecttypecode"] = "email";
if (NotesAttachment.Contains("filename"))
EmailAttachment["filename"] = NotesAttachment.GetAttributeValue<string>("filename");
if (NotesAttachment.Contains("documentbody"))
EmailAttachment["body"] = NotesAttachment.GetAttributeValue<string>("documentbody");
if (NotesAttachment.Contains("mimetype"))
EmailAttachment["mimetype"] = NotesAttachment.GetAttributeValue<string>("mimetype");
service.Create(EmailAttachment);
}
// Sending email
SendEmailRequest SendEmail = new SendEmailRequest();
SendEmail.EmailId = emailCreated.Id;
SendEmail.TrackingToken = "";
SendEmail.IssueSend = true;
SendEmailResponse res = (SendEmailResponse)service.Execute(SendEmail);
}

}
}

Step 3: Combining the Workflows:

  • Open and deactivate the first Workflow we have created.
  • Add custom workflow steps from Add Step.

Auto Generate Word Template 10

  • Click on Add Properties.

Auto Generate Word Template 11

 

 

  • Set Campaign lookup as Input Parameter that we have specified in custom workflow.

Auto Generate Word Template 12

 

  • Save and Activate the Workflow.

When the Status Reason of Campaign record is changed to Completed, it will:

  • Auto-generate the Word Template (Campaign Summary) and attach it as notes.
  • Create a new Email record.
  • Get Campaign Summary from the Notes Attachment.
  • Create new Email Attachment and attach to Email created before.
  • Send the Email to Owner of the campaign.

Conclusion:

Our purpose was to provide user with automation of generating Word Templates and automate the Email Process.It’s really simple and you could actually create some really complex and interesting scenarios with this functionality.