private bool SendEmail(IExtendedExecutionContext context, Entity account, Incident caseRecord)
        {
            context.Trace($"Attempting to retrieve case with title Email Change Request...");

            // Get a system user to send the email (From: field)
            _userId = context.UserId;

            // Create the 'From:' activity party for the email
            ActivityParty fromParty = new ActivityParty
            {
                PartyId = new EntityReference(SystemUser.EntityLogicalName, _userId)
            };

            // Create the 'To:' activity party for the email
            ActivityParty toParty = new ActivityParty
            {
                PartyId     = new EntityReference(PluginXrm.Account.EntityLogicalName, _accountId),
                AddressUsed = account.GetAttributeValue <string>(Email)
            };

            context.Trace("Created To and From activity parties.");

            // Create an email message entity
            Email email = new Email
            {
                To          = new ActivityParty[] { toParty },
                From        = new ActivityParty[] { fromParty },
                Subject     = "Email change request confirmation",
                Description = $"Hello, {account.GetAttributeValue<string>(AccountName)}.{Environment.NewLine}" +
                              $"We received your request to change your primary email address from " +
                              $"{caseRecord.GetAttributeValue<string>(PreviousEmail)} to " +
                              $"{caseRecord.GetAttributeValue<string>(NewEmail)}.{Environment.NewLine}" +
                              @"Please <a href=""https://www.uopeople.edu/"">Click Here</a> to confirm your request",
                DirectionCode     = true,
                RegardingObjectId = new EntityReference(Incident.EntityLogicalName, _caseId)
            };

            _emailId = context.OrganizationService.Create(email);
            context.Trace($"Created {email.Subject} email with description: {email.Description}.");

            SendEmailRequest sendEmailRequest = new SendEmailRequest
            {
                EmailId       = _emailId,
                TrackingToken = string.Empty,
                IssueSend     = true
            };

            SendEmailResponse sendEmailResponse = (SendEmailResponse)context.OrganizationService.Execute(sendEmailRequest);

            return(sendEmailResponse != null);
        }
