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

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

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

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

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

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

            mergeFields.Add("DetailPage", LinkedPageRoute("DetailPage"));
            mergeFields.Add("ContentChannel", contentChannel);
            mergeFields.Add("CurrentPerson", CurrentPerson);
            mergeFields.Add("Items", items.Take(GetAttributeValue("MaxItems").AsInteger()).ToList());

            string template = GetAttributeValue("LavaTemplate");

            lContent.Text = template.ResolveMergeFields(mergeFields);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Handles the Delete event of the gContentChannels 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 gContentChannels_Delete(object sender, RowEventArgs e)
        {
            var rockContext = new RockContext();
            ContentChannelService contentChannelService = new ContentChannelService(rockContext);

            ContentChannel contentChannel = contentChannelService.Get(e.RowKeyId);

            if (contentChannel != null)
            {
                string errorMessage;
                if (!contentChannelService.CanDelete(contentChannel, out errorMessage))
                {
                    mdGridWarning.Show(errorMessage, ModalAlertType.Warning);
                    return;
                }

                contentChannel.ParentContentChannels.Clear();
                contentChannel.ChildContentChannels.Clear();

                contentChannelService.Delete(contentChannel);
                rockContext.SaveChanges();
            }

            BindGrid();
        }
Ejemplo n.º 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);

            maContentChannelWarning.Hide();

            if (!Page.IsPostBack)
            {
                int?contentChannelId = PageParameter("ContentChannelId").AsIntegerOrNull();
                if (contentChannelId.HasValue)
                {
                    upnlContent.Visible = true;
                    ShowDetail(contentChannelId.Value);
                }
                else
                {
                    upnlContent.Visible = false;
                }
            }
            else
            {
                if (pnlEditDetails.Visible)
                {
                    var channel = new ContentChannel();
                    channel.Id = hfId.Value.AsInteger();
                    channel.ContentChannelTypeId = hfTypeId.Value.AsInteger();
                    channel.LoadAttributes();
                    phAttributes.Controls.Clear();
                    Rock.Attribute.Helper.AddEditControls(channel, phAttributes, false, BlockValidationGroup);

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

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

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

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

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

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

            mergeFields.Add("DetailPage", LinkedPageUrl("DetailPage", null));
            mergeFields.Add("ContentChannel", contentChannel);
            mergeFields.Add("CurrentPerson", CurrentPerson);
            mergeFields.Add("Items", items.Take(GetAttributeValue("MaxItems").AsInteger()).ToList());

            string template = GetAttributeValue("LavaTemplate");

            lContent.Text = template.ResolveMergeFields(mergeFields);

            // show debug info
            if (GetAttributeValue("EnableDebug").AsBoolean() && IsUserAuthorized(Authorization.EDIT))
            {
                lDebug.Visible = true;
                lDebug.Text    = mergeFields.lavaDebugInfo();
            }
        }
Ejemplo n.º 5
0
 /// <summary>
 /// Creates the filter control.
 /// </summary>
 /// <param name="channel">The channel.</param>
 /// <param name="filter">The filter.</param>
 /// <param name="setSelection">if set to <c>true</c> [set selection].</param>
 /// <param name="rockContext">The rock context.</param>
 private void CreateFilterControl(ContentChannel channel, DataViewFilter filter, bool setSelection, RockContext rockContext)
 {
     phFilters.Controls.Clear();
     if (filter != null)
     {
         CreateFilterControl(phFilters, filter, setSelection, rockContext, channel);
     }
 }
Ejemplo n.º 6
0
        /// <summary>
        /// Shows the edit details.
        /// </summary>
        /// <param name="contentChannel">Type of the content.</param>
        protected void ShowEditDetails(ContentChannel contentChannel)
        {
            if (contentChannel != null)
            {
                hfId.Value = contentChannel.Id.ToString();
                string title = contentChannel.Id > 0 ?
                               ActionTitle.Edit(ContentChannel.FriendlyTypeName) :
                               ActionTitle.Add(ContentChannel.FriendlyTypeName);

                SetHeadingInfo(contentChannel, title);

                SetEditMode(true);

                LoadDropdowns();

                tbName.Text        = contentChannel.Name;
                tbDescription.Text = contentChannel.Description;
                ddlChannelType.SetValue(contentChannel.ContentChannelTypeId);
                ddlContentControlType.SetValue(contentChannel.ContentControlType.ConvertToInt().ToString());
                tbRootImageDirectory.Text           = contentChannel.RootImageDirectory;
                tbRootImageDirectory.Visible        = contentChannel.ContentControlType == ContentControlType.HtmlEditor;
                tbIconCssClass.Text                 = contentChannel.IconCssClass;
                cbRequireApproval.Checked           = contentChannel.RequiresApproval;
                cbItemsManuallyOrdered.Checked      = contentChannel.ItemsManuallyOrdered;
                cbChildItemsManuallyOrdered.Checked = contentChannel.ChildItemsManuallyOrdered;
                cbEnableRss.Checked                 = contentChannel.EnableRss;

                divRss.Attributes["style"] = cbEnableRss.Checked ? "display:block" : "display:none";
                tbChannelUrl.Text          = contentChannel.ChannelUrl;
                tbItemUrl.Text             = contentChannel.ItemUrl;
                nbTimetoLive.Text          = (contentChannel.TimeToLive ?? 0).ToString();

                ChildContentChannelsList = new List <int>();
                contentChannel.ChildContentChannels.ToList().ForEach(a => ChildContentChannelsList.Add(a.Id));
                BindChildContentChannelsGrid();

                AddAttributeControls(contentChannel);

                // load attribute data
                ItemAttributesState = new List <Attribute>();
                AttributeService attributeService = new AttributeService(new RockContext());

                string qualifierValue = contentChannel.Id.ToString();

                attributeService.GetByEntityTypeId(new ContentChannelItem().TypeId).AsQueryable()
                .Where(a =>
                       a.EntityTypeQualifierColumn.Equals("ContentChannelId", StringComparison.OrdinalIgnoreCase) &&
                       a.EntityTypeQualifierValue.Equals(qualifierValue))
                .ToList()
                .ForEach(a => ItemAttributesState.Add(a));

                // Set order
                int newOrder = 0;
                ItemAttributesState.ForEach(a => a.Order = newOrder++);

                BindItemAttributesGrid();
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Shows the readonly details.
        /// </summary>
        /// <param name="contentChannel">Type of the content.</param>
        private void ShowReadonlyDetails(ContentChannel contentChannel)
        {
            SetEditMode(false);

            if (contentChannel != null)
            {
                hfId.SetValue(contentChannel.Id);

                SetHeadingInfo(contentChannel, contentChannel.Name);
                SetEditMode(false);

                nbRoleMessage.Visible = false;
                if (contentChannel.RequiresApproval && !IsApproverConfigured(contentChannel))
                {
                    nbRoleMessage.Text    = "<p>No role or person is configured to approve the items for this channel. Please configure one or more roles or people in the security settings under the &quot;Approve&quot; tab.</p>";
                    nbRoleMessage.Visible = true;
                }

                lGroupDescription.Text = contentChannel.Description;

                var descriptionListLeft  = new DescriptionList();
                var descriptionListRight = new DescriptionList();

                descriptionListLeft.Add("Items Require Approval", contentChannel.RequiresApproval.ToYesNo());

                // Only show index state if indexing is enabled on the server
                if (IndexContainer.IndexingEnabled)
                {
                    descriptionListRight.Add("Is Indexed", contentChannel.IsIndexEnabled.ToYesNo());
                }

                if (contentChannel.EnableRss)
                {
                    descriptionListLeft.Add("Channel URL", contentChannel.ChannelUrl);
                    descriptionListRight.Add("Item URL", contentChannel.ItemUrl);
                }

                contentChannel.LoadAttributes();
                foreach (var attribute in contentChannel.Attributes
                         .Where(a => a.Value.IsGridColumn)
                         .OrderBy(a => a.Value.Order)
                         .Select(a => a.Value))
                {
                    if (contentChannel.AttributeValues.ContainsKey(attribute.Key))
                    {
                        string value = attribute.FieldType.Field.FormatValueAsHtml(null, attribute.EntityTypeId, contentChannel.Id,
                                                                                   contentChannel.AttributeValues[attribute.Key].Value, attribute.QualifierValues, false);
                        descriptionListLeft.Add(attribute.Name, value);
                    }
                }

                lDetailsLeft.Text  = descriptionListLeft.Html;
                lDetailsRight.Text = descriptionListRight.Html;
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Adds the attribute controls.
        /// </summary>
        /// <param name="contentChannel">The content channel.</param>
        private void AddAttributeControls(ContentChannel contentChannel)
        {
            int typeId = ddlChannelType.SelectedValueAsInt() ?? 0;

            hfTypeId.Value = typeId.ToString();

            contentChannel.ContentChannelTypeId = typeId;
            contentChannel.LoadAttributes();
            phAttributes.Controls.Clear();
            Rock.Attribute.Helper.AddEditControls(contentChannel, phAttributes, true, BlockValidationGroup);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Sets the heading information.
        /// </summary>
        /// <param name="contentChannel">Type of the content.</param>
        /// <param name="title">The title.</param>
        private void SetHeadingInfo(ContentChannel contentChannel, string title)
        {
            string cssIcon = contentChannel.IconCssClass;

            if (string.IsNullOrWhiteSpace(cssIcon))
            {
                cssIcon = "fa fa-bullhorn";
            }
            lIcon.Text            = string.Format("<i class='{0}'></i>", cssIcon);
            lTitle.Text           = title.FormatAsHtmlTitle();
            hlContentChannel.Text = contentChannel.ContentChannelType != null ? contentChannel.ContentChannelType.Name : string.Empty;
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Updates the type of the controls for content channel.
        /// </summary>
        /// <param name="channel">The channel.</param>
        private void UpdateControlsForContentChannelType(ContentChannel channel)
        {
            SetInheritedAttributeKeys(channel.Id);

            AddAttributeControls(channel);

            int contentChannelTypeId = ddlChannelType.SelectedValueAsInt() ?? 0;
            var contentChannelType   = new ContentChannelTypeService(new RockContext()).Get(contentChannelTypeId);

            if (contentChannelType != null)
            {
                ddlContentControlType.Visible = !contentChannelType.DisableContentField;
                cbRequireApproval.Visible     = !contentChannelType.DisableStatus;
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Check if there is any approver configured.
        /// </summary>
        /// <param name="contentChannel">The content channel.</param>
        public bool IsApproverConfigured(ContentChannel contentChannel)
        {
            var rockContext = new RockContext();

            var authService = new AuthService(rockContext);
            var contentChannelEntityTypeId = EntityTypeCache.Get <Rock.Model.ContentChannel>().Id;

            var approvalAuths = authService.GetAuths(contentChannelEntityTypeId, contentChannel.Id, Rock.Security.Authorization.APPROVE);

            // Get a list of all PersonIds that are allowed that are included in the Auths
            // Then, when we get a list of all the allowed people that are in the auth as a specific Person or part of a Role (Group), we'll run all those people thru NoteType.IsAuthorized
            // That way, we don't have to figure out all the logic of Allow/Deny based on Order, etc
            bool isValid = approvalAuths.Any(a => a.AllowOrDeny == "A" && (a.PersonAlias != null || a.GroupId != null));

            return(isValid);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Shows the readonly details.
        /// </summary>
        /// <param name="contentChannel">Type of the content.</param>
        private void ShowReadonlyDetails(ContentChannel contentChannel)
        {
            SetEditMode(false);

            if (contentChannel != null)
            {
                hfId.SetValue(contentChannel.Id);

                SetHeadingInfo(contentChannel, contentChannel.Name);
                SetEditMode(false);

                lGroupDescription.Text = contentChannel.Description;

                var descriptionListLeft  = new DescriptionList();
                var descriptionListRight = new DescriptionList();

                descriptionListLeft.Add("Items Require Approval", contentChannel.RequiresApproval.ToYesNo());
                descriptionListRight.Add("Is Indexed", contentChannel.IsIndexEnabled.ToYesNo());

                if (contentChannel.EnableRss)
                {
                    descriptionListLeft.Add("Channel Url", contentChannel.ChannelUrl);
                    descriptionListRight.Add("Item Url", contentChannel.ItemUrl);
                }

                contentChannel.LoadAttributes();
                foreach (var attribute in contentChannel.Attributes
                         .Where(a => a.Value.IsGridColumn)
                         .OrderBy(a => a.Value.Order)
                         .Select(a => a.Value))
                {
                    if (contentChannel.AttributeValues.ContainsKey(attribute.Key))
                    {
                        string value = attribute.FieldType.Field.FormatValueAsHtml(null, attribute.EntityTypeId, contentChannel.Id,
                                                                                   contentChannel.AttributeValues[attribute.Key].Value, attribute.QualifierValues, false);
                        descriptionListLeft.Add(attribute.Name, value);
                    }
                }

                lDetailsLeft.Text  = descriptionListLeft.Html;
                lDetailsRight.Text = descriptionListRight.Html;
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Sets the heading information.
        /// </summary>
        /// <param name="contentChannel">Type of the content.</param>
        /// <param name="title">The title.</param>
        private void SetHeadingInfo(ContentChannel contentChannel, string title)
        {
            string cssIcon = contentChannel.IconCssClass;

            if (string.IsNullOrWhiteSpace(cssIcon))
            {
                cssIcon = "fa fa-bullhorn";
            }
            lIcon.Text  = string.Format("<i class='{0}'></i>", cssIcon);
            lTitle.Text = title.FormatAsHtmlTitle();
            var categoriesHtml = new StringBuilder();

            foreach (var category in contentChannel.Categories.OrderBy(a => a.Order))
            {
                categoriesHtml.AppendLine(string.Format("<span class='label label-info' data-toggle='tooltip' title='{0}'>{0}</span>", category.Name));
            }
            lCategories.Text      = categoriesHtml.ToString();
            hlContentChannel.Text = contentChannel.ContentChannelType != null ? contentChannel.ContentChannelType.Name : string.Empty;
        }
Ejemplo n.º 14
0
        protected void BindAttributes(ContentChannel channel)
        {
            AvailableAttributes = new List <AttributeCache>();
            int    entityTypeId  = EntityTypeCache.Read(typeof(Rock.Model.ContentChannelItem)).Id;
            string channelId     = channel.Id.ToString();
            string channelTypeId = channel.ContentChannelTypeId.ToString();

            foreach (var attributeModel in new AttributeService(new RockContext()).Queryable()
                     .Where(a =>
                            a.EntityTypeId == entityTypeId &&
                            a.IsGridColumn && ((
                                                   a.EntityTypeQualifierColumn.Equals("ContentChannelTypeId", StringComparison.OrdinalIgnoreCase) &&
                                                   a.EntityTypeQualifierValue.Equals(channelTypeId)
                                                   ) || (
                                                   a.EntityTypeQualifierColumn.Equals("ContentChannelId", StringComparison.OrdinalIgnoreCase) &&
                                                   a.EntityTypeQualifierValue.Equals(channelId)
                                                   )))
                     .OrderBy(a => a.Order)
                     .ThenBy(a => a.Name))
            {
                AvailableAttributes.Add(Rock.Web.Cache.AttributeCache.Read(attributeModel));
            }
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Handles the SelectedIndexChanged event of the ddlChannelType 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 ddlChannelType_SelectedIndexChanged(object sender, EventArgs e)
        {
            ContentChannel channel = null;

            int contentChannelId = hfId.ValueAsInt();

            if (contentChannelId != 0)
            {
                channel = GetContentChannel(hfId.ValueAsInt());
                if (channel != null &&
                    channel.ContentChannelTypeId.ToString() != ddlChannelType.SelectedValue &&
                    channel.Items.Any())
                {
                    maContentChannelWarning.Show("Changing the content type will result in all of this channel's items losing any data that is specific to the original content type!", ModalAlertType.Warning);
                }
            }

            if (channel == null)
            {
                channel = new ContentChannel();
            }

            UpdateControlsForContentChannelType(channel);
        }
        /// <summary>
        /// Shows the edit details.
        /// </summary>
        /// <param name="contentChannel">Type of the content.</param>
        protected void ShowEditDetails( ContentChannel contentChannel )
        {
            if ( contentChannel != null )
            {
                hfId.Value = contentChannel.Id.ToString();
                string title = contentChannel.Id > 0 ?
                    ActionTitle.Edit( ContentChannel.FriendlyTypeName ) :
                    ActionTitle.Add( ContentChannel.FriendlyTypeName );

                SetHeadingInfo( contentChannel, title );

                SetEditMode( true );

                LoadDropdowns();

                tbName.Text = contentChannel.Name;
                tbDescription.Text = contentChannel.Description;
                ddlChannelType.SetValue( contentChannel.ContentChannelTypeId );
                ddlContentControlType.SetValue( contentChannel.ContentControlType.ConvertToInt().ToString() );
                tbRootImageDirectory.Text = contentChannel.RootImageDirectory;
                tbRootImageDirectory.Visible = contentChannel.ContentControlType == ContentControlType.HtmlEditor;
                tbIconCssClass.Text = contentChannel.IconCssClass;
                cbRequireApproval.Checked = contentChannel.RequiresApproval;
                cbItemsManuallyOrdered.Checked = contentChannel.ItemsManuallyOrdered;
                cbChildItemsManuallyOrdered.Checked = contentChannel.ChildItemsManuallyOrdered;
                cbEnableRss.Checked = contentChannel.EnableRss;

                divRss.Attributes["style"] = cbEnableRss.Checked ? "display:block" : "display:none";
                tbChannelUrl.Text = contentChannel.ChannelUrl;
                tbItemUrl.Text = contentChannel.ItemUrl;
                nbTimetoLive.Text = ( contentChannel.TimeToLive ?? 0 ).ToString();

                ChildContentChannelsList = new List<int>();
                contentChannel.ChildContentChannels.ToList().ForEach( a => ChildContentChannelsList.Add( a.Id ) );
                BindChildContentChannelsGrid();

                AddAttributeControls( contentChannel );

                // load attribute data
                ItemAttributesState = new List<Attribute>();
                AttributeService attributeService = new AttributeService( new RockContext() );

                string qualifierValue = contentChannel.Id.ToString();

                attributeService.GetByEntityTypeId( new ContentChannelItem().TypeId ).AsQueryable()
                    .Where( a =>
                        a.EntityTypeQualifierColumn.Equals( "ContentChannelId", StringComparison.OrdinalIgnoreCase ) &&
                        a.EntityTypeQualifierValue.Equals( qualifierValue ) )
                    .ToList()
                    .ForEach( a => ItemAttributesState.Add( a ) );

                // Set order
                int newOrder = 0;
                ItemAttributesState.ForEach( a => a.Order = newOrder++ );

                BindItemAttributesGrid();
            }
        }
        /// <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();
            ContentChannel contentChannel;

            ContentChannelService contentChannelService = new ContentChannelService( rockContext );

            int contentChannelId = hfId.Value.AsInteger();

            if ( contentChannelId == 0 )
            {
                contentChannel = new ContentChannel { Id = 0 };
                contentChannelService.Add( contentChannel );
            }
            else
            {
                contentChannel = contentChannelService.Get( contentChannelId );
            }

            if ( contentChannel != null )
            {
                contentChannel.Name = tbName.Text;
                contentChannel.Description = tbDescription.Text;
                contentChannel.ContentChannelTypeId = ddlChannelType.SelectedValueAsInt() ?? 0;
                contentChannel.ContentControlType = ddlContentControlType.SelectedValueAsEnum<ContentControlType>();
                contentChannel.RootImageDirectory = tbRootImageDirectory.Visible ? tbRootImageDirectory.Text : string.Empty;
                contentChannel.IconCssClass = tbIconCssClass.Text;
                contentChannel.RequiresApproval = cbRequireApproval.Checked;
                contentChannel.ItemsManuallyOrdered = cbItemsManuallyOrdered.Checked;
                contentChannel.ChildItemsManuallyOrdered = cbChildItemsManuallyOrdered.Checked;
                contentChannel.EnableRss = cbEnableRss.Checked;
                contentChannel.ChannelUrl = tbChannelUrl.Text;
                contentChannel.ItemUrl = tbItemUrl.Text;
                contentChannel.TimeToLive = nbTimetoLive.Text.AsIntegerOrNull();

                contentChannel.ChildContentChannels = new List<ContentChannel>();
                contentChannel.ChildContentChannels.Clear();
                foreach ( var item in ChildContentChannelsList )
                {
                    var childContentChannel = contentChannelService.Get( item );
                    if ( childContentChannel != null )
                    {
                        contentChannel.ChildContentChannels.Add( childContentChannel );
                    }
                }

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

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

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

                    foreach( var item in new ContentChannelItemService( rockContext )
                        .Queryable()
                        .Where( i =>
                            i.ContentChannelId == contentChannel.Id &&
                            i.ContentChannelTypeId != contentChannel.ContentChannelTypeId
                        ))
                    {
                        item.ContentChannelTypeId = contentChannel.ContentChannelTypeId;
                    }

                    rockContext.SaveChanges();

                    // Save the Item Attributes
                    int entityTypeId = EntityTypeCache.Read( typeof( ContentChannelItem ) ).Id;
                    SaveAttributes( contentChannel.Id, entityTypeId, ItemAttributesState, rockContext );

                } );

                var pageReference = RockPage.PageReference;
                pageReference.Parameters.AddOrReplace( "contentChannelId", contentChannel.Id.ToString() );
                Response.Redirect( pageReference.BuildUrl(), false );
            }
        }
        /// <summary>
        /// Shows the detail.
        /// </summary>
        /// <param name="contentChannelId">The marketing campaign ad type identifier.</param>
        public void ShowDetail( int contentChannelId )
        {
            ContentChannel contentChannel = null;

            bool editAllowed = IsUserAuthorized( Authorization.EDIT );

            var rockContext = new RockContext();

            if ( !contentChannelId.Equals( 0 ) )
            {
                contentChannel = GetContentChannel( contentChannelId );
                if ( contentChannel != null )
                {
                    editAllowed = editAllowed || contentChannel.IsAuthorized( Authorization.EDIT, CurrentPerson );
                }
                pdAuditDetails.SetEntity( contentChannel, ResolveRockUrl( "~" ) );
            }

            if ( contentChannel == null )
            {
                contentChannel = new ContentChannel { Id = 0 };
                contentChannel.ChildContentChannels = new List<ContentChannel>();
                // hide the panel drawer that show created and last modified dates
                pdAuditDetails.Visible = false;
            }

            if ( contentChannel != null && contentChannel.IsAuthorized( Authorization.VIEW, CurrentPerson ) )
            {
                hfId.Value = contentChannel.Id.ToString();

                bool readOnly = false;
                nbEditModeMessage.Text = string.Empty;

                if ( !editAllowed )
                {
                    readOnly = true;
                    nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed( ContentChannel.FriendlyTypeName );
                }

                if ( readOnly )
                {
                    lbEdit.Visible = false;
                    ShowReadonlyDetails( contentChannel );
                }
                else
                {
                    lbEdit.Visible = true;
                    if ( contentChannel.Id > 0 )
                    {
                        ShowReadonlyDetails( contentChannel );
                    }
                    else
                    {
                        ShowEditDetails( contentChannel );
                    }
                }

                btnSecurity.Visible = contentChannel.IsAuthorized( Authorization.ADMINISTRATE, CurrentPerson );
                btnSecurity.Title = contentChannel.Name;
                btnSecurity.EntityId = contentChannel.Id;

                lbSave.Visible = !readOnly;
            }
            else
            {
                nbEditModeMessage.Text = EditModeMessage.NotAuthorizedToView( ContentChannel.FriendlyTypeName );
                pnlEditDetails.Visible = false;
                fieldsetViewSummary.Visible = false;
            }
        }
        /// <summary>
        /// Handles the SaveClick event of the mdContentComponentConfig control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void mdContentComponentConfig_SaveClick(object sender, EventArgs e)
        {
            var rockContext = new RockContext();

            var dataViewFilter = ReportingHelper.GetFilterFromControls(phFilters);

            if (dataViewFilter != null)
            {
                // update Guids since we are creating a new dataFilter and children and deleting the old one
                SetNewDataFilterGuids(dataViewFilter);

                if (!Page.IsValid)
                {
                    return;
                }

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

                DataViewFilterService dataViewFilterService = new DataViewFilterService(rockContext);

                int?dataViewFilterId = hfDataFilterId.Value.AsIntegerOrNull();
                if (dataViewFilterId.HasValue)
                {
                    var oldDataViewFilter = dataViewFilterService.Get(dataViewFilterId.Value);
                    DeleteDataViewFilter(oldDataViewFilter, dataViewFilterService);
                }

                dataViewFilterService.Add(dataViewFilter);
            }

            rockContext.SaveChanges();

            ContentChannelService contentChannelService = new ContentChannelService(rockContext);
            Guid?          contentChannelGuid           = this.GetAttributeValue("ContentChannel").AsGuidOrNull();
            ContentChannel contentChannel = null;

            if (contentChannelGuid.HasValue)
            {
                contentChannel = contentChannelService.Get(contentChannelGuid.Value);
            }

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

            contentChannel.LoadAttributes(rockContext);
            avcContentChannelAttributes.GetEditValues(contentChannel);

            contentChannel.Name = tbComponentName.Text;
            rockContext.SaveChanges();
            contentChannel.SaveAttributeValues(rockContext);

            this.SetAttributeValue("ContentChannel", contentChannel.Guid.ToString());

            this.SetAttributeValue("ItemCacheDuration", nbItemCacheDuration.Text);

            int? contentComponentTemplateValueId   = dvpContentComponentTemplate.SelectedValue.AsInteger();
            Guid?contentComponentTemplateValueGuid = null;

            if (contentComponentTemplateValueId.HasValue)
            {
                var contentComponentTemplate = DefinedValueCache.Get(contentComponentTemplateValueId.Value);
                if (contentComponentTemplate != null)
                {
                    contentComponentTemplateValueGuid = contentComponentTemplate.Guid;
                }
            }

            this.SetAttributeValue("ContentComponentTemplate", contentComponentTemplateValueGuid.ToString());
            this.SetAttributeValue("AllowMultipleContentItems", cbAllowMultipleContentItems.Checked.ToString());
            this.SetAttributeValue("OutputCacheDuration", nbOutputCacheDuration.Text);
            this.SetAttributeValue("CacheTags", cblCacheTags.SelectedValues.AsDelimited(","));
            if (dataViewFilter != null)
            {
                this.SetAttributeValue("FilterId", dataViewFilter.Id.ToString());
            }
            else
            {
                this.SetAttributeValue("FilterId", null);
            }

            this.SaveAttributeValues();

            var block = new BlockService(rockContext).Get(this.BlockId);

            block.PreHtml  = cePreHtml.Text;
            block.PostHtml = cePostHtml.Text;
            rockContext.SaveChanges();

            mdContentComponentConfig.Hide();
            pnlContentComponentConfig.Visible = false;

            RemoveCacheItem(OUTPUT_CACHE_KEY);
            RemoveCacheItem(ITEM_CACHE_KEY);

            // reload the page to make sure we have a clean load
            NavigateToCurrentPageReference();
        }
Ejemplo n.º 20
0
        private List<ContentChannelItem> GetItems( RockContext rockContext, ContentChannel selectedChannel, out bool isFiltered )
        {
            isFiltered = false;

            var items = new List<ContentChannelItem>();

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

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

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

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

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

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

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

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

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

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

            if ( selectedChannel.ItemsManuallyOrdered && !isFiltered )
            {
                return items.OrderBy( i => i.Order ).ToList();
            }
            else
            {
                return items;
            }
        }
        protected void AddColumns(ContentChannel channel)
        {
            // Remove all columns
            gContentChannelItems.Columns.Clear();

            if (channel != null)
            {
                // Add Title column
                var titleField = new BoundField();
                titleField.DataField      = "Title";
                titleField.HeaderText     = "Title";
                titleField.SortExpression = "Title";
                gContentChannelItems.Columns.Add(titleField);

                // Add Attribute columns
                int    entityTypeId  = EntityTypeCache.Read(typeof(Rock.Model.ContentChannelItem)).Id;
                string channelId     = channel.Id.ToString();
                string channelTypeId = channel.ContentChannelTypeId.ToString();
                foreach (var attribute in new AttributeService(new RockContext()).Queryable()
                         .Where(a =>
                                a.EntityTypeId == entityTypeId &&
                                a.IsGridColumn && ((
                                                       a.EntityTypeQualifierColumn.Equals("ContentChannelTypeId", StringComparison.OrdinalIgnoreCase) &&
                                                       a.EntityTypeQualifierValue.Equals(channelTypeId)
                                                       ) || (
                                                       a.EntityTypeQualifierColumn.Equals("ContentChannelId", StringComparison.OrdinalIgnoreCase) &&
                                                       a.EntityTypeQualifierValue.Equals(channelId)
                                                       )))
                         .OrderBy(a => a.Order)
                         .ThenBy(a => a.Name))
                {
                    string dataFieldExpression = attribute.Key;
                    bool   columnExists        = gContentChannelItems.Columns.OfType <AttributeField>().FirstOrDefault(a => a.DataField.Equals(dataFieldExpression)) != null;
                    if (!columnExists)
                    {
                        AttributeField boundField = new AttributeField();
                        boundField.DataField      = dataFieldExpression;
                        boundField.HeaderText     = attribute.Name;
                        boundField.SortExpression = string.Empty;

                        var attributeCache = Rock.Web.Cache.AttributeCache.Read(attribute.Id);
                        if (attributeCache != null)
                        {
                            boundField.ItemStyle.HorizontalAlign = attributeCache.FieldType.Field.AlignValue;
                        }

                        gContentChannelItems.Columns.Add(boundField);
                    }
                }

                // Add Start column
                var startField = new DateTimeField();
                startField.DataField      = "StartDateTime";
                startField.HeaderText     = channel.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange ? "Start" : "Date";
                startField.SortExpression = "StartDateTime";
                gContentChannelItems.Columns.Add(startField);

                // Expire column
                if (channel.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange)
                {
                    var expireField = new DateTimeField();
                    expireField.DataField      = "ExpireDateTime";
                    expireField.HeaderText     = "Expire";
                    expireField.SortExpression = "ExpireDateTime";
                    gContentChannelItems.Columns.Add(expireField);
                }

                // Priority column
                var priorityField = new BoundField();
                priorityField.DataField                 = "Priority";
                priorityField.HeaderText                = "Priority";
                priorityField.SortExpression            = "Priority";
                priorityField.DataFormatString          = "{0:N0}";
                priorityField.ItemStyle.HorizontalAlign = HorizontalAlign.Right;
                gContentChannelItems.Columns.Add(priorityField);

                // Status column
                if (channel.RequiresApproval)
                {
                    var statusField = new BoundField();
                    gContentChannelItems.Columns.Add(statusField);
                    statusField.DataField      = "Status";
                    statusField.HeaderText     = "Status";
                    statusField.SortExpression = "Status";
                    statusField.HtmlEncode     = false;
                }

                bool canEditChannel = channel.IsAuthorized(Rock.Security.Authorization.EDIT, CurrentPerson);
                gContentChannelItems.Actions.ShowAdd = canEditChannel;
                gContentChannelItems.IsDeleteEnabled = canEditChannel;
                if (canEditChannel)
                {
                    var deleteField = new DeleteField();
                    gContentChannelItems.Columns.Add(deleteField);
                    deleteField.Click += gContentChannelItems_Delete;
                }
            }
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Shows the detail.
        /// </summary>
        /// <param name="contentChannelId">The content channel identifier.</param>
        public void ShowDetail(int contentChannelId)
        {
            ContentChannel contentChannel = null;

            cbIndexChannel.Visible = IndexContainer.IndexingEnabled;

            bool editAllowed = IsUserAuthorized(Authorization.EDIT);

            var rockContext = new RockContext();

            if (!contentChannelId.Equals(0))
            {
                contentChannel = GetContentChannel(contentChannelId);
                if (contentChannel != null)
                {
                    editAllowed = editAllowed || contentChannel.IsAuthorized(Authorization.EDIT, CurrentPerson);
                }
                pdAuditDetails.SetEntity(contentChannel, ResolveRockUrl("~"));
            }

            if (contentChannel == null)
            {
                contentChannel = new ContentChannel {
                    Id = 0
                };
                contentChannel.ChildContentChannels = new List <ContentChannel>();
                // hide the panel drawer that show created and last modified dates
                pdAuditDetails.Visible = false;
            }

            if (contentChannel != null && contentChannel.IsAuthorized(Authorization.VIEW, CurrentPerson))
            {
                hfId.Value = contentChannel.Id.ToString();

                bool readOnly = false;
                nbEditModeMessage.Text = string.Empty;

                if (!editAllowed)
                {
                    readOnly = true;
                    nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed(ContentChannel.FriendlyTypeName);
                }

                if (readOnly)
                {
                    lbEdit.Visible = false;
                    ShowReadonlyDetails(contentChannel);
                }
                else
                {
                    lbEdit.Visible = true;
                    if (contentChannel.Id > 0)
                    {
                        ShowReadonlyDetails(contentChannel);
                    }
                    else
                    {
                        ShowEditDetails(contentChannel);
                    }
                }

                btnSecurity.Visible  = contentChannel.IsAuthorized(Authorization.ADMINISTRATE, CurrentPerson);
                btnSecurity.Title    = contentChannel.Name;
                btnSecurity.EntityId = contentChannel.Id;

                lbSave.Visible = !readOnly;
            }
            else
            {
                nbEditModeMessage.Text      = EditModeMessage.NotAuthorizedToView(ContentChannel.FriendlyTypeName);
                pnlEditDetails.Visible      = false;
                fieldsetViewSummary.Visible = false;
            }
        }
        private void GetData()
        {
            var rockContext = new RockContext();
            var itemService = new ContentChannelItemService(rockContext);

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

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

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

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

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

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

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

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

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

            var contentChannels = qry.ToList();

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

            ContentChannel selectedChannel = null;

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

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

                BindAttributes(selectedChannel);
                AddDynamicControls(selectedChannel);

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

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

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

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

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

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

            var items = new List <ContentChannelItem>();

            var contentChannelItemService = new ContentChannelItemService(rockContext);

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

            var drp = new DateRangePicker();

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

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

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

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

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

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

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

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

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

            if (selectedChannel.ItemsManuallyOrdered && !isFiltered)
            {
                return(items.OrderBy(i => i.Order).ToList());
            }
            else
            {
                return(items);
            }
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Gets the data to display.
        /// </summary>
        private void GetData()
        {
            var rockContext = new RockContext();
            var itemService = new ContentChannelItemService(rockContext);

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

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

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


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

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

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

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

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

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

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

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

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

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

            var contentChannels = qry.ToList();

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

            ContentChannel selectedChannel = null;

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

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

                BindAttributes(selectedChannel);
                AddDynamicControls(selectedChannel);

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

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

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

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

                    gContentChannelItems.AllowSorting = true;

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

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

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

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

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

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

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

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

                lContentChannelItems.Text = selectedChannel.Name + " Items";
            }
            else
            {
                divItemPanel.Visible = false;
            }
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Shows the detail.
        /// </summary>
        /// <param name="contentChannelId">The marketing campaign ad type identifier.</param>
        public void ShowDetail( int contentChannelId )
        {
            ContentChannel contentChannel = null;

            bool editAllowed = IsUserAuthorized( Authorization.EDIT );

            var rockContext = new RockContext();

            if ( !contentChannelId.Equals( 0 ) )
            {
                contentChannel = GetContentChannel( contentChannelId );
                if ( contentChannel != null )
                {
                    editAllowed = editAllowed || contentChannel.IsAuthorized( Authorization.EDIT, CurrentPerson );
                }
            }

            if ( contentChannel == null )
            {
                contentChannel = new ContentChannel { Id = 0 };
            }

            if ( contentChannel != null && contentChannel.IsAuthorized( Authorization.VIEW, CurrentPerson ) )
            {
                hfId.Value = contentChannel.Id.ToString();

                bool readOnly = false;
                nbEditModeMessage.Text = string.Empty;

                if ( !editAllowed || !IsUserAuthorized( Authorization.EDIT ) )
                {
                    readOnly = true;
                    nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed( ContentChannel.FriendlyTypeName );
                }

                if ( readOnly )
                {
                    lbEdit.Visible = false;
                    ShowReadonlyDetails( contentChannel );
                }
                else
                {
                    lbEdit.Visible = true;
                    if ( contentChannel.Id > 0 )
                    {
                        ShowReadonlyDetails( contentChannel );
                    }
                    else
                    {
                        ShowEditDetails( contentChannel );
                    }
                }

                lbSave.Visible = !readOnly;
            }
            else
            {
                nbEditModeMessage.Text = EditModeMessage.NotAuthorizedToView( ContentChannel.FriendlyTypeName );
                pnlEditDetails.Visible = false;
                fieldsetViewSummary.Visible = false;
            }
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Creates the filter control.
        /// </summary>
        /// <param name="parentControl">The parent control.</param>
        /// <param name="filter">The filter.</param>
        /// <param name="setSelection">if set to <c>true</c> [set selection].</param>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="contentChannel">The content channel.</param>
        private void CreateFilterControl(Control parentControl, DataViewFilter filter, bool setSelection, RockContext rockContext, ContentChannel contentChannel)
        {
            try
            {
                if (filter.ExpressionType == FilterExpressionType.Filter)
                {
                    var filterControl = new FilterField
                    {
                        Entity = new ContentChannelItem
                        {
                            ContentChannelId     = contentChannel.Id,
                            ContentChannelTypeId = contentChannel.ContentChannelTypeId
                        }
                    };

                    parentControl.Controls.Add(filterControl);
                    filterControl.DataViewFilterGuid = filter.Guid;
                    filterControl.ID = string.Format("ff_{0}", filterControl.DataViewFilterGuid.ToString("N"));

                    // Remove the 'Other Data View' Filter as it doesn't really make sense to have it available in this scenario
                    filterControl.ExcludedFilterTypes    = new string[] { typeof(Rock.Reporting.DataFilter.OtherDataViewFilter).FullName };
                    filterControl.FilteredEntityTypeName = ITEM_TYPE_NAME;

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

                    filterControl.Expanded = filter.Expanded;
                    if (setSelection)
                    {
                        try
                        {
                            filterControl.SetSelection(filter.Selection);
                        }
                        catch (Exception ex)
                        {
                            ExceptionLogService.LogException(new Exception("Exception setting selection for DataViewFilter: " + filter.Guid, ex));
                        }
                    }

                    filterControl.DeleteClick += filterControl_DeleteClick;
                }
                else
                {
                    var groupControl = new FilterGroup();
                    parentControl.Controls.Add(groupControl);
                    groupControl.DataViewFilterGuid = filter.Guid;
                    groupControl.ID = string.Format("fg_{0}", groupControl.DataViewFilterGuid.ToString("N"));
                    groupControl.FilteredEntityTypeName = ITEM_TYPE_NAME;
                    groupControl.IsDeleteEnabled        = parentControl is FilterGroup;
                    if (setSelection)
                    {
                        groupControl.FilterType = filter.ExpressionType;
                    }

                    groupControl.AddFilterClick   += groupControl_AddFilterClick;
                    groupControl.AddGroupClick    += groupControl_AddGroupClick;
                    groupControl.DeleteGroupClick += groupControl_DeleteGroupClick;
                    foreach (var childFilter in filter.ChildFilters)
                    {
                        CreateFilterControl(groupControl, childFilter, setSelection, rockContext, contentChannel);
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionLogService.LogException(new Exception("Exception creating FilterControl for DataViewFilter: " + filter.Guid, ex));
            }
        }
        /// <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();
        }
 /// <summary>
 /// Sets the heading information.
 /// </summary>
 /// <param name="contentChannel">Type of the content.</param>
 /// <param name="title">The title.</param>
 private void SetHeadingInfo( ContentChannel contentChannel, string title )
 {
     string cssIcon = contentChannel.IconCssClass;
     if (string.IsNullOrWhiteSpace(cssIcon))
     {
         cssIcon = "fa fa-bullhorn";
     }
     lIcon.Text = string.Format("<i class='{0}'></i>", cssIcon);
     lTitle.Text = title.FormatAsHtmlTitle();
     hlContentChannel.Text = contentChannel.ContentChannelType != null ? contentChannel.ContentChannelType.Name : string.Empty;
 }
Ejemplo n.º 30
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();
            ContentChannel contentChannel;

            ContentChannelService contentChannelService = new ContentChannelService(rockContext);

            int contentChannelId = hfId.Value.AsInteger();

            if (contentChannelId == 0)
            {
                contentChannel = new ContentChannel {
                    Id = 0
                };
                contentChannelService.Add(contentChannel);
            }
            else
            {
                contentChannel = contentChannelService.Get(contentChannelId);
            }

            if (contentChannel != null)
            {
                contentChannel.Name                      = tbName.Text;
                contentChannel.Description               = tbDescription.Text;
                contentChannel.ContentChannelTypeId      = ddlChannelType.SelectedValueAsInt() ?? 0;
                contentChannel.ContentControlType        = ddlContentControlType.SelectedValueAsEnum <ContentControlType>();
                contentChannel.RootImageDirectory        = tbRootImageDirectory.Visible ? tbRootImageDirectory.Text : string.Empty;
                contentChannel.IconCssClass              = tbIconCssClass.Text;
                contentChannel.RequiresApproval          = cbRequireApproval.Checked;
                contentChannel.ItemsManuallyOrdered      = cbItemsManuallyOrdered.Checked;
                contentChannel.ChildItemsManuallyOrdered = cbChildItemsManuallyOrdered.Checked;
                contentChannel.EnableRss                 = cbEnableRss.Checked;
                contentChannel.ChannelUrl                = tbChannelUrl.Text;
                contentChannel.ItemUrl                   = tbItemUrl.Text;
                contentChannel.TimeToLive                = nbTimetoLive.Text.AsIntegerOrNull();

                contentChannel.ChildContentChannels = new List <ContentChannel>();
                contentChannel.ChildContentChannels.Clear();
                foreach (var item in ChildContentChannelsList)
                {
                    var childContentChannel = contentChannelService.Get(item);
                    if (childContentChannel != null)
                    {
                        contentChannel.ChildContentChannels.Add(childContentChannel);
                    }
                }

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

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

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

                    foreach (var item in new ContentChannelItemService(rockContext)
                             .Queryable()
                             .Where(i =>
                                    i.ContentChannelId == contentChannel.Id &&
                                    i.ContentChannelTypeId != contentChannel.ContentChannelTypeId
                                    ))
                    {
                        item.ContentChannelTypeId = contentChannel.ContentChannelTypeId;
                    }

                    rockContext.SaveChanges();

                    // Save the Item Attributes
                    int entityTypeId = EntityTypeCache.Read(typeof(ContentChannelItem)).Id;
                    SaveAttributes(contentChannel.Id, entityTypeId, ItemAttributesState, rockContext);
                });

                var pageReference = RockPage.PageReference;
                pageReference.Parameters.AddOrReplace("contentChannelId", contentChannel.Id.ToString());
                Response.Redirect(pageReference.BuildUrl(), false);
            }
        }
Ejemplo n.º 31
0
        private void GetData()
        {
            var rockContext = new RockContext();
            var itemService = new ContentChannelItemService(rockContext);

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

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

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

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

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

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

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

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

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

            var contentChannels = qry.ToList();

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

            ContentChannel selectedChannel = null;

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

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

                BindAttributes(selectedChannel);
                AddDynamicControls(selectedChannel);

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

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

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

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

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

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

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

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

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

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

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

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

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

                lContentChannelItems.Text = selectedChannel.Name + " Items";
            }
            else
            {
                divItemPanel.Visible = false;
            }
        }
Ejemplo n.º 32
0
        /// <summary>
        /// Deletes the specified item.
        /// </summary>
        /// <param name="item">The item.</param>
        public override bool Delete( ContentChannel item )
        {
            string message;
            if ( !CanDelete( item, out message ) )
            {
                return false;
            }

            return base.Delete( item );
        }
Ejemplo n.º 33
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 GetData()
        {
            var rockContext = new RockContext();
            var itemService = new ContentChannelItemService(rockContext);

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

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

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

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

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

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

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

            var contentChannels = qry.ToList();

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

            ContentChannel selectedChannel = null;

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

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

                AddColumns(selectedChannel);

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

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

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

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

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

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

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

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

                lContentChannelItems.Text = selectedChannel.Name + " Items";
            }
            else
            {
                divItemPanel.Visible = false;
            }
        }
Ejemplo n.º 35
0
        protected void AddDynamicControls(ContentChannel channel)
        {
            // Remove all columns
            gContentChannelItems.Columns.Clear();
            phAttributeFilters.Controls.Clear();

            if (channel != null)
            {
                // Add Title column
                var titleField = new BoundField();
                titleField.DataField      = "Title";
                titleField.HeaderText     = "Title";
                titleField.SortExpression = "Title";
                gContentChannelItems.Columns.Add(titleField);

                // Add Attribute columns
                int    entityTypeId  = EntityTypeCache.Read(typeof(Rock.Model.ContentChannelItem)).Id;
                string channelId     = channel.Id.ToString();
                string channelTypeId = channel.ContentChannelTypeId.ToString();
                foreach (var attribute in AvailableAttributes)
                {
                    var control = attribute.FieldType.Field.FilterControl(attribute.QualifierValues, "filter_" + attribute.Id.ToString(), false, Rock.Reporting.FilterMode.SimpleFilter);
                    if (control != null)
                    {
                        if (control is IRockControl)
                        {
                            var rockControl = (IRockControl)control;
                            rockControl.Label = attribute.Name;
                            rockControl.Help  = attribute.Description;
                            phAttributeFilters.Controls.Add(control);
                        }
                        else
                        {
                            var wrapper = new RockControlWrapper();
                            wrapper.ID    = control.ID + "_wrapper";
                            wrapper.Label = attribute.Name;
                            wrapper.Controls.Add(control);
                            phAttributeFilters.Controls.Add(wrapper);
                        }

                        string savedValue = gfFilter.GetUserPreference(MakeKeyUniqueToChannel(channel.Id, attribute.Key));
                        if (!string.IsNullOrWhiteSpace(savedValue))
                        {
                            try
                            {
                                var values = JsonConvert.DeserializeObject <List <string> >(savedValue);
                                attribute.FieldType.Field.SetFilterValues(control, attribute.QualifierValues, values);
                            }
                            catch
                            {
                                // intentionally ignore
                            }
                        }
                    }

                    string dataFieldExpression = attribute.Key;
                    bool   columnExists        = gContentChannelItems.Columns.OfType <AttributeField>().FirstOrDefault(a => a.DataField.Equals(dataFieldExpression)) != null;
                    if (!columnExists)
                    {
                        AttributeField boundField = new AttributeField();
                        boundField.DataField   = dataFieldExpression;
                        boundField.AttributeId = attribute.Id;
                        boundField.HeaderText  = attribute.Name;
                        boundField.ItemStyle.HorizontalAlign = attribute.FieldType.Field.AlignValue;
                        gContentChannelItems.Columns.Add(boundField);
                    }
                }

                if (channel.ContentChannelType.IncludeTime)
                {
                    // Add Start column
                    var startField = new DateTimeField();
                    startField.DataField      = "StartDateTime";
                    startField.HeaderText     = channel.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange ? "Start" : "Date";
                    startField.SortExpression = "StartDateTime";
                    gContentChannelItems.Columns.Add(startField);

                    // Expire column
                    if (channel.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange)
                    {
                        var expireField = new DateTimeField();
                        expireField.DataField      = "ExpireDateTime";
                        expireField.HeaderText     = "Expire";
                        expireField.SortExpression = "ExpireDateTime";
                        gContentChannelItems.Columns.Add(expireField);
                    }
                }
                else
                {
                    // Add Start column
                    var startField = new DateField();
                    startField.DataField      = "StartDateTime";
                    startField.HeaderText     = channel.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange ? "Start" : "Date";
                    startField.SortExpression = "StartDateTime";
                    gContentChannelItems.Columns.Add(startField);

                    // Expire column
                    if (channel.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange)
                    {
                        var expireField = new DateField();
                        expireField.DataField      = "ExpireDateTime";
                        expireField.HeaderText     = "Expire";
                        expireField.SortExpression = "ExpireDateTime";
                        gContentChannelItems.Columns.Add(expireField);
                    }
                }

                // Priority column
                var priorityField = new BoundField();
                priorityField.DataField                 = "Priority";
                priorityField.HeaderText                = "Priority";
                priorityField.SortExpression            = "Priority";
                priorityField.DataFormatString          = "{0:N0}";
                priorityField.ItemStyle.HorizontalAlign = HorizontalAlign.Right;
                gContentChannelItems.Columns.Add(priorityField);


                // Status column
                if (channel.RequiresApproval)
                {
                    var statusField = new BoundField();
                    gContentChannelItems.Columns.Add(statusField);
                    statusField.DataField      = "Status";
                    statusField.HeaderText     = "Status";
                    statusField.SortExpression = "Status";
                    statusField.HtmlEncode     = false;
                }

                // Add occurrences Count column
                var occurrencesField = new BoolField();
                occurrencesField.DataField  = "Occurrences";
                occurrencesField.HeaderText = "Event Occurrences";
                gContentChannelItems.Columns.Add(occurrencesField);

                // Add Created By column
                var createdByPersonNameField = new BoundField();
                createdByPersonNameField.DataField  = "CreatedByPersonName";
                createdByPersonNameField.HeaderText = "Created By";
                createdByPersonNameField.HtmlEncode = false;
                gContentChannelItems.Columns.Add(createdByPersonNameField);

                bool canEditChannel = channel.IsAuthorized(Rock.Security.Authorization.EDIT, CurrentPerson);
                gContentChannelItems.Actions.ShowAdd = canEditChannel;
                gContentChannelItems.IsDeleteEnabled = canEditChannel;
                if (canEditChannel)
                {
                    var deleteField = new DeleteField();
                    gContentChannelItems.Columns.Add(deleteField);
                    deleteField.Click += gContentChannelItems_Delete;
                }
            }
        }
        /// <summary>
        /// Handles the Click event of the lbConfigure control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        private void lbConfigure_Click(object sender, EventArgs e)
        {
            pnlContentComponentConfig.Visible = true;
            mdContentComponentConfig.Show();

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

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

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

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

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

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

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

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

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

            dvpContentComponentTemplate.SetValue(contentComponentTemplate);

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

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

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

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

            hfDataFilterId.Value = GetAttributeValue("FilterId");

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

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

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

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

            CreateFilterControl(this.ContentChannelTypeId, filter, true, rockContext);
        }
 protected void BindAttributes( ContentChannel channel )
 {
     AvailableAttributes = new List<AttributeCache>();
     int entityTypeId = EntityTypeCache.Read( typeof( Rock.Model.ContentChannelItem ) ).Id;
     string channelId = channel.Id.ToString();
     string channelTypeId = channel.ContentChannelTypeId.ToString();
     foreach ( var attributeModel in new AttributeService( new RockContext() ).Queryable()
         .Where( a =>
             a.EntityTypeId == entityTypeId &&
             a.IsGridColumn && ( (
                 a.EntityTypeQualifierColumn.Equals( "ContentChannelTypeId", StringComparison.OrdinalIgnoreCase ) &&
                 a.EntityTypeQualifierValue.Equals( channelTypeId )
             ) || (
                 a.EntityTypeQualifierColumn.Equals( "ContentChannelId", StringComparison.OrdinalIgnoreCase ) &&
                 a.EntityTypeQualifierValue.Equals( channelId )
             ) ) )
         .OrderBy( a => a.Order )
         .ThenBy( a => a.Name ) )
     {
         AvailableAttributes.Add( Rock.Web.Cache.AttributeCache.Read( attributeModel ) );
     }
 }
        protected void AddColumns( ContentChannel channel)
        {
            // Remove all columns
            gContentChannelItems.Columns.Clear();

            if ( channel != null )
            {
                // Add Title column
                var titleField = new BoundField();
                titleField.DataField = "Title";
                titleField.HeaderText = "Title";
                titleField.SortExpression = "Title";
                gContentChannelItems.Columns.Add( titleField );

                // Add Attribute columns
                int entityTypeId = EntityTypeCache.Read( typeof( Rock.Model.ContentChannelItem ) ).Id;
                string channelId = channel.Id.ToString();
                string channelTypeId = channel.ContentChannelTypeId.ToString();
                foreach ( var attribute in new AttributeService( new RockContext() ).Queryable()
                    .Where( a =>
                        a.EntityTypeId == entityTypeId &&
                        a.IsGridColumn && ( (
                            a.EntityTypeQualifierColumn.Equals( "ContentChannelTypeId", StringComparison.OrdinalIgnoreCase ) &&
                            a.EntityTypeQualifierValue.Equals( channelTypeId )
                        ) || (
                            a.EntityTypeQualifierColumn.Equals( "ContentChannelId", StringComparison.OrdinalIgnoreCase ) &&
                            a.EntityTypeQualifierValue.Equals( channelId )
                        ) ) )
                    .OrderBy( a => a.Order )
                    .ThenBy( a => a.Name ) )
                {
                    string dataFieldExpression = attribute.Key;
                    bool columnExists = gContentChannelItems.Columns.OfType<AttributeField>().FirstOrDefault( a => a.DataField.Equals( dataFieldExpression ) ) != null;
                    if ( !columnExists )
                    {
                        AttributeField boundField = new AttributeField();
                        boundField.DataField = dataFieldExpression;
                        boundField.HeaderText = attribute.Name;
                        boundField.SortExpression = string.Empty;

                        var attributeCache = Rock.Web.Cache.AttributeCache.Read( attribute.Id );
                        if ( attributeCache != null )
                        {
                            boundField.ItemStyle.HorizontalAlign = attributeCache.FieldType.Field.AlignValue;
                        }

                        gContentChannelItems.Columns.Add( boundField );
                    }
                }

                // Add Start column
                var startField = new DateTimeField();
                startField.DataField = "StartDateTime";
                startField.HeaderText = channel.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange ? "Start" : "Date";
                startField.SortExpression = "StartDateTime";
                gContentChannelItems.Columns.Add( startField );

                // Expire column
                if ( channel.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange )
                {
                    var expireField = new DateTimeField();
                    expireField.DataField = "ExpireDateTime";
                    expireField.HeaderText = "Expire";
                    expireField.SortExpression = "ExpireDateTime";
                    gContentChannelItems.Columns.Add( expireField );
                }

                // Priority column
                var priorityField = new BoundField();
                priorityField.DataField = "Priority";
                priorityField.HeaderText = "Priority";
                priorityField.SortExpression = "Priority";
                priorityField.DataFormatString = "{0:N0}";
                priorityField.ItemStyle.HorizontalAlign = HorizontalAlign.Right;
                gContentChannelItems.Columns.Add( priorityField );

                // Status column
                if ( channel.RequiresApproval )
                {
                    var statusField = new BoundField();
                    gContentChannelItems.Columns.Add( statusField );
                    statusField.DataField = "Status";
                    statusField.HeaderText = "Status";
                    statusField.SortExpression = "Status";
                    statusField.HtmlEncode = false;
                }

                bool canEditChannel = channel.IsAuthorized( Rock.Security.Authorization.EDIT, CurrentPerson );
                gContentChannelItems.Actions.ShowAdd = canEditChannel;
                gContentChannelItems.IsDeleteEnabled = canEditChannel;
                if ( canEditChannel )
                {

                    var deleteField = new DeleteField();
                    gContentChannelItems.Columns.Add( deleteField );
                    deleteField.Click += gContentChannelItems_Delete;
                }
            }
        }
        protected void AddDynamicControls( ContentChannel channel)
        {
            // Remove all columns
            gContentChannelItems.Columns.Clear();
            phAttributeFilters.Controls.Clear();

            if ( channel != null )
            {
                // Add Title column
                var titleField = new BoundField();
                titleField.DataField = "Title";
                titleField.HeaderText = "Title";
                titleField.SortExpression = "Title";
                gContentChannelItems.Columns.Add( titleField );

                // Add Attribute columns
                int entityTypeId = EntityTypeCache.Read( typeof( Rock.Model.ContentChannelItem ) ).Id;
                string channelId = channel.Id.ToString();
                string channelTypeId = channel.ContentChannelTypeId.ToString();
                foreach ( var attribute in AvailableAttributes )
                {
                    var control = attribute.FieldType.Field.FilterControl( attribute.QualifierValues, "filter_" + attribute.Id.ToString(), false, Rock.Reporting.FilterMode.SimpleFilter );
                    if ( control != null )
                    {
                        if ( control is IRockControl )
                        {
                            var rockControl = (IRockControl)control;
                            rockControl.Label = attribute.Name;
                            rockControl.Help = attribute.Description;
                            phAttributeFilters.Controls.Add( control );
                        }
                        else
                        {
                            var wrapper = new RockControlWrapper();
                            wrapper.ID = control.ID + "_wrapper";
                            wrapper.Label = attribute.Name;
                            wrapper.Controls.Add( control );
                            phAttributeFilters.Controls.Add( wrapper );
                        }

                        string savedValue = gfFilter.GetUserPreference( MakeKeyUniqueToChannel( channel.Id, attribute.Key ) );
                        if ( !string.IsNullOrWhiteSpace( savedValue ) )
                        {
                            try
                            {
                                var values = JsonConvert.DeserializeObject<List<string>>( savedValue );
                                attribute.FieldType.Field.SetFilterValues( control, attribute.QualifierValues, values );
                            }
                            catch
                            {
                                // intentionally ignore
                            }
                        }
                    }

                    string dataFieldExpression = attribute.Key;
                    bool columnExists = gContentChannelItems.Columns.OfType<AttributeField>().FirstOrDefault( a => a.DataField.Equals( dataFieldExpression ) ) != null;
                    if ( !columnExists )
                    {
                        AttributeField boundField = new AttributeField();
                        boundField.DataField = dataFieldExpression;
                        boundField.HeaderText = attribute.Name;
                        boundField.SortExpression = string.Empty;
                        boundField.ItemStyle.HorizontalAlign = attribute.FieldType.Field.AlignValue;
                        gContentChannelItems.Columns.Add( boundField );
                    }
                }

                if ( channel.ContentChannelType.IncludeTime )
                {
                    // Add Start column
                    var startField = new DateTimeField();
                    startField.DataField = "StartDateTime";
                    startField.HeaderText = channel.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange ? "Start" : "Date";
                    startField.SortExpression = "StartDateTime";
                    gContentChannelItems.Columns.Add( startField );

                    // Expire column
                    if ( channel.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange )
                    {
                        var expireField = new DateTimeField();
                        expireField.DataField = "ExpireDateTime";
                        expireField.HeaderText = "Expire";
                        expireField.SortExpression = "ExpireDateTime";
                        gContentChannelItems.Columns.Add( expireField );
                    }
                }
                else
                {
                    // Add Start column
                    var startField = new DateField();
                    startField.DataField = "StartDateTime";
                    startField.HeaderText = channel.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange ? "Start" : "Date";
                    startField.SortExpression = "StartDateTime";
                    gContentChannelItems.Columns.Add( startField );

                    // Expire column
                    if ( channel.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange )
                    {
                        var expireField = new DateField();
                        expireField.DataField = "ExpireDateTime";
                        expireField.HeaderText = "Expire";
                        expireField.SortExpression = "ExpireDateTime";
                        gContentChannelItems.Columns.Add( expireField );
                    }
                }

                // Priority column
                var priorityField = new BoundField();
                priorityField.DataField = "Priority";
                priorityField.HeaderText = "Priority";
                priorityField.SortExpression = "Priority";
                priorityField.DataFormatString = "{0:N0}";
                priorityField.ItemStyle.HorizontalAlign = HorizontalAlign.Right;
                gContentChannelItems.Columns.Add( priorityField );

                // Status column
                if ( channel.RequiresApproval )
                {
                    var statusField = new BoundField();
                    gContentChannelItems.Columns.Add( statusField );
                    statusField.DataField = "Status";
                    statusField.HeaderText = "Status";
                    statusField.SortExpression = "Status";
                    statusField.HtmlEncode = false;
                }

                // Add occurrences Count column
                var occurrencesField = new BoolField();
                occurrencesField.DataField = "Occurrences";
                occurrencesField.HeaderText = "Event Occurrences";
                gContentChannelItems.Columns.Add( occurrencesField );

                bool canEditChannel = channel.IsAuthorized( Rock.Security.Authorization.EDIT, CurrentPerson );
                gContentChannelItems.Actions.ShowAdd = canEditChannel;
                gContentChannelItems.IsDeleteEnabled = canEditChannel;
                if ( canEditChannel )
                {

                    var deleteField = new DeleteField();
                    gContentChannelItems.Columns.Add( deleteField );
                    deleteField.Click += gContentChannelItems_Delete;
                }
            }
        }
        /// <summary>
        /// Handles the SelectedIndexChanged event of the ddlChannelType 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 ddlChannelType_SelectedIndexChanged( object sender, EventArgs e )
        {
            ContentChannel channel = null;

            int contentChannelId = hfId.ValueAsInt();
            if ( contentChannelId != 0 )
            {
                channel = GetContentChannel( hfId.ValueAsInt() );
                if (channel != null &&
                    channel.ContentChannelTypeId.ToString() != ddlChannelType.SelectedValue &&
                    channel.Items.Any() )
                {
                    maContentChannelWarning.Show( "Changing the content type will result in all of this channel\\'s items losing any data that is specific to the original content type!", ModalAlertType.Warning );
                }
            }

            if (channel == null)
            {
                channel = new ContentChannel();
            }

            AddAttributeControls( channel );
        }
Ejemplo n.º 41
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();

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

            maContentChannelWarning.Hide();

            if ( !Page.IsPostBack )
            {
                int? contentChannelId = PageParameter( "contentChannelId" ).AsIntegerOrNull( );
                if( contentChannelId.HasValue )
                {
                    upnlContent.Visible = true;
                    ShowDetail( contentChannelId.Value );
                }
                else
                {
                    upnlContent.Visible = false;
                }
            }
            else
            {
                if ( pnlEditDetails.Visible )
                {
                    var channel = new ContentChannel();
                    channel.Id = hfId.Value.AsInteger();
                    channel.ContentChannelTypeId = hfTypeId.Value.AsInteger();
                    channel.LoadAttributes();
                    phAttributes.Controls.Clear();
                    Rock.Attribute.Helper.AddEditControls( channel, phAttributes, false, BlockValidationGroup );

                    ShowDialog();
                }
            }
        }
Ejemplo n.º 43
0
        /// <summary>
        /// Creates the filter control.
        /// </summary>
        /// <param name="channel">The channel.</param>
        /// <param name="filter">The filter.</param>
        /// <param name="setSelection">if set to <c>true</c> [set selection].</param>
        /// <param name="rockContext">The rock context.</param>
        private void CreateFilterControl( ContentChannel channel, DataViewFilter filter, bool setSelection, RockContext rockContext )
        {
            HackEntityFields( channel, rockContext );

            phFilters.Controls.Clear();
            if ( filter != null )
            {
                CreateFilterControl( phFilters, filter, setSelection, rockContext );
            }
        }
        /// <summary>
        /// Adds the attribute controls.
        /// </summary>
        /// <param name="contentChannel">The content channel.</param>
        private void AddAttributeControls( ContentChannel contentChannel )
        {
            int typeId = ddlChannelType.SelectedValueAsInt() ?? 0;
            hfTypeId.Value = typeId.ToString();

            contentChannel.ContentChannelTypeId = typeId;
            contentChannel.LoadAttributes();
            phAttributes.Controls.Clear();
            Rock.Attribute.Helper.AddEditControls( contentChannel, phAttributes, true, BlockValidationGroup );
        }
Ejemplo n.º 45
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();
            ContentChannel contentChannel;

            ContentChannelService contentChannelService = new ContentChannelService(rockContext);
            CategoryService       categoryService       = new CategoryService(rockContext);

            int contentChannelId = hfId.Value.AsInteger();

            if (contentChannelId == 0)
            {
                contentChannel = new ContentChannel {
                    Id = 0
                };
                contentChannelService.Add(contentChannel);
            }
            else
            {
                contentChannel = contentChannelService.Get(contentChannelId);
            }

            if (contentChannel != null)
            {
                contentChannel.Name                         = tbName.Text;
                contentChannel.Description                  = tbDescription.Text;
                contentChannel.ContentChannelTypeId         = ddlChannelType.SelectedValueAsInt() ?? 0;
                contentChannel.IsStructuredContent          = cbIsStructuredContent.Checked;
                contentChannel.StructuredContentToolValueId = dvEditorTool.SelectedDefinedValueId;
                contentChannel.ContentControlType           = ddlContentControlType.SelectedValueAsEnum <ContentControlType>();
                contentChannel.RootImageDirectory           = tbRootImageDirectory.Visible ? tbRootImageDirectory.Text : string.Empty;
                contentChannel.IconCssClass                 = tbIconCssClass.Text;

                // the cbRequireApproval will be hidden if contentChannelType.DisableStatus == True
                contentChannel.RequiresApproval          = cbRequireApproval.Visible && cbRequireApproval.Checked;
                contentChannel.IsIndexEnabled            = cbIndexChannel.Checked;
                contentChannel.ItemsManuallyOrdered      = cbItemsManuallyOrdered.Checked;
                contentChannel.ChildItemsManuallyOrdered = cbChildItemsManuallyOrdered.Checked;
                contentChannel.EnableRss         = cbEnableRss.Checked;
                contentChannel.ChannelUrl        = tbChannelUrl.Text;
                contentChannel.TimeToLive        = nbTimetoLive.Text.AsIntegerOrNull();
                contentChannel.ItemUrl           = tbContentChannelItemPublishingPoint.Text;
                contentChannel.IsTaggingEnabled  = cbEnableTag.Checked;
                contentChannel.ItemTagCategoryId = cbEnableTag.Checked ? cpCategory.SelectedValueAsInt() : ( int? )null;

                // Add any categories
                contentChannel.Categories.Clear();
                foreach (var categoryId in cpCategories.SelectedValuesAsInt())
                {
                    contentChannel.Categories.Add(categoryService.Get(categoryId));
                }

                // Since changes to Categories isn't tracked by ChangeTracker, set the ModifiedDateTime just in case Categories changed
                contentChannel.ModifiedDateTime = RockDateTime.Now;

                contentChannel.ChildContentChannels = new List <ContentChannel>();
                contentChannel.ChildContentChannels.Clear();
                foreach (var item in ChildContentChannelsList)
                {
                    var childContentChannel = contentChannelService.Get(item);
                    if (childContentChannel != null)
                    {
                        contentChannel.ChildContentChannels.Add(childContentChannel);
                    }
                }

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

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

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

                    foreach (var item in new ContentChannelItemService(rockContext)
                             .Queryable()
                             .Where(i =>
                                    i.ContentChannelId == contentChannel.Id &&
                                    i.ContentChannelTypeId != contentChannel.ContentChannelTypeId
                                    ))
                    {
                        item.ContentChannelTypeId = contentChannel.ContentChannelTypeId;
                    }

                    rockContext.SaveChanges();

                    // Save the Item Attributes
                    int entityTypeId = EntityTypeCache.Get(typeof(ContentChannelItem)).Id;
                    SaveAttributes(contentChannel.Id, entityTypeId, ItemAttributesState, rockContext);
                });

                var pageReference = RockPage.PageReference;
                pageReference.Parameters.AddOrReplace("ContentChannelId", contentChannel.Id.ToString());
                Response.Redirect(pageReference.BuildUrl(), false);
            }
        }
        /// <summary>
        /// Shows the readonly details.
        /// </summary>
        /// <param name="contentChannel">Type of the content.</param>
        private void ShowReadonlyDetails( ContentChannel contentChannel )
        {
            SetEditMode( false );

            if ( contentChannel != null )
            {
                hfId.SetValue( contentChannel.Id );

                SetHeadingInfo( contentChannel, contentChannel.Name );
                SetEditMode( false );

                lGroupDescription.Text = contentChannel.Description;

                var descriptionList = new DescriptionList();
                if ( contentChannel.EnableRss )
                {
                    descriptionList
                    .Add( "Item's Require Approval", contentChannel.RequiresApproval.ToString() )
                    .Add( "Channel Url", contentChannel.ChannelUrl )
                    .Add( "Item Url", contentChannel.ItemUrl );
                }

                contentChannel.LoadAttributes();
                foreach ( var attribute in contentChannel.Attributes
                    .Where( a => a.Value.IsGridColumn )
                    .OrderBy( a => a.Value.Order )
                    .Select( a => a.Value ) )
                {
                    if ( contentChannel.AttributeValues.ContainsKey( attribute.Key ) )
                    {
                        string value = attribute.FieldType.Field.FormatValueAsHtml( null,
                            contentChannel.AttributeValues[attribute.Key].Value, attribute.QualifierValues, false );
                        descriptionList.Add( attribute.Name, value );
                    }
                }

                lDetails.Text = descriptionList.Html;
            }
        }
        /// <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);
        }