/// <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;
            }
        }
Example #2
0
        /// <summary>
        /// Saves any user control view-state changes that have occurred since the last page postback.
        /// </summary>
        /// <returns>
        /// Returns the user control's current view state. If there is no view state associated with the control, it returns null.
        /// </returns>
        protected override object SaveViewState()
        {
            ViewState["FieldSettings"]  = this.FieldSettings.ToJson();
            ViewState["PropertyInfo"]   = _contentChannelProperties.ToJson();
            ViewState["DataViewFilter"] = ReportingHelper.GetFilterFromControls(phFilters).ToJson();
            ViewState["ChannelId"]      = ddlContentChannel.SelectedValueAsId();

            return(base.SaveViewState());
        }
Example #3
0
        /// <summary>
        /// Handles the Click event of the btnPreview 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 btnPreview_Click(object sender, EventArgs e)
        {
            DataView dv = new DataView();

            dv.TransformEntityTypeId = ddlTransform.SelectedValueAsInt();
            dv.EntityTypeId          = etpEntityType.SelectedEntityTypeId;
            dv.DataViewFilter        = ReportingHelper.GetFilterFromControls(phFilters);
            ShowPreview(dv);
        }
Example #4
0
        /// <summary>
        /// Binds the report grid.
        /// </summary>
        private void BindReportGrid()
        {
            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
            {
                nbConfigurationWarning.Visible = false;

                report.DataView.DataViewFilter = ReportingHelper.GetFilterFromControls(phFilters);

                string errorMessage;

                ReportingHelper.BindGrid(report, gReport, this.CurrentPerson, null, out errorMessage);

                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;
                    }
                }

                if (!string.IsNullOrWhiteSpace(errorMessage))
                {
                    nbReportErrors.NotificationBoxType = NotificationBoxType.Warning;
                    nbReportErrors.Text    = errorMessage;
                    nbReportErrors.Visible = true;
                }
                else
                {
                    nbReportErrors.Visible = false;
                }
            }
        }
Example #5
0
        public void GenerateReport_CreateIndexFile()
        {
            var resultFolder = @"Reporting\Test1";

            ReportingHelper.GenerateHtmlReport(new ExecutionEnvironment()
            {
                OutputDirectoryLocation = "Reporting\\Test1"
            });
            Assert.IsTrue(File.Exists(Path.Combine(resultFolder, "index.html")));
        }
Example #6
0
        private AppData()
        {
            // Piece service.

            // Playlist service.
            PlaylistService = new PlaylistService("Playlists.xml");

            // Reporting helper
            ReportingHelper = new ReportingHelper();
        }
        /// <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);
        }
Example #8
0
        /// <summary>
        /// Binds the data filters grid in the Settings dialog
        /// </summary>
        protected void BindDataFiltersGrid()
        {
            var rockContext   = new RockContext();
            var reportService = new ReportService(rockContext);

            var    reportId = rpReport.SelectedValueAsId();
            Report report   = null;

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

            nbConfigurationWarning.Visible = false;

            if (report != null && report.DataView != null && report.DataView.DataViewFilter != null)
            {
                var filters = ReportingHelper.GetFilterInfoList(report.DataView);

                // remove the top level group filter if it is just a GROUPALL
                filters = filters.Where(a => a.ParentFilter != null || a.FilterExpressionType != FilterExpressionType.GroupAll).ToList();

                // set the Title and Summary of Grouped Filters based on the GroupFilter's child filter titles
                foreach (var groupedFilter in filters.Where(a => a.FilterExpressionType != FilterExpressionType.Filter))
                {
                    groupedFilter.Title = string.Format("[{0}]", groupedFilter.FilterExpressionType.ConvertToString());
                }

                ddlPersonIdField.Visible = report.EntityTypeId != EntityTypeCache.GetId <Rock.Model.Person>();
                ddlPersonIdField.Items.Clear();
                ddlPersonIdField.Items.Add(new ListItem());
                ddlPersonIdField.Items.Add(new ListItem("Id", "Id"));
                foreach (var reportField in report.ReportFields)
                {
                    ddlPersonIdField.Items.Add(new ListItem(reportField.ColumnHeaderText, reportField.ColumnHeaderText));
                }

                rptDataFilters.Visible = true;
                mdConfigure.ServerSaveLink.Disabled = false;
                rptDataFilters.DataSource           = filters;

                rptDataFilters.DataBind();
            }
            else
            {
                rptDataFilters.Visible = false;
            }
        }
