/// <summary> /// Creates a new communication. /// </summary> /// <param name="fromPersonAliasId">From person alias identifier.</param> /// <param name="fromPersonName">Name of from person.</param> /// <param name="toPersonAliasId">To person alias identifier.</param> /// <param name="message">The message to send.</param> /// <param name="transportPhone">The transport phone.</param> /// <param name="responseCode">The reponseCode to use for tracking the conversation.</param> /// <param name="rockContext">A context to use for database calls.</param> private void CreateCommunication(int fromPersonAliasId, string fromPersonName, int toPersonAliasId, string message, string transportPhone, string responseCode, Rock.Data.RockContext rockContext) { // add communication for reply var communication = new Rock.Model.Communication(); communication.IsBulkCommunication = false; communication.Status = CommunicationStatus.Approved; communication.SenderPersonAliasId = fromPersonAliasId; communication.Subject = string.Format("From: {0}", fromPersonName); communication.SetMediumDataValue("Message", message); communication.SetMediumDataValue("FromValue", transportPhone); communication.MediumEntityTypeId = EntityTypeCache.Read("Rock.Communication.Medium.Sms").Id; var recipient = new Rock.Model.CommunicationRecipient(); recipient.Status = CommunicationRecipientStatus.Pending; recipient.PersonAliasId = toPersonAliasId; recipient.ResponseCode = responseCode; communication.Recipients.Add(recipient); var communicationService = new Rock.Model.CommunicationService(rockContext); communicationService.Add(communication); rockContext.SaveChanges(); // queue the sending var transaction = new Rock.Transactions.SendCommunicationTransaction(); transaction.CommunicationId = communication.Id; transaction.PersonAlias = null; Rock.Transactions.RockQueue.TransactionQueue.Enqueue(transaction); }
/// <summary> /// Sends the specified communication. /// </summary> /// <param name="communication">The communication.</param> public static void Send(Rock.Model.Communication communication) { if (communication == null || communication.Status != CommunicationStatus.Approved) { return; } if (communication.ListGroupId.HasValue && !communication.SendDateTime.HasValue) { using (var rockContext = new RockContext()) { communication.RefreshCommunicationRecipientList(rockContext); } } foreach (var medium in communication.GetMediums()) { medium.Send(communication); } using (var rockContext = new RockContext()) { var dbCommunication = new CommunicationService(rockContext).Get(communication.Id); // Set the SendDateTime of the Communication dbCommunication.SendDateTime = RockDateTime.Now; rockContext.SaveChanges(); } }
/// <summary> /// Gets the HTML preview. /// </summary> /// <param name="communication">The communication.</param> /// <param name="person">The person.</param> /// <returns></returns> public override string GetHtmlPreview( Model.Communication communication, Person person ) { var rockContext = new RockContext(); // Requery the Communication object communication = new CommunicationService( rockContext ).Get( communication.Id ); var globalAttributes = Rock.Web.Cache.GlobalAttributesCache.Read(); var mergeValues = Rock.Web.Cache.GlobalAttributesCache.GetMergeFields( null ); if ( person != null ) { mergeValues.Add( "Person", person ); var recipient = communication.Recipients.Where( r => r.PersonId == person.Id ).FirstOrDefault(); if ( recipient != null ) { // Add any additional merge fields created through a report foreach ( var mergeField in recipient.AdditionalMergeValues ) { if ( !mergeValues.ContainsKey( mergeField.Key ) ) { mergeValues.Add( mergeField.Key, mergeField.Value ); } } } } string message = communication.GetChannelDataValue( "Message" ); return message.ResolveMergeFields( mergeValues ); }
/// <summary> /// Execute method to write transaction to the database. /// </summary> public void Execute() { var communication = new CommunicationService( new RockContext() ).Get( CommunicationId ); if ( communication != null && communication.Status == CommunicationStatus.Approved ) { var channel = communication.Channel; if ( channel != null ) { channel.Send( communication ); } } }
/// <summary> /// Execute method to write transaction to the database. /// </summary> public void Execute() { using ( var rockContext = new RockContext() ) { var communication = new CommunicationService( rockContext ).Get( CommunicationId ); if ( communication != null && communication.Status == CommunicationStatus.Approved ) { var medium = communication.Medium; if ( medium != null ) { medium.Send( communication ); } } } }
private Dictionary <string, string> CreateCommunication() { var selectedMembers = Request.Form["selectedmembers"]; var selectedIds = new List <string>(); if (selectedMembers != null && !string.IsNullOrWhiteSpace(selectedMembers)) { selectedIds = selectedMembers.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList(); } else { mdAlert.Show("Please select members to communicate to.", ModalAlertType.Warning); return(new Dictionary <string, string>()); } var rockContext = new RockContext(); var service = new Rock.Model.CommunicationService(rockContext); var communication = new Rock.Model.Communication(); communication.IsBulkCommunication = false; communication.Status = Rock.Model.CommunicationStatus.Transient; communication.SenderPersonAliasId = this.CurrentPersonAliasId; service.Add(communication); var personAliasIds = new PersonAliasService(rockContext).Queryable().AsNoTracking() .Where(a => selectedIds.Contains(a.PersonId.ToString())) .GroupBy(a => a.PersonId) .Select(a => a.Min(m => m.Id)) .ToList(); // Get the primary aliases foreach (int personAlias in personAliasIds) { var recipient = new Rock.Model.CommunicationRecipient(); recipient.PersonAliasId = personAlias; communication.Recipients.Add(recipient); } rockContext.SaveChanges(); var queryParameters = new Dictionary <string, string>(); queryParameters.Add("CommunicationId", communication.Id.ToString()); return(queryParameters); }
/// <summary> /// Execute method to write transaction to the database. /// </summary> public void Execute() { var communication = new CommunicationService().Get( CommunicationId ); if ( communication != null && communication.Status == CommunicationStatus.Approved ) { var channel = communication.Channel; if ( channel != null ) { var transport = channel.Transport; if ( transport != null ) { transport.Send( communication, PersonId ); } } } }
/// <summary> /// Handles the Delete event of the gCommunication control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="Rock.Web.UI.Controls.RowEventArgs"/> instance containing the event data.</param> protected void gCommunication_Delete( object sender, Rock.Web.UI.Controls.RowEventArgs e ) { var rockContext = new RockContext(); var communicationService = new CommunicationService( rockContext ); var communication = communicationService.Get( e.RowKeyId ); if ( communication != null ) { string errorMessage; if ( !communicationService.CanDelete( communication, out errorMessage ) ) { mdGridWarning.Show( errorMessage, ModalAlertType.Information ); return; } communicationService.Delete( communication ); rockContext.SaveChanges(); } BindGrid(); }
/// <summary> /// Sends the specified communication. /// </summary> /// <param name="communication">The communication.</param> public static void Send(Rock.Model.Communication communication) { if (communication == null || communication.Status != CommunicationStatus.Approved) { return; } // only alter the Recipient list if it the communication hasn't sent a message to any recipients yet if (communication.SendDateTime.HasValue == false) { using (var rockContext = new RockContext()) { if (communication.ListGroupId.HasValue) { communication.RefreshCommunicationRecipientList(rockContext); } if (communication.ExcludeDuplicateRecipientAddress) { communication.RemoveRecipientsWithDuplicateAddress(rockContext); } communication.RemoveNonPrimaryPersonAliasRecipients(rockContext); } } foreach (var medium in communication.GetMediums()) { medium.Send(communication); } using (var rockContext = new RockContext()) { var dbCommunication = new CommunicationService(rockContext).Get(communication.Id); // Set the SendDateTime of the Communication dbCommunication.SendDateTime = RockDateTime.Now; rockContext.SaveChanges(); } }
/// <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 Communication"; int? commId = PageParameter( "CommunicationId" ).AsIntegerOrNull(); if ( commId.HasValue ) { var communication = new CommunicationService( new RockContext() ).Get( commId.Value ); if ( communication != null ) { RockPage.SaveSharedItem( "communication", communication ); switch ( communication.Status ) { case CommunicationStatus.Approved: case CommunicationStatus.Denied: case CommunicationStatus.PendingApproval: { pageTitle = string.Format( "Communication #{0}", communication.Id ); break; } default: { pageTitle = "New Communication"; break; } } } } breadCrumbs.Add( new BreadCrumb( pageTitle, pageReference ) ); RockPage.Title = pageTitle; return breadCrumbs; }
/// <summary> /// Sends the communication. /// </summary> private void SendCommunication() { // create communication if (this.CurrentPerson != null && _groupId != -1 && !string.IsNullOrWhiteSpace(GetAttributeValue("CommunicationPage"))) { var rockContext = new RockContext(); var service = new Rock.Model.CommunicationService(rockContext); var communication = new Rock.Model.Communication(); communication.IsBulkCommunication = false; communication.Status = Rock.Model.CommunicationStatus.Transient; communication.SenderPersonAliasId = this.CurrentPersonAliasId; service.Add(communication); var personAliasIds = new GroupMemberService(rockContext).Queryable() .Where(m => m.GroupId == _groupId && m.GroupMemberStatus != GroupMemberStatus.Inactive) .ToList() .Select(m => m.Person.PrimaryAliasId) .ToList(); // Get the primary aliases foreach (int personAlias in personAliasIds) { var recipient = new Rock.Model.CommunicationRecipient(); recipient.PersonAliasId = personAlias; communication.Recipients.Add(recipient); } rockContext.SaveChanges(); Dictionary <string, string> queryParameters = new Dictionary <string, string>(); queryParameters.Add("CommunicationId", communication.Id.ToString()); NavigateToLinkedPage("CommunicationPage", queryParameters); } }
/// <summary> /// Executes the specified context. /// </summary> /// <param name="context">The context.</param> public virtual void Execute( IJobExecutionContext context ) { JobDataMap dataMap = context.JobDetail.JobDataMap; var beginWindow = RockDateTime.Now.AddDays( 0 - dataMap.GetInt( "ExpirationPeriod" ) ); var endWindow = RockDateTime.Now.AddMinutes( 0 - dataMap.GetInt( "DelayPeriod" ) ); var qry = new CommunicationService( new RockContext() ).Queryable() .Where( c => c.Status == CommunicationStatus.Approved && c.Recipients.Where( r => r.Status == CommunicationRecipientStatus.Pending ).Any() && ( ( !c.FutureSendDateTime.HasValue && c.CreatedDateTime.HasValue && c.CreatedDateTime.Value.CompareTo( beginWindow ) >= 0 && c.CreatedDateTime.Value.CompareTo( endWindow ) <= 0 ) || ( c.FutureSendDateTime.HasValue && c.FutureSendDateTime.Value.CompareTo( beginWindow ) >= 0 && c.FutureSendDateTime.Value.CompareTo( endWindow ) <= 0 ) ) ); foreach ( var comm in qry.AsNoTracking().ToList() ) { var medium = comm.Medium; if ( medium != null ) { medium.Send( comm ); } } }
/// <summary> /// Updates a communication model with the user-entered values /// </summary> /// <param name="communicationService">The service.</param> /// <returns></returns> private Rock.Model.Communication UpdateCommunication(RockContext rockContext) { var communicationService = new CommunicationService(rockContext); var recipientService = new CommunicationRecipientService(rockContext); Rock.Model.Communication communication = null; if ( CommunicationId.HasValue ) { communication = communicationService.Get( CommunicationId.Value ); // Remove any deleted recipients foreach(var recipient in recipientService.GetByCommunicationId( CommunicationId.Value ) ) { if (!Recipients.Any( r => recipient.PersonAlias != null && r.PersonId == recipient.PersonAlias.PersonId)) { recipientService.Delete(recipient); communication.Recipients.Remove( recipient ); } } } if (communication == null) { communication = new Rock.Model.Communication(); communication.Status = CommunicationStatus.Transient; communication.SenderPersonAliasId = CurrentPersonAliasId; communicationService.Add( communication ); } // Add any new recipients foreach(var recipient in Recipients ) { if ( !communication.Recipients.Any( r => r.PersonAlias != null && r.PersonAlias.PersonId == recipient.PersonId ) ) { var person = new PersonService( rockContext ).Get( recipient.PersonId ); if ( person != null ) { var communicationRecipient = new CommunicationRecipient(); communicationRecipient.PersonAlias = person.PrimaryAlias; communication.Recipients.Add( communicationRecipient ); } } } communication.IsBulkCommunication = cbBulk.Checked; communication.MediumEntityTypeId = MediumEntityTypeId; communication.MediumData.Clear(); GetMediumData(); foreach ( var keyVal in MediumData ) { if ( !string.IsNullOrEmpty( keyVal.Value ) ) { communication.MediumData.Add( keyVal.Key, keyVal.Value ); } } if ( communication.MediumData.ContainsKey( "Subject" ) ) { communication.Subject = communication.MediumData["Subject"]; communication.MediumData.Remove( "Subject" ); } DateTime? futureSendDate = dtpFutureSend.SelectedDateTime; if ( futureSendDate.HasValue && futureSendDate.Value.CompareTo( RockDateTime.Now ) > 0 ) { communication.FutureSendDateTime = futureSendDate; } else { communication.FutureSendDateTime = null; } return communication; }
/// <summary> /// Sends the communication. /// </summary> private void SendCommunication() { // create communication if ( this.CurrentPerson != null && _groupId != -1 && !string.IsNullOrWhiteSpace( GetAttributeValue( "CommunicationPage" ) ) ) { var rockContext = new RockContext(); var service = new Rock.Model.CommunicationService( rockContext ); var communication = new Rock.Model.Communication(); communication.IsBulkCommunication = false; communication.Status = Rock.Model.CommunicationStatus.Transient; communication.SenderPersonAliasId = this.CurrentPersonAliasId; service.Add( communication ); var personAliasIds = new GroupMemberService( rockContext ).Queryable() .Where( m => m.GroupId == _groupId && m.GroupMemberStatus != GroupMemberStatus.Inactive ) .ToList() .Select( m => m.Person.PrimaryAliasId ) .ToList(); // Get the primary aliases foreach ( int personAlias in personAliasIds ) { var recipient = new Rock.Model.CommunicationRecipient(); recipient.PersonAliasId = personAlias; communication.Recipients.Add( recipient ); } rockContext.SaveChanges(); Dictionary<string, string> queryParameters = new Dictionary<string, string>(); queryParameters.Add( "CommunicationId", communication.Id.ToString() ); NavigateToLinkedPage( "CommunicationPage", queryParameters ); } }
/// <summary> /// Sends the specified communication. /// </summary> /// <param name="communication">The communication.</param> public async static Task SendAsync(Rock.Model.Communication communication) { if (communication == null || communication.Status != CommunicationStatus.Approved) { return; } // only alter the Recipient list if it the communication hasn't sent a message to any recipients yet if (communication.SendDateTime.HasValue == false) { using (var rockContext = new RockContext()) { if (communication.ListGroupId.HasValue) { communication.RefreshCommunicationRecipientList(rockContext); } if (communication.ExcludeDuplicateRecipientAddress) { communication.RemoveRecipientsWithDuplicateAddress(rockContext); } communication.RemoveNonPrimaryPersonAliasRecipients(rockContext); } } var sendTasks = new List <Task>(); foreach (var medium in communication.GetMediums()) { var asyncMedium = medium as IAsyncMediumComponent; if (asyncMedium == null) { sendTasks.Add(Task.Run(() => medium.Send(communication))); } else { sendTasks.Add(asyncMedium.SendAsync(communication)); } } var aggregateExceptions = new List <Exception>(); while (sendTasks.Count > 0) { var completedTask = await Task.WhenAny(sendTasks).ConfigureAwait(false); if (completedTask.Exception != null) { aggregateExceptions.AddRange(completedTask.Exception.InnerExceptions); } sendTasks.Remove(completedTask); } if (aggregateExceptions.Count > 0) { throw new AggregateException(aggregateExceptions); } using (var rockContext = new RockContext()) { var dbCommunication = new CommunicationService(rockContext).Get(communication.Id); // Set the SendDateTime of the Communication dbCommunication.SendDateTime = RockDateTime.Now; rockContext.SaveChanges(); } }
/// <summary> /// Handles the Click event of the btnCopy 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 btnCopy_Click( object sender, EventArgs e ) { if ( Page.IsValid && CommunicationId.HasValue ) { var rockContext = new RockContext(); var service = new CommunicationService( rockContext ); var communication = service.Get( CommunicationId.Value ); if ( communication != null ) { var newCommunication = communication.Clone( false ); newCommunication.CreatedByPersonAlias = null; newCommunication.CreatedByPersonAliasId = null; newCommunication.CreatedDateTime = RockDateTime.Now; newCommunication.ModifiedByPersonAlias = null; newCommunication.ModifiedByPersonAliasId = null; newCommunication.ModifiedDateTime = RockDateTime.Now; newCommunication.Id = 0; newCommunication.Guid = Guid.Empty; newCommunication.SenderPersonAliasId = CurrentPersonAliasId; newCommunication.Status = CommunicationStatus.Draft; newCommunication.ReviewerPersonAliasId = null; newCommunication.ReviewedDateTime = null; newCommunication.ReviewerNote = string.Empty; communication.Recipients.ToList().ForEach( r => newCommunication.Recipients.Add( new CommunicationRecipient() { PersonAliasId = r.PersonAliasId, Status = CommunicationRecipientStatus.Pending, StatusNote = string.Empty, AdditionalMergeValuesJson = r.AdditionalMergeValuesJson } ) ); service.Add( newCommunication ); rockContext.SaveChanges(); // Redirect to new communication if ( CurrentPageReference.Parameters.ContainsKey( "CommunicationId" ) ) { CurrentPageReference.Parameters["CommunicationId"] = newCommunication.Id.ToString(); } else { CurrentPageReference.Parameters.Add( "CommunicationId", newCommunication.Id.ToString() ); } Response.Redirect( CurrentPageReference.BuildUrl() ); Context.ApplicationInstance.CompleteRequest(); } } }
/// <summary> /// Copies the specified communication identifier. /// </summary> /// <param name="communicationId">The communication identifier.</param> /// <param name="currentPersonAliasId">The current person alias identifier.</param> /// <returns></returns> public Communication Copy(int communicationId, int?currentPersonAliasId) { var dataContext = ( RockContext )Context; var service = new CommunicationService(dataContext); var communicationRecipientService = new CommunicationRecipientService(dataContext); var communication = service.Get(communicationId); if (communication != null) { var newCommunication = communication.Clone(false); newCommunication.CreatedByPersonAlias = null; newCommunication.CreatedByPersonAliasId = null; newCommunication.CreatedDateTime = RockDateTime.Now; newCommunication.ModifiedByPersonAlias = null; newCommunication.ModifiedByPersonAliasId = null; newCommunication.ModifiedDateTime = RockDateTime.Now; newCommunication.Id = 0; newCommunication.Guid = Guid.Empty; newCommunication.SenderPersonAliasId = currentPersonAliasId; newCommunication.Status = CommunicationStatus.Draft; newCommunication.ReviewerPersonAliasId = null; newCommunication.ReviewedDateTime = null; newCommunication.ReviewerNote = string.Empty; newCommunication.SendDateTime = null; // Get the recipients from the original communication, // but only for recipients that are using the person's primary alias id. // This will avoid an issue where a copied communication will include the same person multiple times // if they have been merged since the original communication was created var primaryAliasRecipients = communicationRecipientService.Queryable() .Where(a => a.CommunicationId == communication.Id) .Select(a => new { a.PersonAlias.Person, a.AdditionalMergeValuesJson, a.PersonAliasId }).ToList() .GroupBy(a => a.Person.PrimaryAliasId) .Select(s => new { PersonAliasId = s.Key, AdditionalMergeValuesJson = s.Where(a => a.PersonAliasId == s.Key).Select(x => x.AdditionalMergeValuesJson).FirstOrDefault() }) .Where(s => s.PersonAliasId.HasValue) .ToList(); foreach (var primaryAliasRecipient in primaryAliasRecipients) { newCommunication.Recipients.Add(new CommunicationRecipient() { PersonAliasId = primaryAliasRecipient.PersonAliasId.Value, Status = CommunicationRecipientStatus.Pending, StatusNote = string.Empty, AdditionalMergeValuesJson = primaryAliasRecipient.AdditionalMergeValuesJson }); } foreach (var attachment in communication.Attachments.ToList()) { var newAttachment = new CommunicationAttachment(); newAttachment.BinaryFileId = attachment.BinaryFileId; newAttachment.CommunicationType = attachment.CommunicationType; newCommunication.Attachments.Add(newAttachment); } return(newCommunication); } return(null); }
/// <summary> /// Handles the Delete event of the gCommunication control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="Rock.Web.UI.Controls.RowEventArgs"/> instance containing the event data.</param> protected void gCommunication_Delete( object sender, Rock.Web.UI.Controls.RowEventArgs e ) { RockTransactionScope.WrapTransaction( () => { var communicationService = new CommunicationService(); var communication = communicationService.Get( e.RowKeyId ); if ( communication != null ) { string errorMessage; if ( !communicationService.CanDelete( communication, out errorMessage ) ) { mdGridWarning.Show( errorMessage, ModalAlertType.Information ); return; } communicationService.Delete( communication, CurrentPersonId ); communicationService.Save( communication, CurrentPersonId ); } } ); BindGrid(); }
/// <summary> /// Handles the Click event of the btnSubmit 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 btnTest_Click( object sender, EventArgs e ) { if ( Page.IsValid && CurrentPersonAliasId.HasValue ) { // Get existing or new communication record var rockContext = new RockContext(); var communication = UpdateCommunication( rockContext ); if ( communication != null ) { // Using a new context (so that changes in the UpdateCommunication() are not persisted ) var testCommunication = new Rock.Model.Communication(); testCommunication.SenderPersonAliasId = communication.SenderPersonAliasId; testCommunication.Subject = communication.Subject; testCommunication.IsBulkCommunication = communication.IsBulkCommunication; testCommunication.MediumEntityTypeId = communication.MediumEntityTypeId; testCommunication.MediumDataJson = communication.MediumDataJson; testCommunication.AdditionalMergeFieldsJson = communication.AdditionalMergeFieldsJson; testCommunication.FutureSendDateTime = null; testCommunication.Status = CommunicationStatus.Approved; testCommunication.ReviewedDateTime = RockDateTime.Now; testCommunication.ReviewerPersonAliasId = CurrentPersonAliasId; var testRecipient = new CommunicationRecipient(); if ( communication.GetRecipientCount( rockContext ) > 0 ) { var recipient = communication.GetRecipientsQry(rockContext).FirstOrDefault(); testRecipient.AdditionalMergeValuesJson = recipient.AdditionalMergeValuesJson; } testRecipient.Status = CommunicationRecipientStatus.Pending; testRecipient.PersonAliasId = CurrentPersonAliasId.Value; testCommunication.Recipients.Add( testRecipient ); var communicationService = new CommunicationService( rockContext ); communicationService.Add( testCommunication ); rockContext.SaveChanges(); var medium = testCommunication.Medium; if ( medium != null ) { medium.Send( testCommunication ); } communicationService.Delete( testCommunication ); rockContext.SaveChanges(); nbTestResult.Visible = true; } } }
/// <summary> /// Sends the specified communication. /// </summary> /// <param name="communication">The communication.</param> /// <exception cref="System.NotImplementedException"></exception> public override void Send( Rock.Model.Communication communication ) { using ( var rockContext = new RockContext() ) { // Requery the Communication object communication = new CommunicationService( rockContext ) .Queryable( "CreatedByPersonAlias.Person" ) .FirstOrDefault( c => c.Id == communication.Id ); if ( communication != null && communication.Status == Model.CommunicationStatus.Approved && communication.Recipients.Where( r => r.Status == Model.CommunicationRecipientStatus.Pending ).Any() && ( !communication.FutureSendDateTime.HasValue || communication.FutureSendDateTime.Value.CompareTo( RockDateTime.Now ) <= 0 ) ) { var currentPerson = communication.CreatedByPersonAlias.Person; var globalAttributes = Rock.Web.Cache.GlobalAttributesCache.Read(); var globalConfigValues = Rock.Web.Cache.GlobalAttributesCache.GetMergeFields( currentPerson ); // From - if none is set, use the one in the Organization's GlobalAttributes. string fromAddress = communication.GetMediumDataValue( "FromAddress" ); if ( string.IsNullOrWhiteSpace( fromAddress ) ) { fromAddress = globalAttributes.GetValue( "OrganizationEmail" ); } string fromName = communication.GetMediumDataValue( "FromName" ); if ( string.IsNullOrWhiteSpace( fromName ) ) { fromName = globalAttributes.GetValue( "OrganizationName" ); } // Resolve any possible merge fields in the from address fromAddress = fromAddress.ResolveMergeFields( globalConfigValues, currentPerson ); fromName = fromName.ResolveMergeFields( globalConfigValues, currentPerson ); MailMessage message = new MailMessage(); message.From = new MailAddress( fromAddress, fromName ); // Reply To string replyTo = communication.GetMediumDataValue( "ReplyTo" ); if ( !string.IsNullOrWhiteSpace( replyTo ) ) { message.ReplyToList.Add( new MailAddress( replyTo ) ); } CheckSafeSender( message, globalAttributes ); // CC string cc = communication.GetMediumDataValue( "CC" ); if ( !string.IsNullOrWhiteSpace( cc ) ) { foreach ( string ccRecipient in cc.SplitDelimitedValues() ) { message.CC.Add( new MailAddress( ccRecipient ) ); } } // BCC string bcc = communication.GetMediumDataValue( "BCC" ); if ( !string.IsNullOrWhiteSpace( bcc ) ) { foreach ( string bccRecipient in bcc.SplitDelimitedValues() ) { message.Bcc.Add( new MailAddress( bccRecipient ) ); } } message.IsBodyHtml = true; message.Priority = MailPriority.Normal; using ( var smtpClient = GetSmtpClient() ) { // Add Attachments string attachmentIds = communication.GetMediumDataValue( "Attachments" ); if ( !string.IsNullOrWhiteSpace( attachmentIds ) ) { var binaryFileService = new BinaryFileService( rockContext ); foreach ( string idVal in attachmentIds.SplitDelimitedValues() ) { int binaryFileId = int.MinValue; if ( int.TryParse( idVal, out binaryFileId ) ) { var binaryFile = binaryFileService.Get( binaryFileId ); if ( binaryFile != null ) { message.Attachments.Add( new Attachment( binaryFile.ContentStream, binaryFile.FileName ) ); } } } } var historyService = new HistoryService( rockContext ); var recipientService = new CommunicationRecipientService( rockContext ); var personEntityTypeId = EntityTypeCache.Read( "Rock.Model.Person" ).Id; var communicationEntityTypeId = EntityTypeCache.Read( "Rock.Model.Communication" ).Id; var communicationCategoryId = CategoryCache.Read( Rock.SystemGuid.Category.HISTORY_PERSON_COMMUNICATIONS.AsGuid(), rockContext ).Id; bool recipientFound = true; while ( recipientFound ) { var recipient = Rock.Model.Communication.GetNextPending( communication.Id, rockContext ); if ( recipient != null ) { if ( string.IsNullOrWhiteSpace( recipient.PersonAlias.Person.Email ) ) { recipient.Status = CommunicationRecipientStatus.Failed; recipient.StatusNote = "No Email Address"; } else { try { message.To.Clear(); message.Headers.Clear(); message.AlternateViews.Clear(); message.To.Add( new MailAddress( recipient.PersonAlias.Person.Email, recipient.PersonAlias.Person.FullName ) ); // Create merge field dictionary var mergeObjects = recipient.CommunicationMergeValues( globalConfigValues ); // Subject message.Subject = communication.Subject.ResolveMergeFields( mergeObjects, currentPerson ); // convert any special microsoft word characters to normal chars so they don't look funny (for example "Hey “double-quotes†from ‘single quote’") message.Subject = message.Subject.ReplaceWordChars(); // Add any additional headers that specific SMTP provider needs AddAdditionalHeaders( message, recipient ); // Add text view first as last view is usually treated as the preferred view by email readers (gmail) string plainTextBody = Rock.Communication.Medium.Email.ProcessTextBody( communication, globalAttributes, mergeObjects, currentPerson ); // convert any special microsoft word characters to normal chars so they don't look funny plainTextBody = plainTextBody.ReplaceWordChars(); if ( !string.IsNullOrWhiteSpace( plainTextBody ) ) { AlternateView plainTextView = AlternateView.CreateAlternateViewFromString( plainTextBody, new System.Net.Mime.ContentType( MediaTypeNames.Text.Plain ) ); message.AlternateViews.Add( plainTextView ); } // Add Html view string htmlBody = Rock.Communication.Medium.Email.ProcessHtmlBody( communication, globalAttributes, mergeObjects, currentPerson ); // convert any special microsoft word characters to normal chars so they don't look funny htmlBody = htmlBody.ReplaceWordChars(); if ( !string.IsNullOrWhiteSpace( htmlBody ) ) { AlternateView htmlView = AlternateView.CreateAlternateViewFromString( htmlBody, new System.Net.Mime.ContentType( MediaTypeNames.Text.Html ) ); message.AlternateViews.Add( htmlView ); } smtpClient.Send( message ); recipient.Status = CommunicationRecipientStatus.Delivered; string statusNote = StatusNote; if ( !string.IsNullOrWhiteSpace( statusNote ) ) { recipient.StatusNote = statusNote; } recipient.TransportEntityTypeName = this.GetType().FullName; historyService.Add( new History { CreatedByPersonAliasId = communication.SenderPersonAliasId, EntityTypeId = personEntityTypeId, CategoryId = communicationCategoryId, EntityId = recipient.PersonAlias.PersonId, Summary = string.Format( "Sent communication from <span class='field-value'>{0}</span>.", message.From.DisplayName ), Caption = message.Subject, RelatedEntityTypeId = communicationEntityTypeId, RelatedEntityId = communication.Id } ); } catch ( Exception ex ) { recipient.Status = CommunicationRecipientStatus.Failed; recipient.StatusNote = "Exception: " + ex.Message; } } rockContext.SaveChanges(); } else { recipientFound = false; } } } } } }
/// <summary> /// Deletes the family's addresses, phone numbers, photos, viewed records, and people. /// TODO: delete attendance codes for attendance data that's about to be deleted when /// we delete the person record. /// </summary> /// <param name="families">The families.</param> /// <param name="rockContext">The rock context.</param> private void DeleteExistingFamilyData( XElement families, RockContext rockContext ) { PersonService personService = new PersonService( rockContext ); PhoneNumberService phoneNumberService = new PhoneNumberService( rockContext ); PersonViewedService personViewedService = new PersonViewedService( rockContext ); PageViewService pageViewService = new PageViewService( rockContext ); BinaryFileService binaryFileService = new BinaryFileService( rockContext ); PersonAliasService personAliasService = new PersonAliasService( rockContext ); PersonDuplicateService personDuplicateService = new PersonDuplicateService( rockContext ); NoteService noteService = new NoteService( rockContext ); AuthService authService = new AuthService( rockContext ); CommunicationService communicationService = new CommunicationService( rockContext ); CommunicationRecipientService communicationRecipientService = new CommunicationRecipientService( rockContext ); FinancialBatchService financialBatchService = new FinancialBatchService( rockContext ); FinancialTransactionService financialTransactionService = new FinancialTransactionService( rockContext ); PersonPreviousNameService personPreviousNameService = new PersonPreviousNameService( rockContext ); ConnectionRequestService connectionRequestService = new ConnectionRequestService( rockContext ); ConnectionRequestActivityService connectionRequestActivityService = new ConnectionRequestActivityService( rockContext ); // delete the batch data List<int> imageIds = new List<int>(); foreach ( var batch in financialBatchService.Queryable().Where( b => b.Name.StartsWith( "SampleData" ) ) ) { imageIds.AddRange( batch.Transactions.SelectMany( t => t.Images ).Select( i => i.BinaryFileId ).ToList() ); financialTransactionService.DeleteRange( batch.Transactions ); financialBatchService.Delete( batch ); } // delete all transaction images foreach ( var image in binaryFileService.GetByIds( imageIds ) ) { binaryFileService.Delete( image ); } foreach ( var elemFamily in families.Elements( "family" ) ) { Guid guid = elemFamily.Attribute( "guid" ).Value.Trim().AsGuid(); GroupService groupService = new GroupService( rockContext ); Group family = groupService.Get( guid ); if ( family != null ) { var groupMemberService = new GroupMemberService( rockContext ); var members = groupMemberService.GetByGroupId( family.Id, true ); // delete the people records string errorMessage; List<int> photoIds = members.Select( m => m.Person ).Where( p => p.PhotoId != null ).Select( a => (int)a.PhotoId ).ToList(); foreach ( var person in members.Select( m => m.Person ) ) { person.GivingGroup = null; person.GivingGroupId = null; person.PhotoId = null; // delete phone numbers foreach ( var phone in phoneNumberService.GetByPersonId( person.Id ) ) { if ( phone != null ) { phoneNumberService.Delete( phone ); } } // delete communication recipient foreach ( var recipient in communicationRecipientService.Queryable().Where( r => r.PersonAlias.PersonId == person.Id ) ) { communicationRecipientService.Delete( recipient ); } // delete communication foreach ( var communication in communicationService.Queryable().Where( c => c.SenderPersonAliasId == person.PrimaryAlias.Id ) ) { communicationService.Delete( communication ); } // delete person viewed records foreach ( var view in personViewedService.GetByTargetPersonId( person.Id ) ) { personViewedService.Delete( view ); } // delete page viewed records foreach ( var view in pageViewService.GetByPersonId( person.Id ) ) { pageViewService.Delete( view ); } // delete notes created by them or on their record. foreach ( var note in noteService.Queryable().Where ( n => n.CreatedByPersonAlias.PersonId == person.Id || (n.NoteType.EntityTypeId == _personEntityTypeId && n.EntityId == person.Id ) ) ) { noteService.Delete( note ); } // delete previous names on their records foreach ( var previousName in personPreviousNameService.Queryable().Where( r => r.PersonAlias.PersonId == person.Id ) ) { personPreviousNameService.Delete( previousName ); } // delete any GroupMember records they have foreach ( var groupMember in groupMemberService.Queryable().Where( gm => gm.PersonId == person.Id ) ) { groupMemberService.Delete( groupMember ); } //// delete any Authorization data //foreach ( var auth in authService.Queryable().Where( a => a.PersonId == person.Id ) ) //{ // authService.Delete( auth ); //} // delete their aliases foreach ( var alias in personAliasService.Queryable().Where( a => a.PersonId == person.Id ) ) { foreach ( var duplicate in personDuplicateService.Queryable().Where( d => d.DuplicatePersonAliasId == alias.Id ) ) { personDuplicateService.Delete( duplicate ); } personAliasService.Delete( alias ); } // delete any connection requests tied to them foreach ( var request in connectionRequestService.Queryable().Where( r => r.PersonAlias.PersonId == person.Id || r.ConnectorPersonAlias.PersonId == person.Id ) ) { connectionRequestActivityService.DeleteRange( request.ConnectionRequestActivities ); connectionRequestService.Delete( request ); } // Save these changes so the CanDelete passes the check... //rockContext.ChangeTracker.DetectChanges(); rockContext.SaveChanges( disablePrePostProcessing: true ); if ( personService.CanDelete( person, out errorMessage ) ) { personService.Delete( person ); //rockContext.ChangeTracker.DetectChanges(); //rockContext.SaveChanges( disablePrePostProcessing: true ); } else { throw new Exception( string.Format( "Trying to delete {0}, but: {1}", person.FullName, errorMessage ) ); } } //rockContext.ChangeTracker.DetectChanges(); rockContext.SaveChanges( disablePrePostProcessing: true ); // delete all member photos foreach ( var photo in binaryFileService.GetByIds( photoIds ) ) { binaryFileService.Delete( photo ); } DeleteGroupAndMemberData( family, rockContext ); } } }
protected void btnEdit_Click( object sender, EventArgs e ) { var rockContext = new RockContext(); var service = new CommunicationService( rockContext ); var communication = service.Get( CommunicationId.Value ); if ( communication != null && communication.Status == CommunicationStatus.PendingApproval && IsUserAuthorized( "Approve" ) ) { // Redirect back to same page without the edit param var pageRef = CurrentPageReference; pageRef.Parameters.Add( "edit", "true" ); Response.Redirect( pageRef.BuildUrl() ); Context.ApplicationInstance.CompleteRequest(); } }
/// <summary> /// Binds the grid. /// </summary> private void BindGrid() { // If configured for a person and person is null, return int personEntityTypeId = EntityTypeCache.Read<Person>().Id; if ( ContextTypesRequired.Any( e => e.Id == personEntityTypeId ) && _person == null ) { return; } var rockContext = new RockContext(); var qryCommunications = new CommunicationService( rockContext ).Queryable().Where( c => c.Status != CommunicationStatus.Transient ); string subject = tbSubject.Text; if ( !string.IsNullOrWhiteSpace( subject ) ) { qryCommunications = qryCommunications.Where( c => c.Subject.Contains( subject ) ); } Guid? entityTypeGuid = cpMedium.SelectedValue.AsGuidOrNull(); if ( entityTypeGuid.HasValue ) { qryCommunications = qryCommunications.Where( c => c.MediumEntityType != null && c.MediumEntityType.Guid.Equals( entityTypeGuid.Value ) ); } var communicationStatus = ddlStatus.SelectedValue.ConvertToEnumOrNull<CommunicationStatus>(); if ( communicationStatus.HasValue ) { qryCommunications = qryCommunications.Where( c => c.Status == communicationStatus.Value ); } // only communications for the selected recipient (_person) if ( _person != null ) { qryCommunications = qryCommunications .Where( c => c.Recipients.Any( a => a.PersonAlias.PersonId == _person.Id && a.Status == CommunicationRecipientStatus.Delivered ) ); } if ( drpDates.LowerValue.HasValue ) { qryCommunications = qryCommunications.Where( a => a.CreatedDateTime >= drpDates.LowerValue.Value ); } if ( drpDates.UpperValue.HasValue ) { DateTime upperDate = drpDates.UpperValue.Value.Date.AddDays( 1 ); qryCommunications = qryCommunications.Where( a => a.CreatedDateTime < upperDate ); } string content = tbContent.Text; if ( !string.IsNullOrWhiteSpace( content ) ) { qryCommunications = qryCommunications.Where( c => c.MediumDataJson.Contains( content ) ); } var sortProperty = gCommunication.SortProperty; if ( sortProperty != null ) { qryCommunications = qryCommunications.Sort( sortProperty ); } else { qryCommunications = qryCommunications.OrderByDescending( c => c.CreatedDateTime ); } gCommunication.EntityTypeId = EntityTypeCache.Read<Rock.Model.Communication>().Id; gCommunication.SetLinqDataSource( qryCommunications.Include(a => a.MediumEntityType).AsNoTracking() ); gCommunication.DataBind(); }
/// <summary> /// Sends the specified communication. /// </summary> /// <param name="communication">The communication.</param> /// <exception cref="System.NotImplementedException"></exception> public override void Send( Rock.Model.Communication communication ) { using ( var rockContext = new RockContext() ) { // Requery the Communication communication = new CommunicationService( rockContext ).Get( communication.Id ); if ( communication != null && communication.Status == CommunicationStatus.Approved && communication.Recipients.Any(r => r.Status == CommunicationRecipientStatus.Pending) && ( !communication.FutureSendDateTime.HasValue || communication.FutureSendDateTime.Value.CompareTo( RockDateTime.Now ) <= 0 ) ) { // Remove all non alpha numeric from fromValue string fromValue = communication.GetMediumDataValue( "NoReply_FromValue" ); //Ensure that the fromValue is correct fromValue = new string( fromValue.ToCharArray().Where( c => char.IsLetterOrDigit( c ) || char.IsWhiteSpace( c ) ).Take( 11 ).ToArray() ) ; string senderGuid = communication.GetMediumDataValue( "SenderGuid" ); if ( !string.IsNullOrWhiteSpace( fromValue ) && !string.IsNullOrWhiteSpace( senderGuid ) ) { string accountSid = GetAttributeValue( "SID" ); string authToken = GetAttributeValue( "Token" ); if (string.IsNullOrWhiteSpace(accountSid) || string.IsNullOrWhiteSpace(authToken)) { throw new Exception("Either SID or Token not provided"); } var twilio = new TwilioRestClient( accountSid, authToken ); var historyService = new HistoryService( rockContext ); int personEntityTypeId = EntityTypeCache.Read( "Rock.Model.Person" ).Id; int communicationEntityTypeId = EntityTypeCache.Read( "Rock.Model.Communication" ).Id; int communicationCategoryId = CategoryCache.Read( Rock.SystemGuid.Category.HISTORY_PERSON_COMMUNICATIONS.AsGuid(), rockContext ).Id; var sender = new PersonService( rockContext ).Get( senderGuid.AsGuid() ); var mergeFields = GlobalAttributesCache.GetMergeFields( null ); if ( sender != null ) { mergeFields.Add( "Sender", sender ); } bool recipientFound = true; while ( recipientFound ) { var recipient = Rock.Model.Communication.GetNextPending( communication.Id, rockContext ); if ( recipient != null ) { try { var phoneNumber = recipient.PersonAlias.Person.PhoneNumbers .FirstOrDefault(p => p.IsMessagingEnabled); if ( phoneNumber != null ) { // Create merge field dictionary var mergeObjects = recipient.CommunicationMergeValues( mergeFields ); string message = communication.GetMediumDataValue( "NoReply_Message" ); string footer = GetAttributeValue( "footer" ); if ( communication.GetMediumDataValue( "NoReply_AppendUserInfo" ).AsBoolean() && !string.IsNullOrEmpty( footer ) ) { message += "\n " + footer; } else { message += "\n This message was sent on behalf of {{ GlobalAttribute.OrganizationName }} from a no reply number."; } message = message.ReplaceWordChars(); message = message.ResolveMergeFields( mergeObjects ); string twilioNumber = phoneNumber.Number; if ( !string.IsNullOrWhiteSpace( phoneNumber.CountryCode ) ) { twilioNumber = "+" + phoneNumber.CountryCode + phoneNumber.Number; } var globalAttributes = GlobalAttributesCache.Read(); if (globalAttributes == null) { throw new Exception("Error getting Global Attributes"); } string callbackUrl = globalAttributes.GetValue( "PublicApplicationRoot" ) + "Webhooks/Twilio.ashx"; var response = twilio.SendMessage( fromValue, twilioNumber, message, callbackUrl ); if (response != null) { recipient.Status = GetCommunicationRecipientStatus(response); recipient.TransportEntityTypeName = GetType().FullName; recipient.UniqueMessageId = response.Sid; try { historyService.Add(new History { CreatedByPersonAliasId = communication.SenderPersonAliasId, EntityTypeId = personEntityTypeId, CategoryId = communicationCategoryId, EntityId = recipient.PersonAlias.PersonId, Summary = "Sent an alphanumeric SMS message from " + fromValue + ".", Caption = message.Truncate(200), RelatedEntityTypeId = communicationEntityTypeId, RelatedEntityId = communication.Id }); } catch (Exception ex) { ExceptionLogService.LogException(ex, null); } } else { recipient.Status = CommunicationRecipientStatus.Failed; recipient.StatusNote = "No response from Twilio"; } } else { recipient.Status = CommunicationRecipientStatus.Failed; recipient.StatusNote = "No phone number with messaging enabled"; } } catch ( Exception ex ) { recipient.Status = CommunicationRecipientStatus.Failed; recipient.StatusNote = "Twilio Exception: " + ex.Message; ExceptionLogService.LogException( ex, null ); } rockContext.SaveChanges(); } else { recipientFound = false; } } } } } }
/// <summary> /// Sends the specified communication. /// </summary> /// <param name="communication">The communication.</param> /// <exception cref="System.NotImplementedException"></exception> public override void Send( Rock.Model.Communication communication ) { var rockContext = new RockContext(); // Requery the Communication communication = new CommunicationService( rockContext ).Get( communication.Id ); if ( communication != null && communication.Status == Model.CommunicationStatus.Approved && communication.Recipients.Where( r => r.Status == Model.CommunicationRecipientStatus.Pending ).Any() && ( !communication.FutureSendDateTime.HasValue || communication.FutureSendDateTime.Value.CompareTo( RockDateTime.Now ) <= 0 ) ) { string fromPhone = string.Empty; string fromValue = communication.GetMediumDataValue( "FromValue" ); int fromValueId = int.MinValue; if ( int.TryParse( fromValue, out fromValueId ) ) { fromPhone = DefinedValueCache.Read( fromValueId, rockContext ).Value; } if ( !string.IsNullOrWhiteSpace( fromPhone ) ) { string accountSid = GetAttributeValue( "SID" ); string authToken = GetAttributeValue( "Token" ); var twilio = new TwilioRestClient( accountSid, authToken ); var historyService = new HistoryService( rockContext ); var recipientService = new CommunicationRecipientService( rockContext ); var personEntityTypeId = EntityTypeCache.Read( "Rock.Model.Person" ).Id; var communicationEntityTypeId = EntityTypeCache.Read( "Rock.Model.Communication" ).Id; var communicationCategoryId = CategoryCache.Read( Rock.SystemGuid.Category.HISTORY_PERSON_COMMUNICATIONS.AsGuid(), rockContext ).Id; var globalConfigValues = GlobalAttributesCache.GetMergeFields( null ); bool recipientFound = true; while ( recipientFound ) { var recipient = recipientService.Get( communication.Id, CommunicationRecipientStatus.Pending ).FirstOrDefault(); if ( recipient != null ) { try { var phoneNumber = recipient.PersonAlias.Person.PhoneNumbers .Where( p => p.IsMessagingEnabled ) .FirstOrDefault(); if ( phoneNumber != null ) { // Create merge field dictionary var mergeObjects = recipient.CommunicationMergeValues( globalConfigValues ); string message = communication.GetMediumDataValue( "Message" ); message = message.ResolveMergeFields( mergeObjects ); string twilioNumber = phoneNumber.Number; if ( !string.IsNullOrWhiteSpace( phoneNumber.CountryCode ) ) { twilioNumber = "+" + phoneNumber.CountryCode + phoneNumber.Number; } var globalAttributes = Rock.Web.Cache.GlobalAttributesCache.Read(); string callbackUrl = globalAttributes.GetValue( "PublicApplicationRoot" ) + "Webhooks/Twilio.ashx"; var response = twilio.SendMessage( fromPhone, twilioNumber, message, callbackUrl ); recipient.Status = CommunicationRecipientStatus.Delivered; recipient.TransportEntityTypeName = this.GetType().FullName; recipient.UniqueMessageId = response.Sid; try { historyService.Add( new History { CreatedByPersonAliasId = communication.SenderPersonAliasId, EntityTypeId = personEntityTypeId, CategoryId = communicationCategoryId, EntityId = recipient.PersonAlias.PersonId, Summary = "Sent SMS message.", Caption = message.Truncate( 200 ), RelatedEntityTypeId = communicationEntityTypeId, RelatedEntityId = communication.Id } ); } catch (Exception ex) { ExceptionLogService.LogException( ex, null ); } } else { recipient.Status = CommunicationRecipientStatus.Failed; recipient.StatusNote = "No Phone Number with Messaging Enabled"; } } catch ( Exception ex ) { recipient.Status = CommunicationRecipientStatus.Failed; recipient.StatusNote = "Twilio Exception: " + ex.Message; } rockContext.SaveChanges(); } else { recipientFound = false; } } } } }
/// <summary> /// Updates a communication model with the user-entered values /// </summary> /// <param name="communicationService">The service.</param> /// <returns></returns> private Rock.Model.Communication UpdateCommunication(RockContext rockContext) { var communicationService = new CommunicationService(rockContext); var recipientService = new CommunicationRecipientService(rockContext); Rock.Model.Communication communication = null; IQueryable<CommunicationRecipient> qryRecipients = null; if ( CommunicationId.HasValue ) { communication = communicationService.Get( CommunicationId.Value ); } if ( communication != null ) { // Remove any deleted recipients HashSet<int> personIdHash = new HashSet<int>( Recipients.Select( a => a.PersonId ) ); qryRecipients = communication.GetRecipientsQry( rockContext ); foreach ( var item in qryRecipients.Select( a => new { Id = a.Id, PersonId = a.PersonAlias.PersonId }) ) { if ( !personIdHash.Contains(item.PersonId) ) { var recipient = qryRecipients.Where( a => a.Id == item.Id ).FirstOrDefault(); recipientService.Delete( recipient ); communication.Recipients.Remove( recipient ); } } } if (communication == null) { communication = new Rock.Model.Communication(); communication.Status = CommunicationStatus.Transient; communication.SenderPersonAliasId = CurrentPersonAliasId; communicationService.Add( communication ); } if (qryRecipients == null) { qryRecipients = communication.GetRecipientsQry( rockContext ); } // Add any new recipients HashSet<int> communicationPersonIdHash = new HashSet<int>( qryRecipients.Select( a => a.PersonAlias.PersonId ) ); foreach(var recipient in Recipients ) { if ( !communicationPersonIdHash.Contains( recipient.PersonId ) ) { var person = new PersonService( rockContext ).Get( recipient.PersonId ); if ( person != null ) { var communicationRecipient = new CommunicationRecipient(); communicationRecipient.PersonAlias = person.PrimaryAlias; communication.Recipients.Add( communicationRecipient ); } } } communication.IsBulkCommunication = cbBulk.Checked; communication.MediumEntityTypeId = MediumEntityTypeId; communication.MediumData.Clear(); GetMediumData(); foreach ( var keyVal in MediumData ) { if ( !string.IsNullOrEmpty( keyVal.Value ) ) { communication.MediumData.Add( keyVal.Key, keyVal.Value ); } } if ( communication.MediumData.ContainsKey( "Subject" ) ) { communication.Subject = communication.MediumData["Subject"]; communication.MediumData.Remove( "Subject" ); } DateTime? futureSendDate = dtpFutureSend.SelectedDateTime; if ( futureSendDate.HasValue && futureSendDate.Value.CompareTo( RockDateTime.Now ) > 0 ) { communication.FutureSendDateTime = futureSendDate; } else { communication.FutureSendDateTime = null; } return communication; }
protected void btnCancel_Click( object sender, EventArgs e ) { if ( _editingApproved ) { var communicationService = new CommunicationService( new RockContext() ); var communication = communicationService.Get( CommunicationId.Value ); if ( communication != null && communication.Status == CommunicationStatus.PendingApproval ) { // Redirect back to same page without the edit param var pageRef = new Rock.Web.PageReference(); pageRef.PageId = CurrentPageReference.PageId; pageRef.RouteId = CurrentPageReference.RouteId; pageRef.Parameters = new Dictionary<string, string>(); pageRef.Parameters.Add("CommunicationId", communication.Id.ToString()); Response.Redirect( pageRef.BuildUrl() ); Context.ApplicationInstance.CompleteRequest(); } } }
/// <summary> /// Handles the Click event of the btnCreateCommunication 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 btnCreateCommunication_Click(object sender, EventArgs e) { // Create communication var rockContext = new RockContext(); var communicationService = new Rock.Model.CommunicationService(rockContext); var communication = new Rock.Model.Communication(); communication.IsBulkCommunication = false; communication.Status = CommunicationStatus.Transient; communication.SenderPersonAliasId = this.CurrentPersonAliasId; if (this.Request != null && this.Request.Url != null) { communication.UrlReferrer = this.Request.UrlProxySafe().AbsoluteUri.TrimForMaxLength(communication, "UrlReferrer"); } communicationService.Add(communication); // save communication to get Id rockContext.SaveChanges(); int[] scheduleIds = lbSchedules.SelectedValuesAsInt.ToArray(); int[] locationIds = cblLocations.SelectedValuesAsInt.ToArray(); List <int> parentGroupIds = gpGroups.SelectedValuesAsInt().ToList(); var allGroupIds = new List <int>(); allGroupIds.AddRange(parentGroupIds); if (cbIncludeChildGroups.Checked) { var groupService = new GroupService(rockContext); foreach (var groupId in parentGroupIds) { // just the first level of child groups, not all decendants var childGroupIds = groupService.Queryable() .Where(a => a.ParentGroupId == groupId && a.GroupType.IsSchedulingEnabled && !a.DisableScheduling) .Select(a => a.Id).ToList(); allGroupIds.AddRange(childGroupIds); } } allGroupIds = allGroupIds.Distinct().ToList(); var attendanceOccurrenceService = new AttendanceOccurrenceService(rockContext); var sundayDate = ddlWeek.SelectedValue.AsDateTime() ?? RockDateTime.Now.SundayDate(); var attendanceOccurrenceQuery = attendanceOccurrenceService .Queryable() .Where(a => a.ScheduleId.HasValue && a.LocationId.HasValue && a.GroupId.HasValue) .WhereDeducedIsActive() .Where(a => allGroupIds.Contains(a.GroupId.Value)) .Where(a => locationIds.Contains(a.LocationId.Value)) .Where(a => scheduleIds.Contains(a.ScheduleId.Value)) .Where(a => a.SundayDate == sundayDate); ScheduledAttendanceItemStatus[] selectedInviteStatus = cblInviteStatus.SelectedValues .Select(a => a.ConvertToEnum <ScheduledAttendanceItemStatus>()) .ToArray(); // limit attendees to ones based on the selected invite status var scheduledAttendancesForOccurrenceQuery = attendanceOccurrenceQuery .SelectMany(a => a.Attendees) .WhereHasScheduledAttendanceItemStatus(selectedInviteStatus); var personIds = scheduledAttendancesForOccurrenceQuery.Select(a => a.PersonAlias.PersonId).Distinct().ToList(); if (!personIds.Any()) { nbCommunicationWarning.Text = "No people found to send communication to."; nbCommunicationWarning.Visible = true; return; } nbCommunicationWarning.Visible = false; var personAliasService = new Rock.Model.PersonAliasService(new Rock.Data.RockContext()); // Get the primary aliases List <Rock.Model.PersonAlias> primaryAliasList = new List <PersonAlias>(personIds.Count); // get the data in chunks just in case we have a large list of PersonIds (to avoid a SQL Expression limit error) var chunkedPersonIds = personIds.Take(1000); int skipCount = 0; while (chunkedPersonIds.Any()) { var chunkedPrimaryAliasList = personAliasService.Queryable() .Where(p => p.PersonId == p.AliasPersonId && chunkedPersonIds.Contains(p.PersonId)).AsNoTracking().ToList(); primaryAliasList.AddRange(chunkedPrimaryAliasList); skipCount += 1000; chunkedPersonIds = personIds.Skip(skipCount).Take(1000); } // NOTE: Set CreatedDateTime, ModifiedDateTime, etc manually set we are using BulkInsert var currentDateTime = RockDateTime.Now; var currentPersonAliasId = this.CurrentPersonAliasId; var communicationRecipientList = primaryAliasList.Select(a => new Rock.Model.CommunicationRecipient { CommunicationId = communication.Id, PersonAliasId = a.Id, CreatedByPersonAliasId = currentPersonAliasId, ModifiedByPersonAliasId = currentPersonAliasId, CreatedDateTime = currentDateTime, ModifiedDateTime = currentDateTime }).ToList(); // BulkInsert to quickly insert the CommunicationRecipient records. Note: This is much faster, but will bypass EF and Rock processing. var communicationRecipientRockContext = new RockContext(); communicationRecipientRockContext.BulkInsert(communicationRecipientList); var pageRef = this.RockPage.Site.CommunicationPageReference; string communicationUrl; if (pageRef.PageId > 0) { pageRef.Parameters.AddOrReplace("CommunicationId", communication.Id.ToString()); communicationUrl = pageRef.BuildUrl(); } else { communicationUrl = "~/Communication/{0}"; } if (communicationUrl.Contains("{0}")) { communicationUrl = string.Format(communicationUrl, communication.Id); } UserPreferenceConfiguration userPreferenceConfiguration = this.GetBlockUserPreference(UserPreferenceKey.UserPreferenceConfigurationJSON).FromJsonOrNull <UserPreferenceConfiguration>() ?? new UserPreferenceConfiguration(); userPreferenceConfiguration.GroupIds = gpGroups.SelectedValuesAsInt().ToArray(); userPreferenceConfiguration.IncludeChildGroups = cbIncludeChildGroups.Checked; userPreferenceConfiguration.InviteStatuses = cblInviteStatus.SelectedValues.ToArray(); userPreferenceConfiguration.ScheduleIds = lbSchedules.SelectedValuesAsInt.ToArray(); userPreferenceConfiguration.LocationIds = cblLocations.SelectedValuesAsInt.ToArray(); this.SetBlockUserPreference(UserPreferenceKey.UserPreferenceConfigurationJSON, userPreferenceConfiguration.ToJson()); Page.Response.Redirect(communicationUrl, false); Context.ApplicationInstance.CompleteRequest(); }
/// <summary> /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event. /// </summary> /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param> protected override void OnLoad( EventArgs e ) { base.OnLoad( e ); nbTestResult.Visible = false; if ( Page.IsPostBack ) { LoadMediumControl( false ); } else { ShowAllRecipients = false; // Check if CommunicationDetail has already loaded existing communication var communication = RockPage.GetSharedItem( "Communication" ) as Rock.Model.Communication; if ( communication == null ) { // If not, check page parameter for existing communiciaton int? communicationId = PageParameter( "CommunicationId" ).AsIntegerOrNull(); if ( communicationId.HasValue ) { communication = new CommunicationService( new RockContext() ).Get( communicationId.Value ); } } else { CommunicationId = communication.Id; } if ( communication == null || communication.Status == CommunicationStatus.Transient || communication.Status == CommunicationStatus.Draft || communication.Status == CommunicationStatus.Denied || ( communication.Status == CommunicationStatus.PendingApproval && _editingApproved ) ) { // If viewing a new, transient, draft, or denied communication, use this block ShowDetail( communication ); } else { // Otherwise, use the communication detail block this.Visible = false; } } }
/// <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 approvers = new GroupService( rockContext ).Get(SystemGuid.Group.GROUP_COMMUNICATION_APPROVERS.AsGuid()); if ( approvers != null ) { var mergeFields = new Dictionary<string, object>(); var globalAttributeFields = Rock.Web.Cache.GlobalAttributesCache.GetMergeFields( null ); globalAttributeFields.ToList().ForEach( d => mergeFields.Add( d.Key, d.Value ) ); 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( "ExternalApplicationRoot" ); string communicationDetails = string.Empty; string typeName = string.Empty; // get custom details by type switch ( communication.Medium.TypeName ) { case "Rock.Communication.Medium.Email": string emailFromName = communication.GetMediumDataValue( "FromName" ); string emailFromAddress = communication.GetMediumDataValue( "FromAddress" ); communicationDetails = string.Format( @" <strong>From Name:</strong> {0}<br/> <strong>From Address:</strong> {1}<br/> <strong>Subject:</strong> {2}<br/>" , emailFromName , emailFromAddress , communication.Subject ); typeName = "Email"; break; case "Rock.Communication.Medium.Sms": int fromValueId = communication.GetMediumDataValue( "FromValue" ).AsInteger(); var fromValue = new DefinedValueService( rockContext ).Get( fromValueId ); typeName = "SMS"; if ( fromValue != null ) { communicationDetails = string.Format( "<strong>SMS Number:</strong> {0} ({1})<br/>", fromValue.Description, fromValue.Value ); } break; } // create approval link if one was not provided if ( ApprovalPageUrl == null ) { ApprovalPageUrl = string.Format( "{0}Communication/{1}", Rock.Web.Cache.GlobalAttributesCache.Read( rockContext ).GetValue( "InternalApplicationRoot" ), communication.Id ); } foreach ( var approver in approvers.Members ) { 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.Recipients.Count(), ApprovalPageUrl); var recipients = new List<string>(); recipients.Add( approver.Person.Email ); Email.Send( fromEmail, fromName, subject, recipients, message.ResolveMergeFields( mergeFields ), appRoot, string.Empty, null, false ); } } } } }
private void BindGrid() { using ( new UnitOfWorkScope() ) { var communications = new CommunicationService() .Queryable() .Where( c => c.Status != CommunicationStatus.Transient ); string subject = rFilter.GetUserPreference( "Subject" ); if ( !string.IsNullOrWhiteSpace( subject ) ) { communications = communications.Where( c => c.Subject.StartsWith( subject ) ); } Guid entityTypeGuid = Guid.Empty; if ( Guid.TryParse( rFilter.GetUserPreference( "Channel" ), out entityTypeGuid ) ) { communications = communications.Where( c => c.ChannelEntityType != null && c.ChannelEntityType.Guid.Equals( entityTypeGuid ) ); } string status = rFilter.GetUserPreference( "Status" ); if ( !string.IsNullOrWhiteSpace( status ) ) { var communicationStatus = (CommunicationStatus)System.Enum.Parse( typeof( CommunicationStatus ), status ); communications = communications.Where( c => c.Status == communicationStatus ); } if ( canApprove ) { int personId = 0; if ( int.TryParse( rFilter.GetUserPreference( "Created By" ), out personId ) && personId != 0 ) { communications = communications.Where( c => c.SenderPersonId.HasValue && c.SenderPersonId.Value == personId ); } } else { communications = communications.Where( c => c.SenderPersonId.HasValue && c.SenderPersonId.Value == CurrentPersonId ); } string content = rFilter.GetUserPreference( "Content" ); if ( !string.IsNullOrWhiteSpace( content ) ) { communications = communications.Where( c => c.ChannelDataJson.Contains( content ) ); } var recipients = new CommunicationRecipientService().Queryable(); var sortProperty = gCommunication.SortProperty; var queryable = communications .Join( recipients, c => c.Id, r => r.CommunicationId, ( c, r ) => new { c, r } ) .GroupBy( cr => cr.c ) .Select( g => new CommunicationItem { Id = g.Key.Id, Communication = g.Key, Recipients = g.Count(), PendingRecipients = g.Count( s => s.r.Status == CommunicationRecipientStatus.Pending ), SuccessRecipients = g.Count( s => s.r.Status == CommunicationRecipientStatus.Success ), FailedRecipients = g.Count( s => s.r.Status == CommunicationRecipientStatus.Failed ), CancelledRecipients = g.Count( s => s.r.Status == CommunicationRecipientStatus.Cancelled ) } ); if ( sortProperty != null ) { queryable = queryable.Sort( sortProperty ); } else { queryable = queryable.OrderByDescending( c => c.Communication.Id ); } gCommunication.DataSource = queryable.ToList(); gCommunication.DataBind(); } }
/// <summary> /// Sends the specified communication. /// </summary> /// <param name="communication">The communication.</param> public override void Send( Model.Communication communication ) { var rockContext = new RockContext(); var communicationService = new CommunicationService( rockContext ); communication = communicationService.Get( communication.Id ); if ( communication != null && communication.Status == Model.CommunicationStatus.Approved && communication.Recipients.Where( r => r.Status == Model.CommunicationRecipientStatus.Pending ).Any() && ( !communication.FutureSendDateTime.HasValue || communication.FutureSendDateTime.Value.CompareTo( RockDateTime.Now ) <= 0 ) ) { // Update any recipients that should not get sent the communication var recipientService = new CommunicationRecipientService( rockContext ); foreach ( var recipient in recipientService.Queryable( "Person" ) .Where( r => r.CommunicationId == communication.Id && r.Status == CommunicationRecipientStatus.Pending ) .ToList() ) { var person = recipient.Person; if ( person.IsDeceased ?? false ) { recipient.Status = CommunicationRecipientStatus.Failed; recipient.StatusNote = "Person is deceased!"; } } rockContext.SaveChanges(); } base.Send( communication ); }
/// <summary> /// Creates a new communication. /// </summary> /// <param name="fromPersonId">Person ID of the sender.</param> /// <param name="fromPersonName">Name of from person.</param> /// <param name="toPersonId">The Person ID of the recipient.</param> /// <param name="message">The message to send.</param> /// <param name="transportPhone">The transport phone.</param> /// <param name="responseCode">The reponseCode to use for tracking the conversation.</param> /// <param name="rockContext">A context to use for database calls.</param> private void CreateCommunication( int fromPersonId, string fromPersonName, int toPersonId, string message, string transportPhone, string responseCode, Rock.Data.RockContext rockContext ) { // add communication for reply var communication = new Rock.Model.Communication(); communication.IsBulkCommunication = false; communication.Status = CommunicationStatus.Approved; communication.SenderPersonId = fromPersonId; communication.Subject = string.Format( "From: {0}", fromPersonName ); communication.SetChannelDataValue( "Message", message ); communication.SetChannelDataValue( "FromValue", transportPhone ); communication.ChannelEntityTypeId = EntityTypeCache.Read( "Rock.Communication.Channel.Sms" ).Id; var recipient = new Rock.Model.CommunicationRecipient(); recipient.Status = CommunicationRecipientStatus.Pending; recipient.PersonId = toPersonId; recipient.ResponseCode = responseCode; communication.Recipients.Add( recipient ); var communicationService = new Rock.Model.CommunicationService( rockContext ); communicationService.Add( communication ); rockContext.SaveChanges(); // queue the sending var transaction = new Rock.Transactions.SendCommunicationTransaction(); transaction.CommunicationId = communication.Id; transaction.PersonAlias = null; Rock.Transactions.RockQueue.TransactionQueue.Enqueue( transaction ); }
/// <summary> /// Handles the Click event of the btnDeny 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 btnDeny_Click( object sender, EventArgs e ) { if ( Page.IsValid && CommunicationId.HasValue ) { var rockContext = new RockContext(); var service = new CommunicationService( rockContext ); var communication = service.Get( CommunicationId.Value ); if ( communication != null ) { if ( communication.Status == CommunicationStatus.PendingApproval ) { if ( IsUserAuthorized( "Approve" ) ) { communication.Status = CommunicationStatus.Denied; communication.ReviewedDateTime = RockDateTime.Now; communication.ReviewerPersonAliasId = CurrentPersonAliasId; rockContext.SaveChanges(); // TODO: Send notice to sneder that communication was denied ShowResult( "The communication has been denied", communication, NotificationBoxType.Warning ); } else { ShowResult( "Sorry, you are not authorized to approve or deny this communication!", communication, NotificationBoxType.Danger ); } } else { ShowResult( string.Format( "This communication is already {0}!", communication.Status.ConvertToString() ), communication, NotificationBoxType.Warning ); } } } }
/// <summary> /// Handles the Click event of the btnTest control and sends a test communication to the /// current person if they have an email address on their record. /// </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 btnTest_Click( object sender, EventArgs e ) { if ( Page.IsValid && CurrentPerson != null ) { SetActionButtons( resetToSend: true ); if ( string.IsNullOrWhiteSpace( CurrentPerson.Email ) ) { nbError.Text = "A test email cannot be sent because you do not have an email address."; nbError.Visible = true; return; } // Get existing or new communication record var communication = GetCommunication( new RockContext(), null ); if ( communication != null && CurrentPersonAliasId.HasValue ) { // Using a new context (so that changes in the UpdateCommunication() are not persisted ) var testCommunication = new Rock.Model.Communication(); testCommunication.SenderPersonAliasId = communication.SenderPersonAliasId; testCommunication.Subject = communication.Subject; testCommunication.IsBulkCommunication = communication.IsBulkCommunication; testCommunication.MediumEntityTypeId = communication.MediumEntityTypeId; testCommunication.MediumDataJson = communication.MediumDataJson; testCommunication.AdditionalMergeFieldsJson = communication.AdditionalMergeFieldsJson; testCommunication.FutureSendDateTime = null; testCommunication.Status = CommunicationStatus.Approved; testCommunication.ReviewedDateTime = RockDateTime.Now; testCommunication.ReviewerPersonAliasId = CurrentPersonAliasId.Value; var testRecipient = new CommunicationRecipient(); if ( communication.Recipients.Any() ) { var recipient = communication.Recipients.FirstOrDefault(); testRecipient.AdditionalMergeValuesJson = recipient.AdditionalMergeValuesJson; } testRecipient.Status = CommunicationRecipientStatus.Pending; testRecipient.PersonAliasId = CurrentPersonAliasId.Value; testCommunication.Recipients.Add( testRecipient ); var rockContext = new RockContext(); var communicationService = new CommunicationService( rockContext ); communicationService.Add( testCommunication ); rockContext.SaveChanges(); var medium = testCommunication.Medium; if ( medium != null ) { medium.Send( testCommunication ); } communicationService.Delete( testCommunication ); rockContext.SaveChanges(); nbTestResult.Visible = true; } } }
/// <summary> /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event. /// </summary> /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param> protected override void OnLoad( EventArgs e ) { base.OnLoad( e ); if ( !Page.IsPostBack ) { // Check if CommunicationDetail has already loaded existing communication var communication = RockPage.GetSharedItem( "Communication" ) as Rock.Model.Communication; if ( communication == null ) { CommunicationId = PageParameter( "CommunicationId" ).AsIntegerOrNull(); if ( CommunicationId.HasValue ) { communication = new CommunicationService( new RockContext() ) .Queryable( "CreatedByPersonAlias.Person" ) .Where( c => c.Id == CommunicationId.Value ) .FirstOrDefault(); } } else { CommunicationId = communication.Id; } // If not valid for this block, hide contents and return if ( communication == null || communication.Status == CommunicationStatus.Transient || communication.Status == CommunicationStatus.Draft || communication.Status == CommunicationStatus.Denied || ( communication.Status == CommunicationStatus.PendingApproval && _editingApproved ) ) { // If viewing a new, transient or draft communication, hide this block and use NewCommunication block this.Visible = false; } else { ShowDetail( communication ); } } }
/// <summary> /// Sends the specified template. /// </summary> /// <param name="template">The template.</param> /// <param name="recipients">The recipients.</param> /// <param name="appRoot">The application root.</param> /// <param name="themeRoot">The theme root.</param> /// <param name="createCommunicationHistory">if set to <c>true</c> [create communication history].</param> public void Send( SystemEmail template, List<RecipientData> recipients, string appRoot, string themeRoot, bool createCommunicationHistory ) { var globalAttributes = GlobalAttributesCache.Read(); string from = template.From; if (string.IsNullOrWhiteSpace(from)) { from = globalAttributes.GetValue( "OrganizationEmail" ); } string fromName = template.FromName; if ( string.IsNullOrWhiteSpace( fromName ) ) { fromName = globalAttributes.GetValue( "OrganizationName" ); } if ( !string.IsNullOrWhiteSpace( from ) ) { // Resolve any possible merge fields in the from address var globalConfigValues = Rock.Web.Cache.GlobalAttributesCache.GetMergeFields( null ); from = from.ResolveMergeFields( globalConfigValues ); fromName = fromName.ResolveMergeFields( globalConfigValues ); MailMessage message = new MailMessage(); if (string.IsNullOrWhiteSpace(fromName)) { message.From = new MailAddress( from ); } else { message.From = new MailAddress( from, fromName ); } CheckSafeSender( message, globalAttributes ); if ( !string.IsNullOrWhiteSpace( template.Cc ) ) { foreach ( string ccRecipient in template.Cc.SplitDelimitedValues() ) { message.CC.Add( new MailAddress( ccRecipient ) ); } } if ( !string.IsNullOrWhiteSpace( template.Bcc ) ) { foreach ( string ccRecipient in template.Bcc.SplitDelimitedValues() ) { message.Bcc.Add( new MailAddress( ccRecipient ) ); } } message.IsBodyHtml = true; message.Priority = MailPriority.Normal; using ( var smtpClient = GetSmtpClient() ) { using ( var rockContext = new RockContext() ) { int? senderPersonAliasId = null; if ( createCommunicationHistory ) { var sender = new PersonService( rockContext ) .Queryable().AsNoTracking() .Where( p => p.Email == from ) .FirstOrDefault(); senderPersonAliasId = sender != null ? sender.PrimaryAliasId : (int?)null; } var communicationService = new CommunicationService( rockContext ); foreach ( var recipientData in recipients ) { foreach ( var g in globalConfigValues ) { if ( recipientData.MergeFields.ContainsKey( g.Key ) ) { recipientData.MergeFields[g.Key] = g.Value; } } // Add the recipients from the template List<string> sendTo = SplitRecipient( template.To ); // Add the recipient from merge data ( if it's not null and not already added ) if ( !string.IsNullOrWhiteSpace( recipientData.To ) && !sendTo.Contains( recipientData.To, StringComparer.OrdinalIgnoreCase ) ) { sendTo.Add( recipientData.To ); } foreach ( string to in sendTo ) { message.To.Clear(); message.To.Add( to ); string subject = template.Subject.ResolveMergeFields( recipientData.MergeFields ); string body = Regex.Replace( template.Body.ResolveMergeFields( recipientData.MergeFields ), @"\[\[\s*UnsubscribeOption\s*\]\]", string.Empty ); if ( !string.IsNullOrWhiteSpace( themeRoot ) ) { subject = subject.Replace( "~~/", themeRoot ); body = body.Replace( "~~/", themeRoot ); } if ( !string.IsNullOrWhiteSpace( appRoot ) ) { subject = subject.Replace( "~/", appRoot ); body = body.Replace( "~/", appRoot ); body = body.Replace( @" src=""/", @" src=""" + appRoot ); body = body.Replace( @" href=""/", @" href=""" + appRoot ); } message.Subject = subject; message.Body = body; smtpClient.Send( message ); if ( createCommunicationHistory ) { communicationService.CreateEmailCommunication( new List<string> { to }, fromName, from, from, subject, body, string.Empty, false, CommunicationRecipientStatus.Delivered, senderPersonAliasId ); } } } if ( createCommunicationHistory ) { rockContext.SaveChanges(); } } } } }
/// <summary> /// Gets the communication. /// </summary> /// <param name="rockContext">The rock context.</param> /// <param name="peopleIds">The people ids.</param> /// <returns></returns> private Rock.Model.Communication GetCommunication( RockContext rockContext, List<int> peopleIds ) { var communicationService = new CommunicationService(rockContext); var recipientService = new CommunicationRecipientService(rockContext); GetTemplateData(); Rock.Model.Communication communication = new Rock.Model.Communication(); communication.Status = CommunicationStatus.Transient; communication.SenderPersonAliasId = CurrentPersonAliasId; communicationService.Add( communication ); communication.IsBulkCommunication = true; communication.MediumEntityTypeId = EntityTypeCache.Read( "Rock.Communication.Medium.Email" ).Id; communication.FutureSendDateTime = null; // add each person as a recipient to the communication if ( peopleIds != null ) { foreach ( var personId in peopleIds ) { if ( !communication.Recipients.Any( r => r.PersonAlias.PersonId == personId ) ) { var communicationRecipient = new CommunicationRecipient(); communicationRecipient.PersonAlias = new PersonAliasService( rockContext ).GetPrimaryAlias( personId ); communication.Recipients.Add( communicationRecipient ); } } } // add the MediumData to the communication communication.MediumData.Clear(); foreach ( var keyVal in MediumData ) { if ( !string.IsNullOrEmpty( keyVal.Value ) ) { communication.MediumData.Add( keyVal.Key, keyVal.Value ); } } if ( communication.MediumData.ContainsKey( "Subject" ) ) { communication.Subject = communication.MediumData["Subject"]; communication.MediumData.Remove( "Subject" ); } return communication; }