/// <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>
        /// Creates an SMS communication with a CommunicationRecipient and adds it to the context.
        /// </summary>
        /// <param name="fromPerson">From person. If null the name for the communication will be From: unknown person.</param>
        /// <param name="toPersonAliasId">To person alias identifier. If null the CommunicationRecipient is not created</param>
        /// <param name="message">The message.</param>
        /// <param name="fromPhone">From phone.</param>
        /// <param name="responseCode">The response code. If null/empty/whitespace then one is generated</param>
        /// <param name="communicationName">Name of the communication.</param>
        /// <returns></returns>
        public Communication CreateSMSCommunication(Person fromPerson, int?toPersonAliasId, string message, DefinedValueCache fromPhone, string responseCode, string communicationName)
        {
            RockContext rockContext = ( RockContext )this.Context;

            if (responseCode.IsNullOrWhiteSpace())
            {
                responseCode = Rock.Communication.Medium.Sms.GenerateResponseCode(rockContext);
            }

            // add communication for reply
            var communication = new Rock.Model.Communication();

            communication.Name = communicationName;
            communication.CommunicationType   = CommunicationType.SMS;
            communication.SenderPersonAliasId = fromPerson?.PrimaryAliasId;
            communication.IsBulkCommunication = false;
            communication.Status                = CommunicationStatus.Approved;
            communication.SMSMessage            = message;
            communication.SMSFromDefinedValueId = fromPhone.Id;

            if (toPersonAliasId != null)
            {
                var recipient = new Rock.Model.CommunicationRecipient();
                recipient.Status             = CommunicationRecipientStatus.Pending;
                recipient.PersonAliasId      = toPersonAliasId.Value;
                recipient.ResponseCode       = responseCode;
                recipient.MediumEntityTypeId = EntityTypeCache.Get("Rock.Communication.Medium.Sms").Id;
                recipient.SentMessage        = message;
                communication.Recipients.Add(recipient);
            }

            Add(communication);
            return(communication);
        }
        /// <summary>
        /// Creates the email communication.
        /// </summary>
        /// <param name="recipientEmails">The recipient emails.</param>
        /// <param name="fromName">From name.</param>
        /// <param name="fromAddress">From address.</param>
        /// <param name="replyTo">The reply to.</param>
        /// <param name="subject">The subject.</param>
        /// <param name="htmlMessage">The HTML message.</param>
        /// <param name="textMessage">The text message.</param>
        /// <param name="bulkCommunication">if set to <c>true</c> [bulk communication].</param>
        /// <param name="recipientStatus">The recipient status.</param>
        /// <param name="senderPersonAliasId">The sender person alias identifier.</param>
        /// <returns></returns>
        public Communication CreateEmailCommunication( 
            List<string> recipientEmails, 
            string fromName,
            string fromAddress,
            string replyTo,
            string subject,
            string htmlMessage,
            string textMessage,
            bool bulkCommunication, 
            CommunicationRecipientStatus recipientStatus = CommunicationRecipientStatus.Delivered, 
            int? senderPersonAliasId = null )
        {
            var recipients = new PersonService( (RockContext)this.Context )
                .Queryable()
                .Where( p => recipientEmails.Contains( p.Email ) )
                .ToList();

            if ( recipients.Any() )
            {
                Rock.Model.Communication communication = new Rock.Model.Communication();
                communication.Status = CommunicationStatus.Approved;
                communication.SenderPersonAliasId = senderPersonAliasId;
                communication.Subject = subject;
                Add( communication );

                communication.IsBulkCommunication = bulkCommunication;
                communication.MediumEntityTypeId = EntityTypeCache.Read( "Rock.Communication.Medium.Email" ).Id;
                communication.FutureSendDateTime = null;

                // add each person as a recipient to the communication
                foreach ( var person in recipients )
                {
                    int? personAliasId = person.PrimaryAliasId;
                    if ( personAliasId.HasValue )
                    {
                        var communicationRecipient = new CommunicationRecipient();
                        communicationRecipient.PersonAliasId = personAliasId.Value;
                        communicationRecipient.Status = recipientStatus;
                        communication.Recipients.Add( communicationRecipient );
                    }
                }

                // add the MediumData to the communication
                communication.MediumData.Clear();
                communication.MediumData.Add( "FromName", fromName );
                communication.MediumData.Add( "FromAddress", fromAddress );
                communication.MediumData.Add( "ReplyTo", replyTo );
                communication.MediumData.Add( "Subject", subject );
                communication.MediumData.Add( "HtmlMessage", htmlMessage );
                communication.MediumData.Add( "TextMessage", textMessage );

                return communication;
            }

            return null;
        }
