How to create Email activity with dynamically retreived data from Dynamics CRM through Plugin C#

In this blog, I am going to show how we can add dynamically retreived data from CRM in a table and show this data inside a table within the Email body. Apart from adding dynamic data in a table into Email body I have also added code for showing Image which we have saved in web resources inside CRM. In short this blog covers below point:


  • Adding Image from Web Resources
  • Creating HTML formatted table from DataTable
  • Converting EntityCollection into DataTable
  • Showing dynamic data in Email body description

 1. First of all below required namespaces in your code(Add required references)
 using Microsoft.Crm.Sdk.Messages;
 using Microsoft.Xrm.Sdk;
 using Microsoft.Xrm.Sdk.Query;
 using System;
 using System.Collections.Generic;
 using System.Data;
 using System.Linq;
 2. Now Goto your CRM Settings, Add a web resource of type Image.
 3. Now Add below codes in the Execute method of your plugin as it is:
 public class Class1 : IPlugin
   {
     public void Execute(IServiceProvider serviceProvider)
     {
       IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
       IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
       IOrganizationService service = (IOrganizationService)serviceFactory.CreateOrganizationService(context.UserId);
       if (context.MessageName == "Update" && context.Stage == 40)
       {
         if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity && (context.PrimaryEntityName == "lead"))
         {
           Entity entLead = (Entity)context.InputParameters["Target"];
           Entity entLeadPreImage = context.PreEntityImages["preImageLead"] as Entity;
           if (entLead != null && entLeadPreImage != null)
           {
             string sCompanyName = string.Empty;
             string sLeadDataDescription = string.Empty;
             string sLogoImg = string.Empty;
             string sImageName = string.Empty;
             string sName = string.Empty;
             sName = entLead.GetAttributeValue<string>("fullname");
             if (sName == null)
               sName = entLeadPreImage.GetAttributeValue<string>("fullname");
             sCompanyName = entLead.GetAttributeValue<string>("companyname");
             if (sCompanyName == null)
               sCompanyName = entLeadPreImage.GetAttributeValue<string>("companyname");
             //From Current User
             Entity from = new Entity("activityparty");
             from["partyid"] = new EntityReference("systemuser", context.UserId);
             // To the Newly Created Lead User
             Entity to = new Entity("activityparty");
             to["partyid"] = new EntityReference("lead", entLead.Id);
 // Below I have used Dictionary for adding attribute schema name and column header name as a Key-Value pair for creating Table
             Dictionary<string, string> LeadDataList = new Dictionary<string, string>();
             LeadDataList.Add("Topic", "subject");
             LeadDataList.Add("Company Name", "companyname");
             LeadDataList.Add("Email Address", "emailaddress1");
             LeadDataList.Add("Address", "address1_composite");
             string[] sHeaderLeadData = LeadDataList.Keys.ToArray();
             string[] sFieldsToQryLeadData = LeadDataList.Values.ToArray();
             sImageName = "new_logo.png";
             sLogoImg = "<img src='~/WebResources/" + sImageName + "' width='30' height='30'>";
             DataTable dtLeadDataTable = GetData("lead", entLead.Id, true, sFieldsToQryLeadData, service);
             sLeadDataDescription = getHtmlFormatCommon(dtLeadDataTable, sHeaderLeadData, sFieldsToQryLeadData);
             //Create Email
             Entity Email = new Entity("email");
             Email["from"] = new Entity[] { from };
             Email["to"] = new Entity[] { to };
             Email["subject"] = "Welcome Mr./ Mrs " + sName;
             //Setting Values in the variables below which I have to add in the Email Body Description
             string sGeneralDisclaimer = "<h2>General Disclaimer</h2>" +
                           "<h5>The details shown below in the table are for demo purpose only</h5>";
             sCompanyName = "<h5>Company Name: " + sCompanyName + "</h5>";
             sLeadDataDescription = "<h2>" + sLogoImg + " Airport Policy & Charges</h2>" + sLeadDataDescription + "" + "<br/>";
             //Description_Ends
             Email["description"] = sCompanyName + sGeneralDisclaimer + sLeadDataDescription;
             Email["regardingobjectid"] = new EntityReference("lead", entLead.Id);
             Guid _emailId = service.Create(Email);
             SendEmailRequest reqSendEmail = new SendEmailRequest();
             reqSendEmail.EmailId = _emailId;
             reqSendEmail.TrackingToken = "";
             reqSendEmail.IssueSend = true;
             SendEmailResponse res = (SendEmailResponse)service.Execute(reqSendEmail);
           }
         }
       }
     }
 // This method is used to fetch Data from the Entity
     private DataTable GetData(string sEntityName, Guid entLeadId, bool IsLeadData, string[] strFieldsToQrySuppliers, IOrganizationService service)
     {
       DataTable dtRecords = new DataTable();
       string sFetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' no-lock='true' distinct='true' >" +
                 "<entity name='" + sEntityName + @"'>";
       foreach (string strAttribute in strFieldsToQrySuppliers)
       {
         sFetchXml += "<attribute name='" + strAttribute + "' />";
       }
       sFetchXml += "<filter type='and'>";
       if (IsLeadData)
         sFetchXml += "<condition attribute='leadid' operator='eq' value='" + entLeadId + @"' />";
       else
         sFetchXml += "<condition attribute='new_leadid' operator='eq' value='" + entLeadId + @"' />";
       sFetchXml += "</filter></entity></fetch>";
       EntityCollection ecContacts = service.RetrieveMultiple(new FetchExpression(sFetchXml));
       dtRecords = GetDataTable(ecContacts);
       return dtRecords;
     }
 // This method converts the EntityCollection into DataTable and returns Data Table
     private DataTable GetDataTable(EntityCollection ecEntities)
     {
       DataTable dTable = new DataTable();
       int iElement = 0;
       if (ecEntities.Entities.Count <= 0)
       {
         return null;
       }
       //Defining the ColumnName for the datatable
       for (iElement = 0; iElement <= ecEntities.Entities[0].Attributes.Count - 1; iElement++)
       {
         string columnName = ecEntities.Entities[0].Attributes.Keys.ElementAt(iElement);
         dTable.Columns.Add(columnName);
       }
       foreach (Entity entity in ecEntities.Entities)
       {
         DataRow dRow = dTable.NewRow();
         for (int i = 0; i <= entity.Attributes.Count - 1; i++)
         {
           string colName = entity.Attributes.Keys.ElementAt(i);
           dRow[colName] = entity.Attributes.Values.ElementAt(i);
         }
         dTable.Rows.Add(dRow);
       }
       return dTable;
     }
 // This method creates HTML formatted Table for the Data table
     private string getHtmlFormatCommon(DataTable dtTable, string[] HeaderCollection, string[] strAttributes)
     {
       string messageBody = string.Empty;
       if (dtTable.Rows.Count == 0)
         return messageBody;
       foreach (DataRow Row in dtTable.Rows)
       {
         string htmlTableStart = "<table style='border-collapse:collapse;border-color:#5c87b2; border-style:solid;border-width:thin; text-align:left; width:100%' >";
         string htmlTableEnd = "</table>";
         string htmlTrStart = "<tr style ='color:#000000'>";
         string htmlTrEnd = "</tr>";
         string htmlHeaderTdStart = "<td style='width:60%; padding: 5px;'>";
         string htmlTdStart = "<td style='width:40%; padding: 5px;'>";
         string htmlTdEnd = "</td>";
         messageBody += htmlTableStart;
         for (int i = 0; i < HeaderCollection.Length; i++)
         {
           messageBody = messageBody + htmlTrStart;
           messageBody = messageBody + htmlHeaderTdStart + HeaderCollection[i] + htmlTdEnd;
           messageBody = messageBody + htmlTdStart + Row[strAttributes[i]] + htmlTdEnd;
           messageBody = messageBody + htmlTrEnd;
         }
         messageBody = messageBody + htmlTableEnd;
       }
       return messageBody;
     }
   }
 Output of Email record will be like this:


Comments

  1. You write this post very carefully I think, which is easily understand to me. Not only this, other post is also good. As a newbie this info is really helpful for me. Thanks to you.
    tally training
    Tally Training in Chennai
    Tally ERP 9 Training
    Tally Course
    tally classes
    Tally institute in Chennai
    Tally Training institute in Chennai
    Tally course in Chennai

    ReplyDelete

Post a Comment

Popular posts from this blog

Search data in Gridview on Textbox Key press event using JQuery in Asp.Net- C#

StateCode and StatusCode Values for mostly used entities in Microsoft Dynamics CRM 2013

Dumps for Microsoft Dynamics CRM MB2-703 Practice Exam Questions Free

How to import CSV files into DataTable in C#

How to show enlarge image when mouse hover on image or link in Asp.Net(c#) using JavaScript

go to top image