Exemplo n.º 2
0
        public override void ExecuteWorkflowActivity(IExtendedExecutionContext context)
        {
            // Depth check to prevent infinite loop
            if (context.Depth > 1)
            {
                return;
            }

            // 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 (context.MessageName.Equals("update", StringComparison.InvariantCultureIgnoreCase) &&
                        target.Attributes.Contains(ChangeEmailStatus) && target.Attributes[ChangeEmailStatus] != null)
                    {
                        context.Trace($"Entered {nameof(OnCaseConfirmChangeEmailStatus_ResolveCaseAndSendEmail)}.Execute()");
                        context.ClearPluginTraceLog(nameof(OnCaseConfirmChangeEmailStatus_ResolveCaseAndSendEmail));

                        if (context.PreImageEntity == null || context.PostImageEntity == null)
                        {
                            throw new ArgumentNullException(context.PreImageEntity == null ?
                                                            nameof(context.PreImageEntity) : nameof(context.PostImageEntity));
                        }

                        int newEmailStatus          = context.PostImageEntity.GetAttributeValue <OptionSetValue>(ChangeEmailStatus).Value;
                        int confirmedOptionSetValue = new OptionSetValue(100000002).Value; //Confirmed

                        if (newEmailStatus != confirmedOptionSetValue)
                        {
                            return;
                        }

                        // Retrieve the account related to the target case
                        _accountId = context.PostImageEntity.GetAttributeValue <EntityReference>("customerid").Id;
                        if (_accountId == null)
                        {
                            context.Trace($"Unable to retrieve the account. Aborting workflow execution.");
                            return;
                        }

                        // Retrieve all the active cases with title "Email Change Request" for the current account
                        var allCases = RetrieveAllEmailChangeRequestCases(context);
                        if (!allCases.Any())
                        {
                            context.Trace($"No active Email Change Request cases found for account with id {_accountId}");
                            return;
                        }

                        context.Trace($"Retrieved {allCases.Count} active Email Change Request cases for account id {_accountId}");

                        // Retrieve the latest active "Email Change Request" case for the current account and resolve it.
                        Incident latestCase = allCases.First();
                        ResolveCase(context, latestCase);

                        Entity account = context.OrganizationService.Retrieve(PluginXrm.Account.EntityLogicalName, _accountId,
                                                                              new ColumnSet(AccointId, AccountName, Email));
                        account.Attributes[Email] = latestCase.GetAttributeValue <string>(NewEmail);
                        context.Trace($"Updated account {account.GetAttributeValue<string>(AccountName)}'s email to " +
                                      $"{latestCase.GetAttributeValue<string>(NewEmail)}");
                        context.OrganizationService.Update(account);

                        //Retrieve all other active "Email Change Request" cases (if any) for the current account that need to be closed as duplicate.
                        var casesToClose = allCases.Skip(1).ToList();
                        if (!casesToClose.Any())
                        {
                            context.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)
                            {
                                CloseCase(context, currentCase);
                            }

                            context.Trace($"Closed {casesToClose.Count} cases with status reason Cancelled for account with id {_accountId}");
                        }

                        // Send Email to the account
                        bool mailSent = SendEmail(context, account, latestCase);
                        context.Trace(mailSent
                            ? $"Sent the email successfully changed message to user {account.GetAttributeValue<string>(AccountName)} with id {_accountId}."
                            : $"Email was not send successfully to user with id {_accountId}");
                    }
                }
                catch (Exception ex)
                {
                    context.Trace($"An error occurred in {nameof(OnCaseConfirmChangeEmailStatus_ResolveCaseAndSendEmail)}. " +
                                  $"Exception details: {ex.Message}");
                    throw new InvalidPluginExecutionException(ex.Message);
                }
                finally
                {
                    context.Trace($"Exiting {nameof(OnCaseConfirmChangeEmailStatus_ResolveCaseAndSendEmail)}.Execute()");
                }
            }
        }
        public override void Execute(ILocalPluginContext localContext)
        {
            // Depth check to prevent infinite loop
            if (localContext.PluginExecutionContext.Depth > 2)
            {
                return;
            }

            // The InputParameters collection contains all the data passed in the message request
            if (localContext.PluginExecutionContext.InputParameters.Contains(Target) &&
                localContext.PluginExecutionContext.InputParameters[Target] is Entity)
            {
                // Obtain the target Case entity from the input parameters
                Entity target = (Entity)localContext.PluginExecutionContext.InputParameters[Target];
                try
                {
                    // Check for update event
                    if (localContext.PluginExecutionContext.MessageName.Equals("update", StringComparison.InvariantCultureIgnoreCase) &&
                        target.Attributes.Contains(ChangeEmailStatus) && target.Attributes[ChangeEmailStatus] != null)
                    {
                        localContext.Trace("Entered {0}.Execute()", nameof(OnCaseChangeEmailStatusConfirmed_OnPostUpdateEmailAndResolveCase));
                        localContext.ClearPluginTraceLog(nameof(OnCaseChangeEmailStatusConfirmed_OnPostUpdateEmailAndResolveCase));

                        Entity postImageEntity = (localContext.PluginExecutionContext.PostEntityImages != null &&
                                                  localContext.PluginExecutionContext.PostEntityImages.Contains(PostImageAlias))
                            ? localContext.PluginExecutionContext.PostEntityImages[PostImageAlias]
                            : null;

                        int?newEmailStatus          = postImageEntity?.GetAttributeValue <OptionSetValue>(ChangeEmailStatus).Value;
                        int confirmedOptionSetValue = new OptionSetValue(100000002).Value;

                        if (newEmailStatus != confirmedOptionSetValue)
                        {
                            return;
                        }

                        _accountId = postImageEntity.GetAttributeValue <EntityReference>("accountid").Id;
                        localContext.Trace($"Attempting to retrieve all active Email Change Request cases for account with id {_accountId}");

                        // Get all the active cases with title "Email Change Request" for the current account
                        using (var crmContext = new ServiceContext(localContext.OrganizationService)
                        {
                            MergeOption = MergeOption.NoTracking
                        })
                        {
                            localContext.Trace($"Attempting to retrieve all active Email Change Request cases for account with id {_accountId}");
                            var allCases = (from incidents in crmContext.IncidentSet
                                            join account in crmContext.AccountSet on incidents.CustomerId.Id equals account.Id
                                            where incidents.CustomerId.Id == _accountId &&
                                            incidents.SubjectId.Id.Equals(Guid.Parse(EmailChangeRequestSubjectId)) &&
                                            incidents.StateCode == IncidentState.Active
                                            orderby incidents.CreatedOn descending
                                            select incidents)
                                           .ToList();

                            if (!allCases.Any())
                            {
                                localContext.Trace($"No active Email Change Request cases found for account with id {_accountId}");
                                return;
                            }

                            localContext.Trace($"Retrieved {allCases.Count} active Email Change Request cases for account id {_accountId}");

                            // Retrieve the latest active "Email Change Request" case for the current account and resolve it.
                            Incident latestCase = allCases.First();
                            ResolveCase(localContext, latestCase);

                            // Create new instance of account for update
                            var retrievedAccount = new Entity(Account.EntityLogicalName, _accountId);
                            var accountInstance  = new Entity(Account.EntityLogicalName)
                            {
                                Id         = retrievedAccount.Id,
                                Attributes =
                                {
                                    ["emailaddress1"]        = latestCase.GetAttributeValue <string>(NewEmail),
                                    ["new_emailsetfromcase"] = true
                                }
                            };

                            localContext.Trace($"Updated account {accountInstance.GetAttributeValue<string>("name")}'s email to " +
                                               $"{latestCase.GetAttributeValue<string>(NewEmail)}");
                            localContext.OrganizationService.Update(accountInstance);

                            //Retrieve all other active "Email Change Request" cases (if any) for the current account that need to be closed as duplicate.
                            var casesToClose = allCases.Skip(1).ToList();
                            if (!casesToClose.Any())
                            {
                                localContext.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)
                                {
                                    CloseCase(localContext, currentCase);
                                }

                                localContext.Trace($"Closed {casesToClose.Count} cases with status reason Cancelled for account with id {_accountId}");
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    localContext.Trace($"An error occurred in {nameof(OnCaseChangeEmailStatusConfirmed_OnPostUpdateEmailAndResolveCase)}. " +
                                       $"Exception details: {ex.Message}");
                    throw new InvalidPluginExecutionException(ex.Message);
                }
            }
        }