/// <summary>
        /// Gets the bread crumbs.
        /// </summary>
        /// <param name="pageReference">The page reference.</param>
        /// <returns></returns>
        public override List<BreadCrumb> GetBreadCrumbs( PageReference pageReference )
        {
            var breadCrumbs = new List<BreadCrumb>();

            var itemIds = GetNavHierarchy().AsIntegerList();
            int? itemId = PageParameter( pageReference, "contentItemId" ).AsIntegerOrNull();
            if ( itemId != null )
            {
                itemIds.Add( itemId.Value );
            }

            foreach( var contentItemId in itemIds )
            {
                ContentChannelItem contentItem = new ContentChannelItemService( new RockContext() ).Get( contentItemId );
                if ( contentItem != null )
                {
                    breadCrumbs.Add( new BreadCrumb( contentItem.Title, pageReference ) );
                }
                else
                {
                    breadCrumbs.Add( new BreadCrumb( "New Content Item", pageReference ) );
                }
            }

            return breadCrumbs;
        }
Example #2
0
        /// <summary>
        /// Handles the GridReorder event of the GItems control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="GridReorderEventArgs"/> instance containing the event data.</param>
        private void GItems_GridReorder(object sender, GridReorderEventArgs e)
        {
            using (var rockContext = new RockContext())
            {
                bool isFiltered = false;
                var  items      = GetItems(rockContext, out isFiltered);

                if (!isFiltered)
                {
                    var service = new ContentChannelItemService(rockContext);
                    service.Reorder(items, e.OldIndex, e.NewIndex);
                    rockContext.SaveChanges();
                }
            }

            BindGrid();
        }
Example #3
0
        /// <summary>
        /// Gets the type of the content.
        /// </summary>
        /// <param name="contentItemId">The content type identifier.</param>
        /// <param name="rockContext">The rock context.</param>
        /// <returns></returns>
        private ContentChannelItem GetContentItem(RockContext rockContext = null)
        {
            rockContext = rockContext ?? new RockContext();
            var contentItemService         = new ContentChannelItemService(rockContext);
            ContentChannelItem contentItem = null;

            int contentItemId = hfId.Value.AsInteger();

            if (contentItemId != 0)
            {
                contentItem = contentItemService
                              .Queryable("ContentChannel,ContentChannelType")
                              .FirstOrDefault(t => t.Id == contentItemId);
            }

            if (contentItem == null)
            {
                var contentChannel = new ContentChannelService(rockContext).Get(hfChannelId.Value.AsInteger());
                if (contentChannel != null)
                {
                    contentItem = new ContentChannelItem
                    {
                        ContentChannel       = contentChannel,
                        ContentChannelId     = contentChannel.Id,
                        ContentChannelType   = contentChannel.ContentChannelType,
                        ContentChannelTypeId = contentChannel.ContentChannelType.Id,
                        StartDateTime        = RockDateTime.Now
                    };

                    if (contentChannel.RequiresApproval)
                    {
                        contentItem.Status = ContentChannelItemStatus.PendingApproval;
                    }
                    else
                    {
                        contentItem.Status                  = ContentChannelItemStatus.Approved;
                        contentItem.ApprovedDateTime        = RockDateTime.Now;
                        contentItem.ApprovedByPersonAliasId = CurrentPersonAliasId;
                    }

                    contentItemService.Add(contentItem);
                }
            }

            return(contentItem);
        }
        public IQueryable <ContentChannelItem> ContentChannelItemsByAttributeValue(int campusId)
        {
            RockContext rockContext = new RockContext();

            string campusGuid = new CampusService(rockContext).Get(campusId).Guid.ToString();

            // Get the Id of the Rock.Model.ContentChannelItem Entity.
            int contentChannelItemEntityTypeId = EntityTypeCache.Get("Rock.Model.ContentChannelItem").Id;

            // Get the Field Type (Attribute Type) Id of the Data View Field Type.
            int fieldTypeId = FieldTypeCache.Get(Rock.SystemGuid.FieldType.CAMPUSES.AsGuid()).Id;

            // Get the list of attributes that are of the Rock.Model.ContentChannelItem entity type
            // and that are of the Campus field type.
            List <int> campusAttributeIdList = new AttributeService(rockContext)
                                               .GetByEntityTypeId(contentChannelItemEntityTypeId)
                                               .Where(item => item.FieldTypeId == fieldTypeId)
                                               .Select(a => a.Id)
                                               .ToList();

            List <string> campusAttributeIdKeyList = new AttributeService(rockContext)
                                                     .GetByEntityTypeId(contentChannelItemEntityTypeId)
                                                     .Where(item => item.FieldTypeId == fieldTypeId)
                                                     .Select(a => a.Key)
                                                     .ToList();

            var avsWithCampus = new AttributeValueService(rockContext).Queryable()
                                .Where(a => campusAttributeIdList.Contains(a.AttributeId))
                                .Where(a => a.Attribute.EntityTypeId == contentChannelItemEntityTypeId)
                                .Where(a => a.Value.Contains(campusGuid))
                                .Select(a => a.EntityId);



            // I want a list of content channel items whose ids match up to attribute values that represent entity ids
            IQueryable <ContentChannelItem> contentChannelItemList = new ContentChannelItemService(rockContext)
                                                                     .Queryable()
                                                                     .AsNoTracking()
                                                                     .Where(c => avsWithCampus.Contains(c.Id) || c.Attributes.Keys.Contains(campusAttributeIdKeyList.FirstOrDefault()));



            // Return this list
            return(contentChannelItemList);
        }
Example #5
0
        protected void lbDeleteChildItem_Click(object sender, EventArgs e)
        {
            using (var rockContext = new RockContext())
            {
                int childItemId = hfRemoveChildItem.ValueAsInt();

                var service   = new ContentChannelItemService(rockContext);
                var childItem = service.Get(childItemId);
                if (childItem != null)
                {
                    service.Delete(childItem);
                    rockContext.SaveChanges();
                }
            }

            BindChildItemsGrid(GetContentItem());

            HideDialog();
        }
Example #6
0
        /// <summary>
        /// Gets the content channel item using the first page parameter or ContentChannelQueryParameter
        /// </summary>
        /// <returns></returns>
        private ContentChannelItem GetContentChannelItemFromKey(string contentChannelItemKey)
        {
            Guid?contentChannelGuid = GetAttributeValue("ContentChannel").AsGuidOrNull();

            ContentChannelItem contentChannelItem = null;

            if (string.IsNullOrEmpty(contentChannelItemKey))
            {
                return(null);
            }

            //
            // Look up the ContentChannelItem from either the Id, Guid, or
            // Slug depending on the datatype of the ContentChannelQueryParameter value
            //
            int? contentChannelItemId   = contentChannelItemKey.AsIntegerOrNull();
            Guid?contentChannelItemGuid = contentChannelItemKey.AsGuidOrNull();

            var rockContext = new RockContext();

            if (contentChannelItemId.HasValue)
            {
                contentChannelItem = new ContentChannelItemService(rockContext).Get(contentChannelItemId.Value);
            }
            else if (contentChannelItemGuid.HasValue)
            {
                contentChannelItem = new ContentChannelItemService(rockContext).Get(contentChannelItemGuid.Value);
            }
            else
            {
                var contentChannelQuery = new ContentChannelItemService(rockContext).Queryable();
                if (contentChannelGuid.HasValue)
                {
                    contentChannelQuery = contentChannelQuery.Where(c => c.ContentChannel.Guid == contentChannelGuid);
                }

                contentChannelItem = contentChannelQuery
                                     .Where(a => a.ContentChannelItemSlugs.Any(s => s.Slug == contentChannelItemKey))
                                     .FirstOrDefault();
            }

            return(contentChannelItem);
        }
Example #7
0
        public object SaveUserValues(Guid itemGuid, Dictionary <string, string> userValues)
        {
            if (RequestContext.CurrentPerson == null)
            {
                return(ActionStatusCode(System.Net.HttpStatusCode.Unauthorized));
            }

            using (var rockContext = new RockContext())
            {
                var contentChannelItemService = new ContentChannelItemService(rockContext);
                var noteService = new NoteService(rockContext);
                var noteTypeId  = NoteTypeCache.Get(SystemGuid.NoteType.CONTENT_CHANNEL_ITEM_STRUCTURED_CONTENT_USER_VALUE).Id;

                var item = contentChannelItemService.Get(itemGuid);

                if (item == null)
                {
                    return(ActionNotFound());
                }

                var note = noteService.Queryable()
                           .Where(a => a.NoteTypeId == noteTypeId && a.EntityId == item.Id)
                           .Where(a => a.CreatedByPersonAliasId.HasValue && a.CreatedByPersonAlias.PersonId == RequestContext.CurrentPerson.Id)
                           .FirstOrDefault();

                if (note == null)
                {
                    note = new Note
                    {
                        NoteTypeId = noteTypeId,
                        EntityId   = item.Id
                    };

                    noteService.Add(note);
                }

                note.Text = userValues.ToJson();

                rockContext.SaveChanges();
            }

            return(ActionOk());
        }
Example #8
0
        /// <summary>
        /// Sets the value. ( as Guid )
        /// </summary>
        /// <param name="control">The control.</param>
        /// <param name="configurationValues">The configuration values.</param>
        /// <param name="value">The value.</param>
        public override void SetEditValue(System.Web.UI.Control control, Dictionary <string, ConfigurationValue> configurationValues, string value)
        {
            var picker = control as ContentChannelItemPicker;

            if (picker != null)
            {
                int? itemId   = null;
                Guid?itemGuid = value.AsGuidOrNull();
                if (itemGuid.HasValue)
                {
                    using (var rockContext = new RockContext())
                    {
                        itemId = new ContentChannelItemService(rockContext).Queryable().Where(a => a.Guid == itemGuid.Value).Select(a => ( int? )a.Id).FirstOrDefault();
                    }
                }

                picker.ContentChannelItemId = itemId;
            }
        }
Example #9
0
        /// <summary>
        /// Returns the field's current value(s)
        /// </summary>
        /// <param name="parentControl">The parent control.</param>
        /// <param name="value">Information about the value</param>
        /// <param name="configurationValues">The configuration values.</param>
        /// <param name="condensed">Flag indicating if the value should be condensed (i.e. for use in a grid column)</param>
        /// <returns></returns>
        public override string FormatValue(Control parentControl, string value, Dictionary <string, ConfigurationValue> configurationValues, bool condensed)
        {
            string formattedValue = string.Empty;

            Guid guid = Guid.Empty;

            if (Guid.TryParse(value, out guid))
            {
                using (var rockContext = new RockContext())
                {
                    var contentChannelItem = new ContentChannelItemService(rockContext).GetNoTracking(guid);
                    if (contentChannelItem != null)
                    {
                        formattedValue = contentChannelItem.Title;
                    }
                }
            }

            return(base.FormatValue(parentControl, formattedValue, null, condensed));
        }
        /// <summary>
        /// Handles the Click event of the lbEditContent 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 lbEditContent_Click(object sender, EventArgs e)
        {
            ContentChannelCache contentChannel = this.GetContentChannel();

            if (contentChannel == null)
            {
                // shouldn't happen. This button isn't visible unless there is a contentChannel configured
                return;
            }

            pnlContentComponentEditContentChannelItems.Visible = true;
            mdContentComponentEditContentChannelItems.Show();

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

            pnlContentChannelItemsList.Visible = allowMultipleContentItems;
            pnlContentChannelItemEdit.CssClass = allowMultipleContentItems ? "col-md-8" : "col-md-12";

            var rockContext          = new RockContext();
            var contentChannelItemId = new ContentChannelItemService(rockContext).Queryable().Where(a => a.ContentChannelId == contentChannel.Id).OrderBy(a => a.Order).ThenBy(a => a.Title).Select(a => ( int? )a.Id).FirstOrDefault();

            EditContentChannelItem(contentChannelItemId);

            if (allowMultipleContentItems)
            {
                // hide the SaveButton
                mdContentComponentEditContentChannelItems.SaveButtonText             = CONTENT_CHANNEL_ITEM_CLOSE_MODAL_TEXT;
                mdContentComponentEditContentChannelItems.SaveButtonCausesValidation = false;
                mdContentComponentEditContentChannelItems.CloseLinkVisible           = true;
                mdContentComponentEditContentChannelItems.CancelLinkVisible          = false;
            }
            else
            {
                mdContentComponentEditContentChannelItems.SaveButtonText             = CONTENT_CHANNEL_ITEM_SAVE_TEXT;
                mdContentComponentEditContentChannelItems.SaveButtonCausesValidation = true;
                mdContentComponentEditContentChannelItems.CloseLinkVisible           = false;
                mdContentComponentEditContentChannelItems.CancelLinkVisible          = true;
            }

            btnSaveItem.Visible = allowMultipleContentItems;
        }
        /// <summary>
        /// Saves the content channel item.
        /// </summary>
        private void SaveContentChannelItem()
        {
            RockContext rockContext = new RockContext();
            ContentChannelItemService contentChannelItemService = new ContentChannelItemService(rockContext);
            ContentChannelItem        contentChannelItem        = null;
            int contentChannelItemId = hfContentChannelItemId.Value.AsInteger();

            if (contentChannelItemId != 0)
            {
                contentChannelItem = contentChannelItemService.Get(contentChannelItemId);
            }

            if (contentChannelItem == null)
            {
                ContentChannelCache contentChannel = this.GetContentChannel();

                contentChannelItem = new ContentChannelItem();
                contentChannelItem.ContentChannelTypeId = contentChannel.ContentChannelTypeId;
                contentChannelItem.ContentChannelId     = contentChannel.Id;
                contentChannelItem.Order = (contentChannelItemService.Queryable().Where(a => a.ContentChannelId == contentChannel.Id).Max(a => ( int? )a.Order) ?? 0) + 1;
                contentChannelItemService.Add(contentChannelItem);
            }

            contentChannelItem.LoadAttributes(rockContext);
            avcContentChannelItemAttributes.GetEditValues(contentChannelItem);

            contentChannelItem.Title   = tbContentChannelItemTitle.Text;
            contentChannelItem.Content = htmlContentChannelItemContent.Text;

            rockContext.SaveChanges();

            // just in case this is a new contentChannelItem, set the hfContentChannelItemId to the Id after SaveChanges.
            hfContentChannelItemId.Value = contentChannelItem.Id.ToString();

            contentChannelItem.SaveAttributeValues(rockContext);

            RemoveCacheItem(OUTPUT_CACHE_KEY);
            RemoveCacheItem(ITEM_CACHE_KEY);

            BindContentChannelItemsGrid();
        }
Example #12
0
        /// <summary>
        /// Handles the Click event of the deleteField control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RowEventArgs"/> instance containing the event data.</param>
        /// <exception cref="System.NotImplementedException"></exception>
        void gContentChannelItems_Delete(object sender, RowEventArgs e)
        {
            var rockContext        = new RockContext();
            var contentItemService = new ContentChannelItemService(rockContext);
            var contentItem        = contentItemService.Get(e.RowKeyId);

            if (contentItem != null)
            {
                string errorMessage;
                if (!contentItemService.CanDelete(contentItem, out errorMessage))
                {
                    mdGridWarning.Show(errorMessage, ModalAlertType.Information);
                    return;
                }

                contentItemService.Delete(contentItem);
                rockContext.SaveChanges();
            }

            GetData();
        }
Example #13
0
        /// <summary>
        /// Reads new values entered by the user for the field ( as Guid )
        /// </summary>
        /// <param name="control">Parent control that controls were added to in the CreateEditControl() method</param>
        /// <param name="configurationValues">The configuration values.</param>
        /// <returns></returns>
        public override string GetEditValue(System.Web.UI.Control control, Dictionary <string, ConfigurationValue> configurationValues)
        {
            var picker = control as ContentChannelItemPicker;

            if (picker != null)
            {
                int? itemId   = picker.ContentChannelItemId;
                Guid?itemGuid = null;
                if (itemId.HasValue)
                {
                    using (var rockContext = new RockContext())
                    {
                        itemGuid = new ContentChannelItemService(rockContext).Queryable().AsNoTracking().Where(a => a.Id == itemId.Value).Select(a => ( Guid? )a.Guid).FirstOrDefault();
                    }
                }

                return(itemGuid?.ToString() ?? string.Empty);
            }

            return(null);
        }
Example #14
0
        /// <summary>
        /// Gets the expression.
        /// </summary>
        /// <param name="entityType">Type of the entity.</param>
        /// <param name="serviceInstance">The service instance.</param>
        /// <param name="parameterExpression">The parameter expression.</param>
        /// <param name="selection">The selection.</param>
        /// <returns></returns>
        public override Expression GetExpression(Type entityType, IService serviceInstance, ParameterExpression parameterExpression, string selection)
        {
            string[] selectionValues = selection.Split('|');
            if (selectionValues.Length >= 1)
            {
                var contentChannelType   = new ContentChannelTypeService(new RockContext()).Get(selectionValues[0].AsGuid());
                int?contentChannelTypeId = null;
                if (contentChannelType != null)
                {
                    contentChannelTypeId = contentChannelType.Id;
                }

                var qry = new ContentChannelItemService((RockContext)serviceInstance.Context).Queryable()
                          .Where(p => p.ContentChannelTypeId == contentChannelTypeId);

                Expression extractedFilterExpression = FilterExpressionExtractor.Extract <Rock.Model.ContentChannelItem>(qry, parameterExpression, "p");

                return(extractedFilterExpression);
            }

            return(null);
        }
