Example #1
0
        /// <summary>
        /// Gets the edit value as the IEntity.Id
        /// </summary>
        /// <param name="control">The control.</param>
        /// <param name="configurationValues">The configuration values.</param>
        /// <returns></returns>
        public int?GetEditValueAsEntityId(System.Web.UI.Control control, Dictionary <string, ConfigurationValue> configurationValues)
        {
            Guid guid     = GetEditValue(control, configurationValues).AsGuid();
            var  entityId = new ContentChannelTypeService(new RockContext()).GetId(guid);

            return(entityId);
        }
Example #2
0
        /// <summary>
        /// Creates the child controls.
        /// Implement this version of CreateChildControls if your DataFilterComponent supports different FilterModes
        /// </summary>
        /// <param name="entityType"></param>
        /// <param name="filterControl"></param>
        /// <param name="filterMode"></param>
        /// <returns></returns>
        public override Control[] CreateChildControls(Type entityType, FilterField filterControl, FilterMode filterMode)
        {
            var containerControl = new DynamicControlsPanel();

            containerControl.ID       = string.Format("{0}_containerControl", filterControl.ID);
            containerControl.CssClass = "js-container-control";
            filterControl.Controls.Add(containerControl);

            RockDropDownList contentChannelTypePicker = new RockDropDownList();

            contentChannelTypePicker.ID    = filterControl.ID + "_contentChannelTypePicker";
            contentChannelTypePicker.Label = "Content Channel Type";

            contentChannelTypePicker.Items.Clear();
            var contentChannelTypeList = new ContentChannelTypeService(new RockContext()).Queryable().OrderBy(a => a.Name).ToList();

            foreach (var contentChannelType in contentChannelTypeList)
            {
                contentChannelTypePicker.Items.Add(new ListItem(contentChannelType.Name, contentChannelType.Id.ToString()));
            }

            contentChannelTypePicker.SelectedIndexChanged += contentChannelTypePicker_SelectedIndexChanged;
            contentChannelTypePicker.AutoPostBack          = true;
            contentChannelTypePicker.Visible = filterMode == FilterMode.AdvancedFilter;
            containerControl.Controls.Add(contentChannelTypePicker);

            // set the contentChannelTypePicker selected value now so we can create the other controls that depend on knowing the contentChannelTypeId
            int?contentChannelTypeId = filterControl.Page.Request.Params[contentChannelTypePicker.UniqueID].AsIntegerOrNull();

            contentChannelTypePicker.SelectedValue = contentChannelTypeId.ToString();
            contentChannelTypePicker_SelectedIndexChanged(contentChannelTypePicker, new EventArgs());

            return(new Control[] { containerControl });
        }
Example #3
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 contentChannelTypeList = new ContentChannelTypeService(new RockContext()).Queryable()
                                         .OrderBy(d => d.Name)
                                         .Select(a => new { a.Name, a.Guid })
                                         .ToList();

            if (contentChannelTypeList.Any())
            {
                foreach (var contentChannelType in contentChannelTypeList)
                {
                    editControl.Items.Add(new ListItem(contentChannelType.Name, contentChannelType.Guid.ToString()));
                }

                return(editControl);
            }

            return(null);
        }
Example #4
0
        /// <summary>
        /// Sets the selection.
        /// </summary>
        /// <param name="entityType"></param>
        /// <param name="controls">The controls.</param>
        /// <param name="selection">The selection.</param>
        public override void SetSelection(Type entityType, Control[] controls, string selection)
        {
            if (!string.IsNullOrWhiteSpace(selection))
            {
                var values = JsonConvert.DeserializeObject <List <string> >(selection);
                if (controls.Length > 0 && values.Count > 0)
                {
                    var contentChannelType = new ContentChannelTypeService(new RockContext()).Get(values[0].AsGuid());
                    if (contentChannelType != null)
                    {
                        var containerControl = controls[0] as DynamicControlsPanel;
                        if (containerControl.Controls.Count > 0)
                        {
                            RockDropDownList contentChannelTypePicker = containerControl.Controls[0] as RockDropDownList;
                            contentChannelTypePicker.SelectedValue = contentChannelType.Id.ToString();
                            contentChannelTypePicker_SelectedIndexChanged(contentChannelTypePicker, new EventArgs());
                        }

                        if (containerControl.Controls.Count > 1 && values.Count > 1)
                        {
                            DropDownList ddlProperty  = containerControl.Controls[1] as DropDownList;
                            var          entityFields = GetContentChannelItemAttributes(contentChannelType.Id);

                            var panelControls = new List <Control>();
                            panelControls.AddRange(containerControl.Controls.OfType <Control>());
                            SetEntityFieldSelection(entityFields, ddlProperty, values.Skip(1).ToList(), panelControls);
                        }
                    }
                }
            }
        }
Example #5
0
        /// <summary>
        /// Gets the expression.
        /// </summary>
        /// <param name="entityType"></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)
        {
            if (!string.IsNullOrWhiteSpace(selection))
            {
                var values = JsonConvert.DeserializeObject <List <string> >(selection);

                if (values.Count >= 3)
                {
                    var contentChannelType = new ContentChannelTypeService(new RockContext()).Get(values[0].AsGuid());
                    if (contentChannelType != null)
                    {
                        string selectedProperty = values[1];

                        var entityFields = GetContentChannelItemAttributes(contentChannelType.Id);
                        var entityField  = entityFields.FirstOrDefault(f => f.Name == selectedProperty);
                        if (entityField != null)
                        {
                            return(GetAttributeExpression(serviceInstance, parameterExpression, entityField, values.Skip(2).ToList()));
                        }
                    }
                }
            }

            return(null);
        }
        /// <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?contentTypeId = PageParameter(pageReference, "typeId").AsIntegerOrNull();

            if (contentTypeId != null)
            {
                ContentChannelType contentType = new ContentChannelTypeService(new RockContext()).Get(contentTypeId.Value);
                if (contentType != null)
                {
                    breadCrumbs.Add(new BreadCrumb(contentType.Name, pageReference));
                }
                else
                {
                    breadCrumbs.Add(new BreadCrumb("New Content Type", pageReference));
                }
            }
            else
            {
                // don't show a breadcrumb if we don't have a pageparam to work with
            }

            return(breadCrumbs);
        }
