Beispiel #1
0
        /// <summary>
        /// Handles the Delete event of the gItems control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RowEventArgs" /> instance containing the event data.</param>
        protected void gItems_Delete(object sender, RowEventArgs e)
        {
            var rockContext = new RockContext();
            ContentChannelItemService contentItemService = new ContentChannelItemService(rockContext);

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

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

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

            BindGrids();
        }
Beispiel #2
0
        private MessageArchiveItem GetArchiveObjectForMessage(ContentChannelItem message)
        {
            message.LoadAttributes(_rockContext);

            var vimeoLinks  = GetVimeoLink(message.GetAttributeValue("VideoId"));
            var messageDate = message.GetAttributeValue("Date").AsDateTime();

            return(new MessageArchiveItem()
            {
                Id = message.Id,
                Title = message.Title,
                Date = messageDate?.ToShortDateString(),
                Content = DotLiquid.StandardFilters.StripHtml(message.Content).Replace("\n\n", "\r\n\r\n"),
                Speaker = message.GetAttributeValue("Speaker"),
                SpeakerTitle = message.GetAttributeValue("SpeakerTitle"),
                VimeoLink = vimeoLinks?.Url,
                VimeoImage = vimeoLinks?.Image,
                AudioLink = GetFileUrlOrNull(message, "PodcastAudio"),
                AudioImage = GetFileUrlOrNull(message, "PodcastImage"),
                Notes = GetFileUrlOrNull(message, "MessageNotes"),
                TalkItOver = GetFileUrlOrNull(message, "TalkItOver")
            });
        }
Beispiel #3
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();
        }
Beispiel #4
0
        /// <summary>
        /// Handles the DeleteClick event of the gContentChannelItems control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Rock.Web.UI.Controls.RowEventArgs"/> instance containing the event data.</param>
        protected void gContentChannelItems_DeleteClick(object sender, Rock.Web.UI.Controls.RowEventArgs e)
        {
            var rockContext                   = new RockContext();
            var contentItemService            = new ContentChannelItemService(rockContext);
            var contentItemAssociationService = new ContentChannelItemAssociationService(rockContext);
            var contentItemSlugService        = new ContentChannelItemSlugService(rockContext);

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

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

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

            BindContentChannelItemsGrid();

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

            EditContentChannelItem(contentChannelItemId);
        }
        protected void lbPersonPaging_Click(object sender, EventArgs e)
        {
            var rockContext        = new RockContext();
            var personService      = new PersonService(rockContext);
            var person             = personService.Queryable().FirstOrDefault(a => a.Guid == personGuid);
            var attributeKey       = GetAttributeValue("PersonAttributeKey");
            var contentChannel     = new ContentChannelService(rockContext).Get(GetAttributeValue("PersonPagingContentChannel").AsGuid());
            var contentChannelItem = new ContentChannelItem
            {
                Title                = string.Empty,
                Status               = ContentChannelItemStatus.Approved,
                Content              = string.Empty,
                ContentChannelId     = contentChannel.Id,
                ContentChannelTypeId = contentChannel.ContentChannelTypeId,
                Priority             = 0,
                StartDateTime        = DateTime.Now,
                Order                = 0,
                Guid = new Guid()
            };

            contentChannelItem.LoadAttributes();

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

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

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

                    nbWarning.Text    = string.Format("{0} added to the list.", person.FullName);
                    nbWarning.Visible = true;
                }
            }
        }
Beispiel #6
0
        /// <summary>
        /// Handles the Click event of the lbSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void lbSave_Click(object sender, EventArgs e)
        {
            var rockContext = new RockContext();
            ContentChannelItem contentItem = GetContentItem(rockContext);

            if (contentItem != null && contentItem.IsAuthorized(Authorization.EDIT, CurrentPerson))
            {
                contentItem.Title   = tbTitle.Text;
                contentItem.Content = contentItem.ContentChannel.ContentControlType == ContentControlType.HtmlEditor ?
                                      htmlContent.Text : ceContent.Text;
                contentItem.Priority = nbPriority.Text.AsInteger();
                if (contentItem.ContentChannelType.IncludeTime)
                {
                    contentItem.StartDateTime  = dtpStart.SelectedDateTime ?? RockDateTime.Now;
                    contentItem.ExpireDateTime = (contentItem.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange) ?
                                                 dtpExpire.SelectedDateTime : null;
                }
                else
                {
                    contentItem.StartDateTime  = dpStart.SelectedDate ?? RockDateTime.Today;
                    contentItem.ExpireDateTime = (contentItem.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange) ?
                                                 dpExpire.SelectedDate : null;
                }

                int newStatusID = hfStatus.Value.AsIntegerOrNull() ?? contentItem.Status.ConvertToInt();
                int oldStatusId = contentItem.Status.ConvertToInt();
                if (newStatusID != oldStatusId && contentItem.IsAuthorized(Authorization.APPROVE, CurrentPerson))
                {
                    contentItem.Status = hfStatus.Value.ConvertToEnum <ContentChannelItemStatus>(ContentChannelItemStatus.PendingApproval);
                    if (contentItem.Status == ContentChannelItemStatus.PendingApproval)
                    {
                        contentItem.ApprovedDateTime        = null;
                        contentItem.ApprovedByPersonAliasId = null;
                    }
                    else
                    {
                        contentItem.ApprovedDateTime        = RockDateTime.Now;
                        contentItem.ApprovedByPersonAliasId = CurrentPersonAliasId;
                    }
                }

                contentItem.LoadAttributes(rockContext);
                Rock.Attribute.Helper.GetEditValues(phAttributes, contentItem);

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

                rockContext.WrapTransaction(() =>
                {
                    rockContext.SaveChanges();
                    contentItem.SaveAttributeValues(rockContext);

                    int?eventItemOccurrenceId = PageParameter("EventItemOccurrenceId").AsIntegerOrNull();
                    if (eventItemOccurrenceId.HasValue)
                    {
                        var occurrenceChannelItemService = new EventItemOccurrenceChannelItemService(rockContext);
                        var occurrenceChannelItem        = occurrenceChannelItemService
                                                           .Queryable()
                                                           .Where(c =>
                                                                  c.ContentChannelItemId == contentItem.Id &&
                                                                  c.EventItemOccurrenceId == eventItemOccurrenceId.Value)
                                                           .FirstOrDefault();

                        if (occurrenceChannelItem == null)
                        {
                            occurrenceChannelItem = new EventItemOccurrenceChannelItem();
                            occurrenceChannelItem.ContentChannelItemId  = contentItem.Id;
                            occurrenceChannelItem.EventItemOccurrenceId = eventItemOccurrenceId.Value;
                            occurrenceChannelItemService.Add(occurrenceChannelItem);
                            rockContext.SaveChanges();
                        }
                    }
                });

                ReturnToParentPage();
            }
        }
        /// <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>
        /// **The PropertyFilter checks for it's property/attribute list in a cached items object before recreating
        /// them using reflection and loading of generic attributes. Because of this, we're going to load them here
        /// and exclude some properties and add additional attributes specific to the channel type, and then save
        /// list to same cached object so that property filter lists our collection of properties/attributes
        /// instead.
        /// </summary>
        private List <Rock.Reporting.EntityField> HackEntityFields(ContentChannel channel, RockContext rockContext)
        {
            if (channel != null)
            {
                var entityTypeCache = EntityTypeCache.Read(ITEM_TYPE_NAME);
                if (entityTypeCache != null)
                {
                    var entityType = entityTypeCache.GetEntityType();

                    /// See above comments on HackEntityFields** to see why we are doing this
                    HttpContext.Current.Items.Remove(Rock.Reporting.EntityHelper.GetCacheKey(entityType));

                    var entityFields = Rock.Reporting.EntityHelper.GetEntityFields(entityType);
                    foreach (var entityField in entityFields
                             .Where(f =>
                                    f.FieldKind == Rock.Reporting.FieldKind.Attribute &&
                                    f.AttributeGuid.HasValue)
                             .ToList())
                    {
                        // remove EntityFields that aren't attributes for this ContentChannelType or ChannelChannel (to avoid duplicate Attribute Keys)
                        var attribute = AttributeCache.Read(entityField.AttributeGuid.Value);
                        if (attribute != null &&
                            attribute.EntityTypeQualifierColumn == "ContentChannelTypeId" &&
                            attribute.EntityTypeQualifierValue.AsInteger() != channel.ContentChannelTypeId)
                        {
                            entityFields.Remove(entityField);
                        }

                        if (attribute != null &&
                            attribute.EntityTypeQualifierColumn == "ContentChannelId" &&
                            attribute.EntityTypeQualifierValue.AsInteger() != channel.Id)
                        {
                            entityFields.Remove(entityField);
                        }
                    }

                    if (entityFields != null)
                    {
                        // Remove the status field
                        var ignoreFields = new List <string>();
                        ignoreFields.Add("ContentChannelId");
                        ignoreFields.Add("Status");

                        entityFields = entityFields.Where(f => !ignoreFields.Contains(f.Name)).ToList();

                        // Add any additional attributes that are specific to channel/type
                        var item = new ContentChannelItem();
                        item.ContentChannel       = channel;
                        item.ContentChannelId     = channel.Id;
                        item.ContentChannelType   = channel.ContentChannelType;
                        item.ContentChannelTypeId = channel.ContentChannelTypeId;
                        item.LoadAttributes(rockContext);
                        foreach (var attribute in item.Attributes
                                 .Where(a =>
                                        a.Value.EntityTypeQualifierColumn != "" &&
                                        a.Value.EntityTypeQualifierValue != "")
                                 .Select(a => a.Value))
                        {
                            if (!entityFields.Any(f => f.AttributeGuid.Equals(attribute.Guid)))
                            {
                                Rock.Reporting.EntityHelper.AddEntityFieldForAttribute(entityFields, attribute);
                            }
                        }

                        // Re-sort fields
                        int index        = 0;
                        var sortedFields = new List <Rock.Reporting.EntityField>();
                        foreach (var entityProperty in entityFields.OrderBy(p => p.Title).ThenBy(p => p.Name))
                        {
                            entityProperty.Index = index;
                            index++;
                            sortedFields.Add(entityProperty);
                        }

                        // Save new fields to cache ( which report field will use instead of reading them again )
                        HttpContext.Current.Items[Rock.Reporting.EntityHelper.GetCacheKey(entityType)] = sortedFields;
                    }

                    return(entityFields);
                }
            }

            return(null);
        }
        /// <summary>
        /// Renders the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="result">The result.</param>
        public override void Render(Context context, TextWriter result)
        {
            // First, ensure that this command is allowed in the context.
            if (!LavaHelper.IsAuthorized(context, this.GetType().Name))
            {
                result.Write(string.Format(RockLavaBlockBase.NotAuthorizedMessage, this.Name));
                base.Render(context, result);
                return;
            }

            // Parse the Lava Command markup to retrieve paramters.
            var parms = new Dictionary <string, string>
            {
                { ParameterKey.Operation, "View" }
            };

            LavaHelper.ParseCommandMarkup(_markup, context, parms);

            // Set local variables from parsed parameters.
            int?contentChannelItemId = parms.GetValueOrNull(ParameterKey.ContentChannelItemId).AsIntegerOrNull();

            if (!contentChannelItemId.HasValue)
            {
                // Do nothing if a ContentChannelItem ID wasn't specified.
                return;
            }

            ContentChannelItem contentChannelItem = null;

            using (var rockContext = new RockContext())
            {
                contentChannelItem = new ContentChannelItemService(rockContext)
                                     .Queryable("ContentChannel")
                                     .AsNoTracking()
                                     .FirstOrDefault(c => c.Id == contentChannelItemId.Value);
            }

            ContentChannel contentChannel = contentChannelItem.ContentChannel;

            if (contentChannelItem == null || contentChannel == null)
            {
                // The caller supplied an invalid ContentChannelItem ID; nothing to do.
                return;
            }

            string operation = parms.GetValueOrNull(ParameterKey.Operation);
            string summary   = parms.GetValueOrNull(ParameterKey.Summary);
            string source    = parms.GetValueOrNull(ParameterKey.Source);
            string medium    = parms.GetValueOrNull(ParameterKey.Medium);
            string campaign  = parms.GetValueOrNull(ParameterKey.Campaign);
            string content   = parms.GetValueOrNull(ParameterKey.Content);
            string term      = parms.GetValueOrNull(ParameterKey.Term);

            int?personAliasId = parms.GetValueOrNull(ParameterKey.PersonAliasId).AsIntegerOrNull();

            if (!personAliasId.HasValue)
            {
                Person currentPerson = LavaHelper.GetCurrentPerson(context);
                personAliasId = LavaHelper.GetPrimaryPersonAliasId(currentPerson);
            }

            // Write the Interaction by way of a transaction.
            DefinedValueCache mediumType = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.INTERACTIONCHANNELTYPE_CONTENTCHANNEL.AsGuid());

            if (mediumType == null)
            {
                return;
            }

            var info = new InteractionTransactionInfo
            {
                ChannelTypeMediumValueId = mediumType.Id,
                ChannelEntityId          = contentChannel.Id,
                ChannelName           = contentChannel.ToString(),
                ComponentEntityTypeId = contentChannel.TypeId,
                ComponentEntityId     = contentChannelItem.Id,
                ComponentName         = contentChannelItem.ToString(),
                InteractionOperation  = operation,
                InteractionSummary    = summary ?? contentChannelItem.Title,
                PersonAliasId         = personAliasId,
                InteractionSource     = source,
                InteractionMedium     = medium,
                InteractionCampaign   = campaign,
                InteractionContent    = content,
                InteractionTerm       = term
            };

            var interactionTransaction = new InteractionTransaction(info);

            interactionTransaction.Enqueue();
        }