Example #15
0
    public TheDailyItem GetDailyItem(int id)
    {
        var rockContext = new RockContext();

        var contentItemService = new ContentChannelItemService(rockContext);

        ContentChannelItem i = null;

        var attrService = new AttributeService(rockContext);

        var dailyItem = new  TheDailyItem();

        i = contentItemService.Get(id);

        if (i != null)
        {
            i.LoadAttributes();

            i.Content = DotLiquid.StandardFilters.StripHtml(i.Content).Replace("\n\n", "\r\n\r\n");

            var attributes = i.Attributes;

            var pdfAttr = i.Attributes["PDF"];

            var binaryFile = new BinaryFileService(new RockContext()).Get(pdfAttr.Id);
            var pdfUrl = binaryFile.Url;

            var scriptureAttr = i.Attributes["ScriptureCards"];

            binaryFile = new BinaryFileService(new RockContext()).Get(scriptureAttr.Id);
            var scriptureUrl = binaryFile.Url;

            dailyItem  = (new TheDailyItem { Id = i.Id, Title = i.Title, Content = i.Content, DailyPDF = pdfUrl, ScriptiureCards = scriptureUrl });

        }

        return dailyItem;
    }
Example #16
0
        /// <summary>
        /// Handles the Click event of the lbDelete 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 lbDelete_Click(object sender, EventArgs e)
        {
            RockContext        rockContext        = new RockContext();
            var                contentItemService = new ContentChannelItemService(rockContext);
            ContentChannelItem contentItem        = null;

            int contentItemId = hfId.Value.AsInteger();

            if (contentItemId != 0)
            {
                contentItem = contentItemService
                              .Queryable("ContentChannel,ContentChannelType")
                              .FirstOrDefault(t => t.Id == contentItemId);
            }

            if (contentItem != null)
            {
                contentItemService.Delete(contentItem);
                rockContext.SaveChanges();
            }

            ReturnToParentPage();
        }
Example #17
0
        /// <summary>
        /// Adds an item to the cart.
        /// </summary>
        /// <param name="itemId">The item identifier.</param>
        protected void AddToCart(int itemId)
        {
            using (var rockContext = new RockContext())
            {
                var item = new ContentChannelItemService(rockContext).Get(itemId);

                if (item != null)
                {
                    var existingItem = Cart.Items.FirstOrDefault(i => i.ItemId == item.Id);

                    if (existingItem != null)
                    {
                        existingItem.Quantity += 1;
                    }
                    else
                    {
                        Cart.Items.Add(new ShoppingCartItem(item));
                    }

                    Cart.Calculate();
                }
            }
        }
        public IHttpActionResult GetById(int id)
        {
            var series = new ContentChannelItemService(_rockContext).Get(id);

            if (series != null &&
                series.ContentChannelId == SeriesContentChannelId &&
                series.StartDateTime < DateTime.Now)
            {
                return(Ok(new MessageSeriesDetailsFull()
                {
                    Id = series.Id,
                    Title = series.Title,
                    SmallTileImageUrl = GetFileUrlOrNull(series, "OptimizedSeriesArchiveImage"),
                    LargeTileImageUrl = GetFileUrlOrNull(series, "SermonGraphic"),
                    BannerImageUrl = GetFileUrlOrNull(series, "HeaderGraphic"),
                    Topics = _definedValueService.GetByGuids(series.GetAttributeValues("Topic").Select(t => t.AsGuid()).ToList()).Select(dv => dv.Value).ToArray()
                }));
            }
            else
            {
                return(NotFound());
            }
        }
        public IQueryable <ContentChannelItem> GetFromPersonDataView(string guids)
        {
            var rockContext = new RockContext();

            rockContext.Configuration.ProxyCreationEnabled = false;

            // Turn the comma separated list of guids into a list of strings.
            List <string> guidList = (guids ?? "").Split(',').ToList();

            // Get the Id of the Rock.Model.ContentChannelItem Entity.
            int contentChannelItemEntityTypeId = EntityTypeCache.Get("Rock.Model.ContentChannelItem").Id;

            // Get the Field Type (Attribute Type) Id of the Data View Field Type.
            int fieldTypeId = FieldTypeCache.Get(Rock.SystemGuid.FieldType.DATAVIEWS.AsGuid()).Id;

            // Get the list of attributes that are of the Rock.Model.ContentChannelItem entity type
            // and that are of the Data View field type.
            List <int> attributeIdList = new AttributeService(rockContext)
                                         .GetByEntityTypeId(contentChannelItemEntityTypeId)
                                         .Where(item => item.FieldTypeId == fieldTypeId)
                                         .Select(a => a.Id)
                                         .ToList();



            // I want a list of content channel items whose ids match up to attribute values that represent entity ids
            IQueryable <ContentChannelItem> contentChannelItemList = new ContentChannelItemService(rockContext)
                                                                     .Queryable()
                                                                     .AsNoTracking()
                                                                     .WhereAttributeValue(rockContext, av => attributeIdList.Contains(av.AttributeId) && guidList.Any(guid => av.Value.Contains(guid)));



            // Return this list
            return(contentChannelItemList);
        }
Example #20
0
        /// <summary>
        /// Inserts the slug for Content Channel Items.
        /// </summary>
        private void UpdateSlugForContentChannelItems()
        {
            int  recordsToProcess = 1000;
            bool isProcess        = true;

            do
            {
                using (var rockContext = new RockContext())
                {
                    rockContext.Database.CommandTimeout = _commandTimeout;
                    var contentChannelItems = new ContentChannelItemService(rockContext)
                                              .Queryable()
                                              .AsNoTracking()
                                              .Where(a => !a.ContentChannelItemSlugs.Any())
                                              .Take(recordsToProcess)
                                              .Select(a => new
                    {
                        a.Id,
                        a.Title
                    }).ToList();

                    var slugService = new ContentChannelItemSlugService(rockContext);
                    if (contentChannelItems.Any())
                    {
                        foreach (var item in contentChannelItems)
                        {
                            slugService.SaveSlug(item.Id, item.Title, null);
                        }
                    }
                    else
                    {
                        isProcess = false;
                    }
                }
            }while (isProcess);
        }
        /// <summary>
        /// Gets the bread crumbs.
        /// </summary>
        /// <param name="pageReference">The page reference.</param>
        /// <returns></returns>
        public override List<BreadCrumb> GetBreadCrumbs( PageReference pageReference )
        {
            var breadCrumbs = new List<BreadCrumb>();

            int? contentItemId = PageParameter( pageReference, "contentItemId" ).AsIntegerOrNull();
            if ( contentItemId != null )
            {
                ContentChannelItem contentItem = new ContentChannelItemService( new RockContext() ).Get( contentItemId.Value );
                if ( contentItem != null )
                {
                    breadCrumbs.Add( new BreadCrumb( contentItem.Title, pageReference ) );
                }
                else
                {
                    breadCrumbs.Add( new BreadCrumb( "New Content Item", pageReference ) );
                }
            }
            else
            {
                // don't show a breadcrumb if we don't have a pageparam to work with
            }

            return breadCrumbs;
        }
Example #22
0
        private void GContentChannelItems_GridReorder(object sender, GridReorderEventArgs e)
        {
            if (SelectedChannelId.HasValue)
            {
                using (var rockContext = new RockContext())
                {
                    var selectedChannel = new ContentChannelService(rockContext).Get(SelectedChannelId.Value);
                    if (selectedChannel != null)
                    {
                        bool isFiltered = false;
                        var  items      = GetItems(rockContext, selectedChannel, out isFiltered);

                        if (!isFiltered)
                        {
                            var service = new ContentChannelItemService(rockContext);
                            service.Reorder(items, e.OldIndex, e.NewIndex);
                            rockContext.SaveChanges();
                        }
                    }
                }
            }

            GetData();
        }
Example #23
0
        /// <summary>
        /// Handles the DeleteClick event of the gContentChannelItems control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Rock.Web.UI.Controls.RowEventArgs"/> instance containing the event data.</param>
        protected void gContentChannelItems_DeleteClick(object sender, Rock.Web.UI.Controls.RowEventArgs e)
        {
            var rockContext                   = new RockContext();
            var contentItemService            = new ContentChannelItemService(rockContext);
            var contentItemAssociationService = new ContentChannelItemAssociationService(rockContext);
            var contentItemSlugService        = new ContentChannelItemSlugService(rockContext);

            ContentChannelItem contentItem = contentItemService.Get(e.RowKeyId);

            if (contentItem != null)
            {
                string errorMessage;
                if (!contentItemService.CanDelete(contentItem, out errorMessage))
                {
                    mdGridWarning.Show(errorMessage, ModalAlertType.Information);
                    return;
                }

                rockContext.WrapTransaction(() =>
                {
                    contentItemAssociationService.DeleteRange(contentItem.ChildItems);
                    contentItemAssociationService.DeleteRange(contentItem.ParentItems);
                    contentItemSlugService.DeleteRange(contentItem.ContentChannelItemSlugs);
                    contentItemService.Delete(contentItem);
                    rockContext.SaveChanges();
                });
            }

            BindContentChannelItemsGrid();

            // edit whatever the first item is, or create a new one
            var contentChannel       = GetContentChannel();
            var contentChannelItemId = new ContentChannelItemService(rockContext).Queryable().Where(a => a.ContentChannelId == contentChannel.Id).OrderBy(a => a.Order).ThenBy(a => a.Title).Select(a => ( int? )a.Id).FirstOrDefault();

            EditContentChannelItem(contentChannelItemId);
        }
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private List<ContentChannelItem> GetItems( RockContext rockContext, out bool isFiltered )
        {
            isFiltered = false;

            var items = new List<ContentChannelItem>();

            if ( _channelId.HasValue )
            {
                ContentChannelItemService contentItemService = new ContentChannelItemService( rockContext );
                var contentItems = contentItemService.Queryable()
                    .Where( c => c.ContentChannelId == _channelId.Value );

                var drp = new DateRangePicker();
                drp.DelimitedValues = gfFilter.GetUserPreference( "Date Range" );
                if ( drp.LowerValue.HasValue )
                {
                    isFiltered = true;
                    contentItems = contentItems.Where( i =>
                        ( i.ExpireDateTime.HasValue && i.ExpireDateTime.Value >= drp.LowerValue.Value ) ||
                        ( !i.ExpireDateTime.HasValue && i.StartDateTime >= drp.LowerValue.Value ) );
                }
                if ( drp.UpperValue.HasValue )
                {
                    isFiltered = true;
                    DateTime upperDate = drp.UpperValue.Value.Date.AddDays( 1 );
                    contentItems = contentItems.Where( i => i.StartDateTime <= upperDate );
                }

                var status = gfFilter.GetUserPreference( "Status" ).ConvertToEnumOrNull<ContentChannelItemStatus>();
                if ( status.HasValue )
                {
                    isFiltered = true;
                    contentItems = contentItems.Where( i => i.Status == status );
                }

                string title = gfFilter.GetUserPreference( "Title" );
                if ( !string.IsNullOrWhiteSpace( title ) )
                {
                    isFiltered = true;
                    contentItems = contentItems.Where( i => i.Title.Contains( title ) );
                }

                // if the block has a person context filter requests for just them
                if ( _person != null )
                {
                    isFiltered = true;
                    contentItems = contentItems.Where( i => i.CreatedByPersonAlias != null && i.CreatedByPersonAlias.PersonId == _person.Id );
                }

                // TODO: Checking security of every item will take longer and longer as more items are added.
                // Eventually we should implement server-side paging so that we only need to check security for
                // the items on the current page
                foreach ( var item in contentItems.ToList() )
                {
                    if ( item.IsAuthorized( Rock.Security.Authorization.VIEW, CurrentPerson ) )
                    {
                        items.Add( item );
                    }
                    else
                    {
                        isFiltered = true;
                    }
                }
            }

            if ( _manuallyOrdered && !isFiltered )
            {
                return items.OrderBy( i => i.Order ).ToList();
            }
            else
            {
                return items;
            }
        }