Example #7
0
        /// <summary>
        /// Gfs the filter_ display filter value.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The e.</param>
        void gfFilter_DisplayFilterValue(object sender, GridFilter.DisplayFilterValueArgs e)
        {
            switch (e.Key)
            {
            case "Type":
            {
                int?typeId = e.Value.AsIntegerOrNull();
                if (typeId.HasValue)
                {
                    var contentType = new ContentChannelTypeService(new RockContext()).Get(typeId.Value);
                    if (contentType != null)
                    {
                        e.Value = contentType.Name;
                    }
                }
                break;
            }

            default:
            {
                e.Value = string.Empty;
                break;
            }
            }
        }
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            ContentChannelTypeService contentTypeService = new ContentChannelTypeService(new RockContext());
            SortProperty sortProperty = gContentChannelType.SortProperty;

            var types = contentTypeService.Queryable("Channels")
                        .Select(t => new
            {
                t.Id,
                t.Name,
                t.IsSystem,
                Channels = t.Channels.Count()
            })
                        .ToList();

            if (sortProperty != null)
            {
                types = types.AsQueryable().Sort(sortProperty).ToList();
            }
            else
            {
                types = types.OrderBy(p => p.Name).ToList();
            }

            gContentChannelType.EntityTypeId = EntityTypeCache.Read <ContentChannelType>().Id;
            gContentChannelType.DataSource   = types;
            gContentChannelType.DataBind();
        }
        /// <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();
            ContentChannelType contentType;

            ContentChannelTypeService contentTypeService = new ContentChannelTypeService(rockContext);

            int contentTypeId = int.Parse(hfId.Value);

            if (contentTypeId == 0)
            {
                contentType = new ContentChannelType();
                contentTypeService.Add(contentType);
                contentType.CreatedByPersonAliasId = CurrentPersonAliasId;
                contentType.CreatedDateTime        = RockDateTime.Now;
            }
            else
            {
                contentType = contentTypeService.Get(contentTypeId);
                contentType.ModifiedByPersonAliasId = CurrentPersonAliasId;
                contentType.ModifiedDateTime        = RockDateTime.Now;
            }

            if (contentType != null)
            {
                contentType.Name                = tbName.Text;
                contentType.DateRangeType       = ddlDateRangeType.SelectedValue.ConvertToEnum <ContentChannelDateType>();
                contentType.IncludeTime         = cbIncludeTime.Checked;
                contentType.DisablePriority     = cbDisablePriority.Checked;
                contentType.DisableContentField = cbDisableContentField.Checked;
                contentType.DisableStatus       = cbDisableStatus.Checked;
                contentType.ShowInChannelList   = cbShowInChannelList.Checked;

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

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

                    // get it back to make sure we have a good Id for it for the Attributes
                    contentType = contentTypeService.Get(contentType.Guid);

                    // Save the Channel Attributes
                    int entityTypeId = EntityTypeCache.Get(typeof(ContentChannel)).Id;
                    SaveAttributes(contentType.Id, entityTypeId, ChannelAttributesState, rockContext);

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

                NavigateToParentPage();
            }
        }
        /// <summary>
        /// Gets the type of the content.
        /// </summary>
        /// <param name="contentTypeId">The content type identifier.</param>
        /// <param name="rockContext">The rock context.</param>
        /// <returns></returns>
        private ContentChannelType GetContentChannelType(int contentTypeId, RockContext rockContext = null)
        {
            rockContext = rockContext ?? new RockContext();
            var contentType = new ContentChannelTypeService(rockContext)
                              .Queryable()
                              .Where(t => t.Id == contentTypeId)
                              .FirstOrDefault();

            return(contentType);
        }
Example #11
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 contentChannelType = new ContentChannelTypeService(new RockContext()).Get(selectionValues[0].AsGuid());
         if (contentChannelType != null)
         {
             (controls[0] as RockDropDownList).SetValue(contentChannelType.Id);
         }
     }
 }
Example #12
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? contentChannelTypeId   = (controls[0] as RockDropDownList).SelectedValueAsId();
            Guid?contentChannelTypeGuid = null;
            var  contentChannelType     = new ContentChannelTypeService(new RockContext()).Get(contentChannelTypeId ?? 0);

            if (contentChannelType != null)
            {
                contentChannelTypeGuid = contentChannelType.Guid;
            }

            return(contentChannelTypeGuid.ToString());
        }
Example #13
0
        /// <summary>
        /// Create an EntityField for an Attribute.
        /// </summary>
        /// <param name="attribute">The attribute.</param>
        /// <param name="limitToFilterableAttributes"></param>
        public static EntityField GetEntityFieldForAttribute(AttributeCache attribute, bool limitToFilterableAttributes = true)
        {
            // Ensure field name only has Alpha, Numeric and underscore chars
            string fieldName = attribute.Key.RemoveSpecialCharacters().Replace(".", "");

            EntityField entityField = null;

            // Make sure that the attributes field type actually renders a filter control if limitToFilterableAttributes
            var fieldType = FieldTypeCache.Read(attribute.FieldTypeId);

            if (fieldType != null && (!limitToFilterableAttributes || fieldType.Field.HasFilterControl()))
            {
                entityField       = new EntityField(fieldName, FieldKind.Attribute, typeof(string), attribute.Guid, fieldType);
                entityField.Title = attribute.Name.SplitCase();
                entityField.TitleWithoutQualifier = entityField.Title;

                foreach (var config in attribute.QualifierValues)
                {
                    entityField.FieldConfig.Add(config.Key, config.Value);
                }

                // Special processing for Entity Type "Group" to handle sub-types that are distinguished by GroupTypeId.
                if (attribute.EntityTypeId == EntityTypeCache.GetId(typeof(Group)) && attribute.EntityTypeQualifierColumn == "GroupTypeId")
                {
                    using (var rockContext = new RockContext())
                    {
                        var groupType = new GroupTypeService(rockContext).Get(attribute.EntityTypeQualifierValue.AsInteger());
                        if (groupType != null)
                        {
                            // Append the Qualifier to the title
                            entityField.Title = string.Format("{0} ({1})", attribute.Name, groupType.Name);
                        }
                    }
                }

                // Special processing for Entity Type "ContentChannelItem" to handle sub-types that are distinguished by ContentChannelTypeId.
                if (attribute.EntityTypeId == EntityTypeCache.GetId(typeof(ContentChannelItem)) && attribute.EntityTypeQualifierColumn == "ContentChannelTypeId")
                {
                    using (var rockContext = new RockContext())
                    {
                        var contentChannelType = new ContentChannelTypeService(rockContext).Get(attribute.EntityTypeQualifierValue.AsInteger());
                        if (contentChannelType != null)
                        {
                            // Append the Qualifier to the title
                            entityField.Title = string.Format("{0} ({1})", attribute.Name, contentChannelType.Name);
                        }
                    }
                }
            }
            return(entityField);
        }
Example #14
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();
            ContentChannelType contentType;

            ContentChannelTypeService contentTypeService = new ContentChannelTypeService(rockContext);

            int contentTypeId = int.Parse(hfId.Value);

            if (contentTypeId == 0)
            {
                contentType = new ContentChannelType();
                contentTypeService.Add(contentType);
            }
            else
            {
                contentType = contentTypeService.Get(contentTypeId);
            }

            if (contentType != null)
            {
                contentType.Name            = tbName.Text;
                contentType.DateRangeType   = (ContentChannelDateType)int.Parse(ddlDateRangeType.SelectedValue);
                contentType.DisablePriority = cbDisablePriority.Checked;

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

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

                    // get it back to make sure we have a good Id for it for the Attributes
                    contentType = contentTypeService.Get(contentType.Guid);

                    // Save the Channel Attributes
                    int entityTypeId = EntityTypeCache.Read(typeof(ContentChannel)).Id;
                    SaveAttributes(contentType.Id, entityTypeId, ChannelAttributesState, rockContext);

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

                NavigateToParentPage();
            }
        }
