Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using Microsoft.Crm.Sdk.Messages;
- using Microsoft.Crm.Sdk.Query;
- using Microsoft.Xrm.Sdk;
- using Microsoft.Xrm.Sdk.Client;
- using Microsoft.Xrm.Sdk.Query;
- using PluginXrm;
- using ColumnSet = Microsoft.Xrm.Sdk.Query.ColumnSet;
- using IncidentState = PluginXrm.IncidentState;
- namespace UOP.Plugins.Case
- {
- public class OnCaseChangeEmailStatusConfirmed_OnPostUpdateEmailAndResolveCase : IPlugin
- {
- private const string PreImageAlias = "Pre";
- private const string PostImageAlias = "Post";
- private Guid _accountId;
- public void Execute(IServiceProvider serviceProvider)
- {
- // Obtain the tracing service
- ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
- // Obtain the execution context from the service provider
- IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
- if (context == null)
- {
- tracingService.Trace($"Error in plugin {nameof(OnCaseChangeEmailStatusConfirmed_OnPostUpdateEmailAndResolveCase)} - Service context is null");
- throw new ArgumentNullException(nameof(context));
- }
- //Depth check to prevent infinite loop
- if (context.Depth > 2)
- {
- return;
- }
- // Obtain the organization service reference
- IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
- IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
- // The InputParameters collection contains all the data passed in the message request
- if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
- {
- // Obtain the target Case entity from the input parameters
- Entity target = (Entity)context.InputParameters["Target"];
- try
- {
- //If it's update get the latest data
- if (context.MessageName.Equals("update", StringComparison.InvariantCultureIgnoreCase) && target.Attributes.Contains("new_changeemailstatus") && target.Attributes["new_changeemailstatus"] != null)
- {
- //Obtain the pre image and post image entities
- Entity preImageEntity = (context.PreEntityImages != null && context.PreEntityImages.Contains(PreImageAlias)) ? context.PreEntityImages[PreImageAlias] : null;
- Entity postImageEntity = (context.PostEntityImages != null && context.PostEntityImages.Contains(PostImageAlias)) ? context.PostEntityImages[PostImageAlias] : null;
- int? previousEmailStatus = preImageEntity?.GetAttributeValue<OptionSetValue>("new_changeemailstatus").Value;
- int? newEmailStatus = postImageEntity?.GetAttributeValue<OptionSetValue>("new_changeemailstatus").Value;
- int confirmedOptionSetValue = new OptionSetValue(100000002).Value;
- if (newEmailStatus != confirmedOptionSetValue)
- {
- return;
- }
- //Get all the active cases with title "Email Change Request" for the current account
- ServiceContext crmContext = new ServiceContext(service)
- {
- MergeOption = MergeOption.NoTracking
- };
- _accountId = postImageEntity.GetAttributeValue<EntityReference>("accountid").Id;
- tracingService.Trace($"Attempting to retrieve all active Email Change Request cases for account with id {_accountId}");
- List<Incident> allCases = (from incidents in crmContext.IncidentSet
- join account in crmContext.AccountSet on incidents.CustomerId.Id equals postImageEntity.GetAttributeValue<EntityReference>("accountid").Id
- where incidents.CustomerId.Id == postImageEntity.GetAttributeValue<EntityReference>("accountid").Id &&
- incidents.Title.Equals("Email Change Request") &&
- incidents.StateCode == IncidentState.Active
- orderby incidents.CreatedOn descending
- select incidents)
- .ToList();
- if (allCases.Count() == 0)
- {
- tracingService.Trace($"No active Email Change Request cases found for account with id {_accountId}");
- return;
- }
- tracingService.Trace($"Retrieved {allCases.Count()} active Email Change Request cases for account id {_accountId}");
- Incident latestCase = allCases.First();
- List<Incident> casesToClose = allCases.Skip(1).ToList();
- if (casesToClose.Count() == 0)
- {
- tracingService.Trace($"No other active cases for account with id {_accountId}");
- }
- else
- {
- //Close all other cases setting their built-in status and status reason to Cancelled
- foreach (var currentCase in casesToClose)
- {
- //currentCase["new_changeemailstatus"] = new OptionSetValue(100000003);
- SetStateRequest setStateRequest = new SetStateRequest
- {
- EntityMoniker = new EntityReference("incident", currentCase.Id),
- State = new OptionSetValue(2),
- Status = new OptionSetValue(6),
- };
- service.Execute(setStateRequest);
- tracingService.Trace($"Set case status to Cancelled for Case with ID {currentCase.Id}");
- }
- tracingService.Trace($"Closed {casesToClose.Count()} cases with status reason \"Cancelled\" for account with id {_accountId}");
- }
- //Change the case built-in status and status reason to Resolved and Problem solved respectively on the latest case created.
- //Create Incident Resolution
- var incidentResolutionResolved = new IncidentResolution
- {
- Subject = "Case Resolved",
- IncidentId = new EntityReference(Incident.EntityLogicalName, latestCase.Id),
- ActualEnd = DateTime.Now
- };
- //Close Incident
- var closeIncidenRequstResolved = new CloseIncidentRequest
- {
- IncidentResolution = incidentResolutionResolved,
- Status = new OptionSetValue(5)
- };
- service.Execute(closeIncidenRequstResolved);
- //Change the Change Email Status to Approved on the latest case created.
- latestCase["new_changeemailstatus"] = new OptionSetValue(100000004);
- tracingService.Trace($"Set case status to Approved for Case with ID {latestCase.Id}");
- Entity accountObj = service.Retrieve("account", _accountId, new ColumnSet(true));
- accountObj.Attributes["emailaddress1"] = latestCase.GetAttributeValue<string>("new_newemail");
- tracingService.Trace($"Updated account's email to {latestCase.GetAttributeValue<string>("new_newemail")}");
- service.Update(accountObj);
- }
- }
- catch (Exception ex)
- {
- tracingService.Trace($"An error occurred in {nameof(OnCaseChangeEmailStatusConfirmed_OnPostUpdateEmailAndResolveCase)}. Exception details: {ex.Message}");
- throw new InvalidPluginExecutionException(ex.Message);
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment