deleriumbg

CRM Email Plugin

Jun 14th, 2019
326
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 5.99 KB | None | 0 0
  1. using System;
  2. using Microsoft.Crm.Sdk.Messages;
  3. using Microsoft.Xrm.Sdk;
  4. using Microsoft.Xrm.Sdk.Query;
  5. using PluginXrm;
  6.  
  7.  
  8. namespace UOP.Plugins.Case
  9. {
  10.     public class OnCreateEmailChangeRequestCase_SendEmailToAccountPreviousEmail : IPlugin
  11.     {
  12.         private Guid _emailId;
  13.         private Guid _contactId;
  14.         private Guid _userId;
  15.  
  16.         public void Execute(IServiceProvider serviceProvider)
  17.         {
  18.             // Obtain the tracing service
  19.             ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
  20.  
  21.             // Obtain the execution context from the service provider
  22.             IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
  23.             if (context == null)
  24.             {
  25.                 tracingService.Trace($"Error in plugin {nameof(OnCreateEmailChangeRequestCase_SendEmailToAccountPreviousEmail)} - Service context is null");
  26.                 throw new ArgumentNullException(nameof(context));
  27.             }
  28.  
  29.             //Depth check to prevent infinite loop
  30.             if (context.Depth > 2)
  31.             {
  32.                 return;
  33.             }
  34.  
  35.             // Obtain the organization service reference
  36.             IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
  37.             IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
  38.  
  39.             // The InputParameters collection contains all the data passed in the message request
  40.             if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
  41.             {
  42.                 // Obtain the target Case entity from the input parameters
  43.                 Entity target = (Entity)context.InputParameters["Target"];
  44.                 try
  45.                 {
  46.                     //If it's update get the latest data
  47.                     if (context.MessageName.Equals("create", StringComparison.InvariantCultureIgnoreCase) && target["title"].Equals("Email Change Request"))
  48.                     {
  49.                         tracingService.Trace($"Attempting to retrieve case with title Email Change Request...");
  50.  
  51.                         // Get a system user to send the email (From: field)
  52.                         WhoAmIRequest systemUserRequest = new WhoAmIRequest();
  53.                         WhoAmIResponse systemUserResponse = (WhoAmIResponse)service.Execute(systemUserRequest);
  54.                         _userId = systemUserResponse.UserId;
  55.  
  56.                         //Get the email recipient user (Contact entity)
  57.                         EntityReference customer = (EntityReference)target.Attributes["customerid"];
  58.                         Entity caseCustomer = service.Retrieve("account", customer.Id, new ColumnSet("primarycontactid"));
  59.                         if (caseCustomer == null)
  60.                         {
  61.                             return;
  62.                         }
  63.  
  64.                         EntityReference contactReference = (EntityReference)caseCustomer.Attributes["primarycontactid"];
  65.                         Entity contact = service.Retrieve("contact", contactReference.Id, new ColumnSet(true));
  66.                         _contactId = contact.Id;
  67.  
  68.                         // Create the 'From:' activity party for the email
  69.                         ActivityParty fromParty = new ActivityParty
  70.                         {
  71.                             PartyId = new EntityReference(SystemUser.EntityLogicalName, _userId)
  72.                         };
  73.  
  74.                         // Create the 'To:' activity party for the email
  75.                         ActivityParty toParty = new ActivityParty
  76.                         {
  77.                             PartyId = new EntityReference(Contact.EntityLogicalName, _contactId)
  78.                         };
  79.  
  80.                         tracingService.Trace("Created To and From activity parties.");
  81.  
  82.                         // Create an email message entity
  83.                         Email email = new Email
  84.                         {
  85.                             To = new ActivityParty[] { toParty },
  86.                             From = new ActivityParty[] { fromParty },
  87.                             Subject = "Confirm email change request",
  88.                             Description = $"Hello, {contact.GetAttributeValue<string>("fullname")}. \r\n" +
  89.                                           $"We received your request to change your primary email address from {target.GetAttributeValue<string>("new_previousemail")} " +
  90.                                           $"to {target.GetAttributeValue<string>("new_newemail")}.\r\n" +
  91.                                           $"Please CLICK HERE to confirm your request",
  92.                             DirectionCode = true
  93.                         };
  94.                         _emailId = service.Create(email);
  95.                         tracingService.Trace($"Created {email.Subject} email.");
  96.                         tracingService.Trace($"Email description: {email.Description}.");
  97.  
  98.                         SendEmailRequest sendEmailRequest = new SendEmailRequest
  99.                         {
  100.                             EmailId = _emailId,
  101.                             TrackingToken = "",
  102.                             IssueSend = true
  103.                         };
  104.  
  105.                         SendEmailResponse sendEmailResponse = (SendEmailResponse)service.Execute(sendEmailRequest);
  106.                         tracingService.Trace($"Sent the confirm email change request message to user with id {contact.Id}.");
  107.                     }
  108.                 }
  109.                 catch (Exception ex)
  110.                 {
  111.                     tracingService.Trace($"An error occurred in {nameof(OnCreateEmailChangeRequestCase_SendEmailToAccountPreviousEmail)}. Exception details: {ex.Message}");
  112.                     throw new InvalidPluginExecutionException(ex.Message);
  113.                 }
  114.             }
  115.         }
  116.     }
  117. }
Advertisement
Add Comment
Please, Sign In to add comment