Example #15
0
        /// <summary>
        /// Gfs the filter_ display filter value.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The e.</param>
        void gfFilter_DisplayFilterValue(object sender, GridFilter.DisplayFilterValueArgs e)
        {
            switch (e.Key)
            {
            case UserPreferenceKey.Categories:
            {
                var categories = new List <string>();

                foreach (var idVal in e.Value.SplitDelimitedValues())
                {
                    int id = int.MinValue;
                    if (int.TryParse(idVal, out id))
                    {
                        if (id != 0)
                        {
                            var category = CategoryCache.Get(id);
                            if (category != null)
                            {
                                categories.Add(CategoryCache.Get(id).Name);
                            }
                        }
                    }
                }

                e.Value = categories.AsDelimited(", ");
                break;
            }

            case UserPreferenceKey.Type:
            {
                int?typeId = e.Value.AsIntegerOrNull();
                if (typeId.HasValue)
                {
                    var contentType = new ContentChannelTypeService(new RockContext()).Get(typeId.Value);
                    if (contentType != null)
                    {
                        e.Value = contentType.Name;
                    }
                }
                break;
            }

            default:
            {
                e.Value = string.Empty;
                break;
            }
            }
        }
Example #16
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;
            }
        }
Example #17
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 contentChannelName = new ContentChannelTypeService(new RockContext()).GetSelect(guid.Value, a => a.Name);
                if (contentChannelName != null)
                {
                    formattedValue = contentChannelName;
                }
            }

            return(base.FormatValue(parentControl, formattedValue, configurationValues, condensed));
        }
Example #18
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 Type";

            string[] selectionValues = selection.Split('|');
            if (selectionValues.Length >= 1)
            {
                var contentChannelType = new ContentChannelTypeService(new RockContext()).Get(selectionValues[0].AsGuid());

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

            return(result);
        }
        protected override void ShowSettings()
        {
            pnlConfigure.Visible = true;

            var rockContext = new RockContext();
            var contentChannelTypeService = new ContentChannelTypeService(rockContext);

            ddlContentChannelType.DataSource = contentChannelTypeService.Queryable().ToList();
            ddlContentChannelType.DataBind();

            int        contentChannelType = GetAttributeValue("ContentChannelType").AsInteger();
            List <int> contentChannels    = GetAttributeValue("ContentChannels").Split(',').AsIntegerList();
            List <int> attributes         = GetAttributeValue("ContentChannelAttributes").Split(',').AsIntegerList();

            // If no saved selection
            ddlContentChannelType.Items.Insert(0, new ListItem(string.Empty, string.Empty));

            if (contentChannelType != 0)
            {
                ddlContentChannelType.SelectedValue = contentChannelType.ToString();
                updateChannelsAndAttributes();

                var contentChannelOptions = from ListItem li in cblContentChannels.Items
                                            where contentChannels.Any((channelId) => { return(channelId == li.Value.AsInteger()); })
                                            select li;
                foreach (ListItem li in contentChannelOptions)
                {
                    li.Selected = true;
                }

                var contentChannelAttributeOptions = from ListItem li in cblContentChannelAttributes.Items
                                                     where attributes.Any((attributeId) => { return(attributeId == li.Value.AsInteger()); })
                                                     select li;
                foreach (ListItem li in contentChannelAttributeOptions)
                {
                    li.Selected = true;
                }
            }
            else
            {
                ddlContentChannelType.SelectedIndex = 0;
            }

            mdConfigure.Show();
            upnlContent.Update();
        }
Example #20
0
        /// <summary>
        /// Gets the selection.
        /// </summary>
        /// <param name="entityType">Type of the entity.</param>
        /// <param name="controls">The controls.</param>
        /// <param name="filterMode"></param>
        /// <returns></returns>
        public override string GetSelection(Type entityType, Control[] controls, FilterMode filterMode)
        {
            var values = new List <string>();

            if (controls.Length > 0)
            {
                var containerControl = controls[0] as DynamicControlsPanel;
                if (containerControl.Controls.Count >= 1)
                {
                    // note: since this datafilter creates additional controls outside of CreateChildControls(), we'll use our _controlsToRender instead of the controls parameter
                    RockDropDownList contentChannelTypePicker = containerControl.Controls[0] as RockDropDownList;
                    var contentChannelType = new ContentChannelTypeService(new RockContext()).Get(contentChannelTypePicker.SelectedValue.AsInteger());
                    if (contentChannelType != null)
                    {
                        if (containerControl.Controls.Count == 1)
                        {
                            contentChannelTypePicker_SelectedIndexChanged(contentChannelTypePicker, new EventArgs());
                        }

                        if (containerControl.Controls.Count > 1)
                        {
                            DropDownList ddlProperty = containerControl.Controls[1] as DropDownList;

                            var entityFields = GetContentChannelItemAttributes(contentChannelType.Id);
                            var entityField  = entityFields.FirstOrDefault(f => f.Name == ddlProperty.SelectedValue);
                            if (entityField != null)
                            {
                                var panelControls = new List <Control>();
                                panelControls.AddRange(containerControl.Controls.OfType <Control>());

                                var control = panelControls.FirstOrDefault(c => c.ID.EndsWith(entityField.Name));
                                if (control != null)
                                {
                                    values.Add(contentChannelType.Guid.ToString());
                                    values.Add(ddlProperty.SelectedValue);
                                    entityField.FieldType.Field.GetFilterValues(control, entityField.FieldConfig, filterMode).ForEach(v => values.Add(v));
                                }
                            }
                        }
                    }
                }
            }

            return(values.ToJson());
        }
Example #21
0
        /// <summary>
        /// Creates the child controls.
        /// </summary>
        /// <returns></returns>
        public override Control[] CreateChildControls( Type entityType, FilterField filterControl )
        {
            RockDropDownList contentChannelTypePicker = new RockDropDownList();
            contentChannelTypePicker.CssClass = "js-content-channel-type-picker";
            contentChannelTypePicker.ID = filterControl.ID + "_contentChannelTypePicker";
            contentChannelTypePicker.Label = "Content Channel Type";

            contentChannelTypePicker.Items.Clear();
            var contentChannelTypeList = new ContentChannelTypeService( new RockContext() ).Queryable().OrderBy( a => a.Name ).ToList();
            foreach ( var contentChannelType in contentChannelTypeList )
            {
                contentChannelTypePicker.Items.Add( new ListItem( contentChannelType.Name, contentChannelType.Id.ToString() ) );
            }

            filterControl.Controls.Add( contentChannelTypePicker );

            return new Control[] { contentChannelTypePicker };
        }
