jeudi 13 juin 2019

Loop through list and add class properties to dictionary

I have an email generator that currently works perfectly, but I'm now designing a template that is going to take in a list of objects. Each object has a few properties, but they are in theory the same class. I'm wanting to loop through and add the properties from each list item into the dictionary, and then use the same template piece and replace the keywords.

I have a the MesssageData file

public class FeedMessageValue
{
    public string Username { get; set; }
    public string SubscriptionID { get; set; }
    public DateTime MessageTime { get; set; }
}

public class FeedMessageData : IMailData
{
    private FeedMessageValue feedMessageValue;
    public Dictionary<string, string> MergeData { get; }

    public FeedMessageData(string username, string subscriptionID, DateTime messageTime)
    {
        this.MergeData = new Dictionary<string, string>();

        this.feedMessageValue = new FeedMessageValue
        {
             Username = username
           , SubscriptionID = subscriptionID
           , MessageTime = messageTime
        };

        PropertyInfo[] infos = this.feedMessageValue.GetType().GetProperties();
        foreach (PropertyInfo info in infos)
        {
            this.MergeData.Add(info.Name, info.GetValue(this.feedMessageValue, null).ToString());
        }
    }
}

This is passed into the Email Generator

public interface IMailData
{
    Dictionary<string, string> MergeData { get; }
}

public interface IEmailGenerator
{
    MailMessage generateEmail(IMailData mailData, string htmlTemplate, string textTemplate);
}

public class EmailGenerator : IEmailGenerator, IRegisterInIoC
{
    static readonly Regex emailRegex = new Regex(@"\$([\w\-\,\.]+)\$", RegexOptions.Compiled);

    private string mergeTemplate(string template, IReadOnlyDictionary<string, string> values)
    {
        string emailTextData = emailRegex.Replace(template, match => values[match.Groups[1].Value]);
        return emailTextData;
    }

    public MailMessage generateEmail(IMailData mailData, string htmlTemplate, string textTemplate)
    {
        // MailMessage Code
    }
}

When the action is called to generate the email then it looks like this. Here you can see the different template elements. They are split due to some of the parts are reused in other emails. EmailTemplates.Body is the template part that will be used multiple times, but with different information. This means that the longer the list of original items, the longer the email becomes.

var mailMessage = this.emailGenerator.generateEmail(mailData, EmailTemplates.Header + EmailTemplates.Body + EmailTemplates.Footer, EmailTemplates.BodyTextVersion);





Aucun commentaire:

Enregistrer un commentaire