Ejemplo n.º 1
0
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            var          systemEmailService = new SystemEmailService(new RockContext());
            SortProperty sortProperty       = gEmailTemplates.SortProperty;

            var systemEmails = systemEmailService.Queryable("Category");

            int?categoryId = rFilter.GetUserPreference("Category").AsIntegerOrNull();

            if (categoryId.HasValue)
            {
                systemEmails = systemEmails.Where(a => a.CategoryId.HasValue && a.CategoryId.Value == categoryId.Value);
            }

            if (sortProperty != null)
            {
                gEmailTemplates.DataSource = systemEmails.Sort(sortProperty).ToList();
            }
            else
            {
                gEmailTemplates.DataSource = systemEmails.OrderBy(a => a.Category.Name).ThenBy(a => a.Title).ToList();
            }

            gEmailTemplates.EntityTypeId = EntityTypeCache.Get <Rock.Model.SystemEmail>().Id;
            gEmailTemplates.DataBind();
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Initializes a new instance of the <see cref="RockEmailMessage" /> class.
        /// </summary>
        /// <param name="systemGuid">The system communication unique identifier.</param>
        public RockEmailMessage(Guid systemGuid) : this()
        {
            using (var rockContext = new RockContext())
            {
                var systemCommunication = new SystemCommunicationService(rockContext).Get(systemGuid);

                if (systemCommunication != null)
                {
                    InitEmailMessage(systemCommunication);
                }
                else
                {
                    // If a matching SystemCommunication could not be found, check if this is a reference to a legacy SystemEmail object.
                    // This is necessary to provide backward-compatibility for third-party plugins.
#pragma warning disable CS0618 // Type or member is obsolete
                    var systemEmail = new SystemEmailService(rockContext).Get(systemGuid);
#pragma warning restore CS0618 // Type or member is obsolete

                    if (systemEmail != null)
                    {
#pragma warning disable CS0612 // Type or member is obsolete
                        InitEmailMessage(systemEmail);
#pragma warning restore CS0612 // Type or member is obsolete
                    }
                }
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Sends the specified email template unique identifier.
        /// </summary>
        /// <param name="emailTemplateGuid">The email template unique identifier.</param>
        /// <param name="recipients">The recipients.</param>
        /// <param name="appRoot">The application root.</param>
        /// <param name="themeRoot">The theme root.</param>
        public static void Send( Guid emailTemplateGuid, List<RecipientData> recipients, string appRoot = "", string themeRoot = "" )
        {
            try
            {
                if ( recipients != null && recipients.Any() )
                {

                    var mediumEntity = EntityTypeCache.Read( Rock.SystemGuid.EntityType.COMMUNICATION_MEDIUM_EMAIL.AsGuid() );
                    if ( mediumEntity != null )
                    {
                        var medium = MediumContainer.GetComponent( mediumEntity.Name );
                        if ( medium != null && medium.IsActive )
                        {
                            var transport = medium.Transport;
                            if ( transport != null && transport.IsActive )
                            {
                                using ( var rockContext = new RockContext() )
                                {
                                    var template = new SystemEmailService( rockContext ).Get( emailTemplateGuid );
                                    if ( template != null )
                                    {
                                        try
                                        {
                                            transport.Send( template, recipients, appRoot, themeRoot );
                                        }
                                        catch ( Exception ex1 )
                                        {
                                            throw new Exception( string.Format( "Error sending System Email ({0}).", template.Title ), ex1 );
                                        }
                                    }
                                    else
                                    {
                                        throw new Exception( string.Format( "Error sending System Email: An invalid System Email Identifier was provided ({0}).", emailTemplateGuid.ToString() ) );
                                    }
                                }
                            }
                            else
                            {
                                throw new Exception( string.Format( "Error sending System Email: The '{0}' medium does not have a valid transport, or the transport is not active.", mediumEntity.FriendlyName ) );
                            }
                        }
                        else
                        {
                            throw new Exception( string.Format( "Error sending System Email: The '{0}' medium does not exist, or is not active (type: {1}).", mediumEntity.FriendlyName, mediumEntity.Name ) );
                        }
                    }
                    else
                    {
                        throw new Exception( "Error sending System Email: Could not read Email Medium Entity Type" );
                    }
                }
            }
            catch ( Exception ex )
            {
                ExceptionLogService.LogException( ex, HttpContext.Current );
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Sets the type of the workflow action.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <param name="workflowTypeAttributes">The workflow type attributes.</param>
        public void SetWorkflowActionType(WorkflowActionType value, Dictionary <Guid, Rock.Model.Attribute> workflowTypeAttributes)
        {
            EnsureChildControls();
            _hfActionTypeGuid.Value = value.Guid.ToString();

            _ddlCriteriaAttribute.Items.Clear();
            _ddlCriteriaAttribute.Items.Add(new ListItem());

            _tbddlCriteriaValue.DropDownList.Items.Clear();
            _tbddlCriteriaValue.DropDownList.Items.Add(new ListItem());
            foreach (var attribute in workflowTypeAttributes)
            {
                var li = new ListItem(attribute.Value.Name, attribute.Key.ToString());
                li.Selected = value.CriteriaAttributeGuid.HasValue && value.CriteriaAttributeGuid.Value.ToString() == li.Value;
                _ddlCriteriaAttribute.Items.Add(li);

                _tbddlCriteriaValue.DropDownList.Items.Add(new ListItem(attribute.Value.Name, attribute.Key.ToString()));
            }

            _ddlCriteriaComparisonType.SetValue(value.CriteriaComparisonType.ConvertToInt());
            _tbddlCriteriaValue.SelectedValue = value.CriteriaValue;

            _tbActionTypeName.Text = value.Name;
            _wfatpEntityType.SetValue(EntityTypeCache.Get(value.EntityTypeId));
            _cbIsActivityCompletedOnSuccess.Checked = value.IsActivityCompletedOnSuccess;

            var entityType = EntityTypeCache.Get(value.EntityTypeId);

            if (entityType != null && entityType.Name == typeof(Rock.Workflow.Action.UserEntryForm).FullName)
            {
                if (value.WorkflowForm == null)
                {
                    value.WorkflowForm         = new WorkflowActionForm();
                    value.WorkflowForm.Actions = "Submit^^^Your information has been submitted successfully.";
                    var systemEmail = new SystemEmailService(new RockContext()).Get(SystemGuid.SystemEmail.WORKFLOW_FORM_NOTIFICATION.AsGuid());
                    if (systemEmail != null)
                    {
                        value.WorkflowForm.NotificationSystemEmailId = systemEmail.Id;
                    }
                }
                _formEditor.SetForm(value.WorkflowForm, workflowTypeAttributes);
                _cbIsActionCompletedOnSuccess.Checked = true;
                _cbIsActionCompletedOnSuccess.Enabled = false;
            }
            else
            {
                _formEditor.SetForm(null, workflowTypeAttributes);
                _cbIsActionCompletedOnSuccess.Checked = value.IsActionCompletedOnSuccess;
                _cbIsActionCompletedOnSuccess.Enabled = true;
            }

            _phActionAttributes.Controls.Clear();
            Rock.Attribute.Helper.AddEditControls(value, _phActionAttributes, true, ValidationGroup, new List <string>()
            {
                "Active", "Order"
            });
        }
Ejemplo n.º 5
0
 /// <summary>
 /// Sends the specified email template unique identifier.
 /// </summary>
 /// <param name="emailTemplateGuid">The email template unique identifier.</param>
 /// <param name="recipients">The recipients.</param>
 /// <param name="appRoot">The application root.</param>
 /// <param name="themeRoot">The theme root.</param>
 public static void Send(Guid emailTemplateGuid, List <RecipientData> recipients, string appRoot = "", string themeRoot = "")
 {
     try
     {
         if (recipients != null && recipients.Any())
         {
             var mediumEntity = EntityTypeCache.Read(Rock.SystemGuid.EntityType.COMMUNICATION_MEDIUM_EMAIL.AsGuid());
             if (mediumEntity != null)
             {
                 var medium = MediumContainer.GetComponent(mediumEntity.Name);
                 if (medium != null && medium.IsActive)
                 {
                     var transport = medium.Transport;
                     if (transport != null && transport.IsActive)
                     {
                         using (var rockContext = new RockContext())
                         {
                             var template = new SystemEmailService(rockContext).Get(emailTemplateGuid);
                             if (template != null)
                             {
                                 try
                                 {
                                     transport.Send(template, recipients, appRoot, themeRoot);
                                 }
                                 catch (Exception ex1)
                                 {
                                     throw new Exception(string.Format("Error sending System Email ({0}).", template.Title), ex1);
                                 }
                             }
                             else
                             {
                                 throw new Exception(string.Format("Error sending System Email: An invalid System Email Identifier was provided ({0}).", emailTemplateGuid.ToString()));
                             }
                         }
                     }
                     else
                     {
                         throw new Exception(string.Format("Error sending System Email: The '{0}' medium does not have a valid transport, or the transport is not active.", mediumEntity.FriendlyName));
                     }
                 }
                 else
                 {
                     throw new Exception(string.Format("Error sending System Email: The '{0}' medium does not exist, or is not active (type: {1}).", mediumEntity.FriendlyName, mediumEntity.Name));
                 }
             }
             else
             {
                 throw new Exception("Error sending System Email: Could not read Email Medium Entity Type");
             }
         }
     }
     catch (Exception ex)
     {
         ExceptionLogService.LogException(ex, HttpContext.Current);
     }
 }
        public void Execute(IJobExecutionContext context)
        {
            // Get job settings
            var dataMap         = context.JobDetail.JobDataMap;
            var systemEmailGuid = dataMap.GetString("Email").AsGuidOrNull();
            var groupGuid       = dataMap.GetString("Group").AsGuidOrNull();
            var previousMinutes = dataMap.GetString("PreviousMinutes").AsIntegerOrNull();

            // Ensure job settings aren't null
            if (systemEmailGuid == null || previousMinutes == null || groupGuid == null)
            {
                throw new Exception("Missing one or more job settings.");
            }

            var rockContext = new RockContext();

            var systemEmail = new SystemEmailService(rockContext).Get(systemEmailGuid.Value);
            var group       = new GroupService(rockContext).Get(groupGuid.Value);

            if (systemEmail == null || group == null)
            {
                throw new Exception("One or more job settings incorrect.");
            }

            string appRoot      = Rock.Web.Cache.GlobalAttributesCache.Read().GetValue("ExternalApplicationRoot");
            var    cutOffBegins = RockDateTime.Now.AddMinutes(-previousMinutes.Value);

            var scheduledTransactions = new FinancialScheduledTransactionService(rockContext)
                                        .Queryable("FinancialPaymentDetail")
                                        .Where(s => s.IsActive && s.CreatedDateTime >= cutOffBegins)
                                        .ToList();

            if (scheduledTransactions.Count > 1)
            {
                foreach (var groupMember in group.Members)
                {
                    var mergeFields = new Dictionary <string, object> {
                        { "Transactions", scheduledTransactions }
                    };

                    var recipients = new List <string>()
                    {
                        groupMember.Person.Email
                    };

                    Email.Send(systemEmail.From.ResolveMergeFields(mergeFields), systemEmail.FromName.ResolveMergeFields(mergeFields), systemEmail.Subject.ResolveMergeFields(mergeFields), recipients, systemEmail.Body.ResolveMergeFields(mergeFields), appRoot, null);
                }
                context.Result = string.Format("{0} transactions were sent ", scheduledTransactions.Count());
            }
            else
            {
                context.Result = "No new transactions to send.";
            }
        }
Ejemplo n.º 7
0
 /// <summary>
 /// Sends the specified email template unique identifier.
 /// </summary>
 /// <param name="emailTemplateGuid">The email template unique identifier.</param>
 /// <param name="recipients">The recipients.</param>
 /// <param name="appRoot">The application root.</param>
 /// <param name="themeRoot">The theme root.</param>
 public static void Send( Guid emailTemplateGuid, Dictionary<string, Dictionary<string, object>> recipients, string appRoot = "", string themeRoot = "" )
 {
     try
     {
         if ( recipients != null && recipients.Any() )
         {
             var channelEntity = EntityTypeCache.Read( Rock.SystemGuid.EntityType.COMMUNICATION_CHANNEL_EMAIL.AsGuid() );
             if ( channelEntity != null )
             {
                 var channel = ChannelContainer.GetComponent( channelEntity.Name );
                 if ( channel != null && channel.IsActive )
                 {
                     var transport = channel.Transport;
                     if ( transport != null && transport.IsActive )
                     {
                         var template = new SystemEmailService( new RockContext() ).Get( emailTemplateGuid );
                         if ( template != null )
                         {
                             try
                             {
                                 transport.Send( template, recipients, appRoot, themeRoot );
                             }
                             catch(Exception ex1)
                             {
                                 throw new Exception( string.Format( "Error sending System Email ({0}).", template.Title ), ex1 );
                             }
                         }
                         else
                         {
                             throw new Exception( string.Format( "Error sending System Email: An invalid System Email Identifier was provided ({0}).", emailTemplateGuid.ToString() ) );
                         }
                     }
                     else
                     {
                         throw new Exception(string.Format("Error sending System Email: The '{0}' channel does not have a valid transport, or the transport is not active.", channelEntity.FriendlyName));
                     }
                 }
                 else
                 {
                     throw new Exception(string.Format("Error sending System Email: The '{0}' channel does not exist, or is not active (type: {1}).", channelEntity.FriendlyName, channelEntity.Name));
                 }
             }
             else
             {
                 throw new Exception("Error sending System Email: Could not read Email Channel Entity Type");
             }
         }
     }
     catch ( Exception ex )
     {
         ExceptionLogService.LogException( ex, HttpContext.Current );
     }
 }
Ejemplo n.º 8
0
        /// <summary>
        /// Shows the edit.
        /// </summary>
        /// <param name="emailTemplateId">The email template id.</param>
        protected void ShowEdit(int emailTemplateId)
        {
            var globalAttributes = GlobalAttributesCache.Get();

            string globalFromName = globalAttributes.GetValue("OrganizationName");

            tbFromName.Help = string.Format("If a From Name value is not entered the 'Organization Name' Global Attribute value of '{0}' will be used when this template is sent. <small><span class='tip tip-lava'></span></small>", globalFromName);

            string globalFrom = globalAttributes.GetValue("OrganizationEmail");

            tbFrom.Help = string.Format("If a From Address value is not entered the 'Organization Email' Global Attribute value of '{0}' will be used when this template is sent. <small><span class='tip tip-lava'></span></small>", globalFrom);

            tbTo.Help = "You can specify multiple email addresses by separating them with commas or semi-colons.";

            SystemEmailService emailTemplateService = new SystemEmailService(new RockContext());
            SystemEmail        emailTemplate        = emailTemplateService.Get(emailTemplateId);

            if (emailTemplate != null)
            {
                pdAuditDetails.Visible = true;
                pdAuditDetails.SetEntity(emailTemplate, ResolveRockUrl("~"));

                lActionTitle.Text       = ActionTitle.Edit(SystemEmail.FriendlyTypeName).FormatAsHtmlTitle();
                hfEmailTemplateId.Value = emailTemplate.Id.ToString();

                cpCategory.SetValue(emailTemplate.CategoryId);
                tbTitle.Text    = emailTemplate.Title;
                tbFromName.Text = emailTemplate.FromName;
                tbFrom.Text     = emailTemplate.From;
                tbTo.Text       = emailTemplate.To;
                tbCc.Text       = emailTemplate.Cc;
                tbBcc.Text      = emailTemplate.Bcc;
                tbSubject.Text  = emailTemplate.Subject;
                tbBody.Text     = emailTemplate.Body;
            }
            else
            {
                pdAuditDetails.Visible  = false;
                lActionTitle.Text       = ActionTitle.Add(SystemEmail.FriendlyTypeName).FormatAsHtmlTitle();
                hfEmailTemplateId.Value = 0.ToString();

                cpCategory.SetValue((int?)null);
                tbTitle.Text    = string.Empty;
                tbFromName.Text = string.Empty;
                tbFrom.Text     = string.Empty;
                tbTo.Text       = string.Empty;
                tbCc.Text       = string.Empty;
                tbBcc.Text      = string.Empty;
                tbSubject.Text  = string.Empty;
                tbBody.Text     = string.Empty;
            }
        }
        /// <summary>
        /// Handles the Delete event of the gEmailTemplates control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RowEventArgs" /> instance containing the event data.</param>
        protected void gEmailTemplates_Delete( object sender, RowEventArgs e )
        {
            var rockContext = new RockContext();
            SystemEmailService emailTemplateService = new SystemEmailService( rockContext );
            SystemEmail emailTemplate = emailTemplateService.Get( (int)gEmailTemplates.DataKeys[e.RowIndex]["id"] );
            if ( emailTemplate != null )
            {
                emailTemplateService.Delete( emailTemplate );
                rockContext.SaveChanges();
            }

            BindGrid();
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Handles the Delete event of the gEmailTemplates control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RowEventArgs" /> instance containing the event data.</param>
        protected void gEmailTemplates_Delete(object sender, RowEventArgs e)
        {
            var rockContext = new RockContext();
            SystemEmailService emailTemplateService = new SystemEmailService(rockContext);
            SystemEmail        emailTemplate        = emailTemplateService.Get(e.RowKeyId);

            if (emailTemplate != null)
            {
                emailTemplateService.Delete(emailTemplate);
                rockContext.SaveChanges();
            }

            BindGrid();
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Sends the welcome email.
        /// </summary>
        /// <param name="systemEmailId">The system email identifier.</param>
        /// <param name="personId">The person identifier.</param>
        /// <param name="syncGroup">The synchronize group.</param>
        /// <param name="createLogin">if set to <c>true</c> [create login].</param>
        /// <param name="requirePasswordReset">if set to <c>true</c> [require password reset].</param>
        private void SendWelcomeEmail(int systemEmailId, int personId, Group syncGroup, bool createLogin, bool requirePasswordReset)
        {
            using (var rockContext = new RockContext())
            {
                SystemEmailService emailService = new SystemEmailService(rockContext);

                var systemEmail = emailService.Get(systemEmailId);

                if (systemEmail != null)
                {
                    string newPassword = string.Empty;

                    var recipients = new List <RecipientData>();

                    var mergeFields = new Dictionary <string, object>();
                    mergeFields.Add("Group", syncGroup);

                    // get person
                    var recipient = new PersonService(rockContext).Queryable("Users").Where(p => p.Id == personId).FirstOrDefault();

                    if (!string.IsNullOrWhiteSpace(recipient.Email))
                    {
                        if (createLogin && recipient.Users.Count == 0)
                        {
                            newPassword = System.Web.Security.Membership.GeneratePassword(9, 1);

                            // create user
                            string username = Rock.Security.Authentication.Database.GenerateUsername(recipient.NickName, recipient.LastName);

                            UserLogin login = UserLoginService.Create(
                                rockContext,
                                recipient,
                                Rock.Model.AuthenticationServiceType.Internal,
                                EntityTypeCache.Read(Rock.SystemGuid.EntityType.AUTHENTICATION_DATABASE.AsGuid()).Id,
                                username,
                                newPassword,
                                true,
                                requirePasswordReset);
                        }
                        mergeFields.Add("Person", recipient);
                        mergeFields.Add("NewPassword", newPassword);
                        mergeFields.Add("CreateLogin", createLogin);
                        recipients.Add(new RecipientData(recipient.Email, mergeFields));

                        var appRoot = Rock.Web.Cache.GlobalAttributesCache.Read(rockContext).GetValue("ExternalApplicationRoot");
                        Email.Send(systemEmail.Guid, recipients, appRoot);
                    }
                }
            }
        }
        /// <summary>
        /// Returns the field's current value(s)
        /// </summary>
        /// <param name="parentControl">The parent control.</param>
        /// <param name="value">Information about the value</param>
        /// <param name="configurationValues">The configuration values.</param>
        /// <param name="condensed">Flag indicating if the value should be condensed (i.e. for use in a grid column)</param>
        /// <returns></returns>
        public override string FormatValue( Control parentControl, string value, Dictionary<string, ConfigurationValue> configurationValues, bool condensed )
        {
            string formattedValue = string.Empty;

            Guid guid = Guid.Empty;
            if ( Guid.TryParse( value, out guid ) )
            {
                var systemEmail = new SystemEmailService( new RockContext() ).Get( guid );
                if ( systemEmail != null )
                {
                    formattedValue = systemEmail.Title;
                }
            }

            return base.FormatValue( parentControl, formattedValue, null, condensed );
        }
Ejemplo n.º 13
0
        private void SendReceipt()
        {
            RockContext rockContext  = new RockContext();
            var         receiptEmail = new SystemEmailService(rockContext).Get(new Guid(GetAttributeValue("ReceiptEmail")));

            if (receiptEmail != null)
            {
                var givingUnit = new PersonAliasService(rockContext).Get(this.SelectedGivingUnit.PersonAliasId).Person;

                var emailMessage = new RockEmailMessage(receiptEmail.Guid);
                emailMessage.AddRecipient(new RecipientData(givingUnit.Email, GetMergeFields(givingUnit)));
                emailMessage.AppRoot   = ResolveRockUrl("~/");
                emailMessage.ThemeRoot = ResolveRockUrl("~~/");
                emailMessage.Send();
            }
        }
        private void SendReceipt()
        {
            RockContext rockContext  = new RockContext();
            var         receiptEmail = new SystemEmailService(rockContext).Get(new Guid(GetAttributeValue("ReceiptEmail")));

            if (receiptEmail != null)
            {
                var givingUnit = new PersonAliasService(rockContext).Get(this.SelectedGivingUnit.PersonAliasId).Person;
                var appRoot    = Rock.Web.Cache.GlobalAttributesCache.Read(rockContext).GetValue("ExternalApplicationRoot");

                var recipients = new List <RecipientData>();
                recipients.Add(new RecipientData(givingUnit.Email, GetMergeFields(givingUnit)));

                Email.Send(receiptEmail.Guid, recipients, appRoot);
            }
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Gets the type of the workflow action.
        /// </summary>
        /// <returns></returns>
        public WorkflowActionType GetWorkflowActionType(bool expandInvalid)
        {
            EnsureChildControls();
            WorkflowActionType result = new WorkflowActionType();

            result.Guid = new Guid(_hfActionTypeGuid.Value);

            result.CriteriaAttributeGuid  = _ddlCriteriaAttribute.SelectedValueAsGuid();
            result.CriteriaComparisonType = _ddlCriteriaComparisonType.SelectedValueAsEnum <ComparisonType>();
            result.CriteriaValue          = _tbddlCriteriaValue.SelectedValue;

            result.Name         = _tbActionTypeName.Text;
            result.EntityTypeId = _wfatpEntityType.SelectedValueAsInt() ?? 0;
            result.IsActionCompletedOnSuccess   = _cbIsActionCompletedOnSuccess.Checked;
            result.IsActivityCompletedOnSuccess = _cbIsActivityCompletedOnSuccess.Checked;

            var entityType = EntityTypeCache.Get(result.EntityTypeId);

            if (entityType != null && entityType.Name == typeof(Rock.Workflow.Action.UserEntryForm).FullName)
            {
                result.WorkflowForm = _formEditor.GetForm();
                if (result.WorkflowForm == null)
                {
                    result.WorkflowForm         = new WorkflowActionForm();
                    result.WorkflowForm.Actions = "Submit^^^Your information has been submitted successfully.";
                    var systemEmail = new SystemEmailService(new RockContext()).Get(SystemGuid.SystemEmail.WORKFLOW_FORM_NOTIFICATION.AsGuid());
                    if (systemEmail != null)
                    {
                        result.WorkflowForm.NotificationSystemEmailId = systemEmail.Id;
                    }
                }
            }
            else
            {
                result.WorkflowForm = null;
            }

            result.LoadAttributes();
            Rock.Attribute.Helper.GetEditValues(_phActionAttributes, result);

            if (expandInvalid && !result.IsValid)
            {
                Expanded = true;
            }

            return(result);
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Creates the control(s) neccessary for prompting user for a new value
        /// </summary>
        /// <param name="configurationValues">The configuration values.</param>
        /// <param name="id"></param>
        /// <returns>
        /// The control
        /// </returns>
        public override Control EditControl(Dictionary<string,ConfigurationValue> configurationValues, string id)
        {
            var editControl = new RockDropDownList { ID = id };

            var systemEmails = new SystemEmailService( new RockContext() ).Queryable().OrderBy( e => e.Title );
            if ( systemEmails.Any() )
            {
                foreach ( var systemEmail in systemEmails )
                {
                    editControl.Items.Add( new ListItem( systemEmail.Title, systemEmail.Guid.ToString() ) );
                }

                return editControl;
            }

            return null;
        }
        private void BindData()
        {
            RockContext rockContext = new RockContext();

            dvpRefundReason.DefinedTypeId = DefinedTypeCache.Get(Rock.SystemGuid.DefinedType.FINANCIAL_TRANSACTION_REFUND_REASON.AsGuid(), rockContext).Id;

            if (!ddlSystemEmail.SelectedValueAsInt().HasValue)
            {
                SystemEmailService systemEmailService = new SystemEmailService(rockContext);
                var systemEmails = systemEmailService.Queryable().Select(e => new { Title = e.Category.Name + " - " + e.Title, e.Id }).OrderBy(e => e.Title).ToList();
                systemEmails.Insert(0, new { Title = "", Id = 0 });
                ddlSystemEmail.DataSource     = systemEmails;
                ddlSystemEmail.DataValueField = "Id";
                ddlSystemEmail.DataTextField  = "Title";
                ddlSystemEmail.DataBind();
            }

            List <int> registrationTemplateIds = rtpRegistrationTemplate.ItemIds.AsIntegerList();

            registrationTemplateIds.RemoveAll(i => i.Equals(0));

            if (registrationTemplateIds.Count > 0)
            {
                RegistrationTemplateService registrationTemplateService = new RegistrationTemplateService(rockContext);
                var templates = registrationTemplateService.GetByIds(rtpRegistrationTemplate.ItemIds.AsIntegerList());
                var instances = templates.SelectMany(t => t.Instances);
                if (ddlRegistrationInstance.SelectedValueAsId().HasValue&& ddlRegistrationInstance.SelectedValueAsId() > 0)
                {
                    var instanceId = ddlRegistrationInstance.SelectedValueAsId();
                    instances = instances.Where(i => i.Id == instanceId);
                }
                int registrationCount = instances.SelectMany(i => i.Registrations).Count();
                var totalPayments     = instances.SelectMany(i => i.Registrations).ToList().SelectMany(r => r.Payments).Sum(p => p.Transaction.TotalAmount);
                lAlert.Text = registrationCount + " Registrations - " + totalPayments.FormatAsCurrency() + " Total";

                if (!ddlRegistrationInstance.SelectedValueAsInt().HasValue)
                {
                    var instanceList = templates.SelectMany(t => t.Instances).OrderBy(i => i.Name).Select(i => new { i.Id, i.Name }).ToList();
                    instanceList.Insert(0, new { Id = 0, Name = "" });
                    ddlRegistrationInstance.DataSource     = instanceList;
                    ddlRegistrationInstance.DataValueField = "Id";
                    ddlRegistrationInstance.DataTextField  = "Name";
                    ddlRegistrationInstance.DataBind();
                }
            }
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Returns the field's current value(s)
        /// </summary>
        /// <param name="parentControl">The parent control.</param>
        /// <param name="value">Information about the value</param>
        /// <param name="configurationValues">The configuration values.</param>
        /// <param name="condensed">Flag indicating if the value should be condensed (i.e. for use in a grid column)</param>
        /// <returns></returns>
        public override string FormatValue(Control parentControl, string value, Dictionary <string, ConfigurationValue> configurationValues, bool condensed)
        {
            string formattedValue = string.Empty;

            Guid guid = Guid.Empty;

            if (Guid.TryParse(value, out guid))
            {
                var systemEmail = new SystemEmailService(new RockContext()).Get(guid);
                if (systemEmail != null)
                {
                    formattedValue = systemEmail.Title;
                }
            }

            return(base.FormatValue(parentControl, formattedValue, null, condensed));
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Shows the edit.
        /// </summary>
        /// <param name="emailTemplateId">The email template id.</param>
        protected void ShowEdit(int emailTemplateId)
        {
            var globalAttributes = GlobalAttributesCache.Read();

            string globalFromName = globalAttributes.GetValue("OrganizationName");

            tbFromName.Help = string.Format("If a From Name value is not entered the 'Organization Name' Global Attribute value of '{0}' will be used when this template is sent.", globalFromName);

            string globalFrom = globalAttributes.GetValue("OrganizationEmail");

            tbFrom.Help = string.Format("If a From Address value is not entered the 'Organization Email' Global Attribute value of '{0}' will be used when this template is sent.", globalFrom);

            SystemEmailService emailTemplateService = new SystemEmailService(new RockContext());
            SystemEmail        emailTemplate        = emailTemplateService.Get(emailTemplateId);

            if (emailTemplate != null)
            {
                lActionTitle.Text       = ActionTitle.Edit(SystemEmail.FriendlyTypeName).FormatAsHtmlTitle();
                hfEmailTemplateId.Value = emailTemplate.Id.ToString();

                tbCategory.Text = emailTemplate.Category;
                tbTitle.Text    = emailTemplate.Title;
                tbFromName.Text = emailTemplate.FromName;
                tbFrom.Text     = emailTemplate.From;
                tbTo.Text       = emailTemplate.To;
                tbCc.Text       = emailTemplate.Cc;
                tbBcc.Text      = emailTemplate.Bcc;
                tbSubject.Text  = emailTemplate.Subject;
                tbBody.Text     = emailTemplate.Body;
            }
            else
            {
                lActionTitle.Text       = ActionTitle.Add(SystemEmail.FriendlyTypeName).FormatAsHtmlTitle();
                hfEmailTemplateId.Value = 0.ToString();

                tbCategory.Text = string.Empty;
                tbTitle.Text    = string.Empty;
                tbFromName.Text = string.Empty;
                tbFrom.Text     = string.Empty;
                tbTo.Text       = string.Empty;
                tbCc.Text       = string.Empty;
                tbBcc.Text      = string.Empty;
                tbSubject.Text  = string.Empty;
                tbBody.Text     = string.Empty;
            }
        }
Ejemplo n.º 20
0
        public static void Send(Guid emailTemplateGuid, List <RecipientData> recipients, string appRoot = "", string themeRoot = "", bool createCommunicationHistory = true)
        {
            using (var rockContext = new RockContext())
            {
                var template = new SystemEmailService(rockContext).Get(emailTemplateGuid);
                if (template != null)
                {
                    var errorMessages = new List <string>();

                    var message = new RockEmailMessage(template);
                    message.SetRecipients(recipients);
                    message.ThemeRoot = themeRoot;
                    message.AppRoot   = appRoot;
                    message.CreateCommunicationRecord = createCommunicationHistory;
                    message.Send(out errorMessages);
                }
            }
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Binds the filter.
        /// </summary>
        private void BindFilter()
        {
            ddlCategoryFilter.Items.Clear();
            ddlCategoryFilter.Items.Add(new ListItem(All.Text, All.Id.ToString()));

            SystemEmailService emailTemplateService = new SystemEmailService(new RockContext());
            var items = emailTemplateService.Queryable().
                        Where(a => a.Category.Trim() != "" && a.Category != null).
                        OrderBy(a => a.Category).
                        Select(a => a.Category.Trim()).
                        Distinct().ToList();

            foreach (var item in items)
            {
                ListItem li = new ListItem(item);
                li.Selected = (!Page.IsPostBack && rFilter.GetUserPreference("Category") == item);
                ddlCategoryFilter.Items.Add(li);
            }
        }
Ejemplo n.º 22
0
        /// <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 System Email";

            int? emailId = PageParameter( "EmailId" ).AsIntegerOrNull();
            if ( emailId.HasValue )
            {
                SystemEmail email = new SystemEmailService( new RockContext() ).Get( emailId.Value );
                if ( email != null )
                {
                    pageTitle = email.Title;
                    breadCrumbs.Add( new BreadCrumb( email.Title, pageReference ) );
                }
            }

            RockPage.Title = pageTitle;

            return breadCrumbs;
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Populate the drop down list as should be for block configuration.
        /// </summary>
        private void PopulateDropDown()
        {
            var rockContext = new RockContext();

            ddlEmail.Items.Clear();
            ddlEmail.Items.Add(new ListItem());

            if (GetAttributeValue("CommunicationType") == "System")
            {
                ltTitle.Text   = "Test System Email";
                ddlEmail.Label = "System Email";

                var emails = new SystemEmailService(rockContext)
                             .Queryable()
                             .OrderBy(c => c.Category.Name)
                             .ThenBy(c => c.Title);

                foreach (var email in emails)
                {
                    ddlEmail.Items.Add(new ListItem(string.Format("{0} > {1}", email.Category.Name, email.Title), email.Guid.ToString()));
                }
            }
            else
            {
                ltTitle.Text   = "Test Communication Template";
                ddlEmail.Label = "Communication Template";

                var entityTypeId = EntityTypeCache.Read("Rock.Communication.Medium.Email").Id;

                var emails = new CommunicationTemplateService(rockContext)
                             .Queryable()
                             .Where(c => c.MediumEntityTypeId == entityTypeId)
                             .OrderBy(c => c.Name);

                foreach (var email in emails)
                {
                    ddlEmail.Items.Add(new ListItem(email.Name, email.Guid.ToString()));
                }
            }
        }
Ejemplo n.º 24
0
        /// <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 System Email";

            int?emailId = PageParameter("EmailId").AsIntegerOrNull();

            if (emailId.HasValue)
            {
                SystemEmail email = new SystemEmailService(new RockContext()).Get(emailId.Value);
                if (email != null)
                {
                    pageTitle = email.Title;
                    breadCrumbs.Add(new BreadCrumb(email.Title, pageReference));
                }
            }

            RockPage.Title = pageTitle;

            return(breadCrumbs);
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            var rockContext = new RockContext();

            SystemEmailService emailTemplateService = new SystemEmailService(rockContext);
            SystemEmail        emailTemplate;

            int emailTemplateId = int.Parse(hfEmailTemplateId.Value);

            if (emailTemplateId == 0)
            {
                emailTemplate = new SystemEmail();
                emailTemplateService.Add(emailTemplate);
            }
            else
            {
                emailTemplate = emailTemplateService.Get(emailTemplateId);
            }

            emailTemplate.CategoryId = cpCategory.SelectedValueAsInt();
            emailTemplate.Title      = tbTitle.Text;
            emailTemplate.FromName   = tbFromName.Text;
            emailTemplate.From       = tbFrom.Text;
            emailTemplate.To         = tbTo.Text;
            emailTemplate.Cc         = tbCc.Text;
            emailTemplate.Bcc        = tbBcc.Text;
            emailTemplate.Subject    = tbSubject.Text;
            emailTemplate.Body       = tbBody.Text;

            if (!emailTemplate.IsValid)
            {
                // Controls will render the error messages
                return;
            }

            rockContext.SaveChanges();

            NavigateToParentPage();
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Creates the control(s) necessary for prompting user for a new value
        /// </summary>
        /// <param name="configurationValues">The configuration values.</param>
        /// <param name="id"></param>
        /// <returns>
        /// The control
        /// </returns>
        public override Control EditControl(Dictionary <string, ConfigurationValue> configurationValues, string id)
        {
            var editControl = new RockDropDownList {
                ID = id
            };

            var systemEmails = new SystemEmailService(new RockContext()).Queryable().OrderBy(e => e.Title);

            // add a blank for the first option
            editControl.Items.Add(new ListItem());

            if (systemEmails.Any())
            {
                foreach (var systemEmail in systemEmails)
                {
                    editControl.Items.Add(new ListItem(systemEmail.Title, systemEmail.Guid.ToString()));
                }

                return(editControl);
            }

            return(null);
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            SystemEmailService emailTemplateService = new SystemEmailService(new RockContext());
            SortProperty       sortProperty         = gEmailTemplates.SortProperty;

            var emailTemplates = emailTemplateService.Queryable();

            if (ddlCategoryFilter.SelectedValue != All.Id.ToString())
            {
                emailTemplates = emailTemplates.Where(a => a.Category.Trim() == ddlCategoryFilter.SelectedValue);
            }

            if (sortProperty != null)
            {
                gEmailTemplates.DataSource = emailTemplates.Sort(sortProperty).ToList();
            }
            else
            {
                gEmailTemplates.DataSource = emailTemplates.OrderBy(a => a.Category).ThenBy(a => a.Title).ToList();
            }

            gEmailTemplates.DataBind();
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Sends the exit email.
        /// </summary>
        /// <param name="systemEmailId">The system email identifier.</param>
        /// <param name="recipient">The recipient.</param>
        /// <param name="syncGroup">The synchronize group.</param>
        private void SendExitEmail(int systemEmailId, Person recipient, Group syncGroup)
        {
            if (!string.IsNullOrWhiteSpace(recipient.Email))
            {
                using (var rockContext = new RockContext())
                {
                    SystemEmailService emailService = new SystemEmailService(rockContext);

                    var systemEmail = emailService.Get(systemEmailId);

                    if (systemEmail != null)
                    {
                        var recipients  = new List <RecipientData>();
                        var mergeFields = new Dictionary <string, object>();
                        mergeFields.Add("Group", syncGroup);
                        mergeFields.Add("Person", recipient);
                        recipients.Add(new RecipientData(recipient.Email, mergeFields));

                        var appRoot = Rock.Web.Cache.GlobalAttributesCache.Read(rockContext).GetValue("ExternalApplicationRoot");
                        Email.Send(systemEmail.Guid, recipients, appRoot);
                    }
                }
            }
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Sends a notification that NCOA finished or failed
        /// </summary>
        /// <param name="sparkDataConfig">The spark data configuration.</param>
        /// <param name="status">The status to put in the notification.</param>
        public void SentNotification(SparkDataConfig sparkDataConfig, string status)
        {
            if (!sparkDataConfig.GlobalNotificationApplicationGroupId.HasValue || sparkDataConfig.GlobalNotificationApplicationGroupId.Value == 0)
            {
                return;
            }

            var recipients = new List <RecipientData>();

            using (RockContext rockContext = new RockContext())
            {
                Group group = new GroupService(rockContext).GetNoTracking(sparkDataConfig.GlobalNotificationApplicationGroupId.Value);

                foreach (var groupMember in group.Members)
                {
                    if (groupMember.GroupMemberStatus == GroupMemberStatus.Active)
                    {
                        var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(null);
                        mergeFields.Add("Person", groupMember.Person);
                        mergeFields.Add("GroupMember", groupMember);
                        mergeFields.Add("Group", groupMember.Group);
                        mergeFields.Add("SparkDataService", "National Change of Address (NCOA)");
                        mergeFields.Add("SparkDataConfig", sparkDataConfig);
                        mergeFields.Add("Status", status);
                        recipients.Add(new RecipientData(groupMember.Person.Email, mergeFields));
                    }
                }

                SystemEmailService emailService = new SystemEmailService(rockContext);
                SystemEmail        systemEmail  = emailService.GetNoTracking(SystemGuid.SystemEmail.SPARK_DATA_NOTIFICATION.AsGuid());

                var emailMessage = new RockEmailMessage(systemEmail.Guid);
                emailMessage.SetRecipients(recipients);
                emailMessage.Send();
            }
        }
        /// <summary>
        /// Executes the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        public void Execute( IJobExecutionContext context )
        {
            var rockContext = new RockContext();
            JobDataMap dataMap = context.JobDetail.JobDataMap;

            // Get the details for the email that we'll be sending out.
            Guid? systemEmailGuid = dataMap.GetString( "ExpiringCreditCardEmail" ).AsGuidOrNull();
            SystemEmailService emailService = new SystemEmailService( rockContext );
            SystemEmail systemEmail = null;

            if ( systemEmailGuid.HasValue )
            {
                systemEmail = emailService.Get( systemEmailGuid.Value );
            }

            // Fetch the configured Workflow once if one was set, we'll use it later.
            Guid? workflowGuid = dataMap.GetString( "Workflow" ).AsGuidOrNull();
            WorkflowType workflowType = null;
            var workflowTypeService = new WorkflowTypeService( rockContext );
            var workflowService = new WorkflowService( rockContext );

            if ( workflowGuid != null )
            {
                workflowType = workflowTypeService.Get( workflowGuid.Value );
            }

            var qry = new FinancialScheduledTransactionService( rockContext )
                .Queryable( "ScheduledTransactionDetails,FinancialPaymentDetail.CurrencyTypeValue,FinancialPaymentDetail.CreditCardTypeValue" )
                .Where( t => t.IsActive && t.FinancialPaymentDetail.ExpirationMonthEncrypted != null
                && ( t.EndDate == null || t.EndDate > DateTime.Now ) )
                .AsNoTracking();

            var appRoot = Rock.Web.Cache.GlobalAttributesCache.Read( rockContext ).GetValue( "PublicApplicationRoot" );

            // Get the current month and year
            DateTime now = DateTime.Now;
            int month = now.Month;
            int year = now.Year;
            int counter = 0;
            foreach ( var transaction in qry )
            {
                int expirationMonthDecrypted = Int32.Parse( Encryption.DecryptString( transaction.FinancialPaymentDetail.ExpirationMonthEncrypted ) );
                int expirationYearDecrypted = Int32.Parse( Encryption.DecryptString( transaction.FinancialPaymentDetail.ExpirationYearEncrypted ) );
                string acctNum = transaction.FinancialPaymentDetail.AccountNumberMasked.Substring( transaction.FinancialPaymentDetail.AccountNumberMasked.Length - 4 );

                int warningYear = expirationYearDecrypted;
                int warningMonth = expirationMonthDecrypted - 1;
                if ( warningMonth == 0 )
                {
                    warningYear -= 1;
                    warningMonth = 12;
                }

                string warningDate = warningMonth.ToString() + warningYear.ToString();
                string currentMonthString = month.ToString() + year.ToString();

                if ( warningDate == currentMonthString )
                {
                    // as per ISO7813 https://en.wikipedia.org/wiki/ISO/IEC_7813
                    var expirationDate = string.Format( "{0:D2}/{1:D2}", expirationMonthDecrypted, expirationYearDecrypted );

                    var recipients = new List<RecipientData>();
                    var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields( null );
                    var person = transaction.AuthorizedPersonAlias.Person;
                    mergeFields.Add( "Person", person );
                    mergeFields.Add( "Card", acctNum );
                    mergeFields.Add( "Expiring", expirationDate );
                    recipients.Add( new RecipientData( person.Email, mergeFields ) );

                    Email.Send( systemEmail.Guid, recipients, appRoot );

                    // Start workflow for this person
                    if ( workflowType != null )
                    {
                        Dictionary<string, string> attributes = new Dictionary<string, string>();
                        attributes.Add( "Person", transaction.AuthorizedPersonAlias.Guid.ToString() );
                        attributes.Add( "Card", acctNum );
                        attributes.Add( "Expiring", expirationDate );
                        StartWorkflow( workflowService, workflowType, attributes, string.Format( "{0} (scheduled transaction Id: {1})", person.FullName, transaction.Id ) );
                    }

                    counter++;
                }
            }

            context.Result = string.Format( "{0} scheduled credit card transactions were examined with {1} notice(s) sent.", qry.Count(), counter );
        }
        /// <summary>
        /// Starts the refund process.
        /// </summary>
        private void StartRefunds()
        {
            long totalMilliseconds = 0;


            var importTask = new Task(() =>
            {
                // wait a little so the browser can render and start listening to events
                System.Threading.Thread.Sleep(1000);
                _hubContext.Clients.All.showButtons(this.SignalRNotificationKey, false);

                Stopwatch stopwatch = Stopwatch.StartNew();

                List <int> registrationTemplateIds = rtpRegistrationTemplate.ItemIds.AsIntegerList();
                registrationTemplateIds.RemoveAll(i => i.Equals(0));

                if (registrationTemplateIds.Count > 0)
                {
                    RockContext rockContext            = new RockContext();
                    List <int> registrationInstanceIds = new List <int>();
                    if (ddlRegistrationInstance.SelectedValueAsId().HasValue&& ddlRegistrationInstance.SelectedValueAsId() > 0)
                    {
                        registrationInstanceIds.Add(ddlRegistrationInstance.SelectedValueAsId().Value);
                    }
                    else
                    {
                        RegistrationTemplateService registrationTemplateService = new RegistrationTemplateService(rockContext);
                        var templates         = registrationTemplateService.GetByIds(rtpRegistrationTemplate.ItemIds.AsIntegerList());
                        int registrationCount = templates.SelectMany(t => t.Instances).SelectMany(i => i.Registrations).Count();

                        registrationInstanceIds.AddRange(templates.SelectMany(t => t.Instances).OrderBy(i => i.Name).Select(i => i.Id));
                    }

                    RegistrationInstanceService registrationInstanceService = new RegistrationInstanceService(rockContext);
                    SystemEmailService systemEmailService = new SystemEmailService(rockContext);

                    // Load the registration instance and then iterate through all registrations.
                    var registrations = registrationInstanceService.Queryable().Where(ri => registrationInstanceIds.Contains(ri.Id)).SelectMany(ri => ri.Registrations);
                    int j             = 1;
                    foreach (Registration registration in registrations)
                    {
                        bool issuedRefund = false;
                        OnProgress("Processing registration refund " + j + " of " + registrations.Count());
                        foreach (var payment in registration.GetPayments(rockContext))
                        {
                            decimal refundAmount = payment.Amount + payment.Transaction.Refunds.Sum(r => r.FinancialTransaction.TotalAmount);

                            // If refunds totalling the amount of the payments have not already been issued
                            if (payment.Amount > 0 && refundAmount > 0)
                            {
                                string errorMessage;

                                using (var refundRockContext = new RockContext())
                                {
                                    var financialTransactionService = new FinancialTransactionService(refundRockContext);
                                    var refundTransaction           = financialTransactionService.ProcessRefund(payment.Transaction, refundAmount, dvpRefundReason.SelectedDefinedValueId, tbRefundSummary.Text, true, string.Empty, out errorMessage);

                                    if (refundTransaction != null)
                                    {
                                        refundRockContext.SaveChanges();
                                    }

                                    if (!string.IsNullOrWhiteSpace(errorMessage))
                                    {
                                        results["Fail"] += string.Format("Failed refund for registration {0}: {1}",
                                                                         registration.FirstName + " " + registration.LastName,
                                                                         errorMessage) + Environment.NewLine;
                                    }
                                    else
                                    {
                                        results["Success"] += string.Format("Successfully issued {0} refund for registration {1} payment {2} ({3}) - Refund Transaction Id: {4}, Amount: {5}",

                                                                            refundAmount < payment.Amount?"Partial":"Full",
                                                                            registration.FirstName + " " + registration.LastName,
                                                                            payment.Transaction.TransactionCode,
                                                                            payment.Transaction.TotalAmount,
                                                                            refundTransaction.TransactionCode,
                                                                            refundTransaction.TotalAmount.FormatAsCurrency()) + Environment.NewLine;
                                        issuedRefund = true;
                                    }
                                }
                                System.Threading.Thread.Sleep(2500);
                            }
                            else if (payment.Transaction.Refunds.Count > 0)
                            {
                                results["Success"] += string.Format("Refund already issued for registration {0} payment {1} ({2})",
                                                                    registration.FirstName + " " + registration.LastName,
                                                                    payment.Transaction.TransactionCode,
                                                                    payment.Transaction.TotalAmount) + Environment.NewLine;
                            }
                        }
                        j++;

                        // Send an email if applicable
                        if (issuedRefund && !string.IsNullOrWhiteSpace(registration.ConfirmationEmail) && ddlSystemEmail.SelectedValueAsInt().HasValue&& ddlSystemEmail.SelectedValueAsInt() > 0)
                        {
                            var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage);
                            mergeFields.Add("Registration", registration);

                            SystemEmail systemEmail = systemEmailService.Get(ddlSystemEmail.SelectedValueAsInt().Value);

                            var emailMessage = new RockEmailMessage(systemEmail);
                            emailMessage.AdditionalMergeFields = mergeFields;
                            emailMessage.AddRecipient(new RecipientData(registration.ConfirmationEmail, mergeFields));
                            emailMessage.CreateCommunicationRecord = true;
                            emailMessage.Send();
                        }
                    }
                }

                stopwatch.Stop();

                totalMilliseconds = stopwatch.ElapsedMilliseconds;

                _hubContext.Clients.All.showButtons(this.SignalRNotificationKey, true);
            });

            importTask.ContinueWith((t) =>
            {
                if (t.IsFaulted)
                {
                    foreach (var exception in t.Exception.InnerExceptions)
                    {
                        LogException(exception);
                    }

                    OnProgress("ERROR: " + t.Exception.Message);
                }
                else
                {
                    OnProgress(string.Format("{0} Complete: [{1}ms]", "All refunds have been issued.", totalMilliseconds));
                }
            });

            importTask.Start();
        }
        /// <summary>
        /// Job that will sync groups.
        ///
        /// Called by the <see cref="IScheduler" /> when a
        /// <see cref="ITrigger" /> fires that is associated with
        /// the <see cref="IJob" />.
        /// </summary>
        public virtual void Execute(IJobExecutionContext context)
        {
            JobDataMap dataMap = context.JobDetail.JobDataMap;

            try
            {
                int notificationsSent   = 0;
                int errorsEncountered   = 0;
                int pendingMembersCount = 0;

                // get groups set to sync
                RockContext rockContext = new RockContext();

                Guid?groupTypeGuid       = dataMap.GetString("GroupType").AsGuidOrNull();
                Guid?systemEmailGuid     = dataMap.GetString("NotificationEmail").AsGuidOrNull();
                Guid?groupRoleFilterGuid = dataMap.GetString("GroupRoleFilter").AsGuidOrNull();
                int? pendingAge          = dataMap.GetString("PendingAge").AsIntegerOrNull();


                bool includePreviouslyNotificed = dataMap.GetString("IncludePreviouslyNotified").AsBoolean();

                // get system email
                SystemEmailService emailService = new SystemEmailService(rockContext);

                SystemEmail systemEmail = null;
                if (!systemEmailGuid.HasValue || systemEmailGuid == Guid.Empty)
                {
                    context.Result = "Job failed. Unable to find System Email";
                    throw new Exception("No system email found.");
                }

                systemEmail = emailService.Get(systemEmailGuid.Value);

                // get group members
                if (!groupTypeGuid.HasValue || groupTypeGuid == Guid.Empty)
                {
                    context.Result = "Job failed. Unable to find group type";
                    throw new Exception("No group type found");
                }

                var qry = new GroupMemberService(rockContext).Queryable("Person, Group, Group.Members.GroupRole")
                          .Where(m => m.Group.GroupType.Guid == groupTypeGuid.Value &&
                                 m.GroupMemberStatus == GroupMemberStatus.Pending);

                if (!includePreviouslyNotificed)
                {
                    qry = qry.Where(m => m.IsNotified == false);
                }

                if (groupRoleFilterGuid.HasValue)
                {
                    qry = qry.Where(m => m.GroupRole.Guid == groupRoleFilterGuid.Value);
                }

                if (pendingAge.HasValue && pendingAge.Value > 0)
                {
                    var ageDate = RockDateTime.Now.AddDays(pendingAge.Value * -1);
                    qry = qry.Where(m => m.ModifiedDateTime > ageDate);
                }

                var pendingGroupMembers = qry.ToList();

                var groups = pendingGroupMembers.GroupBy(m => m.Group);

                var errorList = new List <string>();
                foreach (var groupKey in groups)
                {
                    var group = groupKey.Key;

                    // get list of pending people
                    var qryPendingIndividuals = group.Members.Where(m => m.GroupMemberStatus == GroupMemberStatus.Pending);

                    if (!includePreviouslyNotificed)
                    {
                        qryPendingIndividuals = qryPendingIndividuals.Where(m => m.IsNotified == false);
                    }

                    if (groupRoleFilterGuid.HasValue)
                    {
                        qryPendingIndividuals = qryPendingIndividuals.Where(m => m.GroupRole.Guid == groupRoleFilterGuid.Value);
                    }

                    var pendingIndividuals = qryPendingIndividuals.Select(m => m.Person).ToList();

                    if (!pendingIndividuals.Any())
                    {
                        continue;
                    }

                    // get list of leaders
                    var groupLeaders = group.Members.Where(m => m.GroupRole.IsLeader == true && m.Person != null && m.Person.Email != null && m.Person.Email != string.Empty);

                    if (!groupLeaders.Any())
                    {
                        errorList.Add("Unable to send emails to members in group " + group.Name + " because there is no group leader");
                        continue;
                    }

                    var recipients = new List <RecipientData>();
                    foreach (var leader in groupLeaders)
                    {
                        // create merge object
                        var mergeFields = new Dictionary <string, object>();
                        mergeFields.Add("PendingIndividuals", pendingIndividuals);
                        mergeFields.Add("Group", group);
                        mergeFields.Add("ParentGroup", group.ParentGroup);
                        mergeFields.Add("Person", leader.Person);
                        recipients.Add(new RecipientData(leader.Person.Email, mergeFields));
                    }


                    var errorMessages = new List <string>();
                    var emailMessage  = new RockEmailMessage(systemEmail.Guid);
                    emailMessage.SetRecipients(recipients);
                    emailMessage.Send(out errorMessages);

                    errorsEncountered += errorMessages.Count;
                    errorList.AddRange(errorMessages);

                    // be conservative: only mark as notified if we are sure the email didn't fail
                    if (errorMessages.Any())
                    {
                        continue;
                    }

                    notificationsSent += recipients.Count();
                    // mark pending members as notified as we go in case the job fails
                    var notifiedPersonIds = pendingIndividuals.Select(p => p.Id);
                    foreach (var pendingGroupMember in pendingGroupMembers.Where(m => m.IsNotified == false && notifiedPersonIds.Contains(m.PersonId)))
                    {
                        pendingGroupMember.IsNotified = true;
                    }

                    rockContext.SaveChanges();
                }

                context.Result = string.Format("Sent {0} emails to leaders for {1} pending individuals. {2} errors encountered.", notificationsSent, pendingMembersCount, errorsEncountered);
                if (errorList.Any())
                {
                    StringBuilder sb = new StringBuilder();
                    sb.AppendLine();
                    sb.Append("Errors: ");
                    errorList.ForEach(e => { sb.AppendLine(); sb.Append(e); });
                    string errors = sb.ToString();
                    context.Result += errors;
                    throw new Exception(errors);
                }
            }
            catch (Exception ex)
            {
                HttpContext context2 = HttpContext.Current;
                ExceptionLogService.LogException(ex, context2);
                throw;
            }
        }
        /// <summary>
        /// Gets the type of the workflow action.
        /// </summary>
        /// <returns></returns>
        public WorkflowActionType GetWorkflowActionType( bool expandInvalid )
        {
            EnsureChildControls();
            WorkflowActionType result = new WorkflowActionType();
            result.Guid = new Guid( _hfActionTypeGuid.Value );

            result.CriteriaAttributeGuid = _ddlCriteriaAttribute.SelectedValueAsGuid();
            result.CriteriaComparisonType = _ddlCriteriaComparisonType.SelectedValueAsEnum<ComparisonType>();
            result.CriteriaValue = _tbddlCriteriaValue.SelectedValue;

            result.Name = _tbActionTypeName.Text;
            result.EntityTypeId = _ddlEntityType.SelectedValueAsInt() ?? 0;
            result.IsActionCompletedOnSuccess = _cbIsActionCompletedOnSuccess.Checked;
            result.IsActivityCompletedOnSuccess = _cbIsActivityCompletedOnSuccess.Checked;

            var entityType = EntityTypeCache.Read( result.EntityTypeId );
            if ( entityType != null && entityType.Name == typeof( Rock.Workflow.Action.UserEntryForm ).FullName )
            {
                result.WorkflowForm = _formEditor.GetForm();
                if ( result.WorkflowForm == null )
                {
                    result.WorkflowForm = new WorkflowActionForm();
                    result.WorkflowForm.Actions = "Submit^^^Your information has been submitted successfully.";
                    var systemEmail = new SystemEmailService(new RockContext()).Get(SystemGuid.SystemEmail.WORKFLOW_FORM_NOTIFICATION.AsGuid());
                    if ( systemEmail != null )
                    {
                        result.WorkflowForm.NotificationSystemEmailId = systemEmail.Id;
                    }
                }
            }
            else
            {
                result.WorkflowForm = null;
            }

            result.LoadAttributes();
            Rock.Attribute.Helper.GetEditValues( _phActionAttributes, result );

            if (expandInvalid && !result.IsValid)
            {
                Expanded = true;
            }

            return result;
        }
Ejemplo n.º 34
0
        /// <summary>
        /// Shows the edit details.
        /// </summary>
        /// <param name="group">The group.</param>
        private void ShowEditDetails( Group group )
        {
            if ( group.Id == 0 )
            {
                lReadOnlyTitle.Text = ActionTitle.Add( Group.FriendlyTypeName ).FormatAsHtmlTitle();

                // hide the panel drawer that show created and last modified dates
                pdAuditDetails.Visible = false;
            }
            else
            {
                lReadOnlyTitle.Text = group.Name.FormatAsHtmlTitle();
            }

            SetHighlightLabelVisibility( group, false );

            ddlGroupType.Visible = group.Id == 0;
            lGroupType.Visible = group.Id != 0;

            SetEditMode( true );

            tbName.Text = group.Name;
            tbDescription.Text = group.Description;
            nbGroupCapacity.Text = group.GroupCapacity.ToString();
            cbIsSecurityRole.Checked = group.IsSecurityRole;
            cbIsActive.Checked = group.IsActive;
            cbIsPublic.Checked = group.IsPublic;

            var rockContext = new RockContext();

            var groupService = new GroupService( rockContext );
            var attributeService = new AttributeService( rockContext );

            LoadDropDowns( rockContext );

            ddlSignatureDocumentTemplate.SetValue( group.RequiredSignatureDocumentTemplateId );
            gpParentGroup.SetValue( group.ParentGroup ?? groupService.Get( group.ParentGroupId ?? 0 ) );

            // hide sync and requirements panel if no admin access
            bool canAdministrate = group.IsAuthorized( Authorization.ADMINISTRATE, CurrentPerson );
            wpGroupSync.Visible = canAdministrate;
            wpGroupRequirements.Visible = canAdministrate;
            wpGroupMemberAttributes.Visible = canAdministrate;

            var systemEmails = new SystemEmailService( rockContext ).Queryable().OrderBy( e => e.Title )
                .Select( a => new
                {
                    a.Id,
                    a.Title
                } );

            // add a blank for the first option
            ddlWelcomeEmail.Items.Add( new ListItem() );
            ddlExitEmail.Items.Add( new ListItem() );

            if ( systemEmails.Any() )
            {
                foreach ( var systemEmail in systemEmails )
                {
                    ddlWelcomeEmail.Items.Add( new ListItem( systemEmail.Title, systemEmail.Id.ToString() ) );
                    ddlExitEmail.Items.Add( new ListItem( systemEmail.Title, systemEmail.Id.ToString() ) );
                }
            }

            // set dataview
            dvpSyncDataview.EntityTypeId = EntityTypeCache.Read( "Rock.Model.Person" ).Id;
            dvpSyncDataview.SetValue( group.SyncDataViewId );

            if ( group.AddUserAccountsDuringSync.HasValue )
            {
                rbCreateLoginDuringSync.Checked = group.AddUserAccountsDuringSync.Value;
            }

            if ( group.WelcomeSystemEmailId.HasValue )
            {
                ddlWelcomeEmail.SetValue( group.WelcomeSystemEmailId );
            }

            if ( group.ExitSystemEmailId.HasValue )
            {
                ddlExitEmail.SetValue( group.ExitSystemEmailId );
            }

            // GroupType depends on Selected ParentGroup
            ddlParentGroup_SelectedIndexChanged( null, null );
            gpParentGroup.Label = "Parent Group";

            if ( group.Id == 0 && group.GroupType == null && ddlGroupType.Items.Count > 1 )
            {
                if ( GetAttributeValue( "LimittoSecurityRoleGroups" ).AsBoolean() )
                {
                    // default GroupType for new Group to "Security Roles"  if LimittoSecurityRoleGroups
                    var securityRoleGroupType = GroupTypeCache.GetSecurityRoleGroupType();
                    if ( securityRoleGroupType != null )
                    {
                        CurrentGroupTypeId = securityRoleGroupType.Id;
                        ddlGroupType.SetValue( securityRoleGroupType.Id );
                    }
                    else
                    {
                        ddlGroupType.SelectedIndex = 0;
                    }
                }
                else
                {
                    // if this is a new group (and not "LimitToSecurityRoleGroups", and there is more than one choice for GroupType, default to no selection so they are forced to choose (vs unintentionallly choosing the default one)
                    ddlGroupType.SelectedIndex = 0;
                }
            }
            else
            {
                CurrentGroupTypeId = group.GroupTypeId;
                if ( CurrentGroupTypeId == 0 )
                {
                    CurrentGroupTypeId = ddlGroupType.SelectedValueAsInt() ?? 0;
                }

                var groupType = GroupTypeCache.Read( CurrentGroupTypeId, rockContext );
                lGroupType.Text = groupType != null ? groupType.Name : string.Empty;
                ddlGroupType.SetValue( CurrentGroupTypeId );
            }

            ddlCampus.SetValue( group.CampusId );

            GroupRequirementsState = group.GroupRequirements.ToList();
            GroupLocationsState = group.GroupLocations.ToList();

            var groupTypeCache = CurrentGroupTypeCache;
            nbGroupCapacity.Visible = groupTypeCache != null && groupTypeCache.GroupCapacityRule != GroupCapacityRule.None;
            SetScheduleControls( groupTypeCache, group );
            ShowGroupTypeEditDetails( groupTypeCache, group, true );

            // if this block's attribute limit group to SecurityRoleGroups, don't let them edit the SecurityRole checkbox value
            if ( GetAttributeValue( "LimittoSecurityRoleGroups" ).AsBoolean() )
            {
                cbIsSecurityRole.Enabled = false;
                cbIsSecurityRole.Checked = true;
            }

            string qualifierValue = group.Id.ToString();
            GroupMemberAttributesState = attributeService.GetByEntityTypeId( new GroupMember().TypeId ).AsQueryable()
                    .Where( a =>
                        a.EntityTypeQualifierColumn.Equals( "GroupId", StringComparison.OrdinalIgnoreCase ) &&
                        a.EntityTypeQualifierValue.Equals( qualifierValue ) )
                    .OrderBy( a => a.Order )
                    .ThenBy( a => a.Name )
                    .ToList();
            BindGroupMemberAttributesGrid();

            BindInheritedAttributes( group.GroupTypeId, attributeService );

            cbMembersMustMeetRequirementsOnAdd.Checked = group.MustMeetRequirementsToAddMember ?? false;

            BindGroupRequirementsGrid();

            MemberWorkflowTriggersState = new List<GroupMemberWorkflowTrigger>();
            foreach ( var trigger in group.GroupMemberWorkflowTriggers )
            {
                MemberWorkflowTriggersState.Add( trigger );
            }

            BindMemberWorkflowTriggersGrid();
        }
Ejemplo n.º 35
0
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            var systemEmailService = new SystemEmailService( new RockContext() );
            SortProperty sortProperty = gEmailTemplates.SortProperty;

            var systemEmails = systemEmailService.Queryable( "Category" );

            int? categoryId = rFilter.GetUserPreference( "Category" ).AsIntegerOrNull();
            if ( categoryId.HasValue )
            {
                systemEmails = systemEmails.Where( a => a.CategoryId.HasValue && a.CategoryId.Value == categoryId.Value  );
            }

            if ( sortProperty != null )
            {
                gEmailTemplates.DataSource = systemEmails.Sort( sortProperty ).ToList();
            }
            else
            {
                gEmailTemplates.DataSource = systemEmails.OrderBy( a => a.Category.Name ).ThenBy( a => a.Title ).ToList();
            }

            gEmailTemplates.EntityTypeId = EntityTypeCache.Read<Rock.Model.SystemEmail>().Id;
            gEmailTemplates.DataBind();
        }
        /// <summary>
        /// Shows the detail.
        /// </summary>
        /// <param name="signatureDocumentTemplateId">The signature document type identifier.</param>
        public void ShowDetail( int signatureDocumentTemplateId )
        {
            pnlDetails.Visible = true;
            SignatureDocumentTemplate signatureDocumentTemplate = null;

            using ( var rockContext = new RockContext() )
            {
                if ( !signatureDocumentTemplateId.Equals( 0 ) )
                {
                    signatureDocumentTemplate = new SignatureDocumentTemplateService( rockContext ).Get( signatureDocumentTemplateId );
                }

                if ( signatureDocumentTemplate == null )
                {
                    signatureDocumentTemplate = new SignatureDocumentTemplate { Id = 0 };
                    var components = DigitalSignatureContainer.Instance.Components;
                    var entityType = components.Where( c => c.Value.Value.IsActive ).OrderBy( c => c.Value.Value.Order ).Select( c => c.Value.Value.EntityType ).FirstOrDefault();
                    if ( entityType != null )
                    {
                        signatureDocumentTemplate.ProviderEntityType = new EntityTypeService( rockContext ).Get( entityType.Id );
                    }

                    Guid? fileTypeGuid = GetAttributeValue( "DefaultFileType" ).AsGuidOrNull();
                    if ( fileTypeGuid.HasValue )
                    {
                        var binaryFileType = new BinaryFileTypeService( rockContext ).Get( fileTypeGuid.Value );
                        if ( binaryFileType != null )
                        {
                            signatureDocumentTemplate.BinaryFileType = binaryFileType;
                            signatureDocumentTemplate.BinaryFileTypeId = binaryFileType.Id;
                        }
                    }

                    Guid? inviteEmailGuid = GetAttributeValue( "DefaultInviteEmail" ).AsGuidOrNull();
                    if ( inviteEmailGuid.HasValue )
                    {
                        var systemEmail = new SystemEmailService( rockContext ).Get( inviteEmailGuid.Value );
                        if ( systemEmail != null )
                        {
                            signatureDocumentTemplate.InviteSystemEmail = systemEmail;
                            signatureDocumentTemplate.InviteSystemEmailId = systemEmail.Id;
                        }
                    }

                }

                hfSignatureDocumentTemplateId.SetValue( signatureDocumentTemplate.Id );

                // render UI based on Authorized and IsSystem
                bool readOnly = false;

                nbEditModeMessage.Text = string.Empty;
                bool canEdit = UserCanEdit || signatureDocumentTemplate.IsAuthorized( Authorization.EDIT, CurrentPerson );
                bool canView = canEdit || signatureDocumentTemplate.IsAuthorized( Authorization.VIEW, CurrentPerson );

                if ( !canView )
                {
                    pnlDetails.Visible = false;
                }
                else
                {
                    pnlDetails.Visible = true;

                    if ( !canEdit )
                    {
                        readOnly = true;
                        nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed( SignatureDocumentTemplate.FriendlyTypeName );
                    }

                    if ( readOnly )
                    {
                        btnEdit.Visible = false;
                        btnDelete.Visible = false;
                        ShowReadonlyDetails( signatureDocumentTemplate );
                    }
                    else
                    {
                        btnEdit.Visible = true;
                        btnDelete.Visible = false;
                        if ( signatureDocumentTemplate.Id > 0 )
                        {
                            ShowReadonlyDetails( signatureDocumentTemplate );
                        }
                        else
                        {
                            ShowEditDetails( signatureDocumentTemplate );
                        }
                    }
                }
            }
        }
Ejemplo n.º 37
0
        protected void lbProfileNext_Click(object sender, EventArgs e)
        {
            // setup merge fields
            var mergeFields = new Dictionary <string, object>();

            mergeFields.Add("PersonId", hfPersonId.Value);
            mergeFields.Add("FirstName", tbFirstName.Text);
            mergeFields.Add("LastName", tbLastName.Text);
            mergeFields.Add("StreetAddress", acAddress.Street1);
            mergeFields.Add("City", acAddress.City);
            mergeFields.Add("State", acAddress.State);
            mergeFields.Add("PostalCode", acAddress.PostalCode);
            mergeFields.Add("Country", acAddress.Country);
            mergeFields.Add("Email", tbEmail.Text);
            mergeFields.Add("HomePhone", pnbHomePhone.Text);
            mergeFields.Add("MobilePhone", pnbHomePhone.Text);
            mergeFields.Add("BirthDate", dpBirthdate.Text);
            mergeFields.Add("OtherUpdates", tbOtherUpdates.Text);

            var globalAttributeFields = Rock.Web.Cache.GlobalAttributesCache.GetMergeFields(CurrentPerson);

            globalAttributeFields.ToList().ForEach(d => mergeFields.Add(d.Key, d.Value));

            // if an email was provided email results
            RockContext rockContext = new RockContext();

            if (!string.IsNullOrWhiteSpace(GetAttributeValue("UpdateEmail")))
            {
                var receiptEmail = new SystemEmailService(rockContext).Get(new Guid(GetAttributeValue("UpdateEmail")));

                if (receiptEmail != null)
                {
                    var appRoot = Rock.Web.Cache.GlobalAttributesCache.Read(rockContext).GetValue("ExternalApplicationRoot");

                    var recipients = new List <RecipientData>();
                    recipients.Add(new RecipientData(null, mergeFields));

                    Email.Send(receiptEmail.Guid, recipients, appRoot);
                }
            }

            // launch workflow if configured
            if (!string.IsNullOrWhiteSpace(GetAttributeValue("WorkflowType")))
            {
                var workflowTypeService = new WorkflowTypeService(rockContext);
                var workflowService     = new WorkflowService(rockContext);
                var workflowType        = workflowTypeService.Get(new Guid(GetAttributeValue("WorkflowType")));

                if (workflowType != null)
                {
                    var workflow = Rock.Model.Workflow.Activate(workflowType, "Kiosk Update Info");

                    // set attributes
                    workflow.SetAttributeValue("PersonId", hfPersonId.Value);
                    workflow.SetAttributeValue("FirstName", tbFirstName.Text);
                    workflow.SetAttributeValue("LastName", tbLastName.Text);
                    workflow.SetAttributeValue("StreetAddress", acAddress.Street1);
                    workflow.SetAttributeValue("City", acAddress.City);
                    workflow.SetAttributeValue("State", acAddress.State);
                    workflow.SetAttributeValue("PostalCode", acAddress.PostalCode);
                    workflow.SetAttributeValue("Country", acAddress.Country);
                    workflow.SetAttributeValue("Email", tbEmail.Text);
                    workflow.SetAttributeValue("HomePhone", pnbHomePhone.Text);
                    workflow.SetAttributeValue("MobilePhone", pnbHomePhone.Text);
                    workflow.SetAttributeValue("BirthDate", dpBirthdate.Text);
                    workflow.SetAttributeValue("OtherUpdates", tbOtherUpdates.Text);

                    // lauch workflow
                    List <string> workflowErrors;
                    workflowService.Process(workflow, out workflowErrors);
                }
            }

            HidePanels();
            pnlComplete.Visible = true;

            lCompleteMessage.Text = GetAttributeValue("CompleteMessageLava").ResolveMergeFields(mergeFields);

            bool enableDebug = GetAttributeValue("EnableDebug").AsBoolean();

            if (enableDebug && IsUserAuthorized(Authorization.EDIT))
            {
                lDebug.Visible = true;
                lDebug.Text    = mergeFields.lavaDebugInfo();
            }
        }
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            SystemEmailService emailTemplateService = new SystemEmailService( new RockContext() );
            SortProperty sortProperty = gEmailTemplates.SortProperty;

            var emailTemplates = emailTemplateService.Queryable();

            if ( ddlCategoryFilter.SelectedValue != All.Id.ToString() )
            {
                emailTemplates = emailTemplates.Where( a => a.Category.Trim() == ddlCategoryFilter.SelectedValue );
            }

            if ( sortProperty != null )
            {
                gEmailTemplates.DataSource = emailTemplates.Sort( sortProperty ).ToList();
            }
            else
            {
                gEmailTemplates.DataSource = emailTemplates.OrderBy( a => a.Category ).ThenBy( a => a.Title ).ToList();
            }

            gEmailTemplates.DataBind();
        }
        /// <summary>
        /// Binds the filter.
        /// </summary>
        private void BindFilter()
        {
            ddlCategoryFilter.Items.Clear();
            ddlCategoryFilter.Items.Add( new ListItem(All.Text, All.Id.ToString()) );

            SystemEmailService emailTemplateService = new SystemEmailService( new RockContext() );
            var items = emailTemplateService.Queryable().
                Where( a => a.Category.Trim() != "" && a.Category != null ).
                OrderBy( a => a.Category ).
                Select( a => a.Category.Trim() ).
                Distinct().ToList();

            foreach ( var item in items )
            {
                ListItem li = new ListItem( item );
                li.Selected = ( !Page.IsPostBack && rFilter.GetUserPreference( "Category" ) == item );
                ddlCategoryFilter.Items.Add( li );
            }
        }
Ejemplo n.º 40
0
        private void SendReceipt()
        {
            RockContext rockContext = new RockContext();
            var receiptEmail = new SystemEmailService( rockContext ).Get( new Guid( GetAttributeValue( "ReceiptEmail" ) ) );

            if ( receiptEmail != null )
            {
                var givingUnit = new PersonAliasService( rockContext ).Get( this.SelectedGivingUnit.PersonAliasId ).Person;
                var appRoot = Rock.Web.Cache.GlobalAttributesCache.Read( rockContext ).GetValue( "ExternalApplicationRoot" );

                var recipients = new List<RecipientData>();
                recipients.Add( new RecipientData( givingUnit.Email, GetMergeFields( givingUnit ) ) );

                Email.Send( receiptEmail.Guid, recipients, appRoot );
            }
        }
Ejemplo n.º 41
0
        /// <summary>
        /// Sends the exit email.
        /// </summary>
        /// <param name="systemEmailId">The system email identifier.</param>
        /// <param name="recipient">The recipient.</param>
        /// <param name="syncGroup">The synchronize group.</param>
        private void SendExitEmail( int systemEmailId, Person recipient, Group syncGroup )
        {
            if ( !string.IsNullOrWhiteSpace( recipient.Email ) )
            {
                using ( var rockContext = new RockContext() )
                {
                    SystemEmailService emailService = new SystemEmailService( rockContext );

                    var systemEmail = emailService.Get( systemEmailId );

                    if ( systemEmail != null )
                    {
                        var recipients = new List<RecipientData>();
                        var mergeFields = new Dictionary<string, object>();
                        mergeFields.Add( "Group", syncGroup );
                        mergeFields.Add( "Person", recipient );
                        recipients.Add( new RecipientData( recipient.Email, mergeFields ) );

                        var appRoot = Rock.Web.Cache.GlobalAttributesCache.Read( rockContext ).GetValue( "ExternalApplicationRoot" );
                        Email.Send( systemEmail.Guid, recipients, appRoot );
                    }
                }
            }
        }
        /// <summary>
        /// Sets the type of the workflow action.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <param name="workflowTypeAttributes">The workflow type attributes.</param>
        public void SetWorkflowActionType(WorkflowActionType value, Dictionary<Guid, Rock.Model.Attribute> workflowTypeAttributes )
        {
            EnsureChildControls();
            _hfActionTypeGuid.Value = value.Guid.ToString();

            _ddlCriteriaAttribute.Items.Clear();
            _ddlCriteriaAttribute.Items.Add( new ListItem() );

            _tbddlCriteriaValue.DropDownList.Items.Clear();
            _tbddlCriteriaValue.DropDownList.Items.Add( new ListItem() );
            foreach ( var attribute in workflowTypeAttributes )
            {
                var li = new ListItem( attribute.Value.Name, attribute.Key.ToString() );
                li.Selected = value.CriteriaAttributeGuid.HasValue && value.CriteriaAttributeGuid.Value.ToString() == li.Value;
                _ddlCriteriaAttribute.Items.Add( li );

                _tbddlCriteriaValue.DropDownList.Items.Add( new ListItem( attribute.Value.Name, attribute.Key.ToString() ) );
            }

            _ddlCriteriaComparisonType.SetValue( value.CriteriaComparisonType.ConvertToInt() );
            _tbddlCriteriaValue.SelectedValue = value.CriteriaValue;

            _tbActionTypeName.Text = value.Name;
            _ddlEntityType.SetValue( value.EntityTypeId );
            _cbIsActivityCompletedOnSuccess.Checked = value.IsActivityCompletedOnSuccess;

            var entityType = EntityTypeCache.Read( value.EntityTypeId );
            if ( entityType != null && entityType.Name == typeof( Rock.Workflow.Action.UserEntryForm ).FullName )
            {
                if (value.WorkflowForm == null)
                {
                    value.WorkflowForm = new WorkflowActionForm();
                    value.WorkflowForm.Actions = "Submit^^^Your information has been submitted successfully.";
                    var systemEmail = new SystemEmailService( new RockContext() ).Get( SystemGuid.SystemEmail.WORKFLOW_FORM_NOTIFICATION.AsGuid() );
                    if ( systemEmail != null )
                    {
                        value.WorkflowForm.NotificationSystemEmailId = systemEmail.Id;
                    }
                }
                _formEditor.SetForm( value.WorkflowForm, workflowTypeAttributes );
                _cbIsActionCompletedOnSuccess.Checked = true;
                _cbIsActionCompletedOnSuccess.Enabled = false;
            }
            else
            {
                _formEditor.SetForm( null, workflowTypeAttributes );
                _cbIsActionCompletedOnSuccess.Checked = value.IsActionCompletedOnSuccess;
                _cbIsActionCompletedOnSuccess.Enabled = true;
            }

            _phActionAttributes.Controls.Clear();
            Rock.Attribute.Helper.AddEditControls( value, _phActionAttributes, true, ValidationGroup, new List<string>() { "Active", "Order" } );
        }
Ejemplo n.º 43
0
        /// <summary>
        /// Executes the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        public void Execute(IJobExecutionContext context)
        {
            var rockContext   = new RockContext();
            var personService = new PersonService(rockContext);

            JobDataMap dataMap         = context.JobDetail.JobDataMap;
            Guid?      systemEmailGuid = dataMap.GetString("BirthdayEmail").AsGuidOrNull();

            SystemEmailService emailService = new SystemEmailService(rockContext);

            SystemEmail systemEmail = null;

            if (systemEmailGuid.HasValue)
            {
                systemEmail = emailService.Get(systemEmailGuid.Value);
            }

            if (systemEmail == null)
            {
                // no email specified, so nothing to do
                return;
            }

            var activeStatusGuid = Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_ACTIVE.AsGuid();

            // only include alive people that have record status of Active
            var personQry = personService.Queryable(false, false).Where(a => a.RecordStatusValue.Guid == activeStatusGuid && a.IsDeceased == false);
            var ageRange  = (dataMap.GetString("AgeRange") ?? string.Empty).Split(',');

            if (ageRange.Length == 2)
            {
                int?minimumAge = ageRange[0].AsIntegerOrNull();
                int?maximumAge = ageRange[1].AsIntegerOrNull();
                personQry = personQry.WhereAgeRange(minimumAge, maximumAge, true);
            }

            // only include people whose birthday is today (which can be determined from the computed DaysUntilBirthday column)
            personQry = personQry.Where(a => a.DaysUntilBirthday.HasValue && a.DaysUntilBirthday == 0);

            var connectionStatusGuids = (dataMap.GetString("ConnectionStatuses") ?? string.Empty).Split(',').AsGuidList();

            if (connectionStatusGuids.Any())
            {
                personQry = personQry.Where(a => connectionStatusGuids.Contains(a.ConnectionStatusValue.Guid));
            }

            // only include people that have an email address and want an email
            personQry = personQry.Where(a => (a.Email != null) && (a.Email != string.Empty) && (a.EmailPreference != EmailPreference.DoNotEmail) && (a.IsEmailActive));

            var recipients = new List <RecipientData>();

            var personList = personQry.AsNoTracking().ToList();

            foreach (var person in personList)
            {
                var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(null);
                mergeFields.Add("Person", person);

                recipients.Add(new RecipientData(person.Email, mergeFields));
            }

            var emailMessage = new RockEmailMessage(systemEmail.Guid);

            emailMessage.SetRecipients(recipients);
            var errors = new List <string>();

            emailMessage.Send(out errors);
            context.Result = string.Format("{0} birthday emails sent", recipients.Count());

            if (errors.Any())
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine();
                sb.Append(string.Format("{0} Errors: ", errors.Count()));
                errors.ForEach(e => { sb.AppendLine(); sb.Append(e); });
                string errorMessage = sb.ToString();
                context.Result += errorMessage;
                var         exception = new Exception(errorMessage);
                HttpContext context2  = HttpContext.Current;
                ExceptionLogService.LogException(exception, context2);
                throw exception;
            }
        }
Ejemplo n.º 44
0
        /// <summary>
        /// Executes the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        public void Execute(IJobExecutionContext context)
        {
            var        rockContext = new RockContext();
            JobDataMap dataMap     = context.JobDetail.JobDataMap;

            // Get the details for the email that we'll be sending out.
            Guid?systemEmailGuid            = dataMap.GetString("ExpiringCreditCardEmail").AsGuidOrNull();
            SystemEmailService emailService = new SystemEmailService(rockContext);
            SystemEmail        systemEmail  = null;

            if (systemEmailGuid.HasValue)
            {
                systemEmail = emailService.Get(systemEmailGuid.Value);
            }

            if (systemEmail == null)
            {
                throw new Exception("Expiring credit card email is missing.");
            }

            // Fetch the configured Workflow once if one was set, we'll use it later.
            Guid?workflowGuid = dataMap.GetString("Workflow").AsGuidOrNull();
            WorkflowTypeCache workflowType = null;
            var workflowService            = new WorkflowService(rockContext);

            if (workflowGuid != null)
            {
                workflowType = WorkflowTypeCache.Get(workflowGuid.Value);
            }

            var qry = new FinancialScheduledTransactionService(rockContext)
                      .Queryable("ScheduledTransactionDetails,FinancialPaymentDetail.CurrencyTypeValue,FinancialPaymentDetail.CreditCardTypeValue")
                      .Where(t => t.IsActive && t.FinancialPaymentDetail.ExpirationMonthEncrypted != null &&
                             (t.EndDate == null || t.EndDate > DateTime.Now))
                      .AsNoTracking();

            // Get the current month and year
            DateTime now     = DateTime.Now;
            int      month   = now.Month;
            int      year    = now.Year;
            int      counter = 0;
            var      errors  = new List <string>();

            foreach (var transaction in qry)
            {
                int?expirationMonthDecrypted = Encryption.DecryptString(transaction.FinancialPaymentDetail.ExpirationMonthEncrypted).AsIntegerOrNull();
                int?expirationYearDecrypted  = Encryption.DecryptString(transaction.FinancialPaymentDetail.ExpirationYearEncrypted).AsIntegerOrNull();
                if (expirationMonthDecrypted.HasValue && expirationMonthDecrypted.HasValue)
                {
                    string acctNum = string.Empty;

                    if (!string.IsNullOrEmpty(transaction.FinancialPaymentDetail.AccountNumberMasked) && transaction.FinancialPaymentDetail.AccountNumberMasked.Length >= 4)
                    {
                        acctNum = transaction.FinancialPaymentDetail.AccountNumberMasked.Substring(transaction.FinancialPaymentDetail.AccountNumberMasked.Length - 4);
                    }

                    int warningYear  = expirationYearDecrypted.Value;
                    int warningMonth = expirationMonthDecrypted.Value - 1;
                    if (warningMonth == 0)
                    {
                        warningYear -= 1;
                        warningMonth = 12;
                    }

                    string warningDate        = warningMonth.ToString() + warningYear.ToString();
                    string currentMonthString = month.ToString() + year.ToString();

                    if (warningDate == currentMonthString)
                    {
                        // as per ISO7813 https://en.wikipedia.org/wiki/ISO/IEC_7813
                        var expirationDate = string.Format("{0:D2}/{1:D2}", expirationMonthDecrypted, expirationYearDecrypted);

                        var recipients  = new List <RecipientData>();
                        var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(null);
                        var person      = transaction.AuthorizedPersonAlias.Person;

                        if (!person.IsEmailActive || person.Email.IsNullOrWhiteSpace() || person.EmailPreference == EmailPreference.DoNotEmail)
                        {
                            continue;
                        }

                        mergeFields.Add("Person", person);
                        mergeFields.Add("Card", acctNum);
                        mergeFields.Add("Expiring", expirationDate);
                        recipients.Add(new RecipientData(person.Email, mergeFields));

                        var emailMessage = new RockEmailMessage(systemEmail.Guid);
                        emailMessage.SetRecipients(recipients);

                        var emailErrors = new List <string>();
                        emailMessage.Send(out emailErrors);
                        errors.AddRange(emailErrors);

                        // Start workflow for this person
                        if (workflowType != null)
                        {
                            Dictionary <string, string> attributes = new Dictionary <string, string>();
                            attributes.Add("Person", transaction.AuthorizedPersonAlias.Guid.ToString());
                            attributes.Add("Card", acctNum);
                            attributes.Add("Expiring", expirationDate);
                            StartWorkflow(workflowService, workflowType, attributes, string.Format("{0} (scheduled transaction Id: {1})", person.FullName, transaction.Id));
                        }

                        counter++;
                    }
                }
            }

            context.Result = string.Format("{0} scheduled credit card transactions were examined with {1} notice(s) sent.", qry.Count(), counter);

            if (errors.Any())
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine();
                sb.Append(string.Format("{0} Errors: ", errors.Count()));
                errors.ForEach(e => { sb.AppendLine(); sb.Append(e); });
                string errorMessage = sb.ToString();
                context.Result += errorMessage;
                var         exception = new Exception(errorMessage);
                HttpContext context2  = HttpContext.Current;
                ExceptionLogService.LogException(exception, context2);
                throw exception;
            }
        }
Ejemplo n.º 45
0
        /// <summary>
        /// Shows the detail.
        /// </summary>
        /// <param name="signatureDocumentTemplateId">The signature document type identifier.</param>
        public void ShowDetail(int signatureDocumentTemplateId)
        {
            pnlDetails.Visible = true;
            SignatureDocumentTemplate signatureDocumentTemplate = null;

            using (var rockContext = new RockContext())
            {
                if (!signatureDocumentTemplateId.Equals(0))
                {
                    signatureDocumentTemplate = new SignatureDocumentTemplateService(rockContext).Get(signatureDocumentTemplateId);
                }

                if (signatureDocumentTemplate == null)
                {
                    signatureDocumentTemplate = new SignatureDocumentTemplate {
                        Id = 0
                    };
                    var components = DigitalSignatureContainer.Instance.Components;
                    var entityType = components.Where(c => c.Value.Value.IsActive).OrderBy(c => c.Value.Value.Order).Select(c => c.Value.Value.EntityType).FirstOrDefault();
                    if (entityType != null)
                    {
                        signatureDocumentTemplate.ProviderEntityType = new EntityTypeService(rockContext).Get(entityType.Id);
                    }

                    Guid?fileTypeGuid = GetAttributeValue("DefaultFileType").AsGuidOrNull();
                    if (fileTypeGuid.HasValue)
                    {
                        var binaryFileType = new BinaryFileTypeService(rockContext).Get(fileTypeGuid.Value);
                        if (binaryFileType != null)
                        {
                            signatureDocumentTemplate.BinaryFileType   = binaryFileType;
                            signatureDocumentTemplate.BinaryFileTypeId = binaryFileType.Id;
                        }
                    }

                    Guid?inviteEmailGuid = GetAttributeValue("DefaultInviteEmail").AsGuidOrNull();
                    if (inviteEmailGuid.HasValue)
                    {
                        var systemEmail = new SystemEmailService(rockContext).Get(inviteEmailGuid.Value);
                        if (systemEmail != null)
                        {
                            signatureDocumentTemplate.InviteSystemEmail   = systemEmail;
                            signatureDocumentTemplate.InviteSystemEmailId = systemEmail.Id;
                        }
                    }
                }

                hfSignatureDocumentTemplateId.SetValue(signatureDocumentTemplate.Id);


                // render UI based on Authorized and IsSystem
                bool readOnly = false;

                nbEditModeMessage.Text = string.Empty;
                bool canEdit = UserCanEdit || signatureDocumentTemplate.IsAuthorized(Authorization.EDIT, CurrentPerson);
                bool canView = canEdit || signatureDocumentTemplate.IsAuthorized(Authorization.VIEW, CurrentPerson);

                if (!canView)
                {
                    pnlDetails.Visible = false;
                }
                else
                {
                    pnlDetails.Visible = true;

                    if (!canEdit)
                    {
                        readOnly = true;
                        nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed(SignatureDocumentTemplate.FriendlyTypeName);
                    }

                    if (readOnly)
                    {
                        btnEdit.Visible   = false;
                        btnDelete.Visible = false;
                        ShowReadonlyDetails(signatureDocumentTemplate);
                    }
                    else
                    {
                        btnEdit.Visible   = true;
                        btnDelete.Visible = false;
                        if (signatureDocumentTemplate.Id > 0)
                        {
                            ShowReadonlyDetails(signatureDocumentTemplate);
                        }
                        else
                        {
                            ShowEditDetails(signatureDocumentTemplate);
                        }
                    }
                }
            }
        }
Ejemplo n.º 46
0
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click( object sender, EventArgs e )
        {
            var rockContext = new RockContext();

            SystemEmailService emailTemplateService = new SystemEmailService( rockContext );
            SystemEmail emailTemplate;

            int emailTemplateId = int.Parse(hfEmailTemplateId.Value);

            if ( emailTemplateId == 0 )
            {
                emailTemplate = new SystemEmail();
                emailTemplateService.Add( emailTemplate );
            }
            else
            {
                emailTemplate = emailTemplateService.Get( emailTemplateId );
            }

            emailTemplate.Category = tbCategory.Text;
            emailTemplate.Title = tbTitle.Text;
            emailTemplate.FromName = tbFromName.Text;
            emailTemplate.From = tbFrom.Text;
            emailTemplate.To = tbTo.Text;
            emailTemplate.Cc = tbCc.Text;
            emailTemplate.Bcc = tbBcc.Text;
            emailTemplate.Subject = tbSubject.Text;
            emailTemplate.Body = tbBody.Text;

            if ( !emailTemplate.IsValid )
            {
                // Controls will render the error messages
                return;
            }

            rockContext.SaveChanges();

            NavigateToParentPage();
        }
        /// <summary>
        /// Job that will sync groups.
        /// 
        /// Called by the <see cref="IScheduler" /> when a
        /// <see cref="ITrigger" /> fires that is associated with
        /// the <see cref="IJob" />.
        /// </summary>
        public virtual void Execute( IJobExecutionContext context )
        {
            JobDataMap dataMap = context.JobDetail.JobDataMap;

            try
            {
                int notificationsSent = 0;
                int pendingMembersCount = 0;

                // get groups set to sync
                RockContext rockContext = new RockContext();

                Guid? groupTypeGuid = dataMap.GetString( "GroupType" ).AsGuidOrNull();
                Guid? systemEmailGuid = dataMap.GetString( "NotificationEmail" ).AsGuidOrNull();
                Guid? groupRoleFilterGuid = dataMap.GetString( "GroupRoleFilter" ).AsGuidOrNull();
                int? pendingAge = dataMap.GetString( "PendingAge" ).AsIntegerOrNull();

                bool includePreviouslyNotificed = dataMap.GetString( "IncludePreviouslyNotified" ).AsBoolean();

                // get system email
                SystemEmailService emailService = new SystemEmailService( rockContext );

                SystemEmail systemEmail = null;
                if ( systemEmailGuid.HasValue )
                {
                    systemEmail = emailService.Get( systemEmailGuid.Value );
                }

                if ( systemEmail == null )
                {
                    // no email specified, so nothing to do
                    return;
                }

                // get group members
                if ( groupTypeGuid.HasValue && groupTypeGuid != Guid.Empty )
                {
                    var qry = new GroupMemberService( rockContext ).Queryable( "Person, Group, Group.Members.GroupRole" )
                                            .Where( m => m.Group.GroupType.Guid == groupTypeGuid.Value
                                                && m.GroupMemberStatus == GroupMemberStatus.Pending );

                    if ( !includePreviouslyNotificed )
                    {
                        qry = qry.Where( m => m.IsNotified == false );
                    }

                    if ( groupRoleFilterGuid.HasValue )
                    {
                        qry = qry.Where( m => m.GroupRole.Guid == groupRoleFilterGuid.Value );
                    }

                    if ( pendingAge.HasValue )
                    {
                        var ageDate = RockDateTime.Now.AddDays( pendingAge.Value * -1 );
                        qry = qry.Where( m => m.ModifiedDateTime > ageDate );
                    }

                    var pendingGroupMembers = qry.ToList();

                    var groups = pendingGroupMembers.GroupBy( m => m.Group );

                    foreach ( var groupKey in groups )
                    {
                        var group = groupKey.Key;

                        // get list of pending people
                        var qryPendingIndividuals = group.Members.Where( m => m.GroupMemberStatus == GroupMemberStatus.Pending );

                        if ( !includePreviouslyNotificed )
                        {
                            qryPendingIndividuals = qryPendingIndividuals.Where( m => m.IsNotified == false );
                        }

                        if ( groupRoleFilterGuid.HasValue )
                        {
                            qryPendingIndividuals = qryPendingIndividuals.Where( m => m.GroupRole.Guid == groupRoleFilterGuid.Value );
                        }

                        var pendingIndividuals = qryPendingIndividuals.Select( m => m.Person ).ToList();

                        // get list of leaders
                        var groupLeaders = group.Members.Where( m => m.GroupRole.IsLeader == true );

                        var appRoot = Rock.Web.Cache.GlobalAttributesCache.Read( rockContext ).GetValue( "PublicApplicationRoot" );

                        var recipients = new List<RecipientData>();
                        foreach ( var leader in groupLeaders )
                        {
                            // create merge object
                            var mergeFields = new Dictionary<string, object>();
                            mergeFields.Add( "PendingIndividuals", pendingIndividuals );
                            mergeFields.Add( "Group", group );
                            mergeFields.Add( "ParentGroup", group.ParentGroup );
                            mergeFields.Add( "Person", leader.Person );
                            recipients.Add( new RecipientData( leader.Person.Email, mergeFields ) );
                        }

                        if ( pendingIndividuals.Count() > 0 )
                        {
                            Email.Send( systemEmail.Guid, recipients, appRoot );
                            pendingMembersCount += pendingIndividuals.Count();
                            notificationsSent += recipients.Count();
                        }

                        // mark pending members as notified as we go in case the job fails
                        var notifiedPersonIds = pendingIndividuals.Select( p => p.Id );
                        foreach ( var pendingGroupMember in pendingGroupMembers.Where( m => m.IsNotified == false && notifiedPersonIds.Contains( m.PersonId ) ) )
                        {
                            pendingGroupMember.IsNotified = true;
                        }

                        rockContext.SaveChanges();

                    }
                }

                context.Result = string.Format( "Sent {0} emails to leaders for {1} pending individuals", notificationsSent, pendingMembersCount );
            }
            catch ( System.Exception ex )
            {
                HttpContext context2 = HttpContext.Current;
                ExceptionLogService.LogException( ex, context2 );
                throw;
            }
        }
Ejemplo n.º 48
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The workflow action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            var actionType = action.ActionTypeCache;

            if (!action.LastProcessedDateTime.HasValue &&
                actionType != null &&
                actionType.WorkflowForm != null &&
                actionType.WorkflowForm.NotificationSystemEmailId.HasValue)
            {
                if (action.Activity != null && (action.Activity.AssignedPersonAliasId.HasValue || action.Activity.AssignedGroupId.HasValue))
                {
                    var recipients          = new List <RecipientData>();
                    var workflowMergeFields = GetMergeFields(action);

                    if (action.Activity.AssignedPersonAliasId.HasValue)
                    {
                        var person = new PersonAliasService(rockContext).Queryable()
                                     .Where(a => a.Id == action.Activity.AssignedPersonAliasId.Value)
                                     .Select(a => a.Person)
                                     .FirstOrDefault();

                        if (person != null && !string.IsNullOrWhiteSpace(person.Email))
                        {
                            recipients.Add(new RecipientData(person.Email, CombinePersonMergeFields(person, workflowMergeFields)));
                            action.AddLogEntry(string.Format("Form notification sent to '{0}'", person.FullName));
                        }
                    }

                    if (action.Activity.AssignedGroupId.HasValue)
                    {
                        var personList = new GroupMemberService(rockContext).GetByGroupId(action.Activity.AssignedGroupId.Value)
                                         .Where(m =>
                                                m.GroupMemberStatus == GroupMemberStatus.Active &&
                                                m.Person.Email != "")
                                         .Select(m => m.Person)
                                         .ToList();

                        foreach (var person in personList)
                        {
                            recipients.Add(new RecipientData(person.Email, CombinePersonMergeFields(person, workflowMergeFields)));
                            action.AddLogEntry(string.Format("Form notification sent to '{0}'", person.FullName));
                        }
                    }

                    if (recipients.Count > 0)
                    {
                        // The email may need to reference activity Id, so we need to save here.
                        WorkflowService workflowService = new WorkflowService(rockContext);
                        workflowService.PersistImmediately(action);

                        var systemEmail = new SystemEmailService(rockContext).Get(action.ActionTypeCache.WorkflowForm.NotificationSystemEmailId.Value);
                        if (systemEmail != null)
                        {
                            var emailMessage = new RockEmailMessage(systemEmail);
                            emailMessage.SetRecipients(recipients);
                            emailMessage.CreateCommunicationRecord = false;
                            emailMessage.AppRoot = GlobalAttributesCache.Get().GetValue("InternalApplicationRoot") ?? string.Empty;
                            emailMessage.Send();
                        }
                        else
                        {
                            action.AddLogEntry("Could not find the selected notification system email", true);
                        }
                    }
                    else
                    {
                        action.AddLogEntry("Could not send form notification due to no assigned person or group member not having email address", true);
                    }
                }
                else
                {
                    action.AddLogEntry("Could not send form notification due to no assigned person or group", true);
                }
            }

            return(false);
        }
        /// <summary>
        /// Sends the invite.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="component">The component.</param>
        /// <param name="document">The document.</param>
        /// <param name="person">The person.</param>
        /// <param name="errors">The errors.</param>
        /// <returns></returns>
        private bool SendInvite( RockContext rockContext, DigitalSignatureComponent component, SignatureDocument document, Person person, out List<string> errors )
        {
            errors = new List<string>();
            if ( document != null &&
                document.SignatureDocumentTemplate != null &&
                document.SignatureDocumentTemplate.InviteSystemEmailId.HasValue &&
                person != null &&
                !string.IsNullOrWhiteSpace( person.Email ) )
            {
                string inviteLink = component.GetInviteLink( document, person, out errors );
                if ( !errors.Any() )
                {
                    var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields( null, person );
                    mergeFields.Add( "SignatureDocument", document );
                    mergeFields.Add( "InviteLink", inviteLink );

                    var recipients = new List<RecipientData>();
                    recipients.Add( new RecipientData( person.Email, mergeFields ) );

                    var systemEmail = new SystemEmailService( rockContext ).Get( document.SignatureDocumentTemplate.InviteSystemEmailId.Value );
                    if ( systemEmail != null )
                    {
                        var appRoot = Rock.Web.Cache.GlobalAttributesCache.Read( rockContext ).GetValue( "InternalApplicationRoot" );
                        Email.Send( systemEmail.Guid, recipients, appRoot, string.Empty, false );
                    }
                }
                else
                {
                    return false;
                }
            }

            return true;
        }
Ejemplo n.º 50
0
        /// <summary>
        /// Shows the edit.
        /// </summary>
        /// <param name="emailTemplateId">The email template id.</param>
        protected void ShowEdit( int emailTemplateId )
        {
            var globalAttributes = GlobalAttributesCache.Read();

            string globalFromName = globalAttributes.GetValue( "OrganizationName" );
            tbFromName.Help = string.Format( "If a From Name value is not entered the 'Organization Name' Global Attribute value of '{0}' will be used when this template is sent.", globalFromName );

            string globalFrom = globalAttributes.GetValue( "OrganizationEmail" );
            tbFrom.Help = string.Format( "If a From Address value is not entered the 'Organization Email' Global Attribute value of '{0}' will be used when this template is sent.", globalFrom );

            SystemEmailService emailTemplateService = new SystemEmailService( new RockContext() );
            SystemEmail emailTemplate = emailTemplateService.Get( emailTemplateId );

            if ( emailTemplate != null )
            {
                lActionTitle.Text = ActionTitle.Edit( SystemEmail.FriendlyTypeName ).FormatAsHtmlTitle();
                hfEmailTemplateId.Value = emailTemplate.Id.ToString();

                tbCategory.Text = emailTemplate.Category;
                tbTitle.Text = emailTemplate.Title;
                tbFromName.Text = emailTemplate.FromName;
                tbFrom.Text = emailTemplate.From;
                tbTo.Text = emailTemplate.To;
                tbCc.Text = emailTemplate.Cc;
                tbBcc.Text = emailTemplate.Bcc;
                tbSubject.Text = emailTemplate.Subject;
                tbBody.Text = emailTemplate.Body;
            }
            else
            {
                lActionTitle.Text = ActionTitle.Add( SystemEmail.FriendlyTypeName ).FormatAsHtmlTitle();
                hfEmailTemplateId.Value = 0.ToString();

                tbCategory.Text = string.Empty;
                tbTitle.Text = string.Empty;
                tbFromName.Text = string.Empty;
                tbFrom.Text = string.Empty;
                tbTo.Text = string.Empty;
                tbCc.Text = string.Empty;
                tbBcc.Text = string.Empty;
                tbSubject.Text = string.Empty;
                tbBody.Text = string.Empty;
            }
        }
Ejemplo n.º 51
0
        protected void lbProfileNext_Click( object sender, EventArgs e )
        {
            // setup merge fields
            var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields( this.RockPage, this.CurrentPerson );
            mergeFields.Add( "PersonId", hfPersonId.Value );
            mergeFields.Add( "FirstName", tbFirstName.Text );
            mergeFields.Add( "LastName", tbLastName.Text );
            mergeFields.Add( "StreetAddress", acAddress.Street1 );
            mergeFields.Add( "City", acAddress.City );
            mergeFields.Add( "State", acAddress.State );
            mergeFields.Add( "PostalCode", acAddress.PostalCode );
            mergeFields.Add( "Country", acAddress.Country );
            mergeFields.Add( "Email", tbEmail.Text );
            mergeFields.Add( "HomePhone", pnbHomePhone.Text );
            mergeFields.Add( "MobilePhone", pnbHomePhone.Text );
            mergeFields.Add( "BirthDate", dpBirthdate.Text );
            mergeFields.Add( "OtherUpdates", tbOtherUpdates.Text );

            // if an email was provided email results
            RockContext rockContext = new RockContext();
            if ( !string.IsNullOrWhiteSpace( GetAttributeValue( "UpdateEmail" ) ) )
            {
                var receiptEmail = new SystemEmailService( rockContext ).Get( new Guid( GetAttributeValue( "UpdateEmail" ) ) );

                if ( receiptEmail != null )
                {
                    var appRoot = Rock.Web.Cache.GlobalAttributesCache.Read( rockContext ).GetValue( "PublicApplicationRoot" );

                    var recipients = new List<RecipientData>();
                    recipients.Add( new RecipientData( null, mergeFields ) );

                    Email.Send( receiptEmail.Guid, recipients, appRoot );
                }
            }

            // launch workflow if configured
            if ( !string.IsNullOrWhiteSpace( GetAttributeValue( "WorkflowType" ) ) )
            {
                var workflowTypeService = new WorkflowTypeService( rockContext );
                var workflowService = new WorkflowService( rockContext );
                var workflowType = workflowTypeService.Get( new Guid( GetAttributeValue( "WorkflowType" ) ) );

                if ( workflowType != null )
                {
                    var workflow = Rock.Model.Workflow.Activate( workflowType, "Kiosk Update Info" );

                    // set attributes
                    workflow.SetAttributeValue( "PersonId", hfPersonId.Value );
                    workflow.SetAttributeValue( "FirstName", tbFirstName.Text );
                    workflow.SetAttributeValue( "LastName", tbLastName.Text );
                    workflow.SetAttributeValue( "StreetAddress", acAddress.Street1 );
                    workflow.SetAttributeValue( "City", acAddress.City );
                    workflow.SetAttributeValue( "State", acAddress.State );
                    workflow.SetAttributeValue( "PostalCode", acAddress.PostalCode );
                    workflow.SetAttributeValue( "Country", acAddress.Country );
                    workflow.SetAttributeValue( "Email", tbEmail.Text );
                    workflow.SetAttributeValue( "HomePhone", pnbHomePhone.Text );
                    workflow.SetAttributeValue( "MobilePhone", pnbHomePhone.Text );
                    workflow.SetAttributeValue( "BirthDate", dpBirthdate.Text );
                    workflow.SetAttributeValue( "OtherUpdates", tbOtherUpdates.Text );

                    // lauch workflow
                    List<string> workflowErrors;
                    workflowService.Process( workflow, out workflowErrors );
                }
            }

            HidePanels();
            pnlComplete.Visible = true;

            lCompleteMessage.Text = GetAttributeValue( "CompleteMessageLava" ).ResolveMergeFields( mergeFields );

            bool enableDebug = GetAttributeValue( "EnableDebug" ).AsBoolean();
            if ( enableDebug && IsUserAuthorized( Authorization.EDIT ) )
            {
                lDebug.Visible = true;
                lDebug.Text = mergeFields.lavaDebugInfo();
            }
        }
Ejemplo n.º 52
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The workflow action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute( RockContext rockContext, WorkflowAction action, object entity, out List<string> errorMessages )
        {
            errorMessages = new List<string>();

            if ( !action.LastProcessedDateTime.HasValue &&
                action.ActionType != null &&
                action.ActionType.WorkflowForm != null &&
                action.ActionType.WorkflowForm.NotificationSystemEmailId.HasValue )
            {
                if ( action.Activity != null && ( action.Activity.AssignedPersonAliasId.HasValue || action.Activity.AssignedGroupId.HasValue ) )
                {
                    var recipients = new List<RecipientData>();
                    var workflowMergeFields = GetMergeFields( action );

                    if ( action.Activity.AssignedPersonAliasId.HasValue)
                    {
                        var person = new PersonAliasService( rockContext ).Queryable()
                            .Where( a => a.Id == action.Activity.AssignedPersonAliasId.Value )
                            .Select( a => a.Person )
                            .FirstOrDefault();

                        if ( person != null && !string.IsNullOrWhiteSpace( person.Email ) )
                        {
                            recipients.Add( new RecipientData( person.Email, CombinePersonMergeFields( person, workflowMergeFields ) ) );
                            action.AddLogEntry( string.Format( "Form Notification sent to '{0}'", person.FullName ) );
                        }
                    }

                    if ( action.Activity.AssignedGroupId.HasValue )
                    {
                        var personList = new GroupMemberService(rockContext).GetByGroupId( action.Activity.AssignedGroupId.Value )
                            .Where( m =>
                                m.GroupMemberStatus == GroupMemberStatus.Active &&
                                m.Person.Email != "" )
                            .Select( m => m.Person )
                            .ToList();

                        foreach( var person in personList)
                        {
                            recipients.Add( new RecipientData( person.Email, CombinePersonMergeFields( person, workflowMergeFields ) ) );
                            action.AddLogEntry( string.Format( "Form Notification sent to '{0}'", person.FullName ) );
                        }
                    }

                    if ( recipients.Count > 0 )
                    {
                        var systemEmail = new SystemEmailService( rockContext ).Get( action.ActionType.WorkflowForm.NotificationSystemEmailId.Value );
                        if ( systemEmail != null )
                        {
                            var appRoot = Rock.Web.Cache.GlobalAttributesCache.Read( rockContext ).GetValue( "InternalApplicationRoot" );
                            Email.Send( systemEmail.Guid, recipients, appRoot );
                        }
                        else
                        {
                            action.AddLogEntry( "Could not find the selected notifiction system email!", true );
                        }
                    }
                    else
                    {
                        action.AddLogEntry( "Could not send form notifiction due to no assigned person or group member not having email address!", true );
                    }
                }
                else
                {
                    action.AddLogEntry( "Could not send form notifiction due to no assigned person or group!", true );
                }
            }

            return false;
        }
Ejemplo n.º 53
0
        /// <summary>
        /// Executes the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        public void Execute( IJobExecutionContext context )
        {
            var rockContext = new RockContext();
            var personService = new PersonService( rockContext );

            JobDataMap dataMap = context.JobDetail.JobDataMap;
            Guid? systemEmailGuid = dataMap.GetString( "BirthdayEmail" ).AsGuidOrNull();

            SystemEmailService emailService = new SystemEmailService( rockContext );

            SystemEmail systemEmail = null;
            if ( systemEmailGuid.HasValue )
            {
                systemEmail = emailService.Get( systemEmailGuid.Value );
            }

            if ( systemEmail == null )
            {
                // no email specified, so nothing to do
                return;
            }

            var activeStatusGuid = Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_ACTIVE.AsGuid();

            // only include alive people that have record status of Active
            var personQry = personService.Queryable( false, false ).Where( a => a.RecordStatusValue.Guid == activeStatusGuid && a.IsDeceased == false );
            var ageRange = ( dataMap.GetString( "AgeRange" ) ?? string.Empty ).Split( ',' );
            if ( ageRange.Length == 2 )
            {
                int? minimumAge = ageRange[0].AsIntegerOrNull();
                int? maximumAge = ageRange[1].AsIntegerOrNull();
                personQry = personQry.WhereAgeRange( minimumAge, maximumAge, true );
            }

            // only include people whose birthday is today (which can be determined from the computed DaysUntilBirthday column)
            personQry = personQry.Where( a => a.DaysUntilBirthday.HasValue && a.DaysUntilBirthday == 0 );

            var connectionStatusGuids = ( dataMap.GetString( "ConnectionStatuses" ) ?? string.Empty ).Split( ',' ).AsGuidList();

            if ( connectionStatusGuids.Any() )
            {
                personQry = personQry.Where( a => connectionStatusGuids.Contains( a.ConnectionStatusValue.Guid ) );
            }

            // only include people that have an email address and want an email
            personQry = personQry.Where( a => ( a.Email != null ) && ( a.Email != "" ) && ( a.EmailPreference == EmailPreference.EmailAllowed ) );

            var recipients = new List<RecipientData>();

            var personList = personQry.AsNoTracking().ToList();
            foreach ( var person in personList )
            {
                var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields( null );
                mergeFields.Add( "Person", person );

                recipients.Add( new RecipientData( person.Email, mergeFields ) );
            }

            var appRoot = Rock.Web.Cache.GlobalAttributesCache.Read( rockContext ).GetValue( "ExternalApplicationRoot" );
            Email.Send( systemEmail.Guid, recipients, appRoot );
            context.Result = string.Format( "{0} birthday emails sent", recipients.Count() );
        }
Ejemplo n.º 54
0
        /// <summary>
        /// Sends the welcome email.
        /// </summary>
        /// <param name="systemEmailId">The system email identifier.</param>
        /// <param name="personId">The person identifier.</param>
        /// <param name="syncGroup">The synchronize group.</param>
        /// <param name="createLogin">if set to <c>true</c> [create login].</param>
        private void SendWelcomeEmail( int systemEmailId, int personId, Group syncGroup, bool createLogin )
        {
            using ( var rockContext = new RockContext() )
            {
                SystemEmailService emailService = new SystemEmailService( rockContext );

                var systemEmail = emailService.Get( systemEmailId );

                if ( systemEmail != null )
                {
                    string newPassword = string.Empty;

                    var recipients = new List<RecipientData>();

                    var mergeFields = new Dictionary<string, object>();
                    mergeFields.Add( "Group", syncGroup );

                    // get person
                    var recipient = new PersonService( rockContext ).Queryable( "Users" ).Where( p => p.Id == personId ).FirstOrDefault();

                    if ( !string.IsNullOrWhiteSpace( recipient.Email ) )
                    {
                        if ( createLogin && recipient.Users.Count == 0 )
                        {
                            newPassword = System.Web.Security.Membership.GeneratePassword( 9, 1 );

                            // create user
                            string username = Rock.Security.Authentication.Database.GenerateUsername( recipient.NickName, recipient.LastName );

                            UserLogin login = UserLoginService.Create(
                                rockContext,
                                recipient,
                                Rock.Model.AuthenticationServiceType.Internal,
                                EntityTypeCache.Read( Rock.SystemGuid.EntityType.AUTHENTICATION_DATABASE.AsGuid() ).Id,
                                username,
                                newPassword,
                                true );
                        }
                        mergeFields.Add( "Person", recipient );
                        mergeFields.Add( "NewPassword", newPassword );
                        mergeFields.Add( "CreateLogin", createLogin );
                        recipients.Add( new RecipientData( recipient.Email, mergeFields ) );

                        var appRoot = Rock.Web.Cache.GlobalAttributesCache.Read( rockContext ).GetValue( "ExternalApplicationRoot" );
                        Email.Send( systemEmail.Guid, recipients, appRoot );
                    }
                }
            }
        }