Example #22
0
        /// <summary>
        /// Loads the dropdowns.
        /// </summary>
        private void LoadDropdowns()
        {
            ddlChannelType.Items.Clear();
            var visibleContentChannelTypeList = new ContentChannelTypeService(new RockContext()).Queryable()
                                                .Where(a => a.ShowInChannelList)
                                                .OrderBy(c => c.Name).Select(a => new
            {
                a.Id,
                a.Name
            })
                                                .ToList();

            foreach (var contentType in visibleContentChannelTypeList)
            {
                ddlChannelType.Items.Add(new ListItem(contentType.Name, contentType.Id.ToString()));
            }

            ddlContentControlType.BindToEnum <ContentControlType>();
        }
Example #23
0
        /// <summary>
        /// Creates the child controls.
        /// </summary>
        /// <returns></returns>
        public override Control[] CreateChildControls(Type entityType, FilterField filterControl)
        {
            RockDropDownList contentChannelTypePicker = new RockDropDownList();

            contentChannelTypePicker.CssClass = "js-content-channel-type-picker";
            contentChannelTypePicker.ID       = filterControl.ID + "_contentChannelTypePicker";
            contentChannelTypePicker.Label    = "Content Channel Type";

            contentChannelTypePicker.Items.Clear();
            var contentChannelTypeList = new ContentChannelTypeService(new RockContext()).Queryable().OrderBy(a => a.Name).ToList();

            foreach (var contentChannelType in contentChannelTypeList)
            {
                contentChannelTypePicker.Items.Add(new ListItem(contentChannelType.Name, contentChannelType.Id.ToString()));
            }

            filterControl.Controls.Add(contentChannelTypePicker);

            return(new Control[] { contentChannelTypePicker });
        }
        /// <summary>
        /// Handles the Delete event of the gContentChannelType 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 gContentChannelType_Delete( object sender, RowEventArgs e )
        {
            var rockContext = new RockContext();
            ContentChannelTypeService contentTypeService = new ContentChannelTypeService( rockContext );
            ContentChannelType contentType = contentTypeService.Get( e.RowKeyId );

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

                contentTypeService.Delete( contentType );
                rockContext.SaveChanges();
            }

            BindGrid();
        }
        /// <summary>
        /// Handles the Delete event of the gContentChannelType 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 gContentChannelType_Delete(object sender, RowEventArgs e)
        {
            var rockContext = new RockContext();
            ContentChannelTypeService contentTypeService = new ContentChannelTypeService(rockContext);
            ContentChannelType        contentType        = contentTypeService.Get(e.RowKeyId);

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

                contentTypeService.Delete(contentType);
                rockContext.SaveChanges();
            }

            BindGrid();
        }
Example #26
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 contentChannelType   = new ContentChannelTypeService(new RockContext()).Get(selectionValues[0].AsGuid());
                int?contentChannelTypeId = null;
                if (contentChannelType != null)
                {
                    contentChannelTypeId = contentChannelType.Id;
                }

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

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

                return(extractedFilterExpression);
            }

            return(null);
        }
Example #27
0
        /// <summary>
        /// Formats the selection.
        /// </summary>
        /// <param name="entityType"></param>
        /// <param name="selection">The selection.</param>
        /// <returns></returns>
        public override string FormatSelection(Type entityType, string selection)
        {
            string result = "Content Channel Item Property";

            // First value is content channel type, second value is attribute, remaining values are the field type's filter values
            var values = JsonConvert.DeserializeObject <List <string> >(selection);

            if (values.Count >= 2)
            {
                var contentChannelType = new ContentChannelTypeService(new RockContext()).Get(values[0].AsGuid());
                if (contentChannelType != null)
                {
                    var entityFields = GetContentChannelItemAttributes(contentChannelType.Id);
                    var entityField  = entityFields.FirstOrDefault(f => f.Name == values[1]);
                    if (entityField != null)
                    {
                        result = entityField.FormattedFilterDescription(values.Skip(2).ToList());
                    }
                }
            }

            return(result);
        }
Example #28
0
        /// <summary>
        /// Gets the entity type qualifier value by searching the foreign key.
        /// </summary>
        /// <param name="entityTypeQualifierColumn">The entity type qualifier column.</param>
        /// <param name="entityTypeQualifierValue">The entity type qualifier value.</param>
        /// <param name="rockContext">The rock context.</param>
        /// <returns></returns>
        public static string GetEntityTypeQualifierValue(string entityTypeQualifierColumn, string entityTypeQualifierValue, RockContext rockContext = null)
        {
            rockContext = rockContext ?? new RockContext();

            var id = entityTypeQualifierValue;

            switch (entityTypeQualifierColumn)
            {
            case "ConnectionTypeId":
                var connectionType = new ConnectionTypeService(rockContext)
                                     .Queryable()
                                     .AsNoTracking()
                                     .FirstOrDefault(v => v.ForeignKey.Equals(entityTypeQualifierValue, StringComparison.OrdinalIgnoreCase));
                if (connectionType != null)
                {
                    id = connectionType.Id.ToString();
                }
                break;

            case "ContentChannelId":
                var contentChannel = new ContentChannelService(rockContext)
                                     .Queryable()
                                     .AsNoTracking()
                                     .FirstOrDefault(v => v.ForeignKey.Equals(entityTypeQualifierValue, StringComparison.OrdinalIgnoreCase));
                if (contentChannel != null)
                {
                    id = contentChannel.Id.ToString();
                }
                break;

            case "ContentChannelTypeId":
                var contentChannelType = new ContentChannelTypeService(rockContext)
                                         .Queryable()
                                         .AsNoTracking()
                                         .FirstOrDefault(v => v.ForeignKey.Equals(entityTypeQualifierValue, StringComparison.OrdinalIgnoreCase));
                if (contentChannelType != null)
                {
                    id = contentChannelType.Id.ToString();
                }
                break;

            case "DefinedTypeId":
                var definedType = new DefinedTypeService(rockContext)
                                  .Queryable()
                                  .AsNoTracking()
                                  .FirstOrDefault(v => v.ForeignKey.Equals(entityTypeQualifierValue, StringComparison.OrdinalIgnoreCase));
                if (definedType != null)
                {
                    id = definedType.Id.ToString();
                }
                break;

            case "GroupId":
                var group = new GroupService(rockContext)
                            .Queryable()
                            .AsNoTracking()
                            .FirstOrDefault(v => v.ForeignKey.Equals(entityTypeQualifierValue, StringComparison.OrdinalIgnoreCase));
                if (group != null)
                {
                    id = group.Id.ToString();
                }
                break;

            case "GroupTypeId":
                var groupType = new GroupTypeService(rockContext)
                                .Queryable()
                                .AsNoTracking()
                                .FirstOrDefault(v => v.ForeignKey.Equals(entityTypeQualifierValue, StringComparison.OrdinalIgnoreCase));
                if (groupType != null)
                {
                    id = groupType.Id.ToString();
                }
                break;
            }

            return(id);
        }
        /// <summary>
        /// Gets the list source.
        /// </summary>
        /// <value>
        /// The list source.
        /// </value>
        internal override Dictionary <string, string> GetListSource(Dictionary <string, ConfigurationValue> configurationValues)
        {
            ContentChannelTypeService service = new ContentChannelTypeService(new RockContext());

            return(service.Queryable().OrderBy(a => a.Name).ToDictionary(k => k.Guid.ToString(), v => v.Name));
        }
        /// <summary>
        /// Formats the selection.
        /// </summary>
        /// <param name="entityType"></param>
        /// <param name="selection">The selection.</param>
        /// <returns></returns>
        public override string FormatSelection( Type entityType, string selection )
        {
            string result = "Content Channel Item Property";

            // First value is content channel type, second value is attribute, remaining values are the field type's filter values
            var values = JsonConvert.DeserializeObject<List<string>>( selection );
            if ( values.Count >= 2 )
            {
                var contentChannelType = new ContentChannelTypeService( new RockContext() ).Get( values[0].AsGuid() );
                if ( contentChannelType != null )
                {
                    var entityFields = GetContentChannelItemAttributes( contentChannelType.Id );
                    var entityField = entityFields.FirstOrDefault( f => f.Name == values[1] );
                    if ( entityField != null )
                    {
                        result = entityField.FormattedFilterDescription( values.Skip( 2 ).ToList() );
                    }
                }
            }

            return result;
        }
        /// <summary>
        /// Creates the child controls.
        /// Implement this version of CreateChildControls if your DataFilterComponent supports different FilterModes
        /// </summary>
        /// <param name="entityType"></param>
        /// <param name="filterControl"></param>
        /// <param name="filterMode"></param>
        /// <returns></returns>
        public override Control[] CreateChildControls( Type entityType, FilterField filterControl, FilterMode filterMode )
        {
            var containerControl = new DynamicControlsPanel();
            containerControl.ID = string.Format( "{0}_containerControl", filterControl.ID );
            containerControl.CssClass = "js-container-control";
            filterControl.Controls.Add( containerControl );

            RockDropDownList contentChannelTypePicker = new RockDropDownList();
            contentChannelTypePicker.ID = filterControl.ID + "_contentChannelTypePicker";
            contentChannelTypePicker.Label = "Content Channel Type";

            contentChannelTypePicker.Items.Clear();
            var contentChannelTypeList = new ContentChannelTypeService( new RockContext() ).Queryable().OrderBy( a => a.Name ).ToList();
            foreach ( var contentChannelType in contentChannelTypeList )
            {
                contentChannelTypePicker.Items.Add( new ListItem( contentChannelType.Name, contentChannelType.Id.ToString() ) );
            }

            contentChannelTypePicker.SelectedIndexChanged += contentChannelTypePicker_SelectedIndexChanged;
            contentChannelTypePicker.AutoPostBack = true;
            contentChannelTypePicker.Visible = filterMode == FilterMode.AdvancedFilter;
            containerControl.Controls.Add( contentChannelTypePicker );

            // set the contentChannelTypePicker selected value now so we can create the other controls that depend on knowing the contentChannelTypeId
            int? contentChannelTypeId = filterControl.Page.Request.Params[contentChannelTypePicker.UniqueID].AsIntegerOrNull();
            contentChannelTypePicker.SelectedValue = contentChannelTypeId.ToString();
            contentChannelTypePicker_SelectedIndexChanged( contentChannelTypePicker, new EventArgs() );

            return new Control[] { containerControl };
        }
