/// <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", LinkedPageUrl("DetailPage", null));
            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();
            }
        }
        /// <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);
        }
Example #3
0
        /// <summary>
        /// Handles the Click event of the 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 lbtnLinkExisting_Click(object sender, EventArgs e)
        {
            LinkButton lb = ( LinkButton )sender;
            int        contentChannelId = lb.CommandArgument.AsInteger();

            //
            // Build a list of the existing Content Channel Items that are
            // not expired yet and not currently linked to this even occurrence.
            //
            ddlLinkExistingItems.Items.Clear();
            ddlLinkExistingItems.Items.Add(new ListItem());
            using (var rockContext = new RockContext())
            {
                var      contentChannelItemService = new ContentChannelItemService(rockContext);
                DateTime now = RockDateTime.Now;

                var items = contentChannelItemService.Queryable()
                            .Where(i => i.ContentChannelId == contentChannelId)
                            .Where(i => !i.ExpireDateTime.HasValue || i.ExpireDateTime.Value >= now)
                            .Where(i => !i.EventItemOccurrences.Any(o => o.EventItemOccurrenceId == OccurrenceId))
                            .OrderBy(i => i.Title);

                //
                // Add each item to the list and format the name to be the
                // title and, conditionally, the start and end date/times.
                //
                foreach (var item in items)
                {
                    bool   includeTime   = item.ContentChannelType.IncludeTime;
                    string title         = item.Title;
                    string startDateText = null;
                    string endDateText   = null;

                    if (item.ContentChannelType.DateRangeType == ContentChannelDateType.SingleDate)
                    {
                        startDateText = item.StartDateTime.ToShortDateString();
                    }
                    else if (item.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange)
                    {
                        startDateText = item.StartDateTime.ToShortDateString();
                        endDateText   = item.ExpireDateTime.HasValue ? item.ExpireDateTime.Value.ToShortDateString() : null;
                    }

                    if (endDateText != null)
                    {
                        title += string.Format(" ({0} - {1})", startDateText, endDateText);
                    }
                    else if (startDateText != null)
                    {
                        title += string.Format(" ({0})", startDateText);
                    }

                    ddlLinkExistingItems.Items.Add(new ListItem(title, item.Id.ToString()));
                }
            }

            mdlLinkExisting.Show();
        }
        /// <summary>
        /// Gets the content channel items from the Cache or from Database if not cached
        /// </summary>
        /// <param name="itemCacheKey">The item cache key.</param>
        /// <param name="itemCacheDuration">Duration of the item cache.</param>
        /// <returns></returns>
        public List <ContentChannelItem> GetContentChannelItems(string itemCacheKey, int?itemCacheDuration)
        {
            List <ContentChannelItem> contentChannelItems = null;

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

            ContentChannelCache contentChannel = GetContentChannel();

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

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

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

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

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

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

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

            contentChannelItems = contentChannelItemsQuery.ToList();

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

            return(contentChannelItems);
        }
        /// <summary>
        /// Handles the GridReorder 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.GridReorderEventArgs"/> instance containing the event data.</param>
        protected void gContentChannelItems_GridReorder(object sender, Rock.Web.UI.Controls.GridReorderEventArgs e)
        {
            var contentChannel = this.GetContentChannel();

            if (contentChannel != null)
            {
                var rockContext = new RockContext();
                ContentChannelItemService contentChannelItemService = new ContentChannelItemService(rockContext);
                var contentChannelItems = contentChannelItemService.Queryable().Where(a => a.ContentChannelId == contentChannel.Id).OrderBy(a => a.Order).ThenBy(a => a.Title).ToList();
                contentChannelItemService.Reorder(contentChannelItems, e.OldIndex, e.NewIndex);
                rockContext.SaveChanges();
                BindContentChannelItemsGrid();
            }
        }
Example #6
0
        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);
        }
Example #7
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);
        }
        /// <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 #9
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();
        }
        public IHttpActionResult ChannelItems(int contentChannelId, string tag = "", int take = 20, int page = 0, bool hideInactive = false,
                                              string orderby = "StartDateTime", bool reverse  = false)
        {
            var cacheKey = Request.RequestUri.ToString();

            RockContext rockContext = new RockContext();
            ContentChannelItemService contentChannelItemService = new ContentChannelItemService(rockContext);
            ContentChannelService     contentChannelService     = new ContentChannelService(rockContext);
            var contentChannel = contentChannelService.Get(contentChannelId);

            if (!contentChannel.IsAuthorized(Rock.Security.Authorization.VIEW, GetPerson()))
            {
                throw new HttpResponseException(HttpStatusCode.Unauthorized);
            }

            var contentItems = contentChannelItemService.Queryable().Where(c => c.ContentChannelId == contentChannelId);

            if (hideInactive)
            {
                contentItems = contentItems.Where(i => i.Status == ContentChannelItemStatus.Approved);
            }

            if (tag.IsNotNullOrWhiteSpace())
            {
                TagService tagService      = new TagService(rockContext);
                var        taggedItemGuids = tagService.Queryable().Where(i => i.EntityTypeId == contentChanelItemEntityTypeId && i.Name == tag)
                                             .SelectMany(t => t.TaggedItems).Select(ti => ti.EntityGuid);
                contentItems = contentItems.Where(c => taggedItemGuids.Contains(c.Guid));
            }

            if (reverse)
            {
                contentItems = contentItems.OrderByDescending(orderby);
            }
            else
            {
                contentItems = contentItems.OrderBy(orderby);
            }

            var contentChannelTypeId  = contentChannel.ContentChannelTypeId.ToString();
            var contentChanelIdString = contentChannel.Id.ToString();

            var attributeQry = new AttributeService(rockContext).Queryable()
                               .Where(a => a.EntityTypeId == contentChanelItemEntityTypeId &&
                                      ((a.EntityTypeQualifierColumn == "ContentChannelTypeId" && a.EntityTypeQualifierValue == contentChannelTypeId) ||
                                       (a.EntityTypeQualifierColumn == "ContentChannelId" && a.EntityTypeQualifierValue == contentChanelIdString)))
            ;

            var attributeValueQry = new AttributeValueService(rockContext).Queryable()
                                    .Where(av => attributeQry.Select(a => a.Id).Contains(av.AttributeId));

            //AttributeFiltering
            var ignoreKeys = new List <string> {
                "contentchannelid", "tag", "take", "page", "hideInactive", "orderby", "reverse"
            };

            var urlKeyValues = ControllerContext.Request.GetQueryNameValuePairs();

            foreach (var pair in urlKeyValues)
            {
                if (!ignoreKeys.Contains(pair.Key.ToLower()))
                {
                    var filterQry = new AttributeValueService(rockContext).Queryable()
                                    .Where(av => attributeQry.Where(a => a.Key == pair.Key).Select(a => a.Id).Contains(av.AttributeId))
                                    .Where(av => av.Value == pair.Value);

                    contentItems = contentItems.Where(i => filterQry.Select(av => av.EntityId).Contains(i.Id));
                }
            }

            //Pagination
            if (page > 0)
            {
                var skip = (page - 1) * take;
                contentItems = contentItems.Skip(skip);
                contentItems = contentItems.Take(take);
            }

            //Join attributes and other content channel items
            var complex = contentItems
                          .GroupJoin(attributeValueQry,
                                     i => i.Id,
                                     av => av.EntityId,
                                     (i, av) => new
            {
                ContentChanelItem = i,
                Children          = i.ChildItems.OrderBy(ci => ci.Order).Select(ci => ci.ChildContentChannelItemId),
                ParentItems       = i.ParentItems.Select(ci => ci.ContentChannelItemId),
                AttributeValues   = av
            });

            var items = complex.ToList()
                        .Select(i => new ChannelItem
            {
                Id          = i.ContentChanelItem.Id,
                DateTime    = i.ContentChanelItem.StartDateTime,
                Title       = i.ContentChanelItem.Title,
                Content     = i.ContentChanelItem.Content,
                Priority    = i.ContentChanelItem.Priority,
                Order       = i.ContentChanelItem.Order,
                Attributes  = i.AttributeValues.ToDictionary(a => a.AttributeKey, a => a.Value),
                Tags        = GetTags(i.ContentChanelItem, rockContext),
                Slug        = i.ContentChanelItem.PrimarySlug,
                CreatedBy   = i.ContentChanelItem.CreatedByPersonName,
                ChildItems  = i.Children.ToList(),
                ParentItems = i.ParentItems.ToList()
            }).ToList();

            return(Json(items));
        }
