How to Write a Plugin when a Case is resolved with use Email Template in C#

In this blog, I am going to explain how we can fire a plugin on Resolved Case. Additionally I have added methods which shows how we can use Email Template too.

Follwing points is important when working on resolved case plugin:
1. To fire a plugin when an incident is resolved we need to register the plugin in "Close" message for the incident entity.

2. In Input parameters of the context we need to check for IncidentResolution (this entity holds information of case being closed).

Put below codes inside your Plugin, In my sample code I am creating an email activity after case gets resolved.

        public class IncidentPostCloseHandler : IPlugin
            public void Execute(IServiceProvider serviceProvider)
                    IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
                    IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                    IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

                    #region Variable.Declaration
                    Entity entCase = null;
                    string sEmailSubject = string.Empty, sEmailBody = string.Empty;
                    OptionSetValue osvBeneficiary = null;
                    EntityReference erCaller, erProposer = null;

                    if (Service.IsContextValidForPostCreate(context, "incident"))
                        entCase = CrmEntity.GetEntityFromContextInputParameter(context);

                        erCaller = entCase.GetAttributeValue("customerid");
                        erProposer = entCase.GetAttributeValue("new__proposer");
                        osvBeneficiary = entCase.GetAttributeValue("rhi_beneficiary");

                            if (osvBeneficiary.Value == 1)
                                EntityReference erSender = entCase.GetAttributeValue("rhi_crmadmin");

                                List To = new List();

                                if (erCaller.Id != erProposer.Id)

                                string sEmailTemplateName = "Closed Case Acknowledgement";
                                GetEmailBodyAndSubject(out sEmailSubject, out sEmailBody, sEmailTemplateName, entCase, service);

                                //Create Email Activity
                                SendEmailUsingXrmActivity(To, erSender.Id, "contact", "systemuser", sEmailSubject, sEmailBody, entCase.Id, entCase.LogicalName.ToString(), service);
                        catch (Exception ex) { throw new InvalidPluginExecutionException(ex.Message); }
                catch (Exception ex) { throw new InvalidPluginExecutionException(ex.Message); }

        public static void SendEmailUsingXrmActivity(List idTo, Guid idFrom, string sTo_EntityName, string sFrom_EntityName, string sSubject, string sBody, Guid idRegarding, string sRegaring_EntityName, IOrganizationService srvPortal)
            EntityReference erTo;
            EntityReference erFrom;
            EntityCollection ecToCollection = null;
            ecToCollection = new EntityCollection() { EntityName = sTo_EntityName };

            foreach (Guid gTo in idTo)
                erTo = new EntityReference(sTo_EntityName, gTo);

                Entity entTo = new Entity("activityparty");
                entTo.Attributes.Add("partyid", erTo);

            erFrom = new EntityReference(sFrom_EntityName, idFrom);

            Entity entFrom = new Entity("activityparty");
            entFrom.Attributes.Add("partyid", erFrom);
            EntityCollection ecFromCollection;
            ecFromCollection = new EntityCollection() { EntityName = sFrom_EntityName };

            Entity entEmail = new Entity("email");
            entEmail["to"] = ecToCollection;
            entEmail["from"] = entFrom;
            entEmail["subject"] = sSubject;
            entEmail["description"] = sBody;
            entEmail["directioncode"] = true;

        public static void GetEmailBodyAndSubject(out string sEmailSubject, out string sEmailBody, string sTemplateName, Entity entCase, IOrganizationService service)
            sEmailSubject = string.Empty;
            sEmailBody = string.Empty;

            //Get EmailTemplateId
            Guid gTemplateId = GetRecordId(service, "template", "title", sTemplateName, "templateid");

            InstantiateTemplateRequest instTemplateReq = new InstantiateTemplateRequest
                TemplateId = gTemplateId,
                ObjectId = entCase.Id,
                ObjectType = entCase.LogicalName.ToString()

            InstantiateTemplateResponse instTemplateResp = (InstantiateTemplateResponse)service.Execute(instTemplateReq);
            if (instTemplateResp != null)
                Entity template = instTemplateResp.EntityCollection.Entities[0];
                if (template != null && template.Attributes.Contains("description"))
                    sEmailBody = template.Attributes["description"].ToString();
                if (template != null && template.Attributes.Contains("subject"))
                    sEmailSubject = template.Attributes["subject"].ToString();

        public static Guid GetRecordId(IOrganizationService service, string entityName, string keyAttribute, string keyValue, string recordGuidField)
            Guid recordsGuid = Guid.Empty;

var fetchXml = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>";
            fetchXml += "<entity name='" + entityName + "'>";
            fetchXml += "<attribute name='" + recordGuidField + "' />";
            fetchXml += "<attribute name='createdon' />";
            fetchXml += "<order attribute='createdon' descending='true' />";
            fetchXml += "<filter type='and'>";
            fetchXml += "<condition attribute='" + keyAttribute + "' operator='eq' value='" + System.Net.WebUtility.HtmlEncode(keyValue.ToString()) + "' />";
            fetchXml += "</filter>";
            fetchXml += "</entity>";
            fetchXml += "</fetch>";

            var result = service.RetrieveMultiple(new FetchExpression(fetchXml));

            if (result.Entities.Count > 0)
                recordsGuid = (Guid)result.Entities[0].Attributes[recordGuidField];
            return recordsGuid;


Popular posts from this blog

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

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

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

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

Show GridView row details in tooltip on mouseover with jQuery using inside GridView in c#

go to top image