Example #32
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 Type";
            string[] selectionValues = selection.Split( '|' );
            if ( selectionValues.Length >= 1 )
            {
                var contentChannelType = new ContentChannelTypeService( new RockContext() ).Get( selectionValues[0].AsGuid() );

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

            return result;
        }
Example #33
0
        /// <summary>
        /// Sets the edit value from IEntity.Id value
        /// </summary>
        /// <param name="control">The control.</param>
        /// <param name="configurationValues">The configuration values.</param>
        /// <param name="id">The identifier.</param>
        public void SetEditValueFromEntityId(System.Web.UI.Control control, Dictionary <string, ConfigurationValue> configurationValues, int?id)
        {
            var itemGuid = new ContentChannelTypeService(new RockContext()).GetGuid(id ?? 0);

            SetEditValue(control, configurationValues, itemGuid?.ToString());
        }
 /// <summary>
 /// Gets the type of the content.
 /// </summary>
 /// <param name="contentTypeId">The content type identifier.</param>
 /// <param name="rockContext">The rock context.</param>
 /// <returns></returns>
 private ContentChannelType GetContentChannelType( int contentTypeId, RockContext rockContext = null )
 {
     rockContext = rockContext ?? new RockContext();
     var contentType = new ContentChannelTypeService( rockContext )
         .Queryable()
         .Where( t => t.Id == contentTypeId )
         .FirstOrDefault();
     return contentType;
 }
Example #35
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 contentChannelType = new ContentChannelTypeService( new RockContext() ).Get( selectionValues[0].AsGuid() );
         if ( contentChannelType != null )
         {
             ( controls[0] as RockDropDownList ).SetValue( contentChannelType.Id );
         }
     }
 }