Example #25
0
        /// <summary>
        /// Shows the view.
        /// </summary>
        /// <param name="groupId">The group identifier.</param>
        protected void ShowView(int groupId)
        {
            pnlView.Visible = true;
            hfGroupId.Value = groupId.ToString();
            var rockContext = new RockContext();

            var group = new GroupService(rockContext).Get(groupId);

            if (group == null)
            {
                pnlView.Visible = false;
                return;
            }

            group.LoadAttributes(rockContext);
            var opportunityType = DefinedValueCache.Get(group.GetAttributeValue("OpportunityType").AsGuid());

            if (this.GetAttributeValue("SetPageTitletoOpportunityTitle").AsBoolean())
            {
                RockPage.Title        = group.GetAttributeValue("OpportunityTitle");
                RockPage.BrowserTitle = group.GetAttributeValue("OpportunityTitle");
                RockPage.Header.Title = group.GetAttributeValue("OpportunityTitle");
            }

            var mergeFields = LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson, new CommonMergeFieldsOptions {
                GetLegacyGlobalMergeFields = false
            });

            mergeFields.Add("Block", this.BlockCache);
            mergeFields.Add("Group", group);

            // Left Sidebar
            var photoGuid = group.GetAttributeValue("OpportunityPhoto").AsGuidOrNull();

            imgOpportunityPhoto.Visible  = photoGuid.HasValue;
            imgOpportunityPhoto.ImageUrl = string.Format("~/GetImage.ashx?Guid={0}", photoGuid);

            var groupMembers = group.Members.ToList();

            foreach (var gm in groupMembers)
            {
                gm.LoadAttributes(rockContext);
            }

            // only show the 'Donate to a Participant' button if there are participants that are taking contribution requests
            btnDonateToParticipant.Visible = groupMembers.Where(a => !a.GetAttributeValue("DisablePublicContributionRequests").AsBoolean()).Any();
            if (!string.IsNullOrWhiteSpace(opportunityType.GetAttributeValue("core_DonateButtonText")))
            {
                btnDonateToParticipant.Text = opportunityType.GetAttributeValue("core_DonateButtonText");
            }

            RegistrationInstance registrationInstance = null;
            var registrationInstanceId = group.GetAttributeValue("RegistrationInstance").AsIntegerOrNull();

            if (registrationInstanceId.HasValue)
            {
                registrationInstance = new RegistrationInstanceService(rockContext).Get(registrationInstanceId.Value);
            }

            mergeFields.Add("RegistrationPage", LinkedPageRoute("RegistrationPage"));

            if (registrationInstance != null)
            {
                mergeFields.Add("RegistrationInstance", registrationInstance);
                mergeFields.Add("RegistrationInstanceLinkages", registrationInstance.Linkages);

                // populate merge fields for Registration Counts
                var maxRegistrantCount       = 0;
                var currentRegistrationCount = 0;

                if (registrationInstance.MaxAttendees != 0)
                {
                    maxRegistrantCount = registrationInstance.MaxAttendees;
                }

                currentRegistrationCount = new RegistrationRegistrantService(rockContext).Queryable().AsNoTracking()
                                           .Where(r =>
                                                  r.Registration.RegistrationInstanceId == registrationInstance.Id &&
                                                  r.OnWaitList == false)
                                           .Count();

                mergeFields.Add("CurrentRegistrationCount", currentRegistrationCount);
                if (maxRegistrantCount != 0)
                {
                    mergeFields.Add("MaxRegistrantCount", maxRegistrantCount);
                    mergeFields.Add("RegistrationSpotsAvailable", maxRegistrantCount - currentRegistrationCount);
                }
            }

            string sidebarLavaTemplate = this.GetAttributeValue("SidebarLavaTemplate");

            lSidebarHtml.Text = sidebarLavaTemplate.ResolveMergeFields(mergeFields);

            SetActiveTab("Details");

            // Top Main
            string summaryLavaTemplate = this.GetAttributeValue("SummaryLavaTemplate");

            lMainTopContentHtml.Text = summaryLavaTemplate.ResolveMergeFields(mergeFields);

            // only show the leader toolbox link of the currentperson has a leader role in the group
            btnLeaderToolbox.Visible = group.Members.Any(a => a.PersonId == this.CurrentPersonId && a.GroupRole.IsLeader);

            //// Participant Actions
            // only show if the current person is a group member
            var groupMember = group.Members.FirstOrDefault(a => a.PersonId == this.CurrentPersonId);

            if (groupMember != null)
            {
                hfGroupMemberId.Value         = groupMember.Id.ToString();
                pnlParticipantActions.Visible = true;
            }
            else
            {
                hfGroupMemberId.Value         = null;
                pnlParticipantActions.Visible = false;
            }

            mergeFields.Add("GroupMember", groupMember);

            // Progress
            if (groupMember != null && pnlParticipantActions.Visible)
            {
                var entityTypeIdGroupMember = EntityTypeCache.GetId <Rock.Model.GroupMember>();

                var contributionTotal = new FinancialTransactionDetailService(rockContext).Queryable()
                                        .Where(d => d.EntityTypeId == entityTypeIdGroupMember &&
                                               d.EntityId == groupMember.Id)
                                        .Sum(a => (decimal?)a.Amount) ?? 0.00M;

                var individualFundraisingGoal = groupMember.GetAttributeValue("IndividualFundraisingGoal").AsDecimalOrNull();
                if (!individualFundraisingGoal.HasValue)
                {
                    individualFundraisingGoal = group.GetAttributeValue("IndividualFundraisingGoal").AsDecimalOrNull();
                }

                var amountLeft = individualFundraisingGoal - contributionTotal;
                var percentMet = individualFundraisingGoal > 0 ? contributionTotal * 100 / individualFundraisingGoal : 100;

                mergeFields.Add("AmountLeft", amountLeft);
                mergeFields.Add("PercentMet", percentMet);

                var queryParams = new Dictionary <string, string>();
                queryParams.Add("GroupId", hfGroupId.Value);
                queryParams.Add("GroupMemberId", hfGroupMemberId.Value);
                mergeFields.Add("MakeDonationUrl", LinkedPageUrl("DonationPage", queryParams));
                mergeFields.Add("ParticipantPageUrl", LinkedPageUrl("ParticipantPage", queryParams));

                string makeDonationButtonText = null;
                if (groupMember.PersonId == this.CurrentPersonId)
                {
                    makeDonationButtonText = "Make Payment";
                }
                else
                {
                    makeDonationButtonText = string.Format("Contribute to {0} {1}", RockFilters.Possessive(groupMember.Person.NickName), opportunityType);
                }

                mergeFields.Add("MakeDonationButtonText", makeDonationButtonText);

                var participantLavaTemplate = this.GetAttributeValue("ParticipantLavaTemplate");
                lParticipantActionsHtml.Text = participantLavaTemplate.ResolveMergeFields(mergeFields);
            }

            // Tab:Details
            lDetailsHtml.Text  = group.GetAttributeValue("OpportunityDetails");
            btnDetailsTab.Text = string.Format("{0} Details", opportunityType);

            // Tab:Updates
            liUpdatesTab.Visible = false;
            var updatesContentChannelGuid = group.GetAttributeValue("UpdateContentChannel").AsGuidOrNull();

            if (updatesContentChannelGuid.HasValue)
            {
                var contentChannel = new ContentChannelService(rockContext).Get(updatesContentChannelGuid.Value);
                if (contentChannel != null)
                {
                    liUpdatesTab.Visible = true;
                    string updatesLavaTemplate = this.GetAttributeValue("UpdatesLavaTemplate");
                    var    contentChannelItems = new ContentChannelItemService(rockContext).Queryable().Where(a => a.ContentChannelId == contentChannel.Id).AsNoTracking().ToList();

                    mergeFields.Add("ContentChannelItems", contentChannelItems);
                    lUpdatesContentItemsHtml.Text = updatesLavaTemplate.ResolveMergeFields(mergeFields);

                    btnUpdatesTab.Text = string.Format("{0} Updates ({1})", opportunityType, contentChannelItems.Count());
                }
            }

            // Tab:Comments
            var noteType = NoteTypeCache.Get(this.GetAttributeValue("NoteType").AsGuid());

            if (noteType != null)
            {
                notesCommentsTimeline.NoteOptions.SetNoteTypes(new List <NoteTypeCache> {
                    noteType
                });
            }

            notesCommentsTimeline.NoteOptions.EntityId = groupId;

            // show the Add button on comments for any logged in person
            notesCommentsTimeline.AddAllowed = true;

            var enableCommenting = group.GetAttributeValue("EnableCommenting").AsBoolean();

            btnCommentsTab.Text = string.Format("Comments ({0})", notesCommentsTimeline.NoteCount);

            if (CurrentPerson == null)
            {
                notesCommentsTimeline.Visible = enableCommenting && (notesCommentsTimeline.NoteCount > 0);
                lNoLoginNoCommentsYet.Visible = notesCommentsTimeline.NoteCount == 0;
                liCommentsTab.Visible         = enableCommenting;
                btnLoginToComment.Visible     = enableCommenting;
            }
            else
            {
                lNoLoginNoCommentsYet.Visible = false;
                notesCommentsTimeline.Visible = enableCommenting;
                liCommentsTab.Visible         = enableCommenting;
                btnLoginToComment.Visible     = false;
            }

            // if btnDetailsTab is the only visible tab, hide the tab since there is nothing else to tab to
            if (!liCommentsTab.Visible && !liUpdatesTab.Visible)
            {
                tlTabList.Visible = false;
            }
        }
        protected void lbDeleteChildItem_Click( object sender, EventArgs e )
        {
            using ( var rockContext = new RockContext() )
            {
                int childItemId = hfRemoveChildItem.ValueAsInt();

                var service = new ContentChannelItemService( rockContext );
                var childItem = service.Get( childItemId );
                if ( childItem != null )
                {
                    service.Delete( childItem );
                    rockContext.SaveChanges();
                }
            }

            BindChildItemsGrid( GetContentItem() );

            HideDialog();
        }
        /// <summary>
        /// Shows the active users.
        /// </summary>
        private void DisplayItems()
        {
            RockContext rockContext = new RockContext();

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

            ContentChannelItemService itemService = new ContentChannelItemService( rockContext );
            var items = itemService.Queryable().AsNoTracking().Where(c => c.CreatedByPersonAlias != null && c.CreatedByPersonAlias.PersonId == CurrentPersonId);

            if ( contentChannelGuid.HasValue )
            {
                items = items.Where( c => c.ContentChannel.Guid == contentChannelGuid.Value );

                contentChannel = new ContentChannelService( rockContext ).Get( contentChannelGuid.Value );
            }

            var mergeFields = new Dictionary<string, object>();
            mergeFields.Add( "DetailPage", LinkedPageRoute( "DetailPage" ) );
            mergeFields.Add( "ContentChannel", contentChannel );
            mergeFields.Add( "CurrentPerson", CurrentPerson );
            mergeFields.Add( "Items", items.Take(GetAttributeValue( "MaxItems" ).AsInteger()).ToList() );

            string template = GetAttributeValue( "LavaTemplate" );

            lContent.Text = template.ResolveMergeFields( mergeFields );

            // show debug info
            if ( GetAttributeValue( "EnableDebug" ).AsBoolean() && IsUserAuthorized( Authorization.EDIT ) )
            {
                lDebug.Visible = true;
                lDebug.Text = mergeFields.lavaDebugInfo();
            }
        }
        private void GetData()
        {
            var rockContext = new RockContext();
            var itemService = new ContentChannelItemService(rockContext);

            // Get all of the content channels
            var contentChannelsQry = new ContentChannelService( rockContext ).Queryable( "ContentChannelType" );

            List<Guid> contentChannelTypeGuidsInclude = GetAttributeValue( "ContentChannelTypesInclude" ).SplitDelimitedValues().AsGuidList();
            List<Guid> contentChannelTypeGuidsExclude = GetAttributeValue( "ContentChannelTypesExclude" ).SplitDelimitedValues().AsGuidList();

            if ( contentChannelTypeGuidsInclude.Any() )
            {
                // if contentChannelTypeGuidsInclude is specified, only get contentChannelTypes that are in the contentChannelTypeGuidsInclude
                // NOTE: no need to factor in contentChannelTypeGuidsExclude since included would take precendance and the excluded ones would already not be included
                contentChannelsQry = contentChannelsQry.Where( a => contentChannelTypeGuidsInclude.Contains( a.ContentChannelType.Guid ) );
            }
            else if ( contentChannelTypeGuidsExclude.Any() )
            {
                contentChannelsQry = contentChannelsQry.Where( a => !contentChannelTypeGuidsExclude.Contains( a.ContentChannelType.Guid ) );
            }

            var contentChannelsList = contentChannelsQry.OrderBy( w => w.Name ).ToList();

            // Create variable for storing authorized channels and the count of active items
            var channelCounts = new Dictionary<int, int>();
            foreach ( var channel in contentChannelsList )
            {
                if ( channel.IsAuthorized( Authorization.VIEW, CurrentPerson))
                {
                    channelCounts.Add( channel.Id, 0);
                }
            }

            // Get the pending approval item counts for each channel (if the channel requires approval)
            itemService.Queryable()
                .Where( i =>
                    channelCounts.Keys.Contains( i.ContentChannelId ) &&
                    i.Status == ContentChannelItemStatus.PendingApproval && i.ContentChannel.RequiresApproval )
                .GroupBy( i => i.ContentChannelId )
                .Select( i => new {
                    Id = i.Key,
                    Count = i.Count()
                })
                .ToList()
                .ForEach( i => channelCounts[i.Id] = i.Count );

            // Create a query to return channel, the count of items, and the selected class
            var qry = contentChannelsList
                .Where( c => channelCounts.Keys.Contains( c.Id ) )
                .Select( c => new
                {
                    Channel = c,
                    Count = channelCounts[c.Id],
                    Class = ( SelectedChannelId.HasValue && SelectedChannelId.Value == c.Id ) ? "active" : ""
                } );

            // If displaying active only, update query to exclude those content channels without any items
            if ( tglStatus.Checked )
            {
                qry = qry.Where( c => c.Count > 0 );
            }

            var contentChannels = qry.ToList();

            rptChannels.DataSource = contentChannels;
            rptChannels.DataBind();

            ContentChannel selectedChannel = null;
            if ( SelectedChannelId.HasValue )
            {
                selectedChannel = contentChannelsList
                    .Where( w =>
                        w.Id == SelectedChannelId.Value &&
                        channelCounts.Keys.Contains( SelectedChannelId.Value ) )
                    .FirstOrDefault();
            }

            if ( selectedChannel != null && contentChannels.Count > 0 )
            {
                // show the content item panel
                divItemPanel.Visible = true;

                BindAttributes( selectedChannel );
                AddDynamicControls( selectedChannel );

                bool isFiltered = false;
                var items = GetItems( rockContext, selectedChannel, out isFiltered );

                if ( selectedChannel.ItemsManuallyOrdered && !isFiltered )
                {
                    gContentChannelItems.Columns[0].Visible = true;
                    gContentChannelItems.AllowSorting = false;
                }
                else
                {
                    gContentChannelItems.Columns[0].Visible = false;
                    gContentChannelItems.AllowSorting = true;

                    SortProperty sortProperty = gContentChannelItems.SortProperty;
                    if ( sortProperty != null )
                    {
                        items = items.AsQueryable().Sort( sortProperty ).ToList();
                    }
                    else
                    {
                        items = items.OrderByDescending( p => p.StartDateTime ).ToList();
                    }
                }

                gContentChannelItems.ObjectList = new Dictionary<string, object>();
                items.ForEach( i => gContentChannelItems.ObjectList.Add( i.Id.ToString(), i ) );

                gContentChannelItems.DataSource = items.Select( i => new
                {
                    i.Id,
                    i.Guid,
                    i.Title,
                    i.StartDateTime,
                    i.ExpireDateTime,
                    i.Priority,
                    Status = DisplayStatus( i.Status ),
                    Occurrences = i.EventItemOccurrences.Any(),
                    CreatedByPersonName = i.CreatedByPersonAlias != null ? String.Format( "<a href={0}>{1}</a>", ResolveRockUrl( string.Format( "~/Person/{0}", i.CreatedByPersonAlias.PersonId ) ), i.CreatedByPersonName ) : String.Empty
                } ).ToList();
                gContentChannelItems.DataBind();

                lContentChannelItems.Text = selectedChannel.Name + " Items";
            }
            else
            {
                divItemPanel.Visible = false;
            }
        }
Example #29
0
        /// <summary>
        /// Gets the expression.
        /// </summary>
        /// <param name="entityType">Type of the entity.</param>
        /// <param name="serviceInstance">The service instance.</param>
        /// <param name="parameterExpression">The parameter expression.</param>
        /// <param name="selection">The selection.</param>
        /// <returns></returns>
        public override Expression GetExpression( Type entityType, IService serviceInstance, ParameterExpression parameterExpression, string selection )
        {
            string[] selectionValues = selection.Split( '|' );
            if ( selectionValues.Length >= 1 )
            {
                var contentChannel = new ContentChannelService( new RockContext() ).Get( selectionValues[0].AsGuid() );
                int? contentChannelId = null;
                if ( contentChannel != null )
                {
                    contentChannelId = contentChannel.Id;
                }

                var qry = new ContentChannelItemService( (RockContext)serviceInstance.Context ).Queryable()
                    .Where( p => p.ContentChannelId == contentChannelId );

                Expression extractedFilterExpression = FilterExpressionExtractor.Extract<Rock.Model.ContentChannelItem>( qry, parameterExpression, "p" );

                return extractedFilterExpression;
            }

            return null;
        }
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event.
        /// </summary>
        /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnLoad( EventArgs e )
        {
            base.OnLoad( e );

            if ( !Page.IsPostBack )
            {
                // Get any querystring variables
                ContentItemId = PageParameter( "ContentItemId" ).AsIntegerOrNull();
                EventItemOccurrenceId = PageParameter( "EventItemOccurrenceId" ).AsIntegerOrNull();
                EventItemId = PageParameter( "EventItemId" ).AsIntegerOrNull();
                EventCalendarId = PageParameter( "EventCalendarId" ).AsIntegerOrNull();

                // Load objects neccessary to display names
                using ( var rockContext = new RockContext() )
                {
                    ContentChannelItem contentItem = null;
                    EventItemOccurrence eventItemOccurrence = null;
                    EventItem eventItem = null;
                    EventCalendar eventCalendar = null;

                    if ( ContentItemId.HasValue && ContentItemId.Value > 0 )
                    {
                        PageNumber = 5;
                        var contentChannel = new ContentChannelItemService( rockContext ).Get( ContentItemId.Value );
                    }

                    if ( EventItemOccurrenceId.HasValue && EventItemOccurrenceId.Value > 0 )
                    {
                        PageNumber = PageNumber ?? 4;
                        eventItemOccurrence = new EventItemOccurrenceService( rockContext ).Get( EventItemOccurrenceId.Value );
                        if ( eventItemOccurrence != null )
                        {
                            eventItem = eventItemOccurrence.EventItem;
                            if ( eventItem != null && !EventItemId.HasValue )
                            {
                                EventItemId = eventItem.Id;
                            }
                        }
                    }

                    if ( EventItemId.HasValue && EventItemId.Value > 0 )
                    {
                        PageNumber = PageNumber ?? 3;
                        if ( eventItem == null )
                        {
                            eventItem = new EventItemService( rockContext ).Get( EventItemId.Value );
                        }

                        if ( !EventCalendarId.HasValue )
                        {
                            foreach ( var cal in eventItem.EventCalendarItems )
                            {
                                EventCalendarId = EventCalendarId ?? cal.EventCalendarId;
                                if ( cal.EventCalendar.IsAuthorized( Authorization.EDIT, CurrentPerson ) )
                                {
                                    EventCalendarId = cal.EventCalendarId;
                                    break;
                                }
                            }
                        }
                    }

                    if ( EventCalendarId.HasValue && EventCalendarId.Value > 0 )
                    {
                        PageNumber = PageNumber ?? 2;
                        eventCalendar = new EventCalendarService( rockContext ).Get( EventCalendarId.Value );
                    }

                    PageNumber = PageNumber ?? 1;

                    // Set the names based on current object values
                    lCalendarName.Text = eventCalendar != null ? eventCalendar.Name : "Calendar";
                    lCalendarItemName.Text = eventItem != null ? eventItem.Name : "Event";
                    lEventOccurrenceName.Text = eventItemOccurrence != null ?
                        ( eventItemOccurrence.Campus != null ? eventItemOccurrence.Campus.Name : "All Campuses" ) :
                        "Event Occurrence";
                    lContentItemName.Text = contentItem != null ? contentItem.Title : "Content Item";
                }
            }

            divCalendars.Attributes["class"] = GetDivClass( 1 );
            divCalendar.Attributes["class"] = GetDivClass( 2 );
            divCalendarItem.Attributes["class"] = GetDivClass( 3 );
            divEventOccurrence.Attributes["class"] = GetDivClass( 4 );
            divContentItem.Attributes["class"] = GetDivClass( 5 );
        }
