/// <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 nowDate = RockDateTime.Now; var rockContext = new RockContext(); var qryPendingRecipients = new CommunicationRecipientService( rockContext ).Queryable().Where( a => a.Status == CommunicationRecipientStatus.Pending ); var qry = new CommunicationService( rockContext ).Queryable() .Where( c => c.Status == CommunicationStatus.Approved && qryPendingRecipients.Where( r => r.CommunicationId == c.Id ).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( nowDate ) <= 0 ) ) ); var exceptionMsgs = new List<string>(); int communicationsSent = 0; foreach ( var comm in qry.AsNoTracking().ToList() ) { try { var medium = comm.Medium; if ( medium != null && medium.IsActive ) { medium.Send( comm ); communicationsSent++; } } catch ( Exception ex ) { exceptionMsgs.Add( string.Format( "Exception occurred sending communication ID:{0}:{1} {2}", comm.Id, Environment.NewLine, ex.Messages().AsDelimited( Environment.NewLine + " " ) ) ); ExceptionLogService.LogException( ex, System.Web.HttpContext.Current ); } } if ( communicationsSent > 0 ) { context.Result = string.Format( "Sent {0} {1}", communicationsSent, "communication".PluralizeIf( communicationsSent > 1 ) ); } else { context.Result = "No communications to send"; } if ( exceptionMsgs.Any() ) { throw new Exception( "One or more exceptions occurred sending communications..." + Environment.NewLine + exceptionMsgs.AsDelimited( Environment.NewLine ) ); } // check for communications that have not been sent but are past the expire date. Mark them as failed and set a warning. var qryExpired = new CommunicationService( rockContext ).Queryable() .Where( c => c.Status == CommunicationStatus.Approved && qryPendingRecipients.Where( r => r.CommunicationId == c.Id ).Any() && ( (!c.FutureSendDateTime.HasValue && c.CreatedDateTime.HasValue && c.CreatedDateTime.Value.CompareTo( beginWindow ) < 0 ) || (c.FutureSendDateTime.HasValue && c.FutureSendDateTime.Value.CompareTo( beginWindow ) < 0 ) ) ); foreach ( var comm in qryExpired.ToList() ) { foreach ( var recipient in comm.Recipients.Where( r => r.Status == CommunicationRecipientStatus.Pending ) ) { recipient.Status = CommunicationRecipientStatus.Failed; recipient.StatusNote = "Communication was not sent before the expire window (possibly due to delayed approval)."; rockContext.SaveChanges(); } } }