/// <summary>
        /// Shows the charts.
        /// </summary>
        public void ShowCharts()
        {
            pnlCharts.Visible = false;
            try
            {
                using (var rockContext = new RockContext())
                {
                    rockContext.Database.CommandTimeout = this.GetAttributeValue(AttributeKey.DatabaseTimeoutSeconds).AsIntegerOrNull() ?? 180;
                    if (PopulateCharts(rockContext))
                    {
                        pnlCharts.Visible = true;
                    }
                }
            }
            catch (Exception ex)
            {
                this.LogException(ex);
                var sqlTimeoutException = ReportingHelper.FindSqlTimeoutException(ex);

                if (sqlTimeoutException != null)
                {
                    nbWarningMessage.NotificationBoxType = NotificationBoxType.Warning;
                    nbWarningMessage.Text = "This chart could not be completed in a timely manner. You can try again or adjust the filter or timeout setting of this block.";
                }
                else
                {
                    nbWarningMessage.NotificationBoxType = NotificationBoxType.Danger;
                    nbWarningMessage.Text    = "There was a problem getting the data for the chart.";
                    nbWarningMessage.Details = ex.Message;
                }

                nbWarningMessage.Visible = true;
                return;
            }
        }
        /// <summary>
        /// Loads the responses for recipient.
        /// </summary>
        /// <param name="recipientPersonId">The recipient person identifier.</param>
        /// <returns></returns>
        private string LoadResponsesForRecipientPerson(int recipientPersonId)
        {
            int?smsPhoneDefinedValueId = hfSmsNumber.ValueAsInt();

            if (smsPhoneDefinedValueId == default(int))
            {
                return(string.Empty);
            }

            try
            {
                var rockContext = new RockContext();
                rockContext.Database.CommandTimeout = GetAttributeValue(AttributeKey.DatabaseTimeoutSeconds).AsIntegerOrNull() ?? 180;
                var communicationResponseService = new CommunicationResponseService(rockContext);
                List <CommunicationRecipientResponse> responses = communicationResponseService.GetCommunicationConversationForPerson(recipientPersonId, smsPhoneDefinedValueId.Value);

                BindConversationRepeater(responses);

                if (responses.Any())
                {
                    var responseListItem = responses.Last();

                    if (responseListItem.SMSMessage.IsNullOrWhiteSpace() && responseListItem.HasAttachments(rockContext))
                    {
                        return("Rock-Image-File");
                    }

                    return(responses.Last().SMSMessage);
                }
            }
            catch (Exception ex)
            {
                this.LogException(ex);
                var sqlTimeoutException = ReportingHelper.FindSqlTimeoutException(ex);
                var errorBox            = nbError;

                if (sqlTimeoutException != null)
                {
                    nbError.NotificationBoxType = NotificationBoxType.Warning;
                    nbError.Text = "Unable to load SMS responses for recipient in a timely manner. You can try again or adjust the timeout setting of this block.";
                    return(string.Empty);
                }
                else
                {
                    errorBox.NotificationBoxType = NotificationBoxType.Danger;
                    nbError.Text     = "An error occurred when loading SMS responses for recipient";
                    errorBox.Details = ex.Message;
                    errorBox.Visible = true;
                    return(string.Empty);
                }
            }

            return(string.Empty);
        }
        /// <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)
        {
            try
            {
                nbMessage.Visible = false;

                base.OnLoad(e);
                _entity = this.ContextEntity();
                if (_entity != null)
                {
                    if (!Page.IsPostBack)
                    {
                        var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson);
                        mergeFields.Add("Entity", _entity);
                        lHeading.Text = GetAttributeValue(AttributeKey.Heading).ResolveMergeFields(mergeFields);

                        BindFilter();
                        BindGrid();

                        IModel model = _entity as IModel;
                        if (model != null && model.CreatedDateTime.HasValue)
                        {
                            hlDateAdded.Text = String.Format("Date Created: {0}", model.CreatedDateTime.Value.ToShortDateString());
                        }
                        else
                        {
                            hlDateAdded.Visible = false;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionLogService.LogException(ex);

                Exception sqlException = ReportingHelper.FindSqlTimeoutException(ex);

                nbMessage.Visible = true;
                nbMessage.Text    = string.Format("<p>An error occurred trying to retrieve the history. Please try adjusting your filter settings and try again.</p><p>Error: {0}</p>",
                                                  sqlException != null ? sqlException.Message : ex.Message);
            }
        }
Exemple #4
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;
            }
        }
Exemple #5
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 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;
            }
        }
        /// <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;
                    }
                }
            }
        }
Exemple #8
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;
            }
        }