Example #9
0
        /// <summary>
        /// Binds the report grid.
        /// </summary>
        private void BindReportGrid()
        {
            var    rockContext   = new RockContext();
            var    reportService = new ReportService(rockContext);
            var    reportGuid    = this.GetAttributeValue("Report").AsGuidOrNull();
            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
            {
                nbConfigurationWarning.Visible = false;

                report.DataView.DataViewFilter = ReportingHelper.GetFilterFromControls(phFilters);

                string errorMessage;
                ReportingHelper.BindGrid(report, gReport, this.CurrentPerson, null, out errorMessage);

                if (!string.IsNullOrWhiteSpace(errorMessage))
                {
                    nbReportErrors.NotificationBoxType = NotificationBoxType.Warning;
                    nbReportErrors.Text    = errorMessage;
                    nbReportErrors.Visible = true;
                }
                else
                {
                    nbReportErrors.Visible = false;
                }
            }
        }
Example #10
0
        public void Run()
        {
            ApiAuthentication auth = null;

            //auth = new PasswordAuthentication("username", "passsword", "developerToken");

            auth = new OAuthAuthentication(
                "accessToken",
                "refreshToken",
                "developerToken",
                DateTime.UtcNow.Ticks,
                "clientId");

            IList <AccountInfo> accounts = null;

            using (CustomerMHelper cs = new CustomerMHelper(LogHandler))
            {
                var response = cs.TryGetAccountsInfo(auth, CustomerId, true);
                if (response != null && response.AccountsInfo != null)
                {
                    accounts = response.AccountsInfo.ToList();
                }
            }

            if (accounts == null || accounts.Count == 0)
            {
                return;
            }

            //you can submit a report request which could most contain 1000 accountIds per time
            //if you have more than 1000 accounts, then you should submit the report request every 1000 accountIds
            //for demo, we just pick up the first 1000 accountIds
            if (accounts.Count > 1000)
            {
                accounts = accounts.TakeWhile((p, i) => { return(i < 1000); }).ToList();
            }

            using (ReportingHelper rs = new ReportingHelper(LogHandler))
            {
                //Submit & download
                var succeed =
                    rs.TrySubmitGenerateReport(auth, BuildRequest(accounts.Select(p => p.Id).ToArray()), CustomerId, null, SaveFilePath);
            }
        }
Example #11
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)
        {
            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);
            }
        }
Example #12
0
        /// <summary>
        /// Saves the data view filter and removes the old one.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <returns>
        /// A reference to the new DataViewFilter.
        /// </returns>
        private DataViewFilter SaveDataViewFilter(RockContext rockContext)
        {
            var dataViewFilter = ReportingHelper.GetFilterFromControls(phFilters);

            // update Guids since we are creating a new dataFilter and children and deleting the old one
            SetNewDataFilterGuids(dataViewFilter);

            DataViewFilterService dataViewFilterService = new DataViewFilterService(rockContext);

            int?dataViewFilterId = hfDataFilterId.Value.AsIntegerOrNull();

            if (dataViewFilterId.HasValue)
            {
                var oldDataViewFilter = dataViewFilterService.Get(dataViewFilterId.Value);
                DeleteDataViewFilter(oldDataViewFilter, dataViewFilterService);
            }

            dataViewFilterService.Add(dataViewFilter);

            rockContext.SaveChanges();

            return(dataViewFilter);
        }
Example #13
0
 public ParametersTEXBuilder(ITeXBuilderRepository builderRepository, IDisplayUnitRetriever displayUnitRetriever)
 {
     _builderRepository = builderRepository;
     _reportingHelper   = new ReportingHelper(displayUnitRetriever);
 }