Example #31
0
        private void GetData()
        {
            var rockContext = new RockContext();
            var itemService = new ContentChannelItemService(rockContext);

            // Get all of the content channels
            var contentChannelsQry = new ContentChannelService(rockContext).Queryable("ContentChannelType");

            List <Guid> contentChannelTypeGuidsInclude = GetAttributeValue("ContentChannelTypesInclude").SplitDelimitedValues().AsGuidList();
            List <Guid> contentChannelTypeGuidsExclude = GetAttributeValue("ContentChannelTypesExclude").SplitDelimitedValues().AsGuidList();

            if (contentChannelTypeGuidsInclude.Any())
            {
                // if contentChannelTypeGuidsInclude is specified, only get contentChannelTypes that are in the contentChannelTypeGuidsInclude
                // NOTE: no need to factor in contentChannelTypeGuidsExclude since included would take precendance and the excluded ones would already not be included
                contentChannelsQry = contentChannelsQry.Where(a => contentChannelTypeGuidsInclude.Contains(a.ContentChannelType.Guid));
            }
            else if (contentChannelTypeGuidsExclude.Any())
            {
                contentChannelsQry = contentChannelsQry.Where(a => !contentChannelTypeGuidsExclude.Contains(a.ContentChannelType.Guid));
            }

            var contentChannelsList = contentChannelsQry.OrderBy(w => w.Name).ToList();

            // Create variable for storing authorized channels and the count of active items
            var channelCounts = new Dictionary <int, int>();

            foreach (var channel in contentChannelsList)
            {
                if (channel.IsAuthorized(Authorization.VIEW, CurrentPerson))
                {
                    channelCounts.Add(channel.Id, 0);
                }
            }

            // Get the pending approval item counts for each channel (if the channel requires approval)
            itemService.Queryable()
            .Where(i =>
                   channelCounts.Keys.Contains(i.ContentChannelId) &&
                   i.Status == ContentChannelItemStatus.PendingApproval && i.ContentChannel.RequiresApproval)
            .GroupBy(i => i.ContentChannelId)
            .Select(i => new {
                Id    = i.Key,
                Count = i.Count()
            })
            .ToList()
            .ForEach(i => channelCounts[i.Id] = i.Count);

            // Create a query to return channel, the count of items, and the selected class
            var qry = contentChannelsList
                      .Where(c => channelCounts.Keys.Contains(c.Id))
                      .Select(c => new
            {
                Channel = c,
                Count   = channelCounts[c.Id],
                Class   = (SelectedChannelId.HasValue && SelectedChannelId.Value == c.Id) ? "active" : ""
            });

            // If displaying active only, update query to exclude those content channels without any items
            if (tglStatus.Checked)
            {
                qry = qry.Where(c => c.Count > 0);
            }

            var contentChannels = qry.ToList();

            rptChannels.DataSource = contentChannels;
            rptChannels.DataBind();

            ContentChannel selectedChannel = null;

            if (SelectedChannelId.HasValue)
            {
                selectedChannel = contentChannelsList
                                  .Where(w =>
                                         w.Id == SelectedChannelId.Value &&
                                         channelCounts.Keys.Contains(SelectedChannelId.Value))
                                  .FirstOrDefault();
            }

            if (selectedChannel != null && contentChannels.Count > 0)
            {
                // show the content item panel
                divItemPanel.Visible = true;

                BindAttributes(selectedChannel);
                AddDynamicControls(selectedChannel);

                var itemQry = itemService.Queryable()
                              .Where(i => i.ContentChannelId == selectedChannel.Id);

                var drp = new DateRangePicker();
                drp.DelimitedValues = gfFilter.GetUserPreference("Date Range");
                if (drp.LowerValue.HasValue)
                {
                    if (selectedChannel.ContentChannelType.DateRangeType == ContentChannelDateType.SingleDate)
                    {
                        itemQry = itemQry.Where(i => i.StartDateTime >= drp.LowerValue.Value);
                    }
                    else
                    {
                        itemQry = itemQry.Where(i => i.ExpireDateTime.HasValue && i.ExpireDateTime.Value >= drp.LowerValue.Value);
                    }
                }
                if (drp.UpperValue.HasValue)
                {
                    DateTime upperDate = drp.UpperValue.Value.Date.AddDays(1);
                    itemQry = itemQry.Where(i => i.StartDateTime <= upperDate);
                }

                var status = gfFilter.GetUserPreference("Status").ConvertToEnumOrNull <ContentChannelItemStatus>();
                if (status.HasValue)
                {
                    itemQry = itemQry.Where(i => i.Status == status);
                }

                string title = gfFilter.GetUserPreference("Title");
                if (!string.IsNullOrWhiteSpace(title))
                {
                    itemQry = itemQry.Where(i => i.Title.Contains(title));
                }

                int?personId = gfFilter.GetUserPreference("Created By").AsIntegerOrNull();
                if (personId.HasValue && personId.Value != 0)
                {
                    itemQry = itemQry.Where(i => i.CreatedByPersonAlias.PersonId == personId);
                }

                // Filter query by any configured attribute filters
                if (AvailableAttributes != null && AvailableAttributes.Any())
                {
                    var attributeValueService = new AttributeValueService(rockContext);
                    var parameterExpression   = attributeValueService.ParameterExpression;

                    foreach (var attribute in AvailableAttributes)
                    {
                        var filterControl = phAttributeFilters.FindControl("filter_" + attribute.Id.ToString());
                        if (filterControl != null)
                        {
                            var filterValues = attribute.FieldType.Field.GetFilterValues(filterControl, attribute.QualifierValues, Rock.Reporting.FilterMode.SimpleFilter);
                            var expression   = attribute.FieldType.Field.AttributeFilterExpression(attribute.QualifierValues, filterValues, parameterExpression);
                            if (expression != null)
                            {
                                var attributeValues = attributeValueService
                                                      .Queryable()
                                                      .Where(v => v.Attribute.Id == attribute.Id);

                                attributeValues = attributeValues.Where(parameterExpression, expression, null);

                                itemQry = itemQry.Where(w => attributeValues.Select(v => v.EntityId).Contains(w.Id));
                            }
                        }
                    }
                }

                var items = new List <ContentChannelItem>();
                foreach (var item in itemQry.ToList())
                {
                    if (item.IsAuthorized(Rock.Security.Authorization.VIEW, CurrentPerson))
                    {
                        items.Add(item);
                    }
                }

                SortProperty sortProperty = gContentChannelItems.SortProperty;
                if (sortProperty != null)
                {
                    items = items.AsQueryable().Sort(sortProperty).ToList();
                }
                else
                {
                    items = items.OrderByDescending(p => p.StartDateTime).ToList();
                }

                gContentChannelItems.ObjectList = new Dictionary <string, object>();
                items.ForEach(i => gContentChannelItems.ObjectList.Add(i.Id.ToString(), i));

                gContentChannelItems.DataSource = items.Select(i => new
                {
                    i.Id,
                    i.Guid,
                    i.Title,
                    i.StartDateTime,
                    i.ExpireDateTime,
                    i.Priority,
                    Status              = DisplayStatus(i.Status),
                    Occurrences         = i.EventItemOccurrences.Any(),
                    CreatedByPersonName = i.CreatedByPersonAlias != null ? String.Format("<a href={0}>{1}</a>", ResolveRockUrl(string.Format("~/Person/{0}", i.CreatedByPersonAlias.PersonId)), i.CreatedByPersonName) : String.Empty
                }).ToList();
                gContentChannelItems.DataBind();

                lContentChannelItems.Text = selectedChannel.Name + " Items";
            }
            else
            {
                divItemPanel.Visible = false;
            }
        }
        /// <summary>
        /// Gets the type of the content.
        /// </summary>
        /// <param name="contentItemId">The content type identifier.</param>
        /// <param name="rockContext">The rock context.</param>
        /// <returns></returns>
        private ContentChannelItem GetContentItem( RockContext rockContext = null )
        {
            rockContext = rockContext ?? new RockContext();
            var contentItemService = new ContentChannelItemService( rockContext );
            ContentChannelItem contentItem = null;

            int contentItemId = hfId.Value.AsInteger();
            if ( contentItemId != 0 )
            {
                contentItem = contentItemService
                    .Queryable( "ContentChannel,ContentChannelType" )
                    .FirstOrDefault( t => t.Id == contentItemId );
            }

            if ( contentItem == null)
            {
                var contentChannel = new ContentChannelService( rockContext ).Get( hfChannelId.Value.AsInteger() );
                if ( contentChannel != null )
                {
                    contentItem = new ContentChannelItem
                    {
                        ContentChannel = contentChannel,
                        ContentChannelId = contentChannel.Id,
                        ContentChannelType = contentChannel.ContentChannelType,
                        ContentChannelTypeId = contentChannel.ContentChannelType.Id,
                        StartDateTime = RockDateTime.Now
                    };

                    if ( contentChannel.RequiresApproval )
                    {
                        contentItem.Status = ContentChannelItemStatus.PendingApproval;
                    }
                    else
                    {
                        contentItem.Status = ContentChannelItemStatus.Approved;
                        contentItem.ApprovedDateTime = RockDateTime.Now;
                        contentItem.ApprovedByPersonAliasId = CurrentPersonAliasId;
                    }

                    contentItemService.Add( contentItem );
                }
            }

            return contentItem;
        }
        /// <summary>
        /// Handles the Click event of the deleteField control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RowEventArgs"/> instance containing the event data.</param>
        /// <exception cref="System.NotImplementedException"></exception>
        void gContentChannelItems_Delete( object sender, RowEventArgs e )
        {
            var rockContext = new RockContext();
            var contentItemService = new ContentChannelItemService( rockContext );
            var contentItem = contentItemService.Get( e.RowKeyId );
            if ( contentItem != null )
            {
                string errorMessage;
                if ( !contentItemService.CanDelete( contentItem, out errorMessage ) )
                {
                    mdGridWarning.Show( errorMessage, ModalAlertType.Information );
                    return;
                }

                contentItemService.Delete( contentItem );
                rockContext.SaveChanges();
            }

            GetData();
        }
Example #34
0
        public void ProcessRequest( HttpContext context )
        {
            request = context.Request;
            response = context.Response;

            RockContext rockContext = new RockContext();

            if ( request.HttpMethod != "GET" )
            {
                response.Write( "Invalid request type." );
                response.StatusCode = 200;
                return;
            }

            if ( request.QueryString["ChannelId"] != null )
            {
                int channelId;
                int templateDefinedValueId;
                DefinedValueCache dvRssTemplate;
                string rssTemplate;

                if ( !int.TryParse( request.QueryString["ChannelId"] , out channelId ))
                {
                    response.Write( "Invalid channel id." );
                    response.StatusCode = 200;
                    return;
                }

                if ( request.QueryString["TemplateId"] == null || !int.TryParse( request.QueryString["TemplateId"], out templateDefinedValueId ) )
                {
                    dvRssTemplate = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.DEFAULT_RSS_CHANNEL );
                }
                else
                {
                    dvRssTemplate = DefinedValueCache.Read( templateDefinedValueId );
                }

                rssTemplate = dvRssTemplate.GetAttributeValue( "Template" );

                if ( request.QueryString["EnableDebug"] != null )
                {
                    // when in debug mode we need to export as html and linkin styles so that the debug info will be displayed
                    string appPath = HttpContext.Current.Request.ApplicationPath;

                    response.Write( "<html>" );
                    response.Write( "<head>" );
                    response.Write( string.Format( "<link rel='stylesheet' type='text/css' href='{0}Themes/Rock/Styles/bootstrap.css'>", appPath ) );
                    response.Write( string.Format( "<link rel='stylesheet' type='text/css' href='{0}Themes/Rock/Styles/theme.css'>", appPath ) );
                    response.Write( string.Format( "<script src='{0}Scripts/jquery-1.10.2.min.js'></script>", appPath ) );
                    response.Write( string.Format( "<script src='{0}Scripts/bootstrap.min.js'></script>", appPath ) );
                    response.Write( "</head>" );
                    response.Write( "<body style='padding: 24px;'>" );
                }
                else
                {
                    if ( string.IsNullOrWhiteSpace( dvRssTemplate.GetAttributeValue( "MimeType" ) ) )
                    {
                        response.ContentType = "application/rss+xml";
                    }
                    else
                    {
                        response.ContentType = dvRssTemplate.GetAttributeValue( "MimeType" );
                    }
                }

                ContentChannelService channelService = new ContentChannelService( rockContext );

                var channel = channelService.Queryable( "ContentChannelType" ).Where( c => c.Id == channelId ).FirstOrDefault();

                if ( channel != null )
                {
                    if ( channel.EnableRss )
                    {
                        // load merge fields
                        var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields( null );
                        mergeFields.Add( "Channel", channel );

                        Dictionary<string, object> requestObjects = new Dictionary<string, object>();
                        requestObjects.Add( "Scheme", request.Url.Scheme );
                        requestObjects.Add( "Host", request.Url.Host );
                        requestObjects.Add( "Authority", request.Url.Authority );
                        requestObjects.Add( "LocalPath", request.Url.LocalPath );
                        requestObjects.Add( "AbsoluteUri", request.Url.AbsoluteUri );
                        requestObjects.Add( "AbsolutePath", request.Url.AbsolutePath );
                        requestObjects.Add( "Port", request.Url.Port );
                        requestObjects.Add( "Query", request.Url.Query );
                        requestObjects.Add( "OriginalString", request.Url.OriginalString );

                        mergeFields.Add( "Request", requestObjects );

                        // check for new rss item limit
                        if ( request.QueryString["Count"] != null )
                        {
                            int.TryParse( request.QueryString["Count"], out rssItemLimit );
                        }

                        // get channel items
                        ContentChannelItemService contentService = new ContentChannelItemService( rockContext );

                        var content = contentService.Queryable( "ContentChannelType" )
                                        .Where( c => c.ContentChannelId == channel.Id && (c.Status == ContentChannelItemStatus.Approved || c.ContentChannel.RequiresApproval == false) && c.StartDateTime <= RockDateTime.Now )
                                        .OrderByDescending( c => c.StartDateTime )
                                        .Take( rssItemLimit );

                        if ( channel.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange )
                        {
                            if ( channel.ContentChannelType.IncludeTime )
                            {
                                content = content.Where( c => c.ExpireDateTime >= RockDateTime.Now );
                            }
                            else
                            {
                                content = content.Where( c => c.ExpireDateTime > RockDateTime.Today );
                            }
                        }

                        foreach ( var item in content )
                        {
                            item.Content = item.Content.ResolveMergeFields( mergeFields );

                            // resolve any relative links
                            var globalAttributes = Rock.Web.Cache.GlobalAttributesCache.Read();
                            string publicAppRoot = globalAttributes.GetValue( "PublicApplicationRoot" ).EnsureTrailingForwardslash();
                            item.Content = item.Content.Replace( @" src=""/", @" src=""" + publicAppRoot );
                            item.Content = item.Content.Replace( @" href=""/", @" href=""" + publicAppRoot );

                            // get item attributes and add them as elements to the feed
                            item.LoadAttributes( rockContext );
                            foreach ( var attributeValue in item.AttributeValues )
                            {
                                attributeValue.Value.Value = attributeValue.Value.Value.ResolveMergeFields( mergeFields );
                            }
                        }

                        mergeFields.Add( "Items", content );

                        mergeFields.Add( "RockVersion", Rock.VersionInfo.VersionInfo.GetRockProductVersionNumber() );

                        // show debug info
                        if ( request.QueryString["EnableDebug"] != null )
                        {
                            response.Write( mergeFields.lavaDebugInfo() );
                            response.Write( "<pre>" );
                            response.Write( WebUtility.HtmlEncode(rssTemplate.ResolveMergeFields( mergeFields )) );
                            response.Write( "</pre>" );
                            response.Write( "</body>" );
                            response.Write( "</html" );
                        }
                        else
                        {
                            response.Write( rssTemplate.ResolveMergeFields( mergeFields ) );
                        }
                    }
                    else
                    {
                        response.Write( "RSS is not enabled for this channel." );
                        response.StatusCode = 200;
                        return;
                    }
                }
                else
                {
                    response.StatusCode = 200;
                    response.Write( "Invalid channel id." );
                    response.StatusCode = 200;
                    return;
                }

            }
            else
            {
                response.Write( "A ChannelId is required." );
                response.StatusCode = 200;
                return;
            }
        }