Beispiel #10
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);
        }
        public void ShowDetail(int contentItemId, int?contentChannelId)
        {
            bool canEdit = IsUserAuthorized(Authorization.EDIT);

            hfId.Value        = contentItemId.ToString();
            hfChannelId.Value = contentChannelId.HasValue ? contentChannelId.Value.ToString() : string.Empty;

            ContentChannelItem contentItem = GetContentItem();

            if (contentItem != null &&
                contentItem.ContentChannelType != null &&
                contentItem.ContentChannel != null &&
                (canEdit || contentItem.IsAuthorized(Authorization.EDIT, CurrentPerson)))
            {
                ShowApproval(contentItem);

                pnlEditDetails.Visible = true;

                hfId.Value        = contentItem.Id.ToString();
                hfChannelId.Value = contentItem.ContentChannelId.ToString();

                string cssIcon = contentItem.ContentChannel.IconCssClass;
                if (string.IsNullOrWhiteSpace(cssIcon))
                {
                    cssIcon = "fa fa-certificate";
                }
                lIcon.Text = string.Format("<i class='{0}'></i>", cssIcon);

                string title = contentItem.Id > 0 ?
                               ActionTitle.Edit(ContentChannelItem.FriendlyTypeName) :
                               ActionTitle.Add(ContentChannelItem.FriendlyTypeName);
                lTitle.Text = title.FormatAsHtmlTitle();

                hlContentChannel.Text = contentItem.ContentChannel.Name;
                hlStatus.Text         = contentItem.Status.ConvertToString();

                hlStatus.LabelType = LabelType.Default;
                if (contentItem.Status == ContentChannelItemStatus.Approved)
                {
                    hlStatus.LabelType = LabelType.Success;
                }
                else if (contentItem.Status == ContentChannelItemStatus.Denied)
                {
                    hlStatus.LabelType = LabelType.Danger;
                }
                if (contentItem.Status != ContentChannelItemStatus.PendingApproval)
                {
                    var statusDetail = new System.Text.StringBuilder();
                    if (contentItem.ApprovedByPersonAlias != null && contentItem.ApprovedByPersonAlias.Person != null)
                    {
                        statusDetail.AppendFormat("by {0} ", contentItem.ApprovedByPersonAlias.Person.FullName);
                    }
                    if (contentItem.ApprovedDateTime.HasValue)
                    {
                        statusDetail.AppendFormat("on {0} at {1}", contentItem.ApprovedDateTime.Value.ToShortDateString(),
                                                  contentItem.ApprovedDateTime.Value.ToShortTimeString());
                    }
                    hlStatus.ToolTip = statusDetail.ToString();
                }

                tbTitle.Text = contentItem.Title;

                if (contentItem.ContentChannel.ContentControlType == ContentControlType.HtmlEditor)
                {
                    ceContent.Visible   = false;
                    htmlContent.Visible = true;
                    htmlContent.Text    = contentItem.Content;
                    htmlContent.MergeFields.Clear();
                    htmlContent.MergeFields.Add("GlobalAttribute");
                    htmlContent.MergeFields.Add("Rock.Model.ContentChannelItem|Current Item");
                    htmlContent.MergeFields.Add("Rock.Model.Person|Current Person");
                    htmlContent.MergeFields.Add("Campuses");
                    htmlContent.MergeFields.Add("RockVersion");

                    if (!string.IsNullOrWhiteSpace(contentItem.ContentChannel.RootImageDirectory))
                    {
                        htmlContent.DocumentFolderRoot = contentItem.ContentChannel.RootImageDirectory;
                        htmlContent.ImageFolderRoot    = contentItem.ContentChannel.RootImageDirectory;
                    }
                }
                else
                {
                    htmlContent.Visible = false;
                    ceContent.Visible   = true;
                    ceContent.Text      = contentItem.Content;
                    ceContent.MergeFields.Clear();
                    ceContent.MergeFields.Add("GlobalAttribute");
                    ceContent.MergeFields.Add("Rock.Model.ContentChannelItem|Current Item");
                    ceContent.MergeFields.Add("Rock.Model.Person|Current Person");
                    ceContent.MergeFields.Add("Campuses");
                    ceContent.MergeFields.Add("RockVersion");
                }

                dtpStart.SelectedDateTime  = contentItem.StartDateTime;
                dtpStart.Label             = contentItem.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange ? "Start" : "Active";
                dtpExpire.SelectedDateTime = contentItem.ExpireDateTime;
                dtpExpire.Visible          = contentItem.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange;
                nbPriority.Text            = contentItem.Priority.ToString();
                nbPriority.Visible         = !contentItem.ContentChannelType.DisablePriority;

                contentItem.LoadAttributes();
                phAttributes.Controls.Clear();
                Rock.Attribute.Helper.AddEditControls(contentItem, phAttributes, true, BlockValidationGroup);
            }
            else
            {
                nbEditModeMessage.Text = EditModeMessage.NotAuthorizedToEdit(ContentChannelItem.FriendlyTypeName);
                pnlEditDetails.Visible = false;
            }
        }
Beispiel #12
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);
        }
        /// <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);
        }
Beispiel #14
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);
        }
Beispiel #15
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);
        }
