Tags

, , ,

Hello Everyone,

Today i’ll start with the plugin which I often use and is considered very commonly used for various projects.

One of my client had a requirement in which, when the Opportunity Probability exceeds 90% then the related Account must be send an email regarding the requirement of Opportunity Products. Accounts were Vendors in my scenario.

Since I require multiple lines of Opportunity Products in my email, so it was not possible through workflow as we don’t have any option for selecting Opportunity Products.

  • I started with creating the Class Library Project in Visual Studio 2010. Remember to select .NET Framework 4.

 

  • Added the References from CRM-SDK and .Net

 

  • Then used the following directives in the following Plugin

 

  • The main code used in this plugin is to create Email along with fieldvalues “TO” and “FROM” using ‘partyId’ attribute from ‘activityparty’ entity.

 

  • And the code used to send mail using service requests.

 

If the Email router is set foe sending mails or configured through outlook then the following created email will be send.

  • The final code will look something like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Discovery;
using Microsoft.Crm.Sdk.Messages;
using System.ServiceModel;

namespace EmailOppr
{
    public class Oppr:IPlugin
    {
        IOrganizationService service;
        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);

            if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
            {
                Entity entity = (Entity)context.InputParameters["Target"];

                try
                {
                    if (entity.LogicalName == "opportunity")
                    {
                        if (entity.Contains("closeprobability"))
                        {
                            if ((int)entity.Attributes["closeprobability"] >= 90)
                            {
                                Guid opprid = entity.Id;
                                Entity Opprt = service.Retrieve("opportunity", opprid, new Microsoft.Xrm.Sdk.Query.ColumnSet(true));
                                Guid ownerId = ((EntityReference)Opprt.Attributes["ownerid"]).Id;
                                Entity owner = service.Retrieve("systemuser", ownerId, new Microsoft.Xrm.Sdk.Query.ColumnSet(true));
                                String ownerName = (String)owner.Attributes["fullname"];
                                Guid custId = ((EntityReference)Opprt.Attributes["customerid"]).Id;
                                String oppName = (String)Opprt.Attributes["name"];
                                int prob = (int)Opprt.Attributes["closeprobability"];
                                DateTime dt = (DateTime)Opprt.Attributes["estimatedclosedate"];
                                String subject = "An Opportunity has been created by " + ownerName + " , estimated to be closed by " + dt + " with the Probability of " + prob + ".<br><br>";
                                subject = subject + "The following profiles are required in the Opportunity.<br><br>";

                                var fetchXml = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>";
                                fetchXml += "<entity name='opportunityproduct'>";
                                fetchXml += "<attribute name='opportunityproductid' />";
                                fetchXml += "<attribute name='productid' />";
                                fetchXml += "<attribute name='quantity' />";
                                fetchXml += "<filter type='and'>";
                                fetchXml += "<condition attribute='opportunityid' operator='eq' value='" + opprid + "' />";
                                fetchXml += "</filter>";
                                fetchXml += "</entity>";
                                fetchXml += "</fetch>";

                                var result = service.RetrieveMultiple(new FetchExpression(fetchXml));
                                if (result.Entities.Count > 0)
                                {
                                    subject = subject + "[Opportunity Product Name] [Quantity]<br>";

                                    for (int i = 0; i < result.Entities.Count; i++)
                                    {

                                        Guid opprPd = ((Guid)result.Entities[i].Attributes["opportunityproductid"]);
                                        Guid opprPdId = ((EntityReference)result.Entities[i].Attributes["productid"]).Id;
                                        Entity opppd = service.Retrieve("product", opprPdId, new Microsoft.Xrm.Sdk.Query.ColumnSet(true));
                                        var opprPdName = opppd.Attributes["name"];
                                        Decimal qty = ((Decimal)result.Entities[i].Attributes["quantity"]);
                                        int q = (int)Math.Round(qty);
                                        subject = subject + opprPdName + "--------" + q + "<br>";
                                    }
                                }
                                subject = subject + "<br>Kindly check/ensure availability of the required Products by " + dt + "<br><br>";

                                Entity fromParty = new Entity("activityparty");
                                fromParty["partyid"] = new EntityReference("systemuser", ownerId);
                                Entity toParty = new Entity("activityparty");
                                toParty["partyid"] = new EntityReference("account", custId);

                                Entity Email = new Entity("email");
                                Email.Attributes["from"] = new Entity[] { fromParty };
                                Email.Attributes["to"] = new Entity[] { toParty };
                                Email.Attributes["subject"] = "New Opportunity Requirements";
                                Email.Attributes["regardingobjectid"] = new EntityReference("opportunity", opprid);
                                Email.Attributes["description"] = subject;
                                Email.Attributes["ownerid"] = new EntityReference("systemuser", ownerId);
                                Guid EmailId = service.Create(Email);

                                SendEmailRequest req = new SendEmailRequest();
                                req.EmailId = EmailId;
                                req.IssueSend = true;
                                req.TrackingToken = "";

                                SendEmailResponse res = (SendEmailResponse)service.Execute(req);

                            }

                        }

                    }

                }

                catch (Exception ex)
                {
                    throw new InvalidPluginExecutionException("An error occured in the Plugin.", ex);
                }

            }

        }

    }
}

 

Hope this will help someone to write the plugin for creating and sending email in CRM very easily now.

Thanks !!!

😀