Example #1
0
        public void Execute()
        {
            var filterEntityId = EntityTypeCache.GetId(typeof(SQLFilter));

            if (!filterEntityId.HasValue)
            {
                throw new System.Exception("Could not find SQL Filter");
            }

            RockContext                   rockContext                   = new RockContext();
            DataViewFilterService         dataViewFilterService         = new DataViewFilterService(rockContext);
            DataViewSqlFilterStoreService dataViewSqlFilterStoreService = new DataViewSqlFilterStoreService(rockContext);

            var filters = dataViewFilterService.Queryable().Where(s => s.EntityTypeId == filterEntityId.Value).ToList();

            List <string> hashes = new List <string>();

            foreach (var filter in filters)
            {
                hashes.Add(Helpers.Md5Hash(filter.Selection));
            }

            ReportingContext reportingContext = new ReportingContext();
            var toDelete = reportingContext.DataViewSQLFilterStores
                           .Where(s => !hashes.Contains(s.Hash))
                           .Select(s => s.Hash).Distinct().ToList();

            foreach (var hash in toDelete)
            {
                rockContext.Database.ExecuteSqlCommand(string.Format("DELETE FROM _org_secc_Reporting_DataViewSQLFilterStore WHERE Hash = '{0}'", hash));
            }
        }
        protected void lbSave_Click(object sender, EventArgs e)
        {
            var dataViewFilter = GetFilterControl();

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

            var rockContext = new RockContext();
            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();

            SetAttributeValue("Status", cblStatus.SelectedValuesAsInt.AsDelimited(","));
            SetAttributeValue("Channel", ddlChannel.SelectedValue);
            SetAttributeValue("Count", (nbCount.Text.AsIntegerOrNull() ?? 5).ToString());
            SetAttributeValue("CacheDuration", (nbItemCacheDuration.Text.AsIntegerOrNull() ?? 0).ToString());
            SetAttributeValue("OutputCacheDuration", (nbOutputCacheDuration.Text.AsIntegerOrNull() ?? 0).ToString());
            SetAttributeValue("FilterId", dataViewFilter.Id.ToString());
            SetAttributeValue("Order", kvlOrder.Value);
            SetAttributeValue("TitleLava", tbTitleLava.Text);
            SetAttributeValue("IconLava", tbIconLava.Text);
            SetAttributeValue("ImageLava", tbImageLava.Text);
            SetAttributeValue("SubtitleLava", tbSubtitleLava.Text);
            SetAttributeValue("OrderLava", tbOrder.Text);

            var ppFieldType = new PageReferenceFieldType();

            SetAttributeValue("DetailPage", ppFieldType.GetEditValue(ppDetailPage, null));

            SaveAttributeValues();

            FlushCacheItem(CONTENT_CACHE_KEY);
            FlushCacheItem(TEMPLATE_CACHE_KEY);
            FlushCacheItem(OUTPUT_CACHE_KEY);

            mdEdit.Hide();
            pnlEditModal.Visible = false;
            upnlContent.Update();
        }