Beispiel #16
0
        /// <summary>
        /// Shows the view.
        /// </summary>
        private void ShowView()
        {
            int?outputCacheDuration = GetAttributeValue("OutputCacheDuration").AsIntegerOrNull();

            string outputContents = null;
            string pageTitle      = null;

            var contentChannelItemParameterValue = GetContentChannelItemParameterValue();

            if (string.IsNullOrEmpty(contentChannelItemParameterValue))
            {
                // No item specified, so don't show anything
                ShowNoDataFound();
                return;
            }

            string outputCacheKey    = OUTPUT_CACHE_KEY_PREFIX + contentChannelItemParameterValue;
            string pageTitleCacheKey = PAGETITLE_CACHE_KEY_PREFIX + contentChannelItemParameterValue;

            if (outputCacheDuration.HasValue && outputCacheDuration.Value > 0)
            {
                outputContents = GetCacheItem(outputCacheKey) as string;
                pageTitle      = GetCacheItem(pageTitleCacheKey) as string;
            }

            bool isMergeContentEnabled = GetAttributeValue("MergeContent").AsBoolean();
            bool setPageTitle          = GetAttributeValue("SetPageTitle").AsBoolean();

            if (outputContents == null)
            {
                ContentChannelItem contentChannelItem = GetContentChannelItem(contentChannelItemParameterValue);

                if (contentChannelItem == null)
                {
                    ShowNoDataFound();
                    return;
                }

                if (contentChannelItem.ContentChannel.RequiresApproval)
                {
                    var statuses = new List <ContentChannelItemStatus>();
                    foreach (var status in (GetAttributeValue("Status") ?? "2").Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                    {
                        var statusEnum = status.ConvertToEnumOrNull <ContentChannelItemStatus>();
                        if (statusEnum != null)
                        {
                            statuses.Add(statusEnum.Value);
                        }
                    }

                    if (!statuses.Contains(contentChannelItem.Status))
                    {
                        ShowNoDataFound();
                        return;
                    }
                }

                // if a Channel was specified, verify that the ChannelItem is part of the channel
                var channelGuid = this.GetAttributeValue("ContentChannel").AsGuidOrNull();
                if (channelGuid.HasValue)
                {
                    var channel = ContentChannelCache.Get(channelGuid.Value);
                    if (channel != null)
                    {
                        if (contentChannelItem.ContentChannelId != channel.Id)
                        {
                            ShowNoDataFound();
                            return;
                        }
                    }
                }

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

                // Merge content and attribute fields if block is configured to do so.
                if (isMergeContentEnabled)
                {
                    var itemMergeFields = new Dictionary <string, object>(commonMergeFields);

                    var enabledCommands = GetAttributeValue("EnabledLavaCommands");

                    itemMergeFields.AddOrReplace("Item", contentChannelItem);
                    contentChannelItem.Content = contentChannelItem.Content.ResolveMergeFields(itemMergeFields, enabledCommands);
                    contentChannelItem.LoadAttributes();
                    foreach (var attributeValue in contentChannelItem.AttributeValues)
                    {
                        attributeValue.Value.Value = attributeValue.Value.Value.ResolveMergeFields(itemMergeFields, enabledCommands);
                    }
                }

                var mergeFields = new Dictionary <string, object>(commonMergeFields);

                mergeFields.Add("RockVersion", Rock.VersionInfo.VersionInfo.GetRockProductVersionNumber());
                mergeFields.Add("Item", contentChannelItem);
                int detailPage = 0;
                var page       = PageCache.Get(GetAttributeValue("DetailPage"));
                if (page != null)
                {
                    detailPage = page.Id;
                }

                mergeFields.Add("DetailPage", detailPage);

                string metaDescriptionValue = GetMetaValueFromAttribute(this.GetAttributeValue("MetaDescriptionAttribute"), contentChannelItem);

                if (!string.IsNullOrWhiteSpace(metaDescriptionValue))
                {
                    // remove default meta description
                    RockPage.Header.Description = metaDescriptionValue.SanitizeHtml(true);
                }

                AddHtmlMeta("og:type", this.GetAttributeValue("OpenGraphType"));
                AddHtmlMeta("og:title", GetMetaValueFromAttribute(this.GetAttributeValue("OpenGraphTitleAttribute"), contentChannelItem));
                AddHtmlMeta("og:description", GetMetaValueFromAttribute(this.GetAttributeValue("OpenGraphDescriptionAttribute"), contentChannelItem));
                AddHtmlMeta("og:image", GetMetaValueFromAttribute(this.GetAttributeValue("OpenGraphImageAttribute"), contentChannelItem));
                AddHtmlMeta("twitter:title", GetMetaValueFromAttribute(this.GetAttributeValue("TwitterTitleAttribute"), contentChannelItem));
                AddHtmlMeta("twitter:description", GetMetaValueFromAttribute(this.GetAttributeValue("TwitterDescriptionAttribute"), contentChannelItem));
                AddHtmlMeta("twitter:image", GetMetaValueFromAttribute(this.GetAttributeValue("TwitterImageAttribute"), contentChannelItem));
                var twitterCard = this.GetAttributeValue("TwitterCard");
                if (twitterCard.IsNotNullOrWhiteSpace() && twitterCard != "none")
                {
                    AddHtmlMeta("twitter:card", twitterCard);
                }
                string lavaTemplate        = this.GetAttributeValue("LavaTemplate");
                string enabledLavaCommands = this.GetAttributeValue("EnabledLavaCommands");
                outputContents = lavaTemplate.ResolveMergeFields(mergeFields, enabledLavaCommands);

                if (setPageTitle)
                {
                    pageTitle = contentChannelItem.Title;
                }

                if (outputCacheDuration.HasValue && outputCacheDuration.Value > 0)
                {
                    string cacheTags = GetAttributeValue("CacheTags") ?? string.Empty;
                    var    cacheKeys = GetCacheItem(CACHEKEYS_CACHE_KEY) as HashSet <string> ?? new HashSet <string>();
                    cacheKeys.Add(outputCacheKey);
                    cacheKeys.Add(pageTitleCacheKey);
                    AddCacheItem(CACHEKEYS_CACHE_KEY, cacheKeys, TimeSpan.MaxValue, cacheTags);
                    AddCacheItem(outputCacheKey, outputContents, outputCacheDuration.Value, cacheTags);

                    if (pageTitle != null)
                    {
                        AddCacheItem(pageTitleCacheKey, pageTitle, outputCacheDuration.Value, cacheTags);
                    }
                }
            }

            lContentOutput.Text = outputContents;

            if (setPageTitle && pageTitle != null)
            {
                RockPage.PageTitle    = pageTitle;
                RockPage.BrowserTitle = string.Format("{0} | {1}", pageTitle, RockPage.Site.Name);
                RockPage.Header.Title = string.Format("{0} | {1}", pageTitle, RockPage.Site.Name);

                var pageBreadCrumb = RockPage.PageReference.BreadCrumbs.FirstOrDefault();
                if (pageBreadCrumb != null)
                {
                    pageBreadCrumb.Name = RockPage.PageTitle;
                }
            }

            LaunchWorkflow();

            LaunchInteraction();
        }
Beispiel #17
0
        /// <summary>
        /// The PropertyFilter checks for it's property/attribute list in a cached items object before recreating 
        /// them using reflection and loading of generic attributes. Because of this, we're going to load them here
        /// and exclude some properties and add additional attributes specific to the channel type, and then save
        /// list to same cached object so that property filter lists our collection of properties/attributes
        /// instead.
        /// </summary>
        private List<Rock.Reporting.EntityField> HackEntityFields( ContentChannel channel, RockContext rockContext )
        {
            if ( channel != null )
            {
                var entityTypeCache = EntityTypeCache.Read( ITEM_TYPE_NAME );
                if ( entityTypeCache != null )
                {
                    var entityType = entityTypeCache.GetEntityType();

                    HttpContext.Current.Items.Remove( string.Format( "EntityHelper:GetEntityFields:{0}", entityType.FullName ) );
                    var entityFields = Rock.Reporting.EntityHelper.GetEntityFields( entityType );

                    if ( entityFields != null )
                    {
                        // Remove the status field
                        var ignoreFields = new List<string>();
                        ignoreFields.Add( "ContentChannelId" );
                        ignoreFields.Add( "Status" );

                        entityFields = entityFields.Where( f => !ignoreFields.Contains( f.Name ) ).ToList();

                        // Add any additional attributes that are specific to channel/type
                        var item = new ContentChannelItem();
                        item.ContentChannel = channel;
                        item.ContentChannelId = channel.Id;
                        item.ContentChannelType = channel.ContentChannelType;
                        item.ContentChannelTypeId = channel.ContentChannelTypeId;
                        item.LoadAttributes( rockContext );
                        foreach ( var attribute in item.Attributes
                            .Where( a =>
                                a.Value.EntityTypeQualifierColumn != "" &&
                                a.Value.EntityTypeQualifierValue != "" )
                            .Select( a => a.Value ) )
                        {
                            Rock.Reporting.EntityHelper.AddEntityFieldForAttribute( entityFields, attribute );
                        }

                        // Re-sort fields
                        int index = 0;
                        var sortedFields = new List<Rock.Reporting.EntityField>();
                        foreach ( var entityProperty in entityFields.OrderBy( p => p.Title ).ThenBy( p => p.Name ) )
                        {
                            entityProperty.Index = index;
                            index++;
                            sortedFields.Add( entityProperty );
                        }

                        // Save new fields to cache ( which report field will use instead of reading them again )
                        HttpContext.Current.Items[string.Format( "EntityHelper:GetEntityFields:{0}", entityType.FullName )] = sortedFields;
                    }

                    return entityFields;
                }
            }

            return null;
        }
        private void BindChildItemsGrid( ContentChannelItem contentItem )
        {
            bool isFiltered = false;
            var items = GetChildItems( contentItem, out isFiltered );

            if ( contentItem.ContentChannel.ChildItemsManuallyOrdered && !isFiltered )
            {
                gChildItems.Columns[0].Visible = true;
                gChildItems.AllowSorting = false;
                items = items.OrderBy( i => i.Order ).ToList();
            }
            else
            {
                gChildItems.Columns[0].Visible = false;
                gChildItems.AllowSorting = true;

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

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

            gChildItems.DataSource = items.Select( i => new
            {
                i.Id,
                i.Guid,
                i.Title,
                i.StartDateTime,
                ExpireDateTime = i.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange ? i.ExpireDateTime : (DateTime?)null,
                Priority = i.ContentChannelType.DisablePriority ? (int?)null : (int?)i.Priority,
                Status = i.ContentChannel.RequiresApproval ? DisplayStatus( i.Status ) : string.Empty,
                CreatedBy = i.CreatedByPersonAlias != null && i.CreatedByPersonAlias.Person != null ? i.CreatedByPersonAlias.Person.NickName + " " + i.CreatedByPersonAlias.Person.LastName : ""
            } ).ToList();

            gChildItems.DataBind();
        }
        private void BindParentItemsGrid( ContentChannelItem contentItem )
        {
            var items = GetParentItems( contentItem );

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

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

            gParentItems.DataSource = items.Select( i => new
            {
                i.Id,
                i.Guid,
                i.Title,
                i.StartDateTime,
                ExpireDateTime = i.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange ? i.ExpireDateTime : (DateTime?)null,
                Priority = i.ContentChannelType.DisablePriority ? (int?)null : (int?)i.Priority,
                Status = i.ContentChannel.RequiresApproval ? DisplayStatus( i.Status ) : string.Empty,
                CreatedBy = i.CreatedByPersonAlias != null && i.CreatedByPersonAlias.Person != null ? i.CreatedByPersonAlias.Person.NickName + " " + i.CreatedByPersonAlias.Person.LastName : ""
            } ).ToList();
            gParentItems.DataBind();
        }
Beispiel #20
0
        public void ShowDetail(int contentItemId, int?contentChannelId)
        {
            bool canEdit = IsUserAuthorized(Authorization.EDIT);

            hfId.Value        = contentItemId.ToString();
            hfChannelId.Value = contentChannelId.HasValue ? contentChannelId.Value.ToString() : string.Empty;

            ContentChannelItem contentItem = GetContentItem();

            if (contentItem == null)
            {
                // this block requires a valid ContentChannel in order to know which channel the ContentChannelItem belongs to, so if ContentChannel wasn't specified, don't show this block
                this.Visible = false;
                return;
            }

            if (contentItem.ContentChannel.IsTaggingEnabled)
            {
                taglTags.EntityTypeId = EntityTypeCache.Read(typeof(ContentChannelItem)).Id;
                taglTags.CategoryGuid = (contentItem.ContentChannel != null && contentItem.ContentChannel.ItemTagCategory != null) ?
                                        contentItem.ContentChannel.ItemTagCategory.Guid : (Guid?)null;
                taglTags.EntityGuid = contentItem.Guid;
                taglTags.DelaySave  = true;
                taglTags.GetTagValues(CurrentPersonId);
                rcwTags.Visible = true;
            }
            else
            {
                rcwTags.Visible = false;
            }

            pdAuditDetails.SetEntity(contentItem, ResolveRockUrl("~"));

            if (contentItem != null &&
                contentItem.ContentChannelType != null &&
                contentItem.ContentChannel != null &&
                (canEdit || contentItem.IsAuthorized(Authorization.EDIT, CurrentPerson)))
            {
                hfIsDirty.Value = "false";

                ShowApproval(contentItem);

                pnlEditDetails.Visible = true;

                // show/hide the delete button
                lbDelete.Visible = (GetAttributeValue("ShowDeleteButton").AsBoolean() && contentItem.Id != 0);

                hfId.Value        = contentItem.Id.ToString();
                hfChannelId.Value = contentItem.ContentChannelId.ToString();

                string cssIcon = contentItem.ContentChannel.IconCssClass;
                if (string.IsNullOrWhiteSpace(cssIcon))
                {
                    cssIcon = "fa fa-certificate";
                }
                lIcon.Text = string.Format("<i class='{0}'></i>", cssIcon);

                string title = contentItem.Id > 0 ?
                               ActionTitle.Edit(ContentChannelItem.FriendlyTypeName) :
                               ActionTitle.Add(ContentChannelItem.FriendlyTypeName);
                lTitle.Text = title.FormatAsHtmlTitle();

                hlContentChannel.Text = contentItem.ContentChannel.Name;

                hlStatus.Visible = contentItem.ContentChannel.RequiresApproval && !contentItem.ContentChannelType.DisableStatus;

                hlStatus.Text = contentItem.Status.ConvertToString();

                hlStatus.LabelType = LabelType.Default;
                switch (contentItem.Status)
                {
                case ContentChannelItemStatus.Approved: hlStatus.LabelType = LabelType.Success; break;

                case ContentChannelItemStatus.Denied: hlStatus.LabelType = LabelType.Danger; break;

                case ContentChannelItemStatus.PendingApproval: hlStatus.LabelType = LabelType.Warning; break;

                default: hlStatus.LabelType = LabelType.Default; break;
                }

                var statusDetail = new System.Text.StringBuilder();
                if (contentItem.ApprovedByPersonAlias != null && contentItem.ApprovedByPersonAlias.Person != null)
                {
                    statusDetail.AppendFormat("by {0} ", contentItem.ApprovedByPersonAlias.Person.FullName);
                }
                if (contentItem.ApprovedDateTime.HasValue)
                {
                    statusDetail.AppendFormat("on {0} at {1}", contentItem.ApprovedDateTime.Value.ToShortDateString(),
                                              contentItem.ApprovedDateTime.Value.ToShortTimeString());
                }
                hlStatus.ToolTip = statusDetail.ToString();

                tbTitle.Text = contentItem.Title;

                htmlContent.Visible = !contentItem.ContentChannelType.DisableContentField;
                htmlContent.Text    = contentItem.Content;
                htmlContent.MergeFields.Clear();
                htmlContent.MergeFields.Add("GlobalAttribute");
                htmlContent.MergeFields.Add("Rock.Model.ContentChannelItem|Current Item");
                htmlContent.MergeFields.Add("Rock.Model.Person|Current Person");
                htmlContent.MergeFields.Add("Campuses");
                htmlContent.MergeFields.Add("RockVersion");

                if (!string.IsNullOrWhiteSpace(contentItem.ContentChannel.RootImageDirectory))
                {
                    htmlContent.DocumentFolderRoot = contentItem.ContentChannel.RootImageDirectory;
                    htmlContent.ImageFolderRoot    = contentItem.ContentChannel.RootImageDirectory;
                }

                htmlContent.StartInCodeEditorMode = contentItem.ContentChannel.ContentControlType == ContentControlType.CodeEditor;

                if (contentItem.ContentChannelType.IncludeTime)
                {
                    dpStart.Visible   = false;
                    dpExpire.Visible  = false;
                    dtpStart.Visible  = contentItem.ContentChannelType.DateRangeType != ContentChannelDateType.NoDates;
                    dtpExpire.Visible = contentItem.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange;

                    dtpStart.SelectedDateTime  = contentItem.StartDateTime;
                    dtpStart.Label             = contentItem.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange ? "Start" : "Active";
                    dtpExpire.SelectedDateTime = contentItem.ExpireDateTime;
                }
                else
                {
                    dpStart.Visible   = contentItem.ContentChannelType.DateRangeType != ContentChannelDateType.NoDates;
                    dpExpire.Visible  = contentItem.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange;
                    dtpStart.Visible  = false;
                    dtpExpire.Visible = false;

                    dpStart.SelectedDate  = contentItem.StartDateTime.Date;
                    dpStart.Label         = contentItem.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange ? "Start" : "Active";
                    dpExpire.SelectedDate = contentItem.ExpireDateTime.HasValue ? contentItem.ExpireDateTime.Value.Date : (DateTime?)null;
                }

                nbPriority.Text    = contentItem.Priority.ToString();
                nbPriority.Visible = !contentItem.ContentChannelType.DisablePriority;

                contentItem.LoadAttributes();
                phAttributes.Controls.Clear();
                Rock.Attribute.Helper.AddEditControls(contentItem, phAttributes, true, BlockValidationGroup, 2);

                phOccurrences.Controls.Clear();
                foreach (var occurrence in contentItem.EventItemOccurrences
                         .Where(o => o.EventItemOccurrence != null)
                         .Select(o => o.EventItemOccurrence))
                {
                    var qryParams = new Dictionary <string, string> {
                        { "EventItemOccurrenceId", occurrence.Id.ToString() }
                    };
                    string url          = LinkedPageUrl("EventOccurrencePage", qryParams);
                    var    hlOccurrence = new HighlightLabel();
                    hlOccurrence.LabelType = LabelType.Info;
                    hlOccurrence.ID        = string.Format("hlOccurrence_{0}", occurrence.Id);
                    hlOccurrence.Text      = string.Format("<a href='{0}'><i class='fa fa-calendar-o'></i> {1}</a>", url, occurrence.ToString());
                    phOccurrences.Controls.Add(hlOccurrence);
                }

                bool canHaveChildren = contentItem.Id > 0 && contentItem.ContentChannel.ChildContentChannels.Any();
                bool canHaveParents  = contentItem.Id > 0 && contentItem.ContentChannel.ParentContentChannels.Any();

                pnlChildrenParents.Visible = canHaveChildren || canHaveParents;
                phPills.Visible            = canHaveChildren && canHaveParents;
                if (canHaveChildren && !canHaveParents)
                {
                    lChildrenParentsTitle.Text = "<i class='fa fa-arrow-circle-down'></i> Child Items";
                }

                if (!canHaveChildren && canHaveParents)
                {
                    lChildrenParentsTitle.Text = "<i class='fa fa-arrow-circle-up'></i> Parent Items";
                    divParentItems.AddCssClass("active");
                }

                if (canHaveChildren)
                {
                    BindChildItemsGrid(contentItem);
                }

                if (canHaveParents)
                {
                    BindParentItemsGrid(contentItem);
                }
            }
            else
            {
                nbEditModeMessage.Text = EditModeMessage.NotAuthorizedToEdit(ContentChannelItem.FriendlyTypeName);
                pnlEditDetails.Visible = false;
            }
        }
        private List<ContentChannelItem> GetChildItems( ContentChannelItem contentItem, out bool isFiltered )
        {
            isFiltered = false;
            var items = new List<ContentChannelItem>();

            foreach ( var item in contentItem.ChildItems.Select( a => a.ChildContentChannelItem ).ToList() )
            {
                if ( item.IsAuthorized( Authorization.VIEW, CurrentPerson ) )
                {
                    items.Add( item );
                }
                else
                {
                    isFiltered = true;
                }
            }
            return items;
        }
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event.
        /// </summary>
        /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

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

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

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

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

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

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

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

                    PageNumber = PageNumber ?? 1;

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

            divCalendars.Attributes["class"]       = GetDivClass(1);
            divCalendar.Attributes["class"]        = GetDivClass(2);
            divCalendarItem.Attributes["class"]    = GetDivClass(3);
            divEventOccurrence.Attributes["class"] = GetDivClass(4);
            divContentItem.Attributes["class"]     = GetDivClass(5);
        }
        /// <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;
        }
