Data access/service class for Rock.Model.ContentChannel objects.
    public IHttpActionResult Get(int seriesId)
    {
        var rockContext = new RockContext();

        var contentItemService = new ContentChannelService(rockContext);
        var d = new DotLiquid.Context();
        ContentChannel contentItem = null;

        var attrService = new AttributeService(rockContext);

        var dailyItems = new List<MessageArchiveItem>();

        var ids = rockContext.Database.SqlQuery<int>("exec GetMessageArchivesBySeriesId @seriesId", new SqlParameter("seriesId", seriesId)).ToList();

        contentItem = contentItemService.Get(11);

        var items = contentItem.Items.Where(a => ids.Contains(a.Id)).ToList();

        foreach (var item in items)
        {

            item.LoadAttributes(rockContext);

            var link = GetVimeoLink(item.GetAttributeValue("VideoId"));

            var newItem = new MessageArchiveItem();

            newItem.Id = item.Id;

            //   newItem.Content = item.Content;

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

            newItem.Date = DateTime.Parse(item.GetAttributeValue("Date")).ToShortDateString();
            newItem.Speaker = item.GetAttributeValue("Speaker");
            newItem.SpeakerTitle = item.GetAttributeValue("SpeakerTitle");
            newItem.Title = item.Title;
            newItem.VimeoLink = link;

            var notesAttr = item.Attributes["MessageNotes"];

            var binaryFile = new BinaryFileService(new RockContext()).Get(notesAttr.Id);

            if (binaryFile != null)
                newItem.Notes = binaryFile.Url;

            var talkAttr = item.Attributes["TalkItOver"];
            binaryFile = new BinaryFileService(new RockContext()).Get(talkAttr.Id);
            if (binaryFile != null)
                newItem.TalkItOver = binaryFile.Url;

            dailyItems.Add(newItem);
        }

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

            Guid? guid = value.AsGuidOrNull();
            if (guid.HasValue)
            {
                var contentChannel = new ContentChannelService( new RockContext() ).Get( guid.Value );
                if (contentChannel != null)
                {
                    formattedValue = contentChannel.Name;
                }
            }

            return base.FormatValue( parentControl, formattedValue, configurationValues, condensed );
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Gets the notifications.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="mergeFields">The merge fields.</param>
        /// <returns></returns>
        private List <com.blueboxmoon.Crex.Rest.Notification> GetNotifications(RockContext rockContext, Dictionary <string, object> mergeFields)
        {
            var contentChannelGuid = GetAttributeValue("NotificationChannel").AsGuidOrNull();

            if (!contentChannelGuid.HasValue)
            {
                return(null);
            }

            var contentChannel = new Rock.Model.ContentChannelService(rockContext).Get(contentChannelGuid.Value);

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

            //
            // Filter only items that are approved and should already be displayed.
            //
            var now   = RockDateTime.Now;
            var items = contentChannel.Items.AsQueryable()
                        .Where(i => i.StartDateTime < now);

            //
            // Filter any non-approved items.
            //
            if (contentChannel.RequiresApproval)
            {
                items = items.Where(i => i.ApprovedDateTime.HasValue);
            }

            //
            // Filter any expired items out.
            //
            if (contentChannel.ContentChannelType.DateRangeType == Rock.Model.ContentChannelDateType.DateRange)
            {
                items = items.Where(i => !i.ExpireDateTime.HasValue || i.ExpireDateTime > now);
            }

            items = items.OrderBy(i => i.StartDateTime);

            mergeFields.AddOrReplace("Items", items.ToList());

            var json = GetAttributeValue("NotificationTemplate").ResolveMergeFields(mergeFields, CurrentPerson);

            return(json.FromJsonOrNull <List <com.blueboxmoon.Crex.Rest.Notification> >());
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Creates the control(s) necessary for prompting user for a new value
        /// </summary>
        /// <param name="configurationValues">The configuration values.</param>
        /// <param name="id"></param>
        /// <returns>
        /// The control
        /// </returns>
        public override Control EditControl( Dictionary<string, ConfigurationValue> configurationValues, string id )
        {
            var editControl = new RockDropDownList { ID = id };
            editControl.Items.Add( new ListItem() );

            var contentChannels = new ContentChannelService( new RockContext() ).Queryable().OrderBy( d => d.Name );
            if ( contentChannels.Any() )
            {
                foreach ( var contentChannel in contentChannels )
                {
                    editControl.Items.Add( new ListItem( contentChannel.Name, contentChannel.Guid.ToString().ToUpper() ) );
                }

                return editControl;
            }

            return null;
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Creates the child controls.
        /// </summary>
        /// <returns></returns>
        public override Control[] CreateChildControls( Type entityType, FilterField filterControl )
        {
            RockDropDownList contentChannelPicker = new RockDropDownList();
            contentChannelPicker.CssClass = "js-content-channel-picker";
            contentChannelPicker.ID = filterControl.ID + "_contentChannelPicker";
            contentChannelPicker.Label = "Content Channel";

            contentChannelPicker.Items.Clear();
            var contentChannelList = new ContentChannelService( new RockContext() ).Queryable().OrderBy( a => a.Name ).ToList();
            foreach ( var contentChannel in contentChannelList )
            {
                contentChannelPicker.Items.Add( new ListItem( contentChannel.Name, contentChannel.Id.ToString() ) );
            }

            filterControl.Controls.Add( contentChannelPicker );

            return new Control[] { contentChannelPicker };
        }
Ejemplo n.º 6
0
    public List<int> Test()
    {
        var rockContext = new RockContext();

        var contentItemService = new ContentChannelService(rockContext);
        var d = new DotLiquid.Context();
        ContentChannel contentItem = null;

        var attrService = new AttributeService(rockContext);

        var dailyItems = new List<int>();

        contentItem = contentItemService.Get(20);
        var items = contentItem.Items.Where(a => a.StartDateTime < DateTime.Now).OrderByDescending(i=>i.Id);

        foreach (var i in contentItem.Items)
        {
            dailyItems.Add(i.Id);
        }

        return dailyItems;
    }
Ejemplo n.º 7
0
        /// <summary>
        /// Gets the bread crumbs.
        /// </summary>
        /// <param name="pageReference">The page reference.</param>
        /// <returns></returns>
        public override List<BreadCrumb> GetBreadCrumbs( PageReference pageReference )
        {
            var breadCrumbs = new List<BreadCrumb>();

            int? contentChannelId = PageParameter( pageReference, "contentChannelId" ).AsIntegerOrNull();
            if ( contentChannelId != null )
            {
                ContentChannel contentChannel = new ContentChannelService( new RockContext() ).Get( contentChannelId.Value );
                if ( contentChannel != null )
                {
                    breadCrumbs.Add( new BreadCrumb( contentChannel.Name, pageReference ) );
                }
                else
                {
                    breadCrumbs.Add( new BreadCrumb( "New Content Channel", pageReference ) );
                }
            }
            else
            {
                // don't show a breadcrumb if we don't have a pageparam to work with
            }

            return breadCrumbs;
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Handles the Click event of the btnSave 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 btnSave_Click( object sender, EventArgs e )
        {
            EventCalendar eventCalendar;
            using ( var rockContext = new RockContext() )
            {
                EventCalendarService eventCalendarService = new EventCalendarService( rockContext );
                EventCalendarContentChannelService eventCalendarContentChannelService = new EventCalendarContentChannelService( rockContext );
                ContentChannelService contentChannelService = new ContentChannelService( rockContext );
                AttributeService attributeService = new AttributeService( rockContext );
                AttributeQualifierService qualifierService = new AttributeQualifierService( rockContext );

                int eventCalendarId = int.Parse( hfEventCalendarId.Value );

                if ( eventCalendarId == 0 )
                {
                    eventCalendar = new EventCalendar();
                    eventCalendarService.Add( eventCalendar );
                }
                else
                {
                    eventCalendar = eventCalendarService.Get( eventCalendarId );
                }

                eventCalendar.IsActive = cbActive.Checked;
                eventCalendar.Name = tbName.Text;
                eventCalendar.Description = tbDescription.Text;
                eventCalendar.IconCssClass = tbIconCssClass.Text;

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

                // need WrapTransaction due to Attribute saves
                rockContext.WrapTransaction( () =>
                {
                    rockContext.SaveChanges();

                    var dbChannelGuids = eventCalendarContentChannelService.Queryable()
                        .Where( c => c.EventCalendarId == eventCalendar.Id )
                        .Select( c => c.Guid )
                        .ToList();

                    var uiChannelGuids = ContentChannelsState.Select( c => c.Key ).ToList();

                    var toDelete = eventCalendarContentChannelService
                        .Queryable()
                        .Where( c =>
                            dbChannelGuids.Contains( c.Guid ) &&
                            !uiChannelGuids.Contains( c.Guid ));

                    eventCalendarContentChannelService.DeleteRange( toDelete );
                    contentChannelService.Queryable()
                        .Where( c =>
                            uiChannelGuids.Contains( c.Guid ) &&
                            !dbChannelGuids.Contains( c.Guid ) )
                        .ToList()
                        .ForEach( c =>
                        {
                            var eventCalendarContentChannel = new EventCalendarContentChannel();
                            eventCalendarContentChannel.EventCalendarId = eventCalendar.Id;
                            eventCalendarContentChannel.ContentChannelId = c.Id;
                            eventCalendarContentChannelService.Add( eventCalendarContentChannel );
                        } );

                    rockContext.SaveChanges();

                    /* Save Attributes */
                    string qualifierValue = eventCalendar.Id.ToString();
                    SaveAttributes( new EventCalendarItem().TypeId, "EventCalendarId", qualifierValue, AttributesState, rockContext );

                    // Reload calendar and make sure that the person who may have just added a calendar has security to view/edit/administrate the calendar
                    eventCalendar = eventCalendarService.Get( eventCalendar.Id );
                    if ( eventCalendar != null )
                    {
                        if ( !eventCalendar.IsAuthorized( Authorization.VIEW, CurrentPerson ) )
                        {
                            eventCalendar.AllowPerson( Authorization.VIEW, CurrentPerson, rockContext );
                        }
                        if ( !eventCalendar.IsAuthorized( Authorization.EDIT, CurrentPerson ) )
                        {
                            eventCalendar.AllowPerson( Authorization.EDIT, CurrentPerson, rockContext );
                        }
                        if ( !eventCalendar.IsAuthorized( Authorization.ADMINISTRATE, CurrentPerson ) )
                        {
                            eventCalendar.AllowPerson( Authorization.ADMINISTRATE, CurrentPerson, rockContext );
                        }
                    }

                } );
            }

            // Redirect back to same page so that item grid will show any attributes that were selected to show on grid
            var qryParams = new Dictionary<string, string>();
            qryParams["EventCalendarId"] = eventCalendar.Id.ToString();
            NavigateToPage( RockPage.Guid, qryParams );
        }
        /// <summary>
        /// Gets the type of the content.
        /// </summary>
        /// <param name="contentItemId">The content type identifier.</param>
        /// <param name="rockContext">The rock context.</param>
        /// <returns></returns>
        private ContentChannelItem GetContentItem( RockContext rockContext = null )
        {
            rockContext = rockContext ?? new RockContext();
            var contentItemService = new ContentChannelItemService( rockContext );
            ContentChannelItem contentItem = null;

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

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

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

                    contentItemService.Add( contentItem );
                }
            }

            return contentItem;
        }
Ejemplo n.º 10
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 );

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

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

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

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

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

                lContentChannelItems.Text = selectedChannel.Name + " Items";
            }
            else
            {
                divItemPanel.Visible = false;
            }
        }
        /// <summary>
        /// Binds the child content channels grid.
        /// </summary>
        private void BindChildContentChannelsGrid()
        {
            var contentChannelList = new ContentChannelService( new RockContext() )
                .Queryable()
                .Where( t => ChildContentChannelsList.Contains( t.Id ) )
                .OrderBy( t => t.Name )
                .ToList();

            gChildContentChannels.DataSource = contentChannelList;
            gChildContentChannels.DataBind();
        }
        /// <summary>
        /// Handles the Add event of the gChildContentChannels 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 gChildContentChannels_Add( object sender, EventArgs e )
        {
            // populate dropdown with all grouptypes that aren't already childgroups
            var contentChannelList = new ContentChannelService( new RockContext() )
                .Queryable()
                .Where( t => !ChildContentChannelsList.Contains( t.Id ) )
                .OrderBy( t => t.Name )
                .ToList();

            if ( contentChannelList.Count == 0 )
            {
                modalAlert.Show( "There are not any other content channels that can be added", ModalAlertType.Warning );
            }
            else
            {
                ddlChildContentChannel.DataSource = contentChannelList;
                ddlChildContentChannel.DataBind();
                ShowDialog( "ChildContentChannels" );
            }
        }
        /// <summary>
        /// Shows the active users.
        /// </summary>
        private void DisplayItems()
        {
            RockContext rockContext = new RockContext();

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

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

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

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

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

            string template = GetAttributeValue( "LavaTemplate" );

            lContent.Text = template.ResolveMergeFields( mergeFields );

            // show debug info
            if ( GetAttributeValue( "EnableDebug" ).AsBoolean() && IsUserAuthorized( Authorization.EDIT ) )
            {
                lDebug.Visible = true;
                lDebug.Text = mergeFields.lavaDebugInfo();
            }
        }
        /// <summary>
        /// Restores the view-state information from a previous user control request that was saved by the <see cref="M:System.Web.UI.UserControl.SaveViewState" /> method.
        /// </summary>
        /// <param name="savedState">An <see cref="T:System.Object" /> that represents the user control state to be restored.</param>
        protected override void LoadViewState( object savedState )
        {
            base.LoadViewState( savedState );

            SelectedChannelId = ViewState["SelectedChannelId"] as int?;

            if ( SelectedChannelId.HasValue )
            {
                var channel = new ContentChannelService( new RockContext() ).Get( SelectedChannelId.Value );
                if ( channel != null )
                {
                    BindAttributes( channel );
                    AddDynamicControls( channel );
                }
            }
        }
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            ContentChannelService contentChannelService = new ContentChannelService( new RockContext() );
            SortProperty sortProperty = gContentChannels.SortProperty;
            var qry = contentChannelService.Queryable( "ContentChannelType,Items" );

            int? typeId = gfFilter.GetUserPreference( "Type" ).AsIntegerOrNull();
            if ( typeId.HasValue )
            {
                qry = qry.Where( c => c.ContentChannelTypeId == typeId.Value );
            }

            gContentChannels.ObjectList = new Dictionary<string, object>();

            var channels = new List<ContentChannel>();
            foreach ( var channel in qry.ToList() )
            {
                if ( channel.IsAuthorized(Rock.Security.Authorization.VIEW, CurrentPerson))
                {
                    channels.Add( channel );
                    gContentChannels.ObjectList.Add( channel.Id.ToString(), channel );
                }
            }

            var now = RockDateTime.Now;
            var items = channels.Select( c => new
            {
                c.Id,
                c.Name,
                ContentChannelType = c.ContentChannelType.Name,
                c.EnableRss,
                c.ChannelUrl,
                ItemLastCreated = c.Items.Max( i => i.CreatedDateTime ),
                TotalItems = c.Items.Count(),
                ActiveItems = c.Items
                    .Where( i =>
                        ( i.StartDateTime.CompareTo( now ) < 0 ) &&
                        ( !i.ExpireDateTime.HasValue || i.ExpireDateTime.Value.CompareTo( now ) > 0 ) &&
                        ( i.ApprovedByPersonAliasId.HasValue || !c.RequiresApproval )
                    ).Count()
            } ).AsQueryable();

            if ( sortProperty != null )
            {
                gContentChannels.DataSource = items.Sort( sortProperty ).ToList();
            }
            else
            {
                gContentChannels.DataSource = items.OrderBy( p => p.Name ).ToList();
            }

            gContentChannels.DataBind();
        }