Example #3
0
        /// <summary>
        /// Loads the list box items.
        /// </summary>
        private void LoadListBoxItems()
        {
            this.Items.Clear();

            if (_entityTypeId.HasValue)
            {
                // add Empty option first
                this.Items.Add(new ListItem());

                using (var rockContext = new RockContext())
                {
                    var allEntityFilters = new DataViewFilterService(rockContext)
                                           .Queryable().AsNoTracking()
                                           .Where(f => f.EntityTypeId == _entityTypeId)
                                           .ToList();

                    foreach (var dataView in new DataViewService(rockContext)
                             .GetByEntityTypeId(_entityTypeId.Value)
                             .Include("EntityType")
                             .Include("Category")
                             .Include("DataViewFilter")
                             .AsNoTracking())
                    {
                        var currentPerson = HttpContext.Current.Items["CurrentPerson"] as Person;
                        if (dataView.IsAuthorized(Authorization.VIEW, currentPerson) &&
                            dataView.DataViewFilter.IsAuthorized(Authorization.VIEW, currentPerson, allEntityFilters))
                        {
                            this.Items.Add(new ListItem(dataView.Name, dataView.Id.ToString()));
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Gets the content channel items from the Cache or from Database if not cached
        /// </summary>
        /// <param name="itemCacheKey">The item cache key.</param>
        /// <param name="itemCacheDuration">Duration of the item cache.</param>
        /// <returns></returns>
        public List <ContentChannelItem> GetContentChannelItems(string itemCacheKey, int?itemCacheDuration)
        {
            List <ContentChannelItem> contentChannelItems = null;

            if (itemCacheDuration.HasValue && itemCacheDuration.Value > 0)
            {
                contentChannelItems = GetCacheItem(itemCacheKey) as List <ContentChannelItem>;
                if (contentChannelItems != null)
                {
                    return(contentChannelItems);
                }
            }

            ContentChannelCache contentChannel = GetContentChannel();

            if (contentChannel == null)
            {
                return(null);
            }

            var rockContext = new RockContext();
            var contentChannelItemService = new ContentChannelItemService(rockContext);
            IQueryable <ContentChannelItem> contentChannelItemsQuery = contentChannelItemService.Queryable().Where(a => a.ContentChannelId == contentChannel.Id).OrderBy(a => a.Order).ThenBy(a => a.Title);

            var allowMultipleContentItems = this.GetAttributeValue("AllowMultipleContentItems").AsBoolean();

            if (!allowMultipleContentItems)
            {
                // if allowMultipleContentItems = false, just get the first one
                // if it was configured for allowMultipleContentItems previously, there might be more, but they won't show until allowMultipleContentItems is enabled again
                contentChannelItemsQuery = contentChannelItemsQuery.Take(1);
            }

            int?dataFilterId = GetAttributeValue("FilterId").AsIntegerOrNull();

            if (dataFilterId.HasValue)
            {
                var dataFilterService = new DataViewFilterService(rockContext);
                ParameterExpression paramExpression = contentChannelItemService.ParameterExpression;
                var           itemType        = typeof(Rock.Model.ContentChannelItem);
                var           dataFilter      = dataFilterService.Queryable("ChildFilters").FirstOrDefault(a => a.Id == dataFilterId.Value);
                List <string> errorMessages   = new List <string>();
                Expression    whereExpression = dataFilter != null?dataFilter.GetExpression(itemType, contentChannelItemService, paramExpression, errorMessages) : null;

                contentChannelItemsQuery = contentChannelItemsQuery.Where(paramExpression, whereExpression, null);
            }

            contentChannelItems = contentChannelItemsQuery.ToList();

            if (contentChannelItems != null && itemCacheDuration.HasValue && itemCacheDuration.Value > 0)
            {
                string cacheTags = GetAttributeValue("CacheTags") ?? string.Empty;
                AddCacheItem(itemCacheKey, contentChannelItems, itemCacheDuration.Value, cacheTags);
            }

            return(contentChannelItems);
        }
Example #5
0
 private void DeleteDataViewFilter(DataViewFilter dataViewFilter, DataViewFilterService service)
 {
     if (dataViewFilter != null)
     {
         foreach (var childFilter in dataViewFilter.ChildFilters.ToList())
         {
             DeleteDataViewFilter(childFilter, service);
         }
         service.Delete(dataViewFilter, CurrentPersonId);
     }
 }
        /// <summary>
        /// Creates the test data view.
        /// </summary>
        private static void CreateTestDataView()
        {
            var rockContext           = new RockContext();
            var dataViewService       = new DataViewService(rockContext);
            var dataViewFilterService = new DataViewFilterService(rockContext);

            var subDataViewFilter = new DataViewFilter
            {
                ForeignKey     = ForeignKey,
                ExpressionType = FilterExpressionType.Filter,
                EntityTypeId   = EntityTypeCache.Get <PropertyFilter>().Id,
                Guid           = Guid.NewGuid(),
                Selection      = $@"[""Property_MiddleName"",""1"",""{DataViewMiddleName}""]"
            };

            dataViewFilterService.Add(subDataViewFilter);
            rockContext.SaveChanges();

            var rootDataViewFilter = new DataViewFilter
            {
                ForeignKey     = ForeignKey,
                ExpressionType = FilterExpressionType.GroupAll,
                Guid           = Guid.NewGuid(),
                ChildFilters   = new List <DataViewFilter>
                {
                    subDataViewFilter
                }
            };

            dataViewFilterService.Add(rootDataViewFilter);
            rockContext.SaveChanges();

            var dataView = new DataView
            {
                ForeignKey     = ForeignKey,
                IsSystem       = false,
                Name           = "TEST " + ForeignKey,
                Description    = "TEST " + ForeignKey,
                EntityTypeId   = EntityTypeCache.Get <Person>().Id,
                Guid           = Guid.NewGuid(),
                DataViewFilter = rootDataViewFilter
            };

            dataViewService.Add(dataView);
            rockContext.SaveChanges();

            subDataViewFilter.DataView  = dataView;
            rootDataViewFilter.DataView = dataView;
            rockContext.SaveChanges();
        }
Example #7
0
        /// <summary>
        /// Handles the Click event of the btnDelete 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 btnDelete_Click(object sender, EventArgs e)
        {
            int?categoryId = null;

            var rockContext     = new RockContext();
            var dataViewService = new DataViewService(rockContext);
            var dataView        = dataViewService.Get(int.Parse(hfDataViewId.Value));

            if (dataView != null)
            {
                string errorMessage;
                if (!dataViewService.CanDelete(dataView, out errorMessage))
                {
                    ShowReadonlyDetails(dataView);
                    mdDeleteWarning.Show(errorMessage, ModalAlertType.Information);
                }
                else
                {
                    categoryId = dataView.CategoryId;

                    // delete report filter
                    try
                    {
                        DataViewFilterService dataViewFilterService = new DataViewFilterService(rockContext);
                        DeleteDataViewFilter(dataView.DataViewFilter, dataViewFilterService);
                    }
                    catch
                    {
                        // intentionally ignore if delete fails
                    }

                    dataViewService.Delete(dataView);
                    rockContext.SaveChanges();

                    // reload page, selecting the deleted data view's parent
                    var qryParams = new Dictionary <string, string>();
                    if (categoryId != null)
                    {
                        qryParams["CategoryId"] = categoryId.ToString();
                    }

                    qryParams["DataViewId"]       = null;
                    qryParams["ParentCategoryId"] = null;
                    NavigateToCurrentPageReference(qryParams);
                }
            }
        }
        /// <summary>
        /// Delete the test data
        /// </summary>
        private static void DeleteTestData()
        {
            var rockContext = new RockContext();

            var stepProgramService = new StepProgramService(rockContext);
            var stepProgramQuery   = stepProgramService.Queryable().Where(sp => sp.ForeignKey == ForeignKey);

            stepProgramService.DeleteRange(stepProgramQuery);
            rockContext.SaveChanges();

            var dataViewFilterService = new DataViewFilterService(rockContext);
            var dvfQuery = dataViewFilterService.Queryable().Where(dvf => dvf.DataView.ForeignKey == ForeignKey || dvf.ForeignKey == ForeignKey);

            dataViewFilterService.DeleteRange(dvfQuery);
            rockContext.SaveChanges();

            var dataViewService = new DataViewService(rockContext);
            var dvQuery         = dataViewService.Queryable().Where(dv => dv.ForeignKey == ForeignKey);

            dataViewService.DeleteRange(dvQuery);
            rockContext.SaveChanges();

            var personSearchKeyService = new PersonSearchKeyService(rockContext);
            var personSearchKeyQuery   = personSearchKeyService.Queryable().Where(psk => psk.PersonAlias.Person.ForeignKey == ForeignKey);

            personSearchKeyService.DeleteRange(personSearchKeyQuery);

            var personAliasService = new PersonAliasService(rockContext);
            var personAliasQuery   = personAliasService.Queryable().Where(pa => pa.Person.ForeignKey == ForeignKey || pa.ForeignKey == ForeignKey);

            personAliasService.DeleteRange(personAliasQuery);
            rockContext.SaveChanges();

            var personService = new PersonService(rockContext);
            var personQuery   = personService.Queryable().Where(p => p.ForeignKey == ForeignKey);

            personService.DeleteRange(personQuery);
            rockContext.SaveChanges();
        }
Example #9
0
        /// <summary>
        /// Handles the Click event of the btnFilter 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 btnFilter_Click(object sender, EventArgs e)
        {
            var dataViewFilterService = new DataViewFilterService(new RockContext());

            foreach (var filterControl in phFilters.ControlsOfTypeRecursive <FilterField>())
            {
                string selectionKey = string.Format("{0}_{1}_Selection", GetReportDataKeyPrefix(), filterControl.DataViewFilterGuid.ToString("N"));
                string checkedKey   = string.Format("{0}_{1}_Checked", GetReportDataKeyPrefix(), filterControl.DataViewFilterGuid.ToString("N"));
                if (filterControl.Visible)
                {
                    if (!filterControl.HideFilterCriteria)
                    {
                        // only save the preference if it is different from the original
                        var origFilter = dataViewFilterService.Get(filterControl.DataViewFilterGuid);
                        var selection  = filterControl.GetSelection();
                        if (origFilter != null && origFilter.Selection != selection)
                        {
                            this.SetUserPreference(selectionKey, selection);
                        }
                        else
                        {
                            this.DeleteUserPreference(selectionKey);
                        }
                    }

                    if (filterControl.ShowCheckbox)
                    {
                        this.SetUserPreference(checkedKey, filterControl.CheckBoxChecked.ToString());
                    }
                }
                else
                {
                    this.DeleteUserPreference(selectionKey);
                    this.DeleteUserPreference(checkedKey);
                }
            }

            BindReportGrid();
        }
Example #10
0
        /// <summary>
        /// Loads the drop down items.
        /// </summary>
        public void LoadDropDownItems()
        {
            this.Items.Clear();

            if (EntityTypeId.HasValue)
            {
                // add Empty option first
                this.Items.Add(new ListItem());

                // Get
                var categoryGuids = CategoryGuids ?? new List <Guid>();

                using (var rockContext = new RockContext())
                {
                    var allEntityFilters = new DataViewFilterService(rockContext)
                                           .Queryable().AsNoTracking()
                                           .Where(f => f.EntityTypeId == EntityTypeId)
                                           .ToList();

                    foreach (var dataView in new DataViewService(rockContext)
                             .GetByEntityTypeId(EntityTypeId.Value)
                             .Include("EntityType")
                             .Include("Category")
                             .Include("DataViewFilter")
                             .AsNoTracking())
                    {
                        if (!categoryGuids.Any() || (dataView.Category != null && categoryGuids.Contains(dataView.Category.Guid)))
                        {
                            var currentPerson = HttpContext.Current.Items["CurrentPerson"] as Person;
                            if (dataView.IsAuthorized(Authorization.VIEW, currentPerson) &&
                                dataView.DataViewFilter.IsAuthorized(Authorization.VIEW, currentPerson, allEntityFilters))
                            {
                                this.Items.Add(new ListItem(dataView.Name, dataView.Id.ToString()));
                            }
                        }
                    }
                }
            }
        }
Example #11
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 #12
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;

            using ( new UnitOfWorkScope() )
            {
                DataViewService service = new DataViewService();

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

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

                dataView.Name = tbName.Text;
                dataView.Description = tbDescription.Text;
                dataView.TransformEntityTypeId = ddlTransform.SelectedValueAsInt();
                dataView.EntityTypeId = ddlEntityType.SelectedValueAsInt();
                dataView.CategoryId = cpCategory.SelectedValueAsInt();

                dataView.DataViewFilter = GetFilterControl();

                if ( !Page.IsValid )
                {
                    return;
                }

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

                RockTransactionScope.WrapTransaction( () =>
                {
                    if ( dataView.Id.Equals( 0 ) )
                    {
                        service.Add( dataView, CurrentPersonId );
                    }

                    service.Save( dataView, CurrentPersonId );

                    // Delete old report filter
                    if ( dataViewFilterId.HasValue )
                    {
                        DataViewFilterService dataViewFilterService = new DataViewFilterService();
                        DataViewFilter dataViewFilter = dataViewFilterService.Get( dataViewFilterId.Value );
                        DeleteDataViewFilter( dataViewFilter, dataViewFilterService );
                        dataViewFilterService.Save( dataViewFilter, CurrentPersonId );
                    }

                } );
            }

            var qryParams = new Dictionary<string, string>();
            qryParams["DataViewId"] = dataView.Id.ToString();
            NavigateToPage( RockPage.Guid, qryParams );
        }
Example #13
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? dataViewFilterId = null;

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

            dataView.Name = tbName.Text;
            dataView.Description = tbDescription.Text;
            dataView.TransformEntityTypeId = ddlTransform.SelectedValueAsInt();
            dataView.EntityTypeId = ddlEntityType.SelectedValueAsInt();
            dataView.CategoryId = cpCategory.SelectedValueAsInt();

            dataView.DataViewFilter = GetFilterControl();

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

            if ( !Page.IsValid )
            {
                return;
            }

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


            if ( dataView.Id.Equals( 0 ) )
            {
                service.Add( dataView );
            }

            // Delete old report filter
            if ( dataViewFilterId.HasValue )
            {
                DataViewFilterService dataViewFilterService = new DataViewFilterService( rockContext );
                DataViewFilter dataViewFilter = dataViewFilterService.Get( dataViewFilterId.Value );
                DeleteDataViewFilter( dataViewFilter, dataViewFilterService );
            }

            rockContext.SaveChanges();

            var qryParams = new Dictionary<string, string>();
            qryParams["DataViewId"] = dataView.Id.ToString();
            NavigateToPage( RockPage.Guid, qryParams );
        }
        /// <summary>
        /// Handles the SaveClick event of the mdEdit 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 mdEdit_SaveClick(object sender, EventArgs e)
        {
            var dataViewFilter = GetFilterControl();

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

            var rockContext = new RockContext();
            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);

            //
            // Delete the old file and persist the new file - if they are different.
            //
            var binaryFileService = new BinaryFileService(rockContext);
            var oldBinaryFileGuid = GetAttributeValue("BackgroundImage").AsGuidOrNull();
            var newBinaryFile     = binaryFileService.Get(ftBackgroundImage.BinaryFileId ?? 0);

            if (oldBinaryFileGuid.HasValue && (newBinaryFile == null || oldBinaryFileGuid.Value != newBinaryFile.Guid))
            {
                var oldBinaryFile = binaryFileService.Get(oldBinaryFileGuid.Value);
                if (oldBinaryFile != null)
                {
                    oldBinaryFile.IsTemporary = true;
                }
            }
            if (newBinaryFile != null && (!oldBinaryFileGuid.HasValue || newBinaryFile.Guid != oldBinaryFileGuid.Value))
            {
                newBinaryFile.IsTemporary = false;
            }

            rockContext.SaveChanges();

            SetAttributeValue("ContentChannel", ddlChannel.SelectedValue);
            SetAttributeValue("Status", cblStatus.SelectedValuesAsInt.AsDelimited(","));
            SetAttributeValue("Layout", ddlLayout.SelectedValue);
            var ppFieldType = new PageReferenceFieldType();

            SetAttributeValue("DetailPage", ppFieldType.GetEditValue(ppDetailPage, null));
            SetAttributeValue("FilterId", dataViewFilter.Id.ToString());
            SetAttributeValue("Order", kvlOrder.Value);
            SetAttributeValue("BackgroundImage", newBinaryFile != null ? newBinaryFile.Guid.ToString() : string.Empty);
            SetAttributeValue("BackgroundImageUrl", tbBackgroundImageUrl.Text);
            SetAttributeValue("Template", ceTemplate.Text);

            SaveAttributeValues();

            mdEdit.Hide();

            ShowPreview();
        }
Example #15
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;

            using (new UnitOfWorkScope())
            {
                DataViewService service = new DataViewService();

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

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

                dataView.Name                  = tbName.Text;
                dataView.Description           = tbDescription.Text;
                dataView.TransformEntityTypeId = ddlTransform.SelectedValueAsInt();
                dataView.EntityTypeId          = ddlEntityType.SelectedValueAsInt();
                dataView.CategoryId            = cpCategory.SelectedValueAsInt();

                dataView.DataViewFilter = GetFilterControl();

                if (!Page.IsValid)
                {
                    return;
                }

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

                RockTransactionScope.WrapTransaction(() =>
                {
                    if (dataView.Id.Equals(0))
                    {
                        service.Add(dataView, CurrentPersonId);
                    }

                    service.Save(dataView, CurrentPersonId);

                    // Delete old report filter
                    if (dataViewFilterId.HasValue)
                    {
                        DataViewFilterService dataViewFilterService = new DataViewFilterService();
                        DataViewFilter dataViewFilter = dataViewFilterService.Get(dataViewFilterId.Value);
                        DeleteDataViewFilter(dataViewFilter, dataViewFilterService);
                        dataViewFilterService.Save(dataViewFilter, CurrentPersonId);
                    }
                });
            }

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

            qryParams["DataViewId"] = dataView.Id.ToString();
            NavigateToPage(this.CurrentPage.Guid, qryParams);
        }
Example #16
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();

            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 ( 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();
            NavigateToPage( RockPage.Guid, qryParams );
        }
Example #17
0
        /// <summary>
        /// Handles the Click event of the btnDelete 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 btnDelete_Click( object sender, EventArgs e )
        {
            int? categoryId = null;

            var rockContext = new RockContext();
            var dataViewService = new DataViewService( rockContext );
            var dataView = dataViewService.Get( int.Parse( hfDataViewId.Value ) );

            if ( dataView != null )
            {
                string errorMessage;
                if ( !dataViewService.CanDelete( dataView, out errorMessage ) )
                {
                    ShowReadonlyDetails( dataView );
                    mdDeleteWarning.Show( errorMessage, ModalAlertType.Information );
                }
                else
                {
                    categoryId = dataView.CategoryId;

                    // delete report filter
                    try
                    {
                        DataViewFilterService dataViewFilterService = new DataViewFilterService( rockContext );
                        DeleteDataViewFilter( dataView.DataViewFilter, dataViewFilterService );
                    }
                    catch
                    {
                        //
                    }

                    dataViewService.Delete( dataView );
                    rockContext.SaveChanges();

                    // reload page, selecting the deleted data view's parent
                    var qryParams = new Dictionary<string, string>();
                    if ( categoryId != null )
                    {
                        qryParams["CategoryId"] = categoryId.ToString();
                    }

                    NavigateToPage( RockPage.Guid, qryParams );
                }
            }
        }
Example #18
0
        protected void lbSave_Click( object sender, EventArgs e )
        {

            var dataViewFilter = GetFilterControl();

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

            var rockContext = new RockContext();
            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();

            SetAttributeValue( "Status", cblStatus.SelectedValuesAsInt.AsDelimited(",") );
            SetAttributeValue( "Channel", ddlChannel.SelectedValue );
            SetAttributeValue( "EnableDebug", cbDebug.Checked.ToString() );
            SetAttributeValue( "MergeContent", cbMergeContent.Checked.ToString() );
            SetAttributeValue( "Template", ceTemplate.Text );
            SetAttributeValue( "Count", ( nbCount.Text.AsIntegerOrNull() ?? 5 ).ToString() );
            SetAttributeValue( "CacheDuration", ( nbCacheDuration.Text.AsIntegerOrNull() ?? 5 ).ToString() );
            SetAttributeValue( "FilterId", dataViewFilter.Id.ToString() );
            SetAttributeValue( "QueryParameterFiltering", cbQueryParamFiltering.Checked.ToString() );
            SetAttributeValue( "Order", kvlOrder.Value );
            SetAttributeValue( "SetPageTitle", cbSetPageTitle.Checked.ToString() );
            SetAttributeValue( "RssAutodiscover", cbSetRssAutodiscover.Checked.ToString() );
            SetAttributeValue( "MetaDescriptionAttribute", ddlMetaDescriptionAttribute.SelectedValue );
            SetAttributeValue( "MetaImageAttribute", ddlMetaImageAttribute.SelectedValue );

            var ppFieldType = new PageReferenceFieldType();
            SetAttributeValue( "DetailPage", ppFieldType.GetEditValue( ppDetailPage, null ) );

            SaveAttributeValues();

            FlushCacheItem( CONTENT_CACHE_KEY );
            FlushCacheItem( TEMPLATE_CACHE_KEY );

            mdEdit.Hide();
            pnlEditModal.Visible = false;
            upnlContent.Update();

            ShowView();
        }
Example #19
0
        /// <summary>
        /// Shows the edit.
        /// </summary>
        public void ShowEdit()
        {
            int? filterId = hfDataFilterId.Value.AsIntegerOrNull();

            if ( ChannelGuid.HasValue )
            {
                var rockContext = new RockContext();
                var channel = new ContentChannelService( rockContext ).Queryable( "ContentChannelType" )
                    .FirstOrDefault( c => c.Guid.Equals( ChannelGuid.Value ) );
                if ( channel != null )
                {

                    cblStatus.Visible = channel.RequiresApproval;

                    cbSetRssAutodiscover.Visible = channel.EnableRss;

                    var filterService = new DataViewFilterService( rockContext );
                    DataViewFilter filter = null;

                    if ( filterId.HasValue )
                    {
                        filter = filterService.Get( filterId.Value );
                    }

                    if ( filter == null || filter.ExpressionType == FilterExpressionType.Filter )
                    {
                        filter = new DataViewFilter();
                        filter.Guid = new Guid();
                        filter.ExpressionType = FilterExpressionType.GroupAll;
                    }

                    CreateFilterControl( channel, filter, true, rockContext );

                    kvlOrder.CustomKeys = new Dictionary<string, string>();
                    kvlOrder.CustomKeys.Add( "", "" );
                    kvlOrder.CustomKeys.Add( "Title", "Title" );
                    kvlOrder.CustomKeys.Add( "Priority", "Priority" );
                    kvlOrder.CustomKeys.Add( "Status", "Status" );
                    kvlOrder.CustomKeys.Add( "StartDateTime", "Start" );
                    kvlOrder.CustomKeys.Add( "ExpireDateTime", "Expire" );
                    kvlOrder.CustomKeys.Add( "Order", "Order" );


                    // add attributes to the meta description and meta image attribute list
                    ddlMetaDescriptionAttribute.Items.Clear();
                    ddlMetaImageAttribute.Items.Clear();
                    ddlMetaDescriptionAttribute.Items.Add( "" );
                    ddlMetaImageAttribute.Items.Add( "" );

                    string currentMetaDescriptionAttribute = GetAttributeValue( "MetaDescriptionAttribute" ) ?? string.Empty;
                    string currentMetaImageAttribute = GetAttributeValue( "MetaImageAttribute" ) ?? string.Empty;

                    // add channel attributes
                    channel.LoadAttributes();
                    foreach ( var attribute in channel.Attributes )
                    {
                        var field = attribute.Value.FieldType.Field;
                        string computedKey = "C^" + attribute.Key;

                        ddlMetaDescriptionAttribute.Items.Add( new ListItem( "Channel: " + attribute.Value.ToString(), computedKey ) );

                        if ( field is Rock.Field.Types.ImageFieldType )
                        {
                            ddlMetaImageAttribute.Items.Add( new ListItem( "Channel: " + attribute.Value.ToString(), computedKey ) );
                        }
                    }

                    // add item attributes
                    AttributeService attributeService = new AttributeService( rockContext );
                    var itemAttributes = attributeService.GetByEntityTypeId( new ContentChannelItem().TypeId ).AsQueryable()
                                            .Where( a => (
                                                    a.EntityTypeQualifierColumn.Equals( "ContentChannelTypeId", StringComparison.OrdinalIgnoreCase ) &&
                                                    a.EntityTypeQualifierValue.Equals( channel.ContentChannelTypeId.ToString() ) 
                                                ) || (
                                                    a.EntityTypeQualifierColumn.Equals( "ContentChannelId", StringComparison.OrdinalIgnoreCase ) &&
                                                    a.EntityTypeQualifierValue.Equals( channel.Id.ToString() ) 
                                                ) )
                                            .ToList();

                    foreach ( var attribute in itemAttributes )
                    {
                        kvlOrder.CustomKeys.Add( "Attribute:" + attribute.Key, attribute.Name );

                        string computedKey = "I^" + attribute.Key;
                        ddlMetaDescriptionAttribute.Items.Add( new ListItem( "Item: " + attribute.Name, computedKey ) );

                        var field = attribute.FieldType.Name;

                        if ( field == "Image" )
                        {
                            ddlMetaImageAttribute.Items.Add( new ListItem( "Item: " + attribute.Name, computedKey ) );
                        }
                    }

                    // select attributes
                    SetListValue( ddlMetaDescriptionAttribute, currentMetaDescriptionAttribute );
                    SetListValue( ddlMetaImageAttribute, currentMetaImageAttribute );

                }
            }
        }
Example #20
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>
        /// 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 #22
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?dataViewFilterId = null;

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

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

            dataView.DataViewFilter = GetFilterControl();

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

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

            // Delete old report filter
            if (dataViewFilterId.HasValue)
            {
                DataViewFilterService dataViewFilterService = new DataViewFilterService(rockContext);
                DataViewFilter        dataViewFilter        = dataViewFilterService.Get(dataViewFilterId.Value);
                DeleteDataViewFilter(dataViewFilter, dataViewFilterService);
            }

            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();
            NavigateToPage(RockPage.Guid, qryParams);
        }
        /// <summary>
        /// Shows the edit.
        /// </summary>
        public void ShowEdit()
        {
            int?filterId = hfDataFilterId.Value.AsIntegerOrNull();

            if (ChannelGuid.HasValue)
            {
                var rockContext = new RockContext();
                var channel     = new ContentChannelService(rockContext).Queryable("ContentChannelType")
                                  .FirstOrDefault(c => c.Guid.Equals(ChannelGuid.Value));
                if (channel != null)
                {
                    cblStatus.Visible = channel.RequiresApproval && !channel.ContentChannelType.DisableStatus;

                    var            filterService = new DataViewFilterService(rockContext);
                    DataViewFilter filter        = null;

                    if (filterId.HasValue)
                    {
                        filter = filterService.Get(filterId.Value);
                    }

                    if (filter == null || filter.ExpressionType == FilterExpressionType.Filter)
                    {
                        filter                = new DataViewFilter();
                        filter.Guid           = new Guid();
                        filter.ExpressionType = FilterExpressionType.GroupAll;
                    }

                    CreateFilterControl(channel, filter, true, rockContext);

                    kvlOrder.CustomKeys = new Dictionary <string, string>();
                    kvlOrder.CustomKeys.Add("", "");
                    kvlOrder.CustomKeys.Add("Title", "Title");
                    kvlOrder.CustomKeys.Add("Priority", "Priority");
                    kvlOrder.CustomKeys.Add("Status", "Status");
                    kvlOrder.CustomKeys.Add("StartDateTime", "Start");
                    kvlOrder.CustomKeys.Add("ExpireDateTime", "Expire");
                    kvlOrder.CustomKeys.Add("Order", "Order");

                    string currentMetaDescriptionAttribute = GetAttributeValue("MetaDescriptionAttribute") ?? string.Empty;
                    string currentMetaImageAttribute       = GetAttributeValue("MetaImageAttribute") ?? string.Empty;

                    // add channel attributes
                    channel.LoadAttributes();
                    foreach (var attribute in channel.Attributes)
                    {
                        var    field       = attribute.Value.FieldType.Field;
                        string computedKey = "C^" + attribute.Key;
                    }

                    // add item attributes
                    AttributeService attributeService = new AttributeService(rockContext);
                    var itemAttributes = attributeService.GetByEntityTypeId(new ContentChannelItem().TypeId).AsQueryable()
                                         .Where(a => (
                                                    a.EntityTypeQualifierColumn.Equals("ContentChannelTypeId", StringComparison.OrdinalIgnoreCase) &&
                                                    a.EntityTypeQualifierValue.Equals(channel.ContentChannelTypeId.ToString())
                                                    ) || (
                                                    a.EntityTypeQualifierColumn.Equals("ContentChannelId", StringComparison.OrdinalIgnoreCase) &&
                                                    a.EntityTypeQualifierValue.Equals(channel.Id.ToString())
                                                    ))
                                         .OrderByDescending(a => a.EntityTypeQualifierColumn)
                                         .ThenBy(a => a.Order)
                                         .ToList();

                    foreach (var attribute in itemAttributes)
                    {
                        string attrKey = "Attribute:" + attribute.Key;
                        if (!kvlOrder.CustomKeys.ContainsKey(attrKey))
                        {
                            kvlOrder.CustomKeys.Add("Attribute:" + attribute.Key, attribute.Name);

                            string computedKey = "I^" + attribute.Key;

                            var field = attribute.FieldType.Name;
                        }
                    }
                }
            }
        }
        private List <ContentChannelItem> GetContent(List <string> errorMessages)
        {
            List <ContentChannelItem> items = null;

            // only load from the cache if a cacheDuration was specified
            if (ItemCacheDuration.HasValue && ItemCacheDuration.Value > 0)
            {
                items = GetCacheItem(CONTENT_CACHE_KEY) as List <ContentChannelItem>;
            }


            if (items == null)
            {
                Guid?channelGuid = GetAttributeValue("Channel").AsGuidOrNull();
                if (channelGuid.HasValue)
                {
                    var rockContext = new RockContext();
                    var service     = new ContentChannelItemService(rockContext);
                    var itemType    = typeof(Rock.Model.ContentChannelItem);

                    ParameterExpression paramExpression = service.ParameterExpression;

                    var contentChannel = new ContentChannelService(rockContext).Get(channelGuid.Value);
                    if (contentChannel != null)
                    {
                        var entityFields = HackEntityFields(contentChannel, rockContext);

                        items = new List <ContentChannelItem>();

                        var qry = service
                                  .Queryable("ContentChannel,ContentChannelType")
                                  .Where(i => i.ContentChannelId == contentChannel.Id);

                        if (contentChannel.RequiresApproval && !contentChannel.ContentChannelType.DisableStatus)
                        {
                            // Check for the configured status and limit query to those
                            var statuses = new List <ContentChannelItemStatus>();
                            foreach (string statusVal in (GetAttributeValue("Status") ?? "2").Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                            {
                                var status = statusVal.ConvertToEnumOrNull <ContentChannelItemStatus>();
                                if (status != null)
                                {
                                    statuses.Add(status.Value);
                                }
                            }
                            if (statuses.Any())
                            {
                                qry = qry.Where(i => statuses.Contains(i.Status));
                            }
                        }

                        int?dataFilterId = GetAttributeValue("FilterId").AsIntegerOrNull();
                        if (dataFilterId.HasValue)
                        {
                            var        dataFilterService = new DataViewFilterService(rockContext);
                            var        dataFilter        = dataFilterService.Queryable("ChildFilters").FirstOrDefault(a => a.Id == dataFilterId.Value);
                            Expression whereExpression   = dataFilter != null?dataFilter.GetExpression(itemType, service, paramExpression, errorMessages) : null;

                            qry = qry.Where(paramExpression, whereExpression, null);
                        }

                        // All filtering has been added, now run query, check security and load attributes
                        foreach (var item in qry.ToList())
                        {
                            if (item.IsAuthorized(Authorization.VIEW, CurrentPerson))
                            {
                                item.LoadAttributes(rockContext);
                                items.Add(item);
                            }
                        }

                        // Order the items
                        SortProperty sortProperty = null;

                        string orderBy = GetAttributeValue("Order");
                        if (!string.IsNullOrWhiteSpace(orderBy))
                        {
                            var fieldDirection = new List <string>();
                            foreach (var itemPair in orderBy.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries).Select(a => a.Split('^')))
                            {
                                if (itemPair.Length == 2 && !string.IsNullOrWhiteSpace(itemPair[0]))
                                {
                                    var sortDirection = SortDirection.Ascending;
                                    if (!string.IsNullOrWhiteSpace(itemPair[1]))
                                    {
                                        sortDirection = itemPair[1].ConvertToEnum <SortDirection>(SortDirection.Ascending);
                                    }
                                    fieldDirection.Add(itemPair[0] + (sortDirection == SortDirection.Descending ? " desc" : ""));
                                }
                            }

                            sortProperty           = new SortProperty();
                            sortProperty.Direction = SortDirection.Ascending;
                            sortProperty.Property  = fieldDirection.AsDelimited(",");

                            string[] columns = sortProperty.Property.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                            var itemQry = items.AsQueryable();
                            IOrderedQueryable <ContentChannelItem> orderedQry = null;

                            for (int columnIndex = 0; columnIndex < columns.Length; columnIndex++)
                            {
                                string column = columns[columnIndex].Trim();

                                var direction = sortProperty.Direction;
                                if (column.ToLower().EndsWith(" desc"))
                                {
                                    column    = column.Left(column.Length - 5);
                                    direction = sortProperty.Direction == SortDirection.Ascending ? SortDirection.Descending : SortDirection.Ascending;
                                }

                                try
                                {
                                    if (column.StartsWith("Attribute:"))
                                    {
                                        string attributeKey = column.Substring(10);

                                        if (direction == SortDirection.Ascending)
                                        {
                                            orderedQry = (columnIndex == 0) ?
                                                         itemQry.OrderBy(i => i.AttributeValues.Where(v => v.Key == attributeKey).FirstOrDefault().Value.SortValue) :
                                                         orderedQry.ThenBy(i => i.AttributeValues.Where(v => v.Key == attributeKey).FirstOrDefault().Value.SortValue);
                                        }
                                        else
                                        {
                                            orderedQry = (columnIndex == 0) ?
                                                         itemQry.OrderByDescending(i => i.AttributeValues.Where(v => v.Key == attributeKey).FirstOrDefault().Value.SortValue) :
                                                         orderedQry.ThenByDescending(i => i.AttributeValues.Where(v => v.Key == attributeKey).FirstOrDefault().Value.SortValue);
                                        }
                                    }
                                    else
                                    {
                                        if (direction == SortDirection.Ascending)
                                        {
                                            orderedQry = (columnIndex == 0) ? itemQry.OrderBy(column) : orderedQry.ThenBy(column);
                                        }
                                        else
                                        {
                                            orderedQry = (columnIndex == 0) ? itemQry.OrderByDescending(column) : orderedQry.ThenByDescending(column);
                                        }
                                    }
                                }
                                catch { }
                            }

                            try
                            {
                                if (orderedQry != null)
                                {
                                    items = orderedQry.ToList();
                                }
                            }
                            catch { }
                        }

                        if (ItemCacheDuration.HasValue && ItemCacheDuration.Value > 0)
                        {
                            var cacheItemPolicy = new CacheItemPolicy {
                                AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(ItemCacheDuration.Value)
                            };
                            AddCacheItem(CONTENT_CACHE_KEY, items, cacheItemPolicy);
                        }
                    }
                }
            }

            return(items);
        }
