deleriumbg

Plugin

Jun 19th, 2019
208
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 8.73 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using Microsoft.Crm.Sdk.Messages;
  5. using Microsoft.Crm.Sdk.Query;
  6. using Microsoft.Xrm.Sdk;
  7. using Microsoft.Xrm.Sdk.Client;
  8. using Microsoft.Xrm.Sdk.Query;
  9. using PluginXrm;
  10. using ColumnSet = Microsoft.Xrm.Sdk.Query.ColumnSet;
  11. using IncidentState = PluginXrm.IncidentState;
  12.  
  13. namespace UOP.Plugins.Case
  14. {
  15.     public class OnCaseChangeEmailStatusConfirmed_OnPostUpdateEmailAndResolveCase : IPlugin
  16.     {
  17.         private const string PreImageAlias = "Pre";
  18.         private const string PostImageAlias = "Post";
  19.         private Guid _accountId;
  20.  
  21.         public void Execute(IServiceProvider serviceProvider)
  22.         {
  23.             // Obtain the tracing service
  24.             ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
  25.  
  26.             // Obtain the execution context from the service provider
  27.             IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
  28.             if (context == null)
  29.             {
  30.                 tracingService.Trace($"Error in plugin {nameof(OnCaseChangeEmailStatusConfirmed_OnPostUpdateEmailAndResolveCase)} - Service context is null");
  31.                 throw new ArgumentNullException(nameof(context));
  32.             }
  33.  
  34.             //Depth check to prevent infinite loop
  35.             if (context.Depth > 2)
  36.             {
  37.                 return;
  38.             }
  39.  
  40.             // Obtain the organization service reference
  41.             IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
  42.             IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
  43.  
  44.             // The InputParameters collection contains all the data passed in the message request
  45.             if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
  46.             {
  47.                 // Obtain the target Case entity from the input parameters
  48.                 Entity target = (Entity)context.InputParameters["Target"];
  49.                 try
  50.                 {
  51.                     //If it's update get the latest data
  52.                     if (context.MessageName.Equals("update", StringComparison.InvariantCultureIgnoreCase) && target.Attributes.Contains("new_changeemailstatus") && target.Attributes["new_changeemailstatus"] != null)
  53.                     {
  54.                         //Obtain the pre image and post image entities
  55.                         Entity preImageEntity = (context.PreEntityImages != null && context.PreEntityImages.Contains(PreImageAlias)) ? context.PreEntityImages[PreImageAlias] : null;
  56.                         Entity postImageEntity = (context.PostEntityImages != null && context.PostEntityImages.Contains(PostImageAlias)) ? context.PostEntityImages[PostImageAlias] : null;
  57.  
  58.                         int? previousEmailStatus = preImageEntity?.GetAttributeValue<OptionSetValue>("new_changeemailstatus").Value;
  59.                         int? newEmailStatus = postImageEntity?.GetAttributeValue<OptionSetValue>("new_changeemailstatus").Value;
  60.                         int confirmedOptionSetValue = new OptionSetValue(100000002).Value;
  61.  
  62.                         if (newEmailStatus != confirmedOptionSetValue)
  63.                         {
  64.                             return;
  65.                         }
  66.  
  67.                         //Get all the active cases with title "Email Change Request" for the current account
  68.                         ServiceContext crmContext = new ServiceContext(service)
  69.                         {
  70.                             MergeOption = MergeOption.NoTracking
  71.                         };
  72.  
  73.                         _accountId = postImageEntity.GetAttributeValue<EntityReference>("accountid").Id;
  74.                         tracingService.Trace($"Attempting to retrieve all active Email Change Request cases for account with id {_accountId}");
  75.  
  76.                         List<Incident> allCases = (from incidents in crmContext.IncidentSet
  77.                                         join account in crmContext.AccountSet on incidents.CustomerId.Id equals postImageEntity.GetAttributeValue<EntityReference>("accountid").Id
  78.                                         where incidents.CustomerId.Id == postImageEntity.GetAttributeValue<EntityReference>("accountid").Id &&
  79.                                               incidents.Title.Equals("Email Change Request") &&
  80.                                               incidents.StateCode == IncidentState.Active
  81.                                         orderby incidents.CreatedOn descending
  82.                                         select incidents)
  83.                                         .ToList();
  84.  
  85.                         if (allCases.Count() == 0)
  86.                         {
  87.                             tracingService.Trace($"No active Email Change Request cases found for account with id {_accountId}");
  88.                             return;
  89.                         }
  90.  
  91.                         tracingService.Trace($"Retrieved {allCases.Count()} active Email Change Request cases for account id {_accountId}");
  92.  
  93.                         Incident latestCase = allCases.First();
  94.                         List<Incident> casesToClose = allCases.Skip(1).ToList();
  95.  
  96.                         if (casesToClose.Count() == 0)
  97.                         {
  98.                             tracingService.Trace($"No other active cases for account with id {_accountId}");
  99.                         }
  100.                         else
  101.                         {
  102.                             //Close all other cases setting their built-in status and status reason to Cancelled
  103.                             foreach (var currentCase in casesToClose)
  104.                             {
  105.                                 //currentCase["new_changeemailstatus"] = new OptionSetValue(100000003);
  106.  
  107.                                 SetStateRequest setStateRequest = new SetStateRequest
  108.                                 {
  109.                                     EntityMoniker = new EntityReference("incident", currentCase.Id),
  110.                                     State = new OptionSetValue(2),
  111.                                     Status = new OptionSetValue(6),
  112.                                 };
  113.  
  114.                                 service.Execute(setStateRequest);
  115.                                 tracingService.Trace($"Set case status to Cancelled for Case with ID {currentCase.Id}");
  116.                             }
  117.                            
  118.                             tracingService.Trace($"Closed {casesToClose.Count()} cases with status reason \"Cancelled\" for account with id {_accountId}");
  119.                         }
  120.  
  121.                         //Change the case built-in status and status reason to Resolved and Problem solved respectively on the latest case created.
  122.                         //Create Incident Resolution
  123.                         var incidentResolutionResolved = new IncidentResolution
  124.                         {
  125.                             Subject = "Case Resolved",
  126.                             IncidentId = new EntityReference(Incident.EntityLogicalName, latestCase.Id),
  127.                             ActualEnd = DateTime.Now
  128.                         };
  129.  
  130.                         //Close Incident
  131.                         var closeIncidenRequstResolved = new CloseIncidentRequest
  132.                         {
  133.                             IncidentResolution = incidentResolutionResolved,
  134.                             Status = new OptionSetValue(5)
  135.                         };
  136.  
  137.                         service.Execute(closeIncidenRequstResolved);
  138.  
  139.                         //Change the Change Email Status to Approved on the latest case created.
  140.                         latestCase["new_changeemailstatus"] = new OptionSetValue(100000004);
  141.                         tracingService.Trace($"Set case status to Approved for Case with ID {latestCase.Id}");
  142.  
  143.                         Entity accountObj = service.Retrieve("account", _accountId, new ColumnSet(true));
  144.                         accountObj.Attributes["emailaddress1"] = latestCase.GetAttributeValue<string>("new_newemail");
  145.                         tracingService.Trace($"Updated account's email to {latestCase.GetAttributeValue<string>("new_newemail")}");
  146.                         service.Update(accountObj);
  147.                     }
  148.                 }
  149.                 catch (Exception ex)
  150.                 {
  151.                     tracingService.Trace($"An error occurred in {nameof(OnCaseChangeEmailStatusConfirmed_OnPostUpdateEmailAndResolveCase)}. Exception details: {ex.Message}");
  152.                     throw new InvalidPluginExecutionException(ex.Message);
  153.                 }
  154.             }
  155.         }
  156.     }
  157. }
Advertisement
Add Comment
Please, Sign In to add comment