Ejemplo n.º 16
0
 /// <summary>
 /// Sets the selection.
 /// </summary>
 /// <param name="entityType">Type of the entity.</param>
 /// <param name="controls">The controls.</param>
 /// <param name="selection">The selection.</param>
 public override void SetSelection( Type entityType, Control[] controls, string selection )
 {
     string[] selectionValues = selection.Split( '|' );
     if ( selectionValues.Length >= 1 )
     {
         var contentChannel = new ContentChannelService( new RockContext() ).Get( selectionValues[0].AsGuid() );
         if ( contentChannel != null )
         {
             ( controls[0] as RockDropDownList ).SetValue( contentChannel.Id );
         }
     }
 }
Ejemplo n.º 17
0
        /// <summary>
        /// Gets the selection.
        /// </summary>
        /// <param name="entityType">Type of the entity.</param>
        /// <param name="controls">The controls.</param>
        /// <returns></returns>
        public override string GetSelection( Type entityType, Control[] controls )
        {
            int? contentChannelId = ( controls[0] as RockDropDownList ).SelectedValueAsId();
            Guid? contentChannelGuid = null;
            var contentChannel = new ContentChannelService( new RockContext() ).Get( contentChannelId ?? 0 );
            if ( contentChannel != null )
            {
                contentChannelGuid = contentChannel.Guid;
            }

            return contentChannelGuid.ToString();
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Gets the expression.
        /// </summary>
        /// <param name="entityType">Type of the entity.</param>
        /// <param name="serviceInstance">The service instance.</param>
        /// <param name="parameterExpression">The parameter expression.</param>
        /// <param name="selection">The selection.</param>
        /// <returns></returns>
        public override Expression GetExpression( Type entityType, IService serviceInstance, ParameterExpression parameterExpression, string selection )
        {
            string[] selectionValues = selection.Split( '|' );
            if ( selectionValues.Length >= 1 )
            {
                var contentChannel = new ContentChannelService( new RockContext() ).Get( selectionValues[0].AsGuid() );
                int? contentChannelId = null;
                if ( contentChannel != null )
                {
                    contentChannelId = contentChannel.Id;
                }

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

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

                return extractedFilterExpression;
            }

            return null;
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Formats the selection.
        /// </summary>
        /// <param name="entityType">Type of the entity.</param>
        /// <param name="selection">The selection.</param>
        /// <returns></returns>
        public override string FormatSelection( Type entityType, string selection )
        {
            string result = "Content Channel";
            string[] selectionValues = selection.Split( '|' );
            if ( selectionValues.Length >= 1 )
            {
                var contentChannel = new ContentChannelService( new RockContext() ).Get( selectionValues[0].AsGuid() );

                if ( contentChannel != null )
                {
                    result = string.Format( "Content Channel: {0}", contentChannel.Name );
                }
            }

            return result;
        }
        /// <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.Information );
                    return;
                }

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

            BindGrid();
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Restores the view-state information from a previous user control request that was saved by the <see cref="M:System.Web.UI.UserControl.SaveViewState" /> method.
        /// </summary>
        /// <param name="savedState">An <see cref="T:System.Object" /> that represents the user control state to be restored.</param>
        protected override void LoadViewState( object savedState )
        {
            base.LoadViewState( savedState );

            ChannelGuid = ViewState["ChannelGuid"] as Guid?;

            var rockContext = new RockContext();

            var channel = new ContentChannelService( rockContext ).Queryable( "ContentChannelType" )
                .FirstOrDefault( c => c.Guid.Equals( ChannelGuid.Value ) );
            if ( channel != null )
            {
                CreateFilterControl( channel, DataViewFilter.FromJson( ViewState["DataViewFilter"].ToString() ), false, rockContext );
            }
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Init" /> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnInit( EventArgs e )
        {
            base.OnInit( e );

            // set person context
            var contextEntity = this.ContextEntity();
            if ( contextEntity != null )
            {
                if ( contextEntity is Person )
                {
                    _person = contextEntity as Person;
                }
            }

            // set person if grid should be filtered by the current person
            if ( GetAttributeValue( "FilterItemsForCurrentUser" ).AsBoolean() )
            {
                _person = CurrentPerson;
            }

            gfFilter.Visible = GetAttributeValue( "ShowFilters" ).AsBoolean();

            _channelId = PageParameter( "contentChannelId" ).AsIntegerOrNull();
            if ( _channelId != null )
            {
                upnlContent.Visible = true;

                string cssIcon = "fa fa-bullhorn";
                var contentChannel = new ContentChannelService( new RockContext() ).Get( _channelId.Value );
                if ( contentChannel != null )
                {
                    string startHeading = contentChannel.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange ? "Start" : "Active";
                    bool isRange = contentChannel.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange;

                    gItems.Columns[1].HeaderText = startHeading;
                    gItems.Columns[3].HeaderText = startHeading;

                    ddlStatus.Visible = contentChannel.RequiresApproval;

                    if ( contentChannel.ContentChannelType.IncludeTime )
                    {
                        gItems.Columns[1].Visible = true;
                        gItems.Columns[2].Visible = isRange;
                        gItems.Columns[3].Visible = false;
                        gItems.Columns[4].Visible = false;
                    }
                    else
                    {
                        gItems.Columns[1].Visible = false;
                        gItems.Columns[2].Visible = false;
                        gItems.Columns[3].Visible = true;
                        gItems.Columns[4].Visible = isRange;
                    }

                    gItems.Columns[5].Visible = !contentChannel.ContentChannelType.DisablePriority;
                    lContentChannel.Text = contentChannel.Name;
                    _typeId = contentChannel.ContentChannelTypeId;

                    if ( !string.IsNullOrWhiteSpace( contentChannel.IconCssClass ) )
                    {
                        cssIcon = contentChannel.IconCssClass;
                    }
                }

                lIcon.Text = string.Format( "<i class='{0}'></i>", cssIcon );

                // Block Security and special attributes (RockPage takes care of View)
                bool canAddEditDelete = IsUserAuthorized( Authorization.EDIT );

                gfFilter.ApplyFilterClick += gfFilter_ApplyFilterClick;
                gfFilter.DisplayFilterValue += gfFilter_DisplayFilterValue;

                gItems.DataKeyNames = new string[] { "Id" };
                gItems.Actions.ShowAdd = canAddEditDelete;
                gItems.IsDeleteEnabled = canAddEditDelete;
                gItems.Actions.AddClick += gItems_Add;
                gItems.GridRebind += gItems_GridRebind;

                AddAttributeColumns();

                if ( contentChannel != null && contentChannel.RequiresApproval )
                {
                    var statusField = new BoundField();
                    gItems.Columns.Add( statusField );
                    statusField.DataField = "Status";
                    statusField.HeaderText = "Status";
                    statusField.SortExpression = "Status";
                    statusField.HtmlEncode = false;
                }

                var securityField = new SecurityField();
                gItems.Columns.Add( securityField );
                securityField.TitleField = "Title";
                securityField.EntityTypeId = EntityTypeCache.Read( typeof( Rock.Model.ContentChannelItem ) ).Id;

                var deleteField = new DeleteField();
                gItems.Columns.Add( deleteField );
                deleteField.Click += gItems_Delete;

                // this event gets fired after block settings are updated. it's nice to repaint the screen if these settings would alter it
                this.BlockUpdated += Block_BlockUpdated;
                this.AddConfigurationUpdateTrigger( upnlContent );
            }
            else
            {
                upnlContent.Visible = false;
            }
        }
Ejemplo n.º 23
0
        private List<ContentChannelItem> GetContent( List<string> errorMessages )
        {
            var items = GetCacheItem( CONTENT_CACHE_KEY ) as List<ContentChannelItem>;
            bool queryParameterFiltering = GetAttributeValue( "QueryParameterFiltering" ).AsBoolean( false );

            if ( items == null || ( queryParameterFiltering && Request.QueryString.Count > 0 ) )
            {
                Guid? channelGuid = GetAttributeValue( "Channel" ).AsGuidOrNull();
                if ( channelGuid.HasValue )
                {
                    var rockContext = new RockContext();
                    var service = new ContentChannelItemService( rockContext );
                    var itemType = typeof( Rock.Model.ContentChannelItem );
                    
                    ParameterExpression paramExpression = service.ParameterExpression;

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

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

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

                            int? itemId = PageParameter( "Item" ).AsIntegerOrNull();
                            if ( queryParameterFiltering && itemId.HasValue )
                            {
                                qry = qry.Where( i => i.Id == itemId.Value );
                            }
                            else
                            {
                                qry = qry.Where( i => i.ContentChannelId == contentChannel.Id );

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

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

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

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

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

                            // Order the items
                            SortProperty sortProperty = null;

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

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

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

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

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

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

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

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

                                }

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

                            }

                            int? cacheDuration = GetAttributeValue( "CacheDuration" ).AsInteger();
                            if ( cacheDuration > 0 )
                            {
                                var cacheItemPolicy = new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.Now.AddSeconds( cacheDuration.Value ) };
                                AddCacheItem( CONTENT_CACHE_KEY, items, cacheItemPolicy );
                            }
                        }


                        // If items could be filtered by querystring values, check for filters
                        if ( queryParameterFiltering )
                        {
                            var pageParameters = PageParameters();
                            if ( pageParameters.Count > 0 )
                            {
                                var propertyFilter = new Rock.Reporting.DataFilter.PropertyFilter();

                                var itemQry = items.AsQueryable();
                                foreach ( string key in PageParameters().Select( p => p.Key ).ToList() )
                                {
                                    var selection = new List<string>();
                                    selection.Add( key );

                                    var entityField = entityFields.FirstOrDefault( f => f.Name.Equals( key, StringComparison.OrdinalIgnoreCase ) );
                                    if ( entityField != null )
                                    {
                                        string value = PageParameter( key );
                                        switch ( entityField.FieldType.Guid.ToString().ToUpper() )
                                        {
                                            case Rock.SystemGuid.FieldType.DAY_OF_WEEK:
                                            case Rock.SystemGuid.FieldType.SINGLE_SELECT:
                                                {
                                                    selection.Add( value );
                                                }
                                                break;
                                            case Rock.SystemGuid.FieldType.MULTI_SELECT:
                                                {
                                                    selection.Add( ComparisonType.Contains.ConvertToInt().ToString() );
                                                    selection.Add( value );
                                                }
                                                break;
                                            default:
                                                {
                                                    selection.Add( ComparisonType.EqualTo.ConvertToInt().ToString() );
                                                    selection.Add( value );
                                                }
                                                break;
                                        }

                                        itemQry = itemQry.Where( paramExpression, propertyFilter.GetExpression( itemType, service, paramExpression, Newtonsoft.Json.JsonConvert.SerializeObject( selection ) ) );
                                    }
                                }

                                items = itemQry.ToList();

                            }
                        }
                    }
                }
            }

            return items;

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

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

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

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

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

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

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

            var contentChannels = qry.ToList();

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

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

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

                BindAttributes( selectedChannel );
                AddDynamicControls( selectedChannel );

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

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

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

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

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

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

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

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

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

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

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

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

                lContentChannelItems.Text = selectedChannel.Name + " Items";
            }
            else
            {
                divItemPanel.Visible = false;
            }
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Shows the edit.
        /// </summary>
        public void ShowEdit()
        {
            int? filterId = hfDataFilterId.Value.AsIntegerOrNull();

            if ( ChannelGuid.HasValue )
            {
                var rockContext = new RockContext();
                var channel = new ContentChannelService( rockContext ).Queryable( "ContentChannelType" )
                    .FirstOrDefault( c => c.Guid.Equals( ChannelGuid.Value ) );
                if ( channel != null )
                {

                    cblStatus.Visible = channel.RequiresApproval;

                    cbSetRssAutodiscover.Visible = channel.EnableRss;

                    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( channel, filter, true, rockContext );

                    kvlOrder.CustomKeys = new Dictionary<string, string>();
                    kvlOrder.CustomKeys.Add( "", "" );
                    kvlOrder.CustomKeys.Add( "Title", "Title" );
                    kvlOrder.CustomKeys.Add( "Priority", "Priority" );
                    kvlOrder.CustomKeys.Add( "Status", "Status" );
                    kvlOrder.CustomKeys.Add( "StartDateTime", "Start" );
                    kvlOrder.CustomKeys.Add( "ExpireDateTime", "Expire" );
                    kvlOrder.CustomKeys.Add( "Order", "Order" );


                    // add attributes to the meta description and meta image attribute list
                    ddlMetaDescriptionAttribute.Items.Clear();
                    ddlMetaImageAttribute.Items.Clear();
                    ddlMetaDescriptionAttribute.Items.Add( "" );
                    ddlMetaImageAttribute.Items.Add( "" );

                    string currentMetaDescriptionAttribute = GetAttributeValue( "MetaDescriptionAttribute" ) ?? string.Empty;
                    string currentMetaImageAttribute = GetAttributeValue( "MetaImageAttribute" ) ?? string.Empty;

                    // add channel attributes
                    channel.LoadAttributes();
                    foreach ( var attribute in channel.Attributes )
                    {
                        var field = attribute.Value.FieldType.Field;
                        string computedKey = "C^" + attribute.Key;

                        ddlMetaDescriptionAttribute.Items.Add( new ListItem( "Channel: " + attribute.Value.ToString(), computedKey ) );

                        if ( field is Rock.Field.Types.ImageFieldType )
                        {
                            ddlMetaImageAttribute.Items.Add( new ListItem( "Channel: " + attribute.Value.ToString(), computedKey ) );
                        }
                    }

                    // add item attributes
                    AttributeService attributeService = new AttributeService( rockContext );
                    var itemAttributes = attributeService.GetByEntityTypeId( new ContentChannelItem().TypeId ).AsQueryable()
                                            .Where( a => (
                                                    a.EntityTypeQualifierColumn.Equals( "ContentChannelTypeId", StringComparison.OrdinalIgnoreCase ) &&
                                                    a.EntityTypeQualifierValue.Equals( channel.ContentChannelTypeId.ToString() ) 
                                                ) || (
                                                    a.EntityTypeQualifierColumn.Equals( "ContentChannelId", StringComparison.OrdinalIgnoreCase ) &&
                                                    a.EntityTypeQualifierValue.Equals( channel.Id.ToString() ) 
                                                ) )
                                            .ToList();

                    foreach ( var attribute in itemAttributes )
                    {
                        kvlOrder.CustomKeys.Add( "Attribute:" + attribute.Key, attribute.Name );

                        string computedKey = "I^" + attribute.Key;
                        ddlMetaDescriptionAttribute.Items.Add( new ListItem( "Item: " + attribute.Name, computedKey ) );

                        var field = attribute.FieldType.Name;

                        if ( field == "Image" )
                        {
                            ddlMetaImageAttribute.Items.Add( new ListItem( "Item: " + attribute.Name, computedKey ) );
                        }
                    }

                    // select attributes
                    SetListValue( ddlMetaDescriptionAttribute, currentMetaDescriptionAttribute );
                    SetListValue( ddlMetaImageAttribute, currentMetaImageAttribute );

                }
            }
        }
        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.º 27