Example #36
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? contentChannelTypeId = ( controls[0] as RockDropDownList ).SelectedValueAsId();
            Guid? contentChannelTypeGuid = null;
            var contentChannelType = new ContentChannelTypeService( new RockContext() ).Get( contentChannelTypeId ?? 0 );
            if ( contentChannelType != null )
            {
                contentChannelTypeGuid = contentChannelType.Guid;
            }

            return contentChannelTypeGuid.ToString();
        }
        /// <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();
            ContentChannelType contentType;

            ContentChannelTypeService contentTypeService = new ContentChannelTypeService( rockContext );

            int contentTypeId = int.Parse( hfId.Value );

            if ( contentTypeId == 0 )
            {
                contentType = new ContentChannelType();
                contentTypeService.Add( contentType );
            }
            else
            {
                contentType = contentTypeService.Get( contentTypeId );
            }

            if ( contentType != null )
            {
                contentType.Name = tbName.Text;
                contentType.DateRangeType = (ContentChannelDateType)int.Parse( ddlDateRangeType.SelectedValue );
                contentType.IncludeTime = cbIncludeTime.Checked;
                contentType.DisablePriority = cbDisablePriority.Checked;

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

                rockContext.WrapTransaction( () =>
                {

                    rockContext.SaveChanges();

                    // get it back to make sure we have a good Id for it for the Attributes
                    contentType = contentTypeService.Get( contentType.Guid );

                    // Save the Channel Attributes
                    int entityTypeId = EntityTypeCache.Read( typeof( ContentChannel ) ).Id;
                    SaveAttributes( contentType.Id, entityTypeId, ChannelAttributesState, rockContext );

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

                } );

                NavigateToParentPage();
            }
        }
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            ContentChannelTypeService contentTypeService = new ContentChannelTypeService( new RockContext() );
            SortProperty sortProperty = gContentChannelType.SortProperty;

            var types = contentTypeService.Queryable( "Channels" )
                .Select( t => new
                {
                    t.Id,
                    t.Name,
                    t.IsSystem,
                    Channels = t.Channels.Count()
                } )
                .ToList();

            if ( sortProperty != null )
            {
                types = types.AsQueryable().Sort( sortProperty ).ToList();
            }
            else
            {
                types = types.OrderBy( p => p.Name ).ToList();
            }

            gContentChannelType.DataSource = types;
            gContentChannelType.DataBind();
        }
        /// <summary>
        /// Gets the selection.
        /// </summary>
        /// <param name="entityType">Type of the entity.</param>
        /// <param name="controls">The controls.</param>
        /// <param name="filterMode"></param>
        /// <returns></returns>
        public override string GetSelection( Type entityType, Control[] controls, FilterMode filterMode )
        {
            var values = new List<string>();

            if ( controls.Length > 0 )
            {
                var containerControl = controls[0] as DynamicControlsPanel;
                if ( containerControl.Controls.Count >= 1 )
                {
                    // note: since this datafilter creates additional controls outside of CreateChildControls(), we'll use our _controlsToRender instead of the controls parameter
                    RockDropDownList contentChannelTypePicker = containerControl.Controls[0] as RockDropDownList;
                    var contentChannelType = new ContentChannelTypeService( new RockContext() ).Get( contentChannelTypePicker.SelectedValue.AsInteger() );
                    if ( contentChannelType != null )
                    {
                        if ( containerControl.Controls.Count == 1 )
                        {
                            contentChannelTypePicker_SelectedIndexChanged( contentChannelTypePicker, new EventArgs() );
                        }

                        if ( containerControl.Controls.Count > 1 )
                        {
                            DropDownList ddlProperty = containerControl.Controls[1] as DropDownList;

                            var entityFields = GetContentChannelItemAttributes( contentChannelType.Id );
                            var entityField = entityFields.FirstOrDefault( f => f.Name == ddlProperty.SelectedValue );
                            if ( entityField != null )
                            {
                                var panelControls = new List<Control>();
                                panelControls.AddRange( containerControl.Controls.OfType<Control>() );

                                var control = panelControls.FirstOrDefault( c => c.ID.EndsWith( entityField.Name ) );
                                if ( control != null )
                                {
                                    values.Add( contentChannelType.Guid.ToString() );
                                    values.Add( ddlProperty.SelectedValue );
                                    entityField.FieldType.Field.GetFilterValues( control, entityField.FieldConfig, filterMode ).ForEach( v => values.Add( v ) );
                                }
                            }
                        }
                    }
                }
            }

            return values.ToJson();
        }
        /// <summary>
        /// Sets the selection.
        /// </summary>
        /// <param name="entityType"></param>
        /// <param name="controls">The controls.</param>
        /// <param name="selection">The selection.</param>
        public override void SetSelection( Type entityType, Control[] controls, string selection )
        {
            if ( !string.IsNullOrWhiteSpace( selection ) )
            {
                var values = JsonConvert.DeserializeObject<List<string>>( selection );
                if ( controls.Length > 0 && values.Count > 0 )
                {
                    var contentChannelType = new ContentChannelTypeService( new RockContext() ).Get( values[0].AsGuid() );
                    if ( contentChannelType != null )
                    {
                        var containerControl = controls[0] as DynamicControlsPanel;
                        if ( containerControl.Controls.Count > 0 )
                        {
                            RockDropDownList contentChannelTypePicker = containerControl.Controls[0] as RockDropDownList;
                            contentChannelTypePicker.SelectedValue = contentChannelType.Id.ToString();
                            contentChannelTypePicker_SelectedIndexChanged( contentChannelTypePicker, new EventArgs() );
                        }

                        if ( containerControl.Controls.Count > 1 && values.Count > 1 )
                        {
                            DropDownList ddlProperty = containerControl.Controls[1] as DropDownList;
                            var entityFields = GetContentChannelItemAttributes( contentChannelType.Id );

                            var panelControls = new List<Control>();
                            panelControls.AddRange( containerControl.Controls.OfType<Control>() );
                            SetEntityFieldSelection( entityFields, ddlProperty, values.Skip( 1 ).ToList(), panelControls );
                        }
                    }
                }
            }
        }
Example #41
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 contentChannelType = new ContentChannelTypeService( new RockContext() ).Get( selectionValues[0].AsGuid() );
                int? contentChannelTypeId = null;
                if ( contentChannelType != null )
                {
                    contentChannelTypeId = contentChannelType.Id;
                }

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

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

                return extractedFilterExpression;
            }

            return null;
        }
        /// <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? contentTypeId = PageParameter( pageReference, "typeId" ).AsIntegerOrNull();
            if ( contentTypeId != null )
            {
                ContentChannelType contentType = new ContentChannelTypeService( new RockContext() ).Get( contentTypeId.Value );
                if ( contentType != null )
                {
                    breadCrumbs.Add( new BreadCrumb( contentType.Name, pageReference ) );
                }
                else
                {
                    breadCrumbs.Add( new BreadCrumb( "New Content Type", pageReference ) );
                }
            }
            else
            {
                // don't show a breadcrumb if we don't have a pageparam to work with
            }

            return breadCrumbs;
        }
