Create a quick template engine for Power Platform

Summary

Here is a quick method for creating a templating engine for Microsoft Power Platform.

Let’s say you have the following text that you want to turn into a letter:

Dear {fullname}, we have sent your monthly invoice to: {emailaddress1}. Thank you for shopping at ACME.

In this post I’ll demonstrate how to do just that.

Templating Engine

The following code written in C# will compile and result in a string that you can use in letters/emails or other communication channels.

By calling a function and using string interpolation, you can inject values to complete a sentence.

using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using System;

namespace Discovery
{
    internal class Program
    {
        private static IOrganizationService _service;
        private static Guid _id;

        private static void Main(string[] args)
        {
            // Connect to Dynamics 365 Source
            _service = DynamicsService.Environment.ConnectSource();
            _id = new Guid("34C8B2C13A79EC118D21002248008FED");

            string template = $"Dear Mr {Q("contact", "fullname")}, we have sent your monthly invoice to {Q("contact", "emailaddress1")}. Thank you for shopping at ACME.";

        }

        private static string Q(string entity, string attribute)
        {
            Entity e = _service.Retrieve(entity, _id, new ColumnSet(new string[] { attribute }));
            string t = string.Empty;

            if (e.Attributes.ContainsKey(attribute) && e.Attributes[attribute] != null)
            {
                t = (string)e[attribute];
            }

            return t;
        }
    }
}

Leave a comment