Beispiel #1
0
        /// <summary>
        /// Executes the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        public virtual void Execute(IJobExecutionContext context)
        {
            JobDataMap dataMap           = context.JobDetail.JobDataMap;
            var        emailTemplateGuid = dataMap.GetString("SystemEmail").AsGuidOrNull();
            var        dataViewGuid      = dataMap.GetString("DataView").AsGuidOrNull();

            if (dataViewGuid == null || emailTemplateGuid == null)
            {
                return;
            }

            var rockContext = new RockContext();
            var dataView    = new DataViewService(rockContext).Get(( Guid )dataViewGuid);

            List <IEntity> resultSet;
            Exception      dataViewException = null;

            try
            {
                var dataViewGetQueryArgs = new DataViewGetQueryArgs
                {
                    DatabaseTimeoutSeconds = dataMap.GetString("DatabaseTimeout").AsIntegerOrNull() ?? 180
                };

                var qry = dataView.GetQuery(dataViewGetQueryArgs);
                resultSet = qry.AsNoTracking().ToList();
            }
            catch (Exception exception)
            {
                dataViewException = exception;
                var sqlTimeoutException = ReportingHelper.FindSqlTimeoutException(exception);

                if (sqlTimeoutException != null)
                {
                    var exceptionMessage = $"The dataview did not complete in a timely manner. You can try again or adjust the timeout setting of this job.";
                    dataViewException = new RockDataViewFilterExpressionException(dataView.DataViewFilter, exceptionMessage, sqlTimeoutException);
                }

                HttpContext context2 = HttpContext.Current;
                ExceptionLogService.LogException(dataViewException, context2);
                context.Result = dataViewException.Message;
                throw dataViewException;
            }

            var recipients = new List <RockEmailMessageRecipient>();

            if (resultSet.Any())
            {
                foreach (Person person in resultSet)
                {
                    if (!person.IsEmailActive || person.Email.IsNullOrWhiteSpace() || person.EmailPreference == EmailPreference.DoNotEmail)
                    {
                        continue;
                    }

                    var mergeFields = Lava.LavaHelper.GetCommonMergeFields(null);
                    mergeFields.Add("Person", person);
                    recipients.Add(new RockEmailMessageRecipient(person, mergeFields));
                }
            }

            var emailMessage = new RockEmailMessage(emailTemplateGuid.Value);

            emailMessage.SetRecipients(recipients);

            var emailSendErrors = new List <string>();

            emailMessage.Send(out emailSendErrors);

            context.Result = string.Format("{0} emails sent", recipients.Count());

            if (emailSendErrors.Any())
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine();
                sb.Append(string.Format("{0} Errors: ", emailSendErrors.Count()));
                emailSendErrors.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;
            }
        }