Example #35
0
        /// <summary>
        /// Formats the search result.
        /// </summary>
        /// <param name="person"></param>
        /// <param name="displayOptions"></param>
        /// <returns></returns>
        public override FormattedSearchResult FormatSearchResult( Person person, Dictionary<string, object> displayOptions = null )
        {
            bool showSummary = true;
            string url = string.Empty;
            bool isSecurityDisabled = false;

            if ( displayOptions != null )
            {
                if ( displayOptions.ContainsKey( "ChannelItem.ShowSummary" ) )
                {
                    showSummary = displayOptions["ChannelItem.ShowSummary"].ToString().AsBoolean();
                }
                if ( displayOptions.ContainsKey( "ChannelItem.Url" ) )
                {
                    url = displayOptions["ChannelItem.Url"].ToString();
                }
                if ( displayOptions.ContainsKey( "ChannelItem.IsSecurityDisabled" ) )
                {
                    isSecurityDisabled = displayOptions["ChannelItem.IsSecurityDisabled"].ToString().AsBoolean();
                }
            }

            if ( !isSecurityDisabled )
            {
                // check security
                var contentChannelItem = new ContentChannelItemService( new RockContext() ).Get( (int)this.Id );
                var isAllowedView = false;

                if (contentChannelItem != null )
                {
                    isAllowedView = contentChannelItem.IsAuthorized( "View", person );
                }

                if ( !isAllowedView )
                {
                    return new FormattedSearchResult() { IsViewAllowed = false };
                }
            }

            // if url was not passed in use default from content channel
            if ( string.IsNullOrWhiteSpace( url ) )
            {
                var channel = new ContentChannelService( new RockContext() ).Get( this.ContentChannelId );
                url = channel.ItemUrl;
            }

            var mergeFields = new Dictionary<string, object>();
            mergeFields.Add( "Id", this.Id );
            mergeFields.Add( "Title", this.Title );
            mergeFields.Add( "ContentChannelId", this.ContentChannelId );

            var summary = this["Summary"] ?? "" + this["summaryText"] ?? "";

            return new FormattedSearchResult() { IsViewAllowed = true, FormattedResult = $@"
                            <div class='row model-cannavigate' data-href='{url.ResolveMergeFields( mergeFields )}'>
                                <div class='col-sm-1 text-center'>
                                    <i class='{this.IconCssClass} fa-2x'></i>
                                </div>
                                <div class='col-sm-4'>
                                    {this.Title} <small>({this.ContentChannel})</small>
                                </div>
                                <div class='col-sm-7'>
                                    {(showSummary ? summary : "")}
                                </div>
                            </div>" };
        }
        /// <summary>
        /// Handles the Click event of the lbDelete 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 lbDelete_Click( object sender, EventArgs e )
        {
            RockContext rockContext = new RockContext();
            var contentItemService = new ContentChannelItemService( rockContext );
            ContentChannelItem contentItem = null;

            int contentItemId = hfId.Value.AsInteger();
            if ( contentItemId != 0 )
            {
                contentItem = contentItemService
                    .Queryable( "ContentChannel,ContentChannelType" )
                    .FirstOrDefault( t => t.Id == contentItemId );
            }

            if (contentItem != null )
            {
                contentItemService.Delete( contentItem );
                rockContext.SaveChanges();
            }

            ReturnToParentPage();
        }
Example #37
0
        /// <summary>
        /// Gets the content channel item using the first page parameter or ContentChannelQueryParameter
        /// </summary>
        /// <returns></returns>
        private ContentChannelItem GetContentChannelItem(string contentChannelItemKey)
        {
            int? itemCacheDuration  = GetAttributeValue("ItemCacheDuration").AsIntegerOrNull();
            Guid?contentChannelGuid = GetAttributeValue("ContentChannel").AsGuidOrNull();

            ContentChannelItem contentChannelItem = null;

            if (string.IsNullOrEmpty(contentChannelItemKey))
            {
                // nothing specified, so don't show anything
                return(null);
            }

            string itemCacheKey = ITEM_CACHE_KEY_PREFIX + contentChannelGuid + "_" + contentChannelItemKey;

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

            // look up the ContentChannelItem from either the Id, Guid, or Slug depending on the datatype of the ContentChannelQueryParameter value
            int? contentChannelItemId   = contentChannelItemKey.AsIntegerOrNull();
            Guid?contentChannelItemGuid = contentChannelItemKey.AsGuidOrNull();

            var rockContext = new RockContext();

            if (contentChannelItemId.HasValue)
            {
                contentChannelItem = new ContentChannelItemService(rockContext).Get(contentChannelItemId.Value);
            }
            else if (contentChannelItemGuid.HasValue)
            {
                contentChannelItem = new ContentChannelItemService(rockContext).Get(contentChannelItemGuid.Value);
            }
            else
            {
                var contentChannelQuery = new ContentChannelItemService(rockContext).Queryable();
                if (contentChannelGuid.HasValue)
                {
                    contentChannelQuery = contentChannelQuery.Where(c => c.ContentChannel.Guid == contentChannelGuid);
                }

                contentChannelItem = contentChannelQuery
                                     .Where(a => a.ContentChannelItemSlugs.Any(s => s.Slug == contentChannelItemKey))
                                     .FirstOrDefault();
            }

            if (contentChannelItem != null && itemCacheDuration.HasValue && itemCacheDuration.Value > 0)
            {
                string cacheTags = GetAttributeValue("CacheTags") ?? string.Empty;
                var    cacheKeys = GetCacheItem(CACHEKEYS_CACHE_KEY) as HashSet <string> ?? new HashSet <string>();
                cacheKeys.Add(itemCacheKey);
                AddCacheItem(CACHEKEYS_CACHE_KEY, cacheKeys, TimeSpan.MaxValue, cacheTags);
                AddCacheItem(itemCacheKey, contentChannelItem, itemCacheDuration.Value, cacheTags);
            }

            return(contentChannelItem);
        }
        private void GetData()
        {
            var rockContext = new RockContext();
            var itemService = new ContentChannelItemService(rockContext);

            int personId = CurrentPerson != null ? CurrentPerson.Id : 0;

            // Get all of the content channels
            var allChannels = new ContentChannelService( rockContext ).Queryable( "ContentChannelType" )
                .OrderBy( w => w.Name )
                .ToList();

            // Create variable for storing authorized channels and the count of active items
            var channelCounts = new Dictionary<int, int>();
            foreach ( var channel in allChannels )
            {
                if ( channel.IsAuthorized( Authorization.VIEW, CurrentPerson))
                {
                    channelCounts.Add( channel.Id, 0);
                }
            }

            // Get the pending approval item counts for each channel (if the channel requires approval)
            itemService.Queryable()
                .Where( i =>
                    channelCounts.Keys.Contains( i.ContentChannelId ) &&
                    i.Status == ContentChannelItemStatus.PendingApproval && i.ContentChannel.RequiresApproval )
                .GroupBy( i => i.ContentChannelId )
                .Select( i => new {
                    Id = i.Key,
                    Count = i.Count()
                })
                .ToList()
                .ForEach( i => channelCounts[i.Id] = i.Count );

            // Create a query to return channel, the count of items, and the selected class
            var qry = allChannels
                .Where( c => channelCounts.Keys.Contains( c.Id ) )
                .Select( c => new
                {
                    Channel = c,
                    Count = channelCounts[c.Id],
                    Class = ( SelectedChannelId.HasValue && SelectedChannelId.Value == c.Id ) ? "active" : ""
                } );

            // If displaying active only, update query to exclude those content channels without any items
            if ( tglStatus.Checked )
            {
                qry = qry.Where( c => c.Count > 0 );
            }

            var contentChannels = qry.ToList();

            rptChannels.DataSource = contentChannels;
            rptChannels.DataBind();

            ContentChannel selectedChannel = null;
            if ( SelectedChannelId.HasValue )
            {
                selectedChannel = allChannels
                    .Where( w =>
                        w.Id == SelectedChannelId.Value &&
                        channelCounts.Keys.Contains( SelectedChannelId.Value ) )
                    .FirstOrDefault();
            }

            if ( selectedChannel != null && contentChannels.Count > 0 )
            {
                // show the content item panel
                divItemPanel.Visible = true;

                BindAttributes( selectedChannel );
                AddDynamicControls( selectedChannel );

                var itemQry = itemService.Queryable()
                    .Where( i => i.ContentChannelId == selectedChannel.Id );

                var drp = new DateRangePicker();
                drp.DelimitedValues = gfFilter.GetUserPreference( "Date Range" );
                if ( drp.LowerValue.HasValue )
                {
                    if ( selectedChannel.ContentChannelType.DateRangeType == ContentChannelDateType.SingleDate )
                    {
                        itemQry = itemQry.Where( i => i.StartDateTime >= drp.LowerValue.Value );
                    }
                    else
                    {
                        itemQry = itemQry.Where( i => i.ExpireDateTime.HasValue && i.ExpireDateTime.Value >= drp.LowerValue.Value );
                    }
                }
                if ( drp.UpperValue.HasValue )
                {
                    DateTime upperDate = drp.UpperValue.Value.Date.AddDays( 1 );
                    itemQry = itemQry.Where( i => i.StartDateTime <= upperDate );
                }

                var status = gfFilter.GetUserPreference( "Status" ).ConvertToEnumOrNull<ContentChannelItemStatus>();
                if ( status.HasValue )
                {
                    itemQry = itemQry.Where( i => i.Status == status );
                }

                string title = gfFilter.GetUserPreference( "Title" );
                if (!string.IsNullOrWhiteSpace(title))
                {
                    itemQry = itemQry.Where( i => i.Title.Contains( title ) );
                }

                // Filter query by any configured attribute filters
                if ( AvailableAttributes != null && AvailableAttributes.Any() )
                {
                    var attributeValueService = new AttributeValueService( rockContext );
                    var parameterExpression = attributeValueService.ParameterExpression;

                    foreach ( var attribute in AvailableAttributes )
                    {
                        var filterControl = phAttributeFilters.FindControl( "filter_" + attribute.Id.ToString() );
                        if ( filterControl != null )
                        {
                            var filterValues = attribute.FieldType.Field.GetFilterValues( filterControl, attribute.QualifierValues, Rock.Reporting.FilterMode.SimpleFilter );
                            var expression = attribute.FieldType.Field.AttributeFilterExpression( attribute.QualifierValues, filterValues, parameterExpression );
                            if ( expression != null )
                            {
                                var attributeValues = attributeValueService
                                    .Queryable()
                                    .Where( v => v.Attribute.Id == attribute.Id );

                                attributeValues = attributeValues.Where( parameterExpression, expression, null );

                                itemQry = itemQry.Where( w => attributeValues.Select( v => v.EntityId ).Contains( w.Id ) );
                            }
                        }
                    }
                }

                var items = new List<ContentChannelItem>();
                foreach ( var item in itemQry.ToList() )
                {
                    if ( item.IsAuthorized( Rock.Security.Authorization.VIEW, CurrentPerson ) )
                    {
                        items.Add( item );
                    }
                }

                SortProperty sortProperty = gContentChannelItems.SortProperty;
                if ( sortProperty != null )
                {
                    items = items.AsQueryable().Sort( sortProperty ).ToList();
                }
                else
                {
                    items = items.OrderByDescending( p => p.StartDateTime ).ToList();
                }

                gContentChannelItems.ObjectList = new Dictionary<string, object>();
                items.ForEach( i => gContentChannelItems.ObjectList.Add( i.Id.ToString(), i ) );

                gContentChannelItems.DataSource = items.Select( i => new
                {
                    i.Id,
                    i.Guid,
                    i.Title,
                    i.StartDateTime,
                    i.ExpireDateTime,
                    i.Priority,
                    Status = DisplayStatus( i.Status ),
                    Occurrences = i.EventItemOccurrences.Any()
                } ).ToList();
                gContentChannelItems.DataBind();

                lContentChannelItems.Text = selectedChannel.Name + " Items";
            }
            else
            {
                divItemPanel.Visible = false;
            }
        }
Example #39
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;

        }
        /// <summary>
        /// Handles the GridReorder event of the GItems control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="GridReorderEventArgs"/> instance containing the event data.</param>
        private void GItems_GridReorder( object sender, GridReorderEventArgs e )
        {
            using ( var rockContext = new RockContext() )
            {
                bool isFiltered = false;
                var items = GetItems( rockContext, out isFiltered );

                if ( !isFiltered )
                {
                    var service = new ContentChannelItemService( rockContext );
                    service.Reorder( items, e.OldIndex, e.NewIndex );
                    rockContext.SaveChanges();
                }
            }

            BindGrid();
        }
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            if ( _channelId.HasValue )
            {
                ContentChannelItemService contentItemService = new ContentChannelItemService( new RockContext() );
                var contentItems = contentItemService.Queryable()
                    .Where( c => c.ContentChannelId == _channelId.Value );

                var drp = new DateRangePicker();
                drp.DelimitedValues = gfFilter.GetUserPreference( "Date Range" );
                if ( drp.LowerValue.HasValue )
                {
                    contentItems = contentItems.Where( i =>
                        ( i.ExpireDateTime.HasValue && i.ExpireDateTime.Value >= drp.LowerValue.Value ) ||
                        ( !i.ExpireDateTime.HasValue && i.StartDateTime >= drp.LowerValue.Value ) );
                }
                if ( drp.UpperValue.HasValue )
                {
                    DateTime upperDate = drp.UpperValue.Value.Date.AddDays( 1 );
                    contentItems = contentItems.Where( i => i.StartDateTime <= upperDate );
                }

                var status = gfFilter.GetUserPreference( "Status" ).ConvertToEnumOrNull<ContentChannelItemStatus>();
                if ( status.HasValue )
                {
                    contentItems = contentItems.Where( i => i.Status == status );
                }

                string title = gfFilter.GetUserPreference( "Title" );
                if ( !string.IsNullOrWhiteSpace( title ) )
                {
                    contentItems = contentItems.Where( i => i.Title.Contains( title ) );
                }

                // if the block has a person context filter requests for just them
                if ( _person != null )
                {
                    contentItems = contentItems.Where( i => i.CreatedByPersonAlias != null && i.CreatedByPersonAlias.PersonId == _person.Id );
                }

                // TODO: Checking security of every item will take longer and longer as more items are added.
                // Eventually we should implement server-side paging so that we only need to check security for
                // the items on the current page

                var items = new List<ContentChannelItem>();
                foreach ( var item in contentItems.ToList())
                {
                    if ( item.IsAuthorized( Rock.Security.Authorization.VIEW, CurrentPerson ))
                    {
                        items.Add(item);
                    }
                }

                SortProperty sortProperty = gItems.SortProperty;
                if ( sortProperty != null )
                {
                    items = items.AsQueryable().Sort( sortProperty ).ToList();
                }
                else
                {
                    items = items.OrderByDescending( p => p.StartDateTime ).ToList();
                }

                gItems.ObjectList = new Dictionary<string, object>();
                items.ForEach( i => gItems.ObjectList.Add( i.Id.ToString(), i ) );
                gItems.EntityTypeId = EntityTypeCache.Read<ContentChannelItem>().Id;

                gItems.DataSource = items.Select( i => new
                {
                    i.Id,
                    i.Guid,
                    i.Title,
                    i.StartDateTime,
                    i.ExpireDateTime,
                    i.Priority,
                    Status = DisplayStatus( i.Status ),
                    Occurrences = i.EventItemOccurrences.Any()
                } ).ToList();
                gItems.DataBind();
            }
        }
        protected void lbPersonPaging_Click(object sender, EventArgs e)
        {
            var rockContext        = new RockContext();
            var personService      = new PersonService(rockContext);
            var person             = personService.Queryable().FirstOrDefault(a => a.Guid == personGuid);
            var attributeKey       = GetAttributeValue("PersonAttributeKey");
            var contentChannel     = new ContentChannelService(rockContext).Get(GetAttributeValue("PersonPagingContentChannel").AsGuid());
            var contentChannelItem = new ContentChannelItem
            {
                Title                = string.Empty,
                Status               = ContentChannelItemStatus.Approved,
                Content              = string.Empty,
                ContentChannelId     = contentChannel.Id,
                ContentChannelTypeId = contentChannel.ContentChannelTypeId,
                Priority             = 0,
                StartDateTime        = DateTime.Now,
                Order                = 0,
                Guid = new Guid()
            };

            contentChannelItem.LoadAttributes();

            if (!contentChannelItem.Attributes.ContainsKey(attributeKey))
            {
                nbWarning.Text    = "The selected Content Channel is not configured with provided Attribute Key.";
                nbWarning.Visible = true;
            }
            else
            {
                var contentChannelItems = new ContentChannelItemService(rockContext).Queryable().AsNoTracking().Where(i => i.ContentChannelId.Equals(contentChannel.Id)).ToList();
                var exists = false;
                foreach (var item in contentChannelItems)
                {
                    item.LoadAttributes();
                    if (item.AttributeValues[attributeKey].Value.Equals(person.PrimaryAlias.Guid.ToString()))
                    {
                        exists = true;
                    }
                }

                if (exists)
                {
                    nbWarning.Text    = string.Format("{0} is already on the list.", person.FullName);
                    nbWarning.Visible = true;
                }
                else
                {
                    contentChannelItem.AttributeValues[attributeKey].Value = person.PrimaryAlias.Guid.ToString();

                    rockContext.WrapTransaction(() =>
                    {
                        rockContext.ContentChannelItems.Add(contentChannelItem);
                        rockContext.SaveChanges();
                        contentChannelItem.SaveAttributeValues(rockContext);
                    });

                    nbWarning.Text    = string.Format("{0} added to the list.", person.FullName);
                    nbWarning.Visible = true;
                }
            }
        }
Example #43
0
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event.
        /// </summary>
        /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnLoad( EventArgs e )
        {
            base.OnLoad( e );

            if ( !Page.IsPostBack )
            {
                // Get any querystring variables
                ContentItemId = PageParameter( "ContentItemId" ).AsIntegerOrNull();
                EventItemOccurrenceId = PageParameter( "EventItemOccurrenceId" ).AsIntegerOrNull();
                EventItemId = PageParameter( "EventItemId" ).AsIntegerOrNull();
                EventCalendarId = PageParameter( "EventCalendarId" ).AsIntegerOrNull();

                // Determine current page number based on querystring values
                if ( ContentItemId.HasValue )
                {
                    PageNumber = 5;
                }
                else if ( EventItemOccurrenceId.HasValue )
                {
                    PageNumber = 4;
                }
                else if ( EventItemId.HasValue )
                {
                    PageNumber = 3;
                }
                else if ( EventCalendarId.HasValue )
                {
                    PageNumber = 2;
                }
                else
                {
                    PageNumber = 1;
                }

                // Load objects neccessary to display names
                using ( var rockContext = new RockContext() )
                {
                    ContentChannelItem contentItem = null;
                    EventItemOccurrence eventItemOccurrence = null;
                    EventItem eventItem = null;
                    EventCalendar eventCalendar = null;

                    if ( ContentItemId.HasValue && ContentItemId.Value > 0 )
                    {
                        var contentChannel = new ContentChannelItemService( rockContext ).Get( ContentItemId.Value );
                    }

                    if ( EventItemOccurrenceId.HasValue && EventItemOccurrenceId.Value > 0 )
                    {
                        eventItemOccurrence = new EventItemOccurrenceService( rockContext ).Get( EventItemOccurrenceId.Value );
                        if ( eventItemOccurrence != null )
                        {
                            eventItem = eventItemOccurrence.EventItem;
                            if ( eventItem != null && !EventItemId.HasValue )
                            {
                                EventItemId = eventItem.Id;
                            }
                        }
                    }

                    if ( eventItem == null && EventItemId.HasValue && EventItemId.Value > 0 )
                    {
                        eventItem = new EventItemService( rockContext ).Get( EventItemId.Value );
                    }

                    if ( EventCalendarId.HasValue && EventCalendarId.Value > 0 )
                    {
                        eventCalendar = new EventCalendarService( rockContext ).Get( EventCalendarId.Value );
                    }

                    // Set the names based on current object values
                    lCalendarName.Text = eventCalendar != null ? eventCalendar.Name : "Calendar";
                    lCalendarItemName.Text = eventItem != null ? eventItem.Name : "Event";
                    lEventOccurrenceName.Text = eventItemOccurrence != null ?
                        ( eventItemOccurrence.Campus != null ? eventItemOccurrence.Campus.Name : "All Campuses" ) :
                        "Event Occurrence";
                    lContentItemName.Text = contentItem != null ? contentItem.Title : "Content Item";
                }
            }

            divCalendars.Attributes["class"] = GetDivClass( 1 );
            divCalendar.Attributes["class"] = GetDivClass( 2 );
            divCalendarItem.Attributes["class"] = GetDivClass( 3 );
            divEventOccurrence.Attributes["class"] = GetDivClass( 4 );
            divContentItem.Attributes["class"] = GetDivClass( 5 );
        }