Example #11
0
        public IHttpActionResult GetSpeakerSeries(string slug = "", string speaker = "", int offset = 0)
        {
            var cacheKey = string.Format("api/sermonfeed/{0}/{1}/{2}", slug, speaker, offset);
            var output   = RockCache.Get(cacheKey) as List <SermonSeries>;

            if (output != null)
            {
                return(Json(output));
            }


            string      imageLocation = GlobalAttributesCache.Get().GetValue("PublicApplicationRoot").EnsureTrailingForwardslash() + "GetImage.ashx?Guid=";
            string      audioLocation = GlobalAttributesCache.Get().GetValue("PublicApplicationRoot").EnsureTrailingForwardslash() + "GetFile.ashx?Guid=";
            RockContext rockContext   = new RockContext();

            var speakerQry = new AttributeValueService(rockContext).Queryable().Where(av => av.AttributeId == SPEAKER_ATTRIBUTE && av.Value == speaker);
            ContentChannelItemService contentChannelItemService = new ContentChannelItemService(rockContext);
            var sermonSeriesQry = contentChannelItemService.Queryable()
                                  .Where(i => i.ContentChannelId == CONTENT_CHANNEL);

            if (!string.IsNullOrWhiteSpace(slug))
            {
                sermonSeriesQry = sermonSeriesQry.Where(i => i.ContentChannelItemSlugs.Where(s => s.ContentChannelItemId == i.Id && s.Slug == slug).Any());
            }
            var sermonSeriesList = sermonSeriesQry.SelectMany(i => i.ChildItems)
                                   .Select(i => i.ChildContentChannelItem)
                                   .Join(
                speakerQry,
                i => i.Id,
                a => a.EntityId,
                (i, a) => i
                )
                                   .Select(i => i.ParentItems.FirstOrDefault().ContentChannelItem)
                                   .DistinctBy(i => i.Id)
                                   .OrderByDescending(i => i.StartDateTime)
                                   .Skip(offset)
                                   .Take(12)
                                   .ToList();

            output = new List <SermonSeries>();

            foreach (var seriesItem in sermonSeriesList)
            {
                seriesItem.LoadAttributes();
                var sermonSeries = new SermonSeries
                {
                    id           = seriesItem.Id,
                    title        = seriesItem.Title,
                    description  = seriesItem.Content,
                    slug         = seriesItem.PrimarySlug,
                    image        = imageLocation + seriesItem.GetAttributeValue("Image"),
                    image_url    = imageLocation + seriesItem.GetAttributeValue("Image"),
                    last_updated = ConvertTime(seriesItem.StartDateTime),
                    sermons      = new List <Sermon>()
                };
                if (string.IsNullOrWhiteSpace(seriesItem.GetAttributeValue("Image")))
                {
                    var childItem = seriesItem.ChildItems.FirstOrDefault().ChildContentChannelItem;
                    childItem.LoadAttributes();
                    sermonSeries.image_url = imageLocation + childItem.GetAttributeValue("Image");
                    sermonSeries.image     = imageLocation + childItem.GetAttributeValue("Image");
                }

                output.Add(sermonSeries);

                //add sermons to series
                foreach (var sermonItem in seriesItem.ChildItems.Select(s => s.ChildContentChannelItem))
                {
                    sermonItem.LoadAttributes();
                    if (sermonItem.GetAttributeValue("Speaker").ToLower() != speaker.ToLower())
                    {
                        continue;
                    }

                    sermonSeries.sermons.Add(
                        new Sermon
                    {
                        id          = sermonItem.Id,
                        title       = sermonItem.Title,
                        description = sermonItem.Content,
                        slug        = sermonItem.PrimarySlug,
                        audio_link  = audioLocation + sermonItem.GetAttributeValue("Audio"),
                        date        = ConvertTime(sermonItem.StartDateTime),
                        duration    = sermonItem.GetAttributeValue("Duration").AsInteger(),
                        image       = imageLocation + sermonItem.GetAttributeValue("Image"),
                        image_url   = imageLocation + sermonItem.GetAttributeValue("Image"),
                        speaker     = sermonItem.GetAttributeValue("Speaker"),
                        vimeo_id    = sermonItem.GetAttributeValue("VimeoId").AsInteger()
                    });
                }
            }
            RockCache.AddOrUpdate(cacheKey, null, output, RockDateTime.Now.AddHours(1));

            return(Json(output));
        }
        /// <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();
            }
        }
        /// <summary>
        /// Executes the specified workflow, setting the startDateTime to now (if none was given) and leaving
        /// the expireDateTime as null (if none was given).
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();
            var mergeFields = GetMergeFields(action);

            // Get the content channel
            Guid           contentChannelGuid = GetAttributeValue(action, "ContentChannel").AsGuid();
            ContentChannel contentChannel     = new ContentChannelService(rockContext).Get(contentChannelGuid);

            if (contentChannel == null)
            {
                errorMessages.Add("Invalid Content Channel attribute or value!");
                return(false);
            }

            // Get the Content
            string contentValue = GetAttributeValue(action, "Content", true);
            string content      = string.Empty;
            Guid?  contentGuid  = contentValue.AsGuidOrNull();

            if (contentGuid.HasValue)
            {
                var attribute = AttributeCache.Get(contentGuid.Value, rockContext);
                if (attribute != null)
                {
                    string contentAttributeValue = action.GetWorkflowAttributeValue(contentGuid.Value);
                    if (!string.IsNullOrWhiteSpace(contentAttributeValue))
                    {
                        if (attribute.FieldType.Class == "Rock.Field.Types.TextFieldType" ||
                            attribute.FieldType.Class == "Rock.Field.Types.MemoFieldType")
                        {
                            content = contentAttributeValue;
                        }
                    }
                }
            }
            else
            {
                content = contentValue;
            }

            // Get the Content Creator
            int? personAliasId       = null;
            Guid?personAttributeGuid = GetAttributeValue(action, "CreatedBy").AsGuidOrNull();

            if (personAttributeGuid.HasValue)
            {
                Guid?personAliasGuid = action.GetWorkflowAttributeValue(personAttributeGuid.Value).AsGuidOrNull();
                if (personAliasGuid.HasValue)
                {
                    var personAlias = new PersonAliasService(rockContext).Get(personAliasGuid.Value);
                    if (personAlias != null)
                    {
                        personAliasId = personAlias.Id;
                    }
                }
            }

            // Get the Start Date Time (check if the attribute value is a guid first)
            DateTime startDateTime              = RockDateTime.Now;
            string   startAttributeValue        = GetAttributeValue(action, "StartDateTime");
            Guid     startDateTimeAttributeGuid = startAttributeValue.AsGuid();

            if (!startDateTimeAttributeGuid.IsEmpty())
            {
                var attribute = AttributeCache.Get(startDateTimeAttributeGuid, rockContext);
                if (attribute != null)
                {
                    string attributeValue = action.GetWorkflowAttributeValue(startDateTimeAttributeGuid);
                    if (!string.IsNullOrWhiteSpace(attributeValue))
                    {
                        if (attribute.FieldType.Class == "Rock.Field.Types.TextFieldType" ||
                            attribute.FieldType.Class == "Rock.Field.Types.DateTimeFieldType")
                        {
                            if (!DateTime.TryParse(attributeValue, out startDateTime))
                            {
                                startDateTime = RockDateTime.Now;
                                errorMessages.Add(string.Format("Could not parse the start date provided {0}.", attributeValue));
                            }
                        }
                    }
                }
            }
            // otherwise check just the plain value and then perform lava merge on it.
            else if (!string.IsNullOrWhiteSpace(startAttributeValue))
            {
                string mergedStartAttributeValue = startAttributeValue.ResolveMergeFields(mergeFields);
                if (!DateTime.TryParse(mergedStartAttributeValue, out startDateTime))
                {
                    startDateTime = RockDateTime.Now;
                    errorMessages.Add(string.Format("Could not parse the start date provided {0}.", startAttributeValue));
                }
            }

            // Get the Expire Date Time (check if the attribute value is a guid first)
            DateTime?expireDateTime              = null;
            string   expireAttributeValue        = GetAttributeValue(action, "ExpireDateTime");
            Guid     expireDateTimeAttributeGuid = expireAttributeValue.AsGuid();

            if (!expireDateTimeAttributeGuid.IsEmpty())
            {
                var attribute = AttributeCache.Get(expireDateTimeAttributeGuid, rockContext);
                if (attribute != null)
                {
                    DateTime aDateTime;
                    string   attributeValue = action.GetWorkflowAttributeValue(expireDateTimeAttributeGuid);
                    if (!string.IsNullOrWhiteSpace(attributeValue))
                    {
                        if (attribute.FieldType.Class == "Rock.Field.Types.TextFieldType" ||
                            attribute.FieldType.Class == "Rock.Field.Types.DateTimeFieldType")
                        {
                            if (DateTime.TryParse(attributeValue, out aDateTime))
                            {
                                expireDateTime = aDateTime;
                            }
                            else
                            {
                                errorMessages.Add(string.Format("Could not parse the expire date provided {0}.", attributeValue));
                            }
                        }
                    }
                }
            }
            // otherwise check just the text value and then perform lava merge on it.
            else if (!string.IsNullOrWhiteSpace(expireAttributeValue))
            {
                string   mergedExpireAttributeValue = expireAttributeValue.ResolveMergeFields(mergeFields);
                DateTime aDateTime;
                if (DateTime.TryParse(mergedExpireAttributeValue, out aDateTime))
                {
                    expireDateTime = aDateTime;
                }
                else
                {
                    errorMessages.Add(string.Format("Could not parse the expire date provided {0}.", expireAttributeValue));
                }
            }

            // Get the Content Channel Item Status
            var channelItemStatus = this.GetAttributeValue(action, "Status").ConvertToEnum <ContentChannelItemStatus>(ContentChannelItemStatus.PendingApproval);

            // Get the Foreign Id to lookup an existing ContentChannelItem
            int? foreignId      = null;
            Guid?foreignIdValue = GetAttributeValue(action, "EntityId").AsGuidOrNull();

            if (foreignIdValue.HasValue)
            {
                var attribute = AttributeCache.Get((Guid)foreignIdValue, rockContext);
                if (attribute != null)
                {
                    string attributeValue = action.GetWorkflowAttributeValue((Guid)foreignIdValue);
                    if (!string.IsNullOrWhiteSpace(attributeValue))
                    {
                        if (attribute.FieldType.Class == "Rock.Field.Types.IntegerFieldType")
                        {
                            foreignId = attributeValue.AsIntegerOrNull();
                            if (!foreignId.HasValue)
                            {
                                errorMessages.Add(string.Format("Could not parse the foreign id provided {0}.", attributeValue));
                            }
                        }
                    }
                }
            }

            // Add or update the content channel item
            var itemTitle   = GetAttributeValue(action, "Title").ResolveMergeFields(mergeFields);
            var itemService = new ContentChannelItemService(rockContext);

            // Check by ForeignId or by Channel Type + Title
            var contentChannelItem = itemService.Queryable().FirstOrDefault(i => i.ForeignId == foreignId ||
                                                                            (!foreignId.HasValue &&
                                                                             i.ContentChannelId == contentChannel.Id &&
                                                                             i.ContentChannelTypeId == contentChannel.ContentChannelTypeId &&
                                                                             i.Title.Equals(itemTitle)
                                                                            )
                                                                            );

            if (contentChannelItem == null)
            {
                contentChannelItem = new ContentChannelItem
                {
                    ContentChannelId     = contentChannel.Id,
                    ContentChannelTypeId = contentChannel.ContentChannelTypeId,
                };
                itemService.Add(contentChannelItem);
            }

            contentChannelItem.Title                  = itemTitle;
            contentChannelItem.Content                = content.ResolveMergeFields(mergeFields);
            contentChannelItem.StartDateTime          = startDateTime;
            contentChannelItem.ExpireDateTime         = expireDateTime;
            contentChannelItem.Status                 = channelItemStatus;
            contentChannelItem.CreatedByPersonAliasId = personAliasId;
            contentChannelItem.ForeignId              = foreignId;
            rockContext.SaveChanges();

            Dictionary <string, string> sourceKeyMap = null;
            var itemAttributeKeys = GetAttributeValue(action, "ItemAttributeKey");

            if (!string.IsNullOrWhiteSpace(itemAttributeKeys))
            {
                // TODO Find a way upstream to stop an additional being appended to the value
                sourceKeyMap = itemAttributeKeys.AsDictionaryOrNull();
            }

            sourceKeyMap = sourceKeyMap ?? new Dictionary <string, string>();

            // Load the content channel item attributes if we're going to add some values
            if (sourceKeyMap.Count > 0)
            {
                contentChannelItem.LoadAttributes(rockContext);

                foreach (var keyPair in sourceKeyMap)
                {
                    // Does the source key exist as an attribute in the this workflow?
                    if (action.Activity.Workflow.Attributes.ContainsKey(keyPair.Key))
                    {
                        if (contentChannelItem.Attributes.ContainsKey(keyPair.Value))
                        {
                            var value = action.Activity.Workflow.AttributeValues[keyPair.Key].Value;
                            contentChannelItem.SetAttributeValue(keyPair.Value, value);
                        }
                        else
                        {
                            errorMessages.Add(string.Format("'{0}' is not an attribute key in the content channel: '{1}'", keyPair.Value, contentChannel.Name));
                        }
                    }
                    else
                    {
                        errorMessages.Add(string.Format("'{0}' is not an attribute key in this workflow: '{1}'", keyPair.Key, action.Activity.Workflow.Name));
                    }
                }

                contentChannelItem.SaveAttributeValues(rockContext);
            }

            return(true);
        }
