/// <summary> /// Handles the ItemCommand event of the rptChannels control. /// </summary> /// <param name="source">The source of the event.</param> /// <param name="e">The <see cref="RepeaterCommandEventArgs"/> instance containing the event data.</param> protected void rptChannels_ItemCommand(object source, RepeaterCommandEventArgs e) { string selectedChannelValue = e.CommandArgument.ToString(); SetUserPreference(SELECTED_CHANNEL_SETTING, selectedChannelValue); SelectedChannelId = selectedChannelValue.AsIntegerOrNull(); var selectedChannelGuid = ContentChannelCache.Get(SelectedChannelId.Value).Guid; var queryString = new Dictionary <string, string> { { "ContentChannelGuid", selectedChannelGuid.ToString() } }; // Get CategoryGuid from Route var categoryGuid = PageParameter("CategoryGuid").AsGuidOrNull(); if (!categoryGuid.HasValue) { var categoryId = ddlCategory.SelectedValueAsId(); categoryGuid = CategoryCache.Get(categoryId.GetValueOrDefault())?.Guid; } // if user has selected a category or one was provided as a query param add it to the new route params if (categoryGuid.HasValue) { queryString.Add("CategoryGuid", categoryGuid.ToString()); } // Navigate to page with route parameters set so new Url is generated in browser NavigateToCurrentPage(queryString); }
/// <summary> /// Gets the meta value from attribute. /// </summary> /// <param name="attributeComputedKey">The attribute computed key.</param> /// <param name="contentChannelItem">The content channel item.</param> /// <returns> /// a string value /// </returns> private string GetMetaValueFromAttribute(string attributeComputedKey, ContentChannelItem contentChannelItem) { if (string.IsNullOrEmpty(attributeComputedKey)) { return(null); } string attributeEntityType = attributeComputedKey.Split('^')[0].ToString() ?? "C"; string attributeKey = attributeComputedKey.Split('^')[1].ToString() ?? string.Empty; string attributeValue = string.Empty; object mergeObject; if (attributeEntityType == "C") { mergeObject = ContentChannelCache.Get(contentChannelItem.ContentChannelId); } else { mergeObject = contentChannelItem; } // use Lava to get the Attribute value formatted for the MetaValue, and specify the Url param in case the Attribute supports rendering the value as a Url (for example, Image) string metaTemplate = string.Format("{{{{ mergeObject | Attribute:'{0}':'Url' }}}}", attributeKey); string resolvedValue = metaTemplate.ResolveMergeFields(new Dictionary <string, object> { { "mergeObject", mergeObject } }); return(resolvedValue); }
/// <summary> /// Initializes a new instance of the <see cref="ContentChannelItemFieldAttribute" /> class. /// </summary> /// <param name="contentChannelGuid">The content channel GUID.</param> /// <param name="name">The name.</param> /// <param name="description">The description.</param> /// <param name="required">if set to <c>true</c> [required].</param> /// <param name="defaultValue">The default value.</param> /// <param name="category">The category.</param> /// <param name="order">The order.</param> /// <param name="key">The key.</param> public ContentChannelItemFieldAttribute(string contentChannelGuid = "", string name = "", string description = "", bool required = true, string defaultValue = "", string category = "", int order = 0, string key = null) : base(name, description, required, defaultValue, category, order, key, typeof(Rock.Field.Types.ContentChannelItemFieldType).FullName) { if (!string.IsNullOrWhiteSpace(contentChannelGuid)) { Guid guid = Guid.Empty; if (Guid.TryParse(contentChannelGuid, out guid)) { var contentChannel = ContentChannelCache.Get(guid); if (contentChannel != null) { var configValue = new Field.ConfigurationValue(contentChannel.Id.ToString()); FieldConfigurationValues.Add("contentchannel", configValue); if (string.IsNullOrWhiteSpace(Name)) { Name = contentChannel.Name; } if (string.IsNullOrWhiteSpace(Key)) { Key = Name.Replace(" ", string.Empty); } } } } }
/// <summary> /// Handles the AddFilterClick event of the groupControl control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> protected void groupControl_AddFilterClick(object sender, EventArgs e) { FilterGroup groupControl = sender as FilterGroup; FilterField filterField = new FilterField(); Guid? channelGuid = ddlContentChannel.SelectedValueAsGuid(); if (channelGuid.HasValue) { var contentChannel = ContentChannelCache.Get(channelGuid.Value); if (contentChannel != null) { filterField.Entity = new ContentChannelItem { ContentChannelId = contentChannel.Id, ContentChannelTypeId = contentChannel.ContentChannelTypeId }; } } filterField.DataViewFilterGuid = Guid.NewGuid(); groupControl.Controls.Add(filterField); filterField.ID = string.Format("ff_{0}", filterField.DataViewFilterGuid.ToString("N")); // Remove the 'Other Data View' Filter as it doesn't really make sense to have it available in this scenario filterField.ExcludedFilterTypes = new string[] { typeof(Rock.Reporting.DataFilter.OtherDataViewFilter).FullName }; filterField.FilteredEntityTypeName = groupControl.FilteredEntityTypeName; filterField.Expanded = true; filterField.DeleteClick += filterControl_DeleteClick; }
/// <summary> /// Gets the content channel item. /// </summary> /// <returns></returns> private ContentChannelItem GetContentChannelItem() { var contentChannelItemParameterValue = GetContentChannelItemParameterValue(); if (string.IsNullOrEmpty(contentChannelItemParameterValue)) { return(null); } ContentChannelItem contentChannelItem = GetContentChannelItemFromKey(contentChannelItemParameterValue); if (contentChannelItem == null) { return(null); } //if ( contentChannelItem.ContentChannel.RequiresApproval ) //{ // var statuses = new List<ContentChannelItemStatus>(); // foreach ( var status in ( GetAttributeValue( "Status" ) ?? "2" ).Split( new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries ) ) // { // var statusEnum = status.ConvertToEnumOrNull<ContentChannelItemStatus>(); // if ( statusEnum != null ) // { // statuses.Add( statusEnum.Value ); // } // } // if ( !statuses.Contains( contentChannelItem.Status ) ) // { // return null; // } //} // // If a Channel was specified, verify that the ChannelItem is part of the channel // var channelGuid = this.GetAttributeValue("ContentChannel").AsGuidOrNull(); if (channelGuid.HasValue) { var channel = ContentChannelCache.Get(channelGuid.Value); if (channel != null) { if (contentChannelItem.ContentChannelId != channel.Id) { return(null); } } } LaunchInteraction(contentChannelItem); return(contentChannelItem); }
/// <summary> /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event. /// </summary> /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param> protected override void OnLoad(EventArgs e) { base.OnLoad(e); RockPage.AddScriptLink("~/Scripts/jquery.visible.min.js"); string eventTarget = this.Page.Request.Params["__EVENTTARGET"] ?? string.Empty; if (!Page.IsPostBack) { BindFilter(); tglStatus.Checked = GetUserPreference(STATUS_FILTER_SETTING).AsBoolean(); SelectedChannelId = PageParameter("ContentChannelId").AsIntegerOrNull(); if (!SelectedChannelId.HasValue) { var selectedChannelGuid = PageParameter("ContentChannelGuid").AsGuidOrNull(); if (selectedChannelGuid.HasValue) { SelectedChannelId = ContentChannelCache.Get(selectedChannelGuid.Value)?.Id; } } if (!SelectedChannelId.HasValue) { SelectedChannelId = GetUserPreference(SELECTED_CHANNEL_SETTING).AsIntegerOrNull(); } if (ddlCategory.Visible) { var categoryGuid = PageParameter("CategoryGuid").AsGuidOrNull(); if (categoryGuid.HasValue) { var categoryId = CategoryCache.Get(categoryGuid.Value)?.Id; SetUserPreference(CATEGORY_FILTER_SETTING, categoryId.ToString()); ddlCategory.SetValue(categoryId); } else { ddlCategory.SetValue(GetUserPreference(CATEGORY_FILTER_SETTING).AsIntegerOrNull()); } } GetData(); } else if (eventTarget.StartsWith(gContentChannelItems.UniqueID)) { // if we got a PostBack from the Grid (or child controls) make sure the Grid is bound GetData(); } }
/// <summary> /// Gets the content channel cache object. /// </summary> /// <returns></returns> public ContentChannelCache GetContentChannel() { Guid?contentChannelGuid = this.GetAttributeValue("ContentChannel").AsGuidOrNull(); ContentChannelCache contentChannel = null; if (contentChannelGuid.HasValue) { contentChannel = ContentChannelCache.Get(contentChannelGuid.Value); } return(contentChannel); }
/// <summary> /// Shows the view. /// </summary> private void ShowView() { int?outputCacheDuration = GetAttributeValue("OutputCacheDuration").AsIntegerOrNull(); string outputContents = null; string pageTitle = null; var contentChannelItemParameterValue = GetContentChannelItemParameterValue(); if (string.IsNullOrEmpty(contentChannelItemParameterValue)) { // No item specified, so don't show anything ShowNoDataFound(); return; } string outputCacheKey = OUTPUT_CACHE_KEY_PREFIX + contentChannelItemParameterValue; string pageTitleCacheKey = PAGETITLE_CACHE_KEY_PREFIX + contentChannelItemParameterValue; if (outputCacheDuration.HasValue && outputCacheDuration.Value > 0) { outputContents = GetCacheItem(outputCacheKey) as string; pageTitle = GetCacheItem(pageTitleCacheKey) as string; } bool isMergeContentEnabled = GetAttributeValue("MergeContent").AsBoolean(); bool setPageTitle = GetAttributeValue("SetPageTitle").AsBoolean(); if (outputContents == null) { ContentChannelItem contentChannelItem = GetContentChannelItem(contentChannelItemParameterValue); if (contentChannelItem == null) { ShowNoDataFound(); return; } if (contentChannelItem.ContentChannel.RequiresApproval) { var statuses = new List <ContentChannelItemStatus>(); foreach (var status in (GetAttributeValue("Status") ?? "2").Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) { var statusEnum = status.ConvertToEnumOrNull <ContentChannelItemStatus>(); if (statusEnum != null) { statuses.Add(statusEnum.Value); } } if (!statuses.Contains(contentChannelItem.Status)) { ShowNoDataFound(); return; } } // if a Channel was specified, verify that the ChannelItem is part of the channel var channelGuid = this.GetAttributeValue("ContentChannel").AsGuidOrNull(); if (channelGuid.HasValue) { var channel = ContentChannelCache.Get(channelGuid.Value); if (channel != null) { if (contentChannelItem.ContentChannelId != channel.Id) { ShowNoDataFound(); return; } } } var commonMergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson, new Rock.Lava.CommonMergeFieldsOptions { GetLegacyGlobalMergeFields = false }); // Merge content and attribute fields if block is configured to do so. if (isMergeContentEnabled) { var itemMergeFields = new Dictionary <string, object>(commonMergeFields); var enabledCommands = GetAttributeValue("EnabledLavaCommands"); itemMergeFields.AddOrReplace("Item", contentChannelItem); contentChannelItem.Content = contentChannelItem.Content.ResolveMergeFields(itemMergeFields, enabledCommands); contentChannelItem.LoadAttributes(); foreach (var attributeValue in contentChannelItem.AttributeValues) { attributeValue.Value.Value = attributeValue.Value.Value.ResolveMergeFields(itemMergeFields, enabledCommands); } } var mergeFields = new Dictionary <string, object>(commonMergeFields); mergeFields.Add("RockVersion", Rock.VersionInfo.VersionInfo.GetRockProductVersionNumber()); mergeFields.Add("Item", contentChannelItem); int detailPage = 0; var page = PageCache.Get(GetAttributeValue("DetailPage")); if (page != null) { detailPage = page.Id; } mergeFields.Add("DetailPage", detailPage); string metaDescriptionValue = GetMetaValueFromAttribute(this.GetAttributeValue("MetaDescriptionAttribute"), contentChannelItem); if (!string.IsNullOrWhiteSpace(metaDescriptionValue)) { // remove default meta description RockPage.Header.Description = metaDescriptionValue.SanitizeHtml(true); } AddHtmlMeta("og:type", this.GetAttributeValue("OpenGraphType")); AddHtmlMeta("og:title", GetMetaValueFromAttribute(this.GetAttributeValue("OpenGraphTitleAttribute"), contentChannelItem)); AddHtmlMeta("og:description", GetMetaValueFromAttribute(this.GetAttributeValue("OpenGraphDescriptionAttribute"), contentChannelItem)); AddHtmlMeta("og:image", GetMetaValueFromAttribute(this.GetAttributeValue("OpenGraphImageAttribute"), contentChannelItem)); AddHtmlMeta("twitter:title", GetMetaValueFromAttribute(this.GetAttributeValue("TwitterTitleAttribute"), contentChannelItem)); AddHtmlMeta("twitter:description", GetMetaValueFromAttribute(this.GetAttributeValue("TwitterDescriptionAttribute"), contentChannelItem)); AddHtmlMeta("twitter:image", GetMetaValueFromAttribute(this.GetAttributeValue("TwitterImageAttribute"), contentChannelItem)); var twitterCard = this.GetAttributeValue("TwitterCard"); if (twitterCard.IsNotNullOrWhiteSpace() && twitterCard != "none") { AddHtmlMeta("twitter:card", twitterCard); } string lavaTemplate = this.GetAttributeValue("LavaTemplate"); string enabledLavaCommands = this.GetAttributeValue("EnabledLavaCommands"); outputContents = lavaTemplate.ResolveMergeFields(mergeFields, enabledLavaCommands); if (setPageTitle) { pageTitle = contentChannelItem.Title; } if (outputCacheDuration.HasValue && outputCacheDuration.Value > 0) { string cacheTags = GetAttributeValue("CacheTags") ?? string.Empty; var cacheKeys = GetCacheItem(CACHEKEYS_CACHE_KEY) as HashSet <string> ?? new HashSet <string>(); cacheKeys.Add(outputCacheKey); cacheKeys.Add(pageTitleCacheKey); AddCacheItem(CACHEKEYS_CACHE_KEY, cacheKeys, TimeSpan.MaxValue, cacheTags); AddCacheItem(outputCacheKey, outputContents, outputCacheDuration.Value, cacheTags); if (pageTitle != null) { AddCacheItem(pageTitleCacheKey, pageTitle, outputCacheDuration.Value, cacheTags); } } } lContentOutput.Text = outputContents; if (setPageTitle && pageTitle != null) { RockPage.PageTitle = pageTitle; RockPage.BrowserTitle = string.Format("{0} | {1}", pageTitle, RockPage.Site.Name); RockPage.Header.Title = string.Format("{0} | {1}", pageTitle, RockPage.Site.Name); var pageBreadCrumb = RockPage.PageReference.BreadCrumbs.FirstOrDefault(); if (pageBreadCrumb != null) { pageBreadCrumb.Name = RockPage.PageTitle; } } LaunchWorkflow(); LaunchInteraction(); }
/// <summary> /// Shows the view. /// </summary> private void ShowView() { int?outputCacheDuration = GetAttributeValue("OutputCacheDuration").AsIntegerOrNull(); string outputContents = null; string pageTitle = null; var contentChannelItemParameterValue = GetContentChannelItemParameterValue(); if (string.IsNullOrEmpty(contentChannelItemParameterValue)) { // No item specified, so don't show anything ShowNoDataFound(); return; } string outputCacheKey = OUTPUT_CACHE_KEY_PREFIX + contentChannelItemParameterValue; string pageTitleCacheKey = PAGETITLE_CACHE_KEY_PREFIX + contentChannelItemParameterValue; if (outputCacheDuration.HasValue && outputCacheDuration.Value > 0) { outputContents = GetCacheItem(outputCacheKey) as string; pageTitle = GetCacheItem(pageTitleCacheKey) as string; } bool setPageTitle = GetAttributeValue("SetPageTitle").AsBoolean(); if (outputContents == null) { ContentChannelItem contentChannelItem = GetContentChannelItem(contentChannelItemParameterValue); if (contentChannelItem == null) { ShowNoDataFound(); return; } // if a Channel was specified, verify that the ChannelItem is part of the channel var channelGuid = this.GetAttributeValue("ContentChannel").AsGuidOrNull(); if (channelGuid.HasValue) { var channel = ContentChannelCache.Get(channelGuid.Value); if (channel != null) { if (contentChannelItem.ContentChannelId != channel.Id) { ShowNoDataFound(); return; } } } var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson, new Rock.Lava.CommonMergeFieldsOptions { GetLegacyGlobalMergeFields = false }); mergeFields.Add("RockVersion", Rock.VersionInfo.VersionInfo.GetRockProductVersionNumber()); mergeFields.Add("Item", contentChannelItem); string metaDescriptionValue = GetMetaValueFromAttribute(this.GetAttributeValue("MetaDescriptionAttribute"), contentChannelItem); if (!string.IsNullOrWhiteSpace(metaDescriptionValue)) { // remove default meta description RockPage.Header.Description = metaDescriptionValue.SanitizeHtml(true); } AddHtmlMeta("og:type", this.GetAttributeValue("OpenGraphType")); AddHtmlMeta("og:title", GetMetaValueFromAttribute(this.GetAttributeValue("OpenGraphTitleAttribute"), contentChannelItem)); AddHtmlMeta("og:description", GetMetaValueFromAttribute(this.GetAttributeValue("OpenGraphDescriptionAttribute"), contentChannelItem)); AddHtmlMeta("og:image", GetMetaValueFromAttribute(this.GetAttributeValue("OpenGraphImageAttribute"), contentChannelItem)); AddHtmlMeta("twitter:title", GetMetaValueFromAttribute(this.GetAttributeValue("TwitterTitleAttribute"), contentChannelItem)); AddHtmlMeta("twitter:description", GetMetaValueFromAttribute(this.GetAttributeValue("TwitterDescriptionAttribute"), contentChannelItem)); AddHtmlMeta("twitter:image", GetMetaValueFromAttribute(this.GetAttributeValue("TwitterImageAttribute"), contentChannelItem)); AddHtmlMeta("twitter:card", this.GetAttributeValue("TwitterCard")); string lavaTemplate = this.GetAttributeValue("LavaTemplate"); string enabledLavaCommands = this.GetAttributeValue("EnabledLavaCommands"); outputContents = lavaTemplate.ResolveMergeFields(mergeFields, enabledLavaCommands); if (setPageTitle) { pageTitle = contentChannelItem.Title; } if (outputCacheDuration.HasValue && outputCacheDuration.Value > 0) { string cacheTags = GetAttributeValue("CacheTags") ?? string.Empty; var cacheKeys = GetCacheItem(CACHEKEYS_CACHE_KEY) as HashSet <string> ?? new HashSet <string>(); cacheKeys.Add(outputCacheKey); cacheKeys.Add(pageTitleCacheKey); AddCacheItem(CACHEKEYS_CACHE_KEY, cacheKeys, TimeSpan.MaxValue, cacheTags); AddCacheItem(outputCacheKey, outputContents, outputCacheDuration.Value, cacheTags); if (pageTitle != null) { AddCacheItem(pageTitleCacheKey, pageTitle, outputCacheDuration.Value, cacheTags); } } } lContentOutput.Text = outputContents; if (setPageTitle && pageTitle != null) { RockPage.PageTitle = pageTitle; RockPage.BrowserTitle = string.Format("{0} | {1}", pageTitle, RockPage.Site.Name); RockPage.Header.Title = string.Format("{0} | {1}", pageTitle, RockPage.Site.Name); } LaunchWorkflow(); LaunchInteraction(); }
/// <summary> /// Create an EntityField for an Attribute. /// </summary> /// <param name="attribute">The attribute.</param> /// <param name="limitToFilterableAttributes"></param> /// <param name="rockContext">The RockContext to use.</param> public static EntityField GetEntityFieldForAttribute(AttributeCache attribute, bool limitToFilterableAttributes, RockContext externalRockContext = null) { // 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.Get(attribute.FieldTypeId); if (fieldType != null && (!limitToFilterableAttributes || fieldType.Field.HasFilterControl())) { entityField = new EntityField(fieldName, FieldKind.Attribute, typeof(string), attribute.Guid, fieldType); entityField.Title = attribute.Name; entityField.TitleWithoutQualifier = entityField.Title; foreach (var config in attribute.QualifierValues) { entityField.FieldConfig.Add(config.Key, config.Value); } // Special processing for Entity Type "Group" or "GroupMember" to handle sub-types that are distinguished by GroupTypeId. if ((attribute.EntityTypeId == EntityTypeCache.GetId(typeof(Group)) || attribute.EntityTypeId == EntityTypeCache.GetId(typeof(GroupMember)) && attribute.EntityTypeQualifierColumn == "GroupTypeId")) { using (var rockContext = externalRockContext == null ? new RockContext() : null) { var groupType = GroupTypeCache.Get(attribute.EntityTypeQualifierValue.AsInteger(), externalRockContext ?? 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 = externalRockContext == null ? new RockContext() : null) { var contentChannelType = new ContentChannelTypeService(externalRockContext ?? 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 = externalRockContext == null ? new RockContext() : null) { var contentChannel = ContentChannelCache.Get(attribute.EntityTypeQualifierValue.AsInteger(), externalRockContext ?? rockContext); 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 = externalRockContext == null ? new RockContext() : null) { var workflowType = WorkflowTypeCache.Get(attribute.EntityTypeQualifierValue.AsInteger(), externalRockContext ?? rockContext); if (workflowType != null) { // Append the Qualifier to the title for Workflow Attributes entityField.AttributeEntityTypeQualifierName = workflowType.Name; entityField.Title = string.Format("({1}) {0} ", attribute.Name, workflowType.Name); } } } } return(entityField); }
private void ShowView() { var rockContext = new RockContext(); var missingConfiguration = new List <string>(); var contentChannelGuid = GetAttributeValue("ContentChannel").AsGuidOrNull(); if (!contentChannelGuid.HasValue) { missingConfiguration.Add("The content channel has not yet been configured."); } var blockTitleTemplate = GetAttributeValue("BlockTitleTemplate"); if (blockTitleTemplate.IsNullOrWhiteSpace()) { missingConfiguration.Add("The block title template appears to be blank."); } var bodyTemplate = GetAttributeValue("BodyTemplate"); if (bodyTemplate.IsNullOrWhiteSpace()) { missingConfiguration.Add("The body template appears to be blank."); } if (missingConfiguration.Count > 0) { StringBuilder message = new StringBuilder(); message.Append("Currently, there are some missing configuration items. These items are summarized below: <ul>"); foreach (var configurationItem in missingConfiguration) { message.Append(string.Format("<li>{0}</li>", configurationItem)); } message.Append("</ul>"); nbMessages.Text = message.ToString(); nbMessages.NotificationBoxType = NotificationBoxType.Validation; return; } var enabledLavaCommands = GetAttributeValue("EnabledLavaCommands"); var blockTitleIconCssClass = GetAttributeValue("BlockTitleIconCssClass"); var metricValueCount = GetAttributeValue("MetricValueCount").AsInteger(); var cacheDuration = GetAttributeValue("CacheDuration").AsInteger(); string cacheTags = GetAttributeValue("CacheTags") ?? string.Empty; var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(RockPage, CurrentPerson); var cacheKey = "internal-commmunication-view-" + this.BlockId.ToString(); ContentChannelItem contentChannelItem = null; List <MetricResult> metrics = null; var showPrev = false; CachedBlockData cachedItem = null; if (cacheDuration > 0 && _currentPage == 0) { var serializedCachedItem = RockCache.Get(cacheKey, true); if (serializedCachedItem != null && serializedCachedItem is string && !string.IsNullOrWhiteSpace(( string )serializedCachedItem)) { cachedItem = (( string )serializedCachedItem).FromJsonOrNull <CachedBlockData>(); } } if (cachedItem != null) { contentChannelItem = cachedItem.ContentChannelItem; metrics = cachedItem.Metrics; showPrev = cachedItem.ShowPrev; } else { var channel = ContentChannelCache.Get(contentChannelGuid.Value); // Get latest content channel items, get two so we know if a previous one exists for paging var contentChannelItemsQry = new ContentChannelItemService(rockContext) .Queryable() .AsNoTracking() .Where(i => i.ContentChannel.Guid == contentChannelGuid && i.Status == ContentChannelItemStatus.Approved && i.StartDateTime <= RockDateTime.Now); if (channel.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange) { if (channel.ContentChannelType.IncludeTime) { contentChannelItemsQry = contentChannelItemsQry.Where(c => !c.ExpireDateTime.HasValue || c.ExpireDateTime >= RockDateTime.Now); } else { contentChannelItemsQry = contentChannelItemsQry.Where(c => !c.ExpireDateTime.HasValue || c.ExpireDateTime > RockDateTime.Today); } } var contentChannelItems = contentChannelItemsQry.OrderByDescending(i => i.StartDateTime) .Take(2) .Skip(_currentPage) .ToList(); if (contentChannelItems.IsNull() || contentChannelItems.Count == 0) { nbMessages.Text = "It appears that there are no active communications to display for this content channel."; nbMessages.NotificationBoxType = NotificationBoxType.Info; return; } contentChannelItem = contentChannelItems.First(); showPrev = (contentChannelItems.Count > 1); // Get metrics var metricCategories = Rock.Attribute.MetricCategoriesFieldAttribute.GetValueAsGuidPairs(GetAttributeValue("Metrics")); var metricGuids = metricCategories.Select(a => a.MetricGuid).ToList(); metrics = new MetricService(rockContext).GetByGuids(metricGuids) .Select(m => new MetricResult { Id = m.Id, Title = m.Title, Description = m.Description, IconCssClass = m.IconCssClass, UnitsLabel = m.YAxisLabel, LastRunDateTime = m.MetricValues.OrderByDescending(v => v.MetricValueDateTime).Select(v => v.MetricValueDateTime).FirstOrDefault(), LastValue = m.MetricValues.OrderByDescending(v => v.MetricValueDateTime).Select(v => v.YValue).FirstOrDefault() }).ToList(); // Get metric values for each metric if requested if (metricValueCount > 0) { foreach (var metric in metrics) { metric.MetricValues = new MetricValueService(rockContext).Queryable() .Where(v => v.MetricId == metric.Id) .OrderByDescending(v => v.MetricValueDateTime) .Select(v => new MetricValue { DateTime = v.MetricValueDateTime, Value = v.YValue, Note = v.Note }) .Take(metricValueCount) .ToList(); } } // Set Cache if (cacheDuration > 0 && _currentPage == 0) { var cachedData = new CachedBlockData(); cachedData.ContentChannelItem = contentChannelItem.Clone(false); cachedData.ShowPrev = showPrev; cachedData.Metrics = metrics; var expiration = RockDateTime.Now.AddSeconds(cacheDuration); RockCache.AddOrUpdate(cacheKey, string.Empty, cachedData.ToJson(), expiration, cacheTags); } } mergeFields.Add("Item", contentChannelItem); mergeFields.Add("Metrics", metrics); lBlockTitleIcon.Text = string.Format("<i class='{0}'></i>", blockTitleIconCssClass); lBlockTitle.Text = blockTitleTemplate.ResolveMergeFields(mergeFields, enabledLavaCommands); lBlockBody.Text = bodyTemplate.ResolveMergeFields(mergeFields, enabledLavaCommands); // Determine if we can page backwards btnPrevious.Visible = showPrev; // Determine if we can page forwards btnNext.Visible = (_currentPage > 0); // Set the current page hidden field hfCurrentPage.Value = _currentPage.ToString(); }
/// <summary> /// Gets the cache object associated with this Entity /// </summary> /// <returns></returns> public IEntityCache GetCacheObject() { return(ContentChannelCache.Get(this.Id)); }
public void ProcessRequest(HttpContext context) { request = context.Request; response = context.Response; string cacheKey = "Rock:GetChannelFeed:" + request.RawUrl; var contentCache = RockCache.Get(cacheKey); var mimeTypeCache = RockCache.Get(cacheKey + ":MimeType"); if (mimeTypeCache != null && contentCache != null) { response.ContentType = ( string )mimeTypeCache; response.Write(( string )contentCache); response.StatusCode = 200; return; } if (request.HttpMethod != "GET" && request.HttpMethod != "HEAD") { response.TrySkipIisCustomErrors = true; response.StatusCode = 405; response.Headers.Add("Allow", "GET"); response.Write("Invalid request method."); return; } if (request.QueryString["ChannelId"] == null) { response.TrySkipIisCustomErrors = true; response.StatusCode = 400; response.Write("A ChannelId is required."); return; } int?channelId = request.QueryString["ChannelId"].AsIntegerOrNull(); if (channelId == null) { response.TrySkipIisCustomErrors = true; response.StatusCode = 400; response.Write("Invalid channel id."); return; } var channel = ContentChannelCache.Get(channelId.Value); if (channel == null) { response.TrySkipIisCustomErrors = true; response.StatusCode = 404; response.Write("Channel does not exist."); return; } if (!channel.EnableRss) { response.TrySkipIisCustomErrors = true; response.StatusCode = 403; response.Write("RSS is not enabled for this channel."); return; } DefinedValueCache dvRssTemplate = null; if (request.QueryString["TemplateId"] != null) { int?templateDefinedValueId = request.QueryString["TemplateId"].AsIntegerOrNull(); if (templateDefinedValueId == null) { response.TrySkipIisCustomErrors = true; response.StatusCode = 400; response.Write("Invalid template id."); return; } dvRssTemplate = DefinedValueCache.Get(templateDefinedValueId.Value); } if (dvRssTemplate == null) { dvRssTemplate = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.DEFAULT_RSS_CHANNEL); } if (dvRssTemplate.DefinedType.Guid != new Guid(Rock.SystemGuid.DefinedType.LAVA_TEMPLATES)) { response.TrySkipIisCustomErrors = true; response.StatusCode = 400; response.Write("Invalid template id."); return; } string rssTemplate = dvRssTemplate.GetAttributeValue("Template"); if (string.IsNullOrWhiteSpace(dvRssTemplate.GetAttributeValue("MimeType"))) { response.ContentType = "application/rss+xml"; } else { response.ContentType = dvRssTemplate.GetAttributeValue("MimeType"); } if (request.HttpMethod == "HEAD") { response.StatusCode = 200; return; } // load merge fields var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(null); mergeFields.Add("Channel", channel); var safeProxyUrl = request.UrlProxySafe(); Dictionary <string, object> requestObjects = new Dictionary <string, object>(); requestObjects.Add("Scheme", safeProxyUrl.Scheme); requestObjects.Add("Host", WebRequestHelper.GetHostNameFromRequest(context)); requestObjects.Add("Authority", safeProxyUrl.Authority); requestObjects.Add("LocalPath", safeProxyUrl.LocalPath); requestObjects.Add("AbsoluteUri", safeProxyUrl.AbsoluteUri); requestObjects.Add("AbsolutePath", safeProxyUrl.AbsolutePath); requestObjects.Add("Port", safeProxyUrl.Port); requestObjects.Add("Query", safeProxyUrl.Query); requestObjects.Add("OriginalString", safeProxyUrl.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 var rockContext = new RockContext(); ContentChannelItemService contentService = new ContentChannelItemService(rockContext); var content = contentService.Queryable().AsNoTracking().Where(c => c.ContentChannelId == channel.Id && c.StartDateTime <= RockDateTime.Now); if (!channel.ContentChannelType.DisableStatus && channel.RequiresApproval) { content = content.Where(cci => cci.Status == ContentChannelItemStatus.Approved); } if (channel.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange) { if (channel.ContentChannelType.IncludeTime) { content = content.Where(c => !c.ExpireDateTime.HasValue || c.ExpireDateTime >= RockDateTime.Now); } else { content = content.Where(c => !c.ExpireDateTime.HasValue || c.ExpireDateTime > RockDateTime.Today); } } if (channel.ItemsManuallyOrdered) { content = content.OrderBy(c => c.Order); } else { content = content.OrderByDescending(c => c.StartDateTime); } var contentItems = content.Take(rssItemLimit).ToList(); foreach (var item in contentItems) { item.Content = item.Content.ResolveMergeFields(mergeFields); // resolve any relative links var globalAttributes = GlobalAttributesCache.Get(); string publicAppRoot = globalAttributes.GetValue("PublicApplicationRoot"); 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", contentItems); mergeFields.Add("RockVersion", Rock.VersionInfo.VersionInfo.GetRockProductVersionNumber()); var outputContent = rssTemplate.ResolveMergeFields(mergeFields); response.Write(outputContent); var cacheDuration = dvRssTemplate.GetAttributeValue("CacheDuration").AsInteger(); if (cacheDuration > 0) { var expiration = RockDateTime.Now.AddMinutes(cacheDuration); if (expiration > RockDateTime.Now) { RockCache.AddOrUpdate(cacheKey + ":MimeType", null, response.ContentType, expiration); RockCache.AddOrUpdate(cacheKey, null, outputContent, expiration); } ; } }
/// <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.Get(attribute.FieldTypeId); if (fieldType != null && (!limitToFilterableAttributes || fieldType.Field.HasFilterControl())) { entityField = new EntityField(fieldName, FieldKind.Attribute, typeof(string), attribute.Guid, fieldType); entityField.Title = attribute.Name; entityField.TitleWithoutQualifier = entityField.Title; foreach (var config in attribute.QualifierValues) { entityField.FieldConfig.Add(config.Key, config.Value); } // Special processing for Entity Type "Group" or "GroupMember" to handle sub-types that are distinguished by GroupTypeId. if ((attribute.EntityTypeId == EntityTypeCache.GetId(typeof(Group)) || attribute.EntityTypeId == EntityTypeCache.GetId(typeof(GroupMember)) && attribute.EntityTypeQualifierColumn == "GroupTypeId")) { var groupType = GroupTypeCache.Get(attribute.EntityTypeQualifierValue.AsInteger()); 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 "ConnectionRequest" to handle sub-types that are distinguished by ConnectionOpportunityId. if (attribute.EntityTypeId == EntityTypeCache.GetId(typeof(ConnectionRequest)) && attribute.EntityTypeQualifierColumn == "ConnectionOpportunityId") { using (var rockContext = new RockContext()) { var connectionOpportunityName = new ConnectionOpportunityService(rockContext).GetSelect(attribute.EntityTypeQualifierValue.AsInteger(), s => s.Name); if (connectionOpportunityName != null) { // Append the Qualifier to the title entityField.AttributeEntityTypeQualifierName = connectionOpportunityName; entityField.Title = string.Format("{0} (Opportunity: {1})", attribute.Name, connectionOpportunityName); } } } // 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 contentChannelTypeName = new ContentChannelTypeService(rockContext).GetSelect(attribute.EntityTypeQualifierValue.AsInteger(), s => s.Name); if (contentChannelTypeName != null) { // Append the Qualifier to the title entityField.AttributeEntityTypeQualifierName = contentChannelTypeName; entityField.Title = string.Format("{0} (ChannelType: {1})", attribute.Name, contentChannelTypeName); } } } // Special processing for Entity Type "Registration" to handle sub-types that are distinguished by RegistrationTemplateId. if (attribute.EntityTypeId == EntityTypeCache.GetId(typeof(Registration)) && attribute.EntityTypeQualifierColumn == "RegistrationTemplateId") { using (var rockContext = new RockContext()) { var RegistrationTemplateName = new RegistrationTemplateService(rockContext).GetSelect(attribute.EntityTypeQualifierValue.AsInteger(), s => s.Name); if (RegistrationTemplateName != null) { // Append the Qualifier to the title entityField.AttributeEntityTypeQualifierName = RegistrationTemplateName; entityField.Title = string.Format("{0} (Registration Template: {1})", attribute.Name, RegistrationTemplateName); } } } // 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") { var contentChannel = ContentChannelCache.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") { int workflowTypeId = attribute.EntityTypeQualifierValue.AsInteger(); if (_workflowTypeNameLookup == null) { using (var rockContext = new RockContext()) { _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); }