/// <summary> /// Sets the values. /// </summary> /// <param name="workflowTypes">The schedules.</param> public void SetValues(IEnumerable <WorkflowType> workflowTypes) { var workflowTypeList = workflowTypes.ToList(); if (workflowTypeList.Any()) { var ids = new List <string>(); var names = new List <string>(); var parentCategoryIds = string.Empty; foreach (var workflowType in workflowTypeList) { if (workflowType != null) { ids.Add(workflowType.Id.ToString()); names.Add(workflowType.Name); CategoryCache parentCategory = null; if (workflowType.CategoryId.HasValue) { parentCategory = CategoryCache.Get(workflowType.CategoryId.Value); } while (parentCategory != null) { parentCategoryIds += parentCategory.Id.ToString() + ","; parentCategory = parentCategory.ParentCategory; } } } InitialItemParentIds = parentCategoryIds.TrimEnd(new[] { ',' }); ItemIds = ids; ItemNames = names; } else { ItemId = Constants.None.IdValue; ItemName = Constants.None.TextHtml; } }
/// <summary> /// Sets the values. /// </summary> /// <param name="workflowTypes">The schedules.</param> public void SetValues(IEnumerable <WorkflowType> workflowTypes) { var workflowTypeList = workflowTypes.ToList(); if (workflowTypeList.Any()) { var ids = new List <string>(); var names = new List <string>(); var parentCategoryIds = string.Empty; foreach (var workflowType in workflowTypeList) { if (workflowType != null) { ids.Add(workflowType.Id.ToString()); names.Add(workflowType.Name); CategoryCache parentCategory = null; if (workflowType.CategoryId.HasValue) { parentCategory = CategoryCache.Get(workflowType.CategoryId.Value); } if (parentCategory != null) { // We need to get all of the categories the selected workflowtype is nested in order to expand them parentCategoryIds += string.Join(",", GetWorkflowTypeCategoryAncestorIdList(parentCategory.Id)) + ","; } } } ExpandedCategoryIds = parentCategoryIds.TrimEnd(new[] { ',' }); ItemIds = ids; ItemNames = names; } else { ItemId = Constants.None.IdValue; ItemName = Constants.None.TextHtml; } }
protected override void Render(HtmlTextWriter writer) { if (_comment.IsSpam) { _comment.CommentX = "<em>[comment removed]</em>"; } string alternativeCssClass = ""; if (_useAlternativeStyle) { alternativeCssClass = "CommentAlt"; } writer.WriteLine(@"<a name=""Comment_{0}""></a><div class=""Comment {0}"">", _comment.CommentID, alternativeCssClass); //when displaying user comments //need to show which story they commented on if (_displayStoryTitle) { //build local URL to story Category category = CategoryCache.GetCategory(_comment.Story.CategoryID, KickPage.HostProfile.HostID); string categoryIdentifier = category.CategoryIdentifier; string kickStoryUrl = UrlFactory.CreateUrl(UrlFactory.PageName.ViewStory, _comment.Story.StoryIdentifier, categoryIdentifier); //story title writer.Write(@"<div class=""storyTitle""><a href=""{0}#Comment_{1}"">{2}</a></div><br />", kickStoryUrl, _comment.CommentID, _comment.Story.Title); } writer.WriteLine(@"<div class=""CommentText"">{0}</div> <div class=""CommentAuthor"">posted by ", KickPage.KickUserProfile.ShowEmoticons ? TextHelper.ReplaceEmoticons(_comment.CommentX, KickPage.StaticEmoticonsRootUrl) : _comment.CommentX); UserLink userLink = new UserLink(); userLink.DataBind(UserCache.GetUser(_comment.UserID)); userLink.RenderControl(writer); writer.WriteLine(@" {0}</div></div>", Dates.ReadableDiff(_comment.CreatedOn, DateTime.Now)); }
public void SetValues(IEnumerable <Course> courses) { var courseList = courses.ToList(); if (courseList.Any()) { var ids = new List <string>(); var names = new List <string>(); var parentCategoryIds = string.Empty; foreach (var course in courseList) { if (course != null) { ids.Add(course.Id.ToString()); names.Add(course.Name); CategoryCache parentCategory = null; if (course.CategoryId.HasValue) { parentCategory = CategoryCache.Get(course.CategoryId.Value); } if (parentCategory != null) { // We need to get all of the categories the selected course is nested in order to expand them parentCategoryIds += string.Join(",", GetCategoryAncestorIdList(parentCategory.Id)) + ","; } } } InitialItemParentIds = parentCategoryIds.TrimEnd(new[] { ',' }); ItemIds = ids; ItemNames = names; } else { ItemId = Rock.Constants.None.IdValue; ItemName = Rock.Constants.None.TextHtml; } }
/// <summary> /// Adds the changes. /// </summary> /// <param name="rockContext">The rock context.</param> /// <param name="modelType">Type of the model.</param> /// <param name="categoryGuid">The category unique identifier.</param> /// <param name="entityId">The entity identifier.</param> /// <param name="changes">The changes.</param> /// <param name="caption">The caption.</param> /// <param name="relatedModelType">Type of the related model.</param> /// <param name="relatedEntityId">The related entity identifier.</param> public static void AddChanges(RockContext rockContext, Type modelType, Guid categoryGuid, int entityId, List <string> changes, string caption, Type relatedModelType, int?relatedEntityId) { var entityType = EntityTypeCache.Read(modelType); var category = CategoryCache.Read(categoryGuid); var creationDate = RockDateTime.Now; int?relatedEntityTypeId = null; if (relatedModelType != null) { var relatedEntityType = EntityTypeCache.Read(relatedModelType); if (relatedModelType != null) { relatedEntityTypeId = relatedEntityType.Id; } } if (entityType != null && category != null) { var historyService = new HistoryService(rockContext); foreach (string message in changes.Where(m => m != null && m != "")) { var history = new History(); history.EntityTypeId = entityType.Id; history.CategoryId = category.Id; history.EntityId = entityId; history.Caption = caption.Truncate(200); history.Summary = message; history.RelatedEntityTypeId = relatedEntityTypeId; history.RelatedEntityId = relatedEntityId; // Manually set creation date on these history items so that they will be grouped together history.CreatedDateTime = creationDate; historyService.Add(history); } } }
/// <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; if (this is CategoriesFieldType) { formattedValue = value; } else { if (!string.IsNullOrWhiteSpace(value)) { var category = CategoryCache.Get(value.AsGuid()); if (category != null) { formattedValue = category.Name; } } } return(base.FormatValue(parentControl, formattedValue, null, condensed)); }
/// <summary> /// Binds any needed data to the Grid Filter also using the user's stored /// preferences. /// </summary> private void BindFilter() { ddlGroupType.Items.Clear(); ddlGroupType.Items.Add(Rock.Constants.All.ListItem); var rockContext = new RockContext(); foreach (var groupType in GetTopGroupTypes(rockContext)) { ddlGroupType.Items.Add(new ListItem(groupType.Name, groupType.Id.ToString())); } ddlGroupType.SetValue(GetBlockUserPreference("Group Type")); // hide the GroupType filter if this page has a groupTypeId parameter if (_groupTypeId.HasValue) { pnlGroupType.Visible = false; } int?categoryId = GetBlockUserPreference("Category").AsIntegerOrNull(); if (!categoryId.HasValue) { var categoryCache = CategoryCache.Read(Rock.SystemGuid.Category.SCHEDULE_SERVICE_TIMES.AsGuid()); categoryId = categoryCache != null ? categoryCache.Id : (int?)null; } pCategory.EntityTypeId = EntityTypeCache.GetId(typeof(Rock.Model.Schedule)) ?? 0; if (categoryId.HasValue) { pCategory.SetValue(new CategoryService(rockContext).Get(categoryId.Value)); } else { pCategory.SetValue(null); } pkrParentLocation.SetValue(GetBlockUserPreference("Parent Location").AsIntegerOrNull()); }
public static void AddReturnToRoomHistory(RockContext rockContext, Person person) { if (AttendanceCache.IsWithParent(person.Id)) { AttendanceCache.RemoveWithParent(person.Id); var summary = string.Format("</span>from Parent at <span class=\"field-name\">{0}", Rock.RockDateTime.Now); var changes = new History.HistoryChangeList(); changes.AddCustom("Returned", History.HistoryChangeType.Record.ToString(), summary.Truncate(250)); changes.First().Caption = "Returned from Parent"; changes.First().RelatedData = GetHostInfo(); HistoryService.SaveChanges( rockContext, typeof(Rock.Model.Person), CategoryCache.Get(4).Guid, person.Id, changes, true ); } }
public override List <BreadCrumb> GetBreadCrumbs(PageReference pageReference) { Guid entityTypeGuid = Guid.Empty; Guid.TryParse(GetAttributeValue("EntityType"), out entityTypeGuid); var entityType = EntityTypeCache.Read(entityTypeGuid); if (entityType == null) { return(base.GetBreadCrumbs(pageReference)); } var breadCrumbs = new List <BreadCrumb>(); int parentCategoryId = int.MinValue; if (int.TryParse(PageParameter("CategoryId"), out parentCategoryId)) { var category = CategoryCache.Read(parentCategoryId); while (category != null) { var parms = new Dictionary <string, string>(); parms.Add("CategoryId", category.Id.ToString()); breadCrumbs.Add(new BreadCrumb(category.Name, new PageReference(pageReference.PageId, 0, parms))); category = category.ParentCategory; } } string rootPageTitle = string.IsNullOrWhiteSpace(GetAttributeValue("EntityQualifierColumn")) ? entityType.FriendlyName + " Categories" : this.RockPage.PageTitle; breadCrumbs.Add(new BreadCrumb(rootPageTitle, new PageReference(pageReference.PageId))); breadCrumbs.Reverse(); return(breadCrumbs); }
protected override void OnLoad(EventArgs e) { base.OnLoad(e); var categoryGuids = GetAttributeValue(AttributeKeys.Categories).SplitDelimitedValues(); var categories = categoryGuids.Select(c => CategoryCache.Get(c.AsGuid())).ToList(); lBlockName.Text = this.BlockName; if (Person != null) { var courses = EnrollmentHelper.GetPersonCourses(Person, categories, GetAttributeValue(AttributeKeys.EnrolledOnly).AsBoolean()); foreach (var item in courses) { phCourses.Controls.Add(new RockLiteral { Label = item.Course.Name, Text = item.Experiences.Where(ex => ex.Result.WasSuccess).Any() ? "Complete" : "Incomplete" }); } } }
/// <summary> /// Loads the drop down items. /// </summary> public void LoadDropDownItems() { this.Items.Clear(); if (EntityTypeId.HasValue) { // add Empty option first this.Items.Add(new ListItem()); // Get var categoryGuids = CategoryGuids ?? new List <Guid>(); using (var rockContext = new RockContext()) { var allEntityFilters = new DataViewFilterService(rockContext) .Queryable().AsNoTracking() .Where(f => f.EntityTypeId == EntityTypeId) .ToList(); foreach (var dataView in new DataViewService(rockContext) .GetByEntityTypeId(EntityTypeId.Value) .Include("DataViewFilter") .AsNoTracking()) { var category = dataView.CategoryId.HasValue ? CategoryCache.Get(dataView.CategoryId.Value) : null; if (!categoryGuids.Any() || (category != null && categoryGuids.Contains(category.Guid))) { var currentPerson = HttpContext.Current.Items["CurrentPerson"] as Person; if (dataView.IsAuthorized(Authorization.VIEW, currentPerson) && dataView.DataViewFilter.IsAuthorized(Authorization.VIEW, currentPerson, allEntityFilters)) { this.Items.Add(new ListItem(dataView.Name, dataView.Id.ToString())); } } } } } }
/// <summary> /// fs the schedules display filter value. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The e.</param> private void fSchedules_DisplayFilterValue(object sender, GridFilter.DisplayFilterValueArgs e) { switch (e.Key) { case GridUserPreferenceKey.Category: { var categoryId = e.Value.AsIntegerOrNull(); e.Value = string.Empty; if (categoryId.HasValue && categoryId > 0) { var category = CategoryCache.Get(categoryId.Value); if (category != null) { e.Value = category.Name; } } break; } case GridUserPreferenceKey.ActiveStatus: { if (!string.IsNullOrEmpty(e.Value) && e.Value == "all") { e.Value = string.Empty; } break; } default: { break; } } }
/// <summary> /// Sets the value. /// </summary> /// <param name="dataView">The data view.</param> public void SetValue(DataView dataView) { if (dataView != null) { ItemId = dataView.Id.ToString(); string parentCategoryIds = string.Empty; var parentCategory = dataView.CategoryId.HasValue ? CategoryCache.Get(dataView.CategoryId.Value) : null; while (parentCategory != null) { parentCategoryIds = parentCategory.Id + "," + parentCategoryIds; parentCategory = parentCategory.ParentCategory; } ExpandedCategoryIds = parentCategoryIds.TrimEnd(new[] { ',' }); ItemName = dataView.Name; } else { ItemId = Constants.None.IdValue; ItemName = Constants.None.TextHtml; } }
protected void MoveButton_Click(object sender, EventArgs e) { int currentCategoryId = this.CategoryPath.CurrentCategoryId; int selectedCategoryId = this.CategoryDropDown.SelectedCategoryId; if (this.MoveAction.SelectedValue.Equals("Category")) { ProductCategory productCategory = new ProductCategory { CategoryID = currentCategoryId, ParentCategoryID = selectedCategoryId }; ProductCategories.MoveProductCategory(productCategory); CategoryCache.ClearCategoryCache(); this.CategoryDropDown.Refresh(); this.SetCurrentCategory(this.CategoryPath.CurrentParentCategoryId); } else if (this.MoveAction.SelectedValue.Equals("Ads")) { Products.MoveProductsToCategory(currentCategoryId, selectedCategoryId); this.CategoryDropDown.SelectedIndex = 0; } }
/// <summary> /// Sets the value. /// </summary> /// <param name="workflowType">The Workflow Type.</param> public void SetValue(WorkflowType workflowType) { if (workflowType != null) { ItemId = workflowType.Id.ToString(); string parentCategoryIds = string.Empty; var parentCategory = workflowType.CategoryId.HasValue ? CategoryCache.Get(workflowType.CategoryId.Value) : null; while (parentCategory != null) { parentCategoryIds = parentCategory.Id + "," + parentCategoryIds; parentCategory = parentCategory.ParentCategory; } InitialItemParentIds = parentCategoryIds.TrimEnd(new[] { ',' }); ItemName = workflowType.Name; } else { ItemId = Constants.None.IdValue; ItemName = Constants.None.TextHtml; } }
/// <summary> /// Rs the filter_ display filter value. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The e.</param> /// <exception cref="System.NotImplementedException"></exception> void rFilter_DisplayFilterValue(object sender, GridFilter.DisplayFilterValueArgs e) { if (e.Key == "Category") { int?categoryId = e.Value.AsIntegerOrNull(); if (categoryId.HasValue) { var category = CategoryCache.Get(categoryId.Value); if (category != null) { e.Value = category.Name; } } else { e.Value = string.Empty; } } else { e.Value = string.Empty; } }
private void ShowDetails() { var courseGuids = GetAttributeValues(AttributeKeys.Categories); var categories = new List <CategoryCache>(); foreach (var guid in courseGuids) { var category = CategoryCache.Get(guid); if (category != null) { categories.Add(category); } } List <EnrollmentHelper.CourseResult> courses = EnrollmentHelper.GetPersonCourses(CurrentPerson, categories); var mergeFields = LavaHelper.GetCommonMergeFields(RockPage, CurrentPerson); mergeFields.Add("Courses", courses); ltContent.Text = GetAttributeValue(AttributeKeys.Lava) .ResolveMergeFields(mergeFields, CurrentPerson, GetAttributeValue(AttributeKeys.EnabledCommands)); }
/// <summary> /// Handles displaying the stored filter values. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The e as DisplayFilterValueArgs (hint: e.Key and e.Value).</param> protected void gfFilter_DisplayFilterValue(object sender, GridFilter.DisplayFilterValueArgs e) { switch (e.Key) { case "Date Range": e.Value = DateRangePicker.FormatDelimitedValues(e.Value); break; // don't display dead setting case "From Date": e.Value = string.Empty; break; // don't display dead setting case "To Date": e.Value = string.Empty; break; case "Prayer Category": int categoryId = e.Value.AsIntegerOrNull() ?? All.Id; if (categoryId == All.Id) { e.Value = "All"; } else { var category = CategoryCache.Get(categoryId); if (category != null) { e.Value = category.Name; } } break; } }
private void CategoryList_PreRender(object sender, System.EventArgs e) { CategoryCache cache = new CategoryCache(); cache.Ensure(data); HtmlGenericControl section = new HtmlGenericControl("div"); section.Attributes["class"] = "section"; this.Controls.Add(section); HtmlGenericControl heading = new HtmlGenericControl("h3"); heading.Controls.Add(new LiteralControl("Categories")); section.Controls.Add(heading); HtmlGenericControl list = new HtmlGenericControl("ul"); section.Controls.Add(list); foreach (CategoryCacheEntry catEntry in cache.Entries) { HtmlGenericControl item = new HtmlGenericControl("li"); list.Controls.Add(item); HyperLink catLink = new HyperLink(); catLink.Text = catEntry.Name; catLink.NavigateUrl = BlogXUtils.RelativeToRoot("CategoryView.aspx/" + catEntry.Name); item.Controls.Add(catLink); item.Controls.Add(new LiteralControl(" (")); HyperLink rssLink = new HyperLink(); rssLink.Text = "rss"; rssLink.NavigateUrl = BlogXUtils.RelativeToRoot("BlogXBrowsing.asmx/GetRssCategory?categoryName=" + catEntry.Name); item.Controls.Add(rssLink); item.Controls.Add(new LiteralControl(")")); } }
/// <summary> /// Sets the page title and icon. /// </summary> private void SetPanelTitleAndIcon() { CategoryCache category = null; var categories = GetAttributeValue(AttributeKey.Category).SplitDelimitedValues(false).AsGuidList(); if (categories.Count == 1) { category = CategoryCache.Get(categories.First()); } string panelTitle = this.GetAttributeValue(AttributeKey.BlockTitle); if (!string.IsNullOrEmpty(panelTitle)) { lTitle.Text = panelTitle; } else if (category != null) { lTitle.Text = category.Name; } else { lTitle.Text = "Attribute Values"; } string panelIcon = this.GetAttributeValue(AttributeKey.BlockIcon); if (!string.IsNullOrEmpty(panelIcon)) { iIcon.Attributes["class"] = panelIcon; } else if (category != null) { iIcon.Attributes["class"] = category.IconCssClass; } }
/// <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(); } }
/// <summary> /// Gets the services. /// </summary> /// <returns></returns> private List <Schedule> GetServices() { var services = new List <Schedule>(); var scheduleCategory = CategoryCache.Get(GetAttributeValue("ScheduleCategory").AsGuid()); if (scheduleCategory != null) { using (var rockContext = new RockContext()) { foreach (var schedule in new ScheduleService(rockContext) .Queryable().AsNoTracking() .Where(s => s.CategoryId.HasValue && s.CategoryId.Value == scheduleCategory.Id) .OrderBy(s => s.Name)) { services.Add(schedule); } } } return(services); }
/// <summary> /// Gets the services. /// </summary> /// <returns></returns> private List <Schedule> GetServices() { var services = new List <Schedule>(); var scheduleCategoryGuids = GetAttributeValue(AttributeKey.ScheduleCategory).SplitDelimitedValues().AsGuidList(); foreach (var scheduleCategoryGuid in scheduleCategoryGuids) { var scheduleCategory = CategoryCache.Get(scheduleCategoryGuid); if (scheduleCategory != null) { using (var rockContext = new RockContext()) { foreach (var schedule in new ScheduleService(rockContext) .Queryable().AsNoTracking() .Where(s => s.IsActive && s.CategoryId.HasValue && s.CategoryId.Value == scheduleCategory.Id) .OrderBy(s => s.Name)) { services.Add(schedule); } } } } var filterByCampus = GetAttributeValue(AttributeKey.FilterByCampus).AsBoolean(); if (filterByCampus) { var campus = CampusCache.Get(_selectedCampusId.Value); services = services.Where(s => campus.CampusScheduleIds.Contains(s.Id)).ToList(); } return(services); }
public void GetCategoryReturnsCachedCategoryTest() { var expected = Model.Create <Category>(); var cacheKey = "Category|" + expected.Group + "|" + expected.Name; var cache = Substitute.For <IMemoryCache>(); var config = Substitute.For <ICacheConfig>(); object value; cache.TryGetValue(cacheKey, out value).Returns( x => { x[1] = expected; return(true); }); var sut = new CategoryCache(cache, config); var actual = sut.GetCategory(expected.Group, expected.Name); actual.Should().BeEquivalentTo(expected); }
public void GetCategoriesReturnsCachedCategoriesTest() { var expected = Model.Create <List <Category> >(); const string CacheKey = "Categories"; var cache = Substitute.For <IMemoryCache>(); var config = Substitute.For <ICacheConfig>(); object value; cache.TryGetValue(CacheKey, out value).Returns( x => { x[1] = expected; return(true); }); var sut = new CategoryCache(cache, config); var actual = sut.GetCategories(); actual.Should().BeEquivalentTo(expected); }
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> /// Handles the Click event of the btnDelete 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 btnDelete_Click(object sender, EventArgs e) { int?parentCategoryId = null; var rockContext = new RockContext(); var categoryService = new CategoryService(rockContext); var category = categoryService.Get(int.Parse(hfCategoryId.Value)); if (category != null) { string errorMessage; if (!categoryService.CanDelete(category, out errorMessage)) { ShowReadonlyDetails(category); mdDeleteWarning.Show(errorMessage, ModalAlertType.Information); } else { parentCategoryId = category.ParentCategoryId; CategoryCache.Flush(category.Id); categoryService.Delete(category); rockContext.SaveChanges(); // reload page, selecting the deleted category's parent var qryParams = new Dictionary <string, string>(); if (parentCategoryId != null) { qryParams["CategoryId"] = parentCategoryId.ToString(); } NavigateToPage(RockPage.Guid, qryParams); } } }
/// <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 OnLoad(EventArgs e) { base.OnLoad(e); mdCategoryTreeConfig.Visible = false; bool canEditBlock = IsUserAuthorized(Authorization.EDIT); // hide all the actions if user doesn't have EDIT to the block divTreeviewActions.Visible = canEditBlock; var detailPageReference = new Rock.Web.PageReference(GetAttributeValue("DetailPage")); // NOTE: if the detail page is the current page, use the current route instead of route specified in the DetailPage (to preserve old behavior) if (detailPageReference == null || detailPageReference.PageId == this.RockPage.PageId) { hfPageRouteTemplate.Value = (this.RockPage.RouteData.Route as System.Web.Routing.Route).Url; hfDetailPageUrl.Value = new Rock.Web.PageReference(this.RockPage.PageId).BuildUrl().RemoveLeadingForwardslash(); } else { hfPageRouteTemplate.Value = string.Empty; var pageCache = PageCache.Read(detailPageReference.PageId); if (pageCache != null) { var route = pageCache.PageRoutes.FirstOrDefault(a => a.Id == detailPageReference.RouteId); if (route != null) { hfPageRouteTemplate.Value = route.Route; } } hfDetailPageUrl.Value = detailPageReference.BuildUrl().RemoveLeadingForwardslash(); } // Get EntityTypeName Guid?entityTypeGuid = GetAttributeValue("EntityType").AsGuidOrNull(); nbWarning.Text = "Please select an entity type in the block settings."; nbWarning.Visible = !entityTypeGuid.HasValue; if (entityTypeGuid.HasValue) { int entityTypeId = Rock.Web.Cache.EntityTypeCache.Read(entityTypeGuid.Value).Id; string entityTypeQualiferColumn = GetAttributeValue("EntityTypeQualifierProperty"); string entityTypeQualifierValue = GetAttributeValue("EntityTypeQualifierValue"); bool showUnnamedEntityItems = GetAttributeValue("ShowUnnamedEntityItems").AsBooleanOrNull() ?? true; string parms = string.Format("?getCategorizedItems=true&showUnnamedEntityItems={0}", showUnnamedEntityItems.ToTrueFalse().ToLower()); parms += string.Format("&entityTypeId={0}", entityTypeId); var rootCategory = CategoryCache.Read(this.GetAttributeValue("RootCategory").AsGuid()); // make sure the rootCategory matches the EntityTypeId (just in case they changed the EntityType after setting RootCategory if (rootCategory != null && rootCategory.EntityTypeId == entityTypeId) { parms += string.Format("&rootCategoryId={0}", rootCategory.Id); } if (!string.IsNullOrEmpty(entityTypeQualiferColumn)) { parms += string.Format("&entityQualifier={0}", entityTypeQualiferColumn); if (!string.IsNullOrEmpty(entityTypeQualifierValue)) { parms += string.Format("&entityQualifierValue={0}", entityTypeQualifierValue); } } var excludeCategoriesGuids = this.GetAttributeValue("ExcludeCategories").SplitDelimitedValues().AsGuidList(); List <int> excludedCategoriesIds = new List <int>(); if (excludeCategoriesGuids != null && excludeCategoriesGuids.Any()) { foreach (var excludeCategoryGuid in excludeCategoriesGuids) { var excludedCategory = CategoryCache.Read(excludeCategoryGuid); if (excludedCategory != null) { excludedCategoriesIds.Add(excludedCategory.Id); } } parms += string.Format("&excludedCategoryIds={0}", excludedCategoriesIds.AsDelimited(",")); } string defaultIconCssClass = GetAttributeValue("DefaultIconCSSClass"); if (!string.IsNullOrWhiteSpace(defaultIconCssClass)) { parms += string.Format("&defaultIconCssClass={0}", defaultIconCssClass); } RestParms = parms; var cachedEntityType = Rock.Web.Cache.EntityTypeCache.Read(entityTypeId); if (cachedEntityType != null) { string entityTypeFriendlyName = GetAttributeValue("EntityTypeFriendlyName"); if (string.IsNullOrWhiteSpace(entityTypeFriendlyName)) { entityTypeFriendlyName = cachedEntityType.FriendlyName; } lbAddItem.ToolTip = "Add " + entityTypeFriendlyName; lAddItem.Text = entityTypeFriendlyName; } // Attempt to retrieve an EntityId from the Page URL parameters. PageParameterName = GetAttributeValue("PageParameterKey"); string selectedNodeId = null; int? itemId = PageParameter(PageParameterName).AsIntegerOrNull(); string selectedEntityType; if (itemId.HasValue) { selectedNodeId = itemId.ToString(); selectedEntityType = (cachedEntityType != null) ? cachedEntityType.Name : string.Empty; } else { // If an EntityId was not specified, check for a CategoryId. itemId = PageParameter("CategoryId").AsIntegerOrNull(); selectedNodeId = CategoryNodePrefix + itemId; selectedEntityType = "category"; } lbAddCategoryRoot.Enabled = true; lbAddCategoryChild.Enabled = false; lbAddItem.Enabled = false; CategoryCache selectedCategory = null; if (!string.IsNullOrEmpty(selectedNodeId)) { hfSelectedItemId.Value = selectedNodeId; List <string> parentIdList = new List <string>(); if (selectedEntityType.Equals("category")) { selectedCategory = CategoryCache.Read(itemId.GetValueOrDefault()); } else { if (cachedEntityType != null) { Type entityType = cachedEntityType.GetEntityType(); if (entityType != null) { Type serviceType = typeof(Rock.Data.Service <>); Type[] modelType = { entityType }; Type service = serviceType.MakeGenericType(modelType); var serviceInstance = Activator.CreateInstance(service, new object[] { new RockContext() }); var getMethod = service.GetMethod("Get", new Type[] { typeof(int) }); ICategorized entity = getMethod.Invoke(serviceInstance, new object[] { itemId }) as ICategorized; if (entity != null) { lbAddCategoryChild.Enabled = false; if (entity.CategoryId.HasValue) { selectedCategory = CategoryCache.Read(entity.CategoryId.Value); if (selectedCategory != null) { string categoryExpandedID = CategoryNodePrefix + selectedCategory.Id.ToString(); parentIdList.Insert(0, CategoryNodePrefix + categoryExpandedID); } } } } } } // get the parents of the selected item so we can tell the treeview to expand those var category = selectedCategory; while (category != null) { category = category.ParentCategory; if (category != null) { string categoryExpandedID = CategoryNodePrefix + category.Id.ToString(); if (!parentIdList.Contains(categoryExpandedID)) { parentIdList.Insert(0, categoryExpandedID); } else { // infinite recursion break; } } } // also get any additional expanded nodes that were sent in the Post string postedExpandedIds = this.Request.Params["ExpandedIds"]; if (!string.IsNullOrWhiteSpace(postedExpandedIds)) { var postedExpandedIdList = postedExpandedIds.Split(',').ToList(); foreach (var id in postedExpandedIdList) { if (!parentIdList.Contains(id)) { parentIdList.Add(id); } } } hfInitialCategoryParentIds.Value = parentIdList.AsDelimited(","); } selectedCategory = selectedCategory ?? rootCategory; if (selectedCategory != null) { lbAddItem.Enabled = true; lbAddCategoryChild.Enabled = true; this.SelectedCategoryId = selectedCategory.Id; } else { this.SelectedCategoryId = null; } } }
/// <summary> /// Updates any Cache Objects that are associated with this entity /// </summary> /// <param name="entityState">State of the entity.</param> /// <param name="dbContext">The database context.</param> public void UpdateCache(System.Data.Entity.EntityState entityState, Rock.Data.DbContext dbContext) { CategoryCache.UpdateCachedEntity(this.Id, entityState); }
/// <summary> /// Gets the cache object associated with this Entity /// </summary> /// <returns></returns> public IEntityCache GetCacheObject() { return(CategoryCache.Get(this.Id)); }
public static void Main(string[] args) { string filePath = null; if (args.Length == 0) { throw new ArgumentException("Should be called with a Json PlayDrone file to import."); } filePath = args[0]; var log = new Logger(); var appConverter = new FileReader(log); var apps = appConverter.FileToModel(filePath); var count = apps.Count(); // Setup connection var connectionString = ConfigurationManager.ConnectionStrings["MarketDbConnectionString"]; using (var connection = new SqlConnection(connectionString.ConnectionString)) { // Initialise app store with logger and connection var appSqlStore = new AppStore(connection); var appStore = new AppLogger(appSqlStore, appSqlStore, log); var categorySqlStore = new CategoryStore(); var categoryCacheStore = new CategoryCache(categorySqlStore, categorySqlStore); var categoryStore = new CategoryLogger(categoryCacheStore, categoryCacheStore, log); // Assuming apps are added in order to save multiple queries to the database. var existingAppCount = appStore.Count(); // Loop through apps. App store will save every 100,000 apps var appsToSave = new List<Models.App>(); var appCounter = 0; for (int i = existingAppCount; i < count; i++) { // Get the app from the list. var app = apps[i]; // Store the app category if it doesn't exist. if (!categoryStore.Exists(app.category)) { var category = new Models.Category { Id = Guid.NewGuid(), Name = app.category }; categoryStore.Save(category); } // Lookup app category id. var categoryId = categoryStore.GetId(app.category); app.id = Guid.NewGuid(); app.categoryId = categoryId; appsToSave.Add(app); log.LogOperation(string.Format("App {0}/{1} added: {2}", i + 1, count, app.app_id)); appCounter++; // Save apps if(appCounter >= 100000) { appStore.SaveMany(appsToSave); appsToSave.Clear(); appCounter = 0; } } // Save the remainder appStore.SaveMany(appsToSave); log.LogOperation("DONE!!!!"); } }
CategoryCacheEntryCollection IBlogDataService.GetCategories() { CategoryCacheEntryCollection result; CategoryCache cache = new CategoryCache(); cache.Ensure(data); if (Thread.CurrentPrincipal.IsInRole("admin")) { result = cache.Entries; } else { result = new CategoryCacheEntryCollection(); foreach (CategoryCacheEntry category in cache.Entries) { if (category.IsPublic) { result.Add(category); } } } return result; }
// TODO: Consider refactoring to use InternalGetDayEntries that takes delegates. It is slightly more // complicated because this method uses CategoryCache(). EntryCollection IBlogDataService.GetEntriesForCategory(string categoryName, string acceptLanguages) { CategoryCache cache = new CategoryCache(); cache.Ensure(data); EntryCollection entryList = new EntryCollection(); Entry entry; if (cache.UrlSafeCategories.ContainsKey(categoryName)) { categoryName = cache.UrlSafeCategories[categoryName]; } CategoryCacheEntry catEntry = cache.Entries[categoryName]; if (catEntry != null) { foreach (CategoryCacheEntryDetail detail in catEntry.EntryDetails) { DayEntry day = data.Days[detail.DayDateUtc]; if (day != null) { Predicate<Entry> entryCriteria = null; if (acceptLanguages != null && acceptLanguages.Length > 0) { entryCriteria += EntryCollectionFilter.DefaultFilters.IsInAcceptedLanguagesOrMultiLingual(acceptLanguages); } day.Load(data); entry = day.GetEntries(entryCriteria)[detail.EntryId]; if (entry != null) { entryList.Add(entry); } } } } entryList.Sort((left, right) => right.CreatedUtc.CompareTo(left.CreatedUtc)); return entryList; }