Example #14
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;
            }
        }
        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;
            }
        }
        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;
        }
        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;
            }
        }
        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;
            }
        }
        /// <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;
        }
Example #20
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;

        }
        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;
            }
        }
Example #22
0
        public void Execute(IJobExecutionContext context)
        {
            int storyCount    = 0;
            int newStoryCount = 0;

            JobDataMap dataMap = context.JobDetail.JobDataMap;

            List <Story>              stories                   = new List <Story>();
            RockContext               rockContext               = new RockContext();
            ContentChannelService     contentChannelService     = new ContentChannelService(rockContext);
            ContentChannelItemService contentChannelItemService = new ContentChannelItemService(rockContext);
            BinaryFileService         binaryFileService         = new BinaryFileService(rockContext);
            BinaryFileType            binaryFileType            = new BinaryFileTypeService(rockContext).Get(Rock.SystemGuid.BinaryFiletype.MEDIA_FILE.AsGuid());
            var storiesSeriesChannel = contentChannelService.Get(dataMap.GetString("StoriesContentChannel").AsGuid());

            var dbCon = DBConnection.Instance();

            dbCon.DatabaseName = "secccp_main";
            if (dbCon.IsConnect())
            {
                stories = GetStories(dbCon);

                foreach (var story in stories)
                {
                    storyCount++;
                    var item = contentChannelItemService.Queryable().Where(i => i.ForeignId == story.id && i.ContentChannelId == storiesSeriesChannel.Id).FirstOrDefault();
                    if (item == null)
                    {
                        newStoryCount++;
                        item = new ContentChannelItem()
                        {
                            ContentChannelId     = storiesSeriesChannel.Id,
                            ForeignId            = story.id,
                            ContentChannelTypeId = storiesSeriesChannel.ContentChannelTypeId
                        };
                        contentChannelItemService.Add(item);
                    }
                    item.Title         = story.title;
                    item.Content       = story.description;
                    item.StartDateTime = Helpers.FromUnixTime(story.datecreated);
                    rockContext.SaveChanges();

                    item.LoadAttributes();
                    item.SetAttributeValue("Slug", story.slug);
                    item.SetAttributeValue("VimeoId", story.vimeo_id);
                    item.SetAttributeValue("VimeoStreamingUrl", story.vimeo_live_url);
                    item.SetAttributeValue("VimeoDownloadUrl", story.vimeo_sd_url);
                    item.SetAttributeValue("Tags", story.tags);
                    item.SetAttributeValue("Duration", story.duration);

                    if (string.IsNullOrWhiteSpace(item.GetAttributeValue("Image")))
                    {
                        WebClient client = new WebClient();
                        try
                        {
                            using (MemoryStream stream = new MemoryStream(client.DownloadData(string.Format("http://panel.secc.org/upload/stories/cover-images/story-{0}.jpg", story.id))))
                            {
                                BinaryFile binaryFile = new BinaryFile();
                                binaryFileService.Add(binaryFile);
                                binaryFile.IsTemporary      = false;
                                binaryFile.BinaryFileTypeId = binaryFileType.Id;
                                binaryFile.MimeType         = "image/jpg";
                                binaryFile.FileName         = string.Format("Story-{0}.jpg", story.id);
                                binaryFile.ContentStream    = stream;
                                rockContext.SaveChanges();
                                item.SetAttributeValue("Image", binaryFile.Guid.ToString());
                            }
                        }
                        catch (Exception ex)
                        {
                            var a = ex;
                        }
                    }

                    item.SaveAttributeValues();
                }
            }
            context.Result = string.Format("Synced {0} sermons ({1} New Sermon)", storyCount, newStoryCount);
        }
        public void ProcessRequest(HttpContext context)
        {
            request  = context.Request;
            response = context.Response;

            RockContext rockContext = new RockContext();

            if (request.HttpMethod != "GET" && request.HttpMethod != "HEAD")
            {
                response.TrySkipIisCustomErrors = true;
                response.StatusCode             = 405;
                response.Headers.Add("Allow", "GET");
                response.Write("Invalid request method.");
                return;
            }

            if (request.QueryString["ChannelId"] == null)
            {
                response.TrySkipIisCustomErrors = true;
                response.StatusCode             = 400;
                response.Write("A ChannelId is required.");
                return;
            }

            int?channelId = request.QueryString["ChannelId"].AsIntegerOrNull();

            if (channelId == null)
            {
                response.TrySkipIisCustomErrors = true;
                response.StatusCode             = 400;
                response.Write("Invalid channel id.");
                return;
            }

            ContentChannel channel = new ContentChannelService(rockContext).Queryable("ContentChannelType").FirstOrDefault(c => c.Id == channelId.Value);

            if (channel == null)
            {
                response.TrySkipIisCustomErrors = true;
                response.StatusCode             = 404;
                response.Write("Channel does not exist.");
                return;
            }

            if (!channel.EnableRss)
            {
                response.TrySkipIisCustomErrors = true;
                response.StatusCode             = 403;
                response.Write("RSS is not enabled for this channel.");
                return;
            }

            DefinedValueCache dvRssTemplate = null;

            if (request.QueryString["TemplateId"] != null)
            {
                int?templateDefinedValueId = request.QueryString["TemplateId"].AsIntegerOrNull();

                if (templateDefinedValueId == null)
                {
                    response.TrySkipIisCustomErrors = true;
                    response.StatusCode             = 400;
                    response.Write("Invalid template id.");
                    return;
                }

                dvRssTemplate = DefinedValueCache.Get(templateDefinedValueId.Value);
            }

            if (dvRssTemplate == null)
            {
                dvRssTemplate = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.DEFAULT_RSS_CHANNEL);
            }

            if (dvRssTemplate.DefinedType.Guid != new Guid(Rock.SystemGuid.DefinedType.LAVA_TEMPLATES))
            {
                response.TrySkipIisCustomErrors = true;
                response.StatusCode             = 400;
                response.Write("Invalid template id.");
                return;
            }

            string rssTemplate = dvRssTemplate.GetAttributeValue("Template");

            if (string.IsNullOrWhiteSpace(dvRssTemplate.GetAttributeValue("MimeType")))
            {
                response.ContentType = "application/rss+xml";
            }
            else
            {
                response.ContentType = dvRssTemplate.GetAttributeValue("MimeType");
            }

            if (request.HttpMethod == "HEAD")
            {
                response.StatusCode = 200;
                return;
            }

            // 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", WebRequestHelper.GetHostNameFromRequest(context));
            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.ContentChannelType.DisableStatus || c.ContentChannel.RequiresApproval == false) &&
                                 c.StartDateTime <= RockDateTime.Now);

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

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

            content = content.Take(rssItemLimit);

            content.LoadAttributes();

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

                // resolve any relative links
                var    globalAttributes = GlobalAttributesCache.Get();
                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
                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());

            response.Write(rssTemplate.ResolveMergeFields(mergeFields));
        }