Exemple #9
0
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            var rockContext = new RockContext();

            var communicationsQuery = new CommunicationService(rockContext)
                                      .Queryable().AsNoTracking()
                                      .Where(c => c.Status != CommunicationStatus.Transient);

            string subject = tbSubject.Text;

            if (!string.IsNullOrWhiteSpace(subject))
            {
                communicationsQuery = communicationsQuery.Where(c => (string.IsNullOrEmpty(c.Subject) && c.Name.Contains(subject)) || c.Subject.Contains(subject));
            }

            var communicationType = ddlType.SelectedValueAsEnumOrNull <CommunicationType>();

            if (communicationType != null)
            {
                communicationsQuery = communicationsQuery.Where(c => c.CommunicationType == communicationType);
            }

            string status = ddlStatus.SelectedValue;

            if (!string.IsNullOrWhiteSpace(status))
            {
                var communicationStatus = ( CommunicationStatus )System.Enum.Parse(typeof(CommunicationStatus), status);
                communicationsQuery = communicationsQuery.Where(c => c.Status == communicationStatus);
            }

            if (canApprove)
            {
                if (ppSender.PersonId.HasValue)
                {
                    communicationsQuery = communicationsQuery
                                          .Where(c =>
                                                 c.SenderPersonAlias != null &&
                                                 c.SenderPersonAlias.PersonId == ppSender.PersonId.Value);
                }
            }
            else
            {
                // If can't approve, only show current person's communications
                communicationsQuery = communicationsQuery
                                      .Where(c =>
                                             c.SenderPersonAlias != null &&
                                             c.SenderPersonAlias.PersonId == CurrentPersonId);
            }

            if (nreRecipientCount.LowerValue.HasValue)
            {
                communicationsQuery = communicationsQuery.Where(a => a.Recipients.Count() >= nreRecipientCount.LowerValue.Value);
            }

            if (nreRecipientCount.UpperValue.HasValue)
            {
                communicationsQuery = communicationsQuery.Where(a => a.Recipients.Count() <= nreRecipientCount.UpperValue.Value);
            }

            if (drpCreatedDates.LowerValue.HasValue)
            {
                communicationsQuery = communicationsQuery.Where(a => a.CreatedDateTime.HasValue && a.CreatedDateTime.Value >= drpCreatedDates.LowerValue.Value);
            }

            if (drpCreatedDates.UpperValue.HasValue)
            {
                DateTime upperDate = drpCreatedDates.UpperValue.Value.Date.AddDays(1);
                communicationsQuery = communicationsQuery.Where(a => a.CreatedDateTime.HasValue && a.CreatedDateTime.Value < upperDate);
            }

            if (drpSentDates.LowerValue.HasValue)
            {
                communicationsQuery = communicationsQuery.Where(a => (a.SendDateTime ?? a.FutureSendDateTime) >= drpSentDates.LowerValue.Value);
            }

            if (drpSentDates.UpperValue.HasValue)
            {
                DateTime upperDate = drpSentDates.UpperValue.Value.Date.AddDays(1);
                communicationsQuery = communicationsQuery.Where(a => (a.SendDateTime ?? a.FutureSendDateTime) < upperDate);
            }

            string content = tbContent.Text;

            if (!string.IsNullOrWhiteSpace(content))
            {
                communicationsQuery = communicationsQuery.Where(c =>
                                                                c.Message.Contains(content) ||
                                                                c.SMSMessage.Contains(content) ||
                                                                c.PushMessage.Contains(content));
            }

            var recipients = new CommunicationRecipientService(rockContext).Queryable();

            var communicationItemQuery = communicationsQuery
                                         .WherePersonAuthorizedToView(rockContext, this.CurrentPerson)
                                         .Select(c => new CommunicationItem
            {
                Id = c.Id,
                CommunicationType   = c.CommunicationType,
                Subject             = string.IsNullOrEmpty(c.Subject) ? (string.IsNullOrEmpty(c.PushTitle) ? c.Name : c.PushTitle) : c.Subject,
                CreatedDateTime     = c.CreatedDateTime,
                SendDateTime        = c.SendDateTime ?? c.FutureSendDateTime,
                SendDateTimePrefix  = c.SendDateTime == null && c.FutureSendDateTime != null ? "<span class='label label-info'>Future</span>&nbsp;" : string.Empty,
                Sender              = c.SenderPersonAlias != null ? c.SenderPersonAlias.Person : null,
                ReviewedDateTime    = c.ReviewedDateTime,
                Reviewer            = c.ReviewerPersonAlias != null ? c.ReviewerPersonAlias.Person : null,
                Status              = c.Status,
                Recipients          = recipients.Where(r => r.CommunicationId == c.Id).Count(),
                PendingRecipients   = recipients.Where(r => r.CommunicationId == c.Id && r.Status == CommunicationRecipientStatus.Pending).Count(),
                CancelledRecipients = recipients.Where(r => r.CommunicationId == c.Id && r.Status == CommunicationRecipientStatus.Cancelled).Count(),
                FailedRecipients    = recipients.Where(r => r.CommunicationId == c.Id && r.Status == CommunicationRecipientStatus.Failed).Count(),
                DeliveredRecipients = recipients.Where(r => r.CommunicationId == c.Id && (r.Status == CommunicationRecipientStatus.Delivered || r.Status == CommunicationRecipientStatus.Opened)).Count(),
                OpenedRecipients    = recipients.Where(r => r.CommunicationId == c.Id && r.Status == CommunicationRecipientStatus.Opened).Count()
            });

            var sortProperty = gCommunication.SortProperty;

            if (sortProperty != null)
            {
                communicationItemQuery = communicationItemQuery.Sort(sortProperty);
            }
            else
            {
                communicationItemQuery = communicationItemQuery.OrderByDescending(c => c.SendDateTime);
            }

            gCommunication.EntityTypeId = EntityTypeCache.Get <Rock.Model.Communication>().Id;
            nbBindError.Text            = string.Empty;

            try
            {
                gCommunication.SetLinqDataSource(communicationItemQuery);
                gCommunication.DataBind();
            }
            catch (Exception exception)
            {
                ExceptionLogService.LogException(exception);

                var sqlTimeoutException = ReportingHelper.FindSqlTimeoutException(exception);

                nbBindError.Text = string.Format(
                    "<p>An error occurred trying to retrieve the communication history. Please try adjusting your filter settings and try again.</p><p>Error: {0}</p>",
                    sqlTimeoutException != null ? sqlTimeoutException.Message : exception.Message);

                // if an error occurred, bind the grid with an empty object list
                gCommunication.DataSource = new List <object>();
                gCommunication.DataBind();
            }
        }
        /// <summary>
        /// Loads the response listing.
        /// </summary>
        private void LoadResponseListing(int?personId)
        {
            // NOTE: The FromPersonAliasId is the person who sent a text from a mobile device to Rock.
            // This person is also referred to as the Recipient because they are responding to a
            // communication from Rock. Restated the response is from the recipient of a communication.

            // This is the person lava field, we want to clear it because reloading this list will deselect the user.
            litSelectedRecipientDescription.Text   = string.Empty;
            hfSelectedRecipientPersonAliasId.Value = string.Empty;
            hfSelectedMessageKey.Value             = string.Empty;
            tbNewMessage.Visible      = false;
            btnSend.Visible           = false;
            btnEditNote.Visible       = false;
            lbShowImagePicker.Visible = false;
            noteEditor.Visible        = false;

            int?smsPhoneDefinedValueId = hfSmsNumber.ValueAsInt();

            if (smsPhoneDefinedValueId == default(int))
            {
                return;
            }

            try
            {
                using (var rockContext = new RockContext())
                {
                    rockContext.Database.CommandTimeout = GetAttributeValue(AttributeKey.DatabaseTimeoutSeconds).AsIntegerOrNull() ?? 180;

                    var communicationResponseService = new CommunicationResponseService(rockContext);

                    int months = GetAttributeValue(AttributeKey.ShowConversationsFromMonthsAgo).AsInteger();

                    var  startDateTime = RockDateTime.Now.AddMonths(-months);
                    bool showRead      = tglShowRead.Checked;

                    var maxConversations = this.GetAttributeValue(AttributeKey.MaxConversations).AsIntegerOrNull() ?? 1000;

                    var responseListItems = communicationResponseService.GetCommunicationResponseRecipients(smsPhoneDefinedValueId.Value, startDateTime, showRead, maxConversations, personId);

                    // don't display conversations if we're rebinding the recipient list
                    rptConversation.Visible = false;
                    gRecipients.DataSource  = responseListItems;
                    gRecipients.DataBind();
                }
            }
            catch (Exception ex)
            {
                this.LogException(ex);
                var sqlTimeoutException = ReportingHelper.FindSqlTimeoutException(ex);
                if (sqlTimeoutException != null)
                {
                    nbError.NotificationBoxType = NotificationBoxType.Warning;
                    nbError.Text    = "Unable to load SMS responses in a timely manner. You can try again or adjust the timeout setting of this block.";
                    nbError.Visible = true;
                    return;
                }
                else
                {
                    nbError.NotificationBoxType = NotificationBoxType.Danger;
                    nbError.Text    = "An error occurred when loading SMS responses";
                    nbError.Details = ex.Message;
                    nbError.Visible = true;
                    return;
                }
            }
        }
        /// <summary>
        /// Creates the table controls.
        /// </summary>
        private void BindHtmlGrid()
        {
            _financialTransactionDetailList = null;
            RockContext rockContext = new RockContext();

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

            tableColumns.Add(new RockLiteralField {
                ID = "lPerson", HeaderText = "Person"
            });
            tableColumns.Add(new RockLiteralField {
                ID = "lTransactionInfo", HeaderText = "Transaction Info"
            });
            tableColumns.Add(new RockLiteralField {
                ID = "lCheckImage", HeaderText = "Check Image"
            });
            tableColumns.Add(new RockLiteralField {
                ID = "lMatchedRegistration", HeaderText = "Matched Registration"
            });
            tableColumns.Add(new RockLiteralField {
                ID = "lButton"
            });

            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();
            var registrationEntityTypeId = EntityTypeCache.GetId <Registration>();

            if (BatchId.HasValue && RegistrationInstanceId.HasValue)
            {
                nbErrorMessage.Visible = false;
                try
                {
                    var financialTransactionDetailQuery = new FinancialTransactionDetailService(rockContext).Queryable()
                                                          .Include(a => a.Transaction)
                                                          .Include(a => a.Transaction.AuthorizedPersonAlias.Person)
                                                          .Where(a => a.Transaction.BatchId == BatchId.Value && (!a.EntityTypeId.HasValue || a.EntityTypeId == registrationEntityTypeId))
                                                          .OrderByDescending(a => a.Transaction.TransactionDateTime);

                    _financialTransactionDetailList = financialTransactionDetailQuery.Take(1000).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
                    {
                        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();

                int rowCount = 0;
                foreach (var financialTransactionDetail in _financialTransactionDetailList)
                {
                    rowCount += 1;
                    var tr = new HtmlGenericContainer("tr");
                    tr.ID = "tr_" + rowCount;
                    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 == "lTransactionInfo")
                            {
                                literalControl.Text = string.Format("<td>{0}<br/>{1}</td>", financialTransactionDetail.Amount.FormatAsCurrency(), financialTransactionDetail.Account.ToString());
                            }
                            else if (literalTableColumn.ID == "lCheckImage")
                            {
                                var primaryImage = financialTransactionDetail.Transaction.Images
                                                   .OrderBy(i => i.Order)
                                                   .FirstOrDefault();
                                string imageTag = string.Empty;
                                if (primaryImage != null)
                                {
                                    var imageUrl = string.Format("~/GetImage.ashx?id={0}", primaryImage.BinaryFileId);
                                    imageTag = string.Format("<div class='photo transaction-image' style='max-width: 400px;'><a href='{0}'><img src='{0}'/></a></div>", ResolveRockUrl(imageUrl));
                                }

                                literalControl.Text = string.Format("<td>{0}</td>", imageTag);
                            }
                            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 == "lMatchedRegistration")
                            {
                                if (financialTransactionDetail.EntityTypeId == registrationEntityTypeId && financialTransactionDetail.EntityId.HasValue)
                                {
                                    literalControl.ID   = "lMatchedRegistration_" + financialTransactionDetail.Id.ToString();
                                    literalControl.Text = string.Format("<td></td>");
                                }
                                else
                                {
                                    var tdEntityControls = new HtmlGenericContainer("td")
                                    {
                                        ID = "lMatchedRegistration_" + financialTransactionDetail.Id.ToString()
                                    };
                                    tr.Controls.Add(tdEntityControls);
                                    var ddlRegistration = new RockDropDownList {
                                        ID = "ddlRegistration_" + financialTransactionDetail.Id.ToString(), EnhanceForLongLists = true
                                    };
                                    ddlRegistration.Label                 = "Registration";
                                    ddlRegistration.AutoPostBack          = true;
                                    ddlRegistration.SelectedIndexChanged += ddlRegistration_SelectedIndexChanged;
                                    tdEntityControls.Controls.Add(ddlRegistration);
                                }
                            }
                            else if (literalTableColumn.ID == "lButton")
                            {
                                var tdEntityControls = new HtmlGenericContainer("td")
                                {
                                    ID = "pnlBtnControls_" + financialTransactionDetail.Id.ToString()
                                };
                                tr.Controls.Add(tdEntityControls);
                                var lbDelete = new LinkButton {
                                    ID = "lbDelete_" + financialTransactionDetail.Id.ToString()
                                };
                                lbDelete.CausesValidation = false;
                                lbDelete.Click           += lbDelete_Click;
                                HtmlGenericControl buttonIcon = new HtmlGenericControl("i");
                                buttonIcon.Attributes.Add("class", "fa fa-close");
                                lbDelete.Controls.Add(buttonIcon);
                                tdEntityControls.Controls.Add(lbDelete);
                                lbDelete.Visible = financialTransactionDetail.EntityTypeId == registrationEntityTypeId && financialTransactionDetail.EntityId.HasValue;
                            }
                        }
                    }

                    phTableRows.Controls.Add(tr);

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