Exemple #1
0
        /// <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);
        }
        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);
        }
Exemple #3
0
        /// <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>
        /// 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>
        /// 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;
        }
        /// <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 );
            }
        }
Exemple #8
0
        /// <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>
        /// 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;
        }
        /// <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>
        /// 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>
        /// 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();
        }
Exemple #13
0
        /// <summary>
        /// Updates a communication model with the user-entered values
        /// </summary>
        /// <param name="service">The service.</param>
        /// <returns></returns>
        private Rock.Model.Communication UpdateCommunication(CommunicationService service)
        {
            Rock.Model.Communication communication = null;
            if ( CommunicationId.HasValue )
            {
                communication = service.Get( CommunicationId.Value );
            }

            if (communication == null)
            {
                communication = new Rock.Model.Communication();
                communication.Status = CommunicationStatus.Transient;
                communication.SenderPersonId = CurrentPersonId;
                service.Add( communication, CurrentPersonId );
            }

            communication.ChannelEntityTypeId = ChannelEntityTypeId;

            foreach(var recipient in Recipients)
            {
                if ( !communication.Recipients.Where( r => r.PersonId == recipient.PersonId ).Any() )
                {
                    var communicationRecipient = new CommunicationRecipient();
                    communicationRecipient.Person = new PersonService().Get( recipient.PersonId );
                    communicationRecipient.Status = CommunicationRecipientStatus.Pending;
                    communication.Recipients.Add( communicationRecipient );
                }
            }

            GetChannelData();
            communication.ChannelData = ChannelData;
            if ( communication.ChannelData.ContainsKey( "Subject" ) )
            {
                communication.Subject = communication.ChannelData["Subject"];
                communication.ChannelData.Remove( "Subject" );
            }

            communication.FutureSendDateTime = dtpFutureSend.SelectedDateTime;

            return communication;
        }
Exemple #14
0
        /// <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 )
        {
            using ( new UnitOfWorkScope() )
            {
                var service = new CommunicationService();
                var communication = UpdateCommunication( service );
                if ( communication != null )
                {
                    var newCommunication = communication.Clone( false );
                    newCommunication.Id = 0;
                    newCommunication.Guid = Guid.Empty;
                    newCommunication.SenderPersonId = CurrentPersonId;
                    newCommunication.Status = CommunicationStatus.Transient;
                    newCommunication.ReviewerPersonId = null;
                    newCommunication.ReviewedDateTime = null;
                    newCommunication.ReviewerNote = string.Empty;

                    communication.Recipients.ToList().ForEach( r =>
                        newCommunication.Recipients.Add( new CommunicationRecipient()
                        {
                            PersonId = r.PersonId,
                            Status = CommunicationRecipientStatus.Pending,
                            StatusNote = string.Empty
                        } ) );

                    service.Add( newCommunication, CurrentPersonId );
                    service.Save( newCommunication, CurrentPersonId );

                    // 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();
                }
            }
        }