Tool to Synchronize email templates between different SendGrid accounts

Hi All,

Here I'll directly provide my code where I developed a tool to copy email templates from one SendGrid account to another SendGrid account.

It is nice to have a such tool when migrating all of your newly created and modified email templates from develop environment to production servers.

So here is the code that I have came up with:

public class EmailSyncService : IEmailSyncService
    {
        private readonly EmailSyncSettingsModel _emailSyncSettingsModel;

        public EmailSyncService(IOptions<EmailSyncSettingsModel> emailSyncSettingsModel)
        {
            _emailSyncSettingsModel = emailSyncSettingsModel.Value;
        }

        public async Task<List<KeyValuePair<string, string>>> SyncSendGridTemplates(string source, string destination)
        {
            var newTemplates = new List<KeyValuePair<string, string>>();
            var sourceKey = _emailSyncSettingsModel.GetType().GetProperty(source).GetValue(_emailSyncSettingsModel, null).ToString();
            var destinationKey = _emailSyncSettingsModel.GetType().GetProperty(destination).GetValue(_emailSyncSettingsModel, null).ToString();

            var sourceClient = new SendGridClient(sourceKey);
            var destinationClient = new SendGridClient(destinationKey);

            var sourceRequest = await sourceClient.RequestAsync(
                    method: SendGridClient.Method.GET,
                    urlPath: "templates"
                );
            var sourceResponse = sourceRequest.Body.ReadAsStringAsync().Result;

            var destinationRequest = await destinationClient.RequestAsync(
                    method: SendGridClient.Method.GET,
                    urlPath: "templates"
                );
            var destinationResponse = destinationRequest.Body.ReadAsStringAsync().Result;

            var sourceTemplates = JsonConvert.DeserializeObject<Template>(sourceResponse);
            var destinationTemplates = JsonConvert.DeserializeObject<Template>(destinationResponse);

            foreach (var st in sourceTemplates.templates)
            {
                var sTemplateRequest = await sourceClient.RequestAsync(
                    method: SendGridClient.Method.GET,
                    urlPath: string.Format("templates/{0}", st.id)
                );
                var sTemplateResponse = sTemplateRequest.Body.ReadAsStringAsync().Result;
                var sTemplate = JsonConvert.DeserializeObject<EmailTemplate>(sTemplateResponse);

                var existingTemplate = destinationTemplates.templates.Find(t => t.name == st.name);
                if (existingTemplate != null)
                {
                    var dTemplateRequest = await destinationClient.RequestAsync(
                            method: SendGridClient.Method.GET,
                            urlPath: string.Format("templates/{0}", existingTemplate.id)
                        );

                    var dTemplateResponse = dTemplateRequest.Body.ReadAsStringAsync().Result;
                    var dTemplate = JsonConvert.DeserializeObject<EmailTemplate>(dTemplateResponse);

                    //Update Template
                    if (sTemplate.versions[0].html_content != dTemplate.versions[0].html_content)
                    {
                        dynamic utVersionObject = new JObject();
                        utVersionObject.active = 1;
                        utVersionObject.html_content = sTemplate.versions[0].html_content;
                        utVersionObject.name = sTemplate.versions[0].name;
                        utVersionObject.plain_content = sTemplate.versions[0].plain_content;
                        utVersionObject.subject = sTemplate.versions[0].subject;

                        var utVersionJson = JsonConvert.DeserializeObject<object>(utVersionObject.ToString());
                        var utVersionData = utVersionJson.ToString();
                        var tvUpdateRequest = await destinationClient.RequestAsync(
                                method: SendGridClient.Method.PATCH, 
                                urlPath: "templates/" + dTemplate.id + "/versions/" + dTemplate.versions[0].id, 
                                requestBody: utVersionData
                            );
                        var tvUpdateResponse = tvUpdateRequest.Body.ReadAsStringAsync().Result;
                        if (tvUpdateResponse == null)
                        {
                            return newTemplates;
                        }
                    }
                }
                else
                {
                    //Create Template
                    string data = @"{'name': '" + sTemplate.name + "'}";
                    var json = JsonConvert.DeserializeObject<object>(data);
                    data = json.ToString();
                    var tCreateRequest = await destinationClient.RequestAsync(
                            method: SendGridClient.Method.POST, 
                            urlPath: "templates", 
                            requestBody: data
                        );
                    var tCreateResponse = tCreateRequest.Body.ReadAsStringAsync().Result;
                    if (tCreateResponse != null)
                    {
                        var newTemplate = JsonConvert.DeserializeObject<EmailTemplate>(tCreateResponse);

                        //Create template version
                        dynamic tVersionObject = new JObject();
                        tVersionObject.active = 1;
                        tVersionObject.html_content = sTemplate.versions[0].html_content;
                        tVersionObject.name = sTemplate.versions[0].name;
                        tVersionObject.plain_content = sTemplate.versions[0].plain_content;
                        tVersionObject.subject = sTemplate.versions[0].subject;
                        
                        var versionJson = JsonConvert.DeserializeObject<object>(tVersionObject.ToString());
                        var versionData = versionJson.ToString();
                        var vCreateRequest = await destinationClient.RequestAsync(
                                method: SendGridClient.Method.POST, 
                                urlPath: "templates/" + newTemplate.id + "/versions", 
                                requestBody: versionData
                            );
                        var vCreateResponse = vCreateRequest.Body.ReadAsStringAsync().Result;
                        if (vCreateResponse != null)
                        {
                            newTemplates.Add(new KeyValuePair<string, string>(newTemplate.name, newTemplate.id));
                        }
                    }
                }
            }
            return newTemplates;
        }
    }


Comments

Post a Comment

Popular posts from this blog

Deploy Angular 8 app to Azure with Azure DevOps

Apache ActiveMQ 5 with .Net Core 3.1 and C#

Firebase with.Net Core and C#