Example #24
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> GetContent(List <string> errorMessages)
        {
            List <ContentChannelItem> items = null;

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


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

                    ParameterExpression paramExpression = service.ParameterExpression;

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

                        items = new List <ContentChannelItem>();

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

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

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

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

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

                        // Order the items
                        SortProperty sortProperty = null;

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

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

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

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

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

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

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

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

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

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

            return(items);
        }
        /// <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;
        }
        /// <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 #28
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
                    };

                    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 #29
0
        public object GetItems(int pageNumber = 0)
        {
            var contentChannelId = GetAttributeValue(AttributeKeys.ContentChannel).AsInteger();
            var pageSize         = GetAttributeValue(AttributeKeys.PageSize).AsInteger();
            var checkSecurity    = GetAttributeValue(AttributeKeys.CheckItemSecurity).AsBoolean();
            var skipNumber       = pageNumber * pageSize;

            var rockContext = new RockContext();
            var contentChannelItemService            = new ContentChannelItemService(rockContext);
            var contentChannelItemAssociationService = new ContentChannelItemAssociationService(rockContext);

            var qry = contentChannelItemService.Queryable().AsNoTracking().Where(i => i.ContentChannelId == contentChannelId);

            //
            // Determine if we should be loading child items from a parent
            //
            var showChildrenOfParent = GetAttributeValue(AttributeKeys.ShowChildrenOfParent).AsBoolean();
            var parentKeyPassed      = RequestContext.GetPageParameters().ContainsKey("ParentItemId");

            if (parentKeyPassed && showChildrenOfParent)
            {
                var parentItemId = RequestContext.GetPageParameters()["ParentItemId"].AsIntegerOrNull();

                if (parentItemId.HasValue)
                {
                    var assoctaionsQry = contentChannelItemAssociationService.Queryable().Where(a => a.ContentChannelItemId == parentItemId);

                    qry = qry.Where(i => assoctaionsQry.Any(a => a.ChildContentChannelItemId == i.Id));
                }
            }

            //
            // Apply custom filtering.
            //
            qry = FilterResults(rockContext, contentChannelItemService, qry);

            //
            // Apply custom sorting to the results.
            //
            qry = SortResults(qry);

            var results = new List <ContentChannelItem>();

            //
            // Determine if we need to check the security of the items. Is can be slow, especially for channels with LOTS of items.
            //
            if (checkSecurity)
            {
                // We have to take all items to check security to ensure we have enough to return the desired item count
                results = qry.ToList();
                foreach (var item in results)
                {
                    if (item.IsAuthorized(Authorization.VIEW, RequestContext.CurrentPerson))
                    {
                        results.Add(item);
                    }
                }

                // Take the final number of items requested.
                results = results.Skip(skipNumber)
                          .Take(pageSize)
                          .ToList();
            }
            else
            {
                // Just take the number requested
                results = qry.Skip(skipNumber)
                          .Take(pageSize)
                          .ToList();
            }

            // Load attributes
            foreach (var item in results)
            {
                item.LoadAttributes(rockContext);
            }

            var followedItemIds = GetFollowedItemIds(rockContext, results);

            var lavaTemplate = CreateLavaTemplate(followedItemIds);

            var commonMergeFields = new CommonMergeFieldsOptions
            {
                GetLegacyGlobalMergeFields = false
            };

            var mergeFields = RequestContext.GetCommonMergeFields(null, commonMergeFields);

            mergeFields.Add("Items", results);
            mergeFields.Add("FollowedItemIds", followedItemIds);

            var output = lavaTemplate.ResolveMergeFields(mergeFields);

            return(ActionOk(new StringContent(output, Encoding.UTF8, "application/json")));
        }
        /// <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 #31
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);
            }
        }
        /// <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();
        }
        /// <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();
            }
        }
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.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;
            }
        }
        public IHttpActionResult ChannelItem(string identifier)
        {
            RockContext rockContext = new RockContext();
            ContentChannelItemService contentChannelItemService = new ContentChannelItemService(rockContext);

            IQueryable <ContentChannelItem> contentChannelItem;

            var itemId = identifier.AsInteger();

            if (itemId != 0)
            {
                contentChannelItem = contentChannelItemService.Queryable().Where(i => i.Id == itemId);
            }
            else
            {
                //Get by slug
                ContentChannelItemSlugService contentChannelItemSlugService = new ContentChannelItemSlugService(rockContext);
                contentChannelItem = contentChannelItemSlugService.Queryable()
                                     .Where(s => s.Slug == identifier)
                                     .Select(s => s.ContentChannelItem);
            }

            var contentChannel = contentChannelItem.Select(i => i.ContentChannel).FirstOrDefault();

            if (contentChannel == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }

            if (!contentChannel.IsAuthorized(Rock.Security.Authorization.VIEW, GetPerson()))
            {
                throw new HttpResponseException(HttpStatusCode.Unauthorized);
            }

            var contentChannelTypeId  = contentChannel.ContentChannelTypeId.ToString();
            var contentChanelIdString = contentChannel.Id.ToString();

            var attributeQry = new AttributeService(rockContext).Queryable()
                               .Where(a => a.EntityTypeId == contentChanelItemEntityTypeId &&
                                      ((a.EntityTypeQualifierColumn == "ContentChannelTypeId" && a.EntityTypeQualifierValue == contentChannelTypeId) ||
                                       (a.EntityTypeQualifierColumn == "ContentChannelId" && a.EntityTypeQualifierValue == contentChanelIdString)))
                               .Select(a => a.Id);

            var attributeValueQry = new AttributeValueService(rockContext).Queryable().Where(av => attributeQry.Contains(av.AttributeId));

            var complex = contentChannelItem
                          .GroupJoin(attributeValueQry,
                                     i => i.Id,
                                     av => av.EntityId,
                                     (i, av) => new
            {
                ContentChanelItem = i,
                Children          = i.ChildItems.OrderBy(ci => ci.Order).Select(ci => ci.ChildContentChannelItemId),
                ParentItems       = i.ParentItems.Select(ci => ci.ContentChannelItemId),
                AttributeValues   = av
            })
                          .ToList();

            var items = complex
                        .Select(i => new ChannelItem
            {
                Id          = i.ContentChanelItem.Id,
                DateTime    = i.ContentChanelItem.StartDateTime,
                Title       = i.ContentChanelItem.Title,
                Content     = i.ContentChanelItem.Content,
                Priority    = i.ContentChanelItem.Priority,
                Order       = i.ContentChanelItem.Order,
                Attributes  = i.AttributeValues.ToDictionary(a => a.AttributeKey, a => a.Value),
                Tags        = GetTags(i.ContentChanelItem, rockContext),
                Slug        = i.ContentChanelItem.PrimarySlug,
                CreatedBy   = i.ContentChanelItem.CreatedByPersonName,
                ChildItems  = i.Children.ToList(),
                ParentItems = i.ParentItems.ToList()
            }).ToList();

            return(Json(items.FirstOrDefault()));
        }