Beispiel #24
0
        private void ShowView()
        {
            var rockContext = new RockContext();

            var missingConfiguration = new List <string>();

            var contentChannelGuid = GetAttributeValue("ContentChannel").AsGuidOrNull();

            if (!contentChannelGuid.HasValue)
            {
                missingConfiguration.Add("The content channel has not yet been configured.");
            }

            var blockTitleTemplate = GetAttributeValue("BlockTitleTemplate");

            if (blockTitleTemplate.IsNullOrWhiteSpace())
            {
                missingConfiguration.Add("The block title template appears to be blank.");
            }

            var bodyTemplate = GetAttributeValue("BodyTemplate");

            if (bodyTemplate.IsNullOrWhiteSpace())
            {
                missingConfiguration.Add("The body template appears to be blank.");
            }

            if (missingConfiguration.Count > 0)
            {
                StringBuilder message = new StringBuilder();
                message.Append("Currently, there are some missing configuration items. These items are summarized below: <ul>");

                foreach (var configurationItem in missingConfiguration)
                {
                    message.Append(string.Format("<li>{0}</li>", configurationItem));
                }

                message.Append("</ul>");

                nbMessages.Text = message.ToString();
                nbMessages.NotificationBoxType = NotificationBoxType.Validation;
                return;
            }

            var    enabledLavaCommands    = GetAttributeValue("EnabledLavaCommands");
            var    blockTitleIconCssClass = GetAttributeValue("BlockTitleIconCssClass");
            var    metricValueCount       = GetAttributeValue("MetricValueCount").AsInteger();
            var    cacheDuration          = GetAttributeValue("CacheDuration").AsInteger();
            string cacheTags = GetAttributeValue("CacheTags") ?? string.Empty;

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

            var cacheKey = "internal-commmunication-view-" + this.BlockId.ToString();

            ContentChannelItem  contentChannelItem = null;
            List <MetricResult> metrics            = null;
            var showPrev = false;

            CachedBlockData cachedItem = null;

            if (cacheDuration > 0 && _currentPage == 0)
            {
                var serializedCachedItem = RockCache.Get(cacheKey, true);
                if (serializedCachedItem != null &&
                    serializedCachedItem is string &&
                    !string.IsNullOrWhiteSpace(( string )serializedCachedItem))
                {
                    cachedItem = (( string )serializedCachedItem).FromJsonOrNull <CachedBlockData>();
                }
            }

            if (cachedItem != null)
            {
                contentChannelItem = cachedItem.ContentChannelItem;
                metrics            = cachedItem.Metrics;
                showPrev           = cachedItem.ShowPrev;
            }
            else
            {
                var channel = ContentChannelCache.Get(contentChannelGuid.Value);

                // Get latest content channel items, get two so we know if a previous one exists for paging
                var contentChannelItemsQry = new ContentChannelItemService(rockContext)
                                             .Queryable()
                                             .AsNoTracking()
                                             .Where(i => i.ContentChannel.Guid == contentChannelGuid &&
                                                    i.Status == ContentChannelItemStatus.Approved &&
                                                    i.StartDateTime <= RockDateTime.Now);

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

                var contentChannelItems = contentChannelItemsQry.OrderByDescending(i => i.StartDateTime)
                                          .Take(2)
                                          .Skip(_currentPage)
                                          .ToList();

                if (contentChannelItems.IsNull() || contentChannelItems.Count == 0)
                {
                    nbMessages.Text = "It appears that there are no active communications to display for this content channel.";
                    nbMessages.NotificationBoxType = NotificationBoxType.Info;
                    return;
                }

                contentChannelItem = contentChannelItems.First();
                showPrev           = (contentChannelItems.Count > 1);

                // Get metrics
                var metricCategories = Rock.Attribute.MetricCategoriesFieldAttribute.GetValueAsGuidPairs(GetAttributeValue("Metrics"));

                var metricGuids = metricCategories.Select(a => a.MetricGuid).ToList();
                metrics = new MetricService(rockContext).GetByGuids(metricGuids)
                          .Select(m => new MetricResult
                {
                    Id              = m.Id,
                    Title           = m.Title,
                    Description     = m.Description,
                    IconCssClass    = m.IconCssClass,
                    UnitsLabel      = m.YAxisLabel,
                    LastRunDateTime = m.MetricValues.OrderByDescending(v => v.MetricValueDateTime).Select(v => v.MetricValueDateTime).FirstOrDefault(),
                    LastValue       = m.MetricValues.OrderByDescending(v => v.MetricValueDateTime).Select(v => v.YValue).FirstOrDefault()
                }).ToList();

                // Get metric values for each metric if requested
                if (metricValueCount > 0)
                {
                    foreach (var metric in metrics)
                    {
                        metric.MetricValues = new MetricValueService(rockContext).Queryable()
                                              .Where(v => v.MetricId == metric.Id)
                                              .OrderByDescending(v => v.MetricValueDateTime)
                                              .Select(v => new MetricValue
                        {
                            DateTime = v.MetricValueDateTime,
                            Value    = v.YValue,
                            Note     = v.Note
                        })
                                              .Take(metricValueCount)
                                              .ToList();
                    }
                }

                // Set Cache
                if (cacheDuration > 0 && _currentPage == 0)
                {
                    var cachedData = new CachedBlockData();
                    cachedData.ContentChannelItem = contentChannelItem.Clone(false);
                    cachedData.ShowPrev           = showPrev;
                    cachedData.Metrics            = metrics;

                    var expiration = RockDateTime.Now.AddSeconds(cacheDuration);
                    RockCache.AddOrUpdate(cacheKey, string.Empty, cachedData.ToJson(), expiration, cacheTags);
                }
            }

            mergeFields.Add("Item", contentChannelItem);
            mergeFields.Add("Metrics", metrics);

            lBlockTitleIcon.Text = string.Format("<i class='{0}'></i>", blockTitleIconCssClass);
            lBlockTitle.Text     = blockTitleTemplate.ResolveMergeFields(mergeFields, enabledLavaCommands);

            lBlockBody.Text = bodyTemplate.ResolveMergeFields(mergeFields, enabledLavaCommands);

            // Determine if we can page backwards
            btnPrevious.Visible = showPrev;

            // Determine if we can page forwards
            btnNext.Visible = (_currentPage > 0);

            // Set the current page hidden field
            hfCurrentPage.Value = _currentPage.ToString();
        }
        private List<ContentChannelItem> GetParentItems( ContentChannelItem contentItem )
        {
            var items = new List<ContentChannelItem>();

            foreach ( var item in contentItem.ParentItems.Select( a => a.ContentChannelItem ).ToList() )
            {
                if ( item.IsAuthorized( Authorization.VIEW, CurrentPerson ) )
                {
                    items.Add( item );
                }
            }

            return items;
        }
        private void ShowApproval( ContentChannelItem contentItem )
        {
            if ( contentItem != null &&
                contentItem.ContentChannel != null &&
                contentItem.ContentChannel.RequiresApproval )
            {

                if ( contentItem.IsAuthorized( Authorization.APPROVE, CurrentPerson ) )
                {
                    pnlStatus.Visible = true;

                    PendingCss = contentItem.Status == ContentChannelItemStatus.PendingApproval ? "btn-default active" : "btn-default";
                    ApprovedCss = contentItem.Status == ContentChannelItemStatus.Approved ? "btn-success active" : "btn-default";
                    DeniedCss = contentItem.Status == ContentChannelItemStatus.Denied ? "btn-danger active" : "btn-default";
                }
                else
                {
                    pnlStatus.Visible = false;
                }

                hfStatus.Value = contentItem.Status.ConvertToInt().ToString();
            }
            else
            {
                hfStatus.Value = ContentChannelItemStatus.Approved.ToString();
                pnlStatus.Visible = false;
                divStatus.Visible = false;
            }
        }