Example #43
0
        /// <summary>
        /// Create an EntityField for an Attribute.
        /// </summary>
        /// <param name="attribute">The attribute.</param>
        /// <param name="limitToFilterableAttributes"></param>
        public static EntityField GetEntityFieldForAttribute(AttributeCache attribute, bool limitToFilterableAttributes = true)
        {
            // Ensure field name only has Alpha, Numeric and underscore chars
            string fieldName = attribute.Key.RemoveSpecialCharacters().Replace(".", "");

            EntityField entityField = null;

            // Make sure that the attributes field type actually renders a filter control if limitToFilterableAttributes
            var fieldType = FieldTypeCache.Read(attribute.FieldTypeId);

            if (fieldType != null && (!limitToFilterableAttributes || fieldType.Field.HasFilterControl()))
            {
                entityField       = new EntityField(fieldName, FieldKind.Attribute, typeof(string), attribute.Guid, fieldType);
                entityField.Title = attribute.Name.SplitCase();
                entityField.TitleWithoutQualifier = entityField.Title;

                foreach (var config in attribute.QualifierValues)
                {
                    entityField.FieldConfig.Add(config.Key, config.Value);
                }

                // Special processing for Entity Type "Group" to handle sub-types that are distinguished by GroupTypeId.
                if (attribute.EntityTypeId == EntityTypeCache.GetId(typeof(Group)) && attribute.EntityTypeQualifierColumn == "GroupTypeId")
                {
                    using (var rockContext = new RockContext())
                    {
                        var groupType = GroupTypeCache.Read(attribute.EntityTypeQualifierValue.AsInteger(), rockContext);
                        if (groupType != null)
                        {
                            // Append the Qualifier to the title
                            entityField.AttributeEntityTypeQualifierName = groupType.Name;
                            entityField.Title = string.Format("{0} ({1})", attribute.Name, groupType.Name);
                        }
                    }
                }

                // Special processing for Entity Type "ContentChannelItem" to handle sub-types that are distinguished by ContentChannelTypeId.
                if (attribute.EntityTypeId == EntityTypeCache.GetId(typeof(ContentChannelItem)) && attribute.EntityTypeQualifierColumn == "ContentChannelTypeId")
                {
                    using (var rockContext = new RockContext())
                    {
                        var contentChannelType = new ContentChannelTypeService(rockContext).Get(attribute.EntityTypeQualifierValue.AsInteger());
                        if (contentChannelType != null)
                        {
                            // Append the Qualifier to the title
                            entityField.AttributeEntityTypeQualifierName = contentChannelType.Name;
                            entityField.Title = string.Format("{0} (ChannelType: {1})", attribute.Name, contentChannelType.Name);
                        }
                    }
                }

                // Special processing for Entity Type "ContentChannelItem" to handle sub-types that are distinguished by ContentChannelId.
                if (attribute.EntityTypeId == EntityTypeCache.GetId(typeof(ContentChannelItem)) && attribute.EntityTypeQualifierColumn == "ContentChannelId")
                {
                    using (var rockContext = new RockContext())
                    {
                        var contentChannel = new ContentChannelService(rockContext).Get(attribute.EntityTypeQualifierValue.AsInteger());
                        if (contentChannel != null)
                        {
                            // Append the Qualifier to the title
                            entityField.AttributeEntityTypeQualifierName = contentChannel.Name;
                            entityField.Title = string.Format("{0} (Channel: {1})", attribute.Name, contentChannel.Name);
                        }
                    }
                }

                // Special processing for Entity Type "Workflow" to handle sub-types that are distinguished by WorkflowTypeId.
                if (attribute.EntityTypeId == EntityTypeCache.GetId(typeof(Rock.Model.Workflow)) && attribute.EntityTypeQualifierColumn == "WorkflowTypeId")
                {
                    using (var rockContext = new RockContext())
                    {
                        int workflowTypeId = attribute.EntityTypeQualifierValue.AsInteger();
                        if (_workflowTypeNameLookup == null)
                        {
                            _workflowTypeNameLookup = new WorkflowTypeService(rockContext).Queryable().ToDictionary(k => k.Id, v => v.Name);
                        }

                        var workflowTypeName = _workflowTypeNameLookup.ContainsKey(workflowTypeId) ? _workflowTypeNameLookup[workflowTypeId] : null;
                        if (workflowTypeName != null)
                        {
                            // Append the Qualifier to the title for Workflow Attributes
                            entityField.AttributeEntityTypeQualifierName = workflowTypeName;
                            entityField.Title = string.Format("({1}) {0} ", attribute.Name, workflowTypeName);
                        }
                    }
                }
            }

            return(entityField);
        }
Example #44
0
        /// <summary>
        /// Create an EntityField for an Attribute.
        /// </summary>
        /// <param name="attribute">The attribute.</param>
        /// <param name="limitToFilterableAttributes"></param>
        public static EntityField GetEntityFieldForAttribute( AttributeCache attribute, bool limitToFilterableAttributes = true )
        {
            // Ensure field name only has Alpha, Numeric and underscore chars
            string fieldName = attribute.Key.RemoveSpecialCharacters().Replace( ".", "" );

            EntityField entityField = null;

            // Make sure that the attributes field type actually renders a filter control if limitToFilterableAttributes
            var fieldType = FieldTypeCache.Read( attribute.FieldTypeId );
            if ( fieldType != null && ( !limitToFilterableAttributes || fieldType.Field.HasFilterControl() ) )
            {
                entityField = new EntityField( fieldName, FieldKind.Attribute, typeof( string ), attribute.Guid, fieldType );
                entityField.Title = attribute.Name.SplitCase();
                entityField.TitleWithoutQualifier = entityField.Title;

                foreach ( var config in attribute.QualifierValues )
                {
                    entityField.FieldConfig.Add( config.Key, config.Value );
                }

                // Special processing for Entity Type "Group" to handle sub-types that are distinguished by GroupTypeId.
                if ( attribute.EntityTypeId == EntityTypeCache.GetId( typeof( Group ) ) && attribute.EntityTypeQualifierColumn == "GroupTypeId" )
                {
                    using ( var rockContext = new RockContext() )
                    {
                        var groupType = GroupTypeCache.Read( attribute.EntityTypeQualifierValue.AsInteger(), rockContext );
                        if ( groupType != null )
                        {
                            // Append the Qualifier to the title
                            entityField.AttributeEntityTypeQualifierName = groupType.Name;
                            entityField.Title = string.Format( "{0} ({1})", attribute.Name, groupType.Name );
                        }
                    }
                }

                // Special processing for Entity Type "ContentChannelItem" to handle sub-types that are distinguished by ContentChannelTypeId.
                if ( attribute.EntityTypeId == EntityTypeCache.GetId( typeof( ContentChannelItem ) ) && attribute.EntityTypeQualifierColumn == "ContentChannelTypeId" )
                {
                    using ( var rockContext = new RockContext() )
                    {
                        var contentChannelType = new ContentChannelTypeService( rockContext ).Get( attribute.EntityTypeQualifierValue.AsInteger() );
                        if ( contentChannelType != null )
                        {
                            // Append the Qualifier to the title
                            entityField.AttributeEntityTypeQualifierName = contentChannelType.Name;
                            entityField.Title = string.Format( "{0} ({1})", attribute.Name, contentChannelType.Name );
                        }
                    }
                }

                // Special processing for Entity Type "Workflow" to handle sub-types that are distinguished by WorkflowTypeId.
                if ( attribute.EntityTypeId == EntityTypeCache.GetId( typeof( Rock.Model.Workflow ) ) && attribute.EntityTypeQualifierColumn == "WorkflowTypeId" )
                {
                    using ( var rockContext = new RockContext() )
                    {
                        int workflowTypeId = attribute.EntityTypeQualifierValue.AsInteger();
                        if (_workflowTypeNameLookup == null)
                        {
                            _workflowTypeNameLookup = new WorkflowTypeService( rockContext ).Queryable().ToDictionary( k => k.Id, v => v.Name );
                        }

                        var workflowTypeName = _workflowTypeNameLookup.ContainsKey( workflowTypeId ) ? _workflowTypeNameLookup[workflowTypeId] : null;
                        if ( workflowTypeName != null )
                        {
                            // Append the Qualifier to the title for Workflow Attributes
                            entityField.AttributeEntityTypeQualifierName = workflowTypeName;
                            entityField.Title = string.Format( "({1}) {0} ", attribute.Name, workflowTypeName );
                        }
                    }
                }
            }

            return entityField;
        }
 /// <summary>
 /// Gfs the filter_ display filter value.
 /// </summary>
 /// <param name="sender">The sender.</param>
 /// <param name="e">The e.</param>
 void gfFilter_DisplayFilterValue( object sender, GridFilter.DisplayFilterValueArgs e )
 {
     switch ( e.Key )
     {
         case "Type":
             {
                 int? typeId = e.Value.AsIntegerOrNull();
                 if ( typeId.HasValue )
                 {
                     var contentType = new ContentChannelTypeService( new RockContext() ).Get( typeId.Value );
                     if ( contentType != null )
                     {
                         e.Value = contentType.Name;
                     }
                 }
                 break;
             }
         default:
             {
                 e.Value = string.Empty;
                 break;
             }
     }
 }