Example #36
0
        public void Execute(IJobExecutionContext context)
        {
            JobDataMap dataMap = context.JobDetail.JobDataMap;

            int sermonCount    = 0;
            int newSermonCount = 0;

            List <SermonSeries>       sermonSeries              = new List <SermonSeries>();
            RockContext               rockContext               = new RockContext();
            ContentChannelService     contentChannelService     = new ContentChannelService(rockContext);
            ContentChannelItemService contentChannelItemService = new ContentChannelItemService(rockContext);
            BinaryFileService         binaryFileService         = new BinaryFileService(rockContext);
            BinaryFileType            binaryFileType            = new BinaryFileTypeService(rockContext).Get(Rock.SystemGuid.BinaryFiletype.MEDIA_FILE.AsGuid());
            var sermonSeriesChannel = contentChannelService.Get(dataMap.GetString("SermonSeriesContentChannel").AsGuid());
            var sermonChannel       = contentChannelService.Get(dataMap.GetString("SermonContentChannel").AsGuid());

            var dbCon = DBConnection.Instance();

            dbCon.DatabaseName = "secccp_main";
            if (dbCon.IsConnect())
            {
                sermonSeries = GetSermonSeries(dbCon);

                foreach (var series in sermonSeries.Where(s => s.deleted == false))
                {
                    AddSermons(dbCon, series);
                    var item = contentChannelItemService.Queryable().Where(i => i.ForeignId == series.id && i.ContentChannelId == sermonSeriesChannel.Id).FirstOrDefault();
                    if (item == null)
                    {
                        item = new ContentChannelItem()
                        {
                            ContentChannelId     = sermonSeriesChannel.Id,
                            ForeignId            = series.id,
                            ContentChannelTypeId = sermonSeriesChannel.ContentChannelTypeId
                        };
                        contentChannelItemService.Add(item);
                    }
                    item.Title   = series.title;
                    item.Content = series.description.Replace("\n", "").Replace("\r", "");
                    if (series.sermons.Any())
                    {
                        item.StartDateTime = Helpers.FromUnixTime(series.sermons.FirstOrDefault().date);
                    }
                    else
                    {
                        item.StartDateTime = Rock.RockDateTime.Now;
                    }

                    rockContext.SaveChanges();
                    item.LoadAttributes();
                    item.SetAttributeValue("Slug", series.slug);

                    if (string.IsNullOrWhiteSpace(item.GetAttributeValue("Image")))
                    {
                        WebClient client = new WebClient();
                        try
                        {
                            using (MemoryStream stream = new MemoryStream(client.DownloadData(string.Format("http://files.secc.org/sermons/series/series-{0}.jpg", series.id))))
                            {
                                BinaryFile binaryFile = new BinaryFile();
                                binaryFileService.Add(binaryFile);
                                binaryFile.IsTemporary      = false;
                                binaryFile.BinaryFileTypeId = binaryFileType.Id;
                                binaryFile.MimeType         = "image/jpg";
                                binaryFile.FileName         = string.Format("Series-{0}.jpg", series.id);
                                binaryFile.ContentStream    = stream;
                                rockContext.SaveChanges();
                                item.SetAttributeValue("Image", binaryFile.Guid.ToString());
                            }
                        }
                        catch (Exception ex)
                        {
                            var a = ex;
                        }
                    }

                    item.SaveAttributeValues();
                }
                foreach (var series in sermonSeries.Where(ss => !ss.deleted))
                {
                    //add in sermons
                    foreach (var sermon in series.sermons.Where(s => !s.deleted))
                    {
                        sermonCount++;
                        var child = contentChannelItemService.Queryable().Where(i => i.ForeignId == sermon.id && i.ContentChannelId == sermonChannel.Id).FirstOrDefault();
                        if (child == null)
                        {
                            newSermonCount++;
                            child = new ContentChannelItem()
                            {
                                ContentChannelId     = sermonChannel.Id,
                                ForeignId            = sermon.id,
                                ContentChannelTypeId = sermonChannel.ContentChannelTypeId,
                                StartDateTime        = Helpers.FromUnixTime(sermon.date)
                            };
                            contentChannelItemService.Add(child);
                            rockContext.SaveChanges();
                            var item = contentChannelItemService.Queryable().Where(i => i.ForeignId == series.id).FirstOrDefault();
                            item.ChildItems.Add(new ContentChannelItemAssociation
                            {
                                ContentChannelItemId      = item.Id,
                                ChildContentChannelItemId = child.Id,
                            });
                            rockContext.SaveChanges();
                        }
                        child.Title         = sermon.title;
                        child.Content       = sermon.description.Replace("\n", "").Replace("\r", "");
                        child.StartDateTime = Helpers.FromUnixTime(sermon.date);
                        rockContext.SaveChanges();
                        child.LoadAttributes();
                        child.SetAttributeValue("Slug", sermon.slug);
                        child.SetAttributeValue("Speaker", sermon.speaker);
                        child.SetAttributeValue("Duration", sermon.duration);
                        child.SetAttributeValue("VimeoId", sermon.vimeo_id);
                        child.SetAttributeValue("VimeoDownloadUrl", sermon.vimeo_sd_url);
                        child.SetAttributeValue("VimeoStreamingUrl", sermon.vimeo_live_url);

                        if (string.IsNullOrWhiteSpace(child.GetAttributeValue("Image")))
                        {
                            WebClient client = new WebClient();
                            try
                            {
                                using (MemoryStream stream = new MemoryStream(client.DownloadData(string.Format("http://panel.secc.org/upload/sermon/images/images-{0}.jpg", sermon.id))))
                                {
                                    BinaryFile binaryFile = new BinaryFile();
                                    binaryFileService.Add(binaryFile);
                                    binaryFile.IsTemporary      = false;
                                    binaryFile.BinaryFileTypeId = binaryFileType.Id;
                                    binaryFile.MimeType         = "image/jpg";
                                    binaryFile.FileName         = string.Format("Sermon-{0}.jpg", series.id);
                                    binaryFile.ContentStream    = stream;
                                    rockContext.SaveChanges();
                                    child.SetAttributeValue("Image", binaryFile.Guid.ToString());
                                }
                            }
                            catch (Exception ex)
                            {
                                var a = ex;
                            }
                        }

                        if (string.IsNullOrWhiteSpace(child.GetAttributeValue("Audio")))
                        {
                            try
                            {
                                using (WebClient client = new WebClient())
                                {
                                    using (MemoryStream stream = new MemoryStream(client.DownloadData(sermon.audio_link)))
                                    {
                                        BinaryFile binaryFile = new BinaryFile();
                                        binaryFileService.Add(binaryFile);
                                        binaryFile.IsTemporary      = false;
                                        binaryFile.BinaryFileTypeId = binaryFileType.Id;
                                        binaryFile.MimeType         = "audio/mpeg";
                                        binaryFile.FileName         = string.Format("Sermon-{0}.mp3", sermon.id);
                                        binaryFile.ContentStream    = stream;
                                        rockContext.SaveChanges();
                                        child.SetAttributeValue("Audio", binaryFile.Guid.ToString());
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                var a = ex;
                            }
                        }


                        child.SaveAttributeValues();
                    }
                }
            }
            context.Result = string.Format("Synced {0} sermons ({1} New Sermon)", sermonCount, newSermonCount);
        }
Example #37
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;
            }
        }
        /// <summary>
        /// Gets the content.
        /// </summary>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        private List <ContentChannelItem> GetContent(List <string> errorMessages)
        {
            List <ContentChannelItem> items = null;

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

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

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

                    items = new List <ContentChannelItem>();

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

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

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

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

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

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

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

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

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

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

            return(items);
        }
        /// <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));
                }

                // 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();
            }
        }
