/// <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); }
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> /// Shows the settings. /// </summary> protected override void ShowSettings() { pnlSettings.Visible = true; ddlContentChannel.Items.Clear(); ddlContentChannel.Items.Add(new ListItem()); foreach (var contentChannel in ContentChannelCache.All().OrderBy(a => a.Name)) { ddlContentChannel.Items.Add(new ListItem(contentChannel.Name, contentChannel.Guid.ToString())); } ddlLaunchWorkflowCondition.Items.Clear(); foreach (LaunchWorkflowCondition launchWorkflowCondition in Enum.GetValues(typeof(LaunchWorkflowCondition))) { ddlLaunchWorkflowCondition.Items.Add(new ListItem(launchWorkflowCondition.ConvertToString(true), launchWorkflowCondition.ConvertToInt().ToString())); } var channelGuid = this.GetAttributeValue("ContentChannel").AsGuidOrNull(); ddlContentChannel.SetValue(channelGuid); UpdateSocialMediaDropdowns(channelGuid); cblStatus.BindToEnum <ContentChannelItemStatus>(); foreach (string status in GetAttributeValue("Status").SplitDelimitedValues()) { var li = cblStatus.Items.FindByValue(status); if (li != null) { li.Selected = true; } } var ppFieldType = new PageReferenceFieldType(); ppFieldType.SetEditValue(ppDetailPage, null, GetAttributeValue("DetailPage")); tbContentChannelQueryParameter.Text = this.GetAttributeValue("ContentChannelQueryParameter"); ceLavaTemplate.Text = this.GetAttributeValue("LavaTemplate"); nbOutputCacheDuration.Text = this.GetAttributeValue("OutputCacheDuration"); nbItemCacheDuration.Text = this.GetAttributeValue("ItemCacheDuration"); DefinedValueService definedValueService = new DefinedValueService(new RockContext()); cblCacheTags.DataSource = definedValueService.GetByDefinedTypeGuid(Rock.SystemGuid.DefinedType.CACHE_TAGS.AsGuid()).Select(v => v.Value).ToList(); cblCacheTags.DataBind(); string[] selectedCacheTags = this.GetAttributeValue("CacheTags").SplitDelimitedValues(); foreach (ListItem cacheTag in cblCacheTags.Items) { cacheTag.Selected = selectedCacheTags.Contains(cacheTag.Value); } cbSetPageTitle.Checked = this.GetAttributeValue("SetPageTitle").AsBoolean(); if (this.GetAttributeValue("LogInteractions").AsBoolean()) { cbLogInteractions.Checked = true; cbWriteInteractionOnlyIfIndividualLoggedIn.Visible = true; cbWriteInteractionOnlyIfIndividualLoggedIn.Checked = this.GetAttributeValue("WriteInteractionOnlyIfIndividualLoggedIn").AsBoolean(); } else { cbLogInteractions.Checked = false; cbWriteInteractionOnlyIfIndividualLoggedIn.Visible = false; cbWriteInteractionOnlyIfIndividualLoggedIn.Checked = false; } var rockContext = new RockContext(); // Workflow Guid?workflowTypeGuid = this.GetAttributeValue("WorkflowType").AsGuidOrNull(); if (workflowTypeGuid.HasValue) { wtpWorkflowType.SetValue(new WorkflowTypeService(rockContext).GetNoTracking(workflowTypeGuid.Value)); } else { wtpWorkflowType.SetValue(null); } ShowHideContorls(); cbLaunchWorkflowOnlyIfIndividualLoggedIn.Checked = this.GetAttributeValue("LaunchWorkflowOnlyIfIndividualLoggedIn").AsBoolean(); ddlLaunchWorkflowCondition.SetValue(this.GetAttributeValue("LaunchWorkflowCondition")); // Social Media ddlMetaDescriptionAttribute.SetValue(this.GetAttributeValue("MetaDescriptionAttribute")); ddlOpenGraphType.SetValue(this.GetAttributeValue("OpenGraphType")); ddlOpenGraphTitleAttribute.SetValue(this.GetAttributeValue("OpenGraphTitleAttribute")); ddlOpenGraphDescriptionAttribute.SetValue(this.GetAttributeValue("OpenGraphDescriptionAttribute")); ddlOpenGraphImageAttribute.SetValue(this.GetAttributeValue("OpenGraphImageAttribute")); ddlTwitterTitleAttribute.SetValue(this.GetAttributeValue("TwitterTitleAttribute")); ddlTwitterDescriptionAttribute.SetValue(this.GetAttributeValue("TwitterDescriptionAttribute")); ddlTwitterImageAttribute.SetValue(this.GetAttributeValue("TwitterImageAttribute")); ddlTwitterCard.SetValue(this.GetAttributeValue("TwitterCard")); mdSettings.Show(); }
/// <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 (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 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); 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)); 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(); }
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 == null || 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> /// Updates any Cache Objects that are associated with this entity /// </summary> /// <param name="entityState">State of the entity.</param> /// <param name="dbContext">The database context.</param> public void UpdateCache(EntityState entityState, Rock.Data.DbContext dbContext) { ContentChannelCache.UpdateCachedEntity(this.Id, entityState); }
/// <summary> /// Gets the cache object associated with this Entity /// </summary> /// <returns></returns> public IEntityCache GetCacheObject() { return(ContentChannelCache.Get(this.Id)); }
/// <summary> /// Handles the Click event of the lbSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param> protected void lbSave_Click(object sender, EventArgs e) { var rockContext = new RockContext(); ContentChannel contentChannel; ContentChannelService contentChannelService = new ContentChannelService(rockContext); int contentChannelId = hfId.Value.AsInteger(); if (contentChannelId == 0) { contentChannel = new ContentChannel { Id = 0 }; contentChannelService.Add(contentChannel); } else { contentChannel = contentChannelService.Get(contentChannelId); } if (contentChannel != null) { contentChannel.Name = tbName.Text; contentChannel.Description = tbDescription.Text; contentChannel.ContentChannelTypeId = ddlChannelType.SelectedValueAsInt() ?? 0; contentChannel.ContentControlType = ddlContentControlType.SelectedValueAsEnum <ContentControlType>(); contentChannel.RootImageDirectory = tbRootImageDirectory.Visible ? tbRootImageDirectory.Text : string.Empty; contentChannel.IconCssClass = tbIconCssClass.Text; // the cbRequireApproval will be hidden if contentChannelType.DisableStatus == True contentChannel.RequiresApproval = cbRequireApproval.Visible && cbRequireApproval.Checked; contentChannel.IsIndexEnabled = cbIndexChannel.Checked; contentChannel.ItemsManuallyOrdered = cbItemsManuallyOrdered.Checked; contentChannel.ChildItemsManuallyOrdered = cbChildItemsManuallyOrdered.Checked; contentChannel.EnableRss = cbEnableRss.Checked; contentChannel.ChannelUrl = tbChannelUrl.Text; contentChannel.ItemUrl = tbItemUrl.Text; contentChannel.TimeToLive = nbTimetoLive.Text.AsIntegerOrNull(); contentChannel.ItemUrl = tbContentChannelItemPublishingPoint.Text; contentChannel.IsTaggingEnabled = cbEnableTag.Checked; contentChannel.ItemTagCategoryId = cbEnableTag.Checked ? cpCategory.SelectedValueAsInt() : (int?)null; contentChannel.ChildContentChannels = new List <ContentChannel>(); contentChannel.ChildContentChannels.Clear(); foreach (var item in ChildContentChannelsList) { var childContentChannel = contentChannelService.Get(item); if (childContentChannel != null) { contentChannel.ChildContentChannels.Add(childContentChannel); } } contentChannel.LoadAttributes(rockContext); Rock.Attribute.Helper.GetEditValues(phAttributes, contentChannel); if (!Page.IsValid || !contentChannel.IsValid) { // Controls will render the error messages return; } rockContext.WrapTransaction(() => { rockContext.SaveChanges(); contentChannel.SaveAttributeValues(rockContext); foreach (var item in new ContentChannelItemService(rockContext) .Queryable() .Where(i => i.ContentChannelId == contentChannel.Id && i.ContentChannelTypeId != contentChannel.ContentChannelTypeId )) { item.ContentChannelTypeId = contentChannel.ContentChannelTypeId; } rockContext.SaveChanges(); // Save the Item Attributes int entityTypeId = EntityTypeCache.Read(typeof(ContentChannelItem)).Id; SaveAttributes(contentChannel.Id, entityTypeId, ItemAttributesState, rockContext); }); var pageReference = RockPage.PageReference; pageReference.Parameters.AddOrReplace("contentChannelId", contentChannel.Id.ToString()); Response.Redirect(pageReference.BuildUrl(), false); } // flush cache ContentChannelCache.Flush(contentChannel.Id); }
/// <summary> /// Gets the list source. /// </summary> /// <value> /// The list source. /// </value> internal override Dictionary <string, string> GetListSource(Dictionary <string, ConfigurationValue> configurationValues) { var allChannels = ContentChannelCache.All(); return(allChannels.ToDictionary(c => c.Guid.ToString(), c => c.Name)); }