/// <summary>
        /// Updates the media file attribute dropdowns.
        /// </summary>
        /// <param name="channelGuid">The channel unique identifier.</param>
        private void UpdateMediaFileAttributeDropdowns(Guid?channelGuid)
        {
            List <AttributeCache> channelAttributes = new List <AttributeCache>();

            if (channelGuid.HasValue)
            {
                var rockContext = new RockContext();
                var channel     = new ContentChannelService(rockContext).GetNoTracking(channelGuid.Value);

                // Fake in-memory content channel item so we can properly
                // load all the attributes.
                var contentChannelItem = new ContentChannelItem
                {
                    ContentChannelId     = channel.Id,
                    ContentChannelTypeId = channel.ContentChannelTypeId
                };

                // add content channel item attributes
                contentChannelItem.LoadAttributes(rockContext);
                channelAttributes = contentChannelItem.Attributes.Select(a => a.Value).ToList();
            }

            ddlChannelAttribute.Items.Clear();
            ddlChannelAttribute.Items.Add(new ListItem());
            foreach (var attribute in channelAttributes)
            {
                if (attribute.FieldType.Class == typeof(Rock.Field.Types.MediaElementFieldType).FullName)
                {
                    ddlChannelAttribute.Items.Add(new ListItem(attribute.Name, attribute.Id.ToStringSafe()));
                }
            }
        }
Beispiel #2
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ShoppingCartItem"/> class.
        /// </summary>
        /// <param name="item">The content channel item to build from.</param>
        public ShoppingCartItem(ContentChannelItem item)
            : this()
        {
            if (item.Attributes == null)
            {
                item.LoadAttributes();
            }

            ItemId    = item.Id;
            Name      = item.Title;
            Quantity  = 1;
            Price     = item.GetAttributeValue("CubeDown.Price").AsDecimal();
            IsTaxable = item.GetAttributeValue("CubeDown.Taxable").AsBoolean(false);

            //
            // If an Account Guid was provided, convert it to an Id number.
            //
            var accountGuid = item.GetAttributeValue("CubeDown.Account").AsGuidOrNull();

            if (accountGuid.HasValue)
            {
                using (var rockContext = new RockContext())
                {
                    var account = new FinancialAccountService(rockContext).Get(accountGuid.Value);

                    AccountId = account?.Id;
                }
            }
        }
Beispiel #3
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)
            {
                if (string.IsNullOrWhiteSpace(GetAttributeValue("ContentChannel")))
                {
                    ShowDetail(PageParameter("contentItemId").AsInteger(), PageParameter("contentChannelId").AsIntegerOrNull());
                }
                else
                {
                    var contentChannel = GetAttributeValue("ContentChannel").AsGuid();
                    ShowDetail(PageParameter("contentItemId").AsInteger(), new ContentChannelService(new RockContext()).Get(GetAttributeValue("ContentChannel").AsGuid()).Id);
                }
            }
            else
            {
                var rockContext         = new RockContext();
                ContentChannelItem item = GetContentItem();
                item.LoadAttributes();

                phAttributes.Controls.Clear();
                Rock.Attribute.Helper.AddEditControls(item, phAttributes, false, BlockValidationGroup, 2);

                ShowDialog();
            }
        }
        /// <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();
                contentItem.StartDateTime  = dtpStart.SelectedDateTime ?? RockDateTime.Now;
                contentItem.ExpireDateTime = (contentItem.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange) ?
                                             dtpExpire.SelectedDateTime : 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);
                });

                ReturnToParentPage();
            }
        }
Beispiel #5
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)
            {
                ShowDetail(PageParameter("contentItemId").AsInteger(), PageParameter("contentChannelId").AsIntegerOrNull());
            }
            else
            {
                var rockContext         = new RockContext();
                ContentChannelItem item = GetContentItem();
                item.LoadAttributes();

                phAttributes.Controls.Clear();
                Rock.Attribute.Helper.AddEditControls(item, phAttributes, false, BlockValidationGroup);
            }
        }
Beispiel #6
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")
            });
        }
        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 #8
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 #9
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>
        /// **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>
        /// **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;
        }
Beispiel #12
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 #13
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;
        }
        /// <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.GetWorklowAttributeValue(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 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.GetWorklowAttributeValue(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.GetWorklowAttributeValue(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);

            // Save the new content channel item
            var contentChannelItemService = new ContentChannelItemService(rockContext);
            var contentChannelItem        = new ContentChannelItem();

            contentChannelItem.ContentChannelId     = contentChannel.Id;
            contentChannelItem.ContentChannelTypeId = contentChannel.ContentChannelTypeId;

            contentChannelItem.Title          = GetAttributeValue(action, "Title").ResolveMergeFields(mergeFields);
            contentChannelItem.Content        = content.ResolveMergeFields(mergeFields);
            contentChannelItem.StartDateTime  = startDateTime;
            contentChannelItem.ExpireDateTime = expireDateTime;
            contentChannelItem.Status         = channelItemStatus;

            contentChannelItemService.Add(contentChannelItem);
            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);
        }
        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 #16
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;
            }
        }
Beispiel #17
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 #18
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();
            }
        }