Exemplo n.º 4
0
        /// <summary>
        /// Creates the email communication.
        /// </summary>
        /// <param name="recipientEmails">The recipient emails.</param>
        /// <param name="fromName">From name.</param>
        /// <param name="fromAddress">From address.</param>
        /// <param name="replyTo">The reply to.</param>
        /// <param name="subject">The subject.</param>
        /// <param name="htmlMessage">The HTML message.</param>
        /// <param name="textMessage">The text message.</param>
        /// <param name="bulkCommunication">if set to <c>true</c> [bulk communication].</param>
        /// <param name="recipientStatus">The recipient status.</param>
        /// <param name="senderPersonAliasId">The sender person alias identifier.</param>
        /// <returns></returns>
        public Communication CreateEmailCommunication(
            List <string> recipientEmails,
            string fromName,
            string fromAddress,
            string replyTo,
            string subject,
            string htmlMessage,
            string textMessage,
            bool bulkCommunication,
            CommunicationRecipientStatus recipientStatus = CommunicationRecipientStatus.Delivered,
            int?senderPersonAliasId = null)
        {
            var recipients = new PersonService((RockContext)this.Context)
                             .Queryable()
                             .Where(p => recipientEmails.Contains(p.Email))
                             .ToList();

            if (recipients.Any())
            {
                Rock.Model.Communication communication = new Rock.Model.Communication();
                communication.Status = CommunicationStatus.Approved;
                communication.SenderPersonAliasId = senderPersonAliasId;
                communication.Subject             = subject;
                Add(communication);

                communication.IsBulkCommunication = bulkCommunication;
                communication.MediumEntityTypeId  = EntityTypeCache.Read("Rock.Communication.Medium.Email").Id;
                communication.FutureSendDateTime  = null;

                // add each person as a recipient to the communication
                foreach (var person in recipients)
                {
                    int?personAliasId = person.PrimaryAliasId;
                    if (personAliasId.HasValue)
                    {
                        var communicationRecipient = new CommunicationRecipient();
                        communicationRecipient.PersonAliasId = personAliasId.Value;
                        communicationRecipient.Status        = recipientStatus;
                        communication.Recipients.Add(communicationRecipient);
                    }
                }

                // add the MediumData to the communication
                communication.MediumData.Clear();
                communication.MediumData.Add("FromName", fromName);
                communication.MediumData.Add("FromAddress", fromAddress);
                communication.MediumData.Add("ReplyTo", replyTo);
                communication.MediumData.Add("Subject", subject);
                communication.MediumData.Add("HtmlMessage", htmlMessage);
                communication.MediumData.Add("TextMessage", textMessage);

                return(communication);
            }

            return(null);
        }
Exemplo n.º 5
0
 /// <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)
     {
         foreach (var medium in communication.GetMediums())
         {
             medium.Send(communication);
         }
     }
 }
Exemplo n.º 6
0
        /// <summary>
        /// Creates the email communication.
        /// </summary>
        /// <param name="recipientEmails">The recipient emails.</param>
        /// <param name="fromName">From name.</param>
        /// <param name="fromAddress">From address.</param>
        /// <param name="replyTo">The reply to.</param>
        /// <param name="subject">The subject.</param>
        /// <param name="message">The message.</param>
        /// <param name="bulkCommunication">if set to <c>true</c> [bulk communication].</param>
        /// <param name="recipientStatus">The recipient status.</param>
        /// <param name="senderPersonAliasId">The sender person alias identifier.</param>
        /// <returns></returns>
        public Communication CreateEmailCommunication
        (
            List <string> recipientEmails,
            string fromName,
            string fromAddress,
            string replyTo,
            string subject,
            string message,
            bool bulkCommunication,
            CommunicationRecipientStatus recipientStatus = CommunicationRecipientStatus.Delivered,
            int?senderPersonAliasId = null)
        {
            var recipients = new PersonService((RockContext)this.Context)
                             .Queryable()
                             .Where(p => recipientEmails.Contains(p.Email))
                             .ToList();

            if (recipients.Any())
            {
                Rock.Model.Communication communication = new Rock.Model.Communication();
                Add(communication);

                communication.CommunicationType   = CommunicationType.Email;
                communication.Status              = CommunicationStatus.Approved;
                communication.SenderPersonAliasId = senderPersonAliasId;
                communication.FromName            = fromName.TrimForMaxLength(communication, "FromName");
                communication.FromEmail           = fromAddress.TrimForMaxLength(communication, "FromEmail");
                communication.ReplyToEmail        = replyTo.TrimForMaxLength(communication, "ReplyToEmail");
                communication.Subject             = subject.TrimForMaxLength(communication, "Subject");
                communication.Message             = message;
                communication.IsBulkCommunication = bulkCommunication;
                communication.FutureSendDateTime  = null;

                // add each person as a recipient to the communication
                foreach (var person in recipients)
                {
                    int?personAliasId = person.PrimaryAliasId;
                    if (personAliasId.HasValue)
                    {
                        var communicationRecipient = new CommunicationRecipient();
                        communicationRecipient.PersonAliasId = personAliasId.Value;
                        communicationRecipient.Status        = recipientStatus;
                        communication.Recipients.Add(communicationRecipient);
                    }
                }

                return(communication);
            }

            return(null);
        }