Example #25
0
        /// <summary>
        /// Loads the content.
        /// </summary>
        private void LoadContent()
        {
            var rockContext       = new RockContext();
            var eventCalendarGuid = GetAttributeValue("EventCalendar").AsGuid();
            var eventCalendar     = new EventCalendarService(rockContext).Get(eventCalendarGuid);

            if (eventCalendar == null)
            {
                lMessages.Text = "<div class='alert alert-warning'>No event calendar is configured for this block.</div>";
                lContent.Text  = string.Empty;
                return;
            }
            else
            {
                lMessages.Text = string.Empty;
            }

            var eventItemOccurrenceService = new EventItemOccurrenceService(rockContext);

            // Grab events
            // NOTE: Do not use AsNoTracking() so that things can be lazy loaded if needed
            var qry = eventItemOccurrenceService
                      .Queryable("EventItem, EventItem.EventItemAudiences,Schedule")
                      .Where(m =>
                             m.EventItem.EventCalendarItems.Any(i => i.EventCalendarId == eventCalendar.Id) &&
                             m.EventItem.IsActive);

            // Filter by campus (always include the "All Campuses" events)
            if (GetAttributeValue("UseCampusContext").AsBoolean())
            {
                var campusEntityType = EntityTypeCache.Get <Campus>();
                var contextCampus    = RockPage.GetCurrentContext(campusEntityType) as Campus;

                if (contextCampus != null)
                {
                    qry = qry.Where(e => e.CampusId == contextCampus.Id || !e.CampusId.HasValue);
                }
            }
            else
            {
                var campusGuidList = GetAttributeValue("Campuses").Split(',').AsGuidList();
                if (campusGuidList.Any())
                {
                    qry = qry.Where(e => !e.CampusId.HasValue || campusGuidList.Contains(e.Campus.Guid));
                }
            }

            // make sure they have a date range
            var dateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues(this.GetAttributeValue("DateRange"));
            var today     = RockDateTime.Today;

            dateRange.Start = dateRange.Start ?? today;
            if (dateRange.End == null)
            {
                dateRange.End = dateRange.Start.Value.AddDays(1000);
            }

            // Get the occurrences
            var occurrences          = qry.ToList();
            var occurrencesWithDates = occurrences
                                       .Select(o => new EventOccurrenceDate
            {
                EventItemOccurrence = o,
                Dates = o.GetStartTimes(dateRange.Start.Value, dateRange.End.Value).ToList()
            })
                                       .Where(d => d.Dates.Any())
                                       .ToList();

            CalendarEventDates = new List <DateTime>();

            var eventOccurrenceSummaries = new List <EventOccurrenceSummaryKFS>();

            foreach (var occurrenceDates in occurrencesWithDates)
            {
                var eventItemOccurrence = occurrenceDates.EventItemOccurrence;
                foreach (var datetime in occurrenceDates.Dates)
                {
                    CalendarEventDates.Add(datetime.Date);

                    if (datetime >= dateRange.Start.Value && datetime < dateRange.End.Value)
                    {
                        var eventAudiences = eventItemOccurrence.EventItem.EventItemAudiences;
                        eventOccurrenceSummaries.Add(new EventOccurrenceSummaryKFS
                        {
                            EventItemOccurrence = eventItemOccurrence,
                            EventItem           = eventItemOccurrence.EventItem,
                            EventItemAudiences  = eventAudiences.Select(o => DefinedValueCache.Get(o.DefinedValueId).Value).ToList(),
                            Name        = eventItemOccurrence.EventItem.Name,
                            DateTime    = datetime,
                            Date        = datetime.ToShortDateString(),
                            Time        = datetime.ToShortTimeString(),
                            Location    = eventItemOccurrence.Campus != null ? eventItemOccurrence.Campus.Name : "All Campuses",
                            Description = eventItemOccurrence.EventItem.Description,
                            Summary     = eventItemOccurrence.EventItem.Summary,
                            DetailPage  = string.IsNullOrWhiteSpace(eventItemOccurrence.EventItem.DetailsUrl) ? null : eventItemOccurrence.EventItem.DetailsUrl
                        });
                    }
                }
            }

            eventOccurrenceSummaries = eventOccurrenceSummaries
                                       .OrderBy(e => e.DateTime)
                                       .ThenBy(e => e.Name)
                                       .ToList();

            // limit results
            int?maxItems = GetAttributeValue("MaxOccurrences").AsIntegerOrNull();

            if (maxItems.HasValue)
            {
                eventOccurrenceSummaries = eventOccurrenceSummaries.Take(maxItems.Value).ToList();
            }

            var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson);

            mergeFields.Add("DetailsPage", LinkedPageUrl("DetailsPage", null));
            mergeFields.Add("EventOccurrenceSummaries", eventOccurrenceSummaries);

            //KFS Custom code to link Channels together
            var items         = GetCacheItem(CONTENT_CACHE_KEY) as List <ContentChannelItem>;
            var errorMessages = new List <string>();

            Guid?channelGuid = GetAttributeValue("ChannelforLava").AsGuidOrNull();

            if (channelGuid.HasValue)
            {
                //var rockContext = new RockContext();
                var service  = new ContentChannelItemService(rockContext);
                var itemType = typeof(Rock.Model.ContentChannelItem);

                ParameterExpression paramExpression = service.ParameterExpression;

                var contentChannel = new ContentChannelService(rockContext).Get(channelGuid.Value);

                if (contentChannel != null)
                {
                    var entityFields = HackEntityFields(contentChannel, rockContext);

                    if (items == null)
                    {
                        items = new List <ContentChannelItem>();

                        var qryChannel = service.Queryable("ContentChannel,ContentChannelType");

                        int?itemId = PageParameter("Item").AsIntegerOrNull();
                        {
                            qryChannel = qryChannel.Where(i => i.ContentChannelId == contentChannel.Id);

                            if (contentChannel.RequiresApproval)
                            {
                                // Check for the configured status and limit query to those
                                var statuses = new List <ContentChannelItemStatus>();

                                foreach (string statusVal in (GetAttributeValue("Status") ?? "2").Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                                {
                                    var status = statusVal.ConvertToEnumOrNull <ContentChannelItemStatus>();
                                    if (status != null)
                                    {
                                        statuses.Add(status.Value);
                                    }
                                }
                                if (statuses.Any())
                                {
                                    qryChannel = qryChannel.Where(i => statuses.Contains(i.Status));
                                }
                            }

                            int?dataFilterId = GetAttributeValue("FilterId").AsIntegerOrNull();
                            if (dataFilterId.HasValue)
                            {
                                var        dataFilterService = new DataViewFilterService(rockContext);
                                var        dataFilter        = dataFilterService.Queryable("ChildFilters").FirstOrDefault(a => a.Id == dataFilterId.Value);
                                Expression whereExpression   = dataFilter != null?dataFilter.GetExpression(itemType, service, paramExpression, errorMessages) : null;

                                qryChannel = qryChannel.Where(paramExpression, whereExpression, null);
                            }
                        }

                        // All filtering has been added, now run query and load attributes
                        foreach (var item in qryChannel.ToList())
                        {
                            item.LoadAttributes(rockContext);
                            items.Add(item);
                        }

                        // Order the items
                        SortProperty sortProperty = null;

                        string orderBy = GetAttributeValue("Order");
                        if (!string.IsNullOrWhiteSpace(orderBy))
                        {
                            var fieldDirection = new List <string>();
                            foreach (var itemPair in orderBy.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries).Select(a => a.Split('^')))
                            {
                                if (itemPair.Length == 2 && !string.IsNullOrWhiteSpace(itemPair[0]))
                                {
                                    var sortDirection = SortDirection.Ascending;
                                    if (!string.IsNullOrWhiteSpace(itemPair[1]))
                                    {
                                        sortDirection = itemPair[1].ConvertToEnum <SortDirection>(SortDirection.Ascending);
                                    }
                                    fieldDirection.Add(itemPair[0] + (sortDirection == SortDirection.Descending ? " desc" : ""));
                                }
                            }

                            sortProperty           = new SortProperty();
                            sortProperty.Direction = SortDirection.Ascending;
                            sortProperty.Property  = fieldDirection.AsDelimited(",");

                            string[] columns = sortProperty.Property.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                            var itemQry = items.AsQueryable();
                            IOrderedQueryable <ContentChannelItem> orderedQry = null;

                            for (int columnIndex = 0; columnIndex < columns.Length; columnIndex++)
                            {
                                string column = columns[columnIndex].Trim();

                                var direction = sortProperty.Direction;
                                if (column.ToLower().EndsWith(" desc"))
                                {
                                    column    = column.Left(column.Length - 5);
                                    direction = sortProperty.Direction == SortDirection.Ascending ? SortDirection.Descending : SortDirection.Ascending;
                                }

                                try
                                {
                                    if (column.StartsWith("Attribute:"))
                                    {
                                        string attributeKey = column.Substring(10);

                                        if (direction == SortDirection.Ascending)
                                        {
                                            orderedQry = (columnIndex == 0) ?
                                                         itemQry.OrderBy(i => i.AttributeValues.Where(v => v.Key == attributeKey).FirstOrDefault().Value.SortValue) :
                                                         orderedQry.ThenBy(i => i.AttributeValues.Where(v => v.Key == attributeKey).FirstOrDefault().Value.SortValue);
                                        }
                                        else
                                        {
                                            orderedQry = (columnIndex == 0) ?
                                                         itemQry.OrderByDescending(i => i.AttributeValues.Where(v => v.Key == attributeKey).FirstOrDefault().Value.SortValue) :
                                                         orderedQry.ThenByDescending(i => i.AttributeValues.Where(v => v.Key == attributeKey).FirstOrDefault().Value.SortValue);
                                        }
                                    }
                                    else
                                    {
                                        if (direction == SortDirection.Ascending)
                                        {
                                            orderedQry = (columnIndex == 0) ? itemQry.OrderBy(column) : orderedQry.ThenBy(column);
                                        }
                                        else
                                        {
                                            orderedQry = (columnIndex == 0) ? itemQry.OrderByDescending(column) : orderedQry.ThenByDescending(column);
                                        }
                                    }
                                }
                                catch { }
                            }

                            try
                            {
                                if (orderedQry != null)
                                {
                                    items = orderedQry.ToList();
                                }
                            }
                            catch { }
                        }

                        int?cacheDuration = GetAttributeValue("CacheDuration").AsInteger();
                        if (cacheDuration > 0)
                        {
                            AddCacheItem(CONTENT_CACHE_KEY, items, cacheDuration.Value);
                        }
                    }
                }

                if (items != null)
                {
                    mergeFields.Add("ContentChannelItems", items);
                }
            }

            lContent.Text = GetAttributeValue("LavaTemplate").ResolveMergeFields(mergeFields);
        }
