CRM Document Templates Some Observations

Document templates were added in the 2016 version of Dynamics CRM to allow users to easily generate Word or Excel documents directly from Dynamics CRM. This  Microsoft link explains how to create and upload a Word template and how to generate documents. However there are a number of things you need to be aware of.

There does not seem to be a way of adding templates to a solution so you need figure out a way to move templates  from one environment to another. You could do this manually or write some code using the DocumentTemplate entity in the 2016 SDK.

Also you cannot modify or export a template that you have loaded in CRM so you need to ensure you keep your original template in a safe place in case you ever want to change it. Alternatively write some code to retrieve it and save it out to a file.  Below is a snippet of code that will retrieve all the document templates and writes them to the c:temp folder. It uses the document type to determine the file type to apply. 

      CrmServiceClient conn = new CrmServiceClient(ConfigurationManager.ConnectionStrings[“CRMConnectionString”].ConnectionString);
      IOrganizationService _service = conn.OrganizationServiceProxy;

      QueryExpression qe = new QueryExpression();
      qe.EntityName = “documenttemplate”;
      qe.ColumnSet = new ColumnSet(true);
      EntityCollection retrieved = _service.RetrieveMultiple(qe);

      foreach (var t in retrieved.Entities)
      {
          Console.WriteLine(“account name:” + t[“name”]);
          int doctype = ((OptionSetValue)t[“documenttype”]).Value;
          string fileName = “c:\temp\” + t[“name”] + (doctype == 1 ? “.xlsx” : “.docx”);
          File.WriteAllBytes(fileName, Convert.FromBase64String((string) t[“content”]));
       }

Leave a Reply

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