0
        /// <summary>
        /// Formats the search result.
        /// </summary>
        /// <param name="person"></param>
        /// <param name="displayOptions"></param>
        /// <returns></returns>
        public override FormattedSearchResult FormatSearchResult( Person person, Dictionary<string, object> displayOptions = null )
        {
            bool showSummary = true;
            string url = string.Empty;
            bool isSecurityDisabled = false;

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

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

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

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

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

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

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

            return new FormattedSearchResult() { IsViewAllowed = true, FormattedResult = $@"
                            <div class='row model-cannavigate' data-href='{url.ResolveMergeFields( mergeFields )}'>
                                <div class='col-sm-1 text-center'>
                                    <i class='{this.IconCssClass} fa-2x'></i>
                                </div>
                                <div class='col-sm-4'>
                                    {this.Title} <small>({this.ContentChannel})</small>
                                </div>
                                <div class='col-sm-7'>
                                    {(showSummary ? summary : "")}
                                </div>
                            </div>" };
        }
        /// <summary>
        /// Handles the Click event of the 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.º 29
0
        /// <summary>
        /// Gets the document URL.
        /// </summary>
        /// <param name="displayOptions"></param>
        /// <returns></returns>
        public override string GetDocumentUrl( Dictionary<string, object> displayOptions = null )
        {
            string url = string.Empty;

            if ( displayOptions != null )
            {
                if ( displayOptions.ContainsKey( "ChannelItem.Url" ) )
                {
                    url = displayOptions["ChannelItem.Url"].ToString();
                }
            }

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

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

            return url.ResolveMergeFields( mergeFields );
        }
 /// <summary>
 /// Gets the type of the content.
 /// </summary>
 /// <param name="contentChannelId">The content type identifier.</param>
 /// <param name="rockContext">The rock context.</param>
 /// <returns></returns>
 private ContentChannel GetContentChannel( int contentChannelId, RockContext rockContext = null )
 {
     rockContext = rockContext ?? new RockContext();
     var contentChannel = new ContentChannelService( rockContext )
         .Queryable( "ContentChannelType" )
         .Where( t => t.Id == contentChannelId )
         .FirstOrDefault();
     return contentChannel;
 }
Ejemplo n.º 31
0
        public void ProcessRequest( HttpContext context )
        {
            request = context.Request;
            response = context.Response;

            RockContext rockContext = new RockContext();

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

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

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

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

                rssTemplate = dvRssTemplate.GetAttributeValue( "Template" );

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

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

                ContentChannelService channelService = new ContentChannelService( rockContext );

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

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

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

                        mergeFields.Add( "Request", requestObjects );

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

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

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

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

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

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

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

                        mergeFields.Add( "Items", content );

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

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

            }
            else
            {
                response.Write( "A ChannelId is required." );
                response.StatusCode = 200;
                return;
            }
        }