Example #44
0
        /// <summary>
        /// Gets the data to display.
        /// </summary>
        private void GetData()
        {
            var rockContext = new RockContext();
            var itemService = new ContentChannelItemService(rockContext);

            // Get all of the content channels
            var contentChannelsQry = new ContentChannelService(rockContext).Queryable("ContentChannelType").AsNoTracking();

            List <Guid> contentChannelGuidsFilter      = GetAttributeValue(AttributeKey.ContentChannelsFilter).SplitDelimitedValues().AsGuidList();
            List <Guid> contentChannelTypeGuidsInclude = GetAttributeValue(AttributeKey.ContentChannelTypesInclude).SplitDelimitedValues().AsGuidList();
            List <Guid> contentChannelTypeGuidsExclude = GetAttributeValue(AttributeKey.ContentChannelTypesExclude).SplitDelimitedValues().AsGuidList();

            if (contentChannelGuidsFilter.Any())
            {
                // if contentChannelGuidsFilter is specified, only get those content channels.
                // NOTE: This take precedence over all the other Include/Exclude settings.
                contentChannelsQry = contentChannelsQry.Where(a => contentChannelGuidsFilter.Contains(a.Guid));
            }
            else if (contentChannelTypeGuidsInclude.Any())
            {
                // if contentChannelTypeGuidsInclude is specified, only get contentChannelTypes that are in the contentChannelTypeGuidsInclude
                // NOTE: no need to factor in contentChannelTypeGuidsExclude since included would take precedence and the excluded ones would already not be included
                contentChannelsQry = contentChannelsQry.Where(a => contentChannelTypeGuidsInclude.Contains(a.ContentChannelType.Guid) || a.ContentChannelType.ShowInChannelList);
            }
            else if (contentChannelTypeGuidsExclude.Any())
            {
                contentChannelsQry = contentChannelsQry.Where(a => !contentChannelTypeGuidsExclude.Contains(a.ContentChannelType.Guid) && a.ContentChannelType.ShowInChannelList);
            }
            else
            {
                contentChannelsQry = contentChannelsQry.Where(a => a.ContentChannelType.ShowInChannelList);
            }


            if (GetAttributeValue(AttributeKey.ShowCategoryFilter).AsBoolean())
            {
                int?categoryId          = null;
                var categoryGuid        = PageParameter("CategoryGuid").AsGuidOrNull();
                var selectedChannelGuid = PageParameter("ContentChannelGuid").AsGuidOrNull();

                if (selectedChannelGuid.HasValue)
                {
                    categoryId = CategoryCache.Get(categoryGuid.GetValueOrDefault())?.Id;
                }
                else
                {
                    categoryId = ddlCategory.SelectedValueAsId();
                }

                SetUserPreference(CATEGORY_FILTER_SETTING, categoryId.ToString());
                ddlCategory.SetValue(categoryId);

                var parentCategoryGuid = GetAttributeValue(AttributeKey.ParentCategory).AsGuidOrNull();
                if (ddlCategory.Visible && categoryId.HasValue)
                {
                    contentChannelsQry = contentChannelsQry.Where(a => a.Categories.Any(c => c.Id == categoryId));
                }
                else if (parentCategoryGuid.HasValue)
                {
                    var parentCategoryId = CategoryCache.GetId(parentCategoryGuid.Value);
                    contentChannelsQry = contentChannelsQry.Where(a => a.Categories.Any(c => c.ParentCategoryId == parentCategoryId));
                }
            }

            var contentChannelsList = contentChannelsQry.OrderBy(w => w.Name).ToList();

            // Create variable for storing authorized channels and the count of active items
            var channelCounts = new Dictionary <int, int>();

            foreach (var channel in contentChannelsList)
            {
                if (channel.IsAuthorized(Authorization.VIEW, CurrentPerson))
                {
                    channelCounts.Add(channel.Id, 0);
                }
            }

            // Get the pending approval item counts for each channel (if the channel requires approval)
            itemService.Queryable()
            .Where(i =>
                   channelCounts.Keys.Contains(i.ContentChannelId) &&
                   i.Status == ContentChannelItemStatus.PendingApproval && i.ContentChannel.RequiresApproval)
            .GroupBy(i => i.ContentChannelId)
            .Select(i => new
            {
                Id    = i.Key,
                Count = i.Count()
            })
            .ToList()
            .ForEach(i => channelCounts[i.Id] = i.Count);

            // Create a query to return channel, the count of items, and the selected class
            var qry = contentChannelsList
                      .Where(c => channelCounts.Keys.Contains(c.Id))
                      .Select(c => new
            {
                Channel = c,
                Count   = channelCounts[c.Id],
                Class   = (SelectedChannelId.HasValue && SelectedChannelId.Value == c.Id) ? "active" : ""
            });

            // If displaying active only, update query to exclude those content channels without any items
            if (tglStatus.Checked)
            {
                qry = qry.Where(c => c.Count > 0);
            }

            var contentChannels = qry.ToList();

            rptChannels.DataSource = contentChannels;
            rptChannels.DataBind();

            ContentChannel selectedChannel = null;

            if (SelectedChannelId.HasValue)
            {
                selectedChannel = contentChannelsList
                                  .Where(w =>
                                         w.Id == SelectedChannelId.Value &&
                                         channelCounts.Keys.Contains(SelectedChannelId.Value))
                                  .FirstOrDefault();
            }

            if (selectedChannel != null && contentChannels.Count > 0)
            {
                // show the content item panel
                divItemPanel.Visible = true;

                BindAttributes(selectedChannel);
                AddDynamicControls(selectedChannel);

                bool isFiltered = false;
                var  items      = GetItems(rockContext, selectedChannel, out isFiltered);

                var reorderFieldColumn = gContentChannelItems.ColumnsOfType <ReorderField>().FirstOrDefault();

                if (selectedChannel.ItemsManuallyOrdered && !isFiltered)
                {
                    if (reorderFieldColumn != null)
                    {
                        reorderFieldColumn.Visible = true;
                    }

                    gContentChannelItems.AllowSorting = false;
                }
                else
                {
                    if (reorderFieldColumn != null)
                    {
                        reorderFieldColumn.Visible = false;
                    }

                    gContentChannelItems.AllowSorting = true;

                    SortProperty sortProperty = gContentChannelItems.SortProperty;
                    if (sortProperty != null)
                    {
                        items = items.AsQueryable().Sort(sortProperty).ToList();
                    }
                    else
                    {
                        items = items.OrderByDescending(p => p.StartDateTime).ToList();
                    }
                }

                // Find any possible tags for the items
                var itemTags = new Dictionary <Guid, string>();
                if (selectedChannel.IsTaggingEnabled)
                {
                    itemTags = items.ToDictionary(i => i.Guid, v => "");
                    var entityTypeId = EntityTypeCache.Get(Rock.SystemGuid.EntityType.CONTENT_CHANNEL_ITEM.AsGuid()).Id;
                    var testedTags   = new Dictionary <int, string>();

                    foreach (var taggedItem in new TaggedItemService(rockContext)
                             .Queryable().AsNoTracking()
                             .Where(i =>
                                    i.EntityTypeId == entityTypeId &&
                                    itemTags.Keys.Contains(i.EntityGuid))
                             .OrderBy(i => i.Tag.Name))
                    {
                        if (!testedTags.ContainsKey(taggedItem.TagId))
                        {
                            testedTags.Add(taggedItem.TagId, taggedItem.Tag.IsAuthorized(Authorization.VIEW, CurrentPerson) ? taggedItem.Tag.Name : string.Empty);
                        }

                        if (testedTags[taggedItem.TagId].IsNotNullOrWhiteSpace())
                        {
                            itemTags[taggedItem.EntityGuid] += string.Format("<span class='tag'>{0}</span>", testedTags[taggedItem.TagId]);
                        }
                    }
                }

                gContentChannelItems.ObjectList = new Dictionary <string, object>();
                items.ForEach(i => gContentChannelItems.ObjectList.Add(i.Id.ToString(), i));

                var gridList = items.Select(i => new
                {
                    i.Id,
                    i.Guid,
                    i.Title,
                    i.StartDateTime,
                    i.ExpireDateTime,
                    i.Priority,
                    Status              = DisplayStatus(i.Status),
                    DateStatus          = DisplayDateStatus(i.StartDateTime),
                    Tags                = itemTags.GetValueOrNull(i.Guid),
                    Occurrences         = i.EventItemOccurrences.Any(),
                    CreatedByPersonName = i.CreatedByPersonAlias != null ? String.Format("<a href={0}>{1}</a>", ResolveRockUrl(string.Format("~/Person/{0}", i.CreatedByPersonAlias.PersonId)), i.CreatedByPersonName) : String.Empty
                }).ToList();

                // only show the Event Occurrences item if any of the displayed content channel items have any occurrences (and the block setting is enabled)
                var eventOccurrencesColumn = gContentChannelItems.ColumnsWithDataField("Occurrences").FirstOrDefault();
                eventOccurrencesColumn.Visible = gridList.Any(a => a.Occurrences == true);

                gContentChannelItems.DataSource = gridList;
                gContentChannelItems.DataBind();

                lContentChannelItems.Text = selectedChannel.Name + " Items";
            }
            else
            {
                divItemPanel.Visible = false;
            }
        }
        private List<ContentChannelItem> GetItems( RockContext rockContext, ContentChannel selectedChannel, out bool isFiltered )
        {
            isFiltered = false;

            var items = new List<ContentChannelItem>();

            var itemQry = new ContentChannelItemService( rockContext ).Queryable()
                .Where( i => i.ContentChannelId == selectedChannel.Id );

            var drp = new DateRangePicker();
            drp.DelimitedValues = gfFilter.GetUserPreference( "Date Range" );
            if ( drp.LowerValue.HasValue )
            {
                isFiltered = true;
                if ( selectedChannel.ContentChannelType.DateRangeType == ContentChannelDateType.SingleDate )
                {
                    itemQry = itemQry.Where( i => i.StartDateTime >= drp.LowerValue.Value );
                }
                else
                {
                    itemQry = itemQry.Where( i => i.ExpireDateTime.HasValue && i.ExpireDateTime.Value >= drp.LowerValue.Value );
                }
            }
            if ( drp.UpperValue.HasValue )
            {
                isFiltered = true;
                DateTime upperDate = drp.UpperValue.Value.Date.AddDays( 1 );
                itemQry = itemQry.Where( i => i.StartDateTime <= upperDate );
            }

            var status = gfFilter.GetUserPreference( "Status" ).ConvertToEnumOrNull<ContentChannelItemStatus>();
            if ( status.HasValue )
            {
                isFiltered = true;
                itemQry = itemQry.Where( i => i.Status == status );
            }

            string title = gfFilter.GetUserPreference( "Title" );
            if ( !string.IsNullOrWhiteSpace( title ) )
            {
                isFiltered = true;
                itemQry = itemQry.Where( i => i.Title.Contains( title ) );
            }

            int? personId = gfFilter.GetUserPreference( "Created By" ).AsIntegerOrNull();
            if ( personId.HasValue && personId.Value != 0 )
            {
                isFiltered = true;
                itemQry = itemQry.Where( i => i.CreatedByPersonAlias.PersonId == personId );
            }

            // Filter query by any configured attribute filters
            if ( AvailableAttributes != null && AvailableAttributes.Any() )
            {
                var attributeValueService = new AttributeValueService( rockContext );
                var parameterExpression = attributeValueService.ParameterExpression;

                foreach ( var attribute in AvailableAttributes )
                {
                    var filterControl = phAttributeFilters.FindControl( "filter_" + attribute.Id.ToString() );
                    if ( filterControl != null )
                    {
                        var filterValues = attribute.FieldType.Field.GetFilterValues( filterControl, attribute.QualifierValues, Rock.Reporting.FilterMode.SimpleFilter );
                        var expression = attribute.FieldType.Field.AttributeFilterExpression( attribute.QualifierValues, filterValues, parameterExpression );
                        if ( expression != null )
                        {
                            var attributeValues = attributeValueService
                                .Queryable()
                                .Where( v => v.Attribute.Id == attribute.Id );

                            attributeValues = attributeValues.Where( parameterExpression, expression, null );

                            isFiltered = true;
                            itemQry = itemQry.Where( w => attributeValues.Select( v => v.EntityId ).Contains( w.Id ) );
                        }
                    }
                }
            }

            foreach ( var item in itemQry.ToList() )
            {
                if ( item.IsAuthorized( Rock.Security.Authorization.VIEW, CurrentPerson ) )
                {
                    items.Add( item );
                }
                else
                {
                    isFiltered = true;
                }
            }

            if ( selectedChannel.ItemsManuallyOrdered && !isFiltered )
            {
                return items.OrderBy( i => i.Order ).ToList();
            }
            else
            {
                return items;
            }
        }
Example #46
0
        private List <ContentChannelItem> GetItems(RockContext rockContext, ContentChannel selectedChannel, out bool isFiltered)
        {
            isFiltered = false;

            var items = new List <ContentChannelItem>();

            var contentChannelItemService = new ContentChannelItemService(rockContext);

            var itemQry = contentChannelItemService.Queryable()
                          .Where(i => i.ContentChannelId == selectedChannel.Id);

            var drp = new DateRangePicker();

            drp.DelimitedValues = gfFilter.GetUserPreference("Date Range");
            if (drp.LowerValue.HasValue)
            {
                isFiltered = true;
                if (selectedChannel.ContentChannelType.DateRangeType == ContentChannelDateType.SingleDate)
                {
                    itemQry = itemQry.Where(i => i.StartDateTime >= drp.LowerValue.Value);
                }
                else
                {
                    itemQry = itemQry.Where(i => i.ExpireDateTime.HasValue && i.ExpireDateTime.Value >= drp.LowerValue.Value);
                }
            }
            if (drp.UpperValue.HasValue)
            {
                isFiltered = true;
                DateTime upperDate = drp.UpperValue.Value.Date.AddDays(1);
                itemQry = itemQry.Where(i => i.StartDateTime <= upperDate);
            }

            var status = gfFilter.GetUserPreference("Status").ConvertToEnumOrNull <ContentChannelItemStatus>();

            if (status.HasValue)
            {
                isFiltered = true;
                itemQry    = itemQry.Where(i => i.Status == status);
            }

            string title = gfFilter.GetUserPreference("Title");

            if (!string.IsNullOrWhiteSpace(title))
            {
                isFiltered = true;
                itemQry    = itemQry.Where(i => i.Title.Contains(title));
            }

            int?personId = gfFilter.GetUserPreference("Created By").AsIntegerOrNull();

            if (personId.HasValue && personId.Value != 0)
            {
                isFiltered = true;
                itemQry    = itemQry.Where(i => i.CreatedByPersonAlias.PersonId == personId);
            }

            // Filter query by any configured attribute filters
            if (AvailableAttributes != null && AvailableAttributes.Any())
            {
                foreach (var attribute in AvailableAttributes)
                {
                    var filterControl = phAttributeFilters.FindControl("filter_" + attribute.Id.ToString());
                    itemQry = attribute.FieldType.Field.ApplyAttributeQueryFilter(itemQry, filterControl, attribute, contentChannelItemService, Rock.Reporting.FilterMode.SimpleFilter);
                }
            }

            foreach (var item in itemQry.ToList())
            {
                if (item.IsAuthorized(Rock.Security.Authorization.VIEW, CurrentPerson))
                {
                    items.Add(item);
                }
                else
                {
                    isFiltered = true;
                }
            }

            if (selectedChannel.ItemsManuallyOrdered && !isFiltered)
            {
                return(items.OrderBy(i => i.Order).ToList());
            }
            else
            {
                return(items);
            }
        }
        private void GContentChannelItems_GridReorder( object sender, GridReorderEventArgs e )
        {
            if ( SelectedChannelId.HasValue )
            {
                using ( var rockContext = new RockContext() )
                {
                    var selectedChannel = new ContentChannelService( rockContext ).Get( SelectedChannelId.Value );
                    if ( selectedChannel != null )
                    {
                        bool isFiltered = false;
                        var items = GetItems( rockContext, selectedChannel, out isFiltered );

                        if ( !isFiltered )
                        {
                            var service = new ContentChannelItemService( rockContext );
                            service.Reorder( items, e.OldIndex, e.NewIndex );
                            rockContext.SaveChanges();
                        }
                    }
                }
            }

            GetData();
        }