Example #40
0
        /// <summary>
        /// Loads the content.
        /// </summary>
        private void LoadContent()
        {
            var rockContext       = new RockContext();
            var eventCalendarGuid = GetAttributeValue("EventCalendar").AsGuid();
            var eventCalendar     = new EventCalendarService(rockContext).Get(eventCalendarGuid);

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

            var eventItemOccurrenceService = new EventItemOccurrenceService(rockContext);

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

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

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

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

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

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

            CalendarEventDates = new List <DateTime>();

            var eventOccurrenceSummaries = new List <EventOccurrenceSummaryKFS>();

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

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

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

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

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

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

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

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

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

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

                ParameterExpression paramExpression = service.ParameterExpression;

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

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

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

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

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

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

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

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

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

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

                        // Order the items
                        SortProperty sortProperty = null;

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

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

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

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

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

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

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

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

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

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

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

            lContent.Text = GetAttributeValue("LavaTemplate").ResolveMergeFields(mergeFields);
        }
        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;
            }
        }
Example #42
0
        /// <summary>
        /// Loads the ContentChannelItem data.
        /// </summary>
        /// <param name="csvData">The CSV data.</param>
        private int LoadContentChannelItem(CSVInstance csvData)
        {
            var lookupContext             = new RockContext();
            var contentChannelItemService = new ContentChannelItemService(lookupContext);
            var contentChannelService     = new ContentChannelService(lookupContext);
            var contentChannelTypeService = new ContentChannelTypeService(lookupContext);

            // Look for custom attributes in the Content Channel file
            var allFields        = csvData.TableNodes.FirstOrDefault().Children.Select((node, index) => new { node = node, index = index }).ToList();
            var customAttributes = allFields
                                   .Where(f => f.index > ItemParentId)
                                   .ToDictionary(f => f.index, f => f.node.Name);

            // Set the supported date formats
            var dateFormats = new[] { "yyyy-MM-dd", "MM/dd/yyyy", "MM/dd/yy",
                                      "M/d/yyyy", "M/dd/yyyy",
                                      "M/d/yyyy h:mm:ss tt", "M/d/yyyy h:mm tt",
                                      "MM/dd/yyyy hh:mm:ss", "M/d/yyyy h:mm:ss",
                                      "M/d/yyyy hh:mm tt", "M/d/yyyy hh tt",
                                      "M/d/yyyy h:mm", "M/d/yyyy h:mm",
                                      "MM/dd/yyyy hh:mm", "M/dd/yyyy hh:mm",
                                      "yyyy-MM-dd HH:mm:ss" };

            var importedChannelIds = new List <int>();

            var completed            = 0;
            var importedCount        = 0;
            var alreadyImportedCount = contentChannelItemService.Queryable().AsNoTracking().Count(i => i.ForeignKey != null);

            ReportProgress(0, $"Starting Content Channel Item import ({alreadyImportedCount:N0} already exist).");

            string[] row;
            // Uses a look-ahead enumerator: this call will move to the next record immediately
            while ((row = csvData.Database.FirstOrDefault()) != null)
            {
                var rowContentChannelName         = row[ContentChannelName];
                var rowContentChannelItemTitle    = row[ItemTitle];
                var rowContentChannelItemContent  = row[ItemContent];
                var rowContentChannelItemId       = row[ItemId];
                var rowContentChannelItemParentId = row[ItemParentId];

                var rowChannelItemId = rowContentChannelItemId.AsType <int?>();

                ContentChannel contentChannel = null;
                if (contentChannelService.Queryable().AsNoTracking().FirstOrDefault(t => t.Name.ToLower() == rowContentChannelName.ToLower()) != null)
                {
                    contentChannel = contentChannelService.Queryable().AsNoTracking().FirstOrDefault(c => c.Name.ToLower() == rowContentChannelName.ToLower());
                }

                //
                // Verify the Content Channel exists.
                //
                if (contentChannel.Id < 1)
                {
                    throw new System.Collections.Generic.KeyNotFoundException($"Content Channel {rowContentChannelName} not found", null);
                }

                //
                // Get content channel type
                //
                var contentChannelTypeId = contentChannelService.Queryable().AsNoTracking().FirstOrDefault(c => c.Id == contentChannel.Id).ContentChannelTypeId;

                //
                // Check that this Content Channel Item doesn't already exist.
                //
                var exists = false;
                if (alreadyImportedCount > 0)
                {
                    exists = contentChannelItemService.Queryable().AsNoTracking().Any(i => i.ForeignKey == rowContentChannelItemId);
                }

                if (!exists)
                {
                    //
                    // Create and populate the new Content Channel.
                    //
                    var contentChannelItem = new ContentChannelItem
                    {
                        Title                = rowContentChannelItemTitle,
                        Status               = ContentChannelItemStatus.Approved,
                        Content              = rowContentChannelItemContent,
                        ForeignKey           = rowContentChannelItemId,
                        ForeignId            = rowChannelItemId,
                        ContentChannelId     = contentChannel.Id,
                        ContentChannelTypeId = contentChannelTypeId
                    };

                    DateTime startDateValue;
                    if (DateTime.TryParseExact(row[ItemStart], dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out startDateValue))
                    {
                        contentChannelItem.StartDateTime = startDateValue;
                    }

                    DateTime expireDateValue;
                    if (DateTime.TryParseExact(row[ItemExpire], dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out expireDateValue) && expireDateValue != System.DateTime.MinValue)
                    {
                        contentChannelItem.ExpireDateTime = expireDateValue;
                    }

                    if (contentChannel.RequiresApproval)
                    {
                        contentChannelItem.Status                  = ContentChannelItemStatus.Approved;
                        contentChannelItem.ApprovedDateTime        = ImportDateTime;
                        contentChannelItem.ApprovedByPersonAliasId = ImportPersonAliasId;
                    }

                    // Save changes for context
                    lookupContext.WrapTransaction(() =>
                    {
                        lookupContext.ContentChannelItems.Add(contentChannelItem);
                        lookupContext.SaveChanges(DisableAuditing);
                    });

                    //
                    // Look for Parent Id and create appropriate objects.
                    //
                    if (!string.IsNullOrWhiteSpace(rowContentChannelItemParentId))
                    {
                        var parentFound = false;
                        parentFound = contentChannelItemService.Queryable().AsNoTracking().Any(i => i.ForeignKey == rowContentChannelItemParentId);

                        if (parentFound)
                        {
                            var parentItem = contentChannelItemService.Queryable().FirstOrDefault(i => i.ForeignKey == rowContentChannelItemParentId);

                            var service = new ContentChannelItemAssociationService(lookupContext);
                            var order   = service.Queryable().AsNoTracking()
                                          .Where(a => a.ContentChannelItemId == parentItem.Id)
                                          .Select(a => ( int? )a.Order)
                                          .DefaultIfEmpty()
                                          .Max();

                            var assoc = new ContentChannelItemAssociation();
                            assoc.ContentChannelItemId      = parentItem.Id;
                            assoc.ChildContentChannelItemId = contentChannelItem.Id;
                            assoc.Order = order.HasValue ? order.Value + 1 : 0;
                            service.Add(assoc);

                            lookupContext.SaveChanges(DisableAuditing);
                        }
                    }

                    //
                    // Process Attributes for Content Channel Items
                    //
                    if (customAttributes.Any())
                    {
                        // create content channel item attributes, but only if not already processed in this csv file
                        if (!importedChannelIds.Contains(contentChannel.Id))
                        {
                            // add current content channel id to list so we don't process multiple times
                            importedChannelIds.Add(contentChannel.Id);

                            // create content channel item attributes
                            foreach (var newAttributePair in customAttributes)
                            {
                                var pairs                  = newAttributePair.Value.Split('^');
                                var categoryName           = string.Empty;
                                var attributeName          = string.Empty;
                                var attributeTypeString    = string.Empty;
                                var attributeForeignKey    = string.Empty;
                                var definedValueForeignKey = string.Empty;
                                var fieldTypeId            = TextFieldTypeId;

                                if (pairs.Length == 1)
                                {
                                    attributeName = pairs[0];
                                }
                                else if (pairs.Length == 2)
                                {
                                    attributeName       = pairs[0];
                                    attributeTypeString = pairs[1];
                                }
                                else if (pairs.Length >= 3)
                                {
                                    categoryName  = pairs[1];
                                    attributeName = pairs[2];
                                    if (pairs.Length >= 4)
                                    {
                                        attributeTypeString = pairs[3];
                                    }
                                    if (pairs.Length >= 5)
                                    {
                                        attributeForeignKey = pairs[4];
                                    }
                                    if (pairs.Length >= 6)
                                    {
                                        definedValueForeignKey = pairs[5];
                                    }
                                }

                                var definedValueForeignId = definedValueForeignKey.AsType <int?>();

                                //
                                // Translate the provided attribute type into one we know about.
                                //
                                fieldTypeId = GetAttributeFieldType(attributeTypeString);

                                if (string.IsNullOrEmpty(attributeName))
                                {
                                    LogException($"Content Channel {contentChannelItem.ContentChannel.Name}", $"Content Channel {contentChannelItem.ContentChannel.Name} Item Attribute Name cannot be blank '{newAttributePair.Value}'.");
                                }
                                else
                                {
                                    //
                                    // First try to find the existing attribute, if not found then add a new one.
                                    //
                                    var fk = string.Empty;
                                    if (string.IsNullOrWhiteSpace(attributeForeignKey))
                                    {
                                        fk = $"Bulldozer_ContentChannelItem_{contentChannel.Name.RemoveWhitespace()}_{categoryName.RemoveWhitespace()}_{attributeName.RemoveWhitespace()}".Left(100);
                                    }
                                    else
                                    {
                                        fk = attributeForeignKey;
                                    }

                                    AddEntityAttribute(lookupContext, contentChannelItem.TypeId, "ContentChannelId", contentChannelItem.ContentChannelId.ToString(), fk, categoryName, attributeName, string.Empty, fieldTypeId, true, definedValueForeignId, definedValueForeignKey, attributeTypeString: attributeTypeString);
                                }
                            } // end add attributes
                        }     // end test for first run

                        //
                        // Add any Content Channel Item attribute values
                        //
                        foreach (var attributePair in customAttributes)
                        {
                            var newValue = row[attributePair.Key];

                            if (!string.IsNullOrWhiteSpace(newValue))
                            {
                                var pairs                  = attributePair.Value.Split('^');
                                var categoryName           = string.Empty;
                                var attributeName          = string.Empty;
                                var attributeTypeString    = string.Empty;
                                var attributeForeignKey    = string.Empty;
                                var definedValueForeignKey = string.Empty;

                                if (pairs.Length == 1)
                                {
                                    attributeName = pairs[0];
                                }
                                else if (pairs.Length == 2)
                                {
                                    attributeName       = pairs[0];
                                    attributeTypeString = pairs[1];
                                }
                                else if (pairs.Length >= 3)
                                {
                                    categoryName  = pairs[1];
                                    attributeName = pairs[2];
                                    if (pairs.Length >= 4)
                                    {
                                        attributeTypeString = pairs[3];
                                    }
                                    if (pairs.Length >= 5)
                                    {
                                        attributeForeignKey = pairs[4];
                                    }
                                    if (pairs.Length >= 6)
                                    {
                                        definedValueForeignKey = pairs[5];
                                    }
                                }

                                if (!string.IsNullOrEmpty(attributeName))
                                {
                                    string fk = string.Empty;
                                    if (string.IsNullOrWhiteSpace(attributeForeignKey))
                                    {
                                        fk = $"Bulldozer_ContentChannelItem_{contentChannel.Name.RemoveWhitespace()}_{categoryName.RemoveWhitespace()}_{attributeName.RemoveWhitespace()}".Left(100);
                                    }
                                    else
                                    {
                                        fk = attributeForeignKey;
                                    }

                                    var attribute = FindEntityAttribute(lookupContext, categoryName, attributeName, contentChannelItem.TypeId, fk);
                                    AddEntityAttributeValue(lookupContext, attribute, contentChannelItem, newValue, null, true);
                                }
                            }
                        } // end attribute value processing
                    }     // end custom attribute processing

                    importedCount++;
                }

                //
                // Notify user of our status.
                //
                completed++;
                if (completed % (ReportingNumber * 10) < 1)
                {
                    ReportProgress(0, $"{completed:N0} Content Channel records processed, {importedCount:N0} imported.");
                }

                if (completed % ReportingNumber < 1)
                {
                    lookupContext.SaveChanges();
                    ReportPartialProgress();

                    // Clear out variables
                    contentChannelService = new ContentChannelService(lookupContext);
                }
            }

            //
            // Save any other changes to existing items.
            //
            lookupContext.SaveChanges();
            lookupContext.Dispose();

            ReportProgress(0, $"Finished Content Channel Item import: {importedCount:N0} records added.");

            return(completed);
        }