Exemplo n.º 1
0
        /// <summary>
        /// Sends the confirmation.
        /// </summary>
        /// <param name="userLogin">The user login.</param>
        private void SendConfirmation(UserLogin userLogin)
        {
            string url = LinkedPageUrl("ConfirmationPage");

            if (string.IsNullOrWhiteSpace(url))
            {
                url = ResolveRockUrl("~/ConfirmAccount");
            }

            var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(RockPage, CurrentPerson);

            mergeFields.Add("ConfirmAccountUrl", RootPath + url.TrimStart('/'));
            mergeFields.Add("Person", userLogin.Person);
            mergeFields.Add("User", userLogin);

            var recipients = new List <RecipientData>();

            recipients.Add(new RecipientData(userLogin.Person.Email, mergeFields));

            var message = new RockEmailMessage(GetAttributeValue("ConfirmAccountTemplate").AsGuid());

            message.SetRecipients(recipients);
            message.AppRoot   = ResolveRockUrl("~/");
            message.ThemeRoot = ResolveRockUrl("~~/");
            message.CreateCommunicationRecord = false;
            message.Send();
        }
Exemplo n.º 2
0
        /// <summary>
        /// Sends the specified recipients.
        /// </summary>
        /// <param name="recipients">The recipients.</param>
        /// <param name="fromEmail">From email.</param>
        /// <param name="fromName">From name.</param>
        /// <param name="subject">The subject.</param>
        /// <param name="body">The body.</param>
        /// <param name="ccEmails">The CC emails.</param>
        /// <param name="bccEmails">The BCC emails.</param>
        /// <param name="createCommunicationRecord">if set to <c>true</c> [create communication record].</param>
        /// <param name="attachments">The attachments.</param>
        /// <param name="errorMessages">The error messages.</param>
        private void Send(List <RockEmailMessageRecipient> recipients, string fromEmail, string fromName, string subject, string body, List <string> ccEmails, List <string> bccEmails, bool createCommunicationRecord, BinaryFile[] attachments, out List <string> errorMessages)
        {
            var emailMessage = new RockEmailMessage();

            emailMessage.SetRecipients(recipients);
            emailMessage.FromEmail = fromEmail;
            emailMessage.FromName  = fromName.IsNullOrWhiteSpace() ? fromEmail : fromName;
            emailMessage.Subject   = subject;
            emailMessage.Message   = body;

            emailMessage.CCEmails  = ccEmails ?? new List <string>();
            emailMessage.BCCEmails = bccEmails ?? new List <string>();

            foreach (BinaryFile b in attachments)
            {
                if (b != null)
                {
                    emailMessage.Attachments.Add(b);
                }
            }

            emailMessage.CreateCommunicationRecord = createCommunicationRecord;
            emailMessage.AppRoot = Rock.Web.Cache.GlobalAttributesCache.Get().GetValue("InternalApplicationRoot") ?? string.Empty;

            emailMessage.Send(out errorMessages);
        }
Exemplo n.º 3
0
        public void Send(List <string> recipients, string from, string fromName, string subject, string body, string appRoot, string themeRoot, List <Attachment> attachments, bool createCommunicationHistory)
        {
            var message = new RockEmailMessage();

            message.FromEmail = from;
            message.FromName  = fromName;
            message.SetRecipients(recipients);
            message.Subject   = subject;
            message.Message   = body;
            message.ThemeRoot = themeRoot;
            message.AppRoot   = appRoot;
            message.CreateCommunicationRecord = createCommunicationHistory;

            foreach (var attachment in attachments)
            {
                var binaryFile = new BinaryFile();
                binaryFile.ContentStream = attachment.ContentStream;
                binaryFile.FileName      = attachment.Name;
                message.Attachments.Add(binaryFile);
            }

            var errorMessages  = new List <string>();
            int mediumEntityId = EntityTypeCache.Read(Rock.SystemGuid.EntityType.COMMUNICATION_MEDIUM_EMAIL.AsGuid())?.Id ?? 0;

            Send(message, mediumEntityId, null, out errorMessages);
        }