Exemplo n.º 7
0
        /// <summary>
        /// Creates an SMS communication with a CommunicationRecipient and adds it to the context.
        /// </summary>
        /// <param name="createSMSCommunicationArgs">The create SMS communication arguments.</param>
        /// <returns></returns>
        public Communication CreateSMSCommunication(CreateSMSCommunicationArgs createSMSCommunicationArgs)
        {
            RockContext rockContext           = ( RockContext )this.Context;
            var         responseCode          = createSMSCommunicationArgs.ResponseCode;
            var         communicationName     = createSMSCommunicationArgs.CommunicationName;
            var         fromPerson            = createSMSCommunicationArgs.FromPerson;
            var         message               = createSMSCommunicationArgs.Message;
            var         fromPhone             = createSMSCommunicationArgs.FromPhone;
            var         systemCommunicationId = createSMSCommunicationArgs.SystemCommunicationId;
            var         toPersonAliasId       = createSMSCommunicationArgs.ToPersonAliasId;

            if (responseCode.IsNullOrWhiteSpace())
            {
                responseCode = Rock.Communication.Medium.Sms.GenerateResponseCode(rockContext);
            }

            // add communication for reply
            var communication = new Rock.Model.Communication
            {
                Name = communicationName,
                CommunicationType = CommunicationType.SMS,
                Status            = CommunicationStatus.Approved,
                ReviewedDateTime  = RockDateTime.Now,
                // NOTE: if this communication was created from a mobile device, fromPerson should never be null since a Nameless Person record should have been created if a regular person record wasn't found
                ReviewerPersonAliasId = fromPerson?.PrimaryAliasId,
                SenderPersonAliasId   = fromPerson?.PrimaryAliasId,
                IsBulkCommunication   = false,
                SMSMessage            = message,
                SMSFromDefinedValueId = fromPhone.Id,
                SystemCommunicationId = systemCommunicationId
            };

            if (toPersonAliasId != null)
            {
                var recipient = new Rock.Model.CommunicationRecipient();
                recipient.Status             = CommunicationRecipientStatus.Pending;
                recipient.PersonAliasId      = toPersonAliasId.Value;
                recipient.ResponseCode       = responseCode;
                recipient.MediumEntityTypeId = EntityTypeCache.Get("Rock.Communication.Medium.Sms").Id;
                recipient.SentMessage        = message;
                communication.Recipients.Add(recipient);
            }

            Add(communication);
            return(communication);
        }
Exemplo n.º 8
0
        /// <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();
            }
        }
Exemplo n.º 9
0
        /// <summary>
        /// Handles the CommunicateClick event of the Actions 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 Actions_CommunicateClick( object sender, EventArgs e )
        {
            var rockPage = Page as RockPage;
            if ( rockPage != null )
            {
                OnGridRebind( e );

                var recipients = GetPersonData();
                if ( recipients.Any() )
                {

                    // Create communication
                    var rockContext = new RockContext();
                    var service = new Rock.Model.CommunicationService( rockContext );
                    var communication = new Rock.Model.Communication();
                    communication.IsBulkCommunication = true;
                    communication.Status = Model.CommunicationStatus.Transient;
                    CommunicateMergeFields.ForEach( f => communication.AdditionalMergeFields.Add( f.Replace( '.', '_' ) ) );
                    if ( rockPage.CurrentPerson != null )
                    {
                        communication.SenderPersonAliasId = rockPage.CurrentPersonAliasId;
                    }

                    service.Add( communication );

                    var personIds = recipients.Select( r => r.Key ).ToList();
                    var personAliasService = new Rock.Model.PersonAliasService( new Rock.Data.RockContext() );

                    // Get the primary aliases
                    foreach ( var personAlias in personAliasService.Queryable()
                        .Where( p => p.PersonId == p.AliasPersonId && personIds.Contains( p.PersonId ) ) )
                    {
                        var recipient = new Rock.Model.CommunicationRecipient();
                        recipient.PersonAliasId = personAlias.Id;
                        recipient.AdditionalMergeValues = recipients[personAlias.PersonId];
                        communication.Recipients.Add( recipient );
                    }

                    rockContext.SaveChanges();

                    // Get the URL to communication page
                    string url = CommunicationPageRoute;
                    if ( string.IsNullOrWhiteSpace(url) )
                    {
                        var pageRef = rockPage.Site.CommunicationPageReference;
                        if ( pageRef.PageId > 0 )
                        {
                            pageRef.Parameters.AddOrReplace( "CommunicationId", communication.Id.ToString() );
                            url = pageRef.BuildUrl();
                        }
                        else
                        {
                            url = "~/Communication/{0}";
                        }
                    }
                    if ( url.Contains("{0}"))
                    {
                        url = string.Format( url, communication.Id );
                    }

                    Page.Response.Redirect( url, false );
                    Context.ApplicationInstance.CompleteRequest();
                }
            }
        }