Beispiel #2
0
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event.
        /// </summary>
        /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (!this.IsPostBack)
            {
                var campusIds    = this.GetBlockUserPreference("Campuses").SplitDelimitedValues().AsIntegerList();
                var dataViewGuid = this.GetBlockUserPreference("DataView").AsGuidOrNull();

                cbShowCampusLocations.Checked   = this.GetBlockUserPreference("ShowCampusLocations").AsBoolean();
                this.DataPointRadius            = this.GetBlockUserPreference("DataPointRadius").AsIntegerOrNull() ?? 32;
                rsDataPointRadius.SelectedValue = this.DataPointRadius;

                cpCampuses.SetValues(campusIds);

                // if there is no dataview specified, force the Filter options panel to be visible so they get a hint that a dataview needs to be picked
                ddlUserDataView.SetValue(dataViewGuid);
                if (!dataViewGuid.HasValue && ddlUserDataView.Visible)
                {
                    pnlOptions.Style["display"] = "";
                }

                var groupId = this.GetBlockUserPreference("GroupId").AsIntegerOrNull();
                gpGroupToMap.SetValue(groupId);

                this.LabelFontSize = this.GetAttributeValue("LabelFontSize").AsIntegerOrNull() ?? 24;

                lMessages.Text = string.Empty;
                pnlMap.Visible = true;

                pnlPieSlicer.Visible = this.GetAttributeValue("ShowPieSlicer").AsBoolean();
                pnlSaveShape.Visible = this.GetAttributeValue("ShowSaveLocation").AsBoolean();

                try
                {
                    ShowMap();
                }
                catch (Exception ex)
                {
                    ExceptionLogService.LogException(ex);
                    var sqlTimeoutException = ReportingHelper.FindSqlTimeoutException(ex);

                    if (sqlTimeoutException != null)
                    {
                        nbErrorMessage.NotificationBoxType = NotificationBoxType.Warning;
                        nbErrorMessage.Text = "This query did not complete in a timely manner.";
                    }
                    else
                    {
                        if (ex is RockDataViewFilterExpressionException)
                        {
                            RockDataViewFilterExpressionException rockDataViewFilterExpressionException = ex as RockDataViewFilterExpressionException;
                            nbErrorMessage.Text = rockDataViewFilterExpressionException.GetFriendlyMessage(this.GetDataView());
                        }
                        else
                        {
                            nbErrorMessage.Text = "There was a problem with one of the filters for this report's dataview.";
                        }

                        nbErrorMessage.NotificationBoxType = NotificationBoxType.Danger;

                        nbErrorMessage.Details = ex.Message;
                        nbErrorMessage.Visible = true;
                    }
                }
            }
            else if (this.Request.Params["__EVENTTARGET"] == upSaveLocation.ClientID)
            {
                mdSaveLocation_SaveClick(null, null);
            }
        }
        /// <summary>
        /// Binds the report grid.
        /// </summary>
        private void BindReportGrid(bool isCommunication = false)
        {
            var    rockContext   = new RockContext();
            var    reportService = new ReportService(rockContext);
            var    reportGuid    = this.GetAttributeValue("Report").AsGuidOrNull();
            var    personIdField = this.GetAttributeValue("PersonIdField");
            Report report        = null;

            if (reportGuid.HasValue)
            {
                report = reportService.Get(reportGuid.Value);
            }

            if (report == null)
            {
                nbConfigurationWarning.Visible = true;
                nbConfigurationWarning.Text    = "A report needs to be configured in block settings";
                pnlView.Visible = false;
            }
            else if (report.DataView == null)
            {
                nbConfigurationWarning.Visible = true;
                nbConfigurationWarning.Text    = string.Format("The {0} report does not have a dataview", report);
                pnlView.Visible = false;
            }
            else if (report.DataView.EntityTypeId != report.EntityTypeId)
            {
                nbConfigurationWarning.Visible = true;
                nbConfigurationWarning.Text    = string.Format("The {0} report's EntityType doesn't match the dataview's EntityType", report);
                pnlView.Visible = false;
            }
            else
            {
                nbConfigurationWarning.Visible = false;


                DataViewFilterOverrides dataViewFilterOverrides = ReportingHelper.GetFilterOverridesFromControls(report.DataView, phFilters);

                ReportingHelper.BindGridOptions bindGridOptions = new ReportingHelper.BindGridOptions
                {
                    CurrentPerson           = this.CurrentPerson,
                    DataViewFilterOverrides = dataViewFilterOverrides,
                    DatabaseTimeoutSeconds  = null,
                    IsCommunication         = isCommunication
                };


                nbReportErrors.Visible = false;

                try
                {
                    bindGridOptions.ReportDbContext = Reflection.GetDbContextForEntityType(EntityTypeCache.Get(report.EntityTypeId.Value).GetEntityType());
                    ReportingHelper.BindGrid(report, gReport, bindGridOptions);

                    if (report.EntityTypeId != EntityTypeCache.GetId <Rock.Model.Person>())
                    {
                        var personColumn = gReport.ColumnsOfType <BoundField>().Where(a => a.HeaderText == personIdField).FirstOrDefault();
                        if (personColumn != null)
                        {
                            gReport.PersonIdField = personColumn.SortExpression;
                        }
                    }
                }
                catch (Exception ex)
                {
                    ExceptionLogService.LogException(ex);
                    var sqlTimeoutException = ReportingHelper.FindSqlTimeoutException(ex);

                    if (sqlTimeoutException != null)
                    {
                        nbReportErrors.NotificationBoxType = NotificationBoxType.Warning;
                        nbReportErrors.Text = "This report did not complete in a timely manner.";
                    }
                    else
                    {
                        if (ex is RockDataViewFilterExpressionException)
                        {
                            RockDataViewFilterExpressionException rockDataViewFilterExpressionException = ex as RockDataViewFilterExpressionException;
                            nbReportErrors.Text = rockDataViewFilterExpressionException.GetFriendlyMessage(report.DataView);
                        }
                        else
                        {
                            nbReportErrors.Text = "There was a problem with one of the filters for this report's dataview.";
                        }

                        nbReportErrors.NotificationBoxType = NotificationBoxType.Danger;

                        nbReportErrors.Details = ex.Message;
                        nbReportErrors.Visible = true;
                    }
                }
            }
        }
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            var dataViewId = hfDataViewId.Value.AsIntegerOrNull();

            pnlResultsGrid.Visible = false;

            pnlView.Visible = false;
            if (!dataViewId.HasValue)
            {
                return;
            }

            var dataView = new DataViewService(new RockContext()).Get(dataViewId.Value);

            if (dataView == null)
            {
                return;
            }

            if (!dataView.EntityTypeId.HasValue)
            {
                return;
            }

            var dataViewEntityType = EntityTypeCache.Get(dataView.EntityTypeId.Value);

            if (dataViewEntityType == null || dataViewEntityType.AssemblyName == null)
            {
                return;
            }

            Type dataViewEntityTypeType = dataViewEntityType.GetEntityType();

            if (dataViewEntityTypeType == null)
            {
                return;
            }

            pnlView.Visible = true;

            gDataViewResults.DataSource = null;

            // Only respect the ShowResults option if fetchRowCount is null
            var showResults = GetBlockUserPreference(UserPreferenceKey.ShowResults).AsBooleanOrNull() ?? true;

            if (showResults)
            {
                btnToggleResults.Text    = "Hide Results <i class='fa fa-chevron-up'></i>";
                btnToggleResults.ToolTip = "Hide Results";
                btnToggleResults.RemoveCssClass("btn-primary");
                btnToggleResults.AddCssClass("btn-default");
            }
            else
            {
                btnToggleResults.Text = "Show Results <i class='fa fa-chevron-down'></i>";
                btnToggleResults.RemoveCssClass("btn-default");
                btnToggleResults.AddCssClass("btn-primary");
                btnToggleResults.ToolTip = "Show Results";
            }

            if (!showResults)
            {
                return;
            }

            if (!dataView.IsAuthorized(Authorization.VIEW, CurrentPerson))
            {
                return;
            }

            gDataViewResults.EntityTypeId = dataView.EntityTypeId;
            bool isPersonDataSet = dataView.EntityTypeId == EntityTypeCache.GetId <Rock.Model.Person>();

            if (isPersonDataSet)
            {
                gDataViewResults.PersonIdField = "Id";
                gDataViewResults.DataKeyNames  = new string[] { "Id" };
            }
            else
            {
                gDataViewResults.PersonIdField = null;
            }

            var entityTypeCache = EntityTypeCache.Get(dataView.EntityTypeId.Value);

            if (entityTypeCache != null)
            {
                gDataViewResults.RowItemText = entityTypeCache.FriendlyName;
            }

            pnlResultsGrid.Visible = true;

            var enableCountingDataViewStatistics = this.GetAttributeValue(AttributeKey.EnableCountingDataViewStatistics).AsBooleanOrNull() ?? true;

            try
            {
                gDataViewResults.CreatePreviewColumns(dataViewEntityTypeType);
                var dbContext            = dataView.GetDbContext();
                var dataViewGetQueryArgs = new DataViewGetQueryArgs
                {
                    SortProperty            = gDataViewResults.SortProperty,
                    DbContext               = dbContext,
                    DatabaseTimeoutSeconds  = GetAttributeValue(AttributeKey.DatabaseTimeoutSeconds).AsIntegerOrNull() ?? 180,
                    DataViewFilterOverrides = new DataViewFilterOverrides
                    {
                        ShouldUpdateStatics = enableCountingDataViewStatistics
                    }
                };

                var qry = dataView.GetQuery(dataViewGetQueryArgs);

                gDataViewResults.SetLinqDataSource(qry.AsNoTracking());
                gDataViewResults.DataBind();
            }
            catch (Exception ex)
            {
                this.LogException(ex);
                var sqlTimeoutException = ReportingHelper.FindSqlTimeoutException(ex);
                var errorBox            = nbGridError;

                if (sqlTimeoutException != null)
                {
                    errorBox.NotificationBoxType = NotificationBoxType.Warning;
                    errorBox.Text = "This data view did not complete in a timely manner. You can try again or adjust the timeout setting of this block.";
                    return;
                }
                else
                {
                    if (ex is RockDataViewFilterExpressionException)
                    {
                        RockDataViewFilterExpressionException rockDataViewFilterExpressionException = ex as RockDataViewFilterExpressionException;
                        errorBox.Text = rockDataViewFilterExpressionException.GetFriendlyMessage(dataView);
                    }
                    else
                    {
                        errorBox.Text = "There was a problem with one of the filters for this data view.";
                    }

                    errorBox.NotificationBoxType = NotificationBoxType.Danger;

                    errorBox.Details = ex.Message;
                    errorBox.Visible = true;
                    return;
                }
            }

            gDataViewResults.RowItemText = dataViewEntityType.FriendlyName;

            if (gDataViewResults.DataSource != null)
            {
                gDataViewResults.ExportFilename = dataView.Name;
            }
        }
