/// <summary> /// Gets the edit value as the IEntity.Id /// </summary> /// <param name="control">The control.</param> /// <param name="configurationValues">The configuration values.</param> /// <returns></returns> public int?GetEditValueAsEntityId(Control control, Dictionary <string, ConfigurationValue> configurationValues) { var guid = GetEditValue(control, configurationValues).AsGuid(); var item = new SystemCommunicationService(new RockContext()).Get(guid); return(item != null ? item.Id : ( int? )null); }
/// <summary> /// Sets the edit value from IEntity.Id value /// </summary> /// <param name="control">The control.</param> /// <param name="configurationValues">The configuration values.</param> /// <param name="id">The identifier.</param> public void SetEditValueFromEntityId(Control control, Dictionary <string, ConfigurationValue> configurationValues, int?id) { var item = new SystemCommunicationService(new RockContext()).Get(id ?? 0); var guidValue = item != null?item.Guid.ToString() : string.Empty; SetEditValue(control, configurationValues, guidValue); }
/// <summary> /// Binds the data source to the selection control. /// </summary> private void BindControl() { rblAlertType.BindToEnum <AlertType>(); var rockContext = new RockContext(); var connectionTypeService = new ConnectionTypeService(rockContext); ddlConnectionType.Items.Clear(); ddlConnectionType.Items.Add(new ListItem()); ddlConnectionType.Items.AddRange(connectionTypeService.Queryable().Select(x => new ListItem { Text = x.Name, Value = x.Id.ToString() }).ToArray()); dvpPersonDataView.EntityTypeId = EntityTypeCache.Get(typeof(Rock.Model.Person)).Id; var systemCommunications = new SystemCommunicationService(rockContext).Queryable().OrderBy(e => e.Title); ddlDonorSystemCommunication.Items.Clear(); ddlDonorSystemCommunication.Items.Add(new ListItem()); ddlAccountParticipantSystemCommunication.Items.Clear(); ddlAccountParticipantSystemCommunication.Items.Add(new ListItem()); if (systemCommunications.Any()) { ddlDonorSystemCommunication.Items.AddRange(systemCommunications.Select(x => new ListItem { Text = x.Title, Value = x.Id.ToString() }).ToArray()); ddlAccountParticipantSystemCommunication.Items.AddRange(systemCommunications.Select(x => new ListItem { Text = x.Title, Value = x.Id.ToString() }).ToArray()); } }
/// <summary> /// Returns breadcrumbs specific to the block that should be added to navigation /// based on the current page reference. This function is called during the page's /// oninit to load any initial breadcrumbs. /// </summary> /// <param name="pageReference">The <see cref="Rock.Web.PageReference" />.</param> /// <returns> /// A <see cref="System.Collections.Generic.List{BreadCrumb}" /> of block related <see cref="Rock.Web.UI.BreadCrumb">BreadCrumbs</see>. /// </returns> public override List <Rock.Web.UI.BreadCrumb> GetBreadCrumbs(Rock.Web.PageReference pageReference) { var breadCrumbs = new List <BreadCrumb>(); string pageTitle = "New " + SystemCommunication.FriendlyTypeName; // Get the CommunicationId if it is specified as a parameter. // If not found, check for the legacy parameter "EmailId". var communicationIdentifier = PageParameter(PageParameterKey.CommunicationId); if (string.IsNullOrEmpty(communicationIdentifier)) { communicationIdentifier = PageParameter("emailId"); } int?communicationId = communicationIdentifier.AsIntegerOrNull(); if (communicationId.HasValue) { var communication = new SystemCommunicationService(new RockContext()).Get(communicationId.Value); if (communication != null) { pageTitle = communication.Title; breadCrumbs.Add(new BreadCrumb(communication.Title, pageReference)); } } RockPage.Title = pageTitle; return(breadCrumbs); }
/// <summary> /// Initializes a new instance of the <see cref="RockEmailMessage" /> class. /// </summary> /// <param name="systemGuid">The system communication unique identifier.</param> public RockEmailMessage(Guid systemGuid) : this() { using (var rockContext = new RockContext()) { var systemCommunication = new SystemCommunicationService(rockContext).Get(systemGuid); if (systemCommunication != null) { InitEmailMessage(systemCommunication); } else { // If a matching SystemCommunication could not be found, check if this is a reference to a legacy SystemEmail object. // This is necessary to provide backward-compatibility for third-party plugins. #pragma warning disable CS0618 // Type or member is obsolete var systemEmail = new SystemEmailService(rockContext).Get(systemGuid); #pragma warning restore CS0618 // Type or member is obsolete if (systemEmail != null) { #pragma warning disable CS0612 // Type or member is obsolete InitEmailMessage(systemEmail); #pragma warning restore CS0612 // Type or member is obsolete } } } }
/// <summary> /// Sets the system communication. /// </summary> /// <returns>JobPreviewInfo.</returns> private SystemCommunicationPreviewInfo SetSystemCommunication() { var previewInfo = new SystemCommunicationPreviewInfo(); var systemCommunicationGuid = GetAttributeValue(AttributeKey.SystemCommunication).AsGuid(); if (!systemCommunicationGuid.IsEmpty()) { previewInfo.ParameterSettingType = SystemCommunicationPreviewInfo.ParameterSettingTypeEnum.BlockSetting; ViewState[ViewStateKey.SystemCommunicationGuid] = systemCommunicationGuid; } else { previewInfo.ParameterSettingType = SystemCommunicationPreviewInfo.ParameterSettingTypeEnum.QueryStringParameter; var systemCommunicationId = PageParameter(PageParameterKey.SystemCommunicationId).AsInteger(); if (systemCommunicationId > 0) { var systemCommunicationService = new SystemCommunicationService(new RockContext()); var systemCommunication = systemCommunicationService.Get(systemCommunicationId); if (systemCommunication != null) { systemCommunicationGuid = systemCommunication.Guid; ViewState[ViewStateKey.SystemCommunicationGuid] = systemCommunicationGuid; } } } HasSystemCommunication = ViewState[ViewStateKey.SystemCommunicationGuid].ToStringSafe().Length > 0; return(previewInfo); }
/// <summary> /// Creates a <see cref="Rock.Workflow.FormBuilder.FormEmailSourceSettings"/> /// object from its view model representation. /// </summary> /// <param name="viewModel">The view model that represents the object.</param> /// <returns>The object created from the view model.</returns> internal static Rock.Workflow.FormBuilder.FormEmailSourceSettings FromViewModel(this FormEmailSourceViewModel viewModel, RockContext rockContext) { if (viewModel == null) { return(null); } int?templateId = null; if (viewModel.Template.HasValue) { templateId = new SystemCommunicationService(rockContext).GetId(viewModel.Template.Value); } return(new Rock.Workflow.FormBuilder.FormEmailSourceSettings { Type = viewModel.Type == FormEmailSourceType.UseTemplate ? Rock.Workflow.FormBuilder.FormEmailSourceType.UseTemplate : Rock.Workflow.FormBuilder.FormEmailSourceType.Custom, AppendOrgHeaderAndFooter = viewModel.AppendOrgHeaderAndFooter, Body = viewModel.Body, ReplyTo = viewModel.ReplyTo, Subject = viewModel.Subject, SystemCommunicationId = templateId }); }
/// <summary> /// Initializes the services. /// </summary> /// <param name="rockContext">The rock context.</param> private void InitializeServices(RockContext rockContext) { _systemCommunicationService = new SystemCommunicationService(rockContext); _groupService = new GroupService(rockContext); _groupMemberService = new GroupMemberService(rockContext); _attendanceOccurrenceService = new AttendanceOccurrenceService(rockContext); }
private void BindData() { RockContext rockContext = new RockContext(); dvpRefundReason.DefinedTypeId = DefinedTypeCache.Get(Rock.SystemGuid.DefinedType.FINANCIAL_TRANSACTION_REFUND_REASON.AsGuid(), rockContext).Id; if (!ddlSystemCommunication.SelectedValueAsInt().HasValue) { SystemCommunicationService systemCommunicationService = new SystemCommunicationService(rockContext); var systemCommunications = systemCommunicationService.Queryable().Where(c => c.IsActive == true).Select(e => new { Title = e.Category.Name + " - " + e.Title, e.Id }).OrderBy(e => e.Title).ToList(); systemCommunications.Insert(0, new { Title = "", Id = 0 }); ddlSystemCommunication.DataSource = systemCommunications; ddlSystemCommunication.DataValueField = "Id"; ddlSystemCommunication.DataTextField = "Title"; ddlSystemCommunication.DataBind(); } List <int> registrationTemplateIds = rtpRegistrationTemplate.ItemIds.AsIntegerList(); registrationTemplateIds.RemoveAll(i => i.Equals(0)); int itemCount = 0; decimal totalPayments = 0; if (liRegistration.Visible == true && registrationTemplateIds.Count > 0) { RegistrationTemplateService registrationTemplateService = new RegistrationTemplateService(rockContext); var templates = registrationTemplateService.GetByIds(rtpRegistrationTemplate.ItemIds.AsIntegerList()); var instances = templates.SelectMany(t => t.Instances); if (ddlRegistrationInstance.SelectedValueAsId().HasValue&& ddlRegistrationInstance.SelectedValueAsId() > 0) { var instanceId = ddlRegistrationInstance.SelectedValueAsId(); instances = instances.Where(i => i.Id == instanceId); } itemCount = instances.SelectMany(i => i.Registrations).Count(); totalPayments = instances.SelectMany(i => i.Registrations).ToList().SelectMany(r => r.Payments).Sum(p => p.Transaction.TotalAmount); if (!ddlRegistrationInstance.SelectedValueAsInt().HasValue) { var instanceList = templates.SelectMany(t => t.Instances).OrderBy(i => i.Name).Select(i => new { i.Id, i.Name }).ToList(); instanceList.Insert(0, new { Id = 0, Name = "" }); ddlRegistrationInstance.DataSource = instanceList; ddlRegistrationInstance.DataValueField = "Id"; ddlRegistrationInstance.DataTextField = "Name"; ddlRegistrationInstance.DataBind(); } } if (liTransactionCodes.Visible == true && tbTransactionCodes.Text.Length > 0) { var codes = tbTransactionCodes.Text.SplitDelimitedValues(); FinancialTransactionService financialTransactionService = new FinancialTransactionService(rockContext); var transactions = financialTransactionService.Queryable().Where(ft => codes.Contains(ft.TransactionCode)); totalPayments = transactions.SelectMany(t => t.TransactionDetails).Sum(td => td.Amount); itemCount = transactions.Count(); } lAlert.Text = itemCount + (pnlRegistration.Visible?" Registrations - ": " Transactions - ") + totalPayments.FormatAsCurrency() + " Total"; }
/// <summary> /// Sets the type of the workflow action. /// </summary> /// <param name="value">The value.</param> /// <param name="workflowTypeAttributes">The workflow type attributes.</param> public void SetWorkflowActionType(WorkflowActionType value, Dictionary <Guid, Rock.Model.Attribute> workflowTypeAttributes) { EnsureChildControls(); _hfActionTypeGuid.Value = value.Guid.ToString(); _ddlCriteriaAttribute.Items.Clear(); _ddlCriteriaAttribute.Items.Add(new ListItem()); _tbddlCriteriaValue.DropDownList.Items.Clear(); _tbddlCriteriaValue.DropDownList.Items.Add(new ListItem()); foreach (var attribute in workflowTypeAttributes) { var li = new ListItem(attribute.Value.Name, attribute.Key.ToString()); li.Selected = value.CriteriaAttributeGuid.HasValue && value.CriteriaAttributeGuid.Value.ToString() == li.Value; _ddlCriteriaAttribute.Items.Add(li); _tbddlCriteriaValue.DropDownList.Items.Add(new ListItem(attribute.Value.Name, attribute.Key.ToString())); } _ddlCriteriaComparisonType.SetValue(value.CriteriaComparisonType.ConvertToInt()); _tbddlCriteriaValue.SelectedValue = value.CriteriaValue; _tbActionTypeName.Text = value.Name; _wfatpEntityType.SetValue(EntityTypeCache.Get(value.EntityTypeId)); _cbIsActivityCompletedOnSuccess.Checked = value.IsActivityCompletedOnSuccess; var entityType = EntityTypeCache.Get(value.EntityTypeId); if (entityType != null && entityType.Name == typeof(Rock.Workflow.Action.UserEntryForm).FullName) { if (value.WorkflowForm == null) { value.WorkflowForm = new WorkflowActionForm(); value.WorkflowForm.Actions = "Submit^^^Your information has been submitted successfully."; var systemEmail = new SystemCommunicationService(new RockContext()).Get(SystemGuid.SystemCommunication.WORKFLOW_FORM_NOTIFICATION.AsGuid()); if (systemEmail != null) { value.WorkflowForm.NotificationSystemCommunicationId = systemEmail.Id; } } _formEditor.SetForm(value.WorkflowForm, workflowTypeAttributes); _cbIsActionCompletedOnSuccess.Checked = true; _cbIsActionCompletedOnSuccess.Enabled = false; } else { _formEditor.SetForm(null, workflowTypeAttributes); _cbIsActionCompletedOnSuccess.Checked = value.IsActionCompletedOnSuccess; _cbIsActionCompletedOnSuccess.Enabled = true; } _phActionAttributes.Controls.Clear(); Rock.Attribute.Helper.AddEditControls(value, _phActionAttributes, true, ValidationGroup, new List <string>() { "Active", "Order" }); }
/// <summary> /// Binds the grid. /// </summary> private void BindGrid() { var SystemCommunicationService = new SystemCommunicationService(new RockContext()); SortProperty sortProperty = gEmailTemplates.SortProperty; var systemCommunications = SystemCommunicationService.Queryable("Category"); // Filter By: Category int?categoryId = rFilter.GetUserPreference(FilterSettingName.Category).AsIntegerOrNull(); if (categoryId.HasValue) { systemCommunications = systemCommunications.Where(a => a.CategoryId.HasValue && a.CategoryId.Value == categoryId.Value); } // Filter By: Is Active var activeFilter = rFilter.GetUserPreference(FilterSettingName.Active); switch (activeFilter) { case "Active": systemCommunications = systemCommunications.Where(a => a.IsActive ?? false); break; case "Inactive": systemCommunications = systemCommunications.Where(a => !(a.IsActive ?? false)); break; } // Filter By: Supports (Email|SMS) var supports = rFilter.GetUserPreference(FilterSettingName.Supports); switch (supports) { case NotificationTypeSupportedFilterValueSpecifier.SMS: systemCommunications = systemCommunications.Where(a => a.SMSMessage != null && a.SMSMessage.Trim() != ""); break; case NotificationTypeSupportedFilterValueSpecifier.Push: systemCommunications = systemCommunications.Where(a => a.PushMessage != null && a.PushMessage.Trim() != ""); break; } // Apply grid sort order. if (sortProperty != null) { gEmailTemplates.DataSource = systemCommunications.Sort(sortProperty).ToList(); } else { gEmailTemplates.DataSource = systemCommunications.OrderBy(a => a.Category.Name).ThenBy(a => a.Title).ToList(); } gEmailTemplates.EntityTypeId = EntityTypeCache.Get <Rock.Model.SystemCommunication>().Id; gEmailTemplates.DataBind(); }
/// <summary> /// Gets the <see cref="SystemCommunication"/> for a <see cref="GroupType"/>. /// </summary> /// <param name="groupType">The <see cref="GroupType"/>.</param> /// <param name="systemCommunicationService">The <see cref="SystemCommunicationService"/>.</param> /// <returns>A <see cref="SystemCommunication"/> if one is set on the <see cref="GroupType"/>, otherwise null.</returns> private SystemCommunication GetGroupTypeRsvpReminder(GroupType groupType, SystemCommunicationService systemCommunicationService) { SystemCommunication groupTypeReminder = null; if (groupType.RSVPReminderSystemCommunicationId.HasValue) { groupTypeReminder = systemCommunicationService.Get(groupType.RSVPReminderSystemCommunicationId.Value); } return(groupTypeReminder); }
private SystemCommunication GetSystemCommunication() { var systemCommunicationGuid = ViewState[ViewStateKey.SystemCommunicationGuid].ToStringSafe().AsGuid(); if (systemCommunicationGuid != Guid.Empty) { var communicationService = new SystemCommunicationService(new RockContext()); return(communicationService.Get(systemCommunicationGuid)); } return(null); }
/// <summary> /// Executes the specified context. /// </summary> /// <param name="context">The context.</param> public virtual void Execute(IJobExecutionContext context) { var rockContext = new RockContext(); var dataMap = context.JobDetail.JobDataMap; var groupType = GroupTypeCache.Get(dataMap.GetString(AttributeKey.GroupType).AsGuid()); var isGroupTypeValid = groupType.TakesAttendance && groupType.SendAttendanceReminder; var results = new StringBuilder(); context.Result = "0 attendance reminders sent."; if (!isGroupTypeValid) { var warning = $"Group Type {groupType.Name} isn't setup to take attendance or send attendance reminders."; results.Append(FormatWarningMessage(warning)); RockLogger.Log.Warning(RockLogDomains.Jobs, warning); context.Result = results.ToString(); throw new RockJobWarningException(warning); } var systemEmailGuid = dataMap.GetString(AttributeKey.SystemEmail).AsGuid(); var systemCommunication = new SystemCommunicationService(rockContext).Get(systemEmailGuid); var jobPreferredCommunicationType = ( CommunicationType )dataMap.GetString(AttributeKey.SendUsingConfiguration).AsInteger(); var isSmsEnabled = MediumContainer.HasActiveSmsTransport() && !string.IsNullOrWhiteSpace(systemCommunication.SMSMessage); if (jobPreferredCommunicationType == CommunicationType.SMS && !isSmsEnabled) { // If sms selected but not usable default to email. var errorMessage = $"The job is setup to send via SMS but either SMS isn't enabled or no SMS message was found in system communication {systemCommunication.Title}."; HandleErrorMessage(context, errorMessage); } if (jobPreferredCommunicationType != CommunicationType.Email && string.IsNullOrWhiteSpace(systemCommunication.SMSMessage)) { var warning = $"No SMS message found in system communication {systemCommunication.Title}. All attendance reminders were sent via email."; results.Append(FormatWarningMessage(warning)); RockLogger.Log.Warning(RockLogDomains.Jobs, warning); jobPreferredCommunicationType = CommunicationType.Email; } var occurrences = GetOccurenceDates(groupType, dataMap, rockContext); var groupIds = occurrences.Where(o => o.Value.Any()).Select(o => o.Key).ToList(); var leaders = GetGroupLeaders(groupIds, rockContext); var attendanceRemindersResults = SendAttendanceReminders(leaders, occurrences, systemCommunication, jobPreferredCommunicationType, isSmsEnabled); results.AppendLine($"{attendanceRemindersResults.MessagesSent} attendance reminders sent."); results.Append(FormatWarningMessages(attendanceRemindersResults.Warnings)); context.Result = results.ToString(); HandleErrorMessages(context, attendanceRemindersResults.Errors); }
/// <summary> /// Handles the Delete event of the gEmailTemplates control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RowEventArgs" /> instance containing the event data.</param> protected void gEmailTemplates_Delete(object sender, RowEventArgs e) { var rockContext = new RockContext(); SystemCommunicationService emailTemplateService = new SystemCommunicationService(rockContext); SystemCommunication emailTemplate = emailTemplateService.Get(e.RowKeyId); if (emailTemplate != null) { emailTemplateService.Delete(emailTemplate); rockContext.SaveChanges(); } BindGrid(); }
private void SendReceipt() { RockContext rockContext = new RockContext(); var receiptCommunication = new SystemCommunicationService(rockContext).Get(new Guid(GetAttributeValue("ReceiptEmail"))); if (receiptCommunication != null) { var givingUnit = new PersonAliasService(rockContext).Get(this.SelectedGivingUnit.PersonAliasId).Person; var emailMessage = new RockEmailMessage(receiptCommunication.Guid); emailMessage.AddRecipient(new RockEmailMessageRecipient(givingUnit, GetMergeFields(givingUnit))); emailMessage.AppRoot = ResolveRockUrl("~/"); emailMessage.ThemeRoot = ResolveRockUrl("~~/"); emailMessage.Send(); } }
/// <summary> /// Bind the email templates /// </summary> private void BindApprovalEmailTemplates() { var SystemCommunications = new SystemCommunicationService(new RockContext()).Queryable().OrderBy(e => e.Title); ddlApprovalEmailTemplate.Items.Clear(); if (SystemCommunications.Any()) { foreach (var SystemCommunication in SystemCommunications) { ddlApprovalEmailTemplate.Items.Add(new ListItem(SystemCommunication.Title, SystemCommunication.Guid.ToString())); } } ddlApprovalEmailTemplate.SetValue(Rock.Web.SystemSettings.GetValue(SystemSetting.COMMUNICATION_SETTING_APPROVAL_TEMPLATE).AsGuidOrNull()); }
/// <summary> /// Gets the type of the workflow action. /// </summary> /// <returns></returns> public WorkflowActionType GetWorkflowActionType(bool expandInvalid) { EnsureChildControls(); WorkflowActionType result = new WorkflowActionType(); result.Guid = new Guid(_hfActionTypeGuid.Value); result.CriteriaAttributeGuid = _ddlCriteriaAttribute.SelectedValueAsGuid(); result.CriteriaComparisonType = _ddlCriteriaComparisonType.SelectedValueAsEnum <ComparisonType>(); result.CriteriaValue = _tbddlCriteriaValue.SelectedValue; result.Name = _tbActionTypeName.Text; result.EntityTypeId = _wfatpEntityType.SelectedValueAsInt() ?? 0; result.IsActionCompletedOnSuccess = _cbIsActionCompletedOnSuccess.Checked; result.IsActivityCompletedOnSuccess = _cbIsActivityCompletedOnSuccess.Checked; var entityType = EntityTypeCache.Get(result.EntityTypeId); if (entityType != null && entityType.Name == typeof(Rock.Workflow.Action.UserEntryForm).FullName) { result.WorkflowForm = _formEditor.GetForm(); if (result.WorkflowForm == null) { result.WorkflowForm = new WorkflowActionForm(); result.WorkflowForm.Actions = "Submit^^^Your information has been submitted successfully."; var systemEmail = new SystemCommunicationService(new RockContext()).Get(SystemGuid.SystemCommunication.WORKFLOW_FORM_NOTIFICATION.AsGuid()); if (systemEmail != null) { result.WorkflowForm.NotificationSystemCommunicationId = systemEmail.Id; } } } else { result.WorkflowForm = null; } result.LoadAttributes(); Rock.Attribute.Helper.GetEditValues(_phActionAttributes, result); if (expandInvalid && !result.IsValid) { Expanded = true; } return(result); }
/// <summary> /// /// </summary> /// <returns></returns> private static WorkflowActionForm CreateNewWorkflowForm() { var workflowActionForm = new WorkflowActionForm(); workflowActionForm.PersonEntryConnectionStatusValueId = DefinedValueCache.GetId(Rock.SystemGuid.DefinedValue.PERSON_CONNECTION_STATUS_VISITOR.AsGuid()); workflowActionForm.PersonEntryRecordStatusValueId = DefinedValueCache.GetId(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_PENDING.AsGuid()); workflowActionForm.PersonEntryGroupLocationTypeValueId = DefinedValueCache.GetId(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME.AsGuid()); workflowActionForm.Actions = "Submit^^^Your information has been submitted successfully."; var systemEmail = new SystemCommunicationService(new RockContext()).Get(SystemGuid.SystemCommunication.WORKFLOW_FORM_NOTIFICATION.AsGuid()); if (systemEmail != null) { workflowActionForm.NotificationSystemCommunicationId = systemEmail.Id; } return(workflowActionForm); }
/// <summary> /// Returns the field's current value(s) /// </summary> /// <param name="parentControl">The parent control.</param> /// <param name="value">Information about the value</param> /// <param name="configurationValues">The configuration values.</param> /// <param name="condensed">Flag indicating if the value should be condensed (i.e. for use in a grid column)</param> /// <returns></returns> public override string FormatValue(Control parentControl, string value, Dictionary <string, ConfigurationValue> configurationValues, bool condensed) { string formattedValue = string.Empty; Guid guid = Guid.Empty; if (Guid.TryParse(value, out guid)) { using (var rockContext = new RockContext()) { var SystemCommunication = new SystemCommunicationService(rockContext).GetNoTracking(guid); if (SystemCommunication != null) { formattedValue = SystemCommunication.Title; } } } return(base.FormatValue(parentControl, formattedValue, null, condensed)); }
/// <summary> /// Creates the control(s) necessary for prompting user for a new value /// </summary> /// <param name="configurationValues">The configuration values.</param> /// <param name="id"></param> /// <returns> /// The control /// </returns> public override Control EditControl(Dictionary <string, ConfigurationValue> configurationValues, string id) { var editControl = new RockDropDownList { ID = id }; var SystemCommunications = new SystemCommunicationService(new RockContext()).Queryable().OrderBy(e => e.Title); // add a blank for the first option editControl.Items.Add(new ListItem()); if (SystemCommunications.Any()) { foreach (var SystemCommunication in SystemCommunications) { editControl.Items.Add(new ListItem(SystemCommunication.Title, SystemCommunication.Guid.ToString())); } return(editControl); } return(null); }
/// <summary> /// Creates a view model representation of a /// <see cref="Rock.Workflow.FormBuilder.FormEmailSourceSettings"/> object. /// </summary> /// <param name="sourceSettings">The object to be represented as a view model.</param> /// <param name="rockContext">The database context used for data lookups.</param> /// <returns>The view model representation.</returns> internal static FormEmailSourceViewModel ToViewModel(this Rock.Workflow.FormBuilder.FormEmailSourceSettings sourceSettings, RockContext rockContext) { if (sourceSettings == null) { return(null); } Guid?templateGuid = null; if (sourceSettings.SystemCommunicationId.HasValue) { templateGuid = new SystemCommunicationService(rockContext).GetGuid(sourceSettings.SystemCommunicationId.Value); } return(new FormEmailSourceViewModel { Type = sourceSettings.Type == Rock.Workflow.FormBuilder.FormEmailSourceType.UseTemplate ? FormEmailSourceType.UseTemplate : FormEmailSourceType.Custom, AppendOrgHeaderAndFooter = sourceSettings.AppendOrgHeaderAndFooter, Body = sourceSettings.Body, ReplyTo = sourceSettings.ReplyTo, Subject = sourceSettings.Subject, Template = templateGuid }); }
/// <summary> /// Executes this instance. /// </summary> /// <param name="message"></param> public override void Execute(Message message) { using (var rockContext = new RockContext()) { // Load the alert and alert type var financialTransactionAlertService = new FinancialTransactionAlertService(rockContext); var alert = financialTransactionAlertService.Queryable() .AsNoTracking() .Include(a => a.FinancialTransactionAlertType) .FirstOrDefault(a => a.Id == message.FinancialTransactionAlertId); var alertType = alert?.FinancialTransactionAlertType; // If the alert or alert type are no longer in the database, then there is nothing that can be done if (alertType == null) { return; } // Get the person that this alert was generated for. Several of the items below use this var personAliasService = new PersonAliasService(rockContext); var person = personAliasService.Queryable() .AsNoTracking() .Where(pa => pa.Id == alert.PersonAliasId) .Select(pa => pa.Person) .FirstOrDefault(); // Generate the merge objects for the lava templates used in the items below var isoDate = alert.AlertDateTime.ToISO8601DateString(); var alertsPageId = PageCache.Get(SystemGuid.Page.GIVING_ALERTS).Id; var relativeAlertLink = $"page/{alertsPageId}?StartDate={isoDate}&EndDate={isoDate}&AlertTypeId={alertType.Id}"; var mergeObjects = new Dictionary <string, object> { { nameof(FinancialTransactionAlert), alert }, { nameof(FinancialTransactionAlertType), alertType }, { nameof(Person), person }, { "RelativeAlertLink", relativeAlertLink } }; // Launch workflow if configured if (alertType.WorkflowTypeId.HasValue) { var workflowAttributeValues = new Dictionary <string, string>(); workflowAttributeValues.Add(nameof(FinancialTransactionAlert), alert.Guid.ToString()); workflowAttributeValues.Add(nameof(FinancialTransactionAlertType), alertType.Guid.ToString()); workflowAttributeValues.Add(nameof(Person), person.Guid.ToString()); alert.LaunchWorkflow(alertType.WorkflowTypeId, string.Empty, workflowAttributeValues, null); } // Add the person to a connection opportunity if configured if (alertType.ConnectionOpportunityId.HasValue) { var connectionOpportunityService = new ConnectionOpportunityService(rockContext); var statuses = connectionOpportunityService.Queryable() .AsNoTracking() .Where(co => co.Id == alertType.ConnectionOpportunityId) .SelectMany(co => co.ConnectionType.ConnectionStatuses) .Where(cs => cs.IsActive) .ToList() .OrderBy(cs => cs.Order); var status = statuses.FirstOrDefault(cs => cs.IsDefault) ?? statuses.FirstOrDefault(); if (status != null) { var connectionRequestService = new ConnectionRequestService(rockContext); var request = new ConnectionRequest { ConnectionOpportunityId = alertType.ConnectionOpportunityId.Value, PersonAliasId = alert.PersonAliasId, ConnectionStatusId = status.Id }; if (alert.TransactionId.HasValue) { request.LoadAttributes(); request.SetAttributeValue("FinancialTransactionId", alert.TransactionId.Value.ToString()); } connectionRequestService.Add(request); } } // Send a bus event if configured if (alertType.SendBusEvent) { new TransactionWasAlertedMessage { FinancialTransactionAlertId = alert.Id }.Publish(); } // Send a communication if configured if (alertType.SystemCommunicationId.HasValue) { var systemCommunicationService = new SystemCommunicationService(rockContext); var systemCommunication = systemCommunicationService.Get(alertType.SystemCommunicationId.Value); if (person != null && systemCommunication != null) { CommunicationHelper.SendMessage(person, ( int )person.CommunicationPreference, systemCommunication, mergeObjects); } } // Send a communication to account followers if an Account Participant System Communication and Account is specified // for this alert type if (alertType.AccountParticipantSystemCommunicationId.HasValue && alertType.FinancialAccountId.HasValue) { var systemCommunicationService = new SystemCommunicationService(rockContext); var financialAccountService = new FinancialAccountService(rockContext); var accountParticipantSystemCommunication = systemCommunicationService.Get(alertType.AccountParticipantSystemCommunicationId.Value); if (accountParticipantSystemCommunication != null) { var accountFollowers = financialAccountService .GetAccountParticipants(alertType.FinancialAccountId.Value, RelatedEntityPurposeKey.FinancialAccountGivingAlert) .Select(a => a.Person); foreach (var accountFollower in accountFollowers) { CommunicationHelper.SendMessage(accountFollower, ( int )accountFollower.CommunicationPreference, accountParticipantSystemCommunication, mergeObjects); } } } // Send a notification to a group if configured if (alertType.AlertSummaryNotificationGroupId.HasValue) { var systemEmailGuid = SystemGuid.SystemCommunication.FINANCIAL_TRANSACTION_ALERT_NOTIFICATION_SUMMARY.AsGuid(); var systemCommunicationService = new SystemCommunicationService(rockContext); var systemCommunication = systemCommunicationService.Get(systemEmailGuid); CommunicationHelper.SendMessage(alertType.AlertSummaryNotificationGroupId.Value, systemCommunication, mergeObjects); } rockContext.SaveChanges(); } }
/// <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; /* * 2020-01-30: DL * Workflow Form instances created prior to v1.10.2 may hold a reference to a SystemEmail (deprecated) rather than a SystemCommunication, * Processing has been added here to maintain backward-compatibility, with the SystemCommunication setting being preferred if it exists. */ #pragma warning disable CS0618 // Type or member is obsolete var sendNotification = !action.LastProcessedDateTime.HasValue && actionType != null && actionType.WorkflowForm != null && (actionType.WorkflowForm.NotificationSystemCommunicationId.HasValue || actionType.WorkflowForm.NotificationSystemEmailId.HasValue); #pragma warning restore CS0618 // Type or member is obsolete if (sendNotification) { if (action.Activity != null && (action.Activity.AssignedPersonAliasId.HasValue || action.Activity.AssignedGroupId.HasValue)) { var recipients = new List <RockMessageRecipient>(); 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 RockEmailMessageRecipient(person, 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 RockEmailMessageRecipient(person, 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); // Create and send the notification email. RockEmailMessage emailMessage = null; if (action.ActionTypeCache.WorkflowForm.NotificationSystemCommunicationId.HasValue) { var systemCommunication = new SystemCommunicationService(rockContext).Get(action.ActionTypeCache.WorkflowForm.NotificationSystemCommunicationId.Value); if (systemCommunication != null) { emailMessage = new RockEmailMessage(systemCommunication); } } #pragma warning disable CS0618 // Type or member is obsolete else if (action.ActionTypeCache.WorkflowForm.NotificationSystemEmailId.HasValue) { var systemEmail = new SystemEmailService(rockContext).Get(action.ActionTypeCache.WorkflowForm.NotificationSystemEmailId.Value); if (systemEmail != null) { emailMessage = new RockEmailMessage(systemEmail); } } #pragma warning restore CS0618 // Type or member is obsolete if (emailMessage != null) { 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 communication.", 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); }
/// <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(AttributeKey.SystemCommunication).ToString().AsGuid(); var groupGuid = dataMap.Get(AttributeKey.Group).ToString().AsGuid(); var sendToDescendants = dataMap.Get(AttributeKey.SendToDescendantGroups).ToString().AsBoolean(); var rockContext = new RockContext(); var systemCommunication = new SystemCommunicationService(rockContext).Get(emailTemplateGuid); var group = new GroupService(rockContext).Get(groupGuid); if (group != null) { var groupIds = new List <int>(); GetGroupIds(groupIds, sendToDescendants, group); var recipients = new List <RockEmailMessageRecipient>(); var groupMemberList = new GroupMemberService(rockContext) .Queryable() .Where(gm => groupIds.Contains(gm.GroupId)) .Where(gm => gm.GroupMemberStatus == GroupMemberStatus.Active) .ToList(); var errors = new List <string>(); var warnings = new List <string>(); var messagesSent = 0; foreach (GroupMember groupMember in groupMemberList) { var person = groupMember.Person; var mediumType = Rock.Model.Communication.DetermineMediumEntityTypeId( ( int )CommunicationType.Email, ( int )CommunicationType.SMS, ( int )CommunicationType.PushNotification, groupMember.CommunicationPreference, person.CommunicationPreference); var mergeFields = Lava.LavaHelper.GetCommonMergeFields(null); mergeFields.Add("Person", person); mergeFields.Add("GroupMember", groupMember); mergeFields.Add("Group", groupMember.Group); var sendMessageResults = CommunicationHelper.SendMessage(person, mediumType, systemCommunication, mergeFields); errors.AddRange(sendMessageResults.Errors); warnings.AddRange(sendMessageResults.Warnings); messagesSent += sendMessageResults.MessagesSent; } var jobResults = new StringBuilder($"{messagesSent} messages were sent."); if (warnings.Any()) { jobResults.AppendLine(); jobResults.AppendLine($"{warnings.Count} warnings:"); warnings.ForEach(w => { jobResults.AppendLine(w); }); } context.Result = jobResults.ToString(); 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> /// Shows the edit. /// </summary> /// <param name="emailTemplateId">The email template id.</param> protected void ShowEdit(int emailTemplateId) { var globalAttributes = GlobalAttributesCache.Get(); string globalFromName = globalAttributes.GetValue("OrganizationName"); tbFromName.Help = string.Format("If a From Name value is not entered the 'Organization Name' Global Attribute value of '{0}' will be used when this template is sent. <small><span class='tip tip-lava'></span></small>", globalFromName); string globalFrom = globalAttributes.GetValue("OrganizationEmail"); tbFrom.Help = string.Format("If a From Address value is not entered the 'Organization Email' Global Attribute value of '{0}' will be used when this template is sent. <small><span class='tip tip-lava'></span></small>", globalFrom); tbTo.Help = "You can specify multiple email addresses by separating them with a comma."; SystemCommunicationService emailTemplateService = new SystemCommunicationService(new RockContext()); SystemCommunication emailTemplate = emailTemplateService.Get(emailTemplateId); bool showMessagePreview = false; var pushCommunication = new CommunicationDetails(); if (emailTemplate != null) { pdAuditDetails.Visible = true; pdAuditDetails.SetEntity(emailTemplate, ResolveRockUrl("~")); lActionTitle.Text = ActionTitle.Edit(SystemCommunication.FriendlyTypeName).FormatAsHtmlTitle(); hfEmailTemplateId.Value = emailTemplate.Id.ToString(); cbIsActive.Checked = emailTemplate.IsActive.GetValueOrDefault(); cpCategory.SetValue(emailTemplate.CategoryId); tbTitle.Text = emailTemplate.Title; tbFromName.Text = emailTemplate.FromName; tbFrom.Text = emailTemplate.From; tbTo.Text = emailTemplate.To; tbCc.Text = emailTemplate.Cc; tbBcc.Text = emailTemplate.Bcc; tbSubject.Text = emailTemplate.Subject; ceEmailTemplate.Text = emailTemplate.Body; pushCommunication = new CommunicationDetails { PushData = emailTemplate.PushData, PushImageBinaryFileId = emailTemplate.PushImageBinaryFileId, PushMessage = emailTemplate.PushMessage, PushTitle = emailTemplate.PushTitle, PushOpenMessage = emailTemplate.PushOpenMessage, PushOpenAction = emailTemplate.PushOpenAction }; nbTemplateHelp.InnerHtml = CommunicationTemplateHelper.GetTemplateHelp(false); kvlMergeFields.Value = emailTemplate.LavaFields.Select(a => string.Format("{0}^{1}", a.Key, a.Value)).ToList().AsDelimited("|"); hfShowAdditionalFields.Value = (!string.IsNullOrEmpty(emailTemplate.Cc) || !string.IsNullOrEmpty(emailTemplate.Bcc)).ToTrueFalse().ToLower(); cbCssInliningEnabled.Checked = emailTemplate.CssInliningEnabled; showMessagePreview = true; } else { pdAuditDetails.Visible = false; lActionTitle.Text = ActionTitle.Add(SystemCommunication.FriendlyTypeName).FormatAsHtmlTitle(); hfEmailTemplateId.Value = 0.ToString(); cbIsActive.Checked = true; cpCategory.SetValue(( int? )null); tbTitle.Text = string.Empty; tbFromName.Text = string.Empty; tbFrom.Text = string.Empty; tbTo.Text = string.Empty; tbCc.Text = string.Empty; tbBcc.Text = string.Empty; tbSubject.Text = string.Empty; ceEmailTemplate.Text = string.Empty; } var pushNotificationControl = phPushNotification.Controls[0] as PushNotification; if (pushNotificationControl != null) { pushNotificationControl.SetFromCommunication(pushCommunication); } SetEmailMessagePreviewModeEnabled(showMessagePreview); LoadDropDowns(); // SMS Fields mfpSMSMessage.MergeFields.Clear(); mfpSMSMessage.MergeFields.Add("GlobalAttribute"); mfpSMSMessage.MergeFields.Add("Rock.Model.Person"); if (emailTemplate != null) { dvpSMSFrom.SetValue(emailTemplate.SMSFromDefinedValueId); tbSMSTextMessage.Text = emailTemplate.SMSMessage; } }
/// <summary> /// Private method called by Execute() to process the job. This method should be wrapped in a try/catch block to ensure than any exceptions are sent to the /// <see cref="ExceptionLogService"/>. /// </summary> /// <param name="context">The job's execution context.</param> private void ProcessJob(IJobExecutionContext context) { JobDataMap dataMap = context.JobDetail.JobDataMap; RockContext rockContext = new RockContext(); // Make sure GroupType job attribute was assigned. Guid? groupTypeGuid = dataMap.GetString(AttributeKey.GroupType).AsGuidOrNull(); List <GroupType> rsvpGroupTypes = new List <GroupType>(); if (groupTypeGuid != null) { // Verify GroupType exists. var groupType = new GroupTypeService(rockContext).Get(groupTypeGuid.Value); if (groupType == null) { context.Result = "Job Exited: The selected Group Type does not exist."; return; } // Verify GroupType has RSVP enabled. if (!groupType.EnableRSVP) { context.Result = "Job Exited: The selected Group Type does not have RSVP enabled."; return; } rsvpGroupTypes.Add(groupType); } else { rsvpGroupTypes = new GroupTypeService(rockContext).Queryable().AsNoTracking().Where(gt => gt.EnableRSVP).ToList(); } var sbResults = new StringBuilder(); foreach (var groupType in rsvpGroupTypes) { // Retrieve RSVP settings from GroupType. var systemCommunicationService = new SystemCommunicationService(rockContext); SystemCommunication groupTypeReminder = GetGroupTypeRsvpReminder(groupType, systemCommunicationService); int?groupTypeOffset = GetGroupTypeOffset(groupType); // Get RSVP enabled groups which have an RSVP Reminder set, and verify that there is at least one group to process. var groups = GetRsvpReminderEligibleGroups(groupType, rockContext, groupType.RSVPReminderSystemCommunicationId.HasValue); if (!groups.Any()) { sbResults.AppendLine($"The Group Type {groupType.Name} does not contain any groups with RSVP reminder communications."); continue; } // Process groups and get the response. This is where the actual work starts. sbResults.Append(ProcessGroups(groups, groupTypeReminder, groupTypeOffset, rockContext)); } // Job complete! Record results of the job to the context. var jobResult = sbResults.ToString(); if (string.IsNullOrEmpty(jobResult)) { jobResult = "Job completed successfully, but no reminders were sent."; } context.Result = jobResult; }
/// <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 var emailService = new SystemCommunicationService(rockContext); SystemCommunication 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 <RockEmailMessageRecipient>(); 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 RockEmailMessageRecipient(leader.Person, mergeFields)); } var errorMessages = new List <string>(); var emailMessage = new RockEmailMessage(systemEmail.Guid); emailMessage.SetRecipients(recipients); var sendSuccess = 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 (sendSuccess == false) { 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 && m.GroupId == group.Id && notifiedPersonIds.Contains(m.PersonId))) { pendingGroupMember.IsNotified = true; pendingMembersCount++; } 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 in GroupLeaderPendingNotificationJob: "); 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; } }
/// <summary> /// Checks SystemEmail model for legacy lava and outputs SQL to correct it. /// Fields evaluated: Title From To Cc Bcc Subject Body /// </summary> public void CheckSystemEmail() { try { RockContext rockContext = new RockContext(); var systemEmailService = new SystemCommunicationService(rockContext); foreach (var systemEmail in systemEmailService.Queryable().ToList()) { // don't change if modified if (systemEmail.ModifiedDateTime != null) { continue; } bool isUpdated = false; systemEmail.Title = ReplaceUnformatted(systemEmail.Title, ref isUpdated); systemEmail.Title = ReplaceUrl(systemEmail.Title, ref isUpdated); systemEmail.Title = ReplaceGlobal(systemEmail.Title, ref isUpdated); systemEmail.Title = ReplaceDotNotation(systemEmail.Title, ref isUpdated); systemEmail.From = ReplaceUnformatted(systemEmail.From, ref isUpdated); systemEmail.From = ReplaceUrl(systemEmail.From, ref isUpdated); systemEmail.From = ReplaceGlobal(systemEmail.From, ref isUpdated); systemEmail.From = ReplaceDotNotation(systemEmail.From, ref isUpdated); systemEmail.To = ReplaceUnformatted(systemEmail.To, ref isUpdated); systemEmail.To = ReplaceUrl(systemEmail.To, ref isUpdated); systemEmail.To = ReplaceGlobal(systemEmail.To, ref isUpdated); systemEmail.To = ReplaceDotNotation(systemEmail.To, ref isUpdated); systemEmail.Cc = ReplaceUnformatted(systemEmail.Cc, ref isUpdated); systemEmail.Cc = ReplaceUrl(systemEmail.Cc, ref isUpdated); systemEmail.Cc = ReplaceGlobal(systemEmail.Cc, ref isUpdated); systemEmail.Cc = ReplaceDotNotation(systemEmail.Cc, ref isUpdated); systemEmail.Bcc = ReplaceUnformatted(systemEmail.Bcc, ref isUpdated); systemEmail.Bcc = ReplaceUrl(systemEmail.Bcc, ref isUpdated); systemEmail.Bcc = ReplaceGlobal(systemEmail.Bcc, ref isUpdated); systemEmail.Bcc = ReplaceDotNotation(systemEmail.Bcc, ref isUpdated); systemEmail.Subject = ReplaceUnformatted(systemEmail.Subject, ref isUpdated); systemEmail.Subject = ReplaceUrl(systemEmail.Subject, ref isUpdated); systemEmail.Subject = ReplaceGlobal(systemEmail.Subject, ref isUpdated); systemEmail.Subject = ReplaceDotNotation(systemEmail.Subject, ref isUpdated); systemEmail.Body = ReplaceUnformatted(systemEmail.Body, ref isUpdated); systemEmail.Body = ReplaceUrl(systemEmail.Body, ref isUpdated); systemEmail.Body = ReplaceGlobal(systemEmail.Body, ref isUpdated); systemEmail.Body = ReplaceDotNotation(systemEmail.Body, ref isUpdated); if (isUpdated) { StringBuilder sb = new StringBuilder(); sb.AppendLine("UPDATE[SystemEmail]"); if (systemEmail.Title != null) { sb.AppendLine($"SET [Title] = '{systemEmail.Title.Replace( "'", "''" )}', "); } if (systemEmail.From != null) { sb.AppendLine($"[From] = '{systemEmail.From.Replace( "'", "''" )}', "); } if (systemEmail.To != null) { sb.AppendLine($"[To] = '{systemEmail.To.Replace( "'", "''" )}', "); } if (systemEmail.Cc != null) { sb.AppendLine($"[Cc] = '{systemEmail.Cc.Replace( "'", "''" )}', "); } if (systemEmail.Bcc != null) { sb.AppendLine($"[Bcc] = '{systemEmail.Bcc.Replace( "'", "''" )}', "); } if (systemEmail.Subject != null) { sb.AppendLine($"[Subject] = '{systemEmail.Subject.Replace( "'", "''" )}' , "); } if (systemEmail.Body != null) { sb.AppendLine($"[Body] = '{systemEmail.Body.Replace( "'", "''" )}' "); } sb.AppendLine($"WHERE [Guid] = '{systemEmail.Guid}';"); _sqlUpdateScripts.Add(sb.ToString()); } } } catch (Exception ex) { ExceptionLogService.LogException(ex, null); throw; } }
/// <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(); var emailService = new SystemCommunicationService(rockContext); SystemCommunication 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 <RockEmailMessageRecipient>(); var personList = personQry.AsNoTracking().ToList(); foreach (var person in personList) { var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(null); mergeFields.Add("Person", person); recipients.Add(new RockEmailMessageRecipient(person, 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; } }