Example #46
0
        /// <summary>
        /// Loads the Content Channel data.
        /// </summary>
        /// <param name="csvData">The CSV data.</param>
        private int LoadContentChannel(CSVInstance csvData)
        {
            var lookupContext             = new RockContext();
            var contentChannelService     = new ContentChannelService(lookupContext);
            var contentChannelTypeService = new ContentChannelTypeService(lookupContext);
            var groupService = new GroupService(lookupContext);

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

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

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

            string[] row;
            // Uses a look-ahead enumerator: this call will move to the next record immediately
            while ((row = csvData.Database.FirstOrDefault()) != null)
            {
                var rowContentChannelName             = row[ContentChannelName];
                var rowContentChannelTypeName         = row[ContentChannelTypeName];
                var rowContentChannelDescription      = row[ContentChannelDescription];
                var rowContentChannelId               = row[ContentChannelId];
                var rowContentChannelRequiresApproval = row[ContentChannelRequiresApproval];
                var rowContentChannelParentId         = row[ContentChannelParentId];

                var rowChannelId = rowContentChannelId.AsType <int?>();

                var requiresApproval = ( bool )ParseBoolOrDefault(rowContentChannelRequiresApproval, false);

                var contentChannelTypeId = 0;
                if (contentChannelTypeService.Queryable().AsNoTracking().FirstOrDefault(t => t.Name.ToLower() == rowContentChannelTypeName.ToLower()) != null)
                {
                    contentChannelTypeId = contentChannelTypeService.Queryable().AsNoTracking().FirstOrDefault(t => t.Name.ToLower() == rowContentChannelTypeName.ToLower()).Id;
                }

                //
                // Verify the Content Channel Type Exists
                //
                if (contentChannelTypeId < 1)
                {
                    var newConentChannelType = new ContentChannelType
                    {
                        Name            = rowContentChannelTypeName,
                        DateRangeType   = ContentChannelDateType.DateRange,
                        IncludeTime     = true,
                        DisablePriority = true,
                        CreatedDateTime = ImportDateTime
                    };

                    lookupContext.ContentChannelTypes.Add(newConentChannelType);
                    lookupContext.SaveChanges(DisableAuditing);

                    contentChannelTypeId = lookupContext.ContentChannelTypes.FirstOrDefault(t => t.Name == rowContentChannelTypeName).Id;
                }

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

                if (!exists)
                {
                    //
                    // Create and populate the new Content Channel.
                    //
                    var contentChannel = new ContentChannel
                    {
                        Name                 = rowContentChannelName,
                        Description          = rowContentChannelDescription,
                        ContentChannelTypeId = contentChannelTypeId,
                        ForeignKey           = rowContentChannelId,
                        ForeignId            = rowChannelId,
                        ContentControlType   = ContentControlType.HtmlEditor,
                        RequiresApproval     = requiresApproval
                    };

                    //
                    // Look for Parent Id and create appropriate objects.
                    //
                    if (!string.IsNullOrWhiteSpace(rowContentChannelParentId))
                    {
                        var ParentChannels = new List <ContentChannel>();
                        var parentChannel  = contentChannelService.Queryable().FirstOrDefault(p => p.ForeignKey == rowContentChannelParentId);
                        if (parentChannel.ForeignKey == rowContentChannelParentId)
                        {
                            ParentChannels.Add(parentChannel);
                            contentChannel.ParentContentChannels = ParentChannels;
                        }
                    }

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

                    // Set security if needed
                    if (contentChannel.RequiresApproval)
                    {
                        var rockAdmins = groupService.Get(Rock.SystemGuid.Group.GROUP_ADMINISTRATORS.AsGuid());
                        contentChannel.AllowSecurityRole(Authorization.APPROVE, rockAdmins, lookupContext);

                        var communicationAdmins = groupService.Get(Rock.SystemGuid.Group.GROUP_COMMUNICATION_ADMINISTRATORS.AsGuid());
                        contentChannel.AllowSecurityRole(Authorization.APPROVE, communicationAdmins, lookupContext);

                        // Save security changes
                        lookupContext.WrapTransaction(() =>
                        {
                            lookupContext.SaveChanges(DisableAuditing);
                        });
                    }

                    //
                    // Process Attributes for Content Channels
                    //
                    if (customAttributes.Any())
                    {
                        // create content channel attributes
                        foreach (var newAttributePair in customAttributes)
                        {
                            var pairs                  = newAttributePair.Value.Split('^');
                            var categoryName           = string.Empty;
                            var attributeName          = string.Empty;
                            var attributeTypeString    = string.Empty;
                            var attributeForeignKey    = string.Empty;
                            var definedValueForeignKey = string.Empty;
                            var fieldTypeId            = TextFieldTypeId;

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

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

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

                            if (string.IsNullOrEmpty(attributeName))
                            {
                                LogException("Content Channel Type", $"Content Channel Type Channel Attribute Name cannot be blank '{newAttributePair.Value}'.");
                            }
                            else
                            {
                                var fk = string.Empty;
                                if (string.IsNullOrWhiteSpace(attributeForeignKey))
                                {
                                    fk = $"Bulldozer_ContentChannelType_{contentChannelTypeId}_{categoryName.RemoveWhitespace()}_{attributeName.RemoveWhitespace()}".Left(100);
                                }
                                else
                                {
                                    fk = attributeForeignKey;
                                }

                                AddEntityAttribute(lookupContext, contentChannel.TypeId, "ContentChannelTypeId", contentChannelTypeId.ToString(), fk, categoryName, attributeName, string.Empty, fieldTypeId, true, definedValueForeignId, definedValueForeignKey, attributeTypeString: attributeTypeString);
                            }
                        }

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

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

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

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

                                    var attribute = FindEntityAttribute(lookupContext, categoryName, attributeName, contentChannel.TypeId, fk);
                                    AddEntityAttributeValue(lookupContext, attribute, contentChannel, newValue, null, true);
                                }
                            }
                        }
                    }

                    importedCount++;
                }

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

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

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

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

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

            return(completed);
        }
        /// <summary>
        /// Gets the expression.
        /// </summary>
        /// <param name="entityType"></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 )
        {
            if ( !string.IsNullOrWhiteSpace( selection ) )
            {
                var values = JsonConvert.DeserializeObject<List<string>>( selection );

                if ( values.Count >= 3 )
                {
                    var contentChannelType = new ContentChannelTypeService( new RockContext() ).Get( values[0].AsGuid() );
                    if ( contentChannelType != null )
                    {
                        string selectedProperty = values[1];

                        var entityFields = GetContentChannelItemAttributes( contentChannelType.Id );
                        var entityField = entityFields.FirstOrDefault( f => f.Name == selectedProperty );
                        if ( entityField != null )
                        {
                            return GetAttributeExpression( serviceInstance, parameterExpression, entityField, values.Skip( 2 ).ToList() );
                        }
                    }
                }
            }

            return null;
        }