Example #14
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;
            }
        }
Example #15
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>
 /// Saves any user control view-state changes that have occurred since the last page postback.
 /// </summary>
 /// <returns>
 /// Returns the user control's current view state. If there is no view state associated with the control, it returns null.
 /// </returns>
 protected override object SaveViewState()
 {
     ViewState["DataViewFilter"] = ReportingHelper.GetFilterFromControls(phFilters).ToJson();
     return(base.SaveViewState());
 }
Example #18
0
 /// <summary>
 /// Saves any user control view-state changes that have occurred since the last page postback.
 /// </summary>
 /// <returns>
 /// Returns the user control's current view state. If there is no view state associated with the control, it returns null.
 /// </returns>
 protected override object SaveViewState()
 {
     ViewState["DataViewFilter"] = ReportingHelper.GetFilterFromControls(phFilters).ToJson();
     ViewState["EntityTypeId"]   = etpEntityType.SelectedEntityTypeId;
     return(base.SaveViewState());
 }
Example #19
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;
            }
        }
 public ParameterStartValuesBuildingBlockReporter(IDisplayUnitRetriever displayUnitRetriever) : base(Constants.PARAMETER_START_VALUES_BUILDING_BLOCK, Constants.PARAMETER_START_VALUES_BUILDING_BLOCKS)
 {
     _reportingHelper = new ReportingHelper(displayUnitRetriever);
 }
Example #21
0
        public static async Task Main(string[] args)
        {
            var config = new NLog.Config.LoggingConfiguration();

            // Targets where to log to: File and Console
            //var logfile = new NLog.Targets.FileTarget("logfile") { FileName = "file.txt" };
            //config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile);

            // Rules for mapping loggers to targets
            var logconsole = new NLog.Targets.ConsoleTarget("logconsole");

            config.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole);

            // Apply config
            LogManager.Configuration = config;


            var fluentParser = SetupArguments();
            ICommandLineParserResult result;

            result = fluentParser.Parse(args);



            if (result.HasErrors == false)
            {
                List <string> tests = new List <string>();

                for (int index = 0; index < LogManager.Configuration.LoggingRules.Count; index++)
                {
                    LogManager.Configuration.LoggingRules[index].SetLoggingLevels(fluentParser.Object.LogLevel, LogLevel.Fatal);
                }

                if (fluentParser.Object.Tests != null)
                {
                    tests.AddRange(fluentParser.Object.Tests);
                }

                if (fluentParser.Object.TestsLocation != null)
                {
                    var testfiles = Directory.GetFiles(fluentParser.Object.TestsLocation, "*.json", SearchOption.TopDirectoryOnly);
                    foreach (var testfile in testfiles)
                    {
                        tests.Add(Path.Combine(fluentParser.Object.TestsLocation, testfile));
                    }
                }

                if (tests.Count > 0)
                {
                    if (fluentParser.Object.ParallelScope == ParallelScope.None)
                    {
                        _log_.Info("Executing tests in series");
                        List <ITest> testExecutions = new List <ITest>();
                        foreach (var test in tests)
                        {
                            testExecutions.Add(await ExecuteTestAsync(test, fluentParser.Object));
                        }
                        WriteTestResults(testExecutions);
                        ReportingHelper.GenerateHtmlReport(fluentParser.Object);
                    }

                    if (fluentParser.Object.ParallelScope == ParallelScope.All)
                    {
                        _log_.Info("Executing tests in parallel");
                        List <Task <ITest> > tasks = new List <Task <ITest> >();
                        foreach (var test in tests)
                        {
                            tasks.Add(ExecuteTestAsync(test, fluentParser.Object));
                        }

                        Task.WaitAll(tasks.ToArray());

                        var testExecutions = tasks.Select(ts => ts.Result);

                        WriteTestResults(testExecutions);
                        ReportingHelper.GenerateHtmlReport(fluentParser.Object);
                        if (testExecutions.Where(t => t.Failed.HasValue && t.Failed.Value).Count() > 0)
                        {
                            _log_.Error($"{testExecutions.Where(t => t.Failed.HasValue && t.Failed.Value).Count()} / {testExecutions.Count()} failed tests");
                            Environment.Exit(exitCode: 19);
                        }
                        else
                        {
                            Environment.Exit(exitCode: 0);
                        }
                    }
                }
                else
                {
                    _log_.Error("Spider-cli: ");
                    _log_.Error(result.ErrorText);
                    _log_.Error("Try `Spider-cli.exe --help' for more information.");
                    Environment.Exit(exitCode: 21);
                }
            }
        }
        /// <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;
                }
            }
        }
