/// <summary> /// Gets the category identifier. /// </summary> /// <returns>System.Nullable<System.Int32>.</returns> private int?GetCategoryId() { var categoryGuidBlockAttribute = this.GetAttributeValue(AttributeKey.Category).AsGuidOrNull(); if (categoryGuidBlockAttribute.HasValue) { return(CategoryCache.GetId(categoryGuidBlockAttribute.Value)); } else { return(gfSettings.GetUserPreference("Category").AsIntegerOrNull()); } }
private void SetKiosk(string clientName) { var rockContext = new RockContext(); var kioskService = new KioskService(rockContext); var kiosk = kioskService.GetByClientName(clientName); if (kiosk == null) { kiosk = new Kiosk(); kiosk.Name = clientName; kiosk.Description = "Automatically created Kiosk"; kioskService.Add(kiosk); } kiosk.CategoryId = CategoryCache.GetId(Constants.KIOSK_CATEGORY_STATION.AsGuid()); rockContext.SaveChanges(); GetKioskType(kiosk, rockContext); }
/// <summary> /// Shows the attendees. /// </summary> private void ShowAttendees() { pnlSearchResults.Visible = true; using (var rockContext = new RockContext()) { var attendees = GetAttendees(rockContext); var attendeesSorted = attendees.OrderByDescending(a => a.MeetsRosterStatusFilter(RosterStatusFilter.Present)).ThenByDescending(a => a.CheckInTime).ThenBy(a => a.PersonGuid).ToList(); var checkInRosterAlertIconCategoryGuid = this.GetAttributeValue(AttributeKey.CheckInRosterAlertIconCategory)?.AsGuid(); if (checkInRosterAlertIconCategoryGuid.HasValue) { var categoryId = CategoryCache.GetId(checkInRosterAlertIconCategoryGuid.Value) ?? 0; _attributesForAlertIcons = new AttributeService(rockContext).GetByCategoryId(categoryId).ToAttributeCacheList(); } else { _attributesForAlertIcons = new List <AttributeCache>(); } gAttendees.DataSource = attendeesSorted; gAttendees.DataBind(); } }
public void SendPrayerComments_FilterWithChildCategoriesExcluded_ReturnsRequestsInParentCategoryOnly() { VerifyTestPreconditionsOrThrow(); var dataContext = new RockContext(); var job = GetJobWithDefaultConfiguration(); job.CategoryGuidList = new List <Guid> { TestGuids.Category.PrayerRequestFinancesAndJob.AsGuid() }; job.IncludeChildCategories = false; job.CreateCommunicationRecord = false; job.LoadPrayerRequests(); // Verify at least one known prayer request in the parent category is returned. var parentCategoryId = CategoryCache.GetId(TestGuids.Category.PrayerRequestFinancesAndJob.AsGuid()).GetValueOrDefault(); Assert.IsTrue(job.PrayerRequests.Any(x => x.CategoryId == parentCategoryId), "Expected Prayer Request not found in parent category."); // Verify no requests are returned outside of the parent category. Assert.IsFalse(job.PrayerRequests.Any(x => x.CategoryId != parentCategoryId), "Unexpected Prayer Request found."); }
/// <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; } }
public void GroupsModule_AddDataViews() { var dataContext = new RockContext(); // Add Data View Category "Groups". const string categoryDataViewName = "Groups"; Debug.Print($"Adding Data View Category \"{ categoryDataViewName }\"..."); var entityTypeId = EntityTypeCache.Get(typeof(global::Rock.Model.DataView)).Id; var coreHelper = new CoreModuleTestHelper(_SampleDataForeignKey); var locationsCategory = coreHelper.CreateCategory(categoryDataViewName, Constants.CategoryLocationsGuid, entityTypeId); coreHelper.AddOrUpdateCategory(dataContext, locationsCategory); dataContext.SaveChanges(); // Get Data View service. var service = new DataViewService(dataContext); int categoryId = CategoryCache.GetId(Constants.CategoryLocationsGuid) ?? 0; DataViewFilter rootFilter; // Create Data View: Locations Inside Arizona const string dataViewLocationsInsideArizona = "Locations in the state of Arizona"; Debug.Print($"Adding Data View \"{ dataViewLocationsInsideArizona }\"..."); var dataViewInside = new DataView(); dataViewInside.IsSystem = false; dataViewInside.Name = dataViewLocationsInsideArizona; dataViewInside.Description = "Locations that are within the state of Arizona."; dataViewInside.EntityTypeId = EntityTypeCache.GetId(typeof(global::Rock.Model.Location)); dataViewInside.CategoryId = categoryId; dataViewInside.Guid = Constants.DataViewLocationsInsideArizonaGuid; dataViewInside.ForeignKey = _SampleDataForeignKey; rootFilter = new DataViewFilter(); rootFilter.ExpressionType = FilterExpressionType.GroupAll; dataViewInside.DataViewFilter = rootFilter; var inStateFilter = new TextPropertyFilterSettings { PropertyName = "State", Comparison = ComparisonType.EqualTo, Value = "AZ" }; rootFilter.ChildFilters.Add(inStateFilter.GetFilter()); service.Add(dataViewInside); dataContext.SaveChanges(); // Create Data View: Locations Outside Arizona const string dataViewLocationsOutsideArizona = "Locations outside Arizona"; Debug.Print($"Adding Data View \"{ dataViewLocationsOutsideArizona }\"..."); var dataViewOutside = new DataView(); dataViewOutside.IsSystem = false; dataViewOutside.Name = dataViewLocationsOutsideArizona; dataViewOutside.Description = "Locations that are not within the state of Arizona."; dataViewOutside.EntityTypeId = EntityTypeCache.GetId(typeof(global::Rock.Model.Location)); dataViewOutside.CategoryId = categoryId; dataViewOutside.Guid = Constants.DataViewLocationsOutsideArizonaGuid; dataViewOutside.ForeignKey = _SampleDataForeignKey; rootFilter = new DataViewFilter(); rootFilter.ExpressionType = FilterExpressionType.GroupAll; dataViewOutside.DataViewFilter = rootFilter; var notInStateFilter = new TextPropertyFilterSettings { PropertyName = "State", Comparison = ComparisonType.NotEqualTo, Value = "AZ" }; rootFilter.ChildFilters.Add(notInStateFilter.GetFilter()); service.Add(dataViewOutside); dataContext.SaveChanges(); }
public void AddStepDataViews() { var dataContext = new RockContext(); // Add Data View Category "Steps". const string categoryDataViewStepsName = "Steps"; Debug.Print($"Adding Data View Category \"{ categoryDataViewStepsName }\"..."); var entityTypeId = EntityTypeCache.Get(typeof(Rock.Model.DataView)).Id; var stepsCategory = CreateCategory(categoryDataViewStepsName, Constants.CategoryStepsGuid, entityTypeId); AddOrUpdateCategory(dataContext, stepsCategory); dataContext.SaveChanges(); // Create Data View: Steps Completed const string dataViewStepsCompleted2001Name = "Steps Completed in 2001"; Debug.Print($"Adding Data View \"{ dataViewStepsCompleted2001Name }\"..."); DataView dataView = new DataView(); dataView.IsSystem = false; var service = new DataViewService(dataContext); int categoryId = CategoryCache.GetId(Constants.CategoryStepsGuid) ?? 0; dataView.Name = dataViewStepsCompleted2001Name; dataView.Description = "Steps that have a completion in the year 2001."; dataView.EntityTypeId = EntityTypeCache.GetId(typeof(Rock.Model.Step)); dataView.CategoryId = categoryId; dataView.Guid = Constants.DataViewStepsCompleted2001Guid; dataView.ForeignKey = _SampleDataForeignKey; var rootFilter = new DataViewFilter(); rootFilter.ExpressionType = FilterExpressionType.GroupAll; dataView.DataViewFilter = rootFilter; // Add filter for Step Type var dateCompletedFilter = new DataViewFilter(); dateCompletedFilter.ExpressionType = FilterExpressionType.Filter; dateCompletedFilter.EntityTypeId = EntityTypeCache.GetId(typeof(Rock.Reporting.DataFilter.PropertyFilter)); var dateFilterSettings = new List <string> { "Property_CompletedDateTime", "4096", "\tDateRange|||1/01/2001 12:00:00 AM|31/12/2001 12:00:00 AM" }; dateCompletedFilter.Selection = dateFilterSettings.ToJson(); rootFilter.ChildFilters.Add(dateCompletedFilter); service.Add(dataView); dataContext.SaveChanges(); }
/// <summary> /// Saves the <see cref="MetricValue"/>s and updates the <see cref="IJobExecutionContext"/>'s Result property. /// </summary> /// <param name="context">The <see cref="IJobExecutionContext"/>.</param> /// <exception cref="Exception">Unable to find the "Hosting Metrics" Category ID.</exception> private void SaveMetricValues(IJobExecutionContext context) { var rockContext = new RockContext(); rockContext.Database.CommandTimeout = _commandTimeout; var hostingMetricsCategoryId = CategoryCache.GetId(SystemGuid.Category.METRIC_HOSTING_METRICS.AsGuid()); if (!hostingMetricsCategoryId.HasValue) { throw new Exception(@"Unable to find the ""Hosting Metrics"" Category ID."); } var metricIdsQuery = new MetricCategoryService(rockContext).Queryable() .Where(mc => mc.CategoryId == hostingMetricsCategoryId) .Select(mc => mc.MetricId); // Get all of the Metrics tied to the "Hosting Metrics" Category var metrics = new MetricService(rockContext).Queryable("MetricPartitions") .Where(m => metricIdsQuery.Contains(m.Id)) .ToList(); var metricValues = new List <MetricValue>(); foreach (var metric in metrics) { // Attempt to add any PerformanceCounter MetricValues TryAddPerformanceCounterMetricValue(metric, metricValues); } /* * 2020-04-22 - JPH * * The Metrics being collected by the first revision of this Job each have a single, default MetricPartition. * If we add Metrics to this Job in the future that are more complicated, we'll want to revisit the below logic. * */ var metricValueService = new MetricValueService(rockContext); var metricValuePartitionService = new MetricValuePartitionService(rockContext); foreach (var metricValue in metricValues) { foreach (var metricPartition in metricValue.Metric.MetricPartitions) { metricValue.MetricValuePartitions.Add(new MetricValuePartition { MetricPartitionId = metricPartition.Id }); } metricValueService.Add(metricValue); } rockContext.SaveChanges(); /* * 2020-05-19 - SK * Removing the old metrics based on Maximum Metric to Retain value * */ if (_maximumMetricsToRetain.HasValue) { foreach (var metric in metrics) { var deleteMetricValuesQry = metricValueService .Queryable() .AsNoTracking() .Where(a => a.MetricId == metric.Id) .OrderByDescending(a => a.MetricValueDateTime) .Skip(_maximumMetricsToRetain.Value); if (deleteMetricValuesQry.Any()) { var metricValuePartitionQry = metricValuePartitionService.Queryable().AsNoTracking().Where(a => deleteMetricValuesQry.Any(u => u.Id == a.MetricValueId)); rockContext.BulkDelete(metricValuePartitionQry); rockContext.BulkDelete(deleteMetricValuesQry); } } } context.Result = $"Calculated a total of {metricValues.Count} metric values for {metrics.Count} metrics"; }