Beispiel #5
0
        /// <summary>
        /// Creates the table controls.
        /// </summary>
        /// <param name="batchId">The batch identifier.</param>
        /// <param name="dataViewId">The data view identifier.</param>
        private void BindHtmlGrid(int?batchId, int?dataViewId)
        {
            _financialTransactionDetailList = null;
            RockContext rockContext = new RockContext();

            nbSaveSuccess.Visible = false;
            btnSave.Visible       = false;

            List <DataControlField> tableColumns = new List <DataControlField>();

            tableColumns.Add(new RockLiteralField {
                ID = "lPerson", HeaderText = "Person"
            });
            tableColumns.Add(new RockLiteralField {
                ID = "lAmount", HeaderText = "Amount"
            });
            tableColumns.Add(new RockLiteralField {
                ID = "lAccount", HeaderText = "Account"
            });
            tableColumns.Add(new RockLiteralField {
                ID = "lTransactionType", HeaderText = "Transaction Type"
            });

            string entityColumnHeading = this.GetAttributeValue("EntityColumnHeading");

            if (string.IsNullOrEmpty(entityColumnHeading))
            {
                if (_transactionEntityType != null)
                {
                    entityColumnHeading = _entityTypeQualifiedName;
                }
            }

            tableColumns.Add(new RockLiteralField {
                ID = "lEntityColumn", HeaderText = entityColumnHeading
            });

            var additionalColumns = this.GetAttributeValue(CustomGridColumnsConfig.AttributeKey).FromJsonOrNull <CustomGridColumnsConfig>();

            if (additionalColumns != null)
            {
                foreach (var columnConfig in additionalColumns.ColumnsConfig)
                {
                    int insertPosition;
                    if (columnConfig.PositionOffsetType == CustomGridColumnsConfig.ColumnConfig.OffsetType.LastColumn)
                    {
                        insertPosition = tableColumns.Count - columnConfig.PositionOffset;
                    }
                    else
                    {
                        insertPosition = columnConfig.PositionOffset;
                    }

                    var column = columnConfig.GetGridColumn();
                    tableColumns.Insert(insertPosition, column);
                    insertPosition++;
                }
            }

            StringBuilder headers = new StringBuilder();

            foreach (var tableColumn in tableColumns)
            {
                if (tableColumn.HeaderStyle.CssClass.IsNotNullOrWhiteSpace())
                {
                    headers.AppendFormat("<th class='{0}'>{1}</th>", tableColumn.HeaderStyle.CssClass, tableColumn.HeaderText);
                }
                else
                {
                    headers.AppendFormat("<th>{0}</th>", tableColumn.HeaderText);
                }
            }

            lHeaderHtml.Text = headers.ToString();

            int?     transactionId = this.PageParameter("TransactionId").AsIntegerOrNull();
            DataView dataView      = null;

            if (batchId.HasValue || dataViewId.HasValue || transactionId.HasValue)
            {
                nbErrorMessage.Visible = false;
                try
                {
                    var financialTransactionDetailQuery = new FinancialTransactionDetailService(rockContext).Queryable()
                                                          .Include(a => a.Transaction)
                                                          .Include(a => a.Transaction.AuthorizedPersonAlias.Person);
                    if (batchId.HasValue)
                    {
                        financialTransactionDetailQuery = financialTransactionDetailQuery.Where(a => a.Transaction.BatchId == batchId.Value);
                    }

                    if (dataViewId.HasValue && dataViewId > 0)
                    {
                        dataView = new DataViewService(rockContext).Get(dataViewId.Value);
                        var transactionDetailIdsQry = dataView.GetQuery(new DataViewGetQueryArgs {
                            DbContext = rockContext
                        }).Select(a => a.Id);
                        financialTransactionDetailQuery = financialTransactionDetailQuery.Where(a => transactionDetailIdsQry.Contains(a.Id));
                    }

                    if (transactionId.HasValue)
                    {
                        financialTransactionDetailQuery = financialTransactionDetailQuery.Where(a => transactionId == a.TransactionId);
                    }

                    int maxResults = this.GetAttributeValue("MaxNumberofResults").AsIntegerOrNull() ?? 1000;
                    _financialTransactionDetailList = financialTransactionDetailQuery.OrderByDescending(a => a.Transaction.TransactionDateTime).Take(maxResults).ToList();
                }
                catch (Exception ex)
                {
                    ExceptionLogService.LogException(ex);
                    var sqlTimeoutException = ReportingHelper.FindSqlTimeoutException(ex);

                    if (sqlTimeoutException != null)
                    {
                        nbErrorMessage.NotificationBoxType = NotificationBoxType.Warning;
                        nbErrorMessage.Text = "This report did not complete in a timely manner. You can try again or adjust the timeout setting of this block.";
                    }
                    else
                    {
                        if (ex is RockDataViewFilterExpressionException)
                        {
                            RockDataViewFilterExpressionException rockDataViewFilterExpressionException = ex as RockDataViewFilterExpressionException;
                            nbErrorMessage.Text = rockDataViewFilterExpressionException.GetFriendlyMessage(dataView);
                        }
                        else
                        {
                            nbErrorMessage.Text = "There was a problem with one of the filters for this report's dataview.";
                        }

                        nbErrorMessage.NotificationBoxType = NotificationBoxType.Danger;

                        nbErrorMessage.Details = ex.Message;
                        nbErrorMessage.Visible = true;
                        return;
                    }
                }

                phTableRows.Controls.Clear();
                btnSave.Visible = _financialTransactionDetailList.Any();
                string appRoot   = this.ResolveRockUrl("~/");
                string themeRoot = this.ResolveRockUrl("~~/");

                foreach (var financialTransactionDetail in _financialTransactionDetailList)
                {
                    var tr = new HtmlGenericContainer("tr");
                    foreach (var tableColumn in tableColumns)
                    {
                        var literalControl = new LiteralControl();
                        if (tableColumn is RockLiteralField)
                        {
                            tr.Controls.Add(literalControl);
                            var literalTableColumn = tableColumn as RockLiteralField;
                            if (literalTableColumn.ID == "lPerson")
                            {
                                literalControl.Text = string.Format("<td>{0}</td>", financialTransactionDetail.Transaction.AuthorizedPersonAlias);
                            }
                            else if (literalTableColumn.ID == "lAmount")
                            {
                                literalControl.Text = string.Format("<td>{0}</td>", financialTransactionDetail.Amount.FormatAsCurrency());
                            }
                            else if (literalTableColumn.ID == "lAccount")
                            {
                                literalControl.Text = string.Format("<td>{0}</td>", financialTransactionDetail.Account.ToString());
                            }
                            else if (literalTableColumn.ID == "lTransactionType")
                            {
                                literalControl.ID   = "lTransactionType_" + financialTransactionDetail.Id.ToString();
                                literalControl.Text = string.Format("<td>{0}</td>", financialTransactionDetail.Transaction.TransactionTypeValue);
                            }
                            else if (literalTableColumn.ID == "lEntityColumn")
                            {
                                var tdEntityControls = new HtmlGenericContainer("td")
                                {
                                    ID = "pnlEntityControls_" + financialTransactionDetail.Id.ToString()
                                };
                                tr.Controls.Add(tdEntityControls);

                                if (_transactionEntityType != null)
                                {
                                    if (_transactionEntityType.Id == EntityTypeCache.GetId <GroupMember>())
                                    {
                                        var ddlGroup = new RockDropDownList {
                                            ID = "ddlGroup_" + financialTransactionDetail.Id.ToString(), EnhanceForLongLists = true
                                        };
                                        ddlGroup.Label                 = "Group";
                                        ddlGroup.AutoPostBack          = true;
                                        ddlGroup.SelectedIndexChanged += ddlGroup_SelectedIndexChanged;
                                        tdEntityControls.Controls.Add(ddlGroup);
                                        var ddlGroupMember = new RockDropDownList {
                                            ID = "ddlGroupMember_" + financialTransactionDetail.Id.ToString(), Visible = false, EnhanceForLongLists = true
                                        };
                                        ddlGroupMember.Label = "Group Member";
                                        tdEntityControls.Controls.Add(ddlGroupMember);
                                    }
                                    else if (_transactionEntityType.Id == EntityTypeCache.GetId <Group>())
                                    {
                                        var ddlGroup = new RockDropDownList {
                                            ID = "ddlGroup_" + financialTransactionDetail.Id.ToString(), EnhanceForLongLists = true
                                        };
                                        ddlGroup.AutoPostBack = false;
                                        tdEntityControls.Controls.Add(ddlGroup);
                                    }
                                    else if (_transactionEntityType.Id == EntityTypeCache.GetId <DefinedValue>())
                                    {
                                        var ddlDefinedValue = new DefinedValuePicker {
                                            ID = "ddlDefinedValue_" + financialTransactionDetail.Id.ToString(), EnhanceForLongLists = true
                                        };
                                        tdEntityControls.Controls.Add(ddlDefinedValue);
                                    }
                                    else if (_transactionEntityType.SingleValueFieldType != null)
                                    {
                                        var entityPicker = _transactionEntityType.SingleValueFieldType.Field.EditControl(new Dictionary <string, Rock.Field.ConfigurationValue>(), "entityPicker_" + financialTransactionDetail.Id.ToString());
                                        tdEntityControls.Controls.Add(entityPicker);
                                    }
                                }
                            }
                        }
                        else if (tableColumn is LavaField)
                        {
                            tr.Controls.Add(literalControl);
                            var lavaField = tableColumn as LavaField;

                            Dictionary <string, object> mergeValues = new Dictionary <string, object>();
                            mergeValues.Add("Row", financialTransactionDetail);

                            string lavaOutput = lavaField.LavaTemplate.ResolveMergeFields(mergeValues);

                            // Resolve any dynamic url references
                            lavaOutput = lavaOutput.Replace("~~/", themeRoot).Replace("~/", appRoot);

                            if (lavaField.ItemStyle.CssClass.IsNotNullOrWhiteSpace())
                            {
                                literalControl.Text = string.Format("<td class='{0}'>{1}</td>", lavaField.ItemStyle.CssClass, lavaOutput);
                            }
                            else
                            {
                                literalControl.Text = string.Format("<td>{0}</td>", lavaOutput);
                            }
                        }
                    }

                    phTableRows.Controls.Add(tr);

                    pnlTransactions.Visible = true;
                }
            }
            else
            {
                pnlTransactions.Visible = false;
            }
        }