Beispiel #27
0
        protected void ShowDetail(int contentItemId)
        {
            var rockContext = new RockContext();
            var contentItem = new ContentChannelItem();

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

            if (contentItem == null || contentItem.Id == 0)
            {
                pnlVimeoSync.Visible  = false;
                pnlNewDetails.Visible = false;

                if (_contentChannelId > 0)
                {
                    contentItem = new ContentChannelItemService(rockContext)
                                  .Queryable("ContentChannel,ContentChannelType")
                                  .FirstOrDefault(t => t.ContentChannelId == _contentChannelId);

                    if (contentItem != null && contentItem.Attributes == null)
                    {
                        contentItem.LoadAttributes();
                    }

                    if (contentItem != null)
                    {
                        var attributeKeys = contentItem.Attributes.Select(a => a.Key).ToList();
                        if (!string.IsNullOrWhiteSpace(_vimeoIdKey) && attributeKeys.Contains(_vimeoIdKey))
                        {
                            pnlNewDetails.Visible = true;
                            pnlVimeoSync.Visible  = true;
                            litPreview.Visible    = false;

                            SetupSyncBoxes();
                        }
                    }
                }
            }
            else
            {
                if (contentItem.Attributes == null)
                {
                    contentItem.LoadAttributes();
                }
                _vimeoId = contentItem.GetAttributeValue(_vimeoIdKey).AsInteger();
                if (_vimeoId == 0)
                {
                    pnlVimeoSync.Visible = false;
                    var attributeKeys = contentItem.Attributes.Select(a => a.Key).ToList();
                    if (!string.IsNullOrWhiteSpace(_vimeoIdKey) && attributeKeys.Contains(_vimeoIdKey))
                    {
                        pnlNewDetails.Visible = true;
                        pnlVimeoSync.Visible  = true;
                        litPreview.Visible    = false;

                        SetupSyncBoxes();
                    }
                }
                else
                {
                    SetupSyncBoxes();

                    if (GetAttributeValue("Preview").AsBoolean())
                    {
                        litPreview.Text    = string.Format("<div class=\"{0}\"><div class=\"embed-responsive embed-responsive-16by9\"><iframe class=\"embed-responsive-item\" src=\"https://player.vimeo.com/video/{1}\"></iframe></div></div>", GetAttributeValue("PreviewWidth"), _vimeoId);
                        litPreview.Visible = true;
                    }
                    else
                    {
                        litPreview.Visible = false;
                    }
                }
            }

            if (contentItem != null)
            {
                dpStart.Label = contentItem.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange ? "Start" : "Active";
            }
        }