Exemplo n.º 4
0
        private SendMessageResult SendReminderEmail(Guid assessmentSystemEmailGuid, int PersonAliasId)
        {
            var person = new PersonAliasService(new RockContext()).GetPerson(PersonAliasId);
            var result = new SendMessageResult();

            if (!person.IsEmailActive)
            {
                result.Warnings.Add($"{person.FullName.ToPossessive()} email address is inactive.");
                return(result);
            }

            var mergeObjects = Rock.Lava.LavaHelper.GetCommonMergeFields(null);

            mergeObjects.Add("Person", person);

            var recipients = new List <RockEmailMessageRecipient>();

            recipients.Add(new RockEmailMessageRecipient(person, mergeObjects));

            var emailMessage = new RockEmailMessage(assessmentSystemEmailGuid);

            emailMessage.SetRecipients(recipients);

            if (emailMessage.Send(out var errors))
            {
                result.MessagesSent = 1;
            }
            else
            {
                result.Errors.AddRange(errors);
            }
            return(result);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Sends the confirmation.
        /// </summary>
        /// <param name="userLogin">The user login.</param>
        private void SendConfirmation(UserLogin userLogin)
        {
            string url = LinkedPageUrl("ConfirmationPage");

            if (string.IsNullOrWhiteSpace(url))
            {
                url = ResolveRockUrl("~/ConfirmAccount");
            }

            var mergeObjects = Rock.Lava.LavaHelper.GetCommonMergeFields(null, CurrentPerson);

            mergeObjects.Add("ConfirmAccountUrl", RootPath + url.TrimStart(new char[] { '/' }));

            var personDictionary = userLogin.Person.ToLiquid() as Dictionary <string, object>;

            mergeObjects.Add("Person", personDictionary);
            mergeObjects.Add("User", userLogin);

            var recipients = new List <RockMessageRecipient>();

            recipients.Add(new RockEmailMessageRecipient(userLogin.Person, mergeObjects));

            var emailMessage = new RockEmailMessage(GetAttributeValue("ConfirmAccountTemplate").AsGuid());

            emailMessage.SetRecipients(recipients);
            emailMessage.CreateCommunicationRecord = false;
            emailMessage.Send();
        }
Exemplo n.º 6
0
        private void SendNotifications(List <string> alarms, Guid systemCommunication, Guid notificationGroup)
        {
            var emailMessage = new RockEmailMessage(systemCommunication);
            var recipients   = new List <RockMessageRecipient>();

            var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(null, null);

            mergeFields.Add("Alarms", alarms);

            RockContext  rockContext  = new RockContext();
            GroupService groupService = new GroupService(rockContext);
            var          people       = groupService.Queryable()
                                        .Where(g => g.Guid == notificationGroup)
                                        .SelectMany(g => g.Members)
                                        .Select(m => m.Person)
                                        .ToList();

            foreach (var person in people)
            {
                recipients.Add(new RockEmailMessageRecipient(person, mergeFields));
            }

            emailMessage.SetRecipients(recipients);
            emailMessage.CreateCommunicationRecord = true;
            emailMessage.Send();
        }
Exemplo n.º 7
0
        /// <summary>
        /// Sends the confirmation e-mail to the person this <see cref="UserLogin"/>
        /// is associated with. The e-mail will contain a link to the page where
        /// the person can confirm they own the account.
        /// </summary>
        /// <param name="userLogin">The user login.</param>
        /// <param name="systemEmailGuid">The system email unique identifier.</param>
        /// <param name="confirmationPage">The confirmation page.</param>
        /// <param name="baseUrl">The base URL to use if known, such as https://www.rockrms.com/. If <c>null</c> the default domain for the page will be used.</param>
        /// <param name="mergeFields">The additional merge fields to provide.</param>
        internal static void SendConfirmationEmail(UserLogin userLogin, Guid systemEmailGuid, PageCache confirmationPage, string baseUrl, Dictionary <string, object> mergeFields)
        {
            string url = null;

            // Check for the required parameters.
            if (userLogin == null)
            {
                throw new ArgumentNullException(nameof(userLogin));
            }

            if (confirmationPage == null)
            {
                throw new ArgumentNullException(nameof(confirmationPage));
            }

            // Get the default route that doesn't require any parameters.
            url = confirmationPage.PageRoutes
                  .Where(r => !r.Route.Contains("{"))
                  .OrderByDescending(r => r.IsGlobal)
                  .Select(r => r.Route)
                  .FirstOrDefault();

            // No route, just use legacy page id syntax.
            if (url.IsNullOrWhiteSpace())
            {
                url = $"/page/{confirmationPage.Id}";
            }

            // If they didn't provide a base url, then use the one for the page.
            if (baseUrl.IsNullOrWhiteSpace())
            {
                baseUrl = confirmationPage.Layout.Site.DefaultDomainUri.AbsoluteUri;
            }

            var confirmAccountUrl = baseUrl.TrimEnd('/') + "/" + url.TrimStart('/');

            // Duplicate the merge fields so we don't corrupt the original
            // dictionary.
            mergeFields = mergeFields != null ? new Dictionary <string, object>(mergeFields) : new Dictionary <string, object>();
            mergeFields.AddOrReplace("ConfirmAccountUrl", confirmAccountUrl);
            mergeFields.AddOrReplace("Person", userLogin.Person);
            mergeFields.AddOrReplace("User", userLogin);

            // Send the e-mail to the on-file address for the person.
            var recipients = new List <RockEmailMessageRecipient>
            {
                new RockEmailMessageRecipient(userLogin.Person, mergeFields)
            };

            // Send it off.
            var message = new RockEmailMessage(systemEmailGuid);

            message.SetRecipients(recipients);
            message.AppRoot   = "/";
            message.ThemeRoot = $"/Themes/{confirmationPage.Layout.Site.Theme}";
            message.CreateCommunicationRecord = false;
            message.Send();
        }
Exemplo n.º 8
0
        /// <summary>
        /// Sends the specified recipients.
        /// </summary>
        /// <param name="recipients">The recipients.</param>
        /// <param name="fromEmail">From email.</param>
        /// <param name="fromName">From name.</param>
        /// <param name="subject">The subject.</param>
        /// <param name="body">The body.</param>
        /// <param name="createCommunicationRecord">if set to <c>true</c> [create communication record].</param>
        /// <param name="metaData">The meta data.</param>
        private void Send(List <RockEmailMessageRecipient> recipients, string fromEmail, string fromName, string subject, string body, bool createCommunicationRecord, Dictionary <string, string> metaData)
        {
            var emailMessage = new RockEmailMessage();

            emailMessage.SetRecipients(recipients);
            emailMessage.FromEmail = fromEmail;
            emailMessage.FromName  = fromName;
            emailMessage.Subject   = subject;
            emailMessage.Message   = body;
            emailMessage.CreateCommunicationRecord = createCommunicationRecord;
            emailMessage.MessageMetaData           = metaData;
            emailMessage.Send();
        }
Exemplo n.º 9
0
        /// <summary>
        /// Executes this instance.
        /// </summary>
        /// <param name="message"></param>
        public override void Execute(Message message)
        {
            using (var rockContext = new RockContext())
            {
                var communication = new CommunicationService(rockContext).Get(message.CommunicationId);

                if (communication != null && communication.Status == CommunicationStatus.PendingApproval)
                {
                    // get notification group
                    var groupGuid = SystemGuid.Group.GROUP_COMMUNICATION_APPROVERS.AsGuid();
                    var approvers = new GroupMemberService(rockContext).Queryable()
                                    .Where(m =>
                                           m.Group.Guid == groupGuid &&
                                           m.GroupMemberStatus == GroupMemberStatus.Active)
                                    .ToList();

                    if (approvers.Any())
                    {
                        var communicationSettingApprovalGuid = Rock.Web.SystemSettings.GetValue(SystemSetting.COMMUNICATION_SETTING_APPROVAL_TEMPLATE).AsGuidOrNull();
                        if (communicationSettingApprovalGuid.HasValue)
                        {
                            var approvalPageUrl = message.ApprovalPageUrl;

                            // create approval link if one was not provided
                            if (string.IsNullOrEmpty(approvalPageUrl))
                            {
                                var internalApplicationRoot = GlobalAttributesCache.Value("InternalApplicationRoot").EnsureTrailingForwardslash();
                                approvalPageUrl = $"{internalApplicationRoot}Communication/{communication.Id}";
                            }

                            foreach (var approver in approvers)
                            {
                                var recipients   = new List <RockEmailMessageRecipient>();
                                var emailMessage = new RockEmailMessage(communicationSettingApprovalGuid.Value);

                                // Build Lava merge fields.
                                var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(null);
                                mergeFields.Add("Approver", approver.Person);
                                mergeFields.Add("Communication", communication);
                                mergeFields.Add("RecipientsCount", communication.GetRecipientsQry(rockContext).Count());
                                mergeFields.Add("ApprovalPageUrl", approvalPageUrl);
                                recipients.Add(new RockEmailMessageRecipient(approver.Person, mergeFields));
                                emailMessage.SetRecipients(recipients);
                                emailMessage.Send();
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 10
0
        public void Send(Dictionary <string, string> mediumData, List <string> recipients, string appRoot, string themeRoot, bool createCommunicationHistory, Dictionary <string, string> metaData)
        {
            var message = new RockEmailMessage();

            message.FromEmail    = mediumData.GetValueOrNull("From") ?? string.Empty;
            message.ReplyToEmail = mediumData.GetValueOrNull("ReplyTo") ?? string.Empty;
            message.SetRecipients(recipients);
            message.Subject   = mediumData.GetValueOrNull("Subject") ?? string.Empty;
            message.Message   = mediumData.GetValueOrNull("Body") ?? string.Empty;
            message.ThemeRoot = themeRoot;
            message.AppRoot   = appRoot;
            message.CreateCommunicationRecord = createCommunicationHistory;
            message.MessageMetaData           = metaData;

            var errorMessages  = new List <string>();
            int mediumEntityId = EntityTypeCache.Read(Rock.SystemGuid.EntityType.COMMUNICATION_MEDIUM_EMAIL.AsGuid())?.Id ?? 0;

            Send(message, mediumEntityId, null, out errorMessages);
        }
Exemplo n.º 11
0
        private void SendNotificationEmail(List <TestResult> alarms, List <Person> people)
        {
            var systemCommunication = dataMap.GetString("NotificationCommunication").AsGuid();
            var emailMessage        = new RockEmailMessage(systemCommunication);
            var recipients          = new List <RockMessageRecipient>();

            var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(null, null);

            mergeFields.Add("Alarms", alarms);

            foreach (var person in people)
            {
                recipients.Add(new RockEmailMessageRecipient(person, mergeFields));
            }

            emailMessage.SetRecipients(recipients);
            emailMessage.CreateCommunicationRecord = true;
            emailMessage.Send();
        }
Exemplo n.º 12
0
        private void SendEmailToMember(GroupMember member, Group group, KeyValuePair <int, List <DateTime> > occGroup)
        {
            var email = staffEmail;

            if (member.IsNotNull())
            {
                email = member.Person.Email;
            }

            if (email.IsNotNullOrWhiteSpace())
            {
                groupsNotified.Add(group.Id);

                var mergeObjects = Rock.Lava.LavaHelper.GetCommonMergeFields(null, member.IsNotNull() ? member.Person : null);
                mergeObjects.Add("Person", member.IsNotNull() ? member.Person : null);
                mergeObjects.Add("Group", group);
                mergeObjects.Add("Occurrence", occGroup.Value.Max());

                var recipients = new List <RockEmailMessageRecipient>();
                recipients.Add(RockEmailMessageRecipient.CreateAnonymous(email, mergeObjects));

                var emailMessage = new RockEmailMessage(systemEmailGuid);
                emailMessage.SetRecipients(recipients);
                var errors = new List <string>();
                emailMessage.Send(out errors);

                if (errors.Any())
                {
                    errorCount += errors.Count;
                    errorMessages.AddRange(errors);
                }
                else
                {
                    attendanceRemindersSent++;
                }
            }
            else
            {
                errorCount += 1;
                errorMessages.Add(string.Format("No email specified for group {0} and no fallback email provided.", group.Id));
            }
        }
Exemplo n.º 13
0
        private List <string> SendReminderEmail(Guid assessmentSystemEmailGuid, int PersonAliasId)
        {
            var person = new PersonAliasService(new RockContext()).GetPerson(PersonAliasId);

            var mergeObjects = Rock.Lava.LavaHelper.GetCommonMergeFields(null);

            mergeObjects.Add("Person", person);

            var recipients = new List <RecipientData>();

            recipients.Add(new RecipientData(person.Email, mergeObjects));

            var errors       = new List <string>();
            var emailMessage = new RockEmailMessage(assessmentSystemEmailGuid);

            emailMessage.SetRecipients(recipients);
            emailMessage.Send(out errors);

            return(errors);
        }
Exemplo n.º 14
0
        /// <summary>
        /// Executes the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        public virtual void Execute(IJobExecutionContext context)
        {
            JobDataMap dataMap           = context.JobDetail.JobDataMap;
            var        emailTemplateGuid = dataMap.Get("SystemEmail").ToString().AsGuid();
            var        groupGuid         = dataMap.Get("Group").ToString().AsGuid();
            var        sendToDescendants = dataMap.Get("SendToDescendantGroups").ToString().AsBoolean();

            var rockContext = new RockContext();
            var group       = new GroupService(rockContext).Get(groupGuid);

            if (group != null)
            {
                List <int> groupIds = new List <int>();
                GetGroupIds(groupIds, sendToDescendants, group);

                var recipients = new List <RecipientData>();

                var groupMemberList = new GroupMemberService(rockContext).Queryable().Where(gm =>
                                                                                            groupIds.Contains(gm.GroupId) &&
                                                                                            gm.GroupMemberStatus == GroupMemberStatus.Active)
                                      .ToList();
                foreach (GroupMember groupMember in groupMemberList)
                {
                    var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(null);
                    mergeFields.Add("Person", groupMember.Person);
                    mergeFields.Add("GroupMember", groupMember);
                    mergeFields.Add("Group", groupMember.Group);

                    recipients.Add(new RecipientData(groupMember.Person.Email, mergeFields));
                }

                if (recipients.Any())
                {
                    var emailMessage = new RockEmailMessage(emailTemplateGuid);
                    emailMessage.SetRecipients(recipients);
                    emailMessage.Send();
                }

                context.Result = string.Format("{0} emails sent", recipients.Count());
            }
        }
Exemplo n.º 15
0
        public void Send(SystemEmail template, List <RecipientData> recipients, string appRoot, string themeRoot, bool createCommunicationHistory)
        {
            var message = new RockEmailMessage();

            message.FromEmail = template.From;
            message.FromName  = template.FromName;
            message.SetRecipients(recipients);
            template.To.SplitDelimitedValues().ToList().ForEach(to => message.AddRecipient(to));
            message.CCEmails  = template.Cc.SplitDelimitedValues().ToList();
            message.BCCEmails = template.Bcc.SplitDelimitedValues().ToList();
            message.Subject   = template.Subject;
            message.Message   = template.Body;
            message.ThemeRoot = themeRoot;
            message.AppRoot   = appRoot;
            message.CreateCommunicationRecord = createCommunicationHistory;

            var errorMessages  = new List <string>();
            int mediumEntityId = EntityTypeCache.Read(Rock.SystemGuid.EntityType.COMMUNICATION_MEDIUM_EMAIL.AsGuid())?.Id ?? 0;

            Send(message, mediumEntityId, null, out errorMessages);
        }
        /// <summary>
        /// Sends and individual digest email to the specified person.
        /// </summary>
        /// <param name="systemCommunication">The system communication.</param>
        /// <param name="mergeObjects">The Lava merge objects.</param>
        /// <param name="person">The person who should receive the email.</param>
        /// <param name="regionalGroup">The regional group that this digest email represents.</param>
        private void SendDigestEmail(SystemCommunication systemCommunication, Dictionary <string, object> mergeObjects, Person person, Group regionalGroup)
        {
            mergeObjects.AddOrReplace("Person", person);

            var recipient = new RockEmailMessageRecipient(person, mergeObjects);
            var message   = new RockEmailMessage(systemCommunication);

            message.Subject = $"'{regionalGroup.Name}' Group Attendance Digest";
            message.SetRecipients(new List <RockEmailMessageRecipient> {
                recipient
            });
            message.Send(out List <string> errorMessages);

            if (!errorMessages.Any())
            {
                _digestsSentCount++;
                return;
            }

            _errors.Add($"Unable to send '{regionalGroup.Name}' digest to '{person.Email}'.");
        }
Exemplo n.º 17
0
        /// <summary>
        /// Sends an RSVP reminder SMS to an individual attendee.
        /// </summary>
        /// <param name="person">The <see cref="Person"/>.</param>
        /// <param name="reminder">The <see cref="SystemCommunication"/> to be sent as a reminder.</param>
        /// <param name="lavaMergeFields">A dictionary containing Lava merge fields.</param>
        /// <returns>1 if the communication was successfully sent, otherwise 0.</returns>
        private int SendReminderEmail(Person person, SystemCommunication reminder, Dictionary <string, object> lavaMergeFields)
        {
            if (!person.IsEmailActive)
            {
                return(0);
            }

            var recipient = new RockEmailMessageRecipient(person, lavaMergeFields);
            var message   = new RockEmailMessage(reminder);

            message.SetRecipients(new List <RockEmailMessageRecipient>()
            {
                recipient
            });
            message.Send(out List <string> emailErrors);

            if (!emailErrors.Any())
            {
                return(1); // No error, this should be counted as a sent reminder.
            }

            return(0);
        }
Exemplo n.º 18
0
        /// <summary>
        /// Sends a notification that NCOA finished or failed
        /// </summary>
        /// <param name="sparkDataConfig">The spark data configuration.</param>
        /// <param name="status">The status to put in the notification.</param>
        public void SentNotification(SparkDataConfig sparkDataConfig, string status)
        {
            if (!sparkDataConfig.GlobalNotificationApplicationGroupId.HasValue || sparkDataConfig.GlobalNotificationApplicationGroupId.Value == 0)
            {
                return;
            }

            var recipients = new List <RecipientData>();

            using (RockContext rockContext = new RockContext())
            {
                Group group = new GroupService(rockContext).GetNoTracking(sparkDataConfig.GlobalNotificationApplicationGroupId.Value);

                foreach (var groupMember in group.Members)
                {
                    if (groupMember.GroupMemberStatus == GroupMemberStatus.Active)
                    {
                        var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(null);
                        mergeFields.Add("Person", groupMember.Person);
                        mergeFields.Add("GroupMember", groupMember);
                        mergeFields.Add("Group", groupMember.Group);
                        mergeFields.Add("SparkDataService", "National Change of Address (NCOA)");
                        mergeFields.Add("SparkDataConfig", sparkDataConfig);
                        mergeFields.Add("Status", status);
                        recipients.Add(new RecipientData(groupMember.Person.Email, mergeFields));
                    }
                }

                SystemEmailService emailService = new SystemEmailService(rockContext);
                SystemEmail        systemEmail  = emailService.GetNoTracking(SystemGuid.SystemEmail.SPARK_DATA_NOTIFICATION.AsGuid());

                var emailMessage = new RockEmailMessage(systemEmail.Guid);
                emailMessage.SetRecipients(recipients);
                emailMessage.Send();
            }
        }
Exemplo n.º 19
0
        /// <summary>
        /// Sends the note watch notifications.
        /// </summary>
        /// <param name="context">The context.</param>
        private List <string> SendNoteWatchNotifications(IJobExecutionContext context)
        {
            var        errors = new List <string>();
            List <int> noteIdsToProcessNoteWatchesList = new List <int>();

            using (var rockContext = new RockContext())
            {
                var noteService      = new NoteService(rockContext);
                var noteWatchService = new NoteWatchService(rockContext);
                var noteWatchQuery   = noteWatchService.Queryable();

                if (!noteWatchQuery.Any())
                {
                    // there aren't any note watches, so there is nothing to do
                    return(errors);
                }

                // get all notes that haven't processed notifications yet
                var notesToNotifyQuery = noteService.Queryable().Where(a =>
                                                                       a.NotificationsSent == false &&
                                                                       a.NoteType.AllowsWatching == true &&
                                                                       a.EditedDateTime > _cutoffNoteEditDateTime);

                // limit to notes that don't require approval or are approved
                notesToNotifyQuery = notesToNotifyQuery.Where(a => a.NoteType.RequiresApprovals == false || a.ApprovalStatus == NoteApprovalStatus.Approved);

                if (!notesToNotifyQuery.Any())
                {
                    // there aren't any notes that haven't had notifications processed yet
                    return(errors);
                }

                noteIdsToProcessNoteWatchesList = notesToNotifyQuery.Select(a => a.Id).ToList();
            }

            // make a list of notifications to send to each personId
            Dictionary <int, NoteWatchPersonToNotifyList> personNotificationDigestList = new Dictionary <int, NoteWatchPersonToNotifyList>();

            using (var rockContext = new RockContext())
            {
                foreach (int noteId in noteIdsToProcessNoteWatchesList)
                {
                    this.UpdateNoteWatchNotificationDigest(personNotificationDigestList, rockContext, noteId);
                }

                // Send NoteWatch notifications
                if (personNotificationDigestList.Any())
                {
                    foreach (var personNotificationDigest in personNotificationDigestList)
                    {
                        var         recipients     = new List <RecipientData>();
                        Person      personToNotify = personNotificationDigest.Value.Person;
                        List <Note> noteList       = personNotificationDigest.Value.Select(a => a.Note).OrderBy(a => a.EditedDateTime).ToList();

                        // make sure a person doesn't get a notification on a note that they wrote
                        noteList = noteList.Where(a => a.EditedByPersonAlias?.PersonId != personToNotify.Id).ToList();

                        if (!string.IsNullOrEmpty(personToNotify.Email) && personToNotify.IsEmailActive && personToNotify.EmailPreference != EmailPreference.DoNotEmail && noteList.Any())
                        {
                            var mergeFields = new Dictionary <string, object>(_defaultMergeFields);
                            mergeFields.Add("Person", personToNotify);
                            mergeFields.Add("NoteList", noteList);
                            recipients.Add(new RecipientData(personToNotify.Email, mergeFields));
                        }

                        if (_noteWatchNotificationEmailGuid.HasValue)
                        {
                            var emailMessage = new RockEmailMessage(_noteWatchNotificationEmailGuid.Value);
                            emailMessage.SetRecipients(recipients);
                            emailMessage.Send(out errors);
                            _noteWatchNotificationsSent += recipients.Count();
                        }
                    }
                }
            }

            using (var rockUpdateContext = new RockContext())
            {
                var notesToMarkNotified = new NoteService(rockUpdateContext).Queryable().Where(a => noteIdsToProcessNoteWatchesList.Contains(a.Id));

                // use BulkUpdate to mark all the notes that we processed to NotificationsSent = true
                rockUpdateContext.BulkUpdate(notesToMarkNotified, n => new Note {
                    NotificationsSent = true
                });
            }
            return(errors);
        }
Exemplo n.º 20
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The workflow action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            var actionType = action.ActionTypeCache;

            if (!action.LastProcessedDateTime.HasValue &&
                actionType != null &&
                actionType.WorkflowForm != null &&
                actionType.WorkflowForm.NotificationSystemEmailId.HasValue)
            {
                if (action.Activity != null && (action.Activity.AssignedPersonAliasId.HasValue || action.Activity.AssignedGroupId.HasValue))
                {
                    var recipients          = new List <RecipientData>();
                    var workflowMergeFields = GetMergeFields(action);

                    if (action.Activity.AssignedPersonAliasId.HasValue)
                    {
                        var person = new PersonAliasService(rockContext).Queryable()
                                     .Where(a => a.Id == action.Activity.AssignedPersonAliasId.Value)
                                     .Select(a => a.Person)
                                     .FirstOrDefault();

                        if (person != null && !string.IsNullOrWhiteSpace(person.Email))
                        {
                            recipients.Add(new RecipientData(person.Email, CombinePersonMergeFields(person, workflowMergeFields)));
                            action.AddLogEntry(string.Format("Form notification sent to '{0}'", person.FullName));
                        }
                    }

                    if (action.Activity.AssignedGroupId.HasValue)
                    {
                        var personList = new GroupMemberService(rockContext).GetByGroupId(action.Activity.AssignedGroupId.Value)
                                         .Where(m =>
                                                m.GroupMemberStatus == GroupMemberStatus.Active &&
                                                m.Person.Email != "")
                                         .Select(m => m.Person)
                                         .ToList();

                        foreach (var person in personList)
                        {
                            recipients.Add(new RecipientData(person.Email, CombinePersonMergeFields(person, workflowMergeFields)));
                            action.AddLogEntry(string.Format("Form notification sent to '{0}'", person.FullName));
                        }
                    }

                    if (recipients.Count > 0)
                    {
                        // The email may need to reference activity Id, so we need to save here.
                        WorkflowService workflowService = new WorkflowService(rockContext);
                        workflowService.PersistImmediately(action);

                        var systemEmail = new SystemEmailService(rockContext).Get(action.ActionTypeCache.WorkflowForm.NotificationSystemEmailId.Value);
                        if (systemEmail != null)
                        {
                            var emailMessage = new RockEmailMessage(systemEmail);
                            emailMessage.SetRecipients(recipients);
                            emailMessage.CreateCommunicationRecord = false;
                            emailMessage.AppRoot = GlobalAttributesCache.Get().GetValue("InternalApplicationRoot") ?? string.Empty;
                            emailMessage.Send();
                        }
                        else
                        {
                            action.AddLogEntry("Could not find the selected notification system email", true);
                        }
                    }
                    else
                    {
                        action.AddLogEntry("Could not send form notification due to no assigned person or group member not having email address", true);
                    }
                }
                else
                {
                    action.AddLogEntry("Could not send form notification due to no assigned person or group", true);
                }
            }

            return(false);
        }
Exemplo n.º 21
0
        /// <summary>
        /// Sends the note approval notifications.
        /// </summary>
        /// <param name="context">The context.</param>
        private List <string> SendNoteApprovalNotifications(IJobExecutionContext context)
        {
            var        errors = new List <string>();
            List <int> noteIdsToProcessApprovalsList = new List <int>();

            using (var rockContext = new RockContext())
            {
                var noteService = new Rock.Model.NoteService(rockContext);

                // get all notes that are pending approval and haven't sent approval notifications yet
                var notesThatNeedApprovalNotifyQuery = noteService.Queryable().Where(a =>
                                                                                     a.NoteType.RequiresApprovals &&
                                                                                     a.NoteType.SendApprovalNotifications &&
                                                                                     a.ApprovalsSent == false &&
                                                                                     a.ApprovalStatus == NoteApprovalStatus.PendingApproval &&
                                                                                     a.EditedDateTime > _cutoffNoteEditDateTime);

                if (!notesThatNeedApprovalNotifyQuery.Any())
                {
                    // there aren't any notes that haven't had approval notifications processed yet
                    return(errors);
                }

                noteIdsToProcessApprovalsList = notesThatNeedApprovalNotifyQuery.Select(a => a.Id).ToList();
            }

            using (var rockContext = new RockContext())
            {
                // get the approvers for each notetypeId
                Dictionary <int, List <Person> > noteTypeApprovers = new Dictionary <int, List <Person> >();

                NoteTypeService noteTypeService     = new NoteTypeService(rockContext);
                var             noteTypeIdsForNotes = new NoteService(rockContext).Queryable()
                                                      .Where(a => noteIdsToProcessApprovalsList.Contains(a.Id)).Select(a => a.NoteTypeId).Distinct().ToList();

                foreach (var noteTypeId in noteTypeIdsForNotes)
                {
                    var approvers = noteTypeService.GetApprovers(noteTypeId).ToList();
                    noteTypeApprovers.Add(noteTypeId, approvers);
                }

                // make a list of notes for each approver so we can send a digest of notes to approve to each approver
                Dictionary <Person, List <Note> > approverNotesToApproveList = new Dictionary <Person, List <Note> >();
                foreach (var noteId in noteIdsToProcessApprovalsList)
                {
                    var noteService      = new Rock.Model.NoteService(rockContext);
                    var note             = noteService.Get(noteId);
                    var approversForNote = noteTypeApprovers.GetValueOrNull(note.NoteTypeId);
                    if (approversForNote?.Any() == true)
                    {
                        List <Note> notesToApprove;
                        foreach (Person approverPerson in approversForNote)
                        {
                            if (approverNotesToApproveList.ContainsKey(approverPerson))
                            {
                                notesToApprove = approverNotesToApproveList[approverPerson] ?? new List <Note>();
                            }
                            else
                            {
                                notesToApprove = new List <Note>();
                                approverNotesToApproveList.Add(approverPerson, notesToApprove);
                            }

                            notesToApprove.Add(note);
                        }
                    }
                    else
                    {
                        // if there are no approvers for this note type, leave it as pending approval
                    }
                }

                if (!approverNotesToApproveList.Any())
                {
                    // nothing to do so exit
                    return(errors);
                }

                // send approval emails
                var recipients = new List <RecipientData>();
                foreach (var approverNotesToApprove in approverNotesToApproveList)
                {
                    Person      approverPerson = approverNotesToApprove.Key;
                    List <Note> noteList       = approverNotesToApprove.Value;
                    if (!string.IsNullOrEmpty(approverPerson.Email) && approverPerson.IsEmailActive && noteList.Any())
                    {
                        var mergeFields = new Dictionary <string, object>(_defaultMergeFields);
                        mergeFields.Add("ApproverPerson", approverPerson);
                        mergeFields.Add("NoteList", noteList);
                        recipients.Add(new RecipientData(approverPerson.Email, mergeFields));
                    }

                    if (_noteApprovalNotificationEmailGuid.HasValue)
                    {
                        var emailMessage = new RockEmailMessage(_noteApprovalNotificationEmailGuid.Value);
                        emailMessage.SetRecipients(recipients);
                        emailMessage.Send(out errors);
                        _noteApprovalNotificationsSent += recipients.Count();

                        using (var rockUpdateContext = new RockContext())
                        {
                            var noteListIds             = noteList.Select(a => a.Id).ToList();
                            var notesToMarkApprovalSent = new NoteService(rockUpdateContext).Queryable().Where(a => noteListIds.Contains(a.Id));

                            // use BulkUpdate to mark all the notes that we processed to ApprovalsSent = true
                            rockUpdateContext.BulkUpdate(notesToMarkApprovalSent, n => new Note {
                                ApprovalsSent = true
                            });
                        }
                    }
                }
            }

            return(errors);
        }
Exemplo n.º 22
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            var mergeFields = GetMergeFields(action);
            var recipients  = new List <RecipientData>();

            string to = GetAttributeValue(action, "Recipient");

            Guid?guid = to.AsGuidOrNull();

            if (guid.HasValue)
            {
                var attribute = AttributeCache.Read(guid.Value, rockContext);
                if (attribute != null)
                {
                    string toValue = action.GetWorklowAttributeValue(guid.Value);
                    if (!string.IsNullOrWhiteSpace(toValue))
                    {
                        switch (attribute.FieldType.Class)
                        {
                        case "Rock.Field.Types.TextFieldType":
                        case "Rock.Field.Types.EmailFieldType":
                        {
                            var recipientList = toValue.SplitDelimitedValues().ToList();
                            foreach (string recipient in recipientList)
                            {
                                recipients.Add(new RecipientData(recipient, mergeFields));
                            }
                            break;
                        }

                        case "Rock.Field.Types.PersonFieldType":
                        {
                            Guid personAliasGuid = toValue.AsGuid();
                            if (!personAliasGuid.IsEmpty())
                            {
                                var person = new PersonAliasService(rockContext).Queryable()
                                             .Where(a => a.Guid.Equals(personAliasGuid))
                                             .Select(a => a.Person)
                                             .FirstOrDefault();
                                if (person == null)
                                {
                                    action.AddLogEntry("Invalid Recipient: Person not found", true);
                                }
                                else if (string.IsNullOrWhiteSpace(person.Email))
                                {
                                    action.AddLogEntry("Email was not sent: Recipient does not have an email address", true);
                                }
                                else if (!(person.IsEmailActive))
                                {
                                    action.AddLogEntry("Email was not sent: Recipient email is not active", true);
                                }
                                else if (person.EmailPreference == EmailPreference.DoNotEmail)
                                {
                                    action.AddLogEntry("Email was not sent: Recipient has requested 'Do Not Email'", true);
                                }
                                else
                                {
                                    var personDict = new Dictionary <string, object>(mergeFields);
                                    personDict.Add("Person", person);
                                    recipients.Add(new RecipientData(person.Email, personDict));
                                }
                            }
                            break;
                        }

                        case "Rock.Field.Types.GroupFieldType":
                        case "Rock.Field.Types.SecurityRoleFieldType":
                        {
                            int? groupId   = toValue.AsIntegerOrNull();
                            Guid?groupGuid = toValue.AsGuidOrNull();
                            IQueryable <GroupMember> qry = null;

                            // Handle situations where the attribute value is the ID
                            if (groupId.HasValue)
                            {
                                qry = new GroupMemberService(rockContext).GetByGroupId(groupId.Value);
                            }

                            // Handle situations where the attribute value stored is the Guid
                            else if (groupGuid.HasValue)
                            {
                                qry = new GroupMemberService(rockContext).GetByGroupGuid(groupGuid.Value);
                            }
                            else
                            {
                                action.AddLogEntry("Invalid Recipient: No valid group id or Guid", true);
                            }

                            if (qry != null)
                            {
                                foreach (var person in qry
                                         .Where(m => m.GroupMemberStatus == GroupMemberStatus.Active)
                                         .Select(m => m.Person))
                                {
                                    if (person.IsEmailActive &&
                                        person.EmailPreference != EmailPreference.DoNotEmail &&
                                        !string.IsNullOrWhiteSpace(person.Email))
                                    {
                                        var personDict = new Dictionary <string, object>(mergeFields);
                                        personDict.Add("Person", person);
                                        recipients.Add(new RecipientData(person.Email, personDict));
                                    }
                                }
                            }
                            break;
                        }
                        }
                    }
                }
            }
            else
            {
                var recipientList = to.SplitDelimitedValues().ToList();
                foreach (string recipient in recipientList)
                {
                    recipients.Add(new RecipientData(recipient, mergeFields));
                }
            }

            if (recipients.Any())
            {
                var emailMessage = new RockEmailMessage(GetAttributeValue(action, "SystemEmail").AsGuid());
                emailMessage.SetRecipients(recipients);
                emailMessage.CreateCommunicationRecord = GetAttributeValue(action, "SaveCommunicationHistory").AsBoolean();
                emailMessage.Send();
            }

            return(true);
        }
Exemplo n.º 23
0
        /// <summary>
        /// Executes the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        public virtual void Execute(IJobExecutionContext context)
        {
            JobDataMap dataMap   = context.JobDetail.JobDataMap;
            var        groupType = GroupTypeCache.Get(dataMap.GetString("GroupType").AsGuid());
            int        attendanceRemindersSent = 0;
            int        errorCount    = 0;
            var        errorMessages = new List <string>();

            if (groupType.TakesAttendance && groupType.SendAttendanceReminder)
            {
                // Get the occurrence dates that apply
                var dates = new List <DateTime>();
                dates.Add(RockDateTime.Today);
                try
                {
                    string[] reminderDays = dataMap.GetString("SendReminders").Split(',');
                    foreach (string reminderDay in reminderDays)
                    {
                        if (reminderDay.Trim().IsNotNullOrWhiteSpace())
                        {
                            var reminderDate = RockDateTime.Today.AddDays(0 - Convert.ToInt32(reminderDay));
                            if (!dates.Contains(reminderDate))
                            {
                                dates.Add(reminderDate);
                            }
                        }
                    }
                }
                catch { }

                var rockContext                 = new RockContext();
                var groupService                = new GroupService(rockContext);
                var groupMemberService          = new GroupMemberService(rockContext);
                var scheduleService             = new ScheduleService(rockContext);
                var attendanceOccurrenceService = new AttendanceOccurrenceService(rockContext);

                var startDate = dates.Min();
                var endDate   = dates.Max().AddDays(1);

                // Find all 'occurrences' for the groups that occur on the affected dates
                var occurrences = new Dictionary <int, List <DateTime> >();
                foreach (var group in groupService
                         .Queryable("Schedule").AsNoTracking()
                         .Where(g =>
                                g.GroupTypeId == groupType.Id &&
                                g.IsActive &&
                                g.Schedule != null &&
                                g.Members.Any(m =>
                                              m.GroupMemberStatus == GroupMemberStatus.Active &&
                                              m.GroupRole.IsLeader &&
                                              m.Person.Email != null &&
                                              m.Person.Email != String.Empty)))
                {
                    // Add the group
                    occurrences.Add(group.Id, new List <DateTime>());

                    // Check for a iCal schedule
                    if (!string.IsNullOrWhiteSpace(group.Schedule.iCalendarContent))
                    {
                        // If schedule has an iCal schedule, get occurrences between first and last dates
                        foreach (var occurrence in group.Schedule.GetOccurrences(startDate, endDate))
                        {
                            var startTime = occurrence.Period.StartTime.Value;
                            if (dates.Contains(startTime.Date))
                            {
                                occurrences[group.Id].Add(startTime);
                            }
                        }
                    }
                    else
                    {
                        // if schedule does not have an iCal, then check for weekly schedule and calculate occurrences starting with first attendance or current week
                        if (group.Schedule.WeeklyDayOfWeek.HasValue)
                        {
                            foreach (var date in dates)
                            {
                                if (date.DayOfWeek == group.Schedule.WeeklyDayOfWeek.Value)
                                {
                                    var startTime = date;
                                    if (group.Schedule.WeeklyTimeOfDay.HasValue)
                                    {
                                        startTime = startTime.Add(group.Schedule.WeeklyTimeOfDay.Value);
                                    }
                                    occurrences[group.Id].Add(startTime);
                                }
                            }
                        }
                    }
                }

                // Remove any occurrences during group type exclusion date ranges
                foreach (var exclusion in groupType.GroupScheduleExclusions)
                {
                    if (exclusion.Start.HasValue && exclusion.End.HasValue)
                    {
                        foreach (var keyVal in occurrences)
                        {
                            foreach (var occurrenceDate in keyVal.Value.ToList())
                            {
                                if (occurrenceDate >= exclusion.Start.Value &&
                                    occurrenceDate < exclusion.End.Value.AddDays(1))
                                {
                                    keyVal.Value.Remove(occurrenceDate);
                                }
                            }
                        }
                    }
                }

                // Remove any 'occurrences' that already have attendance data entered
                foreach (var occurrence in attendanceOccurrenceService
                         .Queryable().AsNoTracking()
                         .Where(a =>
                                a.OccurrenceDate >= startDate &&
                                a.OccurrenceDate < endDate &&
                                a.GroupId.HasValue &&
                                occurrences.Keys.Contains(a.GroupId.Value) &&
                                a.ScheduleId.HasValue &&
                                (a.Attendees.Any() || (a.DidNotOccur.HasValue && a.DidNotOccur.Value)))
                         .Select(a => new
                {
                    GroupId = a.GroupId.Value,
                    a.OccurrenceDate
                })
                         .Distinct()
                         .ToList())
                {
                    occurrences[occurrence.GroupId].RemoveAll(d => d.Date == occurrence.OccurrenceDate.Date);
                }

                // Get the groups that have occurrences
                var groupIds = occurrences.Where(o => o.Value.Any()).Select(o => o.Key).ToList();

                // Get the leaders of those groups
                var leaders = groupMemberService
                              .Queryable("Group,Person").AsNoTracking()
                              .Where(m =>
                                     groupIds.Contains(m.GroupId) &&
                                     m.GroupMemberStatus == GroupMemberStatus.Active &&
                                     m.GroupRole.IsLeader &&
                                     m.Person.Email != null &&
                                     m.Person.Email != string.Empty)
                              .ToList();

                // Loop through the leaders
                foreach (var leader in leaders)
                {
                    foreach (var group in occurrences.Where(o => o.Key == leader.GroupId))
                    {
                        var mergeObjects = Rock.Lava.LavaHelper.GetCommonMergeFields(null, leader.Person);
                        mergeObjects.Add("Person", leader.Person);
                        mergeObjects.Add("Group", leader.Group);
                        mergeObjects.Add("Occurrence", group.Value.Max());

                        var recipients = new List <RecipientData>();
                        recipients.Add(new RecipientData(leader.Person.Email, mergeObjects));

                        var emailMessage = new RockEmailMessage(dataMap.GetString("SystemEmail").AsGuid());
                        emailMessage.SetRecipients(recipients);
                        var errors = new List <string>();
                        emailMessage.Send(out errors);

                        if (errors.Any())
                        {
                            errorCount += errors.Count;
                            errorMessages.AddRange(errors);
                        }
                        else
                        {
                            attendanceRemindersSent++;
                        }
                    }
                }
            }

            context.Result = string.Format("{0} attendance reminders sent", attendanceRemindersSent);
            if (errorMessages.Any())
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine();
                sb.Append(string.Format("{0} Errors: ", errorCount));
                errorMessages.ForEach(e => { sb.AppendLine(); sb.Append(e); });
                string errors = sb.ToString();
                context.Result += errors;
                var         exception = new Exception(errors);
                HttpContext context2  = HttpContext.Current;
                ExceptionLogService.LogException(exception, context2);
                throw exception;
            }
        }
Exemplo n.º 24
0
        /// <summary>
        /// Sends the notification.
        /// </summary>
        /// <param name="ex">The ex.</param>
        private void SendNotification(Exception ex)
        {
            int?pageId = (Context.Items["Rock:PageId"] ?? string.Empty).ToString().AsIntegerOrNull();
            int?siteId = (Context.Items["Rock:SiteId"] ?? string.Empty).ToString().AsIntegerOrNull();

            PersonAlias personAlias = null;
            Person      person      = null;

            try
            {
                var user = UserLoginService.GetCurrentUser();
                if (user != null && user.Person != null)
                {
                    person      = user.Person;
                    personAlias = user.Person.PrimaryAlias;
                }
            }
            catch
            {
                // ignore exception
            }

            try
            {
                ExceptionLogService.LogException(ex, Context, pageId, siteId, personAlias);
            }
            catch
            {
                // ignore exception
            }

            try
            {
                bool sendNotification = true;

                var globalAttributesCache = GlobalAttributesCache.Get();

                string filterSettings = globalAttributesCache.GetValue("EmailExceptionsFilter");
                if (!string.IsNullOrWhiteSpace(filterSettings))
                {
                    // Get the current request's list of server variables
                    var serverVarList = Context.Request.ServerVariables;

                    string[] nameValues = filterSettings.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string nameValue in nameValues)
                    {
                        string[] nameAndValue = nameValue.Split(new char[] { '^' }, StringSplitOptions.RemoveEmptyEntries);
                        {
                            if (nameAndValue.Length == 2)
                            {
                                switch (nameAndValue[0].ToLower())
                                {
                                case "type":
                                {
                                    if (ex.GetType().Name.ToLower().Contains(nameAndValue[1].ToLower()))
                                    {
                                        sendNotification = false;
                                    }

                                    break;
                                }

                                case "source":
                                {
                                    if (ex.Source.ToLower().Contains(nameAndValue[1].ToLower()))
                                    {
                                        sendNotification = false;
                                    }

                                    break;
                                }

                                case "message":
                                {
                                    if (ex.Message.ToLower().Contains(nameAndValue[1].ToLower()))
                                    {
                                        sendNotification = false;
                                    }

                                    break;
                                }

                                case "stacktrace":
                                {
                                    if (ex.StackTrace.ToLower().Contains(nameAndValue[1].ToLower()))
                                    {
                                        sendNotification = false;
                                    }

                                    break;
                                }

                                default:
                                {
                                    var serverValue = serverVarList[nameAndValue[0]];
                                    if (serverValue != null && serverValue.ToUpper().Contains(nameAndValue[1].ToUpper().Trim()))
                                    {
                                        sendNotification = false;
                                    }

                                    break;
                                }
                                }
                            }
                        }

                        if (!sendNotification)
                        {
                            break;
                        }
                    }
                }

                if (!sendNotification)
                {
                    return;
                }

                // get email addresses to send to
                string emailAddressesList = globalAttributesCache.GetValue("EmailExceptionsList");
                if (!string.IsNullOrWhiteSpace(emailAddressesList))
                {
                    string[] emailAddresses = emailAddressesList.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    if (emailAddresses.Length > 0)
                    {
                        string siteName = "Rock";
                        if (siteId.HasValue)
                        {
                            var site = SiteCache.Get(siteId.Value);
                            if (site != null)
                            {
                                siteName = site.Name;
                            }
                        }

                        var exceptionDetails = string.Format(
                            "An error occurred{0} on the {1} site on page: <br>{2}<p>{3}</p>",
                            person != null ? " for " + person.FullName : string.Empty,
                            siteName,
                            Context.Request.UrlProxySafe().OriginalString,
                            FormatException(ex, string.Empty));

                        // setup merge codes for email
                        var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(null);
                        mergeFields.Add("ExceptionDetails", exceptionDetails);

                        try
                        {
                            mergeFields.Add("Exception", ex);
                        }
                        catch
                        {
                            // ignore
                        }

                        mergeFields.Add("Person", person);
                        var recipients = new List <RockEmailMessageRecipient>();
                        foreach (string emailAddress in emailAddresses)
                        {
                            recipients.Add(RockEmailMessageRecipient.CreateAnonymous(emailAddress, mergeFields));
                        }

                        if (recipients.Any())
                        {
                            var message = new RockEmailMessage(Rock.SystemGuid.SystemCommunication.CONFIG_EXCEPTION_NOTIFICATION.AsGuid());
                            message.SetRecipients(recipients);
                            message.Send();
                        }
                    }
                }
            }
            catch
            {
                // ignore exception
            }
        }
Exemplo n.º 25
0
        /// <summary>
        /// Executes the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        public void Execute(IJobExecutionContext context)
        {
            var rockContext   = new RockContext();
            var personService = new PersonService(rockContext);

            JobDataMap dataMap         = context.JobDetail.JobDataMap;
            Guid?      systemEmailGuid = dataMap.GetString("BirthdayEmail").AsGuidOrNull();

            SystemEmailService emailService = new SystemEmailService(rockContext);

            SystemEmail systemEmail = null;

            if (systemEmailGuid.HasValue)
            {
                systemEmail = emailService.Get(systemEmailGuid.Value);
            }

            if (systemEmail == null)
            {
                // no email specified, so nothing to do
                return;
            }

            var activeStatusGuid = Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_ACTIVE.AsGuid();

            // only include alive people that have record status of Active
            var personQry = personService.Queryable(false, false).Where(a => a.RecordStatusValue.Guid == activeStatusGuid && a.IsDeceased == false);
            var ageRange  = (dataMap.GetString("AgeRange") ?? string.Empty).Split(',');

            if (ageRange.Length == 2)
            {
                int?minimumAge = ageRange[0].AsIntegerOrNull();
                int?maximumAge = ageRange[1].AsIntegerOrNull();
                personQry = personQry.WhereAgeRange(minimumAge, maximumAge, true);
            }

            // only include people whose birthday is today (which can be determined from the computed DaysUntilBirthday column)
            personQry = personQry.Where(a => a.DaysUntilBirthday.HasValue && a.DaysUntilBirthday == 0);

            var connectionStatusGuids = (dataMap.GetString("ConnectionStatuses") ?? string.Empty).Split(',').AsGuidList();

            if (connectionStatusGuids.Any())
            {
                personQry = personQry.Where(a => connectionStatusGuids.Contains(a.ConnectionStatusValue.Guid));
            }

            // only include people that have an email address and want an email
            personQry = personQry.Where(a => (a.Email != null) && (a.Email != string.Empty) && (a.EmailPreference != EmailPreference.DoNotEmail) && (a.IsEmailActive));

            var recipients = new List <RecipientData>();

            var personList = personQry.AsNoTracking().ToList();

            foreach (var person in personList)
            {
                var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(null);
                mergeFields.Add("Person", person);

                recipients.Add(new RecipientData(person.Email, mergeFields));
            }

            var emailMessage = new RockEmailMessage(systemEmail.Guid);

            emailMessage.SetRecipients(recipients);
            var errors = new List <string>();

            emailMessage.Send(out errors);
            context.Result = string.Format("{0} birthday emails sent", recipients.Count());

            if (errors.Any())
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine();
                sb.Append(string.Format("{0} Errors: ", errors.Count()));
                errors.ForEach(e => { sb.AppendLine(); sb.Append(e); });
                string errorMessage = sb.ToString();
                context.Result += errorMessage;
                var         exception = new Exception(errorMessage);
                HttpContext context2  = HttpContext.Current;
                ExceptionLogService.LogException(exception, context2);
                throw exception;
            }
        }
Exemplo n.º 26
0
        /// <summary>
        /// Executes this instance.
        /// </summary>
        public void Execute()
        {
            using (var rockContext = new RockContext())
            {
                var registration = new RegistrationService(rockContext)
                                   .Queryable("RegistrationInstance.RegistrationTemplate").AsNoTracking()
                                   .FirstOrDefault(r => r.Id == RegistrationId);

                if (registration != null && !string.IsNullOrEmpty(registration.ConfirmationEmail) &&
                    registration.RegistrationInstance != null && registration.RegistrationInstance.RegistrationTemplate != null)
                {
                    var template = registration.RegistrationInstance.RegistrationTemplate;

                    var mergeFields = new Dictionary <string, object>();
                    mergeFields.Add("RegistrationInstance", registration.RegistrationInstance);
                    mergeFields.Add("Registration", registration);

                    var anonymousHash     = new HashSet <string>();
                    var messageRecipients = new List <RockMessageRecipient>();

                    // Contact
                    if (!string.IsNullOrWhiteSpace(registration.RegistrationInstance.ContactEmail) &&
                        (template.Notify & RegistrationNotify.RegistrationContact) == RegistrationNotify.RegistrationContact)
                    {
                        var messageRecipient = registration.RegistrationInstance.GetContactRecipient(mergeFields);
                        if (!anonymousHash.Contains(messageRecipient.To))
                        {
                            messageRecipients.Add(messageRecipient);
                            anonymousHash.Add(messageRecipient.To);
                        }
                    }

                    // Group Followers
                    if (registration.GroupId.HasValue &&
                        (template.Notify & RegistrationNotify.GroupFollowers) == RegistrationNotify.GroupFollowers)
                    {
                        new GroupService(rockContext).GetFollowers(registration.GroupId.Value).AsNoTracking()
                        .Where(p =>
                               p.Email != null &&
                               p.Email != "")
                        .ToList()
                        .ForEach(p => messageRecipients.Add(new RockEmailMessageRecipient(p, mergeFields)));
                    }

                    // Group Leaders
                    if (registration.GroupId.HasValue &&
                        (template.Notify & RegistrationNotify.GroupLeaders) == RegistrationNotify.GroupLeaders)
                    {
                        new GroupMemberService(rockContext).GetLeaders(registration.GroupId.Value)
                        .Where(m =>
                               m.Person != null &&
                               m.Person.Email != null &&
                               m.Person.Email != "")
                        .Select(m => m.Person)
                        .ToList()
                        .ForEach(p => messageRecipients.Add(new RockEmailMessageRecipient(p, mergeFields)));
                    }

                    if (messageRecipients.Any())
                    {
                        var emailMessage = new RockEmailMessage(Rock.SystemGuid.SystemCommunication.REGISTRATION_NOTIFICATION.AsGuid());
                        emailMessage.AdditionalMergeFields = mergeFields;
                        emailMessage.SetRecipients(messageRecipients);
                        emailMessage.AppRoot   = AppRoot;
                        emailMessage.ThemeRoot = ThemeRoot;
                        emailMessage.Send();
                    }
                }
            }
        }
Exemplo n.º 27
0
        /// <summary>
        /// Executes the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        public virtual void Execute(IJobExecutionContext context)
        {
            JobDataMap dataMap           = context.JobDetail.JobDataMap;
            var        emailTemplateGuid = dataMap.GetString("SystemEmail").AsGuidOrNull();
            var        dataViewGuid      = dataMap.GetString("DataView").AsGuidOrNull();

            if (dataViewGuid == null || emailTemplateGuid == null)
            {
                return;
            }

            var rockContext = new RockContext();
            var dataView    = new DataViewService(rockContext).Get(( Guid )dataViewGuid);

            List <IEntity> resultSet;
            Exception      dataViewException = null;

            try
            {
                var dataViewGetQueryArgs = new DataViewGetQueryArgs
                {
                    DatabaseTimeoutSeconds = dataMap.GetString("DatabaseTimeout").AsIntegerOrNull() ?? 180
                };

                var qry = dataView.GetQuery(dataViewGetQueryArgs);
                resultSet = qry.AsNoTracking().ToList();
            }
            catch (Exception exception)
            {
                dataViewException = exception;
                var sqlTimeoutException = ReportingHelper.FindSqlTimeoutException(exception);

                if (sqlTimeoutException != null)
                {
                    var exceptionMessage = $"The dataview did not complete in a timely manner. You can try again or adjust the timeout setting of this job.";
                    dataViewException = new RockDataViewFilterExpressionException(dataView.DataViewFilter, exceptionMessage, sqlTimeoutException);
                }

                HttpContext context2 = HttpContext.Current;
                ExceptionLogService.LogException(dataViewException, context2);
                context.Result = dataViewException.Message;
                throw dataViewException;
            }

            var recipients = new List <RockEmailMessageRecipient>();

            if (resultSet.Any())
            {
                foreach (Person person in resultSet)
                {
                    if (!person.IsEmailActive || person.Email.IsNullOrWhiteSpace() || person.EmailPreference == EmailPreference.DoNotEmail)
                    {
                        continue;
                    }

                    var mergeFields = Lava.LavaHelper.GetCommonMergeFields(null);
                    mergeFields.Add("Person", person);
                    recipients.Add(new RockEmailMessageRecipient(person, mergeFields));
                }
            }

            var emailMessage = new RockEmailMessage(emailTemplateGuid.Value);

            emailMessage.SetRecipients(recipients);

            var emailSendErrors = new List <string>();

            emailMessage.Send(out emailSendErrors);

            context.Result = string.Format("{0} emails sent", recipients.Count());

            if (emailSendErrors.Any())
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine();
                sb.Append(string.Format("{0} Errors: ", emailSendErrors.Count()));
                emailSendErrors.ForEach(e => { sb.AppendLine(); sb.Append(e); });
                string errorMessage = sb.ToString();
                context.Result += errorMessage;
                var         exception = new Exception(errorMessage);
                HttpContext context2  = HttpContext.Current;
                ExceptionLogService.LogException(exception, context2);
                throw exception;
            }
        }
Exemplo n.º 28
0
        /// <summary>
        /// Executes the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        public virtual void Execute(IJobExecutionContext context)
        {
            JobDataMap dataMap           = context.JobDetail.JobDataMap;
            var        emailTemplateGuid = dataMap.GetString("SystemEmail").AsGuidOrNull();
            var        dataViewGuid      = dataMap.GetString("DataView").AsGuidOrNull();

            if (dataViewGuid != null && emailTemplateGuid.HasValue)
            {
                var rockContext = new RockContext();
                var dataView    = new DataViewService(rockContext).Get((Guid)dataViewGuid);

                List <IEntity> resultSet     = null;
                var            errorMessages = new List <string>();
                var            dataTimeout   = dataMap.GetString("DatabaseTimeout").AsIntegerOrNull() ?? 180;
                try
                {
                    var qry = dataView.GetQuery(null, rockContext, dataTimeout, out errorMessages);
                    if (qry != null)
                    {
                        resultSet = qry.AsNoTracking().ToList();
                    }
                }
                catch (Exception exception)
                {
                    ExceptionLogService.LogException(exception, HttpContext.Current);
                    while (exception != null)
                    {
                        if (exception is SqlException && (exception as SqlException).Number == -2)
                        {
                            // if there was a SQL Server Timeout, have the warning be a friendly message about that.
                            errorMessages.Add("This dataview did not complete in a timely manner. You can try again or adjust the timeout setting of this block.");
                            exception = exception.InnerException;
                        }
                        else
                        {
                            errorMessages.Add(exception.Message);
                            exception = exception.InnerException;
                        }

                        return;
                    }
                }

                var recipients = new List <RecipientData>();
                if (resultSet.Any())
                {
                    foreach (Person person in resultSet)
                    {
                        if (!person.IsEmailActive || person.Email.IsNullOrWhiteSpace() || person.EmailPreference == EmailPreference.DoNotEmail)
                        {
                            continue;
                        }
                        var mergeFields = Lava.LavaHelper.GetCommonMergeFields(null);
                        mergeFields.Add("Person", person);
                        recipients.Add(new RecipientData(person.Email, mergeFields));
                    }
                }

                var emailMessage = new RockEmailMessage(emailTemplateGuid.Value);
                emailMessage.SetRecipients(recipients);

                var errors = new List <string>();
                emailMessage.Send(out errors);

                context.Result = string.Format("{0} emails sent", recipients.Count());

                if (errors.Any())
                {
                    StringBuilder sb = new StringBuilder();
                    sb.AppendLine();
                    sb.Append(string.Format("{0} Errors: ", errors.Count()));
                    errors.ForEach(e => { sb.AppendLine(); sb.Append(e); });
                    string errorMessage = sb.ToString();
                    context.Result += errorMessage;
                    var         exception = new Exception(errorMessage);
                    HttpContext context2  = HttpContext.Current;
                    ExceptionLogService.LogException(exception, context2);
                    throw exception;
                }
            }
        }
        /// <summary>
        /// Job that will sync groups.
        ///
        /// Called by the <see cref="IScheduler" /> when a
        /// <see cref="ITrigger" /> fires that is associated with
        /// the <see cref="IJob" />.
        /// </summary>
        public virtual void Execute(IJobExecutionContext context)
        {
            JobDataMap dataMap = context.JobDetail.JobDataMap;

            try
            {
                int notificationsSent   = 0;
                int errorsEncountered   = 0;
                int pendingMembersCount = 0;

                // get groups set to sync
                RockContext rockContext = new RockContext();

                Guid?groupTypeGuid       = dataMap.GetString("GroupType").AsGuidOrNull();
                Guid?systemEmailGuid     = dataMap.GetString("NotificationEmail").AsGuidOrNull();
                Guid?groupRoleFilterGuid = dataMap.GetString("GroupRoleFilter").AsGuidOrNull();
                int? pendingAge          = dataMap.GetString("PendingAge").AsIntegerOrNull();


                bool includePreviouslyNotificed = dataMap.GetString("IncludePreviouslyNotified").AsBoolean();

                // get system email
                SystemEmailService emailService = new SystemEmailService(rockContext);

                SystemEmail systemEmail = null;
                if (!systemEmailGuid.HasValue || systemEmailGuid == Guid.Empty)
                {
                    context.Result = "Job failed. Unable to find System Email";
                    throw new Exception("No system email found.");
                }

                systemEmail = emailService.Get(systemEmailGuid.Value);

                // get group members
                if (!groupTypeGuid.HasValue || groupTypeGuid == Guid.Empty)
                {
                    context.Result = "Job failed. Unable to find group type";
                    throw new Exception("No group type found");
                }

                var qry = new GroupMemberService(rockContext).Queryable("Person, Group, Group.Members.GroupRole")
                          .Where(m => m.Group.GroupType.Guid == groupTypeGuid.Value &&
                                 m.GroupMemberStatus == GroupMemberStatus.Pending);

                if (!includePreviouslyNotificed)
                {
                    qry = qry.Where(m => m.IsNotified == false);
                }

                if (groupRoleFilterGuid.HasValue)
                {
                    qry = qry.Where(m => m.GroupRole.Guid == groupRoleFilterGuid.Value);
                }

                if (pendingAge.HasValue && pendingAge.Value > 0)
                {
                    var ageDate = RockDateTime.Now.AddDays(pendingAge.Value * -1);
                    qry = qry.Where(m => m.ModifiedDateTime > ageDate);
                }

                var pendingGroupMembers = qry.ToList();

                var groups = pendingGroupMembers.GroupBy(m => m.Group);

                var errorList = new List <string>();
                foreach (var groupKey in groups)
                {
                    var group = groupKey.Key;

                    // get list of pending people
                    var qryPendingIndividuals = group.Members.Where(m => m.GroupMemberStatus == GroupMemberStatus.Pending);

                    if (!includePreviouslyNotificed)
                    {
                        qryPendingIndividuals = qryPendingIndividuals.Where(m => m.IsNotified == false);
                    }

                    if (groupRoleFilterGuid.HasValue)
                    {
                        qryPendingIndividuals = qryPendingIndividuals.Where(m => m.GroupRole.Guid == groupRoleFilterGuid.Value);
                    }

                    var pendingIndividuals = qryPendingIndividuals.Select(m => m.Person).ToList();

                    if (!pendingIndividuals.Any())
                    {
                        continue;
                    }

                    // get list of leaders
                    var groupLeaders = group.Members.Where(m => m.GroupRole.IsLeader == true && m.Person != null && m.Person.Email != null && m.Person.Email != string.Empty);

                    if (!groupLeaders.Any())
                    {
                        errorList.Add("Unable to send emails to members in group " + group.Name + " because there is no group leader");
                        continue;
                    }

                    var recipients = new List <RecipientData>();
                    foreach (var leader in groupLeaders)
                    {
                        // create merge object
                        var mergeFields = new Dictionary <string, object>();
                        mergeFields.Add("PendingIndividuals", pendingIndividuals);
                        mergeFields.Add("Group", group);
                        mergeFields.Add("ParentGroup", group.ParentGroup);
                        mergeFields.Add("Person", leader.Person);
                        recipients.Add(new RecipientData(leader.Person.Email, mergeFields));
                    }


                    var errorMessages = new List <string>();
                    var emailMessage  = new RockEmailMessage(systemEmail.Guid);
                    emailMessage.SetRecipients(recipients);
                    emailMessage.Send(out errorMessages);

                    errorsEncountered += errorMessages.Count;
                    errorList.AddRange(errorMessages);

                    // be conservative: only mark as notified if we are sure the email didn't fail
                    if (errorMessages.Any())
                    {
                        continue;
                    }

                    notificationsSent += recipients.Count();
                    // mark pending members as notified as we go in case the job fails
                    var notifiedPersonIds = pendingIndividuals.Select(p => p.Id);
                    foreach (var pendingGroupMember in pendingGroupMembers.Where(m => m.IsNotified == false && notifiedPersonIds.Contains(m.PersonId)))
                    {
                        pendingGroupMember.IsNotified = true;
                    }

                    rockContext.SaveChanges();
                }

                context.Result = string.Format("Sent {0} emails to leaders for {1} pending individuals. {2} errors encountered.", notificationsSent, pendingMembersCount, errorsEncountered);
                if (errorList.Any())
                {
                    StringBuilder sb = new StringBuilder();
                    sb.AppendLine();
                    sb.Append("Errors: ");
                    errorList.ForEach(e => { sb.AppendLine(); sb.Append(e); });
                    string errors = sb.ToString();
                    context.Result += errors;
                    throw new Exception(errors);
                }
            }
            catch (Exception ex)
            {
                HttpContext context2 = HttpContext.Current;
                ExceptionLogService.LogException(ex, context2);
                throw;
            }
        }
Exemplo n.º 30
0
        /// <summary>
        /// Executes the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        public void Execute(IJobExecutionContext context)
        {
            var        rockContext = new RockContext();
            JobDataMap dataMap     = context.JobDetail.JobDataMap;

            // Get the details for the email that we'll be sending out.
            Guid?systemEmailGuid            = dataMap.GetString("ExpiringCreditCardEmail").AsGuidOrNull();
            SystemEmailService emailService = new SystemEmailService(rockContext);
            SystemEmail        systemEmail  = null;

            if (systemEmailGuid.HasValue)
            {
                systemEmail = emailService.Get(systemEmailGuid.Value);
            }

            if (systemEmail == null)
            {
                throw new Exception("Expiring credit card email is missing.");
            }

            // Fetch the configured Workflow once if one was set, we'll use it later.
            Guid?workflowGuid = dataMap.GetString("Workflow").AsGuidOrNull();
            WorkflowTypeCache workflowType = null;
            var workflowService            = new WorkflowService(rockContext);

            if (workflowGuid != null)
            {
                workflowType = WorkflowTypeCache.Get(workflowGuid.Value);
            }

            var qry = new FinancialScheduledTransactionService(rockContext)
                      .Queryable("ScheduledTransactionDetails,FinancialPaymentDetail.CurrencyTypeValue,FinancialPaymentDetail.CreditCardTypeValue")
                      .Where(t => t.IsActive && t.FinancialPaymentDetail.ExpirationMonthEncrypted != null &&
                             (t.EndDate == null || t.EndDate > DateTime.Now))
                      .AsNoTracking();

            // Get the current month and year
            DateTime now     = DateTime.Now;
            int      month   = now.Month;
            int      year    = now.Year;
            int      counter = 0;
            var      errors  = new List <string>();

            foreach (var transaction in qry)
            {
                int?expirationMonthDecrypted = Encryption.DecryptString(transaction.FinancialPaymentDetail.ExpirationMonthEncrypted).AsIntegerOrNull();
                int?expirationYearDecrypted  = Encryption.DecryptString(transaction.FinancialPaymentDetail.ExpirationYearEncrypted).AsIntegerOrNull();
                if (expirationMonthDecrypted.HasValue && expirationMonthDecrypted.HasValue)
                {
                    string acctNum = string.Empty;

                    if (!string.IsNullOrEmpty(transaction.FinancialPaymentDetail.AccountNumberMasked) && transaction.FinancialPaymentDetail.AccountNumberMasked.Length >= 4)
                    {
                        acctNum = transaction.FinancialPaymentDetail.AccountNumberMasked.Substring(transaction.FinancialPaymentDetail.AccountNumberMasked.Length - 4);
                    }

                    int warningYear  = expirationYearDecrypted.Value;
                    int warningMonth = expirationMonthDecrypted.Value - 1;
                    if (warningMonth == 0)
                    {
                        warningYear -= 1;
                        warningMonth = 12;
                    }

                    string warningDate        = warningMonth.ToString() + warningYear.ToString();
                    string currentMonthString = month.ToString() + year.ToString();

                    if (warningDate == currentMonthString)
                    {
                        // as per ISO7813 https://en.wikipedia.org/wiki/ISO/IEC_7813
                        var expirationDate = string.Format("{0:D2}/{1:D2}", expirationMonthDecrypted, expirationYearDecrypted);

                        var recipients  = new List <RecipientData>();
                        var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(null);
                        var person      = transaction.AuthorizedPersonAlias.Person;

                        if (!person.IsEmailActive || person.Email.IsNullOrWhiteSpace() || person.EmailPreference == EmailPreference.DoNotEmail)
                        {
                            continue;
                        }

                        mergeFields.Add("Person", person);
                        mergeFields.Add("Card", acctNum);
                        mergeFields.Add("Expiring", expirationDate);
                        recipients.Add(new RecipientData(person.Email, mergeFields));

                        var emailMessage = new RockEmailMessage(systemEmail.Guid);
                        emailMessage.SetRecipients(recipients);

                        var emailErrors = new List <string>();
                        emailMessage.Send(out emailErrors);
                        errors.AddRange(emailErrors);

                        // Start workflow for this person
                        if (workflowType != null)
                        {
                            Dictionary <string, string> attributes = new Dictionary <string, string>();
                            attributes.Add("Person", transaction.AuthorizedPersonAlias.Guid.ToString());
                            attributes.Add("Card", acctNum);
                            attributes.Add("Expiring", expirationDate);
                            StartWorkflow(workflowService, workflowType, attributes, string.Format("{0} (scheduled transaction Id: {1})", person.FullName, transaction.Id));
                        }

                        counter++;
                    }
                }
            }

            context.Result = string.Format("{0} scheduled credit card transactions were examined with {1} notice(s) sent.", qry.Count(), counter);

            if (errors.Any())
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine();
                sb.Append(string.Format("{0} Errors: ", errors.Count()));
                errors.ForEach(e => { sb.AppendLine(); sb.Append(e); });
                string errorMessage = sb.ToString();
                context.Result += errorMessage;
                var         exception = new Exception(errorMessage);
                HttpContext context2  = HttpContext.Current;
                ExceptionLogService.LogException(exception, context2);
                throw exception;
            }
        }