private void SendEmail(List <Person> emailrecipients, Dictionary <string, object> mergeFields) { var message = new RockEmailMessage(); message.EnabledLavaCommands = GetAttributeValue("EnabledLavaCommands"); foreach (var person in emailrecipients) { if (person.Id > 0) { message.AddRecipient(new RockEmailMessageRecipient(person, mergeFields)); } else { message.AddRecipient(RockEmailMessageRecipient.CreateAnonymous(person.Email, mergeFields)); } } message.FromEmail = tbEmail.Text; message.FromName = tbFirstName.Text + " " + tbLastName.Text; message.Subject = GetAttributeValue("Subject"); message.Message = GetAttributeValue("MessageBody"); message.AppRoot = ResolveRockUrl("~/"); message.ThemeRoot = ResolveRockUrl("~~/"); message.CreateCommunicationRecord = GetAttributeValue("SaveCommunicationHistory").AsBoolean(); message.Send(); }
/// <summary> /// Displays the confirmation. /// </summary> /// <param name="personId">The person identifier.</param> private void DisplayConfirmation(int personId) { PersonService personService = new PersonService(new RockContext()); Person person = personService.Get(personId); if (person != null) { Rock.Model.UserLogin user = CreateUser(person, false); string url = LinkedPageUrl(AttributeKey.ConfirmationPage); if (string.IsNullOrWhiteSpace(url)) { url = ResolveRockUrl("~/ConfirmAccount"); } var mergeObjects = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson); mergeObjects.Add("ConfirmAccountUrl", RootPath + url.TrimStart(new char[] { '/' })); mergeObjects.Add("Person", person); mergeObjects.Add("User", user); var emailMessage = new RockEmailMessage(GetAttributeValue(AttributeKey.ConfirmAccountTemplate).AsGuid()); emailMessage.AddRecipient(new RockEmailMessageRecipient(person, mergeObjects)); emailMessage.AppRoot = ResolveRockUrl("~/"); emailMessage.ThemeRoot = ResolveRockUrl("~~/"); emailMessage.CreateCommunicationRecord = false; emailMessage.Send(); ShowPanel(4); } else { ShowErrorMessage("Invalid Person"); } }
private void SendConfirmation(Person person) { if (person == null) { return; } var mergeObjects = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson); mergeObjects["Person"] = person; mergeObjects["PublishGroup"] = _publishGroup; mergeObjects["Group"] = _publishGroup.Group; var message = new RockEmailMessage(); message.FromEmail = _publishGroup.ConfirmationEmail; message.FromName = _publishGroup.ConfirmationFromName; message.Subject = _publishGroup.ConfirmationSubject; message.Message = _publishGroup.ConfirmationBody; message.AddRecipient(new RecipientData(new CommunicationRecipient() { PersonAlias = person.PrimaryAlias }, mergeObjects)); message.Send(); }
public void HttpSendRockMessage() { var errorMessages = new List <string>(); var binaryFileService = new BinaryFileService(new RockContext()); var rockEmailMessage = new RockEmailMessage { FromName = "Spark Info", FromEmail = "*****@*****.**", ReplyToEmail = "*****@*****.**", CCEmails = new List <string>() { "*****@*****.**" }, //BCCEmails = new List<string>() { "*****@*****.**" }, Subject = "Mailgun HTTP Tests", Message = "This is a test of the mailgun HTTP API", //MessageMetaData = new Dictionary<string, string>() { { "", "" }, { "", "" } }, Attachments = new List <BinaryFile>() { binaryFileService.Get(10) } }; rockEmailMessage.AddRecipient(RockEmailMessageRecipient.CreateAnonymous("*****@*****.**", null)); var mailgunHttp = new MailgunHttp(); mailgunHttp.Send(rockEmailMessage, 0, null, out errorMessages); Assert.True(!errorMessages.Any()); Assert.Equal(System.Net.HttpStatusCode.OK, mailgunHttp.Response.StatusCode); }
/// <summary> /// Handles the Click event of the btnSendReminders control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void btnSendReminders_Click(object sender, EventArgs e) { var registrationsSelected = new List <int>(); int sendCount = 0; gRegistrations.SelectedKeys.ToList().ForEach(r => registrationsSelected.Add(r.ToString().AsInteger())); if (registrationsSelected.Any()) { if (_registrationInstance == null) { int?registrationInstanceId = PageParameter("RegistrationInstanceId").AsIntegerOrNull(); using (RockContext rockContext = new RockContext()) { RegistrationInstanceService registrationInstanceService = new RegistrationInstanceService(rockContext); _registrationInstance = registrationInstanceService.Queryable("RegistrationTemplate").AsNoTracking() .Where(r => r.Id == registrationInstanceId).FirstOrDefault(); } foreach (var registrationId in registrationsSelected) { // use a new rockContext for each registration so that ChangeTracker doesn't get bogged down using (RockContext rockContext = new RockContext()) { var registrationService = new RegistrationService(rockContext); var registration = registrationService.Get(registrationId); if (registration != null && !string.IsNullOrWhiteSpace(registration.ConfirmationEmail)) { Dictionary <string, object> mergeObjects = new Dictionary <string, object>(); mergeObjects.Add("Registration", registration); mergeObjects.Add("RegistrationInstance", _registrationInstance); var emailMessage = new RockEmailMessage(GetAttributeValue("ConfirmAccountTemplate").AsGuid()); emailMessage.AdditionalMergeFields = mergeObjects; emailMessage.FromEmail = txtFromEmail.Text; emailMessage.FromName = txtFromName.Text; emailMessage.Subject = txtFromSubject.Text; emailMessage.AddRecipient(registration.GetConfirmationRecipient(mergeObjects)); emailMessage.Message = ceEmailMessage.Text; emailMessage.AppRoot = ResolveRockUrl("~/"); emailMessage.ThemeRoot = ResolveRockUrl("~~/"); emailMessage.CreateCommunicationRecord = true; emailMessage.Send(); registration.LastPaymentReminderDateTime = RockDateTime.Now; rockContext.SaveChanges(); sendCount++; } } } } } pnlSend.Visible = false; pnlComplete.Visible = true; nbResult.Text = string.Format("Payment reminders have been sent to {0}.", "individuals".ToQuantity(sendCount)); }
/// <summary> /// Sends the invite. /// </summary> /// <param name="rockContext">The rock context.</param> /// <param name="component">The component.</param> /// <param name="document">The document.</param> /// <param name="person">The person.</param> /// <param name="errors">The errors.</param> /// <returns></returns> private bool SendInvite(RockContext rockContext, DigitalSignatureComponent component, SignatureDocument document, Person person, out List <string> errors) { errors = new List <string>(); if (document != null && document.SignatureDocumentTemplate != null && document.SignatureDocumentTemplate.InviteSystemCommunicationId.HasValue && person != null && !string.IsNullOrWhiteSpace(person.Email)) { string inviteLink = component.GetInviteLink(document, person, out errors); if (!errors.Any()) { var systemEmail = new SystemCommunicationService(rockContext).Get(document.SignatureDocumentTemplate.InviteSystemCommunicationId.Value); if (systemEmail != null) { var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(null, person); mergeFields.Add("SignatureDocument", document); mergeFields.Add("InviteLink", inviteLink); var emailMessage = new RockEmailMessage(systemEmail); emailMessage.AddRecipient(new RockEmailMessageRecipient(person, mergeFields)); emailMessage.Send(); } } else { return(false); } } return(true); }
private static void SendNotificationMessage(JobExecutionException jobException, ServiceJob job) { var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(null, null, new Lava.CommonMergeFieldsOptions { GetLegacyGlobalMergeFields = false }); mergeFields.Add("Job", job); try { if (jobException != null) { mergeFields.Add("Exception", Hash.FromAnonymousObject(jobException)); } } catch { // ignore } var notificationEmailAddresses = job.NotificationEmails.ResolveMergeFields(mergeFields).SplitDelimitedValues().ToList(); var emailMessage = new RockEmailMessage(Rock.SystemGuid.SystemCommunication.CONFIG_JOB_NOTIFICATION.AsGuid()); emailMessage.AdditionalMergeFields = mergeFields; // NOTE: the EmailTemplate may also have TO: defined, so even if there are no notificationEmailAddress defined for this specific job, we still should send the mail foreach (var notificationEmailAddress in notificationEmailAddresses) { emailMessage.AddRecipient(RockEmailMessageRecipient.CreateAnonymous(notificationEmailAddress, null)); } emailMessage.Send(); }
private void Send(string recipients, string fromEmail, string fromName, string subject, string body, Dictionary <string, object> mergeFields, RockContext rockContext, bool createCommunicationRecord, BinaryFile[] attachments) { var emailMessage = new RockEmailMessage(); foreach (string recipient in recipients.SplitDelimitedValues().ToList()) { emailMessage.AddRecipient(new RecipientData(recipient, mergeFields)); } emailMessage.FromEmail = fromEmail; emailMessage.FromName = fromName.IsNullOrWhiteSpace() ? fromEmail : fromName; emailMessage.Subject = subject; emailMessage.Message = body; foreach (BinaryFile b in attachments) { if (b != null) { emailMessage.Attachments.Add(b); } } emailMessage.CreateCommunicationRecord = createCommunicationRecord; emailMessage.AppRoot = GlobalAttributesCache.Get().GetValue("InternalApplicationRoot") ?? string.Empty; emailMessage.Send(); }
/// <summary> /// Handles the Click event of the btnSendEmail control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void btnSendEmail_Click(object sender, EventArgs e) { int sendCount = 0; foreach (RepeaterItem repeaterItem in rptRecipients.Items) { CheckBox cbEmailRecipient = (CheckBox)repeaterItem.FindControl("cbEmailRecipient"); if (cbEmailRecipient != null && cbEmailRecipient.Checked) { int?registrationId = cbEmailRecipient.Attributes["Id"].AsIntegerOrNull(); if (registrationId.HasValue) { var registration = _registrants.Where(r => r.RegistrationId == registrationId).Select(r => r.Registration).FirstOrDefault(); var mergeObjects = GetMergeObjects(registration); var emailMessage = new RockEmailMessage(); emailMessage.AdditionalMergeFields = mergeObjects; emailMessage.FromEmail = tbFromEmail.Text; emailMessage.FromName = tbFromName.Text; emailMessage.Subject = tbFromSubject.Text; emailMessage.AddRecipient(new RecipientData(registration.ConfirmationEmail, mergeObjects)); emailMessage.Message = ceEmailMessage.Text; emailMessage.AppRoot = ResolveRockUrl("~/"); emailMessage.ThemeRoot = ResolveRockUrl("~~/"); emailMessage.Send(); sendCount++; } } } pnlSend.Visible = false; pnlComplete.Visible = true; nbResult.Text = string.Format("Wait List Transition emails have been sent to {0}.", "individuals".ToQuantity(sendCount)); }
/// <summary> /// Executes the specified context. /// </summary> /// <param name="context">The context.</param> public virtual void Execute(IJobExecutionContext context) { JobDataMap dataMap = context.JobDetail.JobDataMap; int alertPeriod = dataMap.GetInt("AlertPeriod"); Guid? systemEmailGuid = dataMap.GetString("AlertEmail").AsGuidOrNull(); List <string> recipientEmails = dataMap.GetString("AlertRecipients").SplitDelimitedValues().ToList(); if (systemEmailGuid.HasValue && recipientEmails.Any()) { var rockContext = new RockContext(); int expirationDays = GetJobAttributeValue("ExpirationPeriod", 3, rockContext); var cutoffTime = RockDateTime.Now.AddMinutes(0 - alertPeriod); var communications = new CommunicationService(rockContext) .GetQueued(expirationDays, alertPeriod, false, false) .Where(c => !c.ReviewedDateTime.HasValue || c.ReviewedDateTime.Value.CompareTo(cutoffTime) < 0) // Make sure communication wasn't just recently approved .OrderBy(c => c.Id) .ToList(); if (communications.Any()) { var mergeFields = Lava.LavaHelper.GetCommonMergeFields(null); mergeFields.Add("Communications", communications); var emailMessage = new RockEmailMessage(systemEmailGuid.Value); foreach (var email in recipientEmails) { emailMessage.AddRecipient(new RecipientData(email, mergeFields)); } emailMessage.Send(); } } }
/// <summary> /// Displays the success. /// </summary> /// <param name="user">The user.</param> private void DisplaySuccess(Rock.Model.UserLogin user) { Authorization.SignOut(); Authorization.SetAuthCookie(tbUserName.Text, false, false); if (user != null && user.PersonId.HasValue) { PersonService personService = new PersonService(new RockContext()); Person person = personService.Get(user.PersonId.Value); if (person != null) { try { string url = LinkedPageUrl(AttributeKey.ConfirmationPage); if (string.IsNullOrWhiteSpace(url)) { url = ResolveRockUrl("~/ConfirmAccount"); } var mergeObjects = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson); mergeObjects.Add("ConfirmAccountUrl", RootPath + url.TrimStart(new char[] { '/' })); mergeObjects.Add("Person", person); mergeObjects.Add("User", user); var emailMessage = new RockEmailMessage(GetAttributeValue(AttributeKey.AccountCreatedTemplate).AsGuid()); emailMessage.AddRecipient(new RockEmailMessageRecipient(person, mergeObjects)); emailMessage.AppRoot = ResolveRockUrl("~/"); emailMessage.ThemeRoot = ResolveRockUrl("~~/"); emailMessage.CreateCommunicationRecord = false; emailMessage.Send(); } catch (SystemException ex) { ExceptionLogService.LogException(ex, Context, RockPage.PageId, RockPage.Site.Id, CurrentPersonAlias); } string returnUrl = Request.QueryString["returnurl"]; btnContinue.Visible = !string.IsNullOrWhiteSpace(returnUrl); lSuccessCaption.Text = GetAttributeValue(AttributeKey.SuccessCaption); if (lSuccessCaption.Text.Contains("{0}")) { lSuccessCaption.Text = string.Format(lSuccessCaption.Text, person.FirstName); } ShowPanel(5); } else { ShowErrorMessage("Invalid Person"); } } else { ShowErrorMessage("Invalid User"); } }
/// <summary> /// Displays the sent login. /// </summary> /// <param name="direction">The direction.</param> private void DisplaySentLogin(Direction direction) { var rockContext = new RockContext(); PersonService personService = new PersonService(rockContext); Person person = personService.Get(hfSendPersonId.Value.AsInteger()); if (person != null) { string url = LinkedPageUrl(AttributeKey.ConfirmationPage); if (string.IsNullOrWhiteSpace(url)) { url = ResolveRockUrl("~/ConfirmAccount"); } var mergeObjects = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson); mergeObjects.Add("ConfirmAccountUrl", RootPath + url.TrimStart(new char[] { '/' })); var results = new List <IDictionary <string, object> >(); var users = new List <UserLogin>(); var userLoginService = new UserLoginService(rockContext); foreach (UserLogin user in userLoginService.GetByPersonId(person.Id)) { if (user.EntityType != null) { var component = AuthenticationContainer.GetComponent(user.EntityType.Name); if (component.ServiceType == AuthenticationServiceType.Internal) { users.Add(user); } } } var resultsDictionary = new Dictionary <string, object>(); resultsDictionary.Add("Person", person); resultsDictionary.Add("Users", users); results.Add(resultsDictionary); mergeObjects.Add("Results", results.ToArray()); var emailMessage = new RockEmailMessage(GetAttributeValue(AttributeKey.ForgotUsernameTemplate).AsGuid()); emailMessage.AddRecipient(new RockEmailMessageRecipient(person, mergeObjects)); emailMessage.AppRoot = ResolveRockUrl("~/"); emailMessage.ThemeRoot = ResolveRockUrl("~~/"); emailMessage.CreateCommunicationRecord = false; emailMessage.Send(); } else { ShowErrorMessage("Invalid Person"); } ShowPanel(3); }
/// <summary> /// Executes the specified context. /// </summary> /// <param name="context">The context.</param> public virtual void Execute(IJobExecutionContext context) { JobDataMap dataMap = context.JobDetail.JobDataMap; int alertPeriod = dataMap.GetInt("AlertPeriod"); Guid? systemEmailGuid = dataMap.GetString("AlertEmail").AsGuidOrNull(); List <string> recipientEmails = dataMap.GetString("AlertRecipients").SplitDelimitedValues().ToList(); if (systemEmailGuid.HasValue && recipientEmails.Any()) { var rockContext = new RockContext(); int expirationDays = GetJobAttributeValue("ExpirationPeriod", 3, rockContext); var beginWindow = RockDateTime.Now.AddDays(0 - expirationDays); var cutoffTime = RockDateTime.Now.AddMinutes(0 - alertPeriod); var communications = new CommunicationService(rockContext) .GetQueued(expirationDays, alertPeriod, false, false) .NotRecentlyApproved(cutoffTime) .IfScheduledAreInWindow(beginWindow, cutoffTime) .OrderBy(c => c.Id) .ToList(); if (communications.Any()) { var mergeFields = Lava.LavaHelper.GetCommonMergeFields(null); mergeFields.Add("Communications", communications); var emailMessage = new RockEmailMessage(systemEmailGuid.Value); foreach (var email in recipientEmails) { emailMessage.AddRecipient(RockEmailMessageRecipient.CreateAnonymous(email, mergeFields)); } var errors = new List <string>(); emailMessage.Send(out errors); context.Result = string.Format("Notified about {0} queued communications. {1} errors encountered.", communications.Count, errors.Count); if (errors.Any()) { StringBuilder sb = new StringBuilder(); sb.AppendLine(); sb.Append("Errors: "); errors.ForEach(e => { sb.AppendLine(); sb.Append(e); }); string errorMessage = sb.ToString(); context.Result += errorMessage; throw new Exception(errorMessage); } } } }
private void SendReceipt() { RockContext rockContext = new RockContext(); var receiptEmail = new SystemEmailService(rockContext).Get(new Guid(GetAttributeValue("ReceiptEmail"))); if (receiptEmail != null) { var givingUnit = new PersonAliasService(rockContext).Get(this.SelectedGivingUnit.PersonAliasId).Person; var emailMessage = new RockEmailMessage(receiptEmail.Guid); emailMessage.AddRecipient(new RecipientData(givingUnit.Email, GetMergeFields(givingUnit))); emailMessage.AppRoot = ResolveRockUrl("~/"); emailMessage.ThemeRoot = ResolveRockUrl("~~/"); emailMessage.Send(); } }
private void Send(string recipients, string fromEmail, string fromName, string subject, string body, Dictionary <string, object> mergeFields, RockContext rockContext, bool createCommunicationRecord) { var emailMessage = new RockEmailMessage(); foreach (string recipient in recipients.SplitDelimitedValues().ToList()) { emailMessage.AddRecipient(new RecipientData(recipient, mergeFields)); } emailMessage.FromEmail = fromEmail; emailMessage.FromName = fromName; emailMessage.Subject = subject; emailMessage.Message = body; emailMessage.CreateCommunicationRecord = createCommunicationRecord; emailMessage.Send(); }
/// <summary> /// Sends the new group member an email using the group attributes /// </summary> /// <returns>true if settings are valid; false otherwise</returns> protected void SendGroupEmail(GroupMember groupMember) { var group = groupMember.Group; if (group.Attributes == null) { group.LoadAttributes(); } var sendEmail = group.GetAttributeValue("SendEmail").AsBoolean(); if (sendEmail && !string.IsNullOrWhiteSpace(groupMember.Person.Email)) { var message = group.GetAttributeValue("Message"); if (!string.IsNullOrWhiteSpace(message)) { var mergeFields = new Dictionary <string, object>() { { "Group", group }, { "GroupMember", groupMember }, { "Person", groupMember.Person } }; var fromEmail = group.GetAttributeValue("FromEmail"); var fromName = group.GetAttributeValue("FromName"); var subject = group.GetAttributeValue("Subject"); var emailMessage = new RockEmailMessage(); emailMessage.AddRecipient(new RecipientData(groupMember.Person.Email, mergeFields)); emailMessage.FromEmail = fromEmail; emailMessage.FromName = fromName; emailMessage.Subject = subject; emailMessage.Message = message; emailMessage.CreateCommunicationRecord = true; emailMessage.AppRoot = Rock.Web.Cache.GlobalAttributesCache.Get().GetValue("InternalApplicationRoot") ?? string.Empty; emailMessage.Send(); } } }
/// <summary> /// Sends the confirmation email. /// </summary> /// <param name="attendance">The attendance.</param> /// <param name="recipientEmailAddresses">The recipient email addresses.</param> private void SendResponseEmail(Attendance attendance, List <string> recipientEmailAddresses) { try { var mergeFields = MergeFields(attendance); // Distinct is used so that if the same email address is for both the Scheduler and ScheduleCancellationPersonAlias // Only one email will be sent foreach (var recipient in recipientEmailAddresses.Distinct(StringComparer.CurrentCultureIgnoreCase).Where(s => s.IsNotNullOrWhiteSpace())) { var emailMessage = new RockEmailMessage(GetAttributeValue("SchedulingResponseEmail").AsGuid()); emailMessage.AddRecipient(new RecipientData(recipient, mergeFields)); emailMessage.CreateCommunicationRecord = false; emailMessage.Send(); } } catch (SystemException ex) { ExceptionLogService.LogException(ex, Context, RockPage.PageId, RockPage.Site.Id, CurrentPersonAlias); } }
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); }
public void SendShouldSendEmailWhenReplyToEmailIsNotDefined() { // Arrange var smtp = new SMTP(); var rockEmailMessage = new RockEmailMessage(); rockEmailMessage.ReplyToEmail = null; rockEmailMessage.AddRecipient(new RockEmailMessageRecipient(new Person { Email = "*****@*****.**", FirstName = "Test", LastName = "User" }, new Dictionary <string, object>())); // Act smtp.Send((RockMessage)rockEmailMessage, 0, new Dictionary <string, string>(), out List <string> errorMessages); // Assert Assert.That.AreEqual(0, errorMessages.Count, errorMessages.JoinStrings(", ")); }
/// <summary> /// Sends the confirmation email. /// </summary> /// <param name="attendance">The attendance.</param> /// <param name="recipientEmailAddresses">The recipient email addresses.</param> private void SendResponseEmail(Attendance attendance, List <RockEmailMessageRecipient> recipients) { try { var mergeFields = MergeFields(attendance); // Distinct is used so that if the same email address is for both the Scheduler and ScheduleCancellationPersonAlias // Only one email will be sent foreach (var recipient in recipients) { recipient.MergeFields = mergeFields; var emailMessage = new RockEmailMessage(GetAttributeValue("SchedulingResponseEmail").AsGuid()); emailMessage.AddRecipient(recipient); emailMessage.CreateCommunicationRecord = false; emailMessage.Send(); } } catch (SystemException ex) { ExceptionLogService.LogException(ex, Context, RockPage.PageId, RockPage.Site.Id, CurrentPersonAlias); } }
/// <summary> /// Executes this instance. /// </summary> /// <param name="message"></param> public override void Execute(Message message) { using (var rockContext = new RockContext()) { var registration = new RegistrationService(rockContext) .Queryable("RegistrationInstance.RegistrationTemplate") .AsNoTracking() .FirstOrDefault(r => r.Id == message.RegistrationId); if (registration != null && registration.RegistrationInstance != null && !string.IsNullOrEmpty(registration.ConfirmationEmail)) { var template = registration.RegistrationInstance.RegistrationTemplate; if (template != null && !string.IsNullOrWhiteSpace(template.ConfirmationEmailTemplate)) { var currentPersonOverride = (registration.RegistrationInstance.ContactPersonAlias != null) ? registration.RegistrationInstance.ContactPersonAlias.Person : null; var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(null, currentPersonOverride); mergeFields.Add("RegistrationInstance", registration.RegistrationInstance); mergeFields.Add("Registration", registration); var emailMessage = new RockEmailMessage(); emailMessage.AddRecipient(registration.GetConfirmationRecipient(mergeFields)); emailMessage.AdditionalMergeFields = mergeFields; emailMessage.FromEmail = template.ConfirmationFromEmail; emailMessage.FromName = template.ConfirmationFromName; emailMessage.Subject = template.ConfirmationSubject; emailMessage.Message = template.ConfirmationEmailTemplate; emailMessage.AppRoot = message.AppRoot; emailMessage.ThemeRoot = message.ThemeRoot; emailMessage.CurrentPerson = currentPersonOverride; emailMessage.Send(); } } } }
/// <summary> /// Handles the ItemCommand event of the rptrReceiptOptions control. /// </summary> /// <param name="source">The source of the event.</param> /// <param name="e">The <see cref="RepeaterCommandEventArgs"/> instance containing the event data.</param> protected void rptrReceiptOptions_ItemCommand(object source, RepeaterCommandEventArgs e) { var destination = e.CommandArgument.ToStringSafe(); var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(RockPage, CurrentPerson); mergeFields.AddOrReplace("Person", Customer); mergeFields.AddOrReplace("Cart", Cart); if (destination.StartsWith("email:")) { var emailMessage = new RockEmailMessage(GetAttributeValue("ReceiptEmail").AsGuid()) { AppRoot = GlobalAttributesCache.Get().GetValue("InternalApplicationRoot"), CreateCommunicationRecord = false }; emailMessage.AddRecipient(new RecipientData(destination.Substring(6), mergeFields)); emailMessage.Send(); } else if (destination.StartsWith("sms:")) { var smsMessage = new RockSMSMessage { FromNumber = DefinedValueCache.Get(GetAttributeValue("ReceiptSMSNumber").AsGuid()), Message = GetAttributeValue("SMSReceiptTemplate"), AppRoot = GlobalAttributesCache.Get().GetValue("InternalApplicationRoot") }; smsMessage.AddRecipient(new RecipientData(destination.Substring(4), mergeFields)); List <string> errorMessages; bool result = smsMessage.Send(out errorMessages); } ResetTerminal(); }
/// <summary> /// Handles the Click event of the btnSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> /// <exception cref="System.NotImplementedException"></exception> protected void btnSave_Click(object sender, EventArgs e) { var rockContext = new RockContext(); var financialPledgeService = new FinancialPledgeService(rockContext); var financialAccountService = new FinancialAccountService(rockContext); var definedValueService = new DefinedValueService(rockContext); var person = FindPerson(rockContext); FinancialPledge financialPledge = new FinancialPledge(); financialPledge.PersonAliasId = person.PrimaryAliasId; financialPledge.GroupId = ddlGroup.SelectedValueAsInt(); var financialAccount = financialAccountService.Get(GetAttributeValue("Account").AsGuid()); if (financialAccount != null) { financialPledge.AccountId = financialAccount.Id; } financialPledge.TotalAmount = tbTotalAmount.Value ?? 0.0m; var pledgeFrequencySelection = DefinedValueCache.Get(ddlFrequency.SelectedValue.AsInteger()); if (pledgeFrequencySelection != null) { financialPledge.PledgeFrequencyValueId = pledgeFrequencySelection.Id; } financialPledge.StartDate = drpDateRange.LowerValue ?? DateTime.MinValue; financialPledge.EndDate = drpDateRange.UpperValue ?? DateTime.MaxValue; if (sender != btnConfirm) { var duplicatePledges = financialPledgeService.Queryable() .Where(a => a.PersonAlias.PersonId == person.Id) .Where(a => a.AccountId == financialPledge.AccountId) .Where(a => a.StartDate == financialPledge.StartDate) .Where(a => a.EndDate == financialPledge.EndDate).ToList(); if (duplicatePledges.Any()) { pnlAddPledge.Visible = false; pnlConfirm.Visible = true; nbDuplicatePledgeWarning.Text = "The following pledges have already been entered for you:"; nbDuplicatePledgeWarning.Text += "<ul>"; foreach (var pledge in duplicatePledges.OrderBy(a => a.StartDate).ThenBy(a => a.Account.Name)) { nbDuplicatePledgeWarning.Text += string.Format("<li>{0} {1} {2}</li>", pledge.Account, pledge.PledgeFrequencyValue, pledge.TotalAmount); } nbDuplicatePledgeWarning.Text += "</ul>"; return; } } if (financialPledge.IsValid) { financialPledgeService.Add(financialPledge); rockContext.SaveChanges(); // populate account so that Liquid can access it financialPledge.Account = financialAccount; // populate PledgeFrequencyValue so that Liquid can access it financialPledge.PledgeFrequencyValue = definedValueService.Get(financialPledge.PledgeFrequencyValueId ?? 0); var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson); mergeFields.Add("Person", person); mergeFields.Add("FinancialPledge", financialPledge); mergeFields.Add("PledgeFrequency", pledgeFrequencySelection); mergeFields.Add("Account", financialAccount); lReceipt.Text = GetAttributeValue("ReceiptText").ResolveMergeFields(mergeFields); // Resolve any dynamic url references string appRoot = ResolveRockUrl("~/"); string themeRoot = ResolveRockUrl("~~/"); lReceipt.Text = lReceipt.Text.Replace("~~/", themeRoot).Replace("~/", appRoot); lReceipt.Visible = true; pnlAddPledge.Visible = false; pnlConfirm.Visible = false; // if a ConfirmationEmailTemplate is configured, send an email var confirmationEmailTemplateGuid = GetAttributeValue("ConfirmationEmailTemplate").AsGuidOrNull(); if (confirmationEmailTemplateGuid.HasValue) { var emailMessage = new RockEmailMessage(confirmationEmailTemplateGuid.Value); emailMessage.AddRecipient(new RockEmailMessageRecipient(person, mergeFields)); emailMessage.AppRoot = ResolveRockUrl("~/"); emailMessage.ThemeRoot = ResolveRockUrl("~~/"); emailMessage.Send(); } } else { ShowInvalidResults(financialPledge.ValidationResults); } }
/// <summary> /// Executes the specified context. /// </summary> /// <param name="context">The context.</param> public void Execute(IJobExecutionContext context) { var errors = new List <string>(); var rockContext = new RockContext(); JobDataMap dataMap = context.JobDetail.JobDataMap; Guid? systemEmailGuid = dataMap.GetString("NotificationEmailTemplate").AsGuidOrNull(); if (systemEmailGuid.HasValue) { var selectedGroupTypes = new List <Guid>(); if (!string.IsNullOrWhiteSpace(dataMap.GetString("GroupTypes"))) { selectedGroupTypes = dataMap.GetString("GroupTypes").Split(',').Select(Guid.Parse).ToList(); } var notificationOption = dataMap.GetString("NotifyParentLeaders").ConvertToEnum <NotificationOption>(NotificationOption.None); var accountAbilityGroupGuid = dataMap.GetString("AccountabilityGroup").AsGuid(); var groupRequirementsQry = new GroupRequirementService(rockContext).Queryable(); // get groups matching of the types provided GroupService groupService = new GroupService(rockContext); var groups = groupService.Queryable().AsNoTracking() .Where(g => selectedGroupTypes.Contains(g.GroupType.Guid) && g.IsActive == true && groupRequirementsQry.Any(a => (a.GroupId.HasValue && a.GroupId == g.Id) || (a.GroupTypeId.HasValue && a.GroupTypeId == g.GroupTypeId))); foreach (var group in groups) { // check for members that don't meet requirements var groupMembersWithIssues = groupService.GroupMembersNotMeetingRequirements(group, true); if (groupMembersWithIssues.Count > 0) { // add issues to issue list GroupsMissingRequirements groupMissingRequirements = new GroupsMissingRequirements(); groupMissingRequirements.Id = group.Id; groupMissingRequirements.Name = group.Name; if (group.GroupType != null) { groupMissingRequirements.GroupTypeId = group.GroupTypeId; groupMissingRequirements.GroupTypeName = group.GroupType.Name; } groupMissingRequirements.AncestorPathName = groupService.GroupAncestorPathName(group.Id); // get list of the group leaders groupMissingRequirements.Leaders = group.Members .Where(m => m.GroupRole.ReceiveRequirementsNotifications) .Select(m => new GroupMemberResult { Id = m.Id, PersonId = m.PersonId, FullName = m.Person.FullName }) .ToList(); List <GroupMembersMissingRequirements> groupMembers = new List <GroupMembersMissingRequirements>(); foreach (var groupMemberIssue in groupMembersWithIssues) { GroupMembersMissingRequirements groupMember = new GroupMembersMissingRequirements(); groupMember.FullName = groupMemberIssue.Key.Person.FullName; groupMember.Id = groupMemberIssue.Key.Id; groupMember.PersonId = groupMemberIssue.Key.PersonId; groupMember.GroupMemberRole = groupMemberIssue.Key.GroupRole.Name; List <MissingRequirement> missingRequirements = new List <MissingRequirement>(); foreach (var issue in groupMemberIssue.Value) { MissingRequirement missingRequirement = new MissingRequirement(); missingRequirement.Id = issue.Key.GroupRequirement.GroupRequirementType.Id; missingRequirement.Name = issue.Key.GroupRequirement.GroupRequirementType.Name; missingRequirement.Status = issue.Key.MeetsGroupRequirement; missingRequirement.OccurrenceDate = issue.Value; switch (issue.Key.MeetsGroupRequirement) { case MeetsGroupRequirement.Meets: missingRequirement.Message = issue.Key.GroupRequirement.GroupRequirementType.PositiveLabel; break; case MeetsGroupRequirement.MeetsWithWarning: missingRequirement.Message = issue.Key.GroupRequirement.GroupRequirementType.WarningLabel; break; case MeetsGroupRequirement.NotMet: missingRequirement.Message = issue.Key.GroupRequirement.GroupRequirementType.NegativeLabel; break; } missingRequirements.Add(missingRequirement); } groupMember.MissingRequirements = missingRequirements; groupMembers.Add(groupMember); } groupMissingRequirements.GroupMembersMissingRequirements = groupMembers; _groupsMissingRequriements.Add(groupMissingRequirements); // add leaders as people to notify foreach (var leader in group.Members.Where(m => m.GroupRole.ReceiveRequirementsNotifications)) { NotificationItem notification = new NotificationItem(); notification.GroupId = group.Id; notification.Person = leader.Person; _notificationList.Add(notification); } // notify parents if (notificationOption != NotificationOption.None) { var parentLeaders = new GroupMemberService(rockContext).Queryable("Person").AsNoTracking() .Where(m => m.GroupRole.ReceiveRequirementsNotifications); if (notificationOption == NotificationOption.DirectParent) { // just the parent group parentLeaders = parentLeaders.Where(m => m.GroupId == group.ParentGroupId); } else { // all parents in the hierarchy var parentIds = groupService.GetAllAncestorIds(group.Id); parentLeaders = parentLeaders.Where(m => parentIds.Contains(m.GroupId)); } foreach (var parentLeader in parentLeaders.ToList()) { NotificationItem parentNotification = new NotificationItem(); parentNotification.Person = parentLeader.Person; parentNotification.GroupId = group.Id; _notificationList.Add(parentNotification); } } } } // send out notifications int recipients = 0; var notificationRecipients = _notificationList.GroupBy(p => p.Person.Id).ToList(); foreach (var recipientId in notificationRecipients) { var recipient = _notificationList.Where(n => n.Person.Id == recipientId.Key).Select(n => n.Person).FirstOrDefault(); if (!recipient.IsEmailActive || recipient.Email.IsNullOrWhiteSpace() || recipient.EmailPreference == EmailPreference.DoNotEmail) { continue; } var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(null); mergeFields.Add("Person", recipient); var notificationGroupIds = _notificationList .Where(n => n.Person.Id == recipient.Id) .Select(n => n.GroupId) .ToList(); var missingRequirements = _groupsMissingRequriements.Where(g => notificationGroupIds.Contains(g.Id)).ToList(); mergeFields.Add("GroupsMissingRequirements", missingRequirements); var emailMessage = new RockEmailMessage(systemEmailGuid.Value); emailMessage.AddRecipient(new RecipientData(recipient.Email, mergeFields)); var emailErrors = new List <string>(); emailMessage.Send(out emailErrors); errors.AddRange(emailErrors); recipients++; } // add accountability group members if (!accountAbilityGroupGuid.IsEmpty()) { var accountabilityGroupMembers = new GroupMemberService(rockContext).Queryable().AsNoTracking() .Where(m => m.Group.Guid == accountAbilityGroupGuid) .Select(m => m.Person); var emailMessage = new RockEmailMessage(systemEmailGuid.Value); foreach (var person in accountabilityGroupMembers) { var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(null); mergeFields.Add("Person", person); mergeFields.Add("GroupsMissingRequirements", _groupsMissingRequriements); emailMessage.AddRecipient(new RecipientData(person.Email, mergeFields)); recipients++; } var emailErrors = new List <string>(); emailMessage.Send(out emailErrors); errors.AddRange(emailErrors); } context.Result = string.Format("{0} requirement notification {1} sent", recipients, "email".PluralizeIf(recipients != 1)); 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; } } else { context.Result = "Warning: No NotificationEmailTemplate found"; } }
/// <summary> /// Job that will run quick SQL queries on a schedule. /// /// 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; // get registrations where // + template is active // + instance is active // + template has a number of days between reminders // + template as fields needed to send a reminder email // + the registration has a cost // + the registration has been closed within the last xx days (to prevent eternal nagging) using (RockContext rockContext = new RockContext()) { int sendCount = 0; int registrationInstanceCount = 0; var appRoot = Rock.Web.Cache.GlobalAttributesCache.Read().GetValue("PublicApplicationRoot"); RegistrationService registrationService = new RegistrationService(rockContext); var currentDate = RockDateTime.Today; var cutoffDays = dataMap.GetIntFromString("CutoffDate"); var registrations = registrationService.Queryable("RegistrationInstance") .Where(r => r.RegistrationInstance.RegistrationTemplate.IsActive && r.RegistrationInstance.IsActive == true && (r.RegistrationInstance.RegistrationTemplate.PaymentReminderTimeSpan != null && r.RegistrationInstance.RegistrationTemplate.PaymentReminderTimeSpan != 0) && r.RegistrationInstance.RegistrationTemplate.PaymentReminderEmailTemplate != null && r.RegistrationInstance.RegistrationTemplate.PaymentReminderEmailTemplate.Length > 0 && r.RegistrationInstance.RegistrationTemplate.PaymentReminderFromEmail != null && r.RegistrationInstance.RegistrationTemplate.PaymentReminderFromEmail.Length > 0 && r.RegistrationInstance.RegistrationTemplate.PaymentReminderSubject != null && r.RegistrationInstance.RegistrationTemplate.PaymentReminderSubject.Length > 0 && (r.RegistrationInstance.RegistrationTemplate.Cost != 0 || (r.RegistrationInstance.Cost != null && r.RegistrationInstance.Cost != 0)) && (r.RegistrationInstance.EndDateTime == null || currentDate <= System.Data.Entity.SqlServer.SqlFunctions.DateAdd("day", cutoffDays, r.RegistrationInstance.EndDateTime))) .ToList(); registrationInstanceCount = registrations.Select(r => r.RegistrationInstance.Id).Distinct().Count(); foreach (var registration in registrations) { if (registration.DiscountedCost > registration.TotalPaid) { var reminderDate = RockDateTime.Now.AddDays(registration.RegistrationInstance.RegistrationTemplate.PaymentReminderTimeSpan.Value * -1); if (registration.LastPaymentReminderDateTime < reminderDate) { Dictionary <string, object> mergeObjects = new Dictionary <string, object>(); mergeObjects.Add("Registration", registration); mergeObjects.Add("RegistrationInstance", registration.RegistrationInstance); var emailMessage = new RockEmailMessage(); emailMessage.AdditionalMergeFields = mergeObjects; emailMessage.AddRecipient(new RecipientData(registration.ConfirmationEmail, mergeObjects)); emailMessage.FromEmail = registration.RegistrationInstance.RegistrationTemplate.PaymentReminderFromEmail; emailMessage.FromName = registration.RegistrationInstance.RegistrationTemplate.PaymentReminderSubject; emailMessage.Subject = registration.RegistrationInstance.RegistrationTemplate.PaymentReminderFromName; emailMessage.Message = registration.RegistrationInstance.RegistrationTemplate.PaymentReminderEmailTemplate; emailMessage.Send(); registration.LastPaymentReminderDateTime = RockDateTime.Now; rockContext.SaveChanges(); sendCount++; } } } context.Result = string.Format("Sent {0} from {1}", "reminder".ToQuantity(sendCount), "registration instances".ToQuantity(registrationInstanceCount)); } }
/// <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) { // Get the job setting(s) JobDataMap dataMap = context.JobDetail.JobDataMap; bool requirePasswordReset = dataMap.GetBoolean("RequirePasswordReset"); // Counters for displaying results int groupsSynced = 0; int groupsChanged = 0; string groupName = string.Empty; string dataViewName = string.Empty; var errors = new List <string>(); try { // get groups set to sync var activeSyncIds = new List <int>(); using (var rockContext = new RockContext()) { activeSyncIds = new GroupSyncService(rockContext) .Queryable().AsNoTracking() .Select(x => x.Id) .ToList(); } foreach (var syncId in activeSyncIds) { bool hasSyncChanged = false; // Use a fresh rockContext per syc so that ChangeTracker doesn't get bogged down using (var rockContext = new RockContext()) { // increase the timeout just in case the dataview source is slow rockContext.Database.CommandTimeout = 180; rockContext.SourceOfChange = "Group Sync"; // Get the Sync var sync = new GroupSyncService(rockContext) .Queryable().AsNoTracking() .FirstOrDefault(s => s.Id == syncId); // Ensure that the group's Sync Data View is a person dataview if (sync != null && sync.SyncDataView.EntityTypeId == EntityTypeCache.Get(typeof(Person)).Id) { List <string> syncErrors = new List <string>(); dataViewName = sync.SyncDataView.Name; groupName = sync.Group.Name; // Get the person id's from the dataview (source) var personService = new PersonService(rockContext); var parameterExpression = personService.ParameterExpression; var whereExpression = sync.SyncDataView.GetExpression(personService, parameterExpression, out syncErrors); var sourcePersonIds = new PersonService(rockContext) .Get(parameterExpression, whereExpression) .Select(q => q.Id) .ToList(); // If any error occurred, just skip this sync for now. if (syncErrors.Count > 0) { errors.AddRange(syncErrors); ExceptionLogService.LogException(new Exception(string.Format("An error occurred while trying to GroupSync group '{0}' and data view '{1}' so the sync was skipped. Error: {2}", groupName, dataViewName, String.Join(",", syncErrors)))); continue; } // Get the person id's in the group (target) var targetPersonIds = new GroupMemberService(rockContext) .Queryable().AsNoTracking() .Where(gm => gm.GroupId == sync.GroupId) .Select(gm => gm.PersonId) .ToList(); // Delete people from the group/role that are no longer in the dataview foreach (var personId in targetPersonIds.Where(t => !sourcePersonIds.Contains(t))) { // Use a new context to limit the amount of change-tracking required using (var groupMemberContext = new RockContext()) { // Delete any group members for the role with the person id var groupMemberService = new GroupMemberService(groupMemberContext); foreach (var groupMember in groupMemberService .Queryable() .Where(m => m.GroupId == sync.GroupId && m.GroupRoleId == sync.GroupTypeRoleId && m.PersonId == personId) .ToList()) { groupMemberService.Delete(groupMember); } groupMemberContext.SaveChanges(); // If the Group has an exit email, and person has an email address, send them the exit email if (sync.ExitSystemEmail != null) { var person = new PersonService(groupMemberContext).Get(personId); if (person.Email.IsNotNullOrWhiteSpace()) { // Send the exit email var mergeFields = new Dictionary <string, object>(); mergeFields.Add("Group", sync.Group); mergeFields.Add("Person", person); var emailMessage = new RockEmailMessage(sync.ExitSystemEmail); emailMessage.AddRecipient(new RecipientData(person.Email, mergeFields)); var emailErrors = new List <string>(); emailMessage.Send(out emailErrors); errors.AddRange(emailErrors); } } } hasSyncChanged = true; } foreach (var personId in sourcePersonIds.Where(s => !targetPersonIds.Contains(s))) { // Use a new context to limit the amount of change-tracking required using (var groupMemberContext = new RockContext()) { // Add new person to the group with the role specified in the sync var groupMemberService = new GroupMemberService(groupMemberContext); var newGroupMember = new GroupMember { Id = 0 }; newGroupMember.PersonId = personId; newGroupMember.GroupId = sync.GroupId; newGroupMember.GroupMemberStatus = GroupMemberStatus.Active; newGroupMember.GroupRoleId = sync.GroupTypeRoleId; groupMemberService.Add(newGroupMember); groupMemberContext.SaveChanges(); // If the Group has a welcome email, and person has an email address, send them the welcome email and possibly create a login if (sync.WelcomeSystemEmail != null) { var person = new PersonService(groupMemberContext).Get(personId); if (person.Email.IsNotNullOrWhiteSpace()) { // If the group is configured to add a user account for anyone added to the group, and person does not yet have an // account, add one for them. string newPassword = string.Empty; bool createLogin = sync.AddUserAccountsDuringSync; // Only create a login if requested, no logins exist and we have enough information to generate a username. if (createLogin && !person.Users.Any() && !string.IsNullOrWhiteSpace(person.NickName) && !string.IsNullOrWhiteSpace(person.LastName)) { newPassword = System.Web.Security.Membership.GeneratePassword(9, 1); string username = Rock.Security.Authentication.Database.GenerateUsername(person.NickName, person.LastName); UserLogin login = UserLoginService.Create( groupMemberContext, person, AuthenticationServiceType.Internal, EntityTypeCache.Get(Rock.SystemGuid.EntityType.AUTHENTICATION_DATABASE.AsGuid()).Id, username, newPassword, true, requirePasswordReset); } // Send the welcome email var mergeFields = new Dictionary <string, object>(); mergeFields.Add("Group", sync.Group); mergeFields.Add("Person", person); mergeFields.Add("NewPassword", newPassword); mergeFields.Add("CreateLogin", createLogin); var emailMessage = new RockEmailMessage(sync.WelcomeSystemEmail); emailMessage.AddRecipient(new RecipientData(person.Email, mergeFields)); var emailErrors = new List <string>(); emailMessage.Send(out emailErrors); errors.AddRange(emailErrors); } } } hasSyncChanged = true; } // Increment Groups Changed Counter (if people were deleted or added to the group) if (hasSyncChanged) { groupsChanged++; } // Increment the Groups Synced Counter groupsSynced++; } } } // Format the result message var resultMessage = string.Empty; if (groupsSynced == 0) { resultMessage = "No groups to sync"; } else if (groupsSynced == 1) { resultMessage = "1 group was sync'ed"; } else { resultMessage = string.Format("{0} groups were sync'ed", groupsSynced); } resultMessage += string.Format(" and {0} groups were changed", groupsChanged); if (errors.Any()) { StringBuilder sb = new StringBuilder(); sb.AppendLine(); sb.Append("Errors: "); errors.ForEach(e => { sb.AppendLine(); sb.Append(e); }); string errorMessage = sb.ToString(); resultMessage += errorMessage; throw new Exception(errorMessage); } context.Result = resultMessage; } catch (System.Exception ex) { HttpContext context2 = HttpContext.Current; ExceptionLogService.LogException(ex, context2); throw; } }
/// <summary> /// Executes this instance. /// </summary> public void Execute() { using (var rockContext = new RockContext()) { var communication = new CommunicationService(rockContext).Get(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()) { string fromName = Rock.Web.Cache.GlobalAttributesCache.Value("OrganizationName"); string fromEmail = Rock.Web.Cache.GlobalAttributesCache.Value("OrganizationEmail"); string subject = "Pending Communication Requires Approval"; var appRoot = Rock.Web.Cache.GlobalAttributesCache.Read(rockContext).GetValue("PublicApplicationRoot"); string communicationDetails = string.Empty; string typeName = communication.CommunicationType.ConvertToString(); // get custom details by type switch (communication.CommunicationType) { case CommunicationType.Email: communicationDetails = $@" <strong>From Name:</strong> {communication.FromName}<br/> <strong>From Address:</strong> {communication.FromEmail}<br/> <strong>Subject:</strong> {communication.Subject}<br/>"; break; case CommunicationType.SMS: if (communication.SMSFromDefinedValue != null) { communicationDetails = $"<strong>SMS Number:</strong> {communication.SMSFromDefinedValue.Description} ({communication.SMSFromDefinedValue.Value})<br/>"; } break; case CommunicationType.PushNotification: communicationDetails = $"<strong>Title:</strong> {communication.PushTitle}<br/>"; break; } // create approval link if one was not provided if (string.IsNullOrEmpty(ApprovalPageUrl)) { var internalApplicationRoot = Rock.Web.Cache.GlobalAttributesCache.Read(rockContext).GetValue("InternalApplicationRoot").EnsureTrailingForwardslash(); ApprovalPageUrl = $"{internalApplicationRoot}Communication/{communication.Id}"; } foreach (var approver in approvers) { string message = string.Format(@" {{{{ 'Global' | Attribute:'EmailHeader' }}}} <p>{0}:</p> <p>A new communication requires approval. Information about this communication can be found below.</p> <p> <strong>From:</strong> {1}<br /> <strong>Type:</strong> {2}<br /> {3} <strong>Recipient Count:</strong> {4}<br /> </p> <p> <a href='{5}'>View Communication</a> </p> {{{{ 'Global' | Attribute:'EmailFooter' }}}}", approver.Person.NickName, communication.SenderPersonAlias.Person.FullName, typeName, communicationDetails, communication.GetRecipientsQry(rockContext).Count(), ApprovalPageUrl); var emailMessage = new RockEmailMessage(); emailMessage.AddRecipient(approver.Person.Email); emailMessage.FromEmail = fromEmail; emailMessage.FromName = fromName; emailMessage.Subject = subject; emailMessage.Message = message; emailMessage.AppRoot = appRoot; emailMessage.Send(); } } } } }
/// <summary> /// Starts the refund process. /// </summary> private void StartRefunds() { long totalMilliseconds = 0; var importTask = new Task(() => { // wait a little so the browser can render and start listening to events System.Threading.Thread.Sleep(1000); _hubContext.Clients.All.showButtons(this.SignalRNotificationKey, false); Stopwatch stopwatch = Stopwatch.StartNew(); List <int> registrationTemplateIds = rtpRegistrationTemplate.ItemIds.AsIntegerList(); registrationTemplateIds.RemoveAll(i => i.Equals(0)); if (registrationTemplateIds.Count > 0) { RockContext rockContext = new RockContext(); List <int> registrationInstanceIds = new List <int>(); if (ddlRegistrationInstance.SelectedValueAsId().HasValue&& ddlRegistrationInstance.SelectedValueAsId() > 0) { registrationInstanceIds.Add(ddlRegistrationInstance.SelectedValueAsId().Value); } else { RegistrationTemplateService registrationTemplateService = new RegistrationTemplateService(rockContext); var templates = registrationTemplateService.GetByIds(rtpRegistrationTemplate.ItemIds.AsIntegerList()); int registrationCount = templates.SelectMany(t => t.Instances).SelectMany(i => i.Registrations).Count(); registrationInstanceIds.AddRange(templates.SelectMany(t => t.Instances).OrderBy(i => i.Name).Select(i => i.Id)); } RegistrationInstanceService registrationInstanceService = new RegistrationInstanceService(rockContext); SystemEmailService systemEmailService = new SystemEmailService(rockContext); // Load the registration instance and then iterate through all registrations. var registrations = registrationInstanceService.Queryable().Where(ri => registrationInstanceIds.Contains(ri.Id)).SelectMany(ri => ri.Registrations); int j = 1; foreach (Registration registration in registrations) { bool issuedRefund = false; OnProgress("Processing registration refund " + j + " of " + registrations.Count()); foreach (var payment in registration.GetPayments(rockContext)) { decimal refundAmount = payment.Amount + payment.Transaction.Refunds.Sum(r => r.FinancialTransaction.TotalAmount); // If refunds totalling the amount of the payments have not already been issued if (payment.Amount > 0 && refundAmount > 0) { string errorMessage; using (var refundRockContext = new RockContext()) { var financialTransactionService = new FinancialTransactionService(refundRockContext); var refundTransaction = financialTransactionService.ProcessRefund(payment.Transaction, refundAmount, dvpRefundReason.SelectedDefinedValueId, tbRefundSummary.Text, true, string.Empty, out errorMessage); if (refundTransaction != null) { refundRockContext.SaveChanges(); } if (!string.IsNullOrWhiteSpace(errorMessage)) { results["Fail"] += string.Format("Failed refund for registration {0}: {1}", registration.FirstName + " " + registration.LastName, errorMessage) + Environment.NewLine; } else { results["Success"] += string.Format("Successfully issued {0} refund for registration {1} payment {2} ({3}) - Refund Transaction Id: {4}, Amount: {5}", refundAmount < payment.Amount?"Partial":"Full", registration.FirstName + " " + registration.LastName, payment.Transaction.TransactionCode, payment.Transaction.TotalAmount, refundTransaction.TransactionCode, refundTransaction.TotalAmount.FormatAsCurrency()) + Environment.NewLine; issuedRefund = true; } } System.Threading.Thread.Sleep(2500); } else if (payment.Transaction.Refunds.Count > 0) { results["Success"] += string.Format("Refund already issued for registration {0} payment {1} ({2})", registration.FirstName + " " + registration.LastName, payment.Transaction.TransactionCode, payment.Transaction.TotalAmount) + Environment.NewLine; } } j++; // Send an email if applicable if (issuedRefund && !string.IsNullOrWhiteSpace(registration.ConfirmationEmail) && ddlSystemEmail.SelectedValueAsInt().HasValue&& ddlSystemEmail.SelectedValueAsInt() > 0) { var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage); mergeFields.Add("Registration", registration); SystemEmail systemEmail = systemEmailService.Get(ddlSystemEmail.SelectedValueAsInt().Value); var emailMessage = new RockEmailMessage(systemEmail); emailMessage.AdditionalMergeFields = mergeFields; emailMessage.AddRecipient(new RecipientData(registration.ConfirmationEmail, mergeFields)); emailMessage.CreateCommunicationRecord = true; emailMessage.Send(); } } } stopwatch.Stop(); totalMilliseconds = stopwatch.ElapsedMilliseconds; _hubContext.Clients.All.showButtons(this.SignalRNotificationKey, true); }); importTask.ContinueWith((t) => { if (t.IsFaulted) { foreach (var exception in t.Exception.InnerExceptions) { LogException(exception); } OnProgress("ERROR: " + t.Exception.Message); } else { OnProgress(string.Format("{0} Complete: [{1}ms]", "All refunds have been issued.", totalMilliseconds)); } }); importTask.Start(); }
/// <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 recipients = new Dictionary <string, Dictionary <string, object> >(); // Contact if (!string.IsNullOrWhiteSpace(registration.RegistrationInstance.ContactEmail) && (template.Notify & RegistrationNotify.RegistrationContact) == RegistrationNotify.RegistrationContact) { recipients.AddOrIgnore(registration.RegistrationInstance.ContactEmail, mergeFields); } // Group Followers if (registration.GroupId.HasValue && (template.Notify & RegistrationNotify.GroupFollowers) == RegistrationNotify.GroupFollowers) { new GroupService(rockContext).GetFollowers(registration.GroupId.Value) .Where(f => f.Email != null && f.Email != "") .Select(f => f.Email) .ToList() .ForEach(f => recipients.AddOrIgnore(f, 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.Email) .ToList() .ForEach(m => recipients.AddOrIgnore(m, mergeFields)); } if (recipients.Any()) { var emailMessage = new RockEmailMessage(Rock.SystemGuid.SystemEmail.REGISTRATION_NOTIFICATION.AsGuid()); emailMessage.AdditionalMergeFields = mergeFields; recipients.ToList().ForEach(r => emailMessage.AddRecipient(new RecipientData(r.Key, r.Value))); emailMessage.AppRoot = AppRoot; emailMessage.ThemeRoot = ThemeRoot; emailMessage.Send(); } } } }
/// <summary> /// Handles the Click event of the btnSend control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void btnSend_Click(object sender, EventArgs e) { var url = LinkedPageUrl(AttributeKey.ConfirmationPage); if (string.IsNullOrWhiteSpace(url)) { url = ResolveRockUrl("~/ConfirmAccount"); } var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson); mergeFields.Add("ConfirmAccountUrl", RootPath + url.TrimStart(new char[] { '/' })); var results = new List <IDictionary <string, object> >(); var rockContext = new RockContext(); var personService = new PersonService(rockContext); var userLoginService = new UserLoginService(rockContext); bool hasAccountWithPasswordResetAbility = false; List <string> accountTypes = new List <string>(); foreach (Person person in personService.GetByEmail(tbEmail.Text) .Where(p => p.Users.Any())) { var users = new List <UserLogin>(); List <string> supportsChangePassword = new List <string>(); foreach (UserLogin user in userLoginService.GetByPersonId(person.Id)) { if (user.EntityType != null) { var component = AuthenticationContainer.GetComponent(user.EntityType.Name); if (component != null && !component.RequiresRemoteAuthentication) { if (component.SupportsChangePassword) { supportsChangePassword.Add(user.UserName); } users.Add(user); hasAccountWithPasswordResetAbility = true; } accountTypes.Add(user.EntityType.FriendlyName); } } var resultsDictionary = new Dictionary <string, object>(); resultsDictionary.Add("Person", person); resultsDictionary.Add("Users", users); resultsDictionary.Add("SupportsChangePassword", supportsChangePassword); results.Add(resultsDictionary); } if (results.Count > 0 && hasAccountWithPasswordResetAbility) { mergeFields.Add("Results", results.ToArray()); var emailMessage = new RockEmailMessage(GetAttributeValue(AttributeKey.EmailTemplate).AsGuid()); emailMessage.AddRecipient(RockEmailMessageRecipient.CreateAnonymous(tbEmail.Text, mergeFields)); emailMessage.AppRoot = ResolveRockUrlIncludeRoot("~/"); emailMessage.ThemeRoot = ResolveRockUrlIncludeRoot("~~/"); emailMessage.CreateCommunicationRecord = GetAttributeValue(AttributeKey.CreateCommunicationRecord).AsBoolean(); emailMessage.Send(); pnlEntry.Visible = false; pnlSuccess.Visible = true; } else if (results.Count > 0) { // The person has user accounts but none of them are allowed to have their passwords reset (Facebook/Google/etc). lWarning.Text = string.Format( @"<p>We were able to find the following accounts for this email, but none of them are able to be reset from this website.</p> <p>Accounts:<br /> {0}</p> <p>To create a new account with a username and password please see our <a href='{1}'>New Account</a> page.</p>", string.Join(",", accountTypes), ResolveRockUrl("~/NewAccount")); pnlWarning.Visible = true; } else { pnlWarning.Visible = true; } }