Exemplo n.º 10
0
        /// <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();
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// Handles the CommunicateClick event of the Actions 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 Actions_CommunicateClick( object sender, EventArgs e )
        {
            if ( !string.IsNullOrWhiteSpace( PersonIdField ) )
            {
                var peopleSelected = SelectedKeys.ToList();

                // Set Sender
                var rockPage = Page as RockPage;
                if ( rockPage != null )
                {
                    var communication = new Rock.Model.Communication();
                    communication.IsBulkCommunication = true;
                    communication.Status = Model.CommunicationStatus.Transient;

                    if ( rockPage.CurrentPerson != null )
                    {
                        communication.SenderPersonId = rockPage.CurrentPerson.Id;
                    }

                    OnGridRebind( e );

                    if ( this.DataSource is DataTable || this.DataSource is DataView )
                    {
                        communication.AdditionalMergeFields = CommunicateMergeFields;

                        DataTable data = null;

                        if ( this.DataSource is DataTable )
                        {
                            data = (DataTable)this.DataSource;
                        }
                        else if ( this.DataSource is DataView )
                        {
                            data = ( (DataView)this.DataSource ).Table;
                        }

                        foreach ( DataRow row in data.Rows )
                        {
                            int? personId = null;
                            var mergeValues = new Dictionary<string, string>();
                            for ( int i = 0; i < data.Columns.Count; i++ )
                            {
                                if ( data.Columns[i].ColumnName == this.PersonIdField )
                                {
                                    personId = row[i] as int?;
                                }

                                if ( CommunicateMergeFields.Contains( data.Columns[i].ColumnName ) )
                                {
                                    mergeValues.Add( data.Columns[i].ColumnName, row[i].ToString() );
                                }
                            }

                            // If valid personid and either no people were selected or this person was selected add them as a recipient
                            if ( personId.HasValue && ( !peopleSelected.Any() || peopleSelected.Contains( personId.Value ) ) )
                            {
                                var recipient = new Rock.Model.CommunicationRecipient();
                                recipient.PersonId = personId.Value;
                                recipient.AdditionalMergeValues = mergeValues;
                                communication.Recipients.Add( recipient );
                            }
                        }
                    }
                    else
                    {
                        CommunicateMergeFields.ForEach( f => communication.AdditionalMergeFields.Add( f.Replace( '.', '_' ) ) );

                        // get access to the List<> and its properties
                        IList data = (IList)this.DataSource;
                        Type oType = data.GetType().GetProperty( "Item" ).PropertyType;

                        PropertyInfo idProp = oType.GetProperty( this.PersonIdField );
                        foreach ( var item in data )
                        {
                            if ( idProp == null )
                            {
                                idProp = item.GetType().GetProperty( this.PersonIdField );
                            }
                            if ( idProp != null )
                            {
                                int personId = (int)idProp.GetValue( item, null );
                                if ( !peopleSelected.Any() || peopleSelected.Contains( personId ) )
                                {
                                    var recipient = new Rock.Model.CommunicationRecipient();
                                    recipient.PersonId = personId;

                                    foreach ( string mergeField in CommunicateMergeFields )
                                    {
                                        object obj = item.GetPropertyValue( mergeField );
                                        if ( obj != null )
                                        {
                                            recipient.AdditionalMergeValues.Add( mergeField.Replace( '.', '_' ), obj.ToString() );
                                        }
                                    }

                                    communication.Recipients.Add( recipient );
                                }
                            }
                        }
                        
                        if (idProp == null)
                        {
                            // Couldn't determine data source, at least add recipients for any selected people
                            foreach ( int personId in peopleSelected )
                            {
                                var recipient = new Rock.Model.CommunicationRecipient();
                                recipient.PersonId = personId;
                                communication.Recipients.Add( recipient );
                            }
                        }
                    }

                    if ( communication.Recipients.Any() )
                    {
                        var rockContext = new RockContext();
                        var service = new Rock.Model.CommunicationService( rockContext );
                        service.Add( communication );
                        rockContext.SaveChanges();

                        Page.Response.Redirect( string.Format( CommunicationPageRoute, communication.Id ), false );
                        Context.ApplicationInstance.CompleteRequest();
                    }
                }
            }
        }