CRM 4.0: Programmatically Upload a Mail Merge Template

image

 

The Mail Merge Facility in Microsoft Dynamics CRM 4.0 works fairly well in most cases. It is at the same time a bit to complicated for casual users, and a bit too simplistic for power users, but at least in our environment it has been tweakable enough to be useful.

Like everything in CRM the Mail Merge Template is an Entity, and thankfully Microsoft permits it’s customization (without unsupported tweaking).

image

You can add custom attributes and relationships; you can customize the form and the views; you can trigger workflows when attributes change (although you cannot register a plugin against it without unsupported tweaking). The tricky fields – body, filename, documentformat – they are all read/write through web services (http://msdn.microsoft.com/en-us/library/dd903944.aspx). Meaning you can programmatically upload new templates… but how?

 

After Google failed me, I initially chose the reverse engineer approach. The contents of the body field looked like Base64 (ended with equals signs), and indeed was. I create a tool to download the existing templated, modify them slightly, then add them back.  I had a working solution, but as we approached golive I got cold feet about messing things up in production- what if I’m doing it wrong and something breaks?

A bit of digging with reflector led to the solution: internally, the attachment on a mail merge template is treated the same as the annotation entity, and Microsoft has an article explaining the correct way to upload an attachment here : Upload an Attachment

The paraphrased money line: “updateTemplate.body = System.Convert.ToBase64String(byteData)”;

Leave a Reply

Your email address will not be published. Required fields are marked *