Example #48
0
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event.
        /// </summary>
        /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (!Page.IsPostBack)
            {
                // Get any querystring variables
                ContentItemId         = PageParameter("ContentItemId").AsIntegerOrNull();
                EventItemOccurrenceId = PageParameter("EventItemOccurrenceId").AsIntegerOrNull();
                EventItemId           = PageParameter("EventItemId").AsIntegerOrNull();
                EventCalendarId       = PageParameter("EventCalendarId").AsIntegerOrNull();

                // Determine current page number based on querystring values
                if (ContentItemId.HasValue)
                {
                    PageNumber = 5;
                }
                else if (EventItemOccurrenceId.HasValue)
                {
                    PageNumber = 4;
                }
                else if (EventItemId.HasValue)
                {
                    PageNumber = 3;
                }
                else if (EventCalendarId.HasValue)
                {
                    PageNumber = 2;
                }
                else
                {
                    PageNumber = 1;
                }

                // Load objects neccessary to display names
                using (var rockContext = new RockContext())
                {
                    ContentChannelItem  contentItem         = null;
                    EventItemOccurrence eventItemOccurrence = null;
                    EventItem           eventItem           = null;
                    EventCalendar       eventCalendar       = null;

                    if (ContentItemId.HasValue && ContentItemId.Value > 0)
                    {
                        var contentChannel = new ContentChannelItemService(rockContext).Get(ContentItemId.Value);
                    }

                    if (EventItemOccurrenceId.HasValue && EventItemOccurrenceId.Value > 0)
                    {
                        eventItemOccurrence = new EventItemOccurrenceService(rockContext).Get(EventItemOccurrenceId.Value);
                        if (eventItemOccurrence != null)
                        {
                            eventItem = eventItemOccurrence.EventItem;
                            if (eventItem != null && !EventItemId.HasValue)
                            {
                                EventItemId = eventItem.Id;
                            }
                        }
                    }

                    if (eventItem == null && EventItemId.HasValue && EventItemId.Value > 0)
                    {
                        eventItem = new EventItemService(rockContext).Get(EventItemId.Value);
                    }

                    if (EventCalendarId.HasValue && EventCalendarId.Value > 0)
                    {
                        eventCalendar = new EventCalendarService(rockContext).Get(EventCalendarId.Value);
                    }

                    // Set the names based on current object values
                    lCalendarName.Text        = eventCalendar != null ? eventCalendar.Name : "Calendar";
                    lCalendarItemName.Text    = eventItem != null ? eventItem.Name : "Event";
                    lEventOccurrenceName.Text = eventItemOccurrence != null ?
                                                (eventItemOccurrence.Campus != null ? eventItemOccurrence.Campus.Name : "All Campuses") :
                                                "Event Occurrence";
                    lContentItemName.Text = contentItem != null ? contentItem.Title : "Content Item";
                }
            }

            divCalendars.Attributes["class"]       = GetDivClass(1);
            divCalendar.Attributes["class"]        = GetDivClass(2);
            divCalendarItem.Attributes["class"]    = GetDivClass(3);
            divEventOccurrence.Attributes["class"] = GetDivClass(4);
            divContentItem.Attributes["class"]     = GetDivClass(5);
        }
        /// <summary>
        /// Gets the type of the content.
        /// </summary>
        /// <param name="contentItemId">The content type identifier.</param>
        /// <param name="rockContext">The rock context.</param>
        /// <returns></returns>
        private ContentChannelItem GetContentItem( RockContext rockContext = null )
        {
            rockContext = rockContext ?? new RockContext();
            var contentItemService = new ContentChannelItemService( rockContext );
            ContentChannelItem contentItem = null;

            int contentItemId = hfId.Value.AsInteger();
            if ( contentItemId != 0 )
            {
                contentItem = contentItemService
                    .Queryable( "ContentChannel,ContentChannelType" )
                    .FirstOrDefault( t => t.Id == contentItemId );
            }

            if ( contentItem == null)
            {
                var contentChannel = new ContentChannelService( rockContext ).Get( hfChannelId.Value.AsInteger() );
                if ( contentChannel != null )
                {
                    contentItem = new ContentChannelItem
                    {
                        ContentChannel = contentChannel,
                        ContentChannelId = contentChannel.Id,
                        ContentChannelType = contentChannel.ContentChannelType,
                        ContentChannelTypeId = contentChannel.ContentChannelType.Id,
                        StartDateTime = RockDateTime.Now
                    };

                    var hierarchy = GetNavHierarchy();
                    if ( hierarchy.Any() )
                    {
                        var parentItem = contentItemService.Get( hierarchy.Last().AsInteger() );
                        if ( parentItem != null &&
                            parentItem.IsAuthorized( Authorization.EDIT, CurrentPerson ) &&
                            parentItem.ContentChannel.ChildContentChannels.Any( c => c.Id == contentChannel.Id ) )
                        {
                            var order = parentItem.ChildItems
                                .Select( a => (int?)a.Order )
                                .DefaultIfEmpty()
                                .Max();

                            var assoc = new ContentChannelItemAssociation();
                            assoc.ContentChannelItemId = parentItem.Id;
                            assoc.Order = order.HasValue ? order.Value + 1 : 0;
                            contentItem.ParentItems.Add( assoc );
                        }
                    }

                    if ( contentChannel.RequiresApproval )
                    {
                        contentItem.Status = ContentChannelItemStatus.PendingApproval;
                    }
                    else
                    {
                        contentItem.Status = ContentChannelItemStatus.Approved;
                        contentItem.ApprovedDateTime = RockDateTime.Now;
                        contentItem.ApprovedByPersonAliasId = CurrentPersonAliasId;
                    }

                    contentItemService.Add( contentItem );
                }
            }

            return contentItem;
        }
Example #50
0
        /// <summary>
        /// Shows the view.
        /// </summary>
        /// <param name="groupId">The group identifier.</param>
        /// <param name="groupMemberId">The group member identifier.</param>
        protected void ShowView(int groupId, int groupMemberId)
        {
            pnlView.Visible            = true;
            pnlMain.Visible            = true;
            pnlEditPreferences.Visible = false;
            hfGroupId.Value            = groupId.ToString();
            hfGroupMemberId.Value      = groupMemberId.ToString();
            var rockContext = new RockContext();

            var group = new GroupService(rockContext).Get(groupId);

            if (group == null)
            {
                pnlView.Visible = false;
                return;
            }

            var groupMember = new GroupMemberService(rockContext).Queryable().Where(a => a.GroupId == groupId && a.Id == groupMemberId).FirstOrDefault();

            if (groupMember == null)
            {
                pnlView.Visible = false;
                return;
            }

            group.LoadAttributes(rockContext);

            // set page title to the trip name
            RockPage.Title        = group.GetAttributeValue("OpportunityTitle");
            RockPage.BrowserTitle = group.GetAttributeValue("OpportunityTitle");
            RockPage.Header.Title = group.GetAttributeValue("OpportunityTitle");

            var mergeFields = LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson, new CommonMergeFieldsOptions {
                GetLegacyGlobalMergeFields = false
            });

            mergeFields.Add("Group", group);

            groupMember.LoadAttributes(rockContext);
            mergeFields.Add("GroupMember", groupMember);

            // Left Top Sidebar
            var photoGuid = group.GetAttributeValue("OpportunityPhoto");

            imgOpportunityPhoto.ImageUrl = string.Format("~/GetImage.ashx?Guid={0}", photoGuid);

            // Top Main
            string profileLavaTemplate = this.GetAttributeValue("ProfileLavaTemplate");

            if (groupMember.PersonId == this.CurrentPersonId)
            {
                // show a warning about missing Photo or Intro if the current person is viewing their own profile
                var warningItems = new List <string>();
                if (!groupMember.Person.PhotoId.HasValue)
                {
                    warningItems.Add("photo");
                }
                if (groupMember.GetAttributeValue("PersonalOpportunityIntroduction").IsNullOrWhiteSpace())
                {
                    warningItems.Add("personal opportunity introduction");
                }

                nbProfileWarning.Text    = "<stong>Tip!</strong> Edit your profile to add a " + warningItems.AsDelimited(", ", " and ") + ".";
                nbProfileWarning.Visible = warningItems.Any();
            }
            else
            {
                nbProfileWarning.Visible = false;
            }

            btnEditProfile.Visible = groupMember.PersonId == this.CurrentPersonId;

            lMainTopContentHtml.Text = profileLavaTemplate.ResolveMergeFields(mergeFields);

            bool disablePublicContributionRequests = groupMember.GetAttributeValue("DisablePublicContributionRequests").AsBoolean();

            // only show Contribution stuff if the current person is the participant and contribution requests haven't been disabled
            bool showContributions = !disablePublicContributionRequests && (groupMember.PersonId == this.CurrentPersonId);

            btnContributionsTab.Visible = showContributions;

            // Progress
            var entityTypeIdGroupMember = EntityTypeCache.GetId <Rock.Model.GroupMember>();

            var contributionTotal = new FinancialTransactionDetailService(rockContext).Queryable()
                                    .Where(d => d.EntityTypeId == entityTypeIdGroupMember &&
                                           d.EntityId == groupMemberId)
                                    .Sum(a => (decimal?)a.Amount) ?? 0.00M;

            var individualFundraisingGoal = groupMember.GetAttributeValue("IndividualFundraisingGoal").AsDecimalOrNull();

            if (!individualFundraisingGoal.HasValue)
            {
                individualFundraisingGoal = group.GetAttributeValue("IndividualFundraisingGoal").AsDecimalOrNull();
            }

            var amountLeft = individualFundraisingGoal - contributionTotal;
            var percentMet = individualFundraisingGoal > 0 ? contributionTotal * 100 / individualFundraisingGoal : 100;

            mergeFields.Add("AmountLeft", amountLeft);
            mergeFields.Add("PercentMet", percentMet);

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

            queryParams.Add("GroupId", hfGroupId.Value);
            queryParams.Add("GroupMemberId", hfGroupMemberId.Value);
            mergeFields.Add("MakeDonationUrl", LinkedPageUrl("DonationPage", queryParams));

            var opportunityType = DefinedValueCache.Get(group.GetAttributeValue("OpportunityType").AsGuid());

            string makeDonationButtonText = null;

            if (groupMember.PersonId == this.CurrentPersonId)
            {
                makeDonationButtonText = "Make Payment";
            }
            else
            {
                makeDonationButtonText = string.Format("Contribute to {0} {1}", RockFilters.Possessive(groupMember.Person.NickName), opportunityType);
            }

            mergeFields.Add("MakeDonationButtonText", makeDonationButtonText);

            var progressLavaTemplate = this.GetAttributeValue("ProgressLavaTemplate");

            lProgressHtml.Text = progressLavaTemplate.ResolveMergeFields(mergeFields);

            // set text on the return button
            btnMainPage.Text = opportunityType.Value + " Page";

            // Tab:Updates
            btnUpdatesTab.Visible = false;
            bool showContentChannelUpdates = false;
            var  updatesContentChannelGuid = group.GetAttributeValue("UpdateContentChannel").AsGuidOrNull();

            if (updatesContentChannelGuid.HasValue)
            {
                var contentChannel = new ContentChannelService(rockContext).Get(updatesContentChannelGuid.Value);
                if (contentChannel != null)
                {
                    showContentChannelUpdates = true;

                    // only show the UpdatesTab if there is another Tab option
                    btnUpdatesTab.Visible = btnContributionsTab.Visible;

                    string updatesLavaTemplate = this.GetAttributeValue("UpdatesLavaTemplate");
                    var    contentChannelItems = new ContentChannelItemService(rockContext).Queryable().Where(a => a.ContentChannelId == contentChannel.Id).AsNoTracking().ToList();

                    mergeFields.Add("ContentChannelItems", contentChannelItems);
                    lUpdatesContentItemsHtml.Text = updatesLavaTemplate.ResolveMergeFields(mergeFields);
                    btnUpdatesTab.Text            = string.Format("{0} Updates ({1})", opportunityType, contentChannelItems.Count());
                }
            }

            if (showContentChannelUpdates)
            {
                SetActiveTab("Updates");
            }
            else if (showContributions)
            {
                SetActiveTab("Contributions");
            }
            else
            {
                SetActiveTab("");
            }

            // Tab: Contributions
            BindContributionsGrid();

            // Tab:Comments
            var noteType = NoteTypeCache.Get(this.GetAttributeValue("NoteType").AsGuid());

            if (noteType != null)
            {
                notesCommentsTimeline.NoteOptions.SetNoteTypes(new List <NoteTypeCache> {
                    noteType
                });
            }

            notesCommentsTimeline.NoteOptions.EntityId = groupMember.Id;

            // show the Add button on comments for any logged in person
            notesCommentsTimeline.AddAllowed = true;

            var enableCommenting = group.GetAttributeValue("EnableCommenting").AsBoolean();

            if (CurrentPerson == null)
            {
                notesCommentsTimeline.Visible = enableCommenting && (notesCommentsTimeline.NoteCount > 0);
                lNoLoginNoCommentsYet.Visible = notesCommentsTimeline.NoteCount == 0;
                pnlComments.Visible           = enableCommenting;
                btnLoginToComment.Visible     = enableCommenting;
            }
            else
            {
                lNoLoginNoCommentsYet.Visible = false;
                notesCommentsTimeline.Visible = enableCommenting;
                pnlComments.Visible           = enableCommenting;
                btnLoginToComment.Visible     = false;
            }

            // if btnContributionsTab is the only visible tab, hide the tab since there is nothing else to tab to
            if (!btnUpdatesTab.Visible && btnContributionsTab.Visible)
            {
                SetActiveTab("Contributions");
                btnContributionsTab.Visible = false;
            }
        }