Beispiel #28
0
        public void ShowDetail(int contentItemId, int?contentChannelId)
        {
            bool canEdit = IsUserAuthorized(Authorization.EDIT);

            hfId.Value        = contentItemId.ToString();
            hfChannelId.Value = contentChannelId.HasValue ? contentChannelId.Value.ToString() : string.Empty;

            ContentChannelItem contentItem = GetContentItem();

            if (contentItem != null &&
                contentItem.ContentChannelType != null &&
                contentItem.ContentChannel != null &&
                (canEdit || contentItem.IsAuthorized(Authorization.EDIT, CurrentPerson)))
            {
                ShowApproval(contentItem);

                pnlEditDetails.Visible = true;

                hfId.Value        = contentItem.Id.ToString();
                hfChannelId.Value = contentItem.ContentChannelId.ToString();

                string cssIcon = contentItem.ContentChannel.IconCssClass;
                if (string.IsNullOrWhiteSpace(cssIcon))
                {
                    cssIcon = "fa fa-certificate";
                }
                lIcon.Text = string.Format("<i class='{0}'></i>", cssIcon);

                string title = contentItem.Id > 0 ?
                               ActionTitle.Edit(ContentChannelItem.FriendlyTypeName) :
                               ActionTitle.Add(ContentChannelItem.FriendlyTypeName);
                lTitle.Text = title.FormatAsHtmlTitle();

                hlContentChannel.Text = contentItem.ContentChannel.Name;
                hlStatus.Text         = contentItem.Status.ConvertToString();

                hlStatus.LabelType = LabelType.Default;
                switch (contentItem.Status)
                {
                case ContentChannelItemStatus.Approved: hlStatus.LabelType = LabelType.Success; break;

                case ContentChannelItemStatus.Denied: hlStatus.LabelType = LabelType.Danger; break;

                case ContentChannelItemStatus.PendingApproval: hlStatus.LabelType = LabelType.Warning; break;

                default: hlStatus.LabelType = LabelType.Default; break;
                }

                var statusDetail = new System.Text.StringBuilder();
                if (contentItem.ApprovedByPersonAlias != null && contentItem.ApprovedByPersonAlias.Person != null)
                {
                    statusDetail.AppendFormat("by {0} ", contentItem.ApprovedByPersonAlias.Person.FullName);
                }
                if (contentItem.ApprovedDateTime.HasValue)
                {
                    statusDetail.AppendFormat("on {0} at {1}", contentItem.ApprovedDateTime.Value.ToShortDateString(),
                                              contentItem.ApprovedDateTime.Value.ToShortTimeString());
                }
                hlStatus.ToolTip = statusDetail.ToString();

                tbTitle.Text = contentItem.Title;

                if (contentItem.ContentChannel.ContentControlType == ContentControlType.HtmlEditor)
                {
                    ceContent.Visible   = false;
                    htmlContent.Visible = true;
                    htmlContent.Text    = contentItem.Content;
                    htmlContent.MergeFields.Clear();
                    htmlContent.MergeFields.Add("GlobalAttribute");
                    htmlContent.MergeFields.Add("Rock.Model.ContentChannelItem|Current Item");
                    htmlContent.MergeFields.Add("Rock.Model.Person|Current Person");
                    htmlContent.MergeFields.Add("Campuses");
                    htmlContent.MergeFields.Add("RockVersion");

                    if (!string.IsNullOrWhiteSpace(contentItem.ContentChannel.RootImageDirectory))
                    {
                        htmlContent.DocumentFolderRoot = contentItem.ContentChannel.RootImageDirectory;
                        htmlContent.ImageFolderRoot    = contentItem.ContentChannel.RootImageDirectory;
                    }
                }
                else
                {
                    htmlContent.Visible = false;
                    ceContent.Visible   = true;
                    ceContent.Text      = contentItem.Content;
                    ceContent.MergeFields.Clear();
                    ceContent.MergeFields.Add("GlobalAttribute");
                    ceContent.MergeFields.Add("Rock.Model.ContentChannelItem|Current Item");
                    ceContent.MergeFields.Add("Rock.Model.Person|Current Person");
                    ceContent.MergeFields.Add("Campuses");
                    ceContent.MergeFields.Add("RockVersion");
                }

                if (contentItem.ContentChannelType.IncludeTime)
                {
                    dpStart.Visible   = false;
                    dpExpire.Visible  = false;
                    dtpStart.Visible  = true;
                    dtpExpire.Visible = contentItem.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange;

                    dtpStart.SelectedDateTime  = contentItem.StartDateTime;
                    dtpStart.Label             = contentItem.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange ? "Start" : "Active";
                    dtpExpire.SelectedDateTime = contentItem.ExpireDateTime;
                }
                else
                {
                    dpStart.Visible   = true;
                    dpExpire.Visible  = contentItem.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange;
                    dtpStart.Visible  = false;
                    dtpExpire.Visible = false;

                    dpStart.SelectedDate  = contentItem.StartDateTime.Date;
                    dpStart.Label         = contentItem.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange ? "Start" : "Active";
                    dpExpire.SelectedDate = contentItem.ExpireDateTime.HasValue ? contentItem.ExpireDateTime.Value.Date : (DateTime?)null;
                }

                nbPriority.Text    = contentItem.Priority.ToString();
                nbPriority.Visible = !contentItem.ContentChannelType.DisablePriority;

                contentItem.LoadAttributes();
                phAttributes.Controls.Clear();
                Rock.Attribute.Helper.AddEditControls(contentItem, phAttributes, true, BlockValidationGroup);

                phOccurrences.Controls.Clear();
                foreach (var occurrence in contentItem.EventItemOccurrences
                         .Where(o => o.EventItemOccurrence != null)
                         .Select(o => o.EventItemOccurrence))
                {
                    var qryParams = new Dictionary <string, string> {
                        { "EventItemOccurrenceId", occurrence.Id.ToString() }
                    };
                    string url          = LinkedPageUrl("EventOccurrencePage", qryParams);
                    var    hlOccurrence = new HighlightLabel();
                    hlOccurrence.LabelType = LabelType.Info;
                    hlOccurrence.ID        = string.Format("hlOccurrence_{0}", occurrence.Id);
                    hlOccurrence.Text      = string.Format("<a href='{0}'>{1}</a>", url, occurrence.ToString());
                    phOccurrences.Controls.Add(hlOccurrence);
                }
            }
            else
            {
                nbEditModeMessage.Text = EditModeMessage.NotAuthorizedToEdit(ContentChannelItem.FriendlyTypeName);
                pnlEditDetails.Visible = false;
            }
        }
