/// <summary> /// Returns true if given codename is unique, otherwise false. /// </summary> /// <param name="newCodeName">Code name of the category.</param> /// <param name="isPersonal">Indicates if category is personal.</param> /// <param name="isGlobal">Indicates if category is global.</param> private bool CodeNameIsUnique(string newCodeName, bool isPersonal, bool isGlobal) { string where = "CategoryName = N'" + SqlHelperClass.GetSafeQueryString(newCodeName, false) + "'"; // Check if site category if (!isPersonal && !isGlobal) { // Look for category in global, personal and selected site categories where = SqlHelperClass.AddWhereCondition(where, "CategorySiteID = " + SiteID + " OR CategorySiteID IS NULL"); } // Get existing category DataSet ds = CategoryInfoProvider.GetCategories(where, "CategoryID", 1, "CategoryID"); if (SqlHelperClass.DataSourceIsEmpty(ds)) { return(true); } else { int id = ValidationHelper.GetInteger(ds.Tables[0].Rows[0]["CategoryID"], 0); // If the existing category is updated the code name already exists return((id > 0) && (this.CategoryID == id)); } }
/// <summary> /// Gets and bulk updates categories. Called when the "Get and bulk update categories" button is pressed. /// Expects the CreateCategory method to be run first. /// </summary> private bool GetAndBulkUpdateCategories() { // Prepare the parameters string where = "CategoryName LIKE N'MyNewCategory%'"; // Get the data DataSet categories = CategoryInfoProvider.GetCategories(where, null); if (!DataHelper.DataSourceIsEmpty(categories)) { // Loop through the individual items foreach (DataRow categoryDr in categories.Tables[0].Rows) { // Create object from DataRow CategoryInfo modifyCategory = new CategoryInfo(categoryDr); // Update the properties modifyCategory.CategoryDisplayName = modifyCategory.CategoryDisplayName.ToUpper(); // Save the changes CategoryInfoProvider.SetCategoryInfo(modifyCategory); } return(true); } return(false); }
private async Task CreateCategoriesTaxonomy() { try { SyncLog.LogEvent(EventType.INFORMATION, "KenticoKontentPublishing", "CREATECATEGORIESTAXONOMY"); var categories = CategoryInfoProvider.GetCategories() .OnSite(Settings.Sitename, true) .WhereNull("CategoryUserID") // Global first .OrderBy("CategorySiteID", "CategoryOrder") .TypedResult; var externalId = GetTaxonomyExternalId(CATEGORIES_GUID); var endpoint = $"/taxonomies"; var payload = new { name = "Categories", codename = CATEGORIES.ToLower(), external_id = externalId, terms = GetCategoryTerms(categories), }; await ExecuteWithoutResponse(endpoint, HttpMethod.Post, payload); } catch (Exception ex) { SyncLog.LogException("KenticoKontentPublishing", "CREATECATEGORIESTAXONOMY", ex); throw; } }
// GET: Polygomy public ActionResult Index() { Polygomy Page = DynamicRouteHelper.GetPage <Polygomy>(); HttpContext.Kentico().PageBuilder().Initialize(Page.DocumentID); // Get Categories List <int> PageCategories = TreeCategoryInfoProvider.GetTreeCategories() .WhereEquals("NodeID", Page.NodeID) .Select(x => x.CategoryID).ToList(); PolygomyViewModel model = new PolygomyViewModel() { MemeCategories = CategoryInfoProvider.GetCategories() .WhereIn("CategoryID", PageCategories) .Select(x => x.CategoryDisplayName).ToArray(), }; if (PageCategories.Count > 0) { model.Memes = MemeProvider.GetMemes() .Where(RelHelper.GetNodeCategoryWhere(PageCategories.Select(x => (object)x))) .ToList(); } return(View("NEWCC/Polygomy", model)); }
private void SetPossibleAndSelectedCategories() { PossibleCategories = new List <CategoryInfo>(); PossibleCategoryIDs = new List <int>(); SelectedCategories = new List <CategoryInfo>(); SelectedCategoryIDs = new List <int>(); // navigate through the tree structure foreach (TreeNode node in tvwCategoryTree.Nodes) { SetPossibleAndSelectedCategoriesTreeRecursive(node); } // Get allowed category IDs and those found PossibleCategories = CategoryInfoProvider.GetCategories().WhereIn("CategoryID", PossibleCategoryIDs).TypedResult.ToList(); SelectedCategories = CategoryInfoProvider.GetCategories().WhereIn("CategoryID", SelectedCategoryIDs).TypedResult.ToList(); }
public static CMS.DataEngine.ObjectQuery <CategoryInfo> GenerateCategoryQuery(List <string> IncludeSites, bool IncludeGlobalCategories, bool IncludeDisabledCategories) { try { List <int> siteFilterIDs = new List <int>(); if (IncludeSites != null && IncludeSites.Count() > 0) { foreach (var siteCodeName in IncludeSites) { var site = SiteInfoProvider.GetSiteInfo(siteCodeName); if (site != null) { siteFilterIDs.Add(site.SiteID); } } } CMS.DataEngine.ObjectQuery <CategoryInfo> categoriesQuery = CategoryInfoProvider .GetCategories(); if (!IncludeDisabledCategories) { categoriesQuery = categoriesQuery.WhereEquals("CategoryEnabled", true); } categoriesQuery = categoriesQuery.WhereEquals("CategorySiteID", SiteContext.CurrentSiteID); foreach (var siteC in siteFilterIDs) { categoriesQuery = categoriesQuery.Or().WhereEquals("CategorySiteID", siteC); } if (IncludeGlobalCategories) { categoriesQuery = categoriesQuery.Or().WhereEquals("CategorySiteID", null); // Also get global categories } categoriesQuery = categoriesQuery.OrderBy("CategorySiteId", "CategoryLevel", "CategoryOrder"); return(categoriesQuery); } catch (Exception ex) { throw ex; } }
/// <summary> /// Returns dataset with categories. /// </summary> protected DataSet GetDataSet() { DataSet ds = null; // Prepare user id int userId = 0; if ((MembershipContext.AuthenticatedUser != null) && (MembershipContext.AuthenticatedUser.UserID > 0)) { userId = MembershipContext.AuthenticatedUser.UserID; } // Try to get data from cache using (var cs = new CachedSection <DataSet>(ref ds, CacheMinutes, true, CacheItemName, "categorylist", SiteContext.CurrentSiteName, DisplayGlobalCategories, AllowGlobalCategories, DisplaySiteCategories, DisplayCustomCategories, userId, UseDocumentFilter, AliasPath, CultureCode, MaxRelativeLevel, CombineWithDefaultCulture, SelectOnlyPublished, WhereCondition, StartingCategory)) { if (cs.LoadData) { string where = GetCompleteWhereCondition(); if (mUseCompleteWhere) { ds = CategoryInfoProvider.GetDocumentCategories(where, OrderBy, SelectTopN); } else { ds = CategoryInfoProvider.GetCategories(where, OrderBy, SelectTopN); } // Save the result to the cache if (cs.Cached) { cs.CacheDependency = GetCacheDependency(); } cs.Data = ds; } } return(ds); }
/// <summary> /// Handles the DataBinding of the Tree /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void tvwCategoryTree_TreeNodeDataBound(object sender, TreeNodeEventArgs e) { // Convert value into category and get the proper text. int categoryID = 0; if (SaveModeVal != SaveType.ToCategory && SaveModeVal != SaveType.ToJoinTable) { switch (FieldSaveModeVal) { case FieldSaveType.ID: int.TryParse(e.Node.Value, out categoryID); break; case FieldSaveType.GUID: CategoryInfo temp = CategoryInfoProvider.GetCategories("CategoryGUID = '" + (!string.IsNullOrWhiteSpace(e.Node.Value) ? new Guid().ToString() : e.Node.Value) + "'", null, -1, null, SiteContext.CurrentSiteID).FirstOrDefault(); if (temp != null) { categoryID = temp.CategoryID; } break; case FieldSaveType.CategoryName: CategoryInfo temp2 = CategoryInfoProvider.GetCategories("CategoryName = '" + e.Node.Value + "'", null, -1, null, SiteContext.CurrentSiteID).FirstOrDefault(); if (temp2 != null) { categoryID = temp2.CategoryID; } break; } } else { int.TryParse(e.Node.Value, out categoryID); } if (categoryID > 0) { e.Node.Text = GetInputDataPrepend(CategoryInfo.Provider.Get(categoryID)); } }
/// <summary> /// Populates the List with the children nodes. /// </summary> /// <param name="ParentCategoryNode">The Parent Category, can be null if it's the root</param> /// <param name="ParentNode">The Parent Tree Node</param> /// <param name="SelectedCategories">The currently selected categories</param> private void CreateChildTreeNodes(CategoryInfo ParentCategoryNode, ref TreeNode ParentNode, ref List <CategoryInfo> SelectedCategories) { // Grab all valid child categories var ChildCategories = (ParentCategoryNode == null ? CategoryInfoProvider.GetCategories(AllowableCategoryIDWhere, DefaultSortOrder, -1, null, SiteContext.CurrentSiteID).WhereEquals("CategoryLevel", 0) : CategoryInfoProvider.GetChildCategories(ParentCategoryNode.CategoryID, AllowableCategoryIDWhere, DefaultSortOrder, -1, null, SiteContext.CurrentSiteID)); foreach (CategoryInfo childCategory in ChildCategories) { TreeNode childTreeObj = new TreeNode(GetInputDataPrepend(childCategory), GetNodeValue(childCategory)); childTreeObj.SelectAction = TreeNodeSelectAction.None; // Must save as ID childTreeObj.Expanded = (childCategory.CategoryLevel < ExpandCategoryLevel); SetNodeChecked(childTreeObj, childCategory); // If either all items selectable, or if only leaf selectable and this is a leaf node, save to the possible categories list. if (childCategory.Children.Count == 0 || !OnlyLeafSelectable) { PossibleCategories.Add(childCategory); } CreateChildTreeNodes(childCategory, ref childTreeObj, ref SelectedCategories); ParentNode.ChildNodes.Add(childTreeObj); } }
/// <summary> /// Reloads data. /// </summary> public void ReloadData(bool force) { if (!dataLoaded || force) { DisabledItems = string.Empty; disabledCats = new Hashtable(); int shift = 0; drpCategories.Items.Clear(); string where = GetWhereCondition(); if (AddNoneRecord) { ListItem item = new ListItem(GetString("general.root"), "0"); drpCategories.Items.Add(item); } // Get the data DataSet ds = CategoryInfoProvider.GetCategories(where, "CategoryUserID, CategorySiteID, CategoryOrder", 0, "CategoryID, CategoryParentID, CategoryDisplayName, CategoryOrder, CategoryLevel, CategorySiteID, CategoryEnabled", SiteID); if (!DataHelper.DataSourceIsEmpty(ds)) { gds = new GroupedDataSource(ds, "CategoryParentID"); FillDropDownList(shift, 0); } // Ensure selected category if (CategoryID != mCategoryId) { CategoryID = mCategoryId; } dataLoaded = true; } }
/// <summary> /// Takes the existing value and sets the Category Tree /// </summary> protected void setCategoryTree() { tvwCategoryTree.Nodes.Clear(); // Grab Current Categories CurrentCategories = new List <CategoryInfo>(); if (SaveModeVal == SaveType.ToJoinTable) { // Get initial categories from Join Table. if (!IsPostBack) { // Get the CategoryNames currently in the join table. int totalRecords = 0; var currentCategoriesDS = ConnectionHelper.ExecuteQuery(JoinTableName + ".selectall", null, string.Format("{0} = '{1}'", JoinTableLeftFieldName, CurrentItemIdentification), null, -1, null, -1, -1, ref totalRecords); string CategoryFieldName = ""; switch (FieldSaveModeVal) { case FieldSaveType.ID: CategoryFieldName = "CategoryID"; break; case FieldSaveType.GUID: CategoryFieldName = "CategoryGUID"; break; case FieldSaveType.CategoryName: CategoryFieldName = "CategoryName"; break; } List <string> currentCategories = new List <string>(); foreach (DataRow dr in currentCategoriesDS.Tables[0].Rows) { currentCategories.Add(ValidationHelper.GetString(dr[JoinTableRightFieldName], "")); } var CurrentCategoryObjects = CategoryInfoProvider.GetCategories(null, null, -1, null, SiteContext.CurrentSiteID).WhereIn(CategoryFieldName, currentCategories).Select(x => CategoryInfo.New(x)); if (CurrentCategoryObjects != null) { CurrentCategories.AddRange(CurrentCategoryObjects); } } } else { // Get initial categories from Document listing. if (!IsPostBack) { // Will set the txtValue to the current proper categories after the first setup. var CurrentCategoriesOfDoc = DocumentCategoryInfoProvider.GetDocumentCategories(ValidationHelper.GetInteger(PageDocument.GetValue("DocumentID"), -1)); if (CurrentCategoriesOfDoc != null) { CurrentCategories.AddRange(CurrentCategoriesOfDoc); } /* * // Handle default if new form and no categories * if (Form.Mode != FormModeEnum.Update && CurrentCategories.Count == 0 && !string.IsNullOrWhiteSpace(txtValue.Text)) * { * // Don't know if default is CodeName, Guid, or ID, so cover all * string[] DelimitedValues = SplitAndSecure(txtValue.Text); * string DefaultValueWhereCondition = ""; * int[] intArray = StringArrayToIntArray(DelimitedValues); * Guid[] guidArray = StringArrayToGuidArray(DelimitedValues); * DefaultValueWhereCondition = SqlHelper.AddWhereCondition(DefaultValueWhereCondition, string.Format("CategoryName in ('{0}')", string.Join("','", DelimitedValues)), "OR"); * if (intArray.Length > 0) * { * DefaultValueWhereCondition = SqlHelper.AddWhereCondition(DefaultValueWhereCondition, string.Format("CategoryID in ('{0}')", string.Join("','", intArray)), "OR"); * } * if (guidArray.Length > 0) * { * DefaultValueWhereCondition = SqlHelper.AddWhereCondition(DefaultValueWhereCondition, string.Format("CategoryGUID in ('{0}')", string.Join("','", guidArray)), "OR"); * } * foreach (CategoryInfo catInfo in CategoryInfo.Provider.Get().Where(DefaultValueWhereCondition)) * { * CurrentCategories.Add(catInfo); * } * }*/ } else { /* * var CurrentCategoriesOfDoc = CategoryInfoProvider.GetCategories("CategoryID in ('" + string.Join("','", SplitAndSecure(initialCategories)) + "')", null, -1, null, SiteContext.CurrentSiteID); * if (CurrentCategoriesOfDoc != null) * { * CurrentCategories.AddRange(CurrentCategoriesOfDoc); * } */ } } if (OnlyLeafSelectable) { if (ParentSelectsChildren) { tvwCategoryTree.ShowCheckBoxes = TreeNodeTypes.All; } else { tvwCategoryTree.ShowCheckBoxes = TreeNodeTypes.Leaf; } } else { tvwCategoryTree.ShowCheckBoxes = TreeNodeTypes.All; } // Root Category given, all items must be under that root // If Tree Structure, must go through all children of root and then compare to the "Where" List of items, if where is set // If List, display all valid categories under the root. int RootCategoryID = 0; var rootCategory = CategoryInfo.Provider.Get(RootCategory, SiteContext.CurrentSiteID); if (rootCategory == null && int.TryParse(RootCategory, out RootCategoryID)) { rootCategory = CategoryInfo.Provider.Get(RootCategoryID); } // Grab allowable Categories if user sets a WHERE string TempWhere = "CategoryNamePath like " + (rootCategory == null ? "'/%'" : "'" + rootCategory.CategoryNamePath + "/%'") + (string.IsNullOrWhiteSpace(WhereFilter) ? "" : " and " + WhereFilter); DefaultSortOrder = (string.IsNullOrWhiteSpace(OrderBy) ? (DisplayMode == DisplayType.List ? "CategoryDisplayName" : "CategoryLevel, CategoryOrder") : OrderBy); var AllowableCategoryList = CategoryInfoProvider.GetCategories(TempWhere, DefaultSortOrder, -1, null, SiteContext.CurrentSiteID); if (AllowableCategoryList.Count > 0) { AllowableCategoryIDWhere = "CategoryID in (" + string.Join(",", AllowableCategoryList.Select(x => new CategoryInfo(x).CategoryID)) + ")"; } else { AllowableCategoryIDWhere = ""; } if (DisplayMode == DisplayType.Tree) { pnlSearchFilter.Visible = false; tvwCategoryTree.ShowLines = true; TreeNode rootNode = null; if (rootCategory == null) { rootNode = new TreeNode("Root", GetNodeValue(rootCategory)); rootNode.ShowCheckBox = (OnlyLeafSelectable && ParentSelectsChildren); rootNode.SelectAction = TreeNodeSelectAction.None; // Expand to the nth level from the Category Level. ExpandCategoryLevel = 0 + ExpandToLevel; rootNode.Expanded = (0 < ExpandCategoryLevel); SetNodeChecked(rootNode, rootCategory); } else { rootNode = new TreeNode(GetInputDataPrepend(rootCategory), GetNodeValue(rootCategory)); rootNode.SelectAction = TreeNodeSelectAction.None; // Expand to the nth level from the Category Level. ExpandCategoryLevel = rootCategory.CategoryLevel + ExpandToLevel; rootNode.Expanded = (rootCategory.CategoryLevel < ExpandCategoryLevel); SetNodeChecked(rootNode, rootCategory); // If either all items selectable, or if only leaf selectable and this is a leaf node, save to the possible categories list. if (rootCategory.Children.Count == 0 || !OnlyLeafSelectable) { PossibleCategories.Add(rootCategory); } } CreateChildTreeNodes(rootCategory, ref rootNode, ref CurrentCategories); tvwCategoryTree.Nodes.Add(rootNode); } else if (DisplayMode == DisplayType.List) { pnlTreeButtons.Visible = false; // Just loop through allowable Categories and add to list. foreach (CategoryInfo CategoryItem in AllowableCategoryList) { TreeNode childNode = new TreeNode(GetInputDataPrepend(CategoryItem), GetNodeValue(CategoryItem)); childNode.SelectAction = TreeNodeSelectAction.None; childNode.Expanded = (CategoryItem.CategoryLevel < ExpandCategoryLevel); SetNodeChecked(childNode, CategoryItem); PossibleCategories.Add(CategoryItem); tvwCategoryTree.Nodes.Add(childNode); } } }
/// <summary> /// Converts Category IDs, Guids, or CodeNames to Category CodeNames /// </summary> /// <param name="CategoryIdentifications">List of Category IDs, Guids, or CodeNames</param> /// <returns>List of Category Code Names</returns> private static IEnumerable <string> CategoryIdentitiesToCodeNames(IEnumerable <object> CategoryIdentifications) { return(CategoryInfoProvider.GetCategories().Where(CategoryIdentitiesWhere(CategoryIdentifications)).Columns("CategoryName").Select(x => x.CategoryName).ToArray()); }
/// <summary> /// Converts Category IDs, Guids, or CodeNames to CategoryGUIDs /// </summary> /// <param name="CategoryIdentifications">List of Category IDs, Guids, or CodeNames</param> /// <returns>List of Category GUIDs</returns> private static IEnumerable <Guid> CategoryIdentitiesToGUIDs(IEnumerable <object> CategoryIdentifications) { return(CategoryInfoProvider.GetCategories().Where(CategoryIdentitiesWhere(CategoryIdentifications)).Columns("CategoryGUID").Select(x => x.CategoryGUID).ToArray()); }
/// <summary> /// Figure out using the Join Table which categories need to be removed and which added /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void SaveToJoinTable() { SetPossibleAndSelectedCategories(); // Do check of min/max here if (MinimumCategories > 0 && SelectedCategories.Count() < MinimumCategories) { AddError("Must select at least " + MinimumCategories + " " + (MinimumCategories == 1 ? "category" : "categories")); return; } if (MaximumCategories > 0 && SelectedCategories.Count() > MaximumCategories) { AddError("Can select no more than " + MaximumCategories + " " + (MaximumCategories == 1 ? "category" : "categories")); return; } // filter with only the possible categories DataClassInfo JoinTableClassInfo = DataClassInfoProvider.GetDataClassInfo(JoinTableName); if (JoinTableClassInfo != null) { List <int> DocumentCategoryIds = new List <int>(); // Get all the categories the current entity has int totalRecords = 0; var currentCategoriesDS = ConnectionHelper.ExecuteQuery(JoinTableName + ".selectall", null, string.Format("{0} = '{1}'", JoinTableLeftFieldName, CurrentItemIdentification), null, -1, null, -1, -1, ref totalRecords); CategoryInfo catObject = null; string FieldSaveColumnName = ""; // Convert to CategoryID switch (FieldSaveModeVal) { case FieldSaveType.ID: FieldSaveColumnName = "CategoryID"; break; case FieldSaveType.GUID: FieldSaveColumnName = "CategoryGUID"; break; case FieldSaveType.CategoryName: FieldSaveColumnName = "CategoryName"; break; } foreach (DataRow dr in currentCategoriesDS.Tables[0].Rows) { // Convert to CategoryID switch (FieldSaveModeVal) { case FieldSaveType.ID: catObject = CategoryInfoProvider.GetCategoryInfo(ValidationHelper.GetInteger(dr[JoinTableRightFieldName], 0)); if (catObject != null) { DocumentCategoryIds.Add(catObject.CategoryID); } break; case FieldSaveType.GUID: var ClassObject = CategoryInfoProvider.GetCategories().WhereEquals("CategoryGUID", ValidationHelper.GetGuid(dr[JoinTableRightFieldName], new Guid())).FirstOrDefault(); if (ClassObject != null) { DocumentCategoryIds.Add(ValidationHelper.GetInteger(ClassObject["CategoryID"], 0)); } break; case FieldSaveType.CategoryName: catObject = CategoryInfoProvider.GetCategoryInfo(ValidationHelper.GetString(dr[JoinTableRightFieldName], ""), SiteContext.CurrentSiteName); if (catObject != null) { DocumentCategoryIds.Add(catObject.CategoryID); } break; } } // Find IDs we need to add and remove. List <int> NotSelectedIds = PossibleCategoryIDs.Except(SelectedCategoryIDs).ToList(); List <int> DeselectIds = DocumentCategoryIds.Intersect(NotSelectedIds).ToList(); List <int> SelectIds = SelectedCategoryIDs.Except(DocumentCategoryIds).ToList(); if (DeselectIds.Count > 0) { foreach (int DeselectId in DeselectIds) { if (JoinTableClassInfo.ClassIsCustomTable) { CustomTableItemProvider.GetItems(JoinTableClassInfo.ClassName).WhereEquals(JoinTableLeftFieldName, CurrentItemIdentification) .WhereEquals(JoinTableRightFieldName, CategoryInfoProvider.GetCategoryInfo(DeselectId).GetValue(FieldSaveColumnName)) .ToList().ForEach(x => ((CustomTableItem)x).Delete()); } else { new ObjectQuery(JoinTableClassInfo.ClassName) .WhereEquals(JoinTableLeftFieldName, CurrentItemIdentification) .WhereEquals(JoinTableRightFieldName, CategoryInfoProvider.GetCategoryInfo(DeselectId).GetValue(FieldSaveColumnName)) .ToList().ForEach(x => x.Delete()); } } } if (SelectIds.Count > 0) { foreach (int SelectId in SelectIds) { if (JoinTableClassInfo.ClassIsCustomTable) { CustomTableItem newCustomTableItem = CustomTableItem.New(JoinTableName); SetBaseInfoItemValues(newCustomTableItem, CategoryInfoProvider.GetCategoryInfo(SelectId).GetValue(FieldSaveColumnName), JoinTableClassInfo.ClassName); InsertObjectHandler(newCustomTableItem); } else { // Create a dynamic BaseInfo object of the right type. var JoinTableClassFactory = new InfoObjectFactory(JoinTableClassInfo.ClassName); if (JoinTableClassFactory.Singleton == null) { AddError("Class does not have TypeInfo and TypeInfoProvider generated. Must generate " + JoinTableClassInfo.ClassName + " Code before can bind."); return; } BaseInfo newJoinObj = ((BaseInfo)JoinTableClassFactory.Singleton); SetBaseInfoItemValues(newJoinObj, CategoryInfoProvider.GetCategoryInfo(SelectId).GetValue(FieldSaveColumnName), JoinTableClassInfo.ClassName); InsertObjectHandler(newJoinObj); } } } AddConfirmation(string.Format("{0} Categories Added, {1} Categories Removed.", SelectIds.Count, DeselectIds.Count)); } }