Example #51
0
        public void ProcessRequest(HttpContext context)
        {
            request  = context.Request;
            response = context.Response;

            RockContext rockContext = new RockContext();

            if (request.HttpMethod != "GET")
            {
                response.Write("Invalid request type.");
                response.StatusCode = 200;
                return;
            }

            if (request.QueryString["ChannelId"] != null)
            {
                int channelId;
                int templateDefinedValueId;
                DefinedValueCache dvRssTemplate;
                string            rssTemplate;

                if (!int.TryParse(request.QueryString["ChannelId"], out channelId))
                {
                    response.Write("Invalid channel id.");
                    response.StatusCode = 200;
                    return;
                }

                if (request.QueryString["TemplateId"] == null || !int.TryParse(request.QueryString["TemplateId"], out templateDefinedValueId))
                {
                    dvRssTemplate = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.DEFAULT_RSS_CHANNEL);
                }
                else
                {
                    dvRssTemplate = DefinedValueCache.Read(templateDefinedValueId);
                }

                rssTemplate = dvRssTemplate.GetAttributeValue("Template");


                if (request.QueryString["EnableDebug"] != null)
                {
                    // when in debug mode we need to export as html and linkin styles so that the debug info will be displayed
                    string appPath = HttpContext.Current.Request.ApplicationPath;

                    response.Write("<html>");
                    response.Write("<head>");
                    response.Write(string.Format("<link rel='stylesheet' type='text/css' href='{0}Themes/Rock/Styles/bootstrap.css'>", appPath));
                    response.Write(string.Format("<link rel='stylesheet' type='text/css' href='{0}Themes/Rock/Styles/theme.css'>", appPath));
                    response.Write(string.Format("<script src='{0}Scripts/jquery-1.12.4.min.js'></script>", appPath));
                    response.Write(string.Format("<script src='{0}Scripts/bootstrap.min.js'></script>", appPath));
                    response.Write("</head>");
                    response.Write("<body style='padding: 24px;'>");
                }
                else
                {
                    if (string.IsNullOrWhiteSpace(dvRssTemplate.GetAttributeValue("MimeType")))
                    {
                        response.ContentType = "application/rss+xml";
                    }
                    else
                    {
                        response.ContentType = dvRssTemplate.GetAttributeValue("MimeType");
                    }
                }


                ContentChannelService channelService = new ContentChannelService(rockContext);

                var channel = channelService.Queryable("ContentChannelType").Where(c => c.Id == channelId).FirstOrDefault();

                if (channel != null)
                {
                    if (channel.EnableRss)
                    {
                        // load merge fields
                        var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(null);
                        mergeFields.Add("Channel", channel);

                        Dictionary <string, object> requestObjects = new Dictionary <string, object>();
                        requestObjects.Add("Scheme", request.Url.Scheme);
                        requestObjects.Add("Host", request.Url.Host);
                        requestObjects.Add("Authority", request.Url.Authority);
                        requestObjects.Add("LocalPath", request.Url.LocalPath);
                        requestObjects.Add("AbsoluteUri", request.Url.AbsoluteUri);
                        requestObjects.Add("AbsolutePath", request.Url.AbsolutePath);
                        requestObjects.Add("Port", request.Url.Port);
                        requestObjects.Add("Query", request.Url.Query);
                        requestObjects.Add("OriginalString", request.Url.OriginalString);

                        mergeFields.Add("Request", requestObjects);

                        // check for new rss item limit
                        if (request.QueryString["Count"] != null)
                        {
                            int.TryParse(request.QueryString["Count"], out rssItemLimit);
                        }

                        // get channel items
                        ContentChannelItemService contentService = new ContentChannelItemService(rockContext);

                        var content = contentService.Queryable("ContentChannelType")
                                      .Where(c =>
                                             c.ContentChannelId == channel.Id &&
                                             (c.Status == ContentChannelItemStatus.Approved || c.ContentChannel.RequiresApproval == false) &&
                                             c.StartDateTime <= RockDateTime.Now);

                        if (channel.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange)
                        {
                            if (channel.ContentChannelType.IncludeTime)
                            {
                                content = content.Where(c => c.ExpireDateTime >= RockDateTime.Now);
                            }
                            else
                            {
                                content = content.Where(c => c.ExpireDateTime > RockDateTime.Today);
                            }
                        }

                        if (channel.ItemsManuallyOrdered)
                        {
                            content = content.OrderBy(c => c.Order);
                        }
                        else
                        {
                            content = content.OrderByDescending(c => c.StartDateTime);
                        }

                        content = content.Take(rssItemLimit);

                        foreach (var item in content)
                        {
                            item.Content = item.Content.ResolveMergeFields(mergeFields);

                            // resolve any relative links
                            var    globalAttributes = Rock.Web.Cache.GlobalAttributesCache.Read();
                            string publicAppRoot    = globalAttributes.GetValue("PublicApplicationRoot").EnsureTrailingForwardslash();
                            item.Content = item.Content.Replace(@" src=""/", @" src=""" + publicAppRoot);
                            item.Content = item.Content.Replace(@" href=""/", @" href=""" + publicAppRoot);

                            // get item attributes and add them as elements to the feed
                            item.LoadAttributes(rockContext);
                            foreach (var attributeValue in item.AttributeValues)
                            {
                                attributeValue.Value.Value = attributeValue.Value.Value.ResolveMergeFields(mergeFields);
                            }
                        }

                        mergeFields.Add("Items", content);

                        mergeFields.Add("RockVersion", Rock.VersionInfo.VersionInfo.GetRockProductVersionNumber());

                        // show debug info
                        if (request.QueryString["EnableDebug"] != null)
                        {
                            response.Write(mergeFields.lavaDebugInfo());
                            response.Write("<pre>");
                            response.Write(WebUtility.HtmlEncode(rssTemplate.ResolveMergeFields(mergeFields)));
                            response.Write("</pre>");
                            response.Write("</body>");
                            response.Write("</html");
                        }
                        else
                        {
                            response.Write(rssTemplate.ResolveMergeFields(mergeFields));
                        }
                    }
                    else
                    {
                        response.Write("RSS is not enabled for this channel.");
                        response.StatusCode = 200;
                        return;
                    }
                }
                else
                {
                    response.StatusCode = 200;
                    response.Write("Invalid channel id.");
                    response.StatusCode = 200;
                    return;
                }
            }
            else
            {
                response.Write("A ChannelId is required.");
                response.StatusCode = 200;
                return;
            }
        }
        /// <summary>
        /// Handles the Click event of the lbSave 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 lbSave_Click(object sender, EventArgs e)
        {
            var rockContext = new RockContext();

            rockContext.WrapTransaction(() =>
            {
                if (contextEntity is Person)
                {
                    var personService = new PersonService(rockContext);
                    var changes       = new History.HistoryChangeList();
                    var _person       = personService.Get(contextEntity.Id);

                    History.EvaluateChange(changes, "Foreign Key", _person.ForeignKey, tbForeignKey.Text);
                    _person.ForeignKey = tbForeignKey.Text;

                    History.EvaluateChange(changes, "Foreign Guid", _person.ForeignGuid.ToString(), tbForeignGuid.Text);
                    _person.ForeignGuid = tbForeignGuid.Text.AsType <Guid?>();

                    History.EvaluateChange(changes, "Foreign Id", _person.ForeignId.ToString(), tbForeignId.Text);
                    _person.ForeignId = tbForeignId.Text.AsType <int?>();

                    if (rockContext.SaveChanges() > 0)
                    {
                        if (changes.Any())
                        {
                            HistoryService.SaveChanges(
                                rockContext,
                                typeof(Person),
                                Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(),
                                _person.Id,
                                changes);
                        }
                    }
                }
                else if (contextEntity is FinancialAccount)
                {
                    var accountService = new FinancialAccountService(rockContext);
                    var _account       = accountService.Get(contextEntity.Id);

                    _account.ForeignKey  = tbForeignKey.Text;
                    _account.ForeignGuid = tbForeignGuid.Text.AsType <Guid?>();
                    _account.ForeignId   = tbForeignId.Text.AsType <int?>();

                    rockContext.SaveChanges();
                }
                else if (contextEntity is FinancialBatch)
                {
                    var batchService = new FinancialBatchService(rockContext);
                    var changes      = new History.HistoryChangeList();
                    var _batch       = batchService.Get(contextEntity.Id);

                    History.EvaluateChange(changes, "Foreign Key", _batch.ForeignKey, tbForeignKey.Text);
                    _batch.ForeignKey = tbForeignKey.Text;

                    History.EvaluateChange(changes, "Foreign Guid", _batch.ForeignGuid.ToString(), tbForeignGuid.Text);
                    _batch.ForeignGuid = tbForeignGuid.Text.AsType <Guid?>();

                    History.EvaluateChange(changes, "Foreign Id", _batch.ForeignId.ToString(), tbForeignId.Text);
                    _batch.ForeignId = tbForeignId.Text.AsType <int?>();

                    if (rockContext.SaveChanges() > 0)
                    {
                        if (changes.Any())
                        {
                            HistoryService.SaveChanges(
                                rockContext,
                                typeof(FinancialBatch),
                                Rock.SystemGuid.Category.HISTORY_FINANCIAL_BATCH.AsGuid(),
                                _batch.Id,
                                changes);
                        }
                    }
                }
                else if (contextEntity is FinancialPledge)
                {
                    var pledgeService = new FinancialPledgeService(rockContext);
                    var _pledge       = pledgeService.Get(contextEntity.Id);

                    _pledge.ForeignKey  = tbForeignKey.Text;
                    _pledge.ForeignGuid = tbForeignGuid.Text.AsType <Guid?>();
                    _pledge.ForeignId   = tbForeignId.Text.AsType <int?>();

                    rockContext.SaveChanges();
                }
                else if (contextEntity is FinancialTransaction)
                {
                    var transactionService = new FinancialTransactionService(rockContext);
                    var changes            = new History.HistoryChangeList();
                    var _transaction       = transactionService.Get(contextEntity.Id);

                    History.EvaluateChange(changes, "Foreign Key", _transaction.ForeignKey, tbForeignKey.Text);
                    _transaction.ForeignKey = tbForeignKey.Text;

                    History.EvaluateChange(changes, "Foreign Guid", _transaction.ForeignGuid.ToString(), tbForeignGuid.Text);
                    _transaction.ForeignGuid = tbForeignGuid.Text.AsType <Guid?>();

                    History.EvaluateChange(changes, "Foreign Id", _transaction.ForeignId.ToString(), tbForeignId.Text);
                    _transaction.ForeignId = tbForeignId.Text.AsType <int?>();

                    if (rockContext.SaveChanges() > 0)
                    {
                        if (changes.Any())
                        {
                            HistoryService.SaveChanges(
                                rockContext,
                                typeof(FinancialTransaction),
                                Rock.SystemGuid.Category.HISTORY_FINANCIAL_TRANSACTION.AsGuid(),
                                _transaction.Id,
                                changes);
                        }
                    }
                }
                else if (contextEntity is FinancialScheduledTransaction)
                {
                    var transactionScheduledService = new FinancialScheduledTransactionService(rockContext);
                    var _scheduledTransaction       = transactionScheduledService.Get(contextEntity.Id);

                    _scheduledTransaction.ForeignKey  = tbForeignKey.Text;
                    _scheduledTransaction.ForeignGuid = tbForeignGuid.Text.AsType <Guid?>();
                    _scheduledTransaction.ForeignId   = tbForeignId.Text.AsType <int?>();

                    rockContext.SaveChanges();
                }
                else if (contextEntity is Group)
                {
                    var groupService = new GroupService(rockContext);
                    var _group       = groupService.Get(contextEntity.Id);

                    _group.ForeignKey  = tbForeignKey.Text;
                    _group.ForeignGuid = tbForeignGuid.Text.AsType <Guid?>();
                    _group.ForeignId   = tbForeignId.Text.AsType <int?>();

                    rockContext.SaveChanges();
                }
                else if (contextEntity is GroupMember)
                {
                    var groupMemberService = new GroupMemberService(rockContext);
                    var changes            = new History.HistoryChangeList();
                    var _groupMember       = groupMemberService.Get(contextEntity.Id);

                    History.EvaluateChange(changes, "Foreign Key", _groupMember.ForeignKey, tbForeignKey.Text);
                    _groupMember.ForeignKey = tbForeignKey.Text;

                    History.EvaluateChange(changes, "Foreign Guid", _groupMember.ForeignGuid.ToString(), tbForeignGuid.Text);
                    _groupMember.ForeignGuid = tbForeignGuid.Text.AsType <Guid?>();

                    History.EvaluateChange(changes, "Foreign Id", _groupMember.ForeignId.ToString(), tbForeignId.Text);
                    _groupMember.ForeignId = tbForeignId.Text.AsType <int?>();

                    if (rockContext.SaveChanges() > 0)
                    {
                        if (changes.Any())
                        {
                            HistoryService.SaveChanges(
                                rockContext,
                                typeof(GroupMember),
                                Rock.SystemGuid.Category.HISTORY_PERSON_GROUP_MEMBERSHIP.AsGuid(),
                                _groupMember.Id,
                                changes);
                        }
                    }
                }
                else if (contextEntity is Metric)
                {
                    var metricService = new MetricService(rockContext);
                    var _metric       = metricService.Get(contextEntity.Id);

                    _metric.ForeignKey  = tbForeignKey.Text;
                    _metric.ForeignGuid = tbForeignGuid.Text.AsType <Guid?>();
                    _metric.ForeignId   = tbForeignId.Text.AsType <int?>();

                    rockContext.SaveChanges();
                }
                else if (contextEntity is Location)
                {
                    var locationService = new LocationService(rockContext);
                    var _location       = locationService.Get(contextEntity.Id);

                    _location.ForeignKey  = tbForeignKey.Text;
                    _location.ForeignGuid = tbForeignGuid.Text.AsType <Guid?>();
                    _location.ForeignId   = tbForeignId.Text.AsType <int?>();

                    rockContext.SaveChanges();
                }
                else if (contextEntity is PrayerRequest)
                {
                    var prayerRequestService = new PrayerRequestService(rockContext);
                    var _request             = prayerRequestService.Get(contextEntity.Id);

                    _request.ForeignKey  = tbForeignKey.Text;
                    _request.ForeignGuid = tbForeignGuid.Text.AsType <Guid?>();
                    _request.ForeignId   = tbForeignId.Text.AsType <int?>();

                    rockContext.SaveChanges();
                }
                else if (contextEntity is ContentChannel)
                {
                    var contentChannelService = new ContentChannelService(rockContext);
                    var _channel = contentChannelService.Get(contextEntity.Id);

                    _channel.ForeignKey  = tbForeignKey.Text;
                    _channel.ForeignGuid = tbForeignGuid.Text.AsType <Guid?>();
                    _channel.ForeignId   = tbForeignId.Text.AsType <int?>();

                    rockContext.SaveChanges();
                }
                else if (contextEntity is ContentChannelItem)
                {
                    var contentChannelItemService = new ContentChannelItemService(rockContext);
                    var _item = contentChannelItemService.Get(contextEntity.Id);

                    _item.ForeignKey  = tbForeignKey.Text;
                    _item.ForeignGuid = tbForeignGuid.Text.AsType <Guid?>();
                    _item.ForeignId   = tbForeignId.Text.AsType <int?>();

                    rockContext.SaveChanges();
                }
            });

            Page.Response.Redirect(Page.Request.Url.ToString(), true);
        }
 /// <summary>
 /// Handles the Edit event of the gContentChannelItems control.
 /// </summary>
 /// <param name="sender">The source of the event.</param>
 /// <param name="e">The <see cref="RowEventArgs" /> instance containing the event data.</param>
 protected void gContentChannelItems_Edit( object sender, RowEventArgs e )
 {
     var contentItem = new ContentChannelItemService( new RockContext() ).Get( e.RowKeyId );
     if ( contentItem != null )
     {
         NavigateToLinkedPage( "DetailPage", "contentItemId", contentItem.Id );
     }
 }
        /// <summary>
        /// Handles the Delete event of the gItems control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RowEventArgs" /> instance containing the event data.</param>
        protected void gItems_Delete( object sender, RowEventArgs e )
        {
            var rockContext = new RockContext();
            var contentItemService = new ContentChannelItemService( rockContext );
            var contentItemAssociationService = new ContentChannelItemAssociationService( rockContext );

            ContentChannelItem contentItem = contentItemService.Get( e.RowKeyId );

            if ( contentItem != null )
            {
                string errorMessage;
                if ( !contentItemService.CanDelete( contentItem, out errorMessage ) )
                {
                    mdGridWarning.Show( errorMessage, ModalAlertType.Information );
                    return;
                }

                rockContext.WrapTransaction( () =>
                {
                    contentItemAssociationService.DeleteRange( contentItem.ChildItems );
                    contentItemAssociationService.DeleteRange( contentItem.ParentItems );
                    contentItemService.Delete( contentItem );
                    rockContext.SaveChanges();
                } );
            }

            BindGrid();
        }
        private void GetData()
        {
            var rockContext = new RockContext();
            var itemService = new ContentChannelItemService(rockContext);

            int personId = CurrentPerson != null ? CurrentPerson.Id : 0;

            // Get all of the content channels
            var allChannels = new ContentChannelService( rockContext ).Queryable( "ContentChannelType" )
                .OrderBy( w => w.Name )
                .ToList();

            // Create variable for storing authorized channels and the count of active items
            var channelCounts = new Dictionary<int, int>();
            foreach ( var channel in allChannels )
            {
                if ( channel.IsAuthorized( Authorization.VIEW, CurrentPerson))
                {
                    channelCounts.Add( channel.Id, 0);
                }
            }

            // Get the pending item counts for each channel
            itemService.Queryable()
                .Where( i =>
                    channelCounts.Keys.Contains( i.ContentChannelId ) &&
                    i.Status == ContentChannelItemStatus.PendingApproval )
                .GroupBy( i => i.ContentChannelId )
                .Select( i => new {
                    Id = i.Key,
                    Count = i.Count()
                })
                .ToList()
                .ForEach( i => channelCounts[i.Id] = i.Count );

            // Create a query to return channel, the count of items, and the selected class
            var qry = allChannels
                .Where( c => channelCounts.Keys.Contains( c.Id ) )
                .Select( c => new
                {
                    Channel = c,
                    Count = channelCounts[c.Id],
                    Class = ( SelectedChannelId.HasValue && SelectedChannelId.Value == c.Id ) ? "active" : ""
                } );

            // If displaying active only, update query to exclude those content channels without any items
            if ( StatusFilter.HasValue && StatusFilter.Value )
            {
                qry = qry.Where( c => c.Count > 0 );
            }

            var contentChannels = qry.ToList();

            rptChannels.DataSource = contentChannels;
            rptChannels.DataBind();

            ContentChannel selectedChannel = null;
            if ( SelectedChannelId.HasValue )
            {
                selectedChannel = allChannels
                    .Where( w =>
                        w.Id == SelectedChannelId.Value &&
                        channelCounts.Keys.Contains( SelectedChannelId.Value ) )
                    .FirstOrDefault();
            }

            if ( selectedChannel != null && contentChannels.Count > 0 )
            {
                // show the content item panel
                divItemPanel.Visible = true;

                AddColumns( selectedChannel );

                var itemQry = itemService.Queryable()
                    .Where( i => i.ContentChannelId == selectedChannel.Id );

                var drp = new DateRangePicker();
                drp.DelimitedValues = gfFilter.GetUserPreference( "Date Range" );
                if ( drp.LowerValue.HasValue )
                {
                    if ( selectedChannel.ContentChannelType.DateRangeType == ContentChannelDateType.SingleDate )
                    {
                        itemQry = itemQry.Where( i => i.StartDateTime >= drp.LowerValue.Value );
                    }
                    else
                    {
                        itemQry = itemQry.Where( i => i.ExpireDateTime.HasValue && i.ExpireDateTime.Value >= drp.LowerValue.Value );
                    }
                }
                if ( drp.UpperValue.HasValue )
                {
                    DateTime upperDate = drp.UpperValue.Value.Date.AddDays( 1 );
                    itemQry = itemQry.Where( i => i.StartDateTime < upperDate );
                }

                var status = gfFilter.GetUserPreference( "Status" ).ConvertToEnumOrNull<ContentChannelItemStatus>();
                if ( status.HasValue )
                {
                    itemQry = itemQry.Where( i => i.Status == status );
                }

                string title = gfFilter.GetUserPreference( "Title" );
                if (!string.IsNullOrWhiteSpace(title))
                {
                    itemQry = itemQry.Where( i => i.Title.Contains( title ) );
                }

                var items = new List<ContentChannelItem>();
                foreach ( var item in itemQry.ToList() )
                {
                    if ( item.IsAuthorized( Rock.Security.Authorization.VIEW, CurrentPerson ) )
                    {
                        items.Add( item );
                    }
                }

                SortProperty sortProperty = gContentChannelItems.SortProperty;
                if ( sortProperty != null )
                {
                    items = items.AsQueryable().Sort( sortProperty ).ToList();
                }
                else
                {
                    items = items.OrderByDescending( p => p.StartDateTime ).ToList();
                }

                gContentChannelItems.ObjectList = new Dictionary<string, object>();
                items.ForEach( i => gContentChannelItems.ObjectList.Add( i.Id.ToString(), i ) );

                gContentChannelItems.DataSource = items.Select( i => new
                {
                    i.Id,
                    i.Guid,
                    i.Title,
                    i.StartDateTime,
                    i.ExpireDateTime,
                    i.Priority,
                    Status = DisplayStatus( i.Status )
                } ).ToList();
                gContentChannelItems.DataBind();

                lContentChannelItems.Text = selectedChannel.Name + " Items";
            }
            else
            {
                divItemPanel.Visible = false;
            }
        }
        protected string UpcomingDiscover(Campus theCampus, string theTitle)
        {
            string upcomingDiscovers = "";

            ContentChannelItemService contentChannelItemService = new ContentChannelItemService(rockContext);

            List<ContentChannelItem> contentChannelItemsList = new List<ContentChannelItem>();

            var upcoming =
                contentChannelItemService.Queryable().Where(a => a.ContentChannelId == 14 && a.Title.Contains(theTitle) && a.StartDateTime >= DateTime.Now);

            foreach (var x in upcoming)
            {
                x.LoadAttributes();

                var campus = x.AttributeValues["Campus"];

                if (campus.ValueFormatted == theCampus.Name)
                    {
                    contentChannelItemsList.Add(x);
                    }

            }

            foreach (var x in contentChannelItemsList)
            {
                x.LoadAttributes();

                string registrationLink = "";

                if (x.AttributeValues["RegistrationLink"].ValueFormatted != "")
                {
                    registrationLink = String.Format("<a href= \"{0}\">Register Now!</a>",
                        x.AttributeValues["RegistrationLink"].Value);
                }

                upcomingDiscovers += String.Format("Date: {0} at {1}. Location: {2}. {3} <br>", x.StartDateTime.ToShortDateString(),
                    x.StartDateTime.ToShortTimeString(), x.AttributeValues["Location"], registrationLink);
            }

            if (!contentChannelItemsList.Any())
            {
                upcomingDiscovers = String.Format("There are not upcoming {0} Opportinuties at the {1}.", theTitle,
                    theCampus.Name);
            }

            return upcomingDiscovers;
        }