Beispiel #29
0
        private int SyncVimeo(RockContext rockContext)
        {
            ContentChannelItem contentItem = GetContentItem(rockContext);

            if (contentItem != null)
            {
                if (contentItem.Attributes == null)
                {
                    contentItem.LoadAttributes();
                }

                long videoId = _vimeoId;

                if (_vimeoId == 0)
                {
                    videoId = this.tbVimeoId.Text.AsInteger();
                }

                if (contentItem.AttributeValues.ContainsKey(_vimeoIdKey))
                {
                    contentItem.AttributeValues[_vimeoIdKey].Value = videoId.ToString().AsInteger().ToString();
                }
                else
                {
                    contentItem.SetAttributeValue(_durationAttributeKey, videoId.ToString().AsInteger());
                }

                var client = new VimeoClient(_accessToken);
                var vimeo  = new Video();
                var width  = GetAttributeValue("ImageWidth").AsInteger();
                var video  = vimeo.GetVideoInfo(client, videoId, width);

                var cbName = cblSyncOptions.Items.FindByValue("Name");
                if (cbName != null && cbName.Selected == true)
                {
                    contentItem.Title = video.name;
                }

                var cbDescription = cblSyncOptions.Items.FindByValue("Description");
                if (cbDescription != null && cbDescription.Selected == true)
                {
                    contentItem.Content = video.description;
                }

                var cbImage = cblSyncOptions.Items.FindByValue("Image");
                if (cbImage != null && cbImage.Selected == true)
                {
                    if (contentItem.AttributeValues.ContainsKey(_imageAttributeKey))
                    {
                        contentItem.AttributeValues[_imageAttributeKey].Value = video.imageUrl;
                    }
                    else
                    {
                        contentItem.SetAttributeValue(_imageAttributeKey, video.imageUrl);
                    }
                }

                var cbDuration = cblSyncOptions.Items.FindByValue("Duration");
                if (cbDuration != null && cbDuration.Selected == true)
                {
                    if (contentItem.AttributeValues.ContainsKey(_durationAttributeKey))
                    {
                        contentItem.AttributeValues[_durationAttributeKey].Value = video.duration.ToString();
                    }
                    else
                    {
                        contentItem.SetAttributeValue(_durationAttributeKey, video.duration.ToString());
                    }
                }

                var cbHDVideo = cblSyncOptions.Items.FindByValue("HD Video");
                if (cbHDVideo != null && cbHDVideo.Selected == true && !string.IsNullOrWhiteSpace(video.hdLink))
                {
                    if (contentItem.AttributeValues.ContainsKey(_hdVideoAttributeKey))
                    {
                        contentItem.AttributeValues[_hdVideoAttributeKey].Value = video.hdLink;
                    }
                    else
                    {
                        contentItem.SetAttributeValue(_hdVideoAttributeKey, video.hdLink);
                    }
                }

                var cbSDVideo = cblSyncOptions.Items.FindByValue("SD Video");
                if (cbSDVideo != null && cbSDVideo.Selected == true && !string.IsNullOrWhiteSpace(video.sdLink))
                {
                    if (contentItem.AttributeValues.ContainsKey(_sdVideoAttributeKey))
                    {
                        contentItem.AttributeValues[_sdVideoAttributeKey].Value = video.sdLink;
                    }
                    else
                    {
                        contentItem.SetAttributeValue(_sdVideoAttributeKey, video.sdLink);
                    }
                }

                var cbHLSVideo = cblSyncOptions.Items.FindByValue("HLS Video");
                if (cbHLSVideo != null && cbHLSVideo.Selected == true && !string.IsNullOrWhiteSpace(video.hlsLink))
                {
                    if (contentItem.AttributeValues.ContainsKey(_hlsVideoAttributeKey))
                    {
                        contentItem.AttributeValues[_hlsVideoAttributeKey].Value = video.hlsLink;
                    }
                    else
                    {
                        contentItem.SetAttributeValue(_hlsVideoAttributeKey, video.hlsLink);
                    }
                }

                // Save Everything
                rockContext.WrapTransaction(() =>
                {
                    rockContext.SaveChanges();
                    contentItem.SaveAttributeValues(rockContext);
                });
            }

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

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

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

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

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

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

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

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

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

            divCalendars.Attributes["class"]       = GetDivClass(1);
            divCalendar.Attributes["class"]        = GetDivClass(2);
            divCalendarItem.Attributes["class"]    = GetDivClass(3);
            divEventOccurrence.Attributes["class"] = GetDivClass(4);
            divContentItem.Attributes["class"]     = GetDivClass(5);
        }
        /// <summary>
        /// **The PropertyFilter checks for it's property/attribute list in a cached items object before recreating 
        /// them using reflection and loading of generic attributes. Because of this, we're going to load them here
        /// and exclude some properties and add additional attributes specific to the channel type, and then save
        /// list to same cached object so that property filter lists our collection of properties/attributes
        /// instead.
        /// </summary>
        private List<Rock.Reporting.EntityField> HackEntityFields( ContentChannel channel, RockContext rockContext )
        {
            if ( channel != null )
            {
                var entityTypeCache = EntityTypeCache.Read( ITEM_TYPE_NAME );
                if ( entityTypeCache != null )
                {
                    var entityType = entityTypeCache.GetEntityType();

                    /// See above comments on HackEntityFields** to see why we are doing this
                    HttpContext.Current.Items.Remove( Rock.Reporting.EntityHelper.GetCacheKey( entityType ) );

                    var entityFields = Rock.Reporting.EntityHelper.GetEntityFields( entityType );
                    foreach( var entityField in entityFields
                        .Where( f => 
                            f.FieldKind == Rock.Reporting.FieldKind.Attribute &&
                            f.AttributeGuid.HasValue )
                        .ToList() )
                    {
                        var attribute = AttributeCache.Read( entityField.AttributeGuid.Value );
                        if ( attribute != null && 
                            attribute.EntityTypeQualifierColumn == "ContentChannelTypeId" && 
                            attribute.EntityTypeQualifierValue.AsInteger() != channel.ContentChannelTypeId )
                        {
                            entityFields.Remove( entityField );
                        }
                    }

                    if ( entityFields != null )
                    {
                        // Remove the status field
                        var ignoreFields = new List<string>();
                        ignoreFields.Add( "ContentChannelId" );
                        ignoreFields.Add( "Status" );

                        entityFields = entityFields.Where( f => !ignoreFields.Contains( f.Name ) ).ToList();

                        // Add any additional attributes that are specific to channel/type
                        var item = new ContentChannelItem();
                        item.ContentChannel = channel;
                        item.ContentChannelId = channel.Id;
                        item.ContentChannelType = channel.ContentChannelType;
                        item.ContentChannelTypeId = channel.ContentChannelTypeId;
                        item.LoadAttributes( rockContext );
                        foreach ( var attribute in item.Attributes
                            .Where( a =>
                                a.Value.EntityTypeQualifierColumn != "" &&
                                a.Value.EntityTypeQualifierValue != "" )
                            .Select( a => a.Value ) )
                        {
                            if ( !entityFields.Any( f => f.AttributeGuid.Equals( attribute.Guid ) ) )
                            {
                                Rock.Reporting.EntityHelper.AddEntityFieldForAttribute( entityFields, attribute );
                            }
                        }

                        // Re-sort fields
                        int index = 0;
                        var sortedFields = new List<Rock.Reporting.EntityField>();
                        foreach ( var entityProperty in entityFields.OrderBy( p => p.Title ).ThenBy( p => p.Name ) )
                        {
                            entityProperty.Index = index;
                            index++;
                            sortedFields.Add( entityProperty );
                        }

                        // Save new fields to cache ( which report field will use instead of reading them again )
                        HttpContext.Current.Items[Rock.Reporting.EntityHelper.GetCacheKey( entityType )] = sortedFields;
                    }

                    return entityFields;
                }
            }

            return null;
        }
        /// <summary>
        /// Shows the view.
        /// </summary>
        private void ShowView()
        {
            int?outputCacheDuration = GetAttributeValue("OutputCacheDuration").AsIntegerOrNull();

            string outputContents = null;
            string pageTitle      = null;

            var contentChannelItemParameterValue = GetContentChannelItemParameterValue();

            if (string.IsNullOrEmpty(contentChannelItemParameterValue))
            {
                // No item specified, so don't show anything
                ShowNoDataFound();
                return;
            }

            string outputCacheKey    = OUTPUT_CACHE_KEY_PREFIX + contentChannelItemParameterValue;
            string pageTitleCacheKey = PAGETITLE_CACHE_KEY_PREFIX + contentChannelItemParameterValue;

            if (outputCacheDuration.HasValue && outputCacheDuration.Value > 0)
            {
                outputContents = GetCacheItem(outputCacheKey) as string;
                pageTitle      = GetCacheItem(pageTitleCacheKey) as string;
            }

            bool setPageTitle = GetAttributeValue("SetPageTitle").AsBoolean();

            if (outputContents == null)
            {
                ContentChannelItem contentChannelItem = GetContentChannelItem(contentChannelItemParameterValue);

                if (contentChannelItem == null)
                {
                    ShowNoDataFound();
                    return;
                }

                // if a Channel was specified, verify that the ChannelItem is part of the channel
                var channelGuid = this.GetAttributeValue("ContentChannel").AsGuidOrNull();
                if (channelGuid.HasValue)
                {
                    var channel = ContentChannelCache.Get(channelGuid.Value);
                    if (channel != null)
                    {
                        if (contentChannelItem.ContentChannelId != channel.Id)
                        {
                            ShowNoDataFound();
                            return;
                        }
                    }
                }

                var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson, new Rock.Lava.CommonMergeFieldsOptions {
                    GetLegacyGlobalMergeFields = false
                });
                mergeFields.Add("RockVersion", Rock.VersionInfo.VersionInfo.GetRockProductVersionNumber());
                mergeFields.Add("Item", contentChannelItem);

                string metaDescriptionValue = GetMetaValueFromAttribute(this.GetAttributeValue("MetaDescriptionAttribute"), contentChannelItem);

                if (!string.IsNullOrWhiteSpace(metaDescriptionValue))
                {
                    // remove default meta description
                    RockPage.Header.Description = metaDescriptionValue.SanitizeHtml(true);
                }

                AddHtmlMeta("og:type", this.GetAttributeValue("OpenGraphType"));
                AddHtmlMeta("og:title", GetMetaValueFromAttribute(this.GetAttributeValue("OpenGraphTitleAttribute"), contentChannelItem));
                AddHtmlMeta("og:description", GetMetaValueFromAttribute(this.GetAttributeValue("OpenGraphDescriptionAttribute"), contentChannelItem));
                AddHtmlMeta("og:image", GetMetaValueFromAttribute(this.GetAttributeValue("OpenGraphImageAttribute"), contentChannelItem));
                AddHtmlMeta("twitter:title", GetMetaValueFromAttribute(this.GetAttributeValue("TwitterTitleAttribute"), contentChannelItem));
                AddHtmlMeta("twitter:description", GetMetaValueFromAttribute(this.GetAttributeValue("TwitterDescriptionAttribute"), contentChannelItem));
                AddHtmlMeta("twitter:image", GetMetaValueFromAttribute(this.GetAttributeValue("TwitterImageAttribute"), contentChannelItem));
                AddHtmlMeta("twitter:card", this.GetAttributeValue("TwitterCard"));

                string lavaTemplate        = this.GetAttributeValue("LavaTemplate");
                string enabledLavaCommands = this.GetAttributeValue("EnabledLavaCommands");
                outputContents = lavaTemplate.ResolveMergeFields(mergeFields, enabledLavaCommands);

                if (setPageTitle)
                {
                    pageTitle = contentChannelItem.Title;
                }

                if (outputCacheDuration.HasValue && outputCacheDuration.Value > 0)
                {
                    string cacheTags = GetAttributeValue("CacheTags") ?? string.Empty;
                    var    cacheKeys = GetCacheItem(CACHEKEYS_CACHE_KEY) as HashSet <string> ?? new HashSet <string>();
                    cacheKeys.Add(outputCacheKey);
                    cacheKeys.Add(pageTitleCacheKey);
                    AddCacheItem(CACHEKEYS_CACHE_KEY, cacheKeys, TimeSpan.MaxValue, cacheTags);
                    AddCacheItem(outputCacheKey, outputContents, outputCacheDuration.Value, cacheTags);

                    if (pageTitle != null)
                    {
                        AddCacheItem(pageTitleCacheKey, pageTitle, outputCacheDuration.Value, cacheTags);
                    }
                }
            }

            lContentOutput.Text = outputContents;

            if (setPageTitle && pageTitle != null)
            {
                RockPage.PageTitle    = pageTitle;
                RockPage.BrowserTitle = string.Format("{0} | {1}", pageTitle, RockPage.Site.Name);
                RockPage.Header.Title = string.Format("{0} | {1}", pageTitle, RockPage.Site.Name);
            }

            LaunchWorkflow();

            LaunchInteraction();
        }
        /// <summary>
        /// Loads the by model.
        /// </summary>
        /// <param name="contentChannelItem">The content channel item.</param>
        /// <returns></returns>
        public static ContentChannelItemIndex LoadByModel(ContentChannelItem contentChannelItem )
        {
            var contentChannelItemIndex = new ContentChannelItemIndex();
            contentChannelItemIndex.SourceIndexModel = "Rock.Model.ContentChannel";

            contentChannelItemIndex.Id = contentChannelItem.Id;
            contentChannelItemIndex.Title = contentChannelItem.Title;
            contentChannelItemIndex.Content = contentChannelItem.Content;
            contentChannelItemIndex.ContentChannelId = contentChannelItem.ContentChannelId;
            contentChannelItemIndex.Priority = contentChannelItem.Priority;
            contentChannelItemIndex.Status = contentChannelItem.Status.ToString();
            contentChannelItemIndex.StartDate = contentChannelItem.StartDateTime;
            contentChannelItemIndex.ExpireDate = contentChannelItem.ExpireDateTime;
            contentChannelItemIndex.Permalink = contentChannelItem.Permalink;
            contentChannelItemIndex.IconCssClass = string.IsNullOrWhiteSpace( contentChannelItem.ContentChannel.IconCssClass ) ? "fa fa-bullhorn" : contentChannelItem.ContentChannel.IconCssClass;
            contentChannelItemIndex.IsApproved = false;
            contentChannelItemIndex.ContentChannel = contentChannelItem.ContentChannel.Name;
            contentChannelItemIndex.DocumentName = contentChannelItem.Title;

            if ( contentChannelItem.ContentChannel != null && contentChannelItem.ContentChannel.RequiresApproval && contentChannelItem.ApprovedDateTime != null )
            {
                contentChannelItemIndex.IsApproved = true;
            }

            AddIndexableAttributes( contentChannelItemIndex, contentChannelItem );

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

            ContentChannelItem contentChannelItem = null;

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

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

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

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

            var rockContext = new RockContext();

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

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

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

            return(contentChannelItem);
        }