Example #26
0
        /// <summary>
        /// Configures the channel specific settings.
        /// </summary>
        private void ConfigureChannelSpecificSettings()
        {
            int?filterId  = hfDataFilterId.Value.AsIntegerOrNull();
            int?channelId = ddlContentChannel.SelectedValueAsId();

            if (channelId.HasValue)
            {
                var rockContext = new RockContext();
                var channel     = new ContentChannelService(rockContext).Queryable("ContentChannelType")
                                  .FirstOrDefault(c => c.Id == channelId.Value);

                if (channel != null)
                {
                    //cblStatus.Visible = channel.RequiresApproval && !channel.ContentChannelType.DisableStatus;

                    var            filterService = new DataViewFilterService(rockContext);
                    DataViewFilter filter        = null;

                    if (filterId.HasValue)
                    {
                        filter = filterService.Get(filterId.Value);
                    }

                    if (filter == null || filter.ExpressionType == FilterExpressionType.Filter)
                    {
                        filter = new DataViewFilter
                        {
                            Guid           = new Guid(),
                            ExpressionType = FilterExpressionType.GroupAll
                        };
                    }

                    CreateFilterControl(channel, filter, true, rockContext);

                    //
                    // Setup the available order-by keys.
                    //
                    kvlOrder.CustomKeys = new Dictionary <string, string>
                    {
                        { "", "" },
                        { "Title", "Title" },
                        { "Priority", "Priority" },
                        { "Status", "Status" },
                        { "StartDateTime", "Start" },
                        { "ExpireDateTime", "Expire" },
                        { "Order", "Order" }
                    };

                    //
                    // Add item attributes to the ordery-by keys.
                    //
                    AttributeService attributeService = new AttributeService(rockContext);
                    var itemAttributes = attributeService.GetByEntityTypeId(new ContentChannelItem().TypeId, false).AsQueryable()
                                         .Where(a => (
                                                    a.EntityTypeQualifierColumn.Equals("ContentChannelTypeId", StringComparison.OrdinalIgnoreCase) &&
                                                    a.EntityTypeQualifierValue.Equals(channel.ContentChannelTypeId.ToString())
                                                    ) || (
                                                    a.EntityTypeQualifierColumn.Equals("ContentChannelId", StringComparison.OrdinalIgnoreCase) &&
                                                    a.EntityTypeQualifierValue.Equals(channel.Id.ToString())
                                                    ))
                                         .OrderByDescending(a => a.EntityTypeQualifierColumn)
                                         .ThenBy(a => a.Order)
                                         .ToAttributeCacheList();

                    foreach (var attribute in itemAttributes)
                    {
                        string attrKey = "Attribute:" + attribute.Key;
                        if (!kvlOrder.CustomKeys.ContainsKey(attrKey))
                        {
                            kvlOrder.CustomKeys.Add("Attribute:" + attribute.Key, attribute.Name);
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Gets the content.
        /// </summary>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        private List <ContentChannelItem> GetContent(List <string> errorMessages)
        {
            List <ContentChannelItem> items = null;

            Guid?channelGuid = GetAttributeValue("ContentChannel").AsGuidOrNull();

            if (channelGuid.HasValue)
            {
                var rockContext = new RockContext();
                var service     = new ContentChannelItemService(rockContext);
                var itemType    = typeof(Rock.Model.ContentChannelItem);

                var contentChannel = new ContentChannelService(rockContext).Get(channelGuid.Value);
                if (contentChannel != null)
                {
                    var entityFields = HackEntityFields(contentChannel, rockContext);

                    items = new List <ContentChannelItem>();

                    var qry = service
                              .Queryable("ContentChannel,ContentChannelType")
                              .Where(i => i.ContentChannelId == contentChannel.Id);

                    //
                    // Filter by Status
                    //
                    if (contentChannel.RequiresApproval && !contentChannel.ContentChannelType.DisableStatus)
                    {
                        var statuses = GetAttributeValues("Status")
                                       .Select(s => s.ConvertToEnumOrNull <ContentChannelItemStatus>())
                                       .Where(s => s.HasValue)
                                       .Select(s => s.Value);

                        if (statuses.Any())
                        {
                            qry = qry.Where(i => statuses.Contains(i.Status));
                        }
                    }

                    //
                    // Filer by user-supplied filter options.
                    //
                    int?dataFilterId = GetAttributeValue("FilterId").AsIntegerOrNull();
                    if (dataFilterId.HasValue)
                    {
                        var dataFilterService = new DataViewFilterService(rockContext);
                        var dataFilter        = dataFilterService.Queryable("ChildFilters").FirstOrDefault(a => a.Id == dataFilterId.Value);

                        if (dataFilter != null)
                        {
                            var        parameterExpression = service.ParameterExpression;
                            Expression whereExpression     = dataFilter.GetExpression(itemType, service, parameterExpression, errorMessages);

                            qry = qry.Where(parameterExpression, whereExpression, null);
                        }
                    }

                    //
                    // All filtering has been performed, now run query and check security.
                    //
                    foreach (var item in qry.ToList())
                    {
                        if (item.IsAuthorized(Authorization.VIEW, CurrentPerson))
                        {
                            items.Add(item);
                        }
                    }

                    //
                    // Order the items.
                    //
                    string orderBy = GetAttributeValue("Order");
                    if (!string.IsNullOrWhiteSpace(orderBy))
                    {
                        List <SortProperty> sortProperties = new List <SortProperty>();

                        //
                        // Convert the user-provided sorting options into a format that can be used by SortProperty.
                        //
                        var fieldDirection = new List <string>();
                        foreach (var itemPair in orderBy.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries).Select(a => a.Split('^')))
                        {
                            if (itemPair.Length == 2 && !string.IsNullOrWhiteSpace(itemPair[0]))
                            {
                                sortProperties.Add(new SortProperty
                                {
                                    Property  = itemPair[0],
                                    Direction = itemPair[1].ConvertToEnum <SortDirection>(SortDirection.Ascending)
                                });
                            }
                        }

                        items = OrderBy(items, sortProperties);
                    }
                }
            }

            return(items);
        }
Example #28
0
        private List<ContentChannelItem> GetContent( List<string> errorMessages )
        {
            var items = GetCacheItem( CONTENT_CACHE_KEY ) as List<ContentChannelItem>;
            bool queryParameterFiltering = GetAttributeValue( "QueryParameterFiltering" ).AsBoolean( false );

            if ( items == null || ( queryParameterFiltering && Request.QueryString.Count > 0 ) )
            {
                Guid? channelGuid = GetAttributeValue( "Channel" ).AsGuidOrNull();
                if ( channelGuid.HasValue )
                {
                    var rockContext = new RockContext();
                    var service = new ContentChannelItemService( rockContext );
                    var itemType = typeof( Rock.Model.ContentChannelItem );
                    
                    ParameterExpression paramExpression = service.ParameterExpression;

                    var contentChannel = new ContentChannelService( rockContext ).Get( channelGuid.Value );
                    if ( contentChannel != null )
                    {
                        var entityFields = HackEntityFields( contentChannel, rockContext );

                        if ( items == null )
                        {
                            items = new List<ContentChannelItem>();

                            var qry = service.Queryable( "ContentChannel,ContentChannelType" );

                            int? itemId = PageParameter( "Item" ).AsIntegerOrNull();
                            if ( queryParameterFiltering && itemId.HasValue )
                            {
                                qry = qry.Where( i => i.Id == itemId.Value );
                            }
                            else
                            {
                                qry = qry.Where( i => i.ContentChannelId == contentChannel.Id );

                                if ( contentChannel.RequiresApproval )
                                {
                                    // Check for the configured status and limit query to those
                                    var statuses = new List<ContentChannelItemStatus>();

                                    foreach ( string statusVal in ( GetAttributeValue( "Status" ) ?? "2" ).Split( new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries ) )
                                    {
                                        var status = statusVal.ConvertToEnumOrNull<ContentChannelItemStatus>();
                                        if ( status != null )
                                        {
                                            statuses.Add( status.Value );
                                        }
                                    }
                                    if ( statuses.Any() )
                                    {
                                        qry = qry.Where( i => statuses.Contains( i.Status ) );
                                    }
                                }

                                int? dataFilterId = GetAttributeValue( "FilterId" ).AsIntegerOrNull();
                                if ( dataFilterId.HasValue )
                                {
                                    var dataFilterService = new DataViewFilterService( rockContext );
                                    var dataFilter = dataFilterService.Queryable( "ChildFilters" ).FirstOrDefault( a => a.Id == dataFilterId.Value );
                                    Expression whereExpression = dataFilter != null ? dataFilter.GetExpression( itemType, service, paramExpression, errorMessages ) : null;

                                    qry = qry.Where( paramExpression, whereExpression, null );
                                }
                            }

                            // All filtering has been added, now run query and load attributes
                            foreach ( var item in qry.ToList() )
                            {
                                item.LoadAttributes( rockContext );
                                items.Add( item );
                            }

                            // Order the items
                            SortProperty sortProperty = null;

                            string orderBy = GetAttributeValue( "Order" );
                            if ( !string.IsNullOrWhiteSpace( orderBy ) )
                            {
                                var fieldDirection = new List<string>();
                                foreach ( var itemPair in orderBy.Split( new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries ).Select( a => a.Split( '^' ) ) )
                                {
                                    if ( itemPair.Length == 2 && !string.IsNullOrWhiteSpace( itemPair[0] ) )
                                    {
                                        var sortDirection = SortDirection.Ascending;
                                        if ( !string.IsNullOrWhiteSpace( itemPair[1] ) )
                                        {
                                            sortDirection = itemPair[1].ConvertToEnum<SortDirection>( SortDirection.Ascending );
                                        }
                                        fieldDirection.Add( itemPair[0] + ( sortDirection == SortDirection.Descending ? " desc" : "" ) );
                                    }
                                }

                                sortProperty = new SortProperty();
                                sortProperty.Direction = SortDirection.Ascending;
                                sortProperty.Property = fieldDirection.AsDelimited( "," );

                                string[] columns = sortProperty.Property.Split( new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries );

                                var itemQry = items.AsQueryable();
                                IOrderedQueryable<ContentChannelItem> orderedQry = null;

                                for ( int columnIndex = 0; columnIndex < columns.Length; columnIndex++ )
                                {
                                    string column = columns[columnIndex].Trim();

                                    var direction = sortProperty.Direction;
                                    if ( column.ToLower().EndsWith( " desc" ) )
                                    {
                                        column = column.Left( column.Length - 5 );
                                        direction = sortProperty.Direction == SortDirection.Ascending ? SortDirection.Descending : SortDirection.Ascending;
                                    }

                                    try
                                    {
                                        if ( column.StartsWith( "Attribute:" ) )
                                        {
                                            string attributeKey = column.Substring( 10 );

                                            if ( direction == SortDirection.Ascending )
                                            {
                                                orderedQry = ( columnIndex == 0 ) ?
                                                    itemQry.OrderBy( i => i.AttributeValues.Where( v => v.Key == attributeKey ).FirstOrDefault().Value.SortValue ) :
                                                    orderedQry.ThenBy( i => i.AttributeValues.Where( v => v.Key == attributeKey ).FirstOrDefault().Value.SortValue );
                                            }
                                            else
                                            {
                                                orderedQry = ( columnIndex == 0 ) ?
                                                    itemQry.OrderByDescending( i => i.AttributeValues.Where( v => v.Key == attributeKey ).FirstOrDefault().Value.SortValue ) :
                                                    orderedQry.ThenByDescending( i => i.AttributeValues.Where( v => v.Key == attributeKey ).FirstOrDefault().Value.SortValue );
                                            }
                                        }
                                        else
                                        {
                                            if ( direction == SortDirection.Ascending )
                                            {
                                                orderedQry = ( columnIndex == 0 ) ? itemQry.OrderBy( column ) : orderedQry.ThenBy( column );
                                            }
                                            else
                                            {
                                                orderedQry = ( columnIndex == 0 ) ? itemQry.OrderByDescending( column ) : orderedQry.ThenByDescending( column );
                                            }
                                        }
                                    }
                                    catch { }

                                }

                                try
                                {
                                    if ( orderedQry != null )
                                    {
                                        items = orderedQry.ToList();
                                    }
                                }
                                catch { }

                            }

                            int? cacheDuration = GetAttributeValue( "CacheDuration" ).AsInteger();
                            if ( cacheDuration > 0 )
                            {
                                var cacheItemPolicy = new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.Now.AddSeconds( cacheDuration.Value ) };
                                AddCacheItem( CONTENT_CACHE_KEY, items, cacheItemPolicy );
                            }
                        }


                        // If items could be filtered by querystring values, check for filters
                        if ( queryParameterFiltering )
                        {
                            var pageParameters = PageParameters();
                            if ( pageParameters.Count > 0 )
                            {
                                var propertyFilter = new Rock.Reporting.DataFilter.PropertyFilter();

                                var itemQry = items.AsQueryable();
                                foreach ( string key in PageParameters().Select( p => p.Key ).ToList() )
                                {
                                    var selection = new List<string>();
                                    selection.Add( key );

                                    var entityField = entityFields.FirstOrDefault( f => f.Name.Equals( key, StringComparison.OrdinalIgnoreCase ) );
                                    if ( entityField != null )
                                    {
                                        string value = PageParameter( key );
                                        switch ( entityField.FieldType.Guid.ToString().ToUpper() )
                                        {
                                            case Rock.SystemGuid.FieldType.DAY_OF_WEEK:
                                            case Rock.SystemGuid.FieldType.SINGLE_SELECT:
                                                {
                                                    selection.Add( value );
                                                }
                                                break;
                                            case Rock.SystemGuid.FieldType.MULTI_SELECT:
                                                {
                                                    selection.Add( ComparisonType.Contains.ConvertToInt().ToString() );
                                                    selection.Add( value );
                                                }
                                                break;
                                            default:
                                                {
                                                    selection.Add( ComparisonType.EqualTo.ConvertToInt().ToString() );
                                                    selection.Add( value );
                                                }
                                                break;
                                        }

                                        itemQry = itemQry.Where( paramExpression, propertyFilter.GetExpression( itemType, service, paramExpression, Newtonsoft.Json.JsonConvert.SerializeObject( selection ) ) );
                                    }
                                }

                                items = itemQry.ToList();

                            }
                        }
                    }
                }
            }

            return items;

        }
Example #29
0
 private void DeleteDataViewFilter( DataViewFilter dataViewFilter, DataViewFilterService service )
 {
     if ( dataViewFilter != null )
     {
         foreach ( var childFilter in dataViewFilter.ChildFilters.ToList() )
         {
             DeleteDataViewFilter( childFilter, service );
         }
         service.Delete( dataViewFilter, CurrentPersonId );
     }
 }
Example #30
0
        /// <summary>
        /// Filters the results.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="service">The service.</param>
        /// <param name="itemQry">The item qry.</param>
        /// <returns></returns>
        private IQueryable <ContentChannelItem> FilterResults(RockContext rockContext, ContentChannelItemService service, IQueryable <ContentChannelItem> itemQry)
        {
            var contentChannelId = GetAttributeValue(AttributeKeys.ContentChannel).AsInteger();
            var itemType         = typeof(Rock.Model.ContentChannelItem);
            var paramExpression  = service.ParameterExpression;

            //
            // Apply Data Filter.
            //
            int?dataFilterId = GetAttributeValue(AttributeKeys.FilterId).AsIntegerOrNull();

            if (dataFilterId.HasValue)
            {
                var        dataFilterService = new DataViewFilterService(rockContext);
                var        dataFilter        = dataFilterService.Queryable("ChildFilters").FirstOrDefault(a => a.Id == dataFilterId.Value);
                var        errorMessages     = new List <string>();
                Expression whereExpression   = dataFilter?.GetExpression(itemType, service, paramExpression, errorMessages);

                itemQry = itemQry.Where(paramExpression, whereExpression, null);
            }

            //
            // Apply page parameter filtering.
            //
            var pageParameters = RequestContext.GetPageParameters();

            if (GetAttributeValue(AttributeKeys.QueryParameterFiltering).AsBoolean() && pageParameters.Count > 0)
            {
                var propertyFilter = new Rock.Reporting.DataFilter.PropertyFilter();

                foreach (var kvp in pageParameters)
                {
                    var selection = new List <string>();

                    // Since there could be many matches by the key name for an attribute we have to construct the unique name used by EntityHelper.FindFromFilterSelection and use that
                    var attributeService = new AttributeService(rockContext);
                    var attributeGuid    = attributeService
                                           .Queryable()
                                           .Where(a => a.EntityTypeQualifierColumn == "ContentChannelId")
                                           .Where(a => a.EntityTypeQualifierValue == contentChannelId.ToString())
                                           .Where(a => a.Key == kvp.Key)
                                           .Select(a => a.Guid)
                                           .FirstOrDefault();

                    string uniqueName = kvp.Key;
                    if (attributeGuid != null)
                    {
                        uniqueName = string.Format("Attribute_{0}_{1}", kvp.Key, attributeGuid.ToString().Replace("-", string.Empty));
                    }

                    // Keep using uniquename for attributes since common keys (e.g. "category")will return mutliple values
                    selection.Add(uniqueName);

                    var entityField = Rock.Reporting.EntityHelper.FindFromFilterSelection(itemType, uniqueName, false, false);
                    if (entityField != null)
                    {
                        string value = kvp.Value;
                        switch (entityField.FieldType.Guid.ToString().ToUpper())
                        {
                        case Rock.SystemGuid.FieldType.DAY_OF_WEEK:
                        case Rock.SystemGuid.FieldType.SINGLE_SELECT:
                        {
                            selection.Add(value);
                        }
                        break;

                        case Rock.SystemGuid.FieldType.MULTI_SELECT:
                        {
                            selection.Add(ComparisonType.Contains.ConvertToInt().ToString());
                            selection.Add(value);
                        }
                        break;

                        default:
                        {
                            selection.Add(ComparisonType.EqualTo.ConvertToInt().ToString());
                            selection.Add(value);
                        }
                        break;
                        }

                        itemQry = itemQry.Where(paramExpression, propertyFilter.GetExpression(itemType, service, paramExpression, selection.ToJson()));
                    }
                }
            }

            return(itemQry);
        }
        /// <summary>
        /// Handles the Click event of the lbConfigure control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        private void lbConfigure_Click(object sender, EventArgs e)
        {
            pnlContentComponentConfig.Visible = true;
            mdContentComponentConfig.Show();

            Guid?          contentChannelGuid = this.GetAttributeValue("ContentChannel").AsGuidOrNull();
            ContentChannel contentChannel     = null;

            if (contentChannelGuid.HasValue)
            {
                contentChannel = new ContentChannelService(new RockContext()).Get(contentChannelGuid.Value);
            }

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

            tbComponentName.Text = contentChannel.Name;
            contentChannel.LoadAttributes();
            avcContentChannelAttributes.NumberOfColumns = 2;
            avcContentChannelAttributes.ValidationGroup = mdContentComponentConfig.ValidationGroup;
            avcContentChannelAttributes.AddEditControls(contentChannel);

            nbItemCacheDuration.Text = this.GetAttributeValue("ItemCacheDuration");

            DefinedTypeCache contentComponentTemplateType = DefinedTypeCache.Get(Rock.SystemGuid.DefinedType.CONTENT_COMPONENT_TEMPLATE.AsGuid());

            if (contentComponentTemplateType != null)
            {
                dvpContentComponentTemplate.DefinedTypeId = contentComponentTemplateType.Id;
            }

            DefinedValueCache contentComponentTemplate = null;
            var contentComponentTemplateValueGuid      = this.GetAttributeValue("ContentComponentTemplate").AsGuidOrNull();

            if (contentComponentTemplateValueGuid.HasValue)
            {
                contentComponentTemplate = DefinedValueCache.Get(contentComponentTemplateValueGuid.Value);
            }

            dvpContentComponentTemplate.SetValue(contentComponentTemplate);

            cbAllowMultipleContentItems.Checked = this.GetAttributeValue("AllowMultipleContentItems").AsBoolean();

            nbOutputCacheDuration.Text = this.GetAttributeValue("OutputCacheDuration");

            // Cache Tags
            cblCacheTags.DataSource = DefinedTypeCache.Get(Rock.SystemGuid.DefinedType.CACHE_TAGS.AsGuid()).DefinedValues.Select(v => v.Value).ToList();
            cblCacheTags.DataBind();
            cblCacheTags.Visible = cblCacheTags.Items.Count > 0;
            string[] selectedCacheTags = this.GetAttributeValue("CacheTags").SplitDelimitedValues();
            foreach (ListItem cacheTag in cblCacheTags.Items)
            {
                cacheTag.Selected = selectedCacheTags.Contains(cacheTag.Value);
            }

            cePreHtml.Text  = this.BlockCache.PreHtml;
            cePostHtml.Text = this.BlockCache.PostHtml;

            hfDataFilterId.Value = GetAttributeValue("FilterId");

            int?filterId    = hfDataFilterId.Value.AsIntegerOrNull();
            var rockContext = new RockContext();

            var            filterService = new DataViewFilterService(rockContext);
            DataViewFilter filter        = null;

            if (filterId.HasValue)
            {
                filter = filterService.Get(filterId.Value);
            }

            if (filter == null || filter.ExpressionType == FilterExpressionType.Filter)
            {
                filter                = new DataViewFilter();
                filter.Guid           = new Guid();
                filter.ExpressionType = FilterExpressionType.GroupAll;
            }

            CreateFilterControl(this.ContentChannelTypeId, filter, true, rockContext);
        }
Example #32
0
        /// <summary>
        /// Loads the drop down items.
        /// </summary>
        private void LoadDropDownItems()
        {
            this.Items.Clear();

            if ( _entityTypeId.HasValue )
            {
                // add Empty option first
                this.Items.Add( new ListItem() );

                using ( var rockContext = new RockContext() )
                {
                    var allEntityFilters = new DataViewFilterService( rockContext )
                        .Queryable().AsNoTracking()
                        .Where( f => f.EntityTypeId == _entityTypeId )
                        .ToList();

                    foreach ( var dataView in new DataViewService( rockContext )
                        .GetByEntityTypeId( _entityTypeId.Value )
                        .Include( "EntityType" )
                        .Include( "Category" )
                        .Include( "DataViewFilter" )
                        .AsNoTracking() )
                    {
                        var currentPerson = HttpContext.Current.Items["CurrentPerson"] as Person;
                        if ( dataView.IsAuthorized( Authorization.VIEW, currentPerson ) &&
                            dataView.DataViewFilter.IsAuthorized( Authorization.VIEW, currentPerson, allEntityFilters ) )
                        {
                            this.Items.Add( new ListItem( dataView.Name, dataView.Id.ToString() ) );
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Handles the Click event of the btnFilter 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 btnFilter_Click( object sender, EventArgs e )
        {
            var dataViewFilterService = new DataViewFilterService( new RockContext() );
            foreach ( var filterControl in phFilters.ControlsOfTypeRecursive<FilterField>() )
            {
                string selectionKey = string.Format( "{0}_{1}_Selection", GetReportDataKeyPrefix(), filterControl.DataViewFilterGuid.ToString( "N" ) );
                string checkedKey = string.Format( "{0}_{1}_Checked", GetReportDataKeyPrefix(), filterControl.DataViewFilterGuid.ToString( "N" ) );
                if ( filterControl.Visible )
                {
                    if ( !filterControl.HideFilterCriteria )
                    {
                        // only save the preference if it is different from the original
                        var origFilter = dataViewFilterService.Get( filterControl.DataViewFilterGuid );
                        var selection = filterControl.GetSelection();
                        if ( origFilter != null && origFilter.Selection != selection )
                        {
                            this.SetUserPreference( selectionKey, selection );
                        }
                        else
                        {
                            this.DeleteUserPreference( selectionKey );
                        }
                    }

                    if ( filterControl.ShowCheckbox )
                    {
                        this.SetUserPreference( checkedKey, filterControl.CheckBoxChecked.ToString() );
                    }
                }
                else
                {
                    this.DeleteUserPreference( selectionKey );
                    this.DeleteUserPreference( checkedKey );
                }
            }

            BindReportGrid();
        }
Example #34
0
        /// <summary>
        /// Creates the filter control.
        /// </summary>
        /// <param name="parentControl">The parent control.</param>
        /// <param name="filter">The filter.</param>
        /// <param name="reportEntityType">Type of the report entity.</param>
        /// <param name="setSelection">if set to <c>true</c> [set selection].</param>
        /// <param name="rockContext">The rock context.</param>
        private void CreateFilterControl(
            Control parentControl,
            DataViewFilter filter,
            EntityType reportEntityType,
            bool setSelection,
            RockContext rockContext)
        {
            try
            {
                var filteredEntityTypeName = EntityTypeCache.Get(reportEntityType).Name;
                if (filter.ExpressionType == FilterExpressionType.Filter)
                {
                    var  filterControl   = new FilterField();
                    bool filterIsVisible = _selectedDataFilterGuids.Contains(filter.Guid);

                    if (filterIsVisible)
                    {
                        // only set FilterMode to simple if the filter is visible since SimpleFilters might have a different filtering behavior
                        filterControl.FilterMode = FilterMode.SimpleFilter;
                    }
                    else
                    {
                        filterControl.FilterMode = FilterMode.AdvancedFilter;
                    }

                    bool filterIsConfigurable        = _configurableDataFilterGuids.Contains(filter.Guid);
                    bool showCheckbox                = _togglableDataFilterGuids.Contains(filter.Guid) || !filterIsConfigurable;
                    var  dataFilterPrePostHtmlConfig = _dataFiltersPrePostHtmlConfig.GetValueOrNull(filter.Guid) ?? new DataFilterPrePostHtmlConfig();

                    filterControl.Visible = filterIsVisible;

                    parentControl.Controls.Add(filterControl);

                    filterControl.DataViewFilterGuid = filter.Guid;

                    filterControl.HideFilterCriteria = !filterIsConfigurable;
                    filterControl.ID = string.Format("ff_{0}", filterControl.DataViewFilterGuid.ToString("N"));
                    filterControl.FilteredEntityTypeName = filteredEntityTypeName;

                    if (filter.EntityTypeId.HasValue)
                    {
                        var entityTypeCache = EntityTypeCache.Get(filter.EntityTypeId.Value, rockContext);
                        if (entityTypeCache != null)
                        {
                            filterControl.FilterEntityTypeName = entityTypeCache.Name;
                        }
                    }

                    filterControl.Expanded = true;

                    filterControl.ShowCheckbox    = filterIsVisible && showCheckbox;
                    filterControl.HideDescription = true;

                    var reportEntityTypeCache = EntityTypeCache.Get(reportEntityType);
                    var reportEntityTypeModel = reportEntityTypeCache.GetEntityType();

                    var filterEntityType = EntityTypeCache.Get(filter.EntityTypeId ?? 0);
                    var component        = Rock.Reporting.DataFilterContainer.GetComponent(filterEntityType.Name);
                    if (component != null)
                    {
                        string selectionUserPreference = null;
                        bool?  checkedUserPreference   = null;
                        if (setSelection && filterIsVisible)
                        {
                            if (filterIsConfigurable)
                            {
                                selectionUserPreference = this.GetUserPreference(string.Format("{0}_{1}_Selection", GetReportDataKeyPrefix(), filterControl.DataViewFilterGuid.ToString("N")));
                            }

                            if (filterControl.ShowCheckbox)
                            {
                                checkedUserPreference = this.GetUserPreference(string.Format("{0}_{1}_Checked", GetReportDataKeyPrefix(), filterControl.DataViewFilterGuid.ToString("N"))).AsBooleanOrNull() ?? true;
                            }
                        }

                        if (checkedUserPreference.HasValue)
                        {
                            filterControl.SetCheckBoxChecked(checkedUserPreference.Value);
                        }

                        if (setSelection)
                        {
                            var selection = filter.Selection;
                            if (!string.IsNullOrWhiteSpace(selectionUserPreference))
                            {
                                if (component is Rock.Reporting.DataFilter.PropertyFilter)
                                {
                                    selection = (component as Rock.Reporting.DataFilter.PropertyFilter).UpdateSelectionFromUserPreferenceSelection(selection, selectionUserPreference);
                                }
                                else
                                {
                                    selection = selectionUserPreference;
                                }
                            }

                            if (component is Rock.Reporting.DataFilter.IUpdateSelectionFromPageParameters)
                            {
                                selection = (component as Rock.Reporting.DataFilter.IUpdateSelectionFromPageParameters).UpdateSelectionFromPageParameters(selection, this);
                            }

                            try
                            {
                                filterControl.SetSelection(selection);

                                // if the selection is the same as what is stored in the database for that DataViewFilter,
                                // Do a GetSelection to get the selection in the current format for that filter
                                // This will prevent this dynamic report from thinking the selection has changed from the orig filter
                                if (selection == filter.Selection)
                                {
                                    var normalizedSelection = filterControl.GetSelection();
                                    if (normalizedSelection != filter.Selection)
                                    {
                                        // if the format of the filter.Selection has changed, update the dataViewFilter's Selection to match the current format
                                        filter.Selection = normalizedSelection;
                                        using (var updateSelectionContext = new RockContext())
                                        {
                                            var dataViewFilter = new DataViewFilterService(updateSelectionContext).Get(filter.Id);
                                            dataViewFilter.Selection = normalizedSelection;
                                            updateSelectionContext.SaveChanges();
                                        }
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                this.LogException(new Exception("Exception setting selection for DataViewFilter: " + filter.Guid, ex));
                            }
                        }

                        string defaultFilterLabel;
                        if (!filterIsConfigurable)
                        {
                            // not configurable so just label it with the selection summary
                            defaultFilterLabel = component.FormatSelection(reportEntityTypeModel, filter.Selection);

                            // configuration not visible, so set the selection to what it was in the dataview when it was saved, even if setSelection=False
                            filterControl.SetSelection(filter.Selection);
                        }
                        else if (component is Rock.Reporting.DataFilter.PropertyFilter)
                        {
                            defaultFilterLabel = (component as Rock.Reporting.DataFilter.PropertyFilter).GetSelectionLabel(reportEntityTypeModel, filter.Selection);
                        }
                        else if (component is Rock.Reporting.DataFilter.EntityFieldFilter)
                        {
                            defaultFilterLabel = (component as Rock.Reporting.DataFilter.EntityFieldFilter).GetSelectedFieldName(filter.Selection);
                        }
                        else
                        {
                            defaultFilterLabel = component.GetTitle(reportEntityTypeModel);
                        }

                        var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson, new Rock.Lava.CommonMergeFieldsOptions {
                            GetLegacyGlobalMergeFields = false
                        });
                        mergeFields.Add("Filter", filter);
                        mergeFields.Add("Label", defaultFilterLabel);

                        filterControl.Label = dataFilterPrePostHtmlConfig.LabelHtml.ResolveMergeFields(mergeFields);

                        if (!string.IsNullOrEmpty(dataFilterPrePostHtmlConfig.PreHtml))
                        {
                            filterControl.PreHtml = dataFilterPrePostHtmlConfig.PreHtml.ResolveMergeFields(mergeFields);
                        }

                        if (!string.IsNullOrEmpty(dataFilterPrePostHtmlConfig.PostHtml))
                        {
                            filterControl.PostHtml = dataFilterPrePostHtmlConfig.PostHtml.ResolveMergeFields(mergeFields);
                        }

                        if (component is Rock.Reporting.DataFilter.OtherDataViewFilter)
                        {
                            // don't include the actual DataView Picker filter, just the child filters
                            parentControl.Controls.Remove(filterControl);

                            Rock.Reporting.DataFilter.OtherDataViewFilter otherDataViewFilter = component as Rock.Reporting.DataFilter.OtherDataViewFilter;
                            var otherDataView = otherDataViewFilter.GetSelectedDataView(filter.Selection);
                            if (otherDataView != null)
                            {
                                CreateFilterControl(parentControl, otherDataView.DataViewFilter, reportEntityType, setSelection, rockContext);
                            }
                        }
                    }
                }
                else
                {
                    var groupControl = new FilterGroup();
                    parentControl.Controls.Add(groupControl);
                    groupControl.DataViewFilterGuid = filter.Guid;
                    groupControl.ID = string.Format("fg_{0}", groupControl.DataViewFilterGuid.ToString("N"));
                    groupControl.FilteredEntityTypeName = filteredEntityTypeName;
                    groupControl.IsDeleteEnabled        = false;
                    groupControl.HidePanelHeader        = true;
                    if (setSelection)
                    {
                        groupControl.FilterType = filter.ExpressionType;
                    }

                    foreach (var childFilter in filter.ChildFilters)
                    {
                        CreateFilterControl(groupControl, childFilter, reportEntityType, setSelection, rockContext);
                    }
                }
            }
            catch (Exception ex)
            {
                this.LogException(new Exception("Exception creating FilterControl for DataViewFilter: " + filter.Guid, ex));
            }
        }