C# Antlr String Template + Embedded Resources

Date: 2016-10-25
using Application.Business.Repository;
using Application.Business.UnitOfWork;
using log4net;
using Antlr4.StringTemplate;
using System.Globalization;
using System.Reflection;
using System.IO;

namespace Application.Business.Service
{
    public class ResourceTemplates 
    {
        public const string InvoiceUploaded = "Application.Business.Templates.Email.InvoiceUploaded.html";
        public const string PasswordRequest = "Application.Business.Templates.Email.PasswordRequest.html";
    }

    public class TemplateService : BaseService
    {
        private static TemplateService instance;
        public static TemplateService Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new TemplateService();
                }
                return instance;
            }
        }

        public TemplateService() : base(new RepositoryFactory(), new UnitOfWorkFactory(), LogManager.GetLogger(typeof(UserService)))
        {
        }

        public string GetEmbeddedResourceAsString(string resourceName) {
            var assembly = Assembly.GetExecutingAssembly();
            // assembly.GetManifestResourceNames(); // Get all the resources
            using (Stream stream = assembly.GetManifestResourceStream(resourceName))
            {
                if (stream != null)
                {
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        string result = reader.ReadToEnd();
                        return result;
                    }
                }
                return string.Empty;
            }
        }

        public string ProcessResourceTemplate(string resourceName, string[,] parameters)
        {
            string template = GetEmbeddedResourceAsString(resourceName);
            return ProcessTemplate(template, parameters);
        }

        public string ProcessTemplate(string stringTemplate, string[,] parameters) 
        {
            TemplateGroup templateGroup = new TemplateGroup('{', '}');
            Template template = new Template(templateGroup, stringTemplate);

            for (int i = 0; i < parameters.GetLength(0);i += 1)
            {
                template.Add(parameters[i, 0], parameters[i, 1]);
            }
            return template.Render(new CultureInfo("nl-NL"), 200);
        }
    }
}
5350cookie-checkC# Antlr String Template + Embedded Resources