Beispiel #35
0
        /// <summary>
        /// Handles the Click event of the lbSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void lbSave_Click(object sender, EventArgs e)
        {
            var rockContext = new RockContext();
            ContentChannelItem contentItem = GetContentItem(rockContext);

            if (contentItem != null &&
                (IsUserAuthorized(Authorization.EDIT) || contentItem.IsAuthorized(Authorization.EDIT, CurrentPerson)))
            {
                contentItem.Title    = tbTitle.Text;
                contentItem.Content  = htmlContent.Text;
                contentItem.Priority = nbPriority.Text.AsInteger();

                // If this is a new item and the channel is manually sorted then we need to set the order to the next number
                if (contentItem.Id == 0 && new ContentChannelService(rockContext).IsManuallySorted(contentItem.ContentChannelId))
                {
                    contentItem.Order = new ContentChannelItemService(rockContext).GetNextItemOrderValueForContentChannel(contentItem.ContentChannelId);
                }

                if (contentItem.ContentChannelType.IncludeTime)
                {
                    contentItem.StartDateTime  = dtpStart.SelectedDateTime ?? RockDateTime.Now;
                    contentItem.ExpireDateTime = (contentItem.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange) ?
                                                 dtpExpire.SelectedDateTime : null;
                }
                else
                {
                    contentItem.StartDateTime  = dpStart.SelectedDate ?? RockDateTime.Today;
                    contentItem.ExpireDateTime = (contentItem.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange) ?
                                                 dpExpire.SelectedDate : null;
                }

                if (contentItem.ContentChannelType.DisableStatus)
                {
                    // if DisableStatus == True, just set the status to Approved
                    contentItem.Status = ContentChannelItemStatus.Approved;
                }
                else
                {
                    int newStatusID = hfStatus.Value.AsIntegerOrNull() ?? contentItem.Status.ConvertToInt();
                    int oldStatusId = contentItem.Status.ConvertToInt();
                    if (newStatusID != oldStatusId && contentItem.IsAuthorized(Authorization.APPROVE, CurrentPerson))
                    {
                        contentItem.Status = hfStatus.Value.ConvertToEnum <ContentChannelItemStatus>(ContentChannelItemStatus.PendingApproval);
                        if (contentItem.Status == ContentChannelItemStatus.PendingApproval)
                        {
                            contentItem.ApprovedDateTime        = null;
                            contentItem.ApprovedByPersonAliasId = null;
                        }
                        else
                        {
                            contentItem.ApprovedDateTime        = RockDateTime.Now;
                            contentItem.ApprovedByPersonAliasId = CurrentPersonAliasId;
                        }
                    }

                    // remove approved status if they do not have approve access when editing
                    if (!contentItem.IsAuthorized(Authorization.APPROVE, CurrentPerson))
                    {
                        contentItem.ApprovedDateTime        = null;
                        contentItem.ApprovedByPersonAliasId = null;
                        contentItem.Status = ContentChannelItemStatus.PendingApproval;
                    }
                }

                contentItem.LoadAttributes(rockContext);
                Rock.Attribute.Helper.GetEditValues(phAttributes, contentItem);

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

                rockContext.WrapTransaction(() =>
                {
                    rockContext.SaveChanges();
                    contentItem.SaveAttributeValues(rockContext);

                    if (contentItem.ContentChannel.IsTaggingEnabled)
                    {
                        taglTags.EntityGuid = contentItem.Guid;
                        taglTags.SaveTagValues(CurrentPersonAlias);
                    }

                    int?eventItemOccurrenceId = PageParameter("EventItemOccurrenceId").AsIntegerOrNull();
                    if (eventItemOccurrenceId.HasValue)
                    {
                        var occurrenceChannelItemService = new EventItemOccurrenceChannelItemService(rockContext);
                        var occurrenceChannelItem        = occurrenceChannelItemService
                                                           .Queryable()
                                                           .Where(c =>
                                                                  c.ContentChannelItemId == contentItem.Id &&
                                                                  c.EventItemOccurrenceId == eventItemOccurrenceId.Value)
                                                           .FirstOrDefault();

                        if (occurrenceChannelItem == null)
                        {
                            occurrenceChannelItem = new EventItemOccurrenceChannelItem();
                            occurrenceChannelItem.ContentChannelItemId  = contentItem.Id;
                            occurrenceChannelItem.EventItemOccurrenceId = eventItemOccurrenceId.Value;
                            occurrenceChannelItemService.Add(occurrenceChannelItem);
                            rockContext.SaveChanges();
                        }
                    }
                });

                ReturnToParentPage();
            }
        }