/// <summary> /// Returns the field's current value(s) /// </summary> /// <param name="parentControl">The parent control.</param> /// <param name="value">Information about the value</param> /// <param name="configurationValues">The configuration values.</param> /// <param name="condensed">Flag indicating if the value should be condensed (i.e. for use in a grid column)</param> /// <returns></returns> public override string FormatValue(Control parentControl, string value, Dictionary <string, ConfigurationValue> configurationValues, bool condensed) { string formattedValue = string.Empty; Guid?guid = value.AsGuidOrNull(); if (guid.HasValue) { var contentChannel = new ContentChannelService(new RockContext()).Get(guid.Value); if (contentChannel != null) { formattedValue = contentChannel.Name; } } return(base.FormatValue(parentControl, formattedValue, configurationValues, condensed)); }
/// <summary> /// Gets the type of the content. /// </summary> /// <param name="contentItemId">The content type identifier.</param> /// <param name="rockContext">The rock context.</param> /// <returns></returns> private ContentChannelItem GetContentItem(RockContext rockContext = null) { rockContext = rockContext ?? new RockContext(); var contentItemService = new ContentChannelItemService(rockContext); ContentChannelItem contentItem = null; int contentItemId = hfId.Value.AsInteger(); if (contentItemId != 0) { contentItem = contentItemService .Queryable("ContentChannel,ContentChannelType") .FirstOrDefault(t => t.Id == contentItemId); } if (contentItem == null) { var contentChannel = new ContentChannelService(rockContext).Get(hfChannelId.Value.AsInteger()); if (contentChannel != null) { contentItem = new ContentChannelItem { ContentChannel = contentChannel, ContentChannelId = contentChannel.Id, ContentChannelType = contentChannel.ContentChannelType, ContentChannelTypeId = contentChannel.ContentChannelType.Id, StartDateTime = RockDateTime.Now }; if (contentChannel.RequiresApproval) { contentItem.Status = ContentChannelItemStatus.PendingApproval; } else { contentItem.Status = ContentChannelItemStatus.Approved; contentItem.ApprovedDateTime = RockDateTime.Now; contentItem.ApprovedByPersonAliasId = CurrentPersonAliasId; } contentItemService.Add(contentItem); } } return(contentItem); }
/// <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) { Guid?itemGuid = null; if (id.HasValue && id > 0) { itemGuid = new ContentChannelService(new RockContext()).GetGuid(id.Value); } if (itemGuid.HasValue) { SetEditValue(control, configurationValues, itemGuid.ToString()); } else { SetEditValue(control, configurationValues, string.Empty); } }
/// <summary> /// Gets the properties and attributes for the entity /// </summary> /// <param name="contentChannelTypeId">The content channel type identifier.</param> /// <returns></returns> private List <EntityField> GetContentChannelItemAttributes(int?contentChannelTypeId) { List <EntityField> entityAttributeFields = new List <EntityField>(); if (contentChannelTypeId.HasValue) { using (var rockContext = new RockContext()) { var contentChannelService = new ContentChannelService(rockContext); var allEntityAttributeFields = EntityHelper.GetEntityFields(typeof(Rock.Model.ContentChannelItem)).Where(a => a.FieldKind == FieldKind.Attribute); foreach (var entityAttributeField in allEntityAttributeFields) { var attributeCache = AttributeCache.Read(entityAttributeField.AttributeGuid.Value); if (attributeCache.EntityTypeQualifierColumn == "ContentChannelTypeId" && attributeCache.EntityTypeQualifierValue == contentChannelTypeId.ToString()) { entityAttributeFields.Add(entityAttributeField); } else if (attributeCache.EntityTypeQualifierColumn == "ContentChannelId") { int contentChannelId = attributeCache.EntityTypeQualifierValue.AsInteger(); var contentChannel = contentChannelService.Queryable().Where(a => a.Id == contentChannelId).FirstOrDefault(); if (contentChannel?.ContentChannelTypeId == contentChannelTypeId.Value) { entityAttributeFields.Add(entityAttributeField); } } } } } int index = 0; var sortedFields = new List <EntityField>(); foreach (var entityProperty in entityAttributeFields.OrderBy(p => p.TitleWithoutQualifier).ThenBy(p => p.Name)) { entityProperty.Index = index; index++; sortedFields.Add(entityProperty); } return(sortedFields); }
/// <summary> /// Handles the Add event of the gChildContentChannels control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param> protected void gChildContentChannels_Add(object sender, EventArgs e) { // populate dropdown with all grouptypes that aren't already childgroups var contentChannelList = new ContentChannelService(new RockContext()) .Queryable() .Where(t => !ChildContentChannelsList.Contains(t.Id)) .OrderBy(t => t.Name) .ToList(); if (contentChannelList.Count == 0) { modalAlert.Show("There are not any other content channels that can be added", ModalAlertType.Warning); } else { ddlChildContentChannel.DataSource = contentChannelList; ddlChildContentChannel.DataBind(); ShowDialog("ChildContentChannels"); } }
/// <summary> /// Creates the child controls. /// </summary> /// <returns></returns> public override Control[] CreateChildControls(Type entityType, FilterField filterControl) { RockDropDownList contentChannelPicker = new RockDropDownList(); contentChannelPicker.CssClass = "js-content-channel-picker"; contentChannelPicker.ID = filterControl.ID + "_contentChannelPicker"; contentChannelPicker.Label = "Content Channel"; contentChannelPicker.Items.Clear(); var contentChannelList = new ContentChannelService(new RockContext()).Queryable().OrderBy(a => a.Name).ToList(); foreach (var contentChannel in contentChannelList) { contentChannelPicker.Items.Add(new ListItem(contentChannel.Name, contentChannel.Id.ToString())); } filterControl.Controls.Add(contentChannelPicker); return(new Control[] { contentChannelPicker }); }
protected void ddlAddExistingItemChannel_SelectedIndexChanged(object sender, EventArgs e) { ddlAddExistingItem.Items.Clear(); int?channelId = ddlAddExistingItemChannel.SelectedValueAsInt(); if (channelId.HasValue) { using (var rockContext = new RockContext()) { var contentItem = GetContentItem(rockContext); var channel = new ContentChannelService(rockContext).Get(channelId.Value); var items = new List <ContentChannelItem>(); foreach (var item in channel.Items) { if (!contentItem.ChildItems.Any(i => i.ChildContentChannelItemId == item.Id) && item.IsAuthorized(Authorization.VIEW, CurrentPerson)) { items.Add(item); } } if (channel.ItemsManuallyOrdered) { items = items.OrderBy(i => i.Order).ToList(); } else { items = items.OrderByDescending(i => i.StartDateTime).ToList(); } foreach (var item in items) { ddlAddExistingItem.Items.Add(new ListItem(string.Format("{0} ({1})", item.Title, item.StartDateTime.ToShortDateString()), item.Id.ToString())); } } } }
/// <summary> /// Handles the Delete event of the gContentChannels control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RowEventArgs" /> instance containing the event data.</param> protected void gContentChannels_Delete(object sender, RowEventArgs e) { var rockContext = new RockContext(); ContentChannelService contentChannelService = new ContentChannelService(rockContext); ContentChannel contentChannel = contentChannelService.Get(e.RowKeyId); if (contentChannel != null) { string errorMessage; if (!contentChannelService.CanDelete(contentChannel, out errorMessage)) { mdGridWarning.Show(errorMessage, ModalAlertType.Information); return; } contentChannelService.Delete(contentChannel); rockContext.SaveChanges(); } BindGrid(); }
/// <summary> /// Gets the expression. /// </summary> /// <param name="entityType">Type of the entity.</param> /// <param name="serviceInstance">The service instance.</param> /// <param name="parameterExpression">The parameter expression.</param> /// <param name="selection">The selection.</param> /// <returns></returns> public override Expression GetExpression(Type entityType, IService serviceInstance, ParameterExpression parameterExpression, string selection) { string[] selectionValues = selection.Split('|'); if (selectionValues.Length >= 1) { var contentChannel = new ContentChannelService(new RockContext()).Get(selectionValues[0].AsGuid()); int?contentChannelId = null; if (contentChannel != null) { contentChannelId = contentChannel.Id; } var qry = new ContentChannelItemService((RockContext)serviceInstance.Context).Queryable() .Where(p => p.ContentChannelId == contentChannelId); Expression extractedFilterExpression = FilterExpressionExtractor.Extract <Rock.Model.ContentChannelItem>(qry, parameterExpression, "p"); return(extractedFilterExpression); } return(null); }
/// <summary> /// Creates the control(s) necessary for prompting user for a new value /// </summary> /// <param name="configurationValues">The configuration values.</param> /// <param name="id"></param> /// <returns> /// The control /// </returns> public override Control EditControl(Dictionary <string, ConfigurationValue> configurationValues, string id) { var editControl = new RockDropDownList { ID = id }; editControl.Items.Add(new ListItem()); var contentChannels = new ContentChannelService(new RockContext()).Queryable().OrderBy(d => d.Name); if (contentChannels.Any()) { foreach (var contentChannel in contentChannels) { editControl.Items.Add(new ListItem(contentChannel.Name, contentChannel.Guid.ToString().ToUpper())); } return(editControl); } return(null); }
private void GContentChannelItems_GridReorder(object sender, GridReorderEventArgs e) { if (SelectedChannelId.HasValue) { using (var rockContext = new RockContext()) { var selectedChannel = new ContentChannelService(rockContext).Get(SelectedChannelId.Value); if (selectedChannel != null) { bool isFiltered = false; var items = GetItems(rockContext, selectedChannel, out isFiltered); if (!isFiltered) { var service = new ContentChannelItemService(rockContext); service.Reorder(items, e.OldIndex, e.NewIndex); rockContext.SaveChanges(); } } } } GetData(); }
/// <summary> /// Handles the Click event of the lbSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param> protected void lbSave_Click(object sender, EventArgs e) { var rockContext = new RockContext(); ContentChannel contentChannel; ContentChannelService contentChannelService = new ContentChannelService(rockContext); CategoryService categoryService = new CategoryService(rockContext); int contentChannelId = hfId.Value.AsInteger(); if (contentChannelId == 0) { contentChannel = new ContentChannel { Id = 0 }; contentChannelService.Add(contentChannel); } else { contentChannel = contentChannelService.Get(contentChannelId); } if (contentChannel != null) { contentChannel.Name = tbName.Text; contentChannel.Description = tbDescription.Text; contentChannel.ContentChannelTypeId = ddlChannelType.SelectedValueAsInt() ?? 0; contentChannel.IsStructuredContent = cbIsStructuredContent.Checked; contentChannel.StructuredContentToolValueId = dvEditorTool.SelectedDefinedValueId; contentChannel.ContentControlType = ddlContentControlType.SelectedValueAsEnum <ContentControlType>(); contentChannel.RootImageDirectory = tbRootImageDirectory.Visible ? tbRootImageDirectory.Text : string.Empty; contentChannel.IconCssClass = tbIconCssClass.Text; // the cbRequireApproval will be hidden if contentChannelType.DisableStatus == True contentChannel.RequiresApproval = cbRequireApproval.Visible && cbRequireApproval.Checked; contentChannel.IsIndexEnabled = cbIndexChannel.Checked; contentChannel.ItemsManuallyOrdered = cbItemsManuallyOrdered.Checked; contentChannel.ChildItemsManuallyOrdered = cbChildItemsManuallyOrdered.Checked; contentChannel.EnableRss = cbEnableRss.Checked; contentChannel.ChannelUrl = tbChannelUrl.Text; contentChannel.TimeToLive = nbTimetoLive.Text.AsIntegerOrNull(); contentChannel.ItemUrl = tbContentChannelItemPublishingPoint.Text; contentChannel.IsTaggingEnabled = cbEnableTag.Checked; contentChannel.ItemTagCategoryId = cbEnableTag.Checked ? cpCategory.SelectedValueAsInt() : ( int? )null; // Add any categories contentChannel.Categories.Clear(); foreach (var categoryId in cpCategories.SelectedValuesAsInt()) { contentChannel.Categories.Add(categoryService.Get(categoryId)); } // Since changes to Categories isn't tracked by ChangeTracker, set the ModifiedDateTime just in case Categories changed contentChannel.ModifiedDateTime = RockDateTime.Now; contentChannel.ChildContentChannels = new List <ContentChannel>(); contentChannel.ChildContentChannels.Clear(); foreach (var item in ChildContentChannelsList) { var childContentChannel = contentChannelService.Get(item); if (childContentChannel != null) { contentChannel.ChildContentChannels.Add(childContentChannel); } } contentChannel.LoadAttributes(rockContext); Rock.Attribute.Helper.GetEditValues(phAttributes, contentChannel); if (!Page.IsValid || !contentChannel.IsValid) { // Controls will render the error messages return; } rockContext.WrapTransaction(() => { rockContext.SaveChanges(); contentChannel.SaveAttributeValues(rockContext); foreach (var item in new ContentChannelItemService(rockContext) .Queryable() .Where(i => i.ContentChannelId == contentChannel.Id && i.ContentChannelTypeId != contentChannel.ContentChannelTypeId )) { item.ContentChannelTypeId = contentChannel.ContentChannelTypeId; } rockContext.SaveChanges(); // Save the Item Attributes int entityTypeId = EntityTypeCache.Get(typeof(ContentChannelItem)).Id; SaveAttributes(contentChannel.Id, entityTypeId, ItemAttributesState, rockContext); }); var pageReference = RockPage.PageReference; pageReference.Parameters.AddOrReplace("ContentChannelId", contentChannel.Id.ToString()); Response.Redirect(pageReference.BuildUrl(), false); } }
/// <summary> /// 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); }
public void ProcessRequest(HttpContext context) { request = context.Request; response = context.Response; RockContext rockContext = new RockContext(); 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; } ContentChannel channel = new ContentChannelService(rockContext).Queryable("ContentChannelType").FirstOrDefault(c => c.Id == 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); Dictionary <string, object> requestObjects = new Dictionary <string, object>(); requestObjects.Add("Scheme", request.Url.Scheme); requestObjects.Add("Host", WebRequestHelper.GetHostNameFromRequest(context)); requestObjects.Add("Authority", request.Url.Authority); requestObjects.Add("LocalPath", request.Url.LocalPath); requestObjects.Add("AbsoluteUri", request.Url.AbsoluteUri); requestObjects.Add("AbsolutePath", request.Url.AbsolutePath); requestObjects.Add("Port", request.Url.Port); requestObjects.Add("Query", request.Url.Query); requestObjects.Add("OriginalString", request.Url.OriginalString); mergeFields.Add("Request", requestObjects); // check for new rss item limit if (request.QueryString["Count"] != null) { int.TryParse(request.QueryString["Count"], out rssItemLimit); } // get channel items ContentChannelItemService contentService = new ContentChannelItemService(rockContext); var content = contentService.Queryable("ContentChannelType") .Where(c => c.ContentChannelId == channel.Id && (c.Status == ContentChannelItemStatus.Approved || c.ContentChannel.ContentChannelType.DisableStatus || c.ContentChannel.RequiresApproval == false) && c.StartDateTime <= RockDateTime.Now); 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); } content = content.Take(rssItemLimit); content.LoadAttributes(); foreach (var item in content) { item.Content = item.Content.ResolveMergeFields(mergeFields); // resolve any relative links var globalAttributes = GlobalAttributesCache.Get(); string publicAppRoot = globalAttributes.GetValue("PublicApplicationRoot").EnsureTrailingForwardslash(); item.Content = item.Content.Replace(@" src=""/", @" src=""" + publicAppRoot); item.Content = item.Content.Replace(@" href=""/", @" href=""" + publicAppRoot); // get item attributes and add them as elements to the feed foreach (var attributeValue in item.AttributeValues) { attributeValue.Value.Value = attributeValue.Value.Value.ResolveMergeFields(mergeFields); } } mergeFields.Add("Items", content); mergeFields.Add("RockVersion", Rock.VersionInfo.VersionInfo.GetRockProductVersionNumber()); response.Write(rssTemplate.ResolveMergeFields(mergeFields)); }
/// <summary> /// Loads the content. /// </summary> private void LoadContent() { var rockContext = new RockContext(); var eventCalendarGuid = GetAttributeValue("EventCalendar").AsGuid(); var eventCalendar = new EventCalendarService(rockContext).Get(eventCalendarGuid); if (eventCalendar == null) { lMessages.Text = "<div class='alert alert-warning'>No event calendar is configured for this block.</div>"; lContent.Text = string.Empty; return; } else { lMessages.Text = string.Empty; } var eventItemOccurrenceService = new EventItemOccurrenceService(rockContext); // Grab events // NOTE: Do not use AsNoTracking() so that things can be lazy loaded if needed var qry = eventItemOccurrenceService .Queryable("EventItem, EventItem.EventItemAudiences,Schedule") .Where(m => m.EventItem.EventCalendarItems.Any(i => i.EventCalendarId == eventCalendar.Id) && m.EventItem.IsActive); // Filter by campus (always include the "All Campuses" events) if (GetAttributeValue("UseCampusContext").AsBoolean()) { var campusEntityType = EntityTypeCache.Get <Campus>(); var contextCampus = RockPage.GetCurrentContext(campusEntityType) as Campus; if (contextCampus != null) { qry = qry.Where(e => e.CampusId == contextCampus.Id || !e.CampusId.HasValue); } } else { var campusGuidList = GetAttributeValue("Campuses").Split(',').AsGuidList(); if (campusGuidList.Any()) { qry = qry.Where(e => !e.CampusId.HasValue || campusGuidList.Contains(e.Campus.Guid)); } } // make sure they have a date range var dateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues(this.GetAttributeValue("DateRange")); var today = RockDateTime.Today; dateRange.Start = dateRange.Start ?? today; if (dateRange.End == null) { dateRange.End = dateRange.Start.Value.AddDays(1000); } // Get the occurrences var occurrences = qry.ToList(); var occurrencesWithDates = occurrences .Select(o => new EventOccurrenceDate { EventItemOccurrence = o, Dates = o.GetStartTimes(dateRange.Start.Value, dateRange.End.Value).ToList() }) .Where(d => d.Dates.Any()) .ToList(); CalendarEventDates = new List <DateTime>(); var eventOccurrenceSummaries = new List <EventOccurrenceSummaryKFS>(); foreach (var occurrenceDates in occurrencesWithDates) { var eventItemOccurrence = occurrenceDates.EventItemOccurrence; foreach (var datetime in occurrenceDates.Dates) { CalendarEventDates.Add(datetime.Date); if (datetime >= dateRange.Start.Value && datetime < dateRange.End.Value) { var eventAudiences = eventItemOccurrence.EventItem.EventItemAudiences; eventOccurrenceSummaries.Add(new EventOccurrenceSummaryKFS { EventItemOccurrence = eventItemOccurrence, EventItem = eventItemOccurrence.EventItem, EventItemAudiences = eventAudiences.Select(o => DefinedValueCache.Get(o.DefinedValueId).Value).ToList(), Name = eventItemOccurrence.EventItem.Name, DateTime = datetime, Date = datetime.ToShortDateString(), Time = datetime.ToShortTimeString(), Location = eventItemOccurrence.Campus != null ? eventItemOccurrence.Campus.Name : "All Campuses", Description = eventItemOccurrence.EventItem.Description, Summary = eventItemOccurrence.EventItem.Summary, DetailPage = string.IsNullOrWhiteSpace(eventItemOccurrence.EventItem.DetailsUrl) ? null : eventItemOccurrence.EventItem.DetailsUrl }); } } } eventOccurrenceSummaries = eventOccurrenceSummaries .OrderBy(e => e.DateTime) .ThenBy(e => e.Name) .ToList(); // limit results int?maxItems = GetAttributeValue("MaxOccurrences").AsIntegerOrNull(); if (maxItems.HasValue) { eventOccurrenceSummaries = eventOccurrenceSummaries.Take(maxItems.Value).ToList(); } var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson); mergeFields.Add("DetailsPage", LinkedPageUrl("DetailsPage", null)); mergeFields.Add("EventOccurrenceSummaries", eventOccurrenceSummaries); //KFS Custom code to link Channels together var items = GetCacheItem(CONTENT_CACHE_KEY) as List <ContentChannelItem>; var errorMessages = new List <string>(); Guid?channelGuid = GetAttributeValue("ChannelforLava").AsGuidOrNull(); if (channelGuid.HasValue) { //var rockContext = new RockContext(); var service = new ContentChannelItemService(rockContext); var itemType = typeof(Rock.Model.ContentChannelItem); ParameterExpression paramExpression = service.ParameterExpression; var contentChannel = new ContentChannelService(rockContext).Get(channelGuid.Value); if (contentChannel != null) { var entityFields = HackEntityFields(contentChannel, rockContext); if (items == null) { items = new List <ContentChannelItem>(); var qryChannel = service.Queryable("ContentChannel,ContentChannelType"); int?itemId = PageParameter("Item").AsIntegerOrNull(); { qryChannel = qryChannel.Where(i => i.ContentChannelId == contentChannel.Id); if (contentChannel.RequiresApproval) { // Check for the configured status and limit query to those var statuses = new List <ContentChannelItemStatus>(); foreach (string statusVal in (GetAttributeValue("Status") ?? "2").Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) { var status = statusVal.ConvertToEnumOrNull <ContentChannelItemStatus>(); if (status != null) { statuses.Add(status.Value); } } if (statuses.Any()) { qryChannel = qryChannel.Where(i => statuses.Contains(i.Status)); } } int?dataFilterId = GetAttributeValue("FilterId").AsIntegerOrNull(); if (dataFilterId.HasValue) { var dataFilterService = new DataViewFilterService(rockContext); var dataFilter = dataFilterService.Queryable("ChildFilters").FirstOrDefault(a => a.Id == dataFilterId.Value); Expression whereExpression = dataFilter != null?dataFilter.GetExpression(itemType, service, paramExpression, errorMessages) : null; qryChannel = qryChannel.Where(paramExpression, whereExpression, null); } } // All filtering has been added, now run query and load attributes foreach (var item in qryChannel.ToList()) { item.LoadAttributes(rockContext); items.Add(item); } // Order the items SortProperty sortProperty = null; string orderBy = GetAttributeValue("Order"); if (!string.IsNullOrWhiteSpace(orderBy)) { var fieldDirection = new List <string>(); foreach (var itemPair in orderBy.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries).Select(a => a.Split('^'))) { if (itemPair.Length == 2 && !string.IsNullOrWhiteSpace(itemPair[0])) { var sortDirection = SortDirection.Ascending; if (!string.IsNullOrWhiteSpace(itemPair[1])) { sortDirection = itemPair[1].ConvertToEnum <SortDirection>(SortDirection.Ascending); } fieldDirection.Add(itemPair[0] + (sortDirection == SortDirection.Descending ? " desc" : "")); } } sortProperty = new SortProperty(); sortProperty.Direction = SortDirection.Ascending; sortProperty.Property = fieldDirection.AsDelimited(","); string[] columns = sortProperty.Property.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); var itemQry = items.AsQueryable(); IOrderedQueryable <ContentChannelItem> orderedQry = null; for (int columnIndex = 0; columnIndex < columns.Length; columnIndex++) { string column = columns[columnIndex].Trim(); var direction = sortProperty.Direction; if (column.ToLower().EndsWith(" desc")) { column = column.Left(column.Length - 5); direction = sortProperty.Direction == SortDirection.Ascending ? SortDirection.Descending : SortDirection.Ascending; } try { if (column.StartsWith("Attribute:")) { string attributeKey = column.Substring(10); if (direction == SortDirection.Ascending) { orderedQry = (columnIndex == 0) ? itemQry.OrderBy(i => i.AttributeValues.Where(v => v.Key == attributeKey).FirstOrDefault().Value.SortValue) : orderedQry.ThenBy(i => i.AttributeValues.Where(v => v.Key == attributeKey).FirstOrDefault().Value.SortValue); } else { orderedQry = (columnIndex == 0) ? itemQry.OrderByDescending(i => i.AttributeValues.Where(v => v.Key == attributeKey).FirstOrDefault().Value.SortValue) : orderedQry.ThenByDescending(i => i.AttributeValues.Where(v => v.Key == attributeKey).FirstOrDefault().Value.SortValue); } } else { if (direction == SortDirection.Ascending) { orderedQry = (columnIndex == 0) ? itemQry.OrderBy(column) : orderedQry.ThenBy(column); } else { orderedQry = (columnIndex == 0) ? itemQry.OrderByDescending(column) : orderedQry.ThenByDescending(column); } } } catch { } } try { if (orderedQry != null) { items = orderedQry.ToList(); } } catch { } } int?cacheDuration = GetAttributeValue("CacheDuration").AsInteger(); if (cacheDuration > 0) { AddCacheItem(CONTENT_CACHE_KEY, items, cacheDuration.Value); } } } if (items != null) { mergeFields.Add("ContentChannelItems", items); } } lContent.Text = GetAttributeValue("LavaTemplate").ResolveMergeFields(mergeFields); }
/// <summary> /// Formats the search result. /// </summary> /// <param name="person">The person.</param> /// <param name="displayOptions">The display options.</param> /// <param name="mergeFields"></param> /// <returns></returns> public override FormattedSearchResult FormatSearchResult(Person person, Dictionary <string, object> displayOptions = null, Dictionary <string, object> mergeFields = null) { string url = string.Empty; bool isSecurityDisabled = false; if (displayOptions != null) { if (displayOptions.ContainsKey("ChannelItem-IsSecurityDisabled")) { isSecurityDisabled = displayOptions["ChannelItem-IsSecurityDisabled"].ToString().AsBoolean(); } } if (!isSecurityDisabled) { // check security var contentChannelItem = new ContentChannelItemService(new RockContext()).Get((int)this.Id); var isAllowedView = false; if (contentChannelItem != null) { isAllowedView = contentChannelItem.IsAuthorized("View", person); } if (!isAllowedView) { return(new FormattedSearchResult() { IsViewAllowed = false }); } } // if url was not passed in use default from content channel if (displayOptions == null || !displayOptions.ContainsKey("ChannelItem-Url")) { var channel = new ContentChannelService(new RockContext()).Get(this.ContentChannelId); if (channel != null) { url = channel.ItemUrl; if (url.IsNotNullOrWhiteSpace()) { if (mergeFields == null) { mergeFields = new Dictionary <string, object>(); } mergeFields.AddOrReplace("Id", this.Id); mergeFields.AddOrReplace("Title", this.Title); mergeFields.AddOrReplace("ContentChannelId", this.ContentChannelId); mergeFields.AddOrReplace("Slug", this.PrimarySlug); if (displayOptions == null) { displayOptions = new Dictionary <string, object>(); } displayOptions["ChannelItem-Url"] = url.ResolveMergeFields(mergeFields); } } } return(base.FormatSearchResult(person, displayOptions)); }
private void GetData() { var rockContext = new RockContext(); var itemService = new ContentChannelItemService(rockContext); // Get all of the content channels var contentChannelsQry = new ContentChannelService(rockContext).Queryable("ContentChannelType"); List <Guid> contentChannelTypeGuidsInclude = GetAttributeValue("ContentChannelTypesInclude").SplitDelimitedValues().AsGuidList(); List <Guid> contentChannelTypeGuidsExclude = GetAttributeValue("ContentChannelTypesExclude").SplitDelimitedValues().AsGuidList(); if (contentChannelTypeGuidsInclude.Any()) { // if contentChannelTypeGuidsInclude is specified, only get contentChannelTypes that are in the contentChannelTypeGuidsInclude // NOTE: no need to factor in contentChannelTypeGuidsExclude since included would take precendance and the excluded ones would already not be included contentChannelsQry = contentChannelsQry.Where(a => contentChannelTypeGuidsInclude.Contains(a.ContentChannelType.Guid)); } else if (contentChannelTypeGuidsExclude.Any()) { contentChannelsQry = contentChannelsQry.Where(a => !contentChannelTypeGuidsExclude.Contains(a.ContentChannelType.Guid)); } var contentChannelsList = contentChannelsQry.OrderBy(w => w.Name).ToList(); // Create variable for storing authorized channels and the count of active items var channelCounts = new Dictionary <int, int>(); foreach (var channel in contentChannelsList) { if (channel.IsAuthorized(Authorization.VIEW, CurrentPerson)) { channelCounts.Add(channel.Id, 0); } } // Get the pending approval item counts for each channel (if the channel requires approval) itemService.Queryable() .Where(i => channelCounts.Keys.Contains(i.ContentChannelId) && i.Status == ContentChannelItemStatus.PendingApproval && i.ContentChannel.RequiresApproval) .GroupBy(i => i.ContentChannelId) .Select(i => new { Id = i.Key, Count = i.Count() }) .ToList() .ForEach(i => channelCounts[i.Id] = i.Count); // Create a query to return channel, the count of items, and the selected class var qry = contentChannelsList .Where(c => channelCounts.Keys.Contains(c.Id)) .Select(c => new { Channel = c, Count = channelCounts[c.Id], Class = (SelectedChannelId.HasValue && SelectedChannelId.Value == c.Id) ? "active" : "" }); // If displaying active only, update query to exclude those content channels without any items if (tglStatus.Checked) { qry = qry.Where(c => c.Count > 0); } var contentChannels = qry.ToList(); rptChannels.DataSource = contentChannels; rptChannels.DataBind(); ContentChannel selectedChannel = null; if (SelectedChannelId.HasValue) { selectedChannel = contentChannelsList .Where(w => w.Id == SelectedChannelId.Value && channelCounts.Keys.Contains(SelectedChannelId.Value)) .FirstOrDefault(); } if (selectedChannel != null && contentChannels.Count > 0) { // show the content item panel divItemPanel.Visible = true; BindAttributes(selectedChannel); AddDynamicControls(selectedChannel); var itemQry = itemService.Queryable() .Where(i => i.ContentChannelId == selectedChannel.Id); var drp = new DateRangePicker(); drp.DelimitedValues = gfFilter.GetUserPreference("Date Range"); if (drp.LowerValue.HasValue) { if (selectedChannel.ContentChannelType.DateRangeType == ContentChannelDateType.SingleDate) { itemQry = itemQry.Where(i => i.StartDateTime >= drp.LowerValue.Value); } else { itemQry = itemQry.Where(i => i.ExpireDateTime.HasValue && i.ExpireDateTime.Value >= drp.LowerValue.Value); } } if (drp.UpperValue.HasValue) { DateTime upperDate = drp.UpperValue.Value.Date.AddDays(1); itemQry = itemQry.Where(i => i.StartDateTime <= upperDate); } var status = gfFilter.GetUserPreference("Status").ConvertToEnumOrNull <ContentChannelItemStatus>(); if (status.HasValue) { itemQry = itemQry.Where(i => i.Status == status); } string title = gfFilter.GetUserPreference("Title"); if (!string.IsNullOrWhiteSpace(title)) { itemQry = itemQry.Where(i => i.Title.Contains(title)); } int?personId = gfFilter.GetUserPreference("Created By").AsIntegerOrNull(); if (personId.HasValue && personId.Value != 0) { itemQry = itemQry.Where(i => i.CreatedByPersonAlias.PersonId == personId); } // Filter query by any configured attribute filters if (AvailableAttributes != null && AvailableAttributes.Any()) { var attributeValueService = new AttributeValueService(rockContext); var parameterExpression = attributeValueService.ParameterExpression; foreach (var attribute in AvailableAttributes) { var filterControl = phAttributeFilters.FindControl("filter_" + attribute.Id.ToString()); if (filterControl != null) { var filterValues = attribute.FieldType.Field.GetFilterValues(filterControl, attribute.QualifierValues, Rock.Reporting.FilterMode.SimpleFilter); var expression = attribute.FieldType.Field.AttributeFilterExpression(attribute.QualifierValues, filterValues, parameterExpression); if (expression != null) { var attributeValues = attributeValueService .Queryable() .Where(v => v.Attribute.Id == attribute.Id); attributeValues = attributeValues.Where(parameterExpression, expression, null); itemQry = itemQry.Where(w => attributeValues.Select(v => v.EntityId).Contains(w.Id)); } } } } var items = new List <ContentChannelItem>(); foreach (var item in itemQry.ToList()) { if (item.IsAuthorized(Rock.Security.Authorization.VIEW, CurrentPerson)) { items.Add(item); } } SortProperty sortProperty = gContentChannelItems.SortProperty; if (sortProperty != null) { items = items.AsQueryable().Sort(sortProperty).ToList(); } else { items = items.OrderByDescending(p => p.StartDateTime).ToList(); } gContentChannelItems.ObjectList = new Dictionary <string, object>(); items.ForEach(i => gContentChannelItems.ObjectList.Add(i.Id.ToString(), i)); gContentChannelItems.DataSource = items.Select(i => new { i.Id, i.Guid, i.Title, i.StartDateTime, i.ExpireDateTime, i.Priority, Status = DisplayStatus(i.Status), Occurrences = i.EventItemOccurrences.Any(), CreatedByPersonName = i.CreatedByPersonAlias != null ? String.Format("<a href={0}>{1}</a>", ResolveRockUrl(string.Format("~/Person/{0}", i.CreatedByPersonAlias.PersonId)), i.CreatedByPersonName) : String.Empty }).ToList(); gContentChannelItems.DataBind(); lContentChannelItems.Text = selectedChannel.Name + " Items"; } else { divItemPanel.Visible = false; } }
/// <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(); rockContext.WrapTransaction(() => { if (contextEntity is Person) { var personService = new PersonService(rockContext); var changes = new History.HistoryChangeList(); var _person = personService.Get(contextEntity.Id); History.EvaluateChange(changes, "Foreign Key", _person.ForeignKey, tbForeignKey.Text); _person.ForeignKey = tbForeignKey.Text; History.EvaluateChange(changes, "Foreign Guid", _person.ForeignGuid.ToString(), tbForeignGuid.Text); _person.ForeignGuid = tbForeignGuid.Text.AsType <Guid?>(); History.EvaluateChange(changes, "Foreign Id", _person.ForeignId.ToString(), tbForeignId.Text); _person.ForeignId = tbForeignId.Text.AsType <int?>(); if (rockContext.SaveChanges() > 0) { if (changes.Any()) { HistoryService.SaveChanges( rockContext, typeof(Person), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(), _person.Id, changes); } } } else if (contextEntity is FinancialAccount) { var accountService = new FinancialAccountService(rockContext); var _account = accountService.Get(contextEntity.Id); _account.ForeignKey = tbForeignKey.Text; _account.ForeignGuid = tbForeignGuid.Text.AsType <Guid?>(); _account.ForeignId = tbForeignId.Text.AsType <int?>(); rockContext.SaveChanges(); } else if (contextEntity is FinancialBatch) { var batchService = new FinancialBatchService(rockContext); var changes = new History.HistoryChangeList(); var _batch = batchService.Get(contextEntity.Id); History.EvaluateChange(changes, "Foreign Key", _batch.ForeignKey, tbForeignKey.Text); _batch.ForeignKey = tbForeignKey.Text; History.EvaluateChange(changes, "Foreign Guid", _batch.ForeignGuid.ToString(), tbForeignGuid.Text); _batch.ForeignGuid = tbForeignGuid.Text.AsType <Guid?>(); History.EvaluateChange(changes, "Foreign Id", _batch.ForeignId.ToString(), tbForeignId.Text); _batch.ForeignId = tbForeignId.Text.AsType <int?>(); if (rockContext.SaveChanges() > 0) { if (changes.Any()) { HistoryService.SaveChanges( rockContext, typeof(FinancialBatch), Rock.SystemGuid.Category.HISTORY_FINANCIAL_BATCH.AsGuid(), _batch.Id, changes); } } } else if (contextEntity is FinancialPledge) { var pledgeService = new FinancialPledgeService(rockContext); var _pledge = pledgeService.Get(contextEntity.Id); _pledge.ForeignKey = tbForeignKey.Text; _pledge.ForeignGuid = tbForeignGuid.Text.AsType <Guid?>(); _pledge.ForeignId = tbForeignId.Text.AsType <int?>(); rockContext.SaveChanges(); } else if (contextEntity is FinancialTransaction) { var transactionService = new FinancialTransactionService(rockContext); var changes = new History.HistoryChangeList(); var _transaction = transactionService.Get(contextEntity.Id); History.EvaluateChange(changes, "Foreign Key", _transaction.ForeignKey, tbForeignKey.Text); _transaction.ForeignKey = tbForeignKey.Text; History.EvaluateChange(changes, "Foreign Guid", _transaction.ForeignGuid.ToString(), tbForeignGuid.Text); _transaction.ForeignGuid = tbForeignGuid.Text.AsType <Guid?>(); History.EvaluateChange(changes, "Foreign Id", _transaction.ForeignId.ToString(), tbForeignId.Text); _transaction.ForeignId = tbForeignId.Text.AsType <int?>(); if (rockContext.SaveChanges() > 0) { if (changes.Any()) { HistoryService.SaveChanges( rockContext, typeof(FinancialTransaction), Rock.SystemGuid.Category.HISTORY_FINANCIAL_TRANSACTION.AsGuid(), _transaction.Id, changes); } } } else if (contextEntity is FinancialScheduledTransaction) { var transactionScheduledService = new FinancialScheduledTransactionService(rockContext); var _scheduledTransaction = transactionScheduledService.Get(contextEntity.Id); _scheduledTransaction.ForeignKey = tbForeignKey.Text; _scheduledTransaction.ForeignGuid = tbForeignGuid.Text.AsType <Guid?>(); _scheduledTransaction.ForeignId = tbForeignId.Text.AsType <int?>(); rockContext.SaveChanges(); } else if (contextEntity is Group) { var groupService = new GroupService(rockContext); var _group = groupService.Get(contextEntity.Id); _group.ForeignKey = tbForeignKey.Text; _group.ForeignGuid = tbForeignGuid.Text.AsType <Guid?>(); _group.ForeignId = tbForeignId.Text.AsType <int?>(); rockContext.SaveChanges(); } else if (contextEntity is GroupMember) { var groupMemberService = new GroupMemberService(rockContext); var changes = new History.HistoryChangeList(); var _groupMember = groupMemberService.Get(contextEntity.Id); History.EvaluateChange(changes, "Foreign Key", _groupMember.ForeignKey, tbForeignKey.Text); _groupMember.ForeignKey = tbForeignKey.Text; History.EvaluateChange(changes, "Foreign Guid", _groupMember.ForeignGuid.ToString(), tbForeignGuid.Text); _groupMember.ForeignGuid = tbForeignGuid.Text.AsType <Guid?>(); History.EvaluateChange(changes, "Foreign Id", _groupMember.ForeignId.ToString(), tbForeignId.Text); _groupMember.ForeignId = tbForeignId.Text.AsType <int?>(); if (rockContext.SaveChanges() > 0) { if (changes.Any()) { HistoryService.SaveChanges( rockContext, typeof(GroupMember), Rock.SystemGuid.Category.HISTORY_PERSON_GROUP_MEMBERSHIP.AsGuid(), _groupMember.Id, changes); } } } else if (contextEntity is Metric) { var metricService = new MetricService(rockContext); var _metric = metricService.Get(contextEntity.Id); _metric.ForeignKey = tbForeignKey.Text; _metric.ForeignGuid = tbForeignGuid.Text.AsType <Guid?>(); _metric.ForeignId = tbForeignId.Text.AsType <int?>(); rockContext.SaveChanges(); } else if (contextEntity is Location) { var locationService = new LocationService(rockContext); var _location = locationService.Get(contextEntity.Id); _location.ForeignKey = tbForeignKey.Text; _location.ForeignGuid = tbForeignGuid.Text.AsType <Guid?>(); _location.ForeignId = tbForeignId.Text.AsType <int?>(); rockContext.SaveChanges(); } else if (contextEntity is PrayerRequest) { var prayerRequestService = new PrayerRequestService(rockContext); var _request = prayerRequestService.Get(contextEntity.Id); _request.ForeignKey = tbForeignKey.Text; _request.ForeignGuid = tbForeignGuid.Text.AsType <Guid?>(); _request.ForeignId = tbForeignId.Text.AsType <int?>(); rockContext.SaveChanges(); } else if (contextEntity is ContentChannel) { var contentChannelService = new ContentChannelService(rockContext); var _channel = contentChannelService.Get(contextEntity.Id); _channel.ForeignKey = tbForeignKey.Text; _channel.ForeignGuid = tbForeignGuid.Text.AsType <Guid?>(); _channel.ForeignId = tbForeignId.Text.AsType <int?>(); rockContext.SaveChanges(); } else if (contextEntity is ContentChannelItem) { var contentChannelItemService = new ContentChannelItemService(rockContext); var _item = contentChannelItemService.Get(contextEntity.Id); _item.ForeignKey = tbForeignKey.Text; _item.ForeignGuid = tbForeignGuid.Text.AsType <Guid?>(); _item.ForeignId = tbForeignId.Text.AsType <int?>(); rockContext.SaveChanges(); } }); Page.Response.Redirect(Page.Request.Url.ToString(), true); }
public void ProcessRequest(HttpContext context) { request = context.Request; response = context.Response; RockContext rockContext = new RockContext(); if (request.HttpMethod != "GET") { response.Write("Invalid request type."); response.StatusCode = 200; return; } if (request.QueryString["ChannelId"] != null) { int channelId; int templateDefinedValueId; DefinedValueCache dvRssTemplate; string rssTemplate; if (!int.TryParse(request.QueryString["ChannelId"], out channelId)) { response.Write("Invalid channel id."); response.StatusCode = 200; return; } if (request.QueryString["TemplateId"] == null || !int.TryParse(request.QueryString["TemplateId"], out templateDefinedValueId)) { dvRssTemplate = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.DEFAULT_RSS_CHANNEL); } else { dvRssTemplate = DefinedValueCache.Read(templateDefinedValueId); } rssTemplate = dvRssTemplate.GetAttributeValue("Template"); if (request.QueryString["EnableDebug"] != null) { // when in debug mode we need to export as html and linkin styles so that the debug info will be displayed string appPath = HttpContext.Current.Request.ApplicationPath; response.Write("<html>"); response.Write("<head>"); response.Write(string.Format("<link rel='stylesheet' type='text/css' href='{0}Themes/Rock/Styles/bootstrap.css'>", appPath)); response.Write(string.Format("<link rel='stylesheet' type='text/css' href='{0}Themes/Rock/Styles/theme.css'>", appPath)); response.Write(string.Format("<script src='{0}Scripts/jquery-1.12.4.min.js'></script>", appPath)); response.Write(string.Format("<script src='{0}Scripts/bootstrap.min.js'></script>", appPath)); response.Write("</head>"); response.Write("<body style='padding: 24px;'>"); } else { if (string.IsNullOrWhiteSpace(dvRssTemplate.GetAttributeValue("MimeType"))) { response.ContentType = "application/rss+xml"; } else { response.ContentType = dvRssTemplate.GetAttributeValue("MimeType"); } } ContentChannelService channelService = new ContentChannelService(rockContext); var channel = channelService.Queryable("ContentChannelType").Where(c => c.Id == channelId).FirstOrDefault(); if (channel != null) { if (channel.EnableRss) { // load merge fields var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(null); mergeFields.Add("Channel", channel); Dictionary <string, object> requestObjects = new Dictionary <string, object>(); requestObjects.Add("Scheme", request.Url.Scheme); requestObjects.Add("Host", request.Url.Host); requestObjects.Add("Authority", request.Url.Authority); requestObjects.Add("LocalPath", request.Url.LocalPath); requestObjects.Add("AbsoluteUri", request.Url.AbsoluteUri); requestObjects.Add("AbsolutePath", request.Url.AbsolutePath); requestObjects.Add("Port", request.Url.Port); requestObjects.Add("Query", request.Url.Query); requestObjects.Add("OriginalString", request.Url.OriginalString); mergeFields.Add("Request", requestObjects); // check for new rss item limit if (request.QueryString["Count"] != null) { int.TryParse(request.QueryString["Count"], out rssItemLimit); } // get channel items ContentChannelItemService contentService = new ContentChannelItemService(rockContext); var content = contentService.Queryable("ContentChannelType") .Where(c => c.ContentChannelId == channel.Id && (c.Status == ContentChannelItemStatus.Approved || c.ContentChannel.RequiresApproval == false) && c.StartDateTime <= RockDateTime.Now); if (channel.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange) { if (channel.ContentChannelType.IncludeTime) { content = content.Where(c => c.ExpireDateTime >= RockDateTime.Now); } else { content = content.Where(c => c.ExpireDateTime > RockDateTime.Today); } } if (channel.ItemsManuallyOrdered) { content = content.OrderBy(c => c.Order); } else { content = content.OrderByDescending(c => c.StartDateTime); } content = content.Take(rssItemLimit); foreach (var item in content) { item.Content = item.Content.ResolveMergeFields(mergeFields); // resolve any relative links var globalAttributes = Rock.Web.Cache.GlobalAttributesCache.Read(); string publicAppRoot = globalAttributes.GetValue("PublicApplicationRoot").EnsureTrailingForwardslash(); item.Content = item.Content.Replace(@" src=""/", @" src=""" + publicAppRoot); item.Content = item.Content.Replace(@" href=""/", @" href=""" + publicAppRoot); // get item attributes and add them as elements to the feed item.LoadAttributes(rockContext); foreach (var attributeValue in item.AttributeValues) { attributeValue.Value.Value = attributeValue.Value.Value.ResolveMergeFields(mergeFields); } } mergeFields.Add("Items", content); mergeFields.Add("RockVersion", Rock.VersionInfo.VersionInfo.GetRockProductVersionNumber()); // show debug info if (request.QueryString["EnableDebug"] != null) { response.Write(mergeFields.lavaDebugInfo()); response.Write("<pre>"); response.Write(WebUtility.HtmlEncode(rssTemplate.ResolveMergeFields(mergeFields))); response.Write("</pre>"); response.Write("</body>"); response.Write("</html"); } else { response.Write(rssTemplate.ResolveMergeFields(mergeFields)); } } else { response.Write("RSS is not enabled for this channel."); response.StatusCode = 200; return; } } else { response.StatusCode = 200; response.Write("Invalid channel id."); response.StatusCode = 200; return; } } else { response.Write("A ChannelId is required."); response.StatusCode = 200; return; } }
/// <summary> /// Gets the data to display. /// </summary> private void GetData() { var rockContext = new RockContext(); var itemService = new ContentChannelItemService(rockContext); // Get all of the content channels var contentChannelsQry = new ContentChannelService(rockContext).Queryable("ContentChannelType").AsNoTracking(); List <Guid> contentChannelGuidsFilter = GetAttributeValue(AttributeKey.ContentChannelsFilter).SplitDelimitedValues().AsGuidList(); List <Guid> contentChannelTypeGuidsInclude = GetAttributeValue(AttributeKey.ContentChannelTypesInclude).SplitDelimitedValues().AsGuidList(); List <Guid> contentChannelTypeGuidsExclude = GetAttributeValue(AttributeKey.ContentChannelTypesExclude).SplitDelimitedValues().AsGuidList(); if (contentChannelGuidsFilter.Any()) { // if contentChannelGuidsFilter is specified, only get those content channels. // NOTE: This take precedence over all the other Include/Exclude settings. contentChannelsQry = contentChannelsQry.Where(a => contentChannelGuidsFilter.Contains(a.Guid)); } else if (contentChannelTypeGuidsInclude.Any()) { // if contentChannelTypeGuidsInclude is specified, only get contentChannelTypes that are in the contentChannelTypeGuidsInclude // NOTE: no need to factor in contentChannelTypeGuidsExclude since included would take precedence and the excluded ones would already not be included contentChannelsQry = contentChannelsQry.Where(a => contentChannelTypeGuidsInclude.Contains(a.ContentChannelType.Guid) || a.ContentChannelType.ShowInChannelList); } else if (contentChannelTypeGuidsExclude.Any()) { contentChannelsQry = contentChannelsQry.Where(a => !contentChannelTypeGuidsExclude.Contains(a.ContentChannelType.Guid) && a.ContentChannelType.ShowInChannelList); } else { contentChannelsQry = contentChannelsQry.Where(a => a.ContentChannelType.ShowInChannelList); } if (GetAttributeValue(AttributeKey.ShowCategoryFilter).AsBoolean()) { int?categoryId = null; var categoryGuid = PageParameter("CategoryGuid").AsGuidOrNull(); var selectedChannelGuid = PageParameter("ContentChannelGuid").AsGuidOrNull(); if (selectedChannelGuid.HasValue) { categoryId = CategoryCache.Get(categoryGuid.GetValueOrDefault())?.Id; } else { categoryId = ddlCategory.SelectedValueAsId(); } SetUserPreference(CATEGORY_FILTER_SETTING, categoryId.ToString()); ddlCategory.SetValue(categoryId); var parentCategoryGuid = GetAttributeValue(AttributeKey.ParentCategory).AsGuidOrNull(); if (ddlCategory.Visible && categoryId.HasValue) { contentChannelsQry = contentChannelsQry.Where(a => a.Categories.Any(c => c.Id == categoryId)); } else if (parentCategoryGuid.HasValue) { var parentCategoryId = CategoryCache.GetId(parentCategoryGuid.Value); contentChannelsQry = contentChannelsQry.Where(a => a.Categories.Any(c => c.ParentCategoryId == parentCategoryId)); } } var contentChannelsList = contentChannelsQry.OrderBy(w => w.Name).ToList(); // Create variable for storing authorized channels and the count of active items var channelCounts = new Dictionary <int, int>(); foreach (var channel in contentChannelsList) { if (channel.IsAuthorized(Authorization.VIEW, CurrentPerson)) { channelCounts.Add(channel.Id, 0); } } // Get the pending approval item counts for each channel (if the channel requires approval) itemService.Queryable() .Where(i => channelCounts.Keys.Contains(i.ContentChannelId) && i.Status == ContentChannelItemStatus.PendingApproval && i.ContentChannel.RequiresApproval) .GroupBy(i => i.ContentChannelId) .Select(i => new { Id = i.Key, Count = i.Count() }) .ToList() .ForEach(i => channelCounts[i.Id] = i.Count); // Create a query to return channel, the count of items, and the selected class var qry = contentChannelsList .Where(c => channelCounts.Keys.Contains(c.Id)) .Select(c => new { Channel = c, Count = channelCounts[c.Id], Class = (SelectedChannelId.HasValue && SelectedChannelId.Value == c.Id) ? "active" : "" }); // If displaying active only, update query to exclude those content channels without any items if (tglStatus.Checked) { qry = qry.Where(c => c.Count > 0); } var contentChannels = qry.ToList(); rptChannels.DataSource = contentChannels; rptChannels.DataBind(); ContentChannel selectedChannel = null; if (SelectedChannelId.HasValue) { selectedChannel = contentChannelsList .Where(w => w.Id == SelectedChannelId.Value && channelCounts.Keys.Contains(SelectedChannelId.Value)) .FirstOrDefault(); } if (selectedChannel != null && contentChannels.Count > 0) { // show the content item panel divItemPanel.Visible = true; BindAttributes(selectedChannel); AddDynamicControls(selectedChannel); bool isFiltered = false; var items = GetItems(rockContext, selectedChannel, out isFiltered); var reorderFieldColumn = gContentChannelItems.ColumnsOfType <ReorderField>().FirstOrDefault(); if (selectedChannel.ItemsManuallyOrdered && !isFiltered) { if (reorderFieldColumn != null) { reorderFieldColumn.Visible = true; } gContentChannelItems.AllowSorting = false; } else { if (reorderFieldColumn != null) { reorderFieldColumn.Visible = false; } gContentChannelItems.AllowSorting = true; SortProperty sortProperty = gContentChannelItems.SortProperty; if (sortProperty != null) { items = items.AsQueryable().Sort(sortProperty).ToList(); } else { items = items.OrderByDescending(p => p.StartDateTime).ToList(); } } // Find any possible tags for the items var itemTags = new Dictionary <Guid, string>(); if (selectedChannel.IsTaggingEnabled) { itemTags = items.ToDictionary(i => i.Guid, v => ""); var entityTypeId = EntityTypeCache.Get(Rock.SystemGuid.EntityType.CONTENT_CHANNEL_ITEM.AsGuid()).Id; var testedTags = new Dictionary <int, string>(); foreach (var taggedItem in new TaggedItemService(rockContext) .Queryable().AsNoTracking() .Where(i => i.EntityTypeId == entityTypeId && itemTags.Keys.Contains(i.EntityGuid)) .OrderBy(i => i.Tag.Name)) { if (!testedTags.ContainsKey(taggedItem.TagId)) { testedTags.Add(taggedItem.TagId, taggedItem.Tag.IsAuthorized(Authorization.VIEW, CurrentPerson) ? taggedItem.Tag.Name : string.Empty); } if (testedTags[taggedItem.TagId].IsNotNullOrWhiteSpace()) { itemTags[taggedItem.EntityGuid] += string.Format("<span class='tag'>{0}</span>", testedTags[taggedItem.TagId]); } } } gContentChannelItems.ObjectList = new Dictionary <string, object>(); items.ForEach(i => gContentChannelItems.ObjectList.Add(i.Id.ToString(), i)); var gridList = items.Select(i => new { i.Id, i.Guid, i.Title, i.StartDateTime, i.ExpireDateTime, i.Priority, Status = DisplayStatus(i.Status), DateStatus = DisplayDateStatus(i.StartDateTime), Tags = itemTags.GetValueOrNull(i.Guid), Occurrences = i.EventItemOccurrences.Any(), CreatedByPersonName = i.CreatedByPersonAlias != null ? String.Format("<a href={0}>{1}</a>", ResolveRockUrl(string.Format("~/Person/{0}", i.CreatedByPersonAlias.PersonId)), i.CreatedByPersonName) : String.Empty }).ToList(); // only show the Event Occurrences item if any of the displayed content channel items have any occurrences (and the block setting is enabled) var eventOccurrencesColumn = gContentChannelItems.ColumnsWithDataField("Occurrences").FirstOrDefault(); eventOccurrencesColumn.Visible = gridList.Any(a => a.Occurrences == true); gContentChannelItems.DataSource = gridList; gContentChannelItems.DataBind(); lContentChannelItems.Text = selectedChannel.Name + " Items"; } else { divItemPanel.Visible = false; } }
/// <summary> /// Shows the view. /// </summary> /// <param name="groupId">The group identifier.</param> /// <param name="groupMemberId">The group member identifier.</param> protected void ShowView(int groupId, int groupMemberId) { pnlView.Visible = true; pnlMain.Visible = true; pnlEditPreferences.Visible = false; hfGroupId.Value = groupId.ToString(); hfGroupMemberId.Value = groupMemberId.ToString(); var rockContext = new RockContext(); var group = new GroupService(rockContext).Get(groupId); if (group == null) { pnlView.Visible = false; return; } var groupMember = new GroupMemberService(rockContext).Queryable().Where(a => a.GroupId == groupId && a.Id == groupMemberId).FirstOrDefault(); if (groupMember == null) { pnlView.Visible = false; return; } group.LoadAttributes(rockContext); // set page title to the trip name RockPage.Title = group.GetAttributeValue("OpportunityTitle"); RockPage.BrowserTitle = group.GetAttributeValue("OpportunityTitle"); RockPage.Header.Title = group.GetAttributeValue("OpportunityTitle"); var mergeFields = LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson, new CommonMergeFieldsOptions { GetLegacyGlobalMergeFields = false }); mergeFields.Add("Group", group); groupMember.LoadAttributes(rockContext); mergeFields.Add("GroupMember", groupMember); // Left Top Sidebar var photoGuid = group.GetAttributeValue("OpportunityPhoto"); imgOpportunityPhoto.ImageUrl = string.Format("~/GetImage.ashx?Guid={0}", photoGuid); // Top Main string profileLavaTemplate = this.GetAttributeValue("ProfileLavaTemplate"); if (groupMember.PersonId == this.CurrentPersonId) { // show a warning about missing Photo or Intro if the current person is viewing their own profile var warningItems = new List <string>(); if (!groupMember.Person.PhotoId.HasValue) { warningItems.Add("photo"); } if (groupMember.GetAttributeValue("PersonalOpportunityIntroduction").IsNullOrWhiteSpace()) { warningItems.Add("personal opportunity introduction"); } nbProfileWarning.Text = "<stong>Tip!</strong> Edit your profile to add a " + warningItems.AsDelimited(", ", " and ") + "."; nbProfileWarning.Visible = warningItems.Any(); } else { nbProfileWarning.Visible = false; } btnEditProfile.Visible = groupMember.PersonId == this.CurrentPersonId; lMainTopContentHtml.Text = profileLavaTemplate.ResolveMergeFields(mergeFields); bool disablePublicContributionRequests = groupMember.GetAttributeValue("DisablePublicContributionRequests").AsBoolean(); // only show Contribution stuff if the current person is the participant and contribution requests haven't been disabled bool showContributions = !disablePublicContributionRequests && (groupMember.PersonId == this.CurrentPersonId); btnContributionsTab.Visible = showContributions; // Progress var entityTypeIdGroupMember = EntityTypeCache.GetId <Rock.Model.GroupMember>(); var contributionTotal = new FinancialTransactionDetailService(rockContext).Queryable() .Where(d => d.EntityTypeId == entityTypeIdGroupMember && d.EntityId == groupMemberId) .Sum(a => (decimal?)a.Amount) ?? 0.00M; var individualFundraisingGoal = groupMember.GetAttributeValue("IndividualFundraisingGoal").AsDecimalOrNull(); if (!individualFundraisingGoal.HasValue) { individualFundraisingGoal = group.GetAttributeValue("IndividualFundraisingGoal").AsDecimalOrNull(); } var amountLeft = individualFundraisingGoal - contributionTotal; var percentMet = individualFundraisingGoal > 0 ? contributionTotal * 100 / individualFundraisingGoal : 100; mergeFields.Add("AmountLeft", amountLeft); mergeFields.Add("PercentMet", percentMet); var queryParams = new Dictionary <string, string>(); queryParams.Add("GroupId", hfGroupId.Value); queryParams.Add("GroupMemberId", hfGroupMemberId.Value); mergeFields.Add("MakeDonationUrl", LinkedPageUrl("DonationPage", queryParams)); var opportunityType = DefinedValueCache.Get(group.GetAttributeValue("OpportunityType").AsGuid()); string makeDonationButtonText = null; if (groupMember.PersonId == this.CurrentPersonId) { makeDonationButtonText = "Make Payment"; } else { makeDonationButtonText = string.Format("Contribute to {0} {1}", RockFilters.Possessive(groupMember.Person.NickName), opportunityType); } mergeFields.Add("MakeDonationButtonText", makeDonationButtonText); var progressLavaTemplate = this.GetAttributeValue("ProgressLavaTemplate"); lProgressHtml.Text = progressLavaTemplate.ResolveMergeFields(mergeFields); // set text on the return button btnMainPage.Text = opportunityType.Value + " Page"; // Tab:Updates btnUpdatesTab.Visible = false; bool showContentChannelUpdates = false; var updatesContentChannelGuid = group.GetAttributeValue("UpdateContentChannel").AsGuidOrNull(); if (updatesContentChannelGuid.HasValue) { var contentChannel = new ContentChannelService(rockContext).Get(updatesContentChannelGuid.Value); if (contentChannel != null) { showContentChannelUpdates = true; // only show the UpdatesTab if there is another Tab option btnUpdatesTab.Visible = btnContributionsTab.Visible; string updatesLavaTemplate = this.GetAttributeValue("UpdatesLavaTemplate"); var contentChannelItems = new ContentChannelItemService(rockContext).Queryable().Where(a => a.ContentChannelId == contentChannel.Id).AsNoTracking().ToList(); mergeFields.Add("ContentChannelItems", contentChannelItems); lUpdatesContentItemsHtml.Text = updatesLavaTemplate.ResolveMergeFields(mergeFields); btnUpdatesTab.Text = string.Format("{0} Updates ({1})", opportunityType, contentChannelItems.Count()); } } if (showContentChannelUpdates) { SetActiveTab("Updates"); } else if (showContributions) { SetActiveTab("Contributions"); } else { SetActiveTab(""); } // Tab: Contributions BindContributionsGrid(); // Tab:Comments var noteType = NoteTypeCache.Get(this.GetAttributeValue("NoteType").AsGuid()); if (noteType != null) { notesCommentsTimeline.NoteOptions.SetNoteTypes(new List <NoteTypeCache> { noteType }); } notesCommentsTimeline.NoteOptions.EntityId = groupMember.Id; // show the Add button on comments for any logged in person notesCommentsTimeline.AddAllowed = true; var enableCommenting = group.GetAttributeValue("EnableCommenting").AsBoolean(); if (CurrentPerson == null) { notesCommentsTimeline.Visible = enableCommenting && (notesCommentsTimeline.NoteCount > 0); lNoLoginNoCommentsYet.Visible = notesCommentsTimeline.NoteCount == 0; pnlComments.Visible = enableCommenting; btnLoginToComment.Visible = enableCommenting; } else { lNoLoginNoCommentsYet.Visible = false; notesCommentsTimeline.Visible = enableCommenting; pnlComments.Visible = enableCommenting; btnLoginToComment.Visible = false; } // if btnContributionsTab is the only visible tab, hide the tab since there is nothing else to tab to if (!btnUpdatesTab.Visible && btnContributionsTab.Visible) { SetActiveTab("Contributions"); btnContributionsTab.Visible = false; } }
private List <ContentChannelItem> GetContent(List <string> errorMessages) { List <ContentChannelItem> items = null; // only load from the cache if a cacheDuration was specified if (ItemCacheDuration.HasValue && ItemCacheDuration.Value > 0) { items = GetCacheItem(CONTENT_CACHE_KEY) as List <ContentChannelItem>; } if (items == null) { Guid?channelGuid = GetAttributeValue("Channel").AsGuidOrNull(); if (channelGuid.HasValue) { var rockContext = new RockContext(); var service = new ContentChannelItemService(rockContext); var itemType = typeof(Rock.Model.ContentChannelItem); ParameterExpression paramExpression = service.ParameterExpression; var contentChannel = new ContentChannelService(rockContext).Get(channelGuid.Value); if (contentChannel != null) { var entityFields = HackEntityFields(contentChannel, rockContext); items = new List <ContentChannelItem>(); var qry = service .Queryable("ContentChannel,ContentChannelType") .Where(i => i.ContentChannelId == contentChannel.Id); if (contentChannel.RequiresApproval && !contentChannel.ContentChannelType.DisableStatus) { // Check for the configured status and limit query to those var statuses = new List <ContentChannelItemStatus>(); foreach (string statusVal in (GetAttributeValue("Status") ?? "2").Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) { var status = statusVal.ConvertToEnumOrNull <ContentChannelItemStatus>(); if (status != null) { statuses.Add(status.Value); } } if (statuses.Any()) { qry = qry.Where(i => statuses.Contains(i.Status)); } } int?dataFilterId = GetAttributeValue("FilterId").AsIntegerOrNull(); if (dataFilterId.HasValue) { var dataFilterService = new DataViewFilterService(rockContext); var dataFilter = dataFilterService.Queryable("ChildFilters").FirstOrDefault(a => a.Id == dataFilterId.Value); Expression whereExpression = dataFilter != null?dataFilter.GetExpression(itemType, service, paramExpression, errorMessages) : null; qry = qry.Where(paramExpression, whereExpression, null); } // All filtering has been added, now run query, check security and load attributes foreach (var item in qry.ToList()) { if (item.IsAuthorized(Authorization.VIEW, CurrentPerson)) { item.LoadAttributes(rockContext); items.Add(item); } } // Order the items SortProperty sortProperty = null; string orderBy = GetAttributeValue("Order"); if (!string.IsNullOrWhiteSpace(orderBy)) { var fieldDirection = new List <string>(); foreach (var itemPair in orderBy.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries).Select(a => a.Split('^'))) { if (itemPair.Length == 2 && !string.IsNullOrWhiteSpace(itemPair[0])) { var sortDirection = SortDirection.Ascending; if (!string.IsNullOrWhiteSpace(itemPair[1])) { sortDirection = itemPair[1].ConvertToEnum <SortDirection>(SortDirection.Ascending); } fieldDirection.Add(itemPair[0] + (sortDirection == SortDirection.Descending ? " desc" : "")); } } sortProperty = new SortProperty(); sortProperty.Direction = SortDirection.Ascending; sortProperty.Property = fieldDirection.AsDelimited(","); string[] columns = sortProperty.Property.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); var itemQry = items.AsQueryable(); IOrderedQueryable <ContentChannelItem> orderedQry = null; for (int columnIndex = 0; columnIndex < columns.Length; columnIndex++) { string column = columns[columnIndex].Trim(); var direction = sortProperty.Direction; if (column.ToLower().EndsWith(" desc")) { column = column.Left(column.Length - 5); direction = sortProperty.Direction == SortDirection.Ascending ? SortDirection.Descending : SortDirection.Ascending; } try { if (column.StartsWith("Attribute:")) { string attributeKey = column.Substring(10); if (direction == SortDirection.Ascending) { orderedQry = (columnIndex == 0) ? itemQry.OrderBy(i => i.AttributeValues.Where(v => v.Key == attributeKey).FirstOrDefault().Value.SortValue) : orderedQry.ThenBy(i => i.AttributeValues.Where(v => v.Key == attributeKey).FirstOrDefault().Value.SortValue); } else { orderedQry = (columnIndex == 0) ? itemQry.OrderByDescending(i => i.AttributeValues.Where(v => v.Key == attributeKey).FirstOrDefault().Value.SortValue) : orderedQry.ThenByDescending(i => i.AttributeValues.Where(v => v.Key == attributeKey).FirstOrDefault().Value.SortValue); } } else { if (direction == SortDirection.Ascending) { orderedQry = (columnIndex == 0) ? itemQry.OrderBy(column) : orderedQry.ThenBy(column); } else { orderedQry = (columnIndex == 0) ? itemQry.OrderByDescending(column) : orderedQry.ThenByDescending(column); } } } catch { } } try { if (orderedQry != null) { items = orderedQry.ToList(); } } catch { } } if (ItemCacheDuration.HasValue && ItemCacheDuration.Value > 0) { var cacheItemPolicy = new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(ItemCacheDuration.Value) }; AddCacheItem(CONTENT_CACHE_KEY, items, cacheItemPolicy); } } } } return(items); }
protected void lbPersonPaging_Click(object sender, EventArgs e) { var rockContext = new RockContext(); var personService = new PersonService(rockContext); var person = personService.Queryable().FirstOrDefault(a => a.Guid == personGuid); var attributeKey = GetAttributeValue("PersonAttributeKey"); var contentChannel = new ContentChannelService(rockContext).Get(GetAttributeValue("PersonPagingContentChannel").AsGuid()); var contentChannelItem = new ContentChannelItem { Title = string.Empty, Status = ContentChannelItemStatus.Approved, Content = string.Empty, ContentChannelId = contentChannel.Id, ContentChannelTypeId = contentChannel.ContentChannelTypeId, Priority = 0, StartDateTime = DateTime.Now, Order = 0, Guid = new Guid() }; contentChannelItem.LoadAttributes(); if (!contentChannelItem.Attributes.ContainsKey(attributeKey)) { nbWarning.Text = "The selected Content Channel is not configured with provided Attribute Key."; nbWarning.Visible = true; } else { var contentChannelItems = new ContentChannelItemService(rockContext).Queryable().AsNoTracking().Where(i => i.ContentChannelId.Equals(contentChannel.Id)).ToList(); var exists = false; foreach (var item in contentChannelItems) { item.LoadAttributes(); if (item.AttributeValues[attributeKey].Value.Equals(person.PrimaryAlias.Guid.ToString())) { exists = true; } } if (exists) { nbWarning.Text = string.Format("{0} is already on the list.", person.FullName); nbWarning.Visible = true; } else { contentChannelItem.AttributeValues[attributeKey].Value = person.PrimaryAlias.Guid.ToString(); rockContext.WrapTransaction(() => { rockContext.ContentChannelItems.Add(contentChannelItem); rockContext.SaveChanges(); contentChannelItem.SaveAttributeValues(rockContext); }); nbWarning.Text = string.Format("{0} added to the list.", person.FullName); nbWarning.Visible = true; } } }
/// <summary> /// Shows the edit. /// </summary> public void ShowEdit() { int?filterId = hfDataFilterId.Value.AsIntegerOrNull(); if (ChannelGuid.HasValue) { var rockContext = new RockContext(); var channel = new ContentChannelService(rockContext).Queryable("ContentChannelType") .FirstOrDefault(c => c.Guid.Equals(ChannelGuid.Value)); if (channel != null) { cblStatus.Visible = channel.RequiresApproval && !channel.ContentChannelType.DisableStatus; var filterService = new DataViewFilterService(rockContext); DataViewFilter filter = null; if (filterId.HasValue) { filter = filterService.Get(filterId.Value); } if (filter == null || filter.ExpressionType == FilterExpressionType.Filter) { filter = new DataViewFilter(); filter.Guid = new Guid(); filter.ExpressionType = FilterExpressionType.GroupAll; } CreateFilterControl(channel, filter, true, rockContext); kvlOrder.CustomKeys = new Dictionary <string, string>(); kvlOrder.CustomKeys.Add("", ""); kvlOrder.CustomKeys.Add("Title", "Title"); kvlOrder.CustomKeys.Add("Priority", "Priority"); kvlOrder.CustomKeys.Add("Status", "Status"); kvlOrder.CustomKeys.Add("StartDateTime", "Start"); kvlOrder.CustomKeys.Add("ExpireDateTime", "Expire"); kvlOrder.CustomKeys.Add("Order", "Order"); string currentMetaDescriptionAttribute = GetAttributeValue("MetaDescriptionAttribute") ?? string.Empty; string currentMetaImageAttribute = GetAttributeValue("MetaImageAttribute") ?? string.Empty; // add channel attributes channel.LoadAttributes(); foreach (var attribute in channel.Attributes) { var field = attribute.Value.FieldType.Field; string computedKey = "C^" + attribute.Key; } // add item attributes AttributeService attributeService = new AttributeService(rockContext); var itemAttributes = attributeService.GetByEntityTypeId(new ContentChannelItem().TypeId).AsQueryable() .Where(a => ( a.EntityTypeQualifierColumn.Equals("ContentChannelTypeId", StringComparison.OrdinalIgnoreCase) && a.EntityTypeQualifierValue.Equals(channel.ContentChannelTypeId.ToString()) ) || ( a.EntityTypeQualifierColumn.Equals("ContentChannelId", StringComparison.OrdinalIgnoreCase) && a.EntityTypeQualifierValue.Equals(channel.Id.ToString()) )) .OrderByDescending(a => a.EntityTypeQualifierColumn) .ThenBy(a => a.Order) .ToList(); foreach (var attribute in itemAttributes) { string attrKey = "Attribute:" + attribute.Key; if (!kvlOrder.CustomKeys.ContainsKey(attrKey)) { kvlOrder.CustomKeys.Add("Attribute:" + attribute.Key, attribute.Name); string computedKey = "I^" + attribute.Key; var field = attribute.FieldType.Name; } } } } }
/// <summary> /// Handles the Click event of the lbConfigure control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> private void lbConfigure_Click(object sender, EventArgs e) { pnlContentComponentConfig.Visible = true; mdContentComponentConfig.Show(); Guid? contentChannelGuid = this.GetAttributeValue("ContentChannel").AsGuidOrNull(); ContentChannel contentChannel = null; if (contentChannelGuid.HasValue) { contentChannel = new ContentChannelService(new RockContext()).Get(contentChannelGuid.Value); } if (contentChannel == null) { contentChannel = new ContentChannel { ContentChannelTypeId = this.ContentChannelTypeId }; } tbComponentName.Text = contentChannel.Name; contentChannel.LoadAttributes(); avcContentChannelAttributes.NumberOfColumns = 2; avcContentChannelAttributes.ValidationGroup = mdContentComponentConfig.ValidationGroup; avcContentChannelAttributes.AddEditControls(contentChannel); nbItemCacheDuration.Text = this.GetAttributeValue("ItemCacheDuration"); DefinedTypeCache contentComponentTemplateType = DefinedTypeCache.Get(Rock.SystemGuid.DefinedType.CONTENT_COMPONENT_TEMPLATE.AsGuid()); if (contentComponentTemplateType != null) { dvpContentComponentTemplate.DefinedTypeId = contentComponentTemplateType.Id; } DefinedValueCache contentComponentTemplate = null; var contentComponentTemplateValueGuid = this.GetAttributeValue("ContentComponentTemplate").AsGuidOrNull(); if (contentComponentTemplateValueGuid.HasValue) { contentComponentTemplate = DefinedValueCache.Get(contentComponentTemplateValueGuid.Value); } dvpContentComponentTemplate.SetValue(contentComponentTemplate); cbAllowMultipleContentItems.Checked = this.GetAttributeValue("AllowMultipleContentItems").AsBoolean(); nbOutputCacheDuration.Text = this.GetAttributeValue("OutputCacheDuration"); // Cache Tags cblCacheTags.DataSource = DefinedTypeCache.Get(Rock.SystemGuid.DefinedType.CACHE_TAGS.AsGuid()).DefinedValues.Select(v => v.Value).ToList(); cblCacheTags.DataBind(); cblCacheTags.Visible = cblCacheTags.Items.Count > 0; string[] selectedCacheTags = this.GetAttributeValue("CacheTags").SplitDelimitedValues(); foreach (ListItem cacheTag in cblCacheTags.Items) { cacheTag.Selected = selectedCacheTags.Contains(cacheTag.Value); } cePreHtml.Text = this.BlockCache.PreHtml; cePostHtml.Text = this.BlockCache.PostHtml; hfDataFilterId.Value = GetAttributeValue("FilterId"); int?filterId = hfDataFilterId.Value.AsIntegerOrNull(); var rockContext = new RockContext(); var filterService = new DataViewFilterService(rockContext); DataViewFilter filter = null; if (filterId.HasValue) { filter = filterService.Get(filterId.Value); } if (filter == null || filter.ExpressionType == FilterExpressionType.Filter) { filter = new DataViewFilter(); filter.Guid = new Guid(); filter.ExpressionType = FilterExpressionType.GroupAll; } CreateFilterControl(this.ContentChannelTypeId, filter, true, rockContext); }
/// <summary> /// Binds the grid. /// </summary> private void BindGrid() { ContentChannelService contentChannelService = new ContentChannelService(new RockContext()); SortProperty sortProperty = gContentChannels.SortProperty; var qry = contentChannelService.Queryable() .Include(a => a.ContentChannelType) .Include(a => a.Items) .Where(a => a.ContentChannelType.ShowInChannelList == true); int?typeId = gfFilter.GetUserPreference(UserPreferenceKey.Type).AsIntegerOrNull(); if (typeId.HasValue) { qry = qry.Where(c => c.ContentChannelTypeId == typeId.Value); } var selectedCategoryIds = new List <int>(); gfFilter.GetUserPreference(UserPreferenceKey.Categories).SplitDelimitedValues().ToList().ForEach(s => selectedCategoryIds.Add(int.Parse(s))); if (selectedCategoryIds.Any()) { qry = qry.Where(a => a.Categories.Any(c => selectedCategoryIds.Contains(c.Id))); } gContentChannels.ObjectList = new Dictionary <string, object>(); var channels = new List <ContentChannel>(); foreach (var channel in qry.ToList()) { if (channel.IsAuthorized(Rock.Security.Authorization.VIEW, CurrentPerson)) { channels.Add(channel); gContentChannels.ObjectList.Add(channel.Id.ToString(), channel); } } var now = RockDateTime.Now; var items = channels.Select(c => new { c.Id, c.Name, ContentChannelType = c.ContentChannelType.Name, c.EnableRss, c.ChannelUrl, ItemLastCreated = c.Items.Max(i => i.CreatedDateTime), TotalItems = c.Items.Count(), ActiveItems = c.Items .Where(i => (i.StartDateTime.CompareTo(now) < 0) && (!i.ExpireDateTime.HasValue || i.ExpireDateTime.Value.CompareTo(now) > 0) && (i.ApprovedByPersonAliasId.HasValue || !c.RequiresApproval) ).Count() }).AsQueryable(); gContentChannels.EntityTypeId = EntityTypeCache.Get <ContentChannel>().Id; if (sortProperty != null) { gContentChannels.DataSource = items.Sort(sortProperty).ToList(); } else { gContentChannels.DataSource = items.OrderBy(p => p.Name).ToList(); } gContentChannels.DataBind(); }
/// <summary> /// Handles the SaveClick event of the mdContentComponentConfig control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void mdContentComponentConfig_SaveClick(object sender, EventArgs e) { var rockContext = new RockContext(); var dataViewFilter = ReportingHelper.GetFilterFromControls(phFilters); if (dataViewFilter != null) { // update Guids since we are creating a new dataFilter and children and deleting the old one SetNewDataFilterGuids(dataViewFilter); if (!Page.IsValid) { return; } if (!dataViewFilter.IsValid) { // Controls will render the error messages return; } DataViewFilterService dataViewFilterService = new DataViewFilterService(rockContext); int?dataViewFilterId = hfDataFilterId.Value.AsIntegerOrNull(); if (dataViewFilterId.HasValue) { var oldDataViewFilter = dataViewFilterService.Get(dataViewFilterId.Value); DeleteDataViewFilter(oldDataViewFilter, dataViewFilterService); } dataViewFilterService.Add(dataViewFilter); } rockContext.SaveChanges(); ContentChannelService contentChannelService = new ContentChannelService(rockContext); Guid? contentChannelGuid = this.GetAttributeValue("ContentChannel").AsGuidOrNull(); ContentChannel contentChannel = null; if (contentChannelGuid.HasValue) { contentChannel = contentChannelService.Get(contentChannelGuid.Value); } if (contentChannel == null) { contentChannel = new ContentChannel(); contentChannel.ContentChannelTypeId = this.ContentChannelTypeId; contentChannelService.Add(contentChannel); } contentChannel.LoadAttributes(rockContext); avcContentChannelAttributes.GetEditValues(contentChannel); contentChannel.Name = tbComponentName.Text; rockContext.SaveChanges(); contentChannel.SaveAttributeValues(rockContext); this.SetAttributeValue("ContentChannel", contentChannel.Guid.ToString()); this.SetAttributeValue("ItemCacheDuration", nbItemCacheDuration.Text); int? contentComponentTemplateValueId = dvpContentComponentTemplate.SelectedValue.AsInteger(); Guid?contentComponentTemplateValueGuid = null; if (contentComponentTemplateValueId.HasValue) { var contentComponentTemplate = DefinedValueCache.Get(contentComponentTemplateValueId.Value); if (contentComponentTemplate != null) { contentComponentTemplateValueGuid = contentComponentTemplate.Guid; } } this.SetAttributeValue("ContentComponentTemplate", contentComponentTemplateValueGuid.ToString()); this.SetAttributeValue("AllowMultipleContentItems", cbAllowMultipleContentItems.Checked.ToString()); this.SetAttributeValue("OutputCacheDuration", nbOutputCacheDuration.Text); this.SetAttributeValue("CacheTags", cblCacheTags.SelectedValues.AsDelimited(",")); if (dataViewFilter != null) { this.SetAttributeValue("FilterId", dataViewFilter.Id.ToString()); } else { this.SetAttributeValue("FilterId", null); } this.SaveAttributeValues(); var block = new BlockService(rockContext).Get(this.BlockId); block.PreHtml = cePreHtml.Text; block.PostHtml = cePostHtml.Text; rockContext.SaveChanges(); mdContentComponentConfig.Hide(); pnlContentComponentConfig.Visible = false; RemoveCacheItem(OUTPUT_CACHE_KEY); RemoveCacheItem(ITEM_CACHE_KEY); // reload the page to make sure we have a clean load NavigateToCurrentPageReference(); }
/// <summary> /// Updates the social media dropdowns. /// </summary> /// <param name="channelGuid">The channel unique identifier.</param> private void UpdateSocialMediaDropdowns(Guid?channelGuid) { List <AttributeCache> channelAttributes = new List <AttributeCache>(); List <AttributeCache> itemAttributes = new List <AttributeCache>(); if (channelGuid.HasValue) { var rockContext = new RockContext(); var channel = new ContentChannelService(rockContext).GetNoTracking(channelGuid.Value); // add channel attributes channel.LoadAttributes(); channelAttributes = channel.Attributes.Select(a => a.Value).ToList(); // add item attributes AttributeService attributeService = new AttributeService(rockContext); itemAttributes = attributeService.GetByEntityTypeId(new ContentChannelItem().TypeId, false).AsQueryable() .Where(a => ( a.EntityTypeQualifierColumn.Equals("ContentChannelTypeId", StringComparison.OrdinalIgnoreCase) && a.EntityTypeQualifierValue.Equals(channel.ContentChannelTypeId.ToString()) ) || ( a.EntityTypeQualifierColumn.Equals("ContentChannelId", StringComparison.OrdinalIgnoreCase) && a.EntityTypeQualifierValue.Equals(channel.Id.ToString()) )) .OrderByDescending(a => a.EntityTypeQualifierColumn) .ThenBy(a => a.Order) .ToAttributeCacheList(); } RockDropDownList[] attributeDropDowns = new RockDropDownList[] { ddlMetaDescriptionAttribute, ddlOpenGraphTitleAttribute, ddlOpenGraphDescriptionAttribute, ddlOpenGraphImageAttribute, ddlTwitterTitleAttribute, ddlTwitterDescriptionAttribute, ddlTwitterImageAttribute, ddlMetaDescriptionAttribute }; RockDropDownList[] attributeDropDownsImage = new RockDropDownList[] { ddlOpenGraphImageAttribute, ddlTwitterImageAttribute, }; foreach (var attributeDropDown in attributeDropDowns) { attributeDropDown.Items.Clear(); attributeDropDown.Items.Add(new ListItem()); foreach (var attribute in channelAttributes) { string computedKey = "C^" + attribute.Key; if (attributeDropDownsImage.Contains(attributeDropDown)) { if (attribute.FieldType.Name == "Image") { attributeDropDown.Items.Add(new ListItem("Channel: " + attribute.Name, computedKey)); } } else { attributeDropDown.Items.Add(new ListItem("Channel: " + attribute.Name, computedKey)); } } // get all the possible Item attributes for items in this Content Channel and add those as options too foreach (var attribute in itemAttributes.DistinctBy(a => a.Key).ToList()) { string computedKey = "I^" + attribute.Key; if (attributeDropDownsImage.Contains(attributeDropDown)) { if (attribute.FieldType.Name == "Image") { attributeDropDown.Items.Add(new ListItem("Item: " + attribute.Name, computedKey)); } } else { attributeDropDown.Items.Add(new ListItem("Item: " + attribute.Name, computedKey)); } } } }
/// <summary> /// Shows the view. /// </summary> /// <param name="groupId">The group identifier.</param> protected void ShowView(int groupId) { pnlView.Visible = true; hfGroupId.Value = groupId.ToString(); var rockContext = new RockContext(); var group = new GroupService(rockContext).Get(groupId); if (group == null) { pnlView.Visible = false; return; } group.LoadAttributes(rockContext); var opportunityType = DefinedValueCache.Get(group.GetAttributeValue("OpportunityType").AsGuid()); if (this.GetAttributeValue("SetPageTitletoOpportunityTitle").AsBoolean()) { RockPage.Title = group.GetAttributeValue("OpportunityTitle"); RockPage.BrowserTitle = group.GetAttributeValue("OpportunityTitle"); RockPage.Header.Title = group.GetAttributeValue("OpportunityTitle"); } var mergeFields = LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson, new CommonMergeFieldsOptions { GetLegacyGlobalMergeFields = false }); mergeFields.Add("Block", this.BlockCache); mergeFields.Add("Group", group); // Left Sidebar var photoGuid = group.GetAttributeValue("OpportunityPhoto").AsGuidOrNull(); imgOpportunityPhoto.Visible = photoGuid.HasValue; imgOpportunityPhoto.ImageUrl = string.Format("~/GetImage.ashx?Guid={0}", photoGuid); var groupMembers = group.Members.ToList(); foreach (var gm in groupMembers) { gm.LoadAttributes(rockContext); } // only show the 'Donate to a Participant' button if there are participants that are taking contribution requests btnDonateToParticipant.Visible = groupMembers.Where(a => !a.GetAttributeValue("DisablePublicContributionRequests").AsBoolean()).Any(); if (!string.IsNullOrWhiteSpace(opportunityType.GetAttributeValue("core_DonateButtonText"))) { btnDonateToParticipant.Text = opportunityType.GetAttributeValue("core_DonateButtonText"); } RegistrationInstance registrationInstance = null; var registrationInstanceId = group.GetAttributeValue("RegistrationInstance").AsIntegerOrNull(); if (registrationInstanceId.HasValue) { registrationInstance = new RegistrationInstanceService(rockContext).Get(registrationInstanceId.Value); } mergeFields.Add("RegistrationPage", LinkedPageRoute("RegistrationPage")); if (registrationInstance != null) { mergeFields.Add("RegistrationInstance", registrationInstance); mergeFields.Add("RegistrationInstanceLinkages", registrationInstance.Linkages); // populate merge fields for Registration Counts var maxRegistrantCount = 0; var currentRegistrationCount = 0; if (registrationInstance.MaxAttendees != 0) { maxRegistrantCount = registrationInstance.MaxAttendees; } currentRegistrationCount = new RegistrationRegistrantService(rockContext).Queryable().AsNoTracking() .Where(r => r.Registration.RegistrationInstanceId == registrationInstance.Id && r.OnWaitList == false) .Count(); mergeFields.Add("CurrentRegistrationCount", currentRegistrationCount); if (maxRegistrantCount != 0) { mergeFields.Add("MaxRegistrantCount", maxRegistrantCount); mergeFields.Add("RegistrationSpotsAvailable", maxRegistrantCount - currentRegistrationCount); } } string sidebarLavaTemplate = this.GetAttributeValue("SidebarLavaTemplate"); lSidebarHtml.Text = sidebarLavaTemplate.ResolveMergeFields(mergeFields); SetActiveTab("Details"); // Top Main string summaryLavaTemplate = this.GetAttributeValue("SummaryLavaTemplate"); lMainTopContentHtml.Text = summaryLavaTemplate.ResolveMergeFields(mergeFields); // only show the leader toolbox link of the currentperson has a leader role in the group btnLeaderToolbox.Visible = group.Members.Any(a => a.PersonId == this.CurrentPersonId && a.GroupRole.IsLeader); //// Participant Actions // only show if the current person is a group member var groupMember = group.Members.FirstOrDefault(a => a.PersonId == this.CurrentPersonId); if (groupMember != null) { hfGroupMemberId.Value = groupMember.Id.ToString(); pnlParticipantActions.Visible = true; } else { hfGroupMemberId.Value = null; pnlParticipantActions.Visible = false; } mergeFields.Add("GroupMember", groupMember); // Progress if (groupMember != null && pnlParticipantActions.Visible) { var entityTypeIdGroupMember = EntityTypeCache.GetId <Rock.Model.GroupMember>(); var contributionTotal = new FinancialTransactionDetailService(rockContext).Queryable() .Where(d => d.EntityTypeId == entityTypeIdGroupMember && d.EntityId == groupMember.Id) .Sum(a => (decimal?)a.Amount) ?? 0.00M; var individualFundraisingGoal = groupMember.GetAttributeValue("IndividualFundraisingGoal").AsDecimalOrNull(); if (!individualFundraisingGoal.HasValue) { individualFundraisingGoal = group.GetAttributeValue("IndividualFundraisingGoal").AsDecimalOrNull(); } var amountLeft = individualFundraisingGoal - contributionTotal; var percentMet = individualFundraisingGoal > 0 ? contributionTotal * 100 / individualFundraisingGoal : 100; mergeFields.Add("AmountLeft", amountLeft); mergeFields.Add("PercentMet", percentMet); var queryParams = new Dictionary <string, string>(); queryParams.Add("GroupId", hfGroupId.Value); queryParams.Add("GroupMemberId", hfGroupMemberId.Value); mergeFields.Add("MakeDonationUrl", LinkedPageUrl("DonationPage", queryParams)); mergeFields.Add("ParticipantPageUrl", LinkedPageUrl("ParticipantPage", queryParams)); string makeDonationButtonText = null; if (groupMember.PersonId == this.CurrentPersonId) { makeDonationButtonText = "Make Payment"; } else { makeDonationButtonText = string.Format("Contribute to {0} {1}", RockFilters.Possessive(groupMember.Person.NickName), opportunityType); } mergeFields.Add("MakeDonationButtonText", makeDonationButtonText); var participantLavaTemplate = this.GetAttributeValue("ParticipantLavaTemplate"); lParticipantActionsHtml.Text = participantLavaTemplate.ResolveMergeFields(mergeFields); } // Tab:Details lDetailsHtml.Text = group.GetAttributeValue("OpportunityDetails"); btnDetailsTab.Text = string.Format("{0} Details", opportunityType); // Tab:Updates liUpdatesTab.Visible = false; var updatesContentChannelGuid = group.GetAttributeValue("UpdateContentChannel").AsGuidOrNull(); if (updatesContentChannelGuid.HasValue) { var contentChannel = new ContentChannelService(rockContext).Get(updatesContentChannelGuid.Value); if (contentChannel != null) { liUpdatesTab.Visible = true; string updatesLavaTemplate = this.GetAttributeValue("UpdatesLavaTemplate"); var contentChannelItems = new ContentChannelItemService(rockContext).Queryable().Where(a => a.ContentChannelId == contentChannel.Id).AsNoTracking().ToList(); mergeFields.Add("ContentChannelItems", contentChannelItems); lUpdatesContentItemsHtml.Text = updatesLavaTemplate.ResolveMergeFields(mergeFields); btnUpdatesTab.Text = string.Format("{0} Updates ({1})", opportunityType, contentChannelItems.Count()); } } // Tab:Comments var noteType = NoteTypeCache.Get(this.GetAttributeValue("NoteType").AsGuid()); if (noteType != null) { notesCommentsTimeline.NoteOptions.SetNoteTypes(new List <NoteTypeCache> { noteType }); } notesCommentsTimeline.NoteOptions.EntityId = groupId; // show the Add button on comments for any logged in person notesCommentsTimeline.AddAllowed = true; var enableCommenting = group.GetAttributeValue("EnableCommenting").AsBoolean(); btnCommentsTab.Text = string.Format("Comments ({0})", notesCommentsTimeline.NoteCount); if (CurrentPerson == null) { notesCommentsTimeline.Visible = enableCommenting && (notesCommentsTimeline.NoteCount > 0); lNoLoginNoCommentsYet.Visible = notesCommentsTimeline.NoteCount == 0; liCommentsTab.Visible = enableCommenting; btnLoginToComment.Visible = enableCommenting; } else { lNoLoginNoCommentsYet.Visible = false; notesCommentsTimeline.Visible = enableCommenting; liCommentsTab.Visible = enableCommenting; btnLoginToComment.Visible = false; } // if btnDetailsTab is the only visible tab, hide the tab since there is nothing else to tab to if (!liCommentsTab.Visible && !liUpdatesTab.Visible) { tlTabList.Visible = false; } }
/// <summary> /// Raises the <see cref="E:System.Web.UI.Control.Init" /> event. /// </summary> /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param> protected override void OnInit(EventArgs e) { base.OnInit(e); // set person context var contextEntity = this.ContextEntity(); if (contextEntity != null) { if (contextEntity is Person) { _person = contextEntity as Person; } } // set person if grid should be filtered by the current person if (GetAttributeValue(AttributeKey.FilterItemsForCurrentUser).AsBoolean()) { _person = CurrentPerson; } gfFilter.Visible = GetAttributeValue(AttributeKey.ShowFilters).AsBoolean(); if (string.IsNullOrWhiteSpace(GetAttributeValue(AttributeKey.ContentChannel))) { _channelId = PageParameter(PageParameterKey.ContentChannelId).AsIntegerOrNull(); } else { _channelId = new ContentChannelService(new RockContext()).Get(GetAttributeValue(AttributeKey.ContentChannel).AsGuid()).Id; } if (_channelId != null) { upnlContent.Visible = true; string cssIcon = "fa fa-bullhorn"; var contentChannel = new ContentChannelService(new RockContext()).Get(_channelId.Value); if (contentChannel != null) { string startHeading = contentChannel.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange ? "Start" : "Active"; _manuallyOrdered = contentChannel.ItemsManuallyOrdered; var startDateTimeColumn = gItems.ColumnsWithDataField("StartDateTime").OfType <DateTimeField>().FirstOrDefault(); var expireDateTimeColumn = gItems.ColumnsWithDataField("ExpireDateTime").OfType <DateTimeField>().FirstOrDefault(); var startDateColumn = gItems.ColumnsWithDataField("StartDateTime").OfType <DateField>().FirstOrDefault(); var expireDateColumn = gItems.ColumnsWithDataField("ExpireDateTime").OfType <DateField>().FirstOrDefault(); var priorityColumn = gItems.ColumnsWithDataField("Priority").FirstOrDefault(); //// NOTE: The EventOccurrences Column's visibility is set in GridBind() startDateTimeColumn.HeaderText = startHeading; startDateColumn.HeaderText = startHeading; ddlStatus.Visible = contentChannel.RequiresApproval && !contentChannel.ContentChannelType.DisableStatus; if (contentChannel.ContentChannelType.IncludeTime) { startDateTimeColumn.Visible = contentChannel.ContentChannelType.DateRangeType != ContentChannelDateType.NoDates; expireDateTimeColumn.Visible = contentChannel.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange && GetAttributeValue(AttributeKey.ShowExpireColumn).AsBoolean(); startDateColumn.Visible = false; expireDateColumn.Visible = false; } else { startDateTimeColumn.Visible = false; expireDateTimeColumn.Visible = false; startDateColumn.Visible = contentChannel.ContentChannelType.DateRangeType != ContentChannelDateType.NoDates; expireDateColumn.Visible = contentChannel.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange && GetAttributeValue(AttributeKey.ShowExpireColumn).AsBoolean(); } priorityColumn.Visible = !contentChannel.ContentChannelType.DisablePriority && GetAttributeValue(AttributeKey.ShowPriorityColumn).AsBoolean(); lContentChannel.Text = contentChannel.Name; _typeId = contentChannel.ContentChannelTypeId; if (!string.IsNullOrWhiteSpace(contentChannel.IconCssClass)) { cssIcon = contentChannel.IconCssClass; } } lIcon.Text = string.Format("<i class='{0}'></i>", cssIcon); // Block Security and special attributes (RockPage takes care of View) bool canAddEditDelete = IsUserAuthorized(Authorization.EDIT); gfFilter.ApplyFilterClick += gfFilter_ApplyFilterClick; gfFilter.DisplayFilterValue += gfFilter_DisplayFilterValue; gItems.DataKeyNames = new string[] { "Id" }; gItems.AllowSorting = !_manuallyOrdered; gItems.Actions.ShowAdd = canAddEditDelete; gItems.IsDeleteEnabled = canAddEditDelete; gItems.Actions.AddClick += gItems_Add; gItems.GridRebind += gItems_GridRebind; gItems.GridReorder += GItems_GridReorder; gItems.EntityTypeId = EntityTypeCache.Get <ContentChannelItem>().Id; AddAttributeColumns(); if (contentChannel != null && contentChannel.RequiresApproval && !contentChannel.ContentChannelType.DisableStatus) { var statusField = new BoundField(); gItems.Columns.Add(statusField); statusField.DataField = "Status"; statusField.HeaderText = "Status"; statusField.SortExpression = "Status"; statusField.HtmlEncode = false; } var securityField = new SecurityField(); gItems.Columns.Add(securityField); securityField.TitleField = "Title"; securityField.EntityTypeId = EntityTypeCache.Get(typeof(Rock.Model.ContentChannelItem)).Id; var securityColumn = gItems.Columns.OfType <SecurityField>().FirstOrDefault(); if (securityColumn != null) { securityColumn.Visible = GetAttributeValue(AttributeKey.ShowSecurityColumn).AsBoolean(); } var deleteField = new DeleteField(); gItems.Columns.Add(deleteField); deleteField.Click += gItems_Delete; // this event gets fired after block settings are updated. it's nice to repaint the screen if these settings would alter it this.BlockUpdated += Block_BlockUpdated; this.AddConfigurationUpdateTrigger(upnlContent); } else { upnlContent.Visible = false; } }