Example #23
0
        private void GetResult(Guid verResultJobId)
        {
            bool gotIt    = false;
            int  waitTime = 1000;
            int  cnt      = 0;

            do
            {
                Thread.Sleep(waitTime);
                UpdateProgress(cnt++ % 2 == 0 ? $"Getting result..." : $"Please wait...");

                try
                {
                    using (var client = SslScsServiceClientBuilder.CreateSslClient <INetworkBVPSService>(
                               new ScsTcpEndPoint(Program.ServerIp, Program.ServerPort)
                               , Program.ServerPublicKey
                               , Program.ServerIp
                               , SslScsAuthMode.ServerAuth
                               , null
                               ))
                    {
                        client.Timeout = 10 * 60 * 1000;//timeout 10 minutes
                        var details = new RequiredCommunicationDetails
                        {
                            JobId           = verResultJobId,
                            DeviceID        = Program.DeviceId,
                            TimeStamp       = DateTime.Now,
                            ScanningDetails = RequiredDetailsHelper.GetRequiredScanningDetails()
                        };


                        var requiredDetails = new RequiredCommunicationDetailsPacket
                        {
                            DeviceID             = Program.DeviceId,
                            CommunicationDetails = details
                        };

                        requiredDetails.PrepareForSending(Program.AuthKey);

                        client.Connect();
                        var verResult = client.ServiceProxy.GetResult(requiredDetails);


                        switch (verResult.ScanningResult)
                        {
                        case ScanningReturnResult.InvalidAuthentication:
                            LogHelper.LogMessageToAll(Program.FileLogger, null, $"Scanning Refused by the server, due to ${ScanningReturnResult.InvalidAuthentication}, ID={Program.DeviceId}", LogMsgType.Warning);
                            break;

                        case ScanningReturnResult.Error:
                            MessageBox.Show(@"UNKNOWN ERROR, try again later!");
                            gotIt = true;
                            break;

                        case ScanningReturnResult.Success:
                            LogHelper.LogMessageToAll(Program.FileLogger, null, $"Scan result received succesfully for Device ID={Program.DeviceId} \n Received Response from Server {verResult.Message}", LogMsgType.Debug);
                            var report = ReportingHelper.GetCompleteReport(verResult.CompressedHTML);
                            var dial   = new SaveFileDialog();
                            dial.FileName = "Report.html";
                            dial.Filter   = "html files (*.html)|*.html";
                            BeginInvoke((Action)(() =>
                            {
                                if (dial.ShowDialog() == DialogResult.OK)
                                {
                                    File.WriteAllText(dial.FileName, report);
                                    LogHelper.LogMessageToAll(Program.FileLogger, null, $"User saved the report to {dial.FileName}", LogMsgType.Warning);
                                    Process.Start(dial.FileName);
                                }
                                else
                                {
                                    LogHelper.LogMessageToAll(Program.FileLogger, null, $"User selected not to save the report", LogMsgType.Warning);
                                }
                            }), null);


                            gotIt = true;
                            break;

                        case ScanningReturnResult.StillScanning:
                            waitTime *= 2;
                            break;

                        case ScanningReturnResult.ServerBusyJobRefused:
                            LogHelper.LogMessageToAll(Program.FileLogger, null, $"Scanning Refused by the server, due to ${ScanningReturnResult.ServerBusyJobRefused}, ID={Program.DeviceId}", LogMsgType.Warning);
                            break;

                        default:
                            throw new ArgumentOutOfRangeException();
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(@"exception [most probably server is not running] " + ex);
                    Program.FileLogger.Log(@"exception [most probably server is not running] " + ex.Message,
                                           LogMsgType.Exception);
                }
            } while (!gotIt);
            EnableUI();
        }
        public void ExportFiles(string filename, ImportExportSettings settings, IProgress<ActiveProgress> progress)
        {
            if (filename == null) throw new ArgumentNullException(nameof(filename));
            if (settings == null) throw new ArgumentNullException(nameof(settings));
            if (progress == null) throw new ArgumentNullException(nameof(progress));

            var helper = new ReportingHelper(settings, progress, type =>
            {
                switch (type)
                {
                    case ReportingStepType.Plugins:
                        return new StepInfo(RadioStreamerResources.SettingIEProcessingPlugIns,
                                            _plugInManager.GetInstalledAddIns().Count());
                    case ReportingStepType.Radios:
                        return new StepInfo(RadioStreamerResources.SettingIEProcessingRadios, _radioDatabase.Count);
                    case ReportingStepType.Scripts:
                        return new StepInfo(RadioStreamerResources.SettingIEProcessingScripts, _scriptEngine.FileNames.Count());
                    case ReportingStepType.Settings:
                        return new StepInfo(RadioStreamerResources.SettingIEProcessingSettings, _radioEnvironment.Settings.PropertyStore.Count);
                    default:
                        throw new ArgumentOutOfRangeException(nameof(type));
                }
            });

            var export = new RadioStreamerExport(settings);

            var store = _radioEnvironment.Settings.PropertyStore;

            if (settings.ProcessSettings)
            {
                helper.SwitchToStep(ReportingStepType.Settings);
                foreach (var name in store)
                {
                    helper.Step();
                    string value = store.GetValue(name, null);
                    if (!string.IsNullOrEmpty(value)) export.RadioSettings[name] = value;
                }
            }

            if (settings.ProcessRadios)
            {
                helper.SwitchToStep(ReportingStepType.Radios);
                foreach (var radioEntry in _radioDatabase.GetRadios())
                {
                    helper.Step();
                    var entry = new ExportRadio();
                    var qentry = new ExportQuality {Name = radioEntry.Name};

                    if (radioEntry.Metadata == null) continue;

                    entry.Entries.AddRange(GetEntries(radioEntry.Metadata));

                    foreach (var quality in radioEntry.Metadata.GetQualitys())
                    {
                        var qent = new QualityEntry();
                        qent.Entries.AddRange(GetEntries(radioEntry.Metadata.GetQuality(quality)));
                        qentry.Qualitys.Add(qent);
                    }

                    export.Qualities.Add(qentry);
                    export.Radios.Add(entry);
                }
            }

            if (settings.ProcessPlugIns)
            {
                helper.SwitchToStep(ReportingStepType.Plugins);
                foreach (var installedPackInfo in _plugInManager.GetInstalledAddIns())
                {
                    helper.Step();
                    export.PlugIns.Add(installedPackInfo.Name);
                }
            }

            if (settings.ProcessScripts)
            {
                helper.SwitchToStep(ReportingStepType.Scripts);
                foreach (var scriptFile in _scriptEngine.FileNames)
                {
                    helper.Step();
                    export.Scripts.Add(new ExportScript(scriptFile.GetFileName(), scriptFile.ReadAllBytesIfExis()));
                }
            }

            progress.Report(new ActiveProgress(RadioStreamerResources.SettingIEProcessingFile, 0, 100));

            using (var stream = new DeflateStream(new FileStream(filename, FileMode.Create),CompressionLevel.Optimal))
            {
                new BinaryFormatter().Serialize(stream, export);
            }
        }
        public void ImportFiles(string file, bool merge, ImportExportSettings settings, IProgress<ActiveProgress> progress)
        {
            if (file == null) throw new ArgumentNullException(nameof(file));
            if (settings == null) throw new ArgumentNullException(nameof(settings));
            if (progress == null) throw new ArgumentNullException(nameof(progress));

            try
            {
                progress.Report(new ActiveProgress(RadioStreamerResources.SettingIEProcessingFile, 0, 0));

                RadioStreamerExport exported;

                using (var stream = new DeflateStream(new FileStream(file, FileMode.Open), CompressionMode.Decompress))
                    exported = (RadioStreamerExport) new BinaryFormatter().Deserialize(stream);

                var exportSettings = exported.ImportExportSettings.Merge(settings);

                var helper = new ReportingHelper(exportSettings, progress, type =>
                {
                    switch (type)
                    {
                        case ReportingStepType.Plugins:
                            return new StepInfo(RadioStreamerResources.SettingIEProcessingPlugIns, exported.PlugIns.Count);
                        case ReportingStepType.Radios:
                            return new StepInfo(RadioStreamerResources.SettingIEProcessingRadios, exported.Radios.Count + 1);
                        case ReportingStepType.Scripts:
                            return new StepInfo(RadioStreamerResources.SettingIEProcessingScripts, exported.Scripts.Count + 1);
                        case ReportingStepType.Settings:
                            return new StepInfo(RadioStreamerResources.SettingIEProcessingSettings, exported.RadioSettings.Count);
                        default:
                            throw new ArgumentOutOfRangeException("type");
                    }
                });

                if (exportSettings.ProcessSettings)
                {
                    helper.SwitchToStep(ReportingStepType.Settings);
                    var store = _radioEnvironment.Settings.PropertyStore;

                    foreach (var setting in exported.RadioSettings)
                    {
                        helper.Step();
                        store.SetValue(setting.Key, setting.Value);
                    }

                    _radioEnvironment.Settings.Save();
                    _radioEnvironment.ReloadSetting();
                }

                if (exportSettings.ProcessRadios)
                {
                    helper.SwitchToStep(ReportingStepType.Radios);
                    if (!merge) _radioDatabase.Clear();

                    var fac = _radioDatabase.GetEntryFactory();

                    fac.BeginChanging();
                    try
                    {
                        foreach (var exportRadio in exported.Radios)
                        {
                            helper.Step();
                            var name = exportRadio.Entries.FirstOrDefault(e => e.Key == RadioEntry.MetaName);
                            if (name == null) continue;

                            bool cr;
                            var ent = fac.AddOrGetEntry(name.Value, out cr);
                            var meta = ent.Metadata;
                            if (meta == null) continue;

                            foreach (var metadataEntry in exportRadio.Entries) meta[metadataEntry.Key] = metadataEntry.Value;

                            var qfac = new RadioQualityFactory(ent);
                            var equality = exported.Qualities.FirstOrDefault(q => q.Name == ent.Name);
                            if (equality == null) continue;

                            foreach (var qualityEntry in equality.Qualitys)
                            {
                                name = qualityEntry.Entries.FirstOrDefault(e => e.Key == RadioQuality.MetaName);
                                if (name == null) continue;

                                var qua = qfac.Create(name.Value, string.Empty, string.Empty);
                                meta = qua.Metadata;
                                if (meta == null) continue;

                                foreach (var metadataEntry in qualityEntry.Entries) meta[metadataEntry.Key] = metadataEntry.Value;
                            }
                        }
                    }
                    finally
                    {
                        helper.Step(RadioStreamerResources.SettingIEProcessingDatabaseSave);
                        fac.Compled();
                    }
                }

                if (exportSettings.ProcessScripts)
                {
                    helper.SwitchToStep(ReportingStepType.Scripts);

                    foreach (var script in exported.Scripts)
                    {
                        helper.Step();
                        _scriptEngine.CopyFile(script.FileName, script.Content);
                    }

                    helper.Step(RadioStreamerResources.SettingIEProcessingPrecompile);
                    _scriptEngine.PreCompile(new StringWriter());
                }

                if (!exportSettings.ProcessPlugIns) return;

                helper.SwitchToStep(ReportingStepType.Plugins);
                var installedPlagIns = new List<string>(_plugInManager.GetInstalledAddIns().Select(p => p.Name));

                foreach (var plugIn in exported.PlugIns.Where(p => !installedPlagIns.Contains(p)))
                {
                    helper.Step();
                    _plugInManager.InstallPlugIn(plugIn);
                }
            }
            catch (Exception e)
            {
                if (CriticalExceptions.IsCriticalException(e)) throw;
            }
        }
 public DataRepositoryTEXBuilder(ITeXBuilderRepository builderRepository, IDimensionFactory dimensionFactory, IDisplayUnitRetriever displayUnitRetriever)
 {
     _builderRepository = builderRepository;
     _dimensionFactory  = dimensionFactory;
     _reportingHelper   = new ReportingHelper(displayUnitRetriever);
 }
Example #27
0
 public MoleculeStartValuesBuildingBlockReporter(IDisplayUnitRetriever displayUnitRetriever)
     : base(Constants.MOLECULE_START_VALUES_BUILDING_BLOCK, Constants.MOLECULE_START_VALUES_BUILDING_BLOCKS)
 {
     _reportingHelper = new ReportingHelper(displayUnitRetriever);
 }
Example #28
0
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Init" /> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            ReportingHelper.RegisterJavascriptInclude(this);
        }
Example #29
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)
        {
            DataView dataView = null;

            var             rockContext = new RockContext();
            DataViewService service     = new DataViewService(rockContext);

            int dataViewId           = int.Parse(hfDataViewId.Value);
            int?origDataViewFilterId = null;

            if (dataViewId == 0)
            {
                dataView          = new DataView();
                dataView.IsSystem = false;
            }
            else
            {
                dataView             = service.Get(dataViewId);
                origDataViewFilterId = dataView.DataViewFilterId;
            }

            dataView.Name                             = tbName.Text;
            dataView.Description                      = tbDescription.Text;
            dataView.TransformEntityTypeId            = ddlTransform.SelectedValueAsInt();
            dataView.EntityTypeId                     = etpEntityType.SelectedEntityTypeId;
            dataView.CategoryId                       = cpCategory.SelectedValueAsInt();
            dataView.PersistedScheduleIntervalMinutes = nbPersistedScheduleIntervalMinutes.Text.AsIntegerOrNull();

            var newDataViewFilter = ReportingHelper.GetFilterFromControls(phFilters);

            if (!Page.IsValid)
            {
                return;
            }

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

            var adding = dataView.Id.Equals(0);

            if (adding)
            {
                service.Add(dataView);
            }

            rockContext.WrapTransaction(() =>
            {
                if (origDataViewFilterId.HasValue)
                {
                    // delete old report filter so that we can add the new filter (but with original guids), then drop the old filter
                    DataViewFilterService dataViewFilterService = new DataViewFilterService(rockContext);
                    DataViewFilter origDataViewFilter           = dataViewFilterService.Get(origDataViewFilterId.Value);

                    dataView.DataViewFilterId = null;
                    rockContext.SaveChanges();

                    DeleteDataViewFilter(origDataViewFilter, dataViewFilterService);
                }

                dataView.DataViewFilter = newDataViewFilter;
                rockContext.SaveChanges();
            });

            if (dataView.PersistedScheduleIntervalMinutes.HasValue)
            {
                dataView.PersistResult(GetAttributeValue("DatabaseTimeout").AsIntegerOrNull() ?? 180);
                dataView.PersistedLastRefreshDateTime = RockDateTime.Now;
                rockContext.SaveChanges();
            }

            if (adding)
            {
                // add EDIT and ADMINISTRATE to the person who added the dataView
                Rock.Security.Authorization.AllowPerson(dataView, Authorization.EDIT, this.CurrentPerson, rockContext);
                Rock.Security.Authorization.AllowPerson(dataView, Authorization.ADMINISTRATE, this.CurrentPerson, rockContext);
            }

            var qryParams = new Dictionary <string, string>();

            qryParams["DataViewId"]       = dataView.Id.ToString();
            qryParams["ParentCategoryId"] = null;
            NavigateToCurrentPageReference(qryParams);
        }
        /// <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>
        /// Handles the SaveClick event of the mdContentComponentConfig 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 mdContentComponentConfig_SaveClick(object sender, EventArgs e)
        {
            var rockContext = new RockContext();

            var dataViewFilter = ReportingHelper.GetFilterFromControls(phFilters);

            if (dataViewFilter != null)
            {
                // update Guids since we are creating a new dataFilter and children and deleting the old one
                SetNewDataFilterGuids(dataViewFilter);

                if (!Page.IsValid)
                {
                    return;
                }

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

                DataViewFilterService dataViewFilterService = new DataViewFilterService(rockContext);

                int?dataViewFilterId = hfDataFilterId.Value.AsIntegerOrNull();
                if (dataViewFilterId.HasValue)
                {
                    var oldDataViewFilter = dataViewFilterService.Get(dataViewFilterId.Value);
                    DeleteDataViewFilter(oldDataViewFilter, dataViewFilterService);
                }

                dataViewFilterService.Add(dataViewFilter);
            }

            rockContext.SaveChanges();

            ContentChannelService contentChannelService = new ContentChannelService(rockContext);
            Guid?          contentChannelGuid           = this.GetAttributeValue("ContentChannel").AsGuidOrNull();
            ContentChannel contentChannel = null;

            if (contentChannelGuid.HasValue)
            {
                contentChannel = contentChannelService.Get(contentChannelGuid.Value);
            }

            if (contentChannel == null)
            {
                contentChannel = new ContentChannel();
                contentChannel.ContentChannelTypeId = this.ContentChannelTypeId;
                contentChannelService.Add(contentChannel);
            }

            contentChannel.LoadAttributes(rockContext);
            avcContentChannelAttributes.GetEditValues(contentChannel);

            contentChannel.Name = tbComponentName.Text;
            rockContext.SaveChanges();
            contentChannel.SaveAttributeValues(rockContext);

            this.SetAttributeValue("ContentChannel", contentChannel.Guid.ToString());

            this.SetAttributeValue("ItemCacheDuration", nbItemCacheDuration.Text);

            int? contentComponentTemplateValueId   = dvpContentComponentTemplate.SelectedValue.AsInteger();
            Guid?contentComponentTemplateValueGuid = null;

            if (contentComponentTemplateValueId.HasValue)
            {
                var contentComponentTemplate = DefinedValueCache.Get(contentComponentTemplateValueId.Value);
                if (contentComponentTemplate != null)
                {
                    contentComponentTemplateValueGuid = contentComponentTemplate.Guid;
                }
            }

            this.SetAttributeValue("ContentComponentTemplate", contentComponentTemplateValueGuid.ToString());
            this.SetAttributeValue("AllowMultipleContentItems", cbAllowMultipleContentItems.Checked.ToString());
            this.SetAttributeValue("OutputCacheDuration", nbOutputCacheDuration.Text);
            this.SetAttributeValue("CacheTags", cblCacheTags.SelectedValues.AsDelimited(","));
            if (dataViewFilter != null)
            {
                this.SetAttributeValue("FilterId", dataViewFilter.Id.ToString());
            }
            else
            {
                this.SetAttributeValue("FilterId", null);
            }

            this.SaveAttributeValues();

            var block = new BlockService(rockContext).Get(this.BlockId);

            block.PreHtml  = cePreHtml.Text;
            block.PostHtml = cePostHtml.Text;
            rockContext.SaveChanges();

            mdContentComponentConfig.Hide();
            pnlContentComponentConfig.Visible = false;

            RemoveCacheItem(OUTPUT_CACHE_KEY);
            RemoveCacheItem(ITEM_CACHE_KEY);

            // reload the page to make sure we have a clean load
            NavigateToCurrentPageReference();
        }
Example #32
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();
            }
        }