private void DeleteCategory(CategoryInfo categoryObj, bool reload = false) { // Check if category if ((categoryObj != null) && CanModifyCategory(categoryObj.CategoryIsPersonal, categoryObj.CategoryIsGlobal)) { var parentCategory = CategoryInfoProvider.GetCategoryInfo(categoryObj.CategoryParentID); var isPersonal = categoryObj.CategoryIsPersonal; // Delete category CategoryInfoProvider.DeleteCategoryInfo(categoryObj); // Check if deleted category has parent if (parentCategory != null) { SelectedCategoryID = parentCategory.CategoryID; // Switch to editing of parent category catEdit.UserID = parentCategory.CategoryUserID; catEdit.Category = parentCategory; SwitchToEdit(reload); PreselectCategory(parentCategory, false); } else { SelectedCategoryID = 0; SelectedCategoryParentID = isPersonal ? PERSONAL_CATEGORIES_ROOT_PARENT_ID : CATEGORIES_ROOT_PARENT_ID; SwitchToInfo(); } pnlUpdateTree.Update(); pnlUpdateContent.Update(); } }
protected override void OnInit(EventArgs e) { base.OnInit(e); // Init trees handlers treeElemG.OnGetImage += treeElem_OnGetImage; treeElemP.OnGetImage += treeElem_OnGetImage; treeElemG.OnNodeCreated += treeElem_OnNodeCreated; treeElemP.OnNodeCreated += treeElem_OnNodeCreated; // Load parameters LoadParameters(); // Stop personal category tree when disabled if (!string.IsNullOrEmpty(disabledItems)) { if (disabledItems.ToLower().Contains("personal")) { treeElemP.StopProcessing = true; } if (disabledItems.ToLower().Contains("globalandsite")) { treeElemG.StopProcessing = true; } } // Get and store permissions canModifyGlobal = AllowGlobalCategories && CMSContext.CurrentUser.IsAuthorizedPerResource("CMS.Categories", "GlobalModify"); canModifySite = CMSContext.CurrentUser.IsAuthorizedPerResource("CMS.Categories", "Modify"); // Expand and preselect selected category when in single select mode if (!RequestHelper.IsPostBack() && !allowMultiple) { string value = hidItem.Value; if (!string.IsNullOrEmpty(value)) { string[] values = value.Split(new string[] { valuesSeparator }, StringSplitOptions.RemoveEmptyEntries); if (values.Length == 1) { int catId = 0; if (returnColumnName == "CategoryID") { catId = ValidationHelper.GetInteger(values[0], 0); } else { CategoryInfo cat = CategoryInfoProvider.GetCategoryInfo(values[0], CMSContext.CurrentSiteName); catId = (cat != null) ? cat.CategoryID : 0; } if (catId > 0) { // Select category SelectedCategoryID = catId; } } } } }
/// <summary> /// Handles request for deleting category. /// </summary> public void Delete() { CategoryInfo categoryObj = SelectedCategory; if ((categoryObj != null) && CanModifySelectedCategory) { // Remove deleted category from selection if (!string.IsNullOrEmpty(hidItem.Value)) { hidItem.Value = hidItem.Value.Replace(ValuesSeparator + categoryObj.CategoryID + ValuesSeparator, ValuesSeparator); hidHash.Value = ValidationHelper.GetHashString(hidItem.Value, new HashSettings(mSecurityPurpose)); pnlHidden.Update(); } // Preselect parent category CategoryInfo parentCategory = CategoryInfoProvider.GetCategoryInfo(categoryObj.CategoryParentID); if (parentCategory != null) { SelectedCategoryID = parentCategory.CategoryID; PreselectCategory(parentCategory, true); } else { SelectedCategoryID = 0; SelectedCategoryParentID = categoryObj.CategoryIsPersonal ? PERSONAL_CATEGORIES_ROOT_PARENT_ID : CATEGORIES_ROOT_PARENT_ID; } // Delete category CategoryInfoProvider.DeleteCategoryInfo(categoryObj); pnlUpdateTrees.Update(); } }
/// <summary> /// Creates subcategory. Called when the "Create subcategory" button is pressed. /// </summary> private bool CreateSubcategory() { // Get the parent category CategoryInfo parentCategory = CategoryInfoProvider.GetCategoryInfo("MyNewCategory", SiteContext.CurrentSiteName); if (parentCategory != null) { // Create new category object CategoryInfo newSubcategory = new CategoryInfo(); // Set the properties newSubcategory.CategoryDisplayName = "My new subcategory"; newSubcategory.CategoryName = "MyNewSubcategory"; newSubcategory.CategoryDescription = "My new subcategory description"; newSubcategory.CategorySiteID = SiteContext.CurrentSiteID; newSubcategory.CategoryCount = 0; newSubcategory.CategoryEnabled = true; newSubcategory.CategoryParentID = parentCategory.CategoryID; // Save the category CategoryInfoProvider.SetCategoryInfo(newSubcategory); return(true); } return(false); }
/// <summary> /// Handles request for deleting category. /// </summary> /// <param name="sender">Sender object.</param> /// <param name="e">Arguments.</param> public void lnkDelete_Click(object sender, EventArgs e) { CategoryInfo categoryObj = SelectedCategory; if ((categoryObj != null) && CanModifySelectedCategory) { // Remove deleted category from selection if (!string.IsNullOrEmpty(hidItem.Value)) { hidItem.Value = hidItem.Value.Replace(valuesSeparator + categoryObj.CategoryID + valuesSeparator, valuesSeparator); pnlHidden.Update(); } // Preselect parent category CategoryInfo parentCategory = CategoryInfoProvider.GetCategoryInfo(categoryObj.CategoryParentID); if (parentCategory != null) { SelectedCategoryID = parentCategory.CategoryID; PreselectCategory(parentCategory, true); } else { SelectedCategoryID = 0; SelectedCategoryParentID = categoryObj.CategoryIsPersonal ? PERSONAL_CATEGORIES_ROOT_PARENT_ID : CATEGORIES_ROOT_PARENT_ID; } // Delete category CategoryInfoProvider.DeleteCategoryInfo(categoryObj); pnlUpdateTrees.Update(); } }
/// <summary> /// Removes document from category. Called when the button "Remove document from category" is pressed. /// Expects the method AddDocumentToCategory to be run first. /// </summary> private bool RemoveDocumentFromCategory() { // Get the category CategoryInfo category = CategoryInfoProvider.GetCategoryInfo("MyNewCategory", CMSContext.CurrentSiteName); if (category != null) { // Get the tree structure TreeProvider tree = new TreeProvider(CMSContext.CurrentUser); // Get the root document TreeNode root = tree.SelectSingleNode(CMSContext.CurrentSiteName, "/", null, true); // Get the document category relationship DocumentCategoryInfo documentCategory = DocumentCategoryInfoProvider.GetDocumentCategoryInfo(root.DocumentID, category.CategoryID); if (documentCategory != null) { // Remove document from category DocumentCategoryInfoProvider.DeleteDocumentCategoryInfo(documentCategory); return(true); } } return(false); }
private void SetSelectedCategory() { string value = hidItem.Value; if (string.IsNullOrEmpty(value)) { return; } string[] values = value.Split(new[] { ValuesSeparator }, StringSplitOptions.RemoveEmptyEntries); if (values.Length != 1) { return; } int catId; if (returnColumnName == "CategoryID") { catId = ValidationHelper.GetInteger(values[0], 0); } else { CategoryInfo cat = CategoryInfoProvider.GetCategoryInfo(values[0], SiteContext.CurrentSiteName); catId = (cat != null) ? cat.CategoryID : 0; } if (catId > 0) { // Select category SelectedCategoryID = catId; } }
protected IEnumerable <String> GetCategories(String parentName) { CategoryInfo info = CategoryInfoProvider.GetCategoryInfo(parentName, CMSContext.CurrentSite.SiteName); var children = CategoryInfoProvider.GetChildCategories(info.CategoryID, null, null, -1, null, CMSContext.CurrentSite.SiteID); children.AsEnumerable().ToArray(); }
/// <summary> /// Handles actions risen from javascript. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void hdnButton_Click(object sender, EventArgs e) { string param = hidParam.Value; // Check if action was saving of existing category if (param.StartsWith("edit")) { // Check if category was disabled during editing if ((SelectedCategory != null) && !SelectedCategory.CategoryEnabled) { // Select coresponding root element bool personal = SelectedCategory.CategoryIsPersonal; SelectedCategoryID = 0; SelectedCategoryParentID = personal ? PERSONAL_CATEGORIES_ROOT_PARENT_ID : CATEGORIES_ROOT_PARENT_ID; } pnlUpdateTrees.Update(); } // Check if action was creation of new category else if (param.StartsWith("new")) { string[] splits = param.Split('|'); if (splits.Length == 2) { int id = ValidationHelper.GetInteger(splits[1], 0); if (id > 0) { // Select created category CategoryInfo category = CategoryInfoProvider.GetCategoryInfo(id); if (category != null) { SelectedCategoryID = category.CategoryID; PreselectCategory(category, false); if (!allowMultiple) { if (returnColumnName == "CategoryID") { hidItem.Value = valuesSeparator + id + valuesSeparator; } else { hidItem.Value = valuesSeparator + ScriptHelper.GetString(category.CategoryName, false) + valuesSeparator; } pnlHidden.Update(); } } } } pnlUpdateTrees.Update(); } // Remove parameter hidParam.Value = ""; }
/// <summary> /// Deletes category. Called when the "Delete category" button is pressed. /// Expects the CreateCategory method to be run first. /// </summary> private bool DeleteCategory() { // Get the category CategoryInfo deleteCategory = CategoryInfoProvider.GetCategoryInfo("MyNewCategory", CMSContext.CurrentSiteName); // Delete the category CategoryInfoProvider.DeleteCategoryInfo(deleteCategory); return(deleteCategory != null); }
protected override void OnInit(EventArgs e) { base.OnInit(e); // Init trees handlers treeElemG.OnGetImage += treeElem_OnGetImage; treeElemP.OnGetImage += treeElem_OnGetImage; treeElemG.OnNodeCreated += treeElem_OnNodeCreated; treeElemP.OnNodeCreated += treeElem_OnNodeCreated; // Set enabled state of actions before rendering actions Page.PreRender += (sender, args) => { HandleEnabledActions(); }; // Load parameters LoadParameters(); StopDisabledTrees(); // Get and store permissions canModifyGlobal = AllowGlobalCategories && CMSContext.CurrentUser.IsAuthorizedPerResource("CMS.Categories", "GlobalModify"); canModifySite = CMSContext.CurrentUser.IsAuthorizedPerResource("CMS.Categories", "Modify"); // Expand and preselect selected category when in single select mode if (!RequestHelper.IsPostBack() && !AllowMultipleSelection) { string value = hidItem.Value; if (!string.IsNullOrEmpty(value)) { string[] values = value.Split(new string[] { ValuesSeparator }, StringSplitOptions.RemoveEmptyEntries); if (values.Length == 1) { int catId = 0; if (returnColumnName == "CategoryID") { catId = ValidationHelper.GetInteger(values[0], 0); } else { CategoryInfo cat = CategoryInfoProvider.GetCategoryInfo(values[0], CMSContext.CurrentSiteName); catId = (cat != null) ? cat.CategoryID : 0; } if (catId > 0) { // Select category SelectedCategoryID = catId; } } } } }
/// <summary> /// Creates HTML code for category link. /// </summary> /// <param name="categoryId">ID of the category to create link for.</param> protected string CreateCategoryPartLink(int categoryId) { CategoryInfo cat = CategoryInfoProvider.GetCategoryInfo(categoryId); if (cat != null) { return(CreateCategoryPartLink(cat)); } return(""); }
/// <summary> /// Builds category tree from given dataset and returns root node object. /// </summary> /// <param name="data">Dataset containing categories to be organized as tree.</param> private void CreateCategoryTrees(DataSet data) { generalRoot = new CategoryNode(CategoriesRoot); personalRoot = new CategoryNode(PersonalCategoriesRoot); if (!DataHelper.DataSourceIsEmpty(data)) { // Handle custom starting category string prefixToRemove = ""; if (!string.IsNullOrEmpty(StartingCategory) && (StartingCategoryObj != null)) { prefixToRemove = StartingCategoryObj.CategoryIDPath; } foreach (DataRow dr in data.Tables[0].Rows) { // Get processed category path string idPath = dr["CategoryIDPath"].ToString(); // Shorten ID path when starting category entered if (!string.IsNullOrEmpty(prefixToRemove)) { idPath = idPath.Replace(prefixToRemove, ""); } // Split path string[] idSplits = idPath.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries); int[] ids = ValidationHelper.GetIntegers(idSplits, -1); // Add categories from path to tree foreach (int id in ids) { CategoryInfo category = CategoryInfoProvider.GetCategoryInfo(id); if (category != null) { if (category.CategoryIsPersonal) { personalRoot.AddCategory(category); } else { generalRoot.AddCategory(category); } } } } } }
/// <summary> /// Handles sub categories grid actions. /// </summary> /// <param name="actionName">Action name</param> /// <param name="actionArgument">Parameter</param> protected void gridSubCategories_OnAction(string actionName, object actionArgument) { switch (actionName.ToLowerCSafe()) { case "delete": int categoryId = ValidationHelper.GetInteger(actionArgument, 0); // Get category CategoryInfo categoryObj = CategoryInfoProvider.GetCategoryInfo(categoryId); if (categoryObj != null) { // Delete the category DeleteCategory(categoryObj); } break; } }
/// <summary> /// Gets and updates category. Called when the "Get and update category" button is pressed. /// Expects the CreateCategory method to be run first. /// </summary> private bool GetAndUpdateCategory() { // Get the category CategoryInfo updateCategory = CategoryInfoProvider.GetCategoryInfo("MyNewCategory", CMSContext.CurrentSiteName); if (updateCategory != null) { // Update the properties updateCategory.CategoryDisplayName = updateCategory.CategoryDisplayName.ToLower(); // Save the changes CategoryInfoProvider.SetCategoryInfo(updateCategory); return(true); } return(false); }
/// <summary> /// Creates HTML code for category link. /// </summary> /// <param name="categoryId">ID of the category.</param> protected string CreateCategoryPartLink(int categoryId) { // Get category CategoryInfo category = CategoryInfoProvider.GetCategoryInfo(categoryId); if (category != null) { string categoryDisplayName = category.CategoryDisplayName; // Get target url string url = (String.IsNullOrEmpty(CategoriesPagePath) ? RequestContext.CurrentURL : DocumentURLProvider.GetUrl(CategoriesPagePath)); // Append category parameter if (UseCodeNameInQuery) { url = URLHelper.AddParameterToUrl(url, "categoryname", category.CategoryName); } else { url = URLHelper.AddParameterToUrl(url, "categoryid", categoryId.ToString()); } StringBuilder attrs = new StringBuilder(); // Append target attribute if (!string.IsNullOrEmpty(CategoriesPageTarget)) { attrs.Append(" target=\"").Append(CategoriesPageTarget).Append("\""); } // Append title attribute if (RenderLinkTitle) { // Encode category name attrs.Append(" title=\"").Append(HTMLHelper.HTMLEncode(categoryDisplayName)).Append("\""); } return(string.Format("<a href=\"{0}\"{1}>{2}</a>", HTMLHelper.EncodeForHtmlAttribute(url), attrs, FormatCategoryDisplayName(categoryDisplayName, true))); } return(""); }
/// <summary> /// Adds document to category. Called when the button "Add document from category" is pressed. /// </summary> private bool AddDocumentToCategory() { // Get the category CategoryInfo category = CategoryInfoProvider.GetCategoryInfo("MyNewCategory", CMSContext.CurrentSiteName); if (category != null) { // Get the tree structure TreeProvider tree = new TreeProvider(CMSContext.CurrentUser); // Get the root document TreeNode root = tree.SelectSingleNode(CMSContext.CurrentSiteName, "/", null, true); // Add document to category DocumentCategoryInfoProvider.AddDocumentToCategory(root.DocumentID, category.CategoryID); return(true); } return(false); }
/// <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(CategoryInfoProvider.GetCategoryInfo(categoryID)); } }
/// <summary> /// Handles sub categories grid actions. /// </summary> /// <param name="actionName">Action name</param> /// <param name="actionArgument">Parameter</param> protected void gridSubCategories_OnAction(string actionName, object actionArgument) { int categoryId = ValidationHelper.GetInteger(actionArgument, 0); // Get category CategoryInfo categoryObj = CategoryInfoProvider.GetCategoryInfo(categoryId); if (categoryObj != null) { switch (actionName.ToLowerCSafe()) { case "edit": SelectedCategoryID = categoryObj.CategoryID; SwitchToEdit(); // Switch to editing mode catEdit.UserID = categoryObj.CategoryUserID; catEdit.Category = categoryObj; catEdit.ReloadData(); // Preselect category PreselectCategory(categoryObj, false); pnlUpdateTree.Update(); // Show general tab pnlTabs.SelectedTab = tabGeneral; break; case "delete": // Delete the category DeleteCategory(categoryObj); break; } } }
private void DeleteCategory(CategoryInfo categoryObj) { // Check if category if ((categoryObj != null) && CanModifyCategory(categoryObj.CategoryIsPersonal, categoryObj.CategoryIsGlobal)) { CategoryInfo parentCategory = CategoryInfoProvider.GetCategoryInfo(categoryObj.CategoryParentID); // Check if deleted category has parent if (parentCategory != null) { // Switch to editing of parent category SwitchToEdit(); catEdit.UserID = parentCategory.CategoryUserID; catEdit.Category = parentCategory; catEdit.ReloadData(); SelectedCategoryID = parentCategory.CategoryID; PreselectCategory(parentCategory, false); } else { SelectedCategoryID = 0; SelectedCategoryParentID = categoryObj.CategoryIsPersonal ? PERSONAL_CATEGORIES_ROOT_PARENT_ID : CATEGORIES_ROOT_PARENT_ID; SwitchToInfo(); } // Delete category CategoryInfoProvider.DeleteCategoryInfo(categoryObj); // Reload subcategories gridSubCategories.ReloadData(); pnlUpdateTree.Update(); pnlUpdateContent.Update(); } }
/// <summary> /// Saves the values. /// </summary> public void Save() { if (Node == null) { return; } if (!RaiseOnCheckPermissions(PERMISSION_MODIFY, this)) { var cui = MembershipContext.AuthenticatedUser; if ((cui == null) || ((UserID != cui.UserID) && !cui.IsAuthorizedPerResource("CMS.Users", PERMISSION_MODIFY))) { RedirectToAccessDenied("CMS.Users", PERMISSION_MODIFY); } } // Prepare selected values InitCurrentValues(); bool logUpdateTask = false; // Remove old items string newValues = ValidationHelper.GetString(selectCategory.Value, null); string items = DataHelper.GetNewItemsInList(newValues, mCurrentValues); if (!String.IsNullOrEmpty(items)) { string[] newItems = items.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); // Add all new items to user foreach (string item in newItems) { int categoryId = ValidationHelper.GetInteger(item, 0); DocumentCategoryInfoProvider.RemoveDocumentFromCategory(Node.DocumentID, categoryId); } logUpdateTask = true; } // Add new items items = DataHelper.GetNewItemsInList(mCurrentValues, newValues); if (!String.IsNullOrEmpty(items)) { string[] newItems = items.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); // Add all new items to user foreach (string item in newItems) { int categoryId = ValidationHelper.GetInteger(item, 0); // Make sure, that category still exists if (CategoryInfoProvider.GetCategoryInfo(categoryId) != null) { DocumentCategoryInfoProvider.AddDocumentToCategory(Node.DocumentID, categoryId); } } // Find all categories which child categories are bound to edited document DataSet catsToRemove = CategoryInfoProvider.GetDocumentCategories(Node.DocumentID, "EXISTS (SELECT CategoryID FROM CMS_Category AS CC WHERE CC.CategoryIDPath LIKE CMS_Category.CategoryIDPath + '/%' AND CC.CategoryID IN (SELECT CategoryID FROM CMS_DocumentCategory WHERE DocumentID = " + Node.DocumentID + "))", null, 0, "CMS_Category.CategoryID AS ID"); if (!DataHelper.DataSourceIsEmpty(catsToRemove)) { foreach (DataRow dr in catsToRemove.Tables[0].Rows) { // Remove categories covered by their children from document DocumentCategoryInfoProvider.RemoveDocumentFromCategory(Node.DocumentID, ValidationHelper.GetInteger(dr["ID"], 0)); } } logUpdateTask = true; } // Raise on after save if (OnAfterSave != null) { OnAfterSave(); } if (logUpdateTask) { // Log the synchronization if category bindings were changed DocumentSynchronizationHelper.LogDocumentChange(Node.NodeSiteName, Node.NodeAliasPath, TaskTypeEnum.UpdateDocument, DocumentManager.Tree); } isSaved = true; // Clear content changed flag, changes are saved directly DocumentManager.ClearContentChanged(); }
/// <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)); } }
/// <summary> /// Saves the values. /// </summary> public void Save() { if (!RaiseOnCheckPermissions(PERMISSION_MODIFY, this)) { CurrentUserInfo cui = CMSContext.CurrentUser; if ((cui == null) || ((UserID != cui.UserID) && !cui.IsAuthorizedPerResource("CMS.Users", PERMISSION_MODIFY))) { RedirectToAccessDenied("CMS.Users", PERMISSION_MODIFY); } } // Remove old items string newValues = ValidationHelper.GetString(selectCategory.Value, null); string items = DataHelper.GetNewItemsInList(newValues, mCurrentValues); if (!String.IsNullOrEmpty(items)) { string[] newItems = items.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); if (newItems != null) { // Add all new items to user foreach (string item in newItems) { int categoryId = ValidationHelper.GetInteger(item, 0); DocumentCategoryInfoProvider.RemoveDocumentFromCategory(mDocumentID, categoryId); } } } // Add new items items = DataHelper.GetNewItemsInList(mCurrentValues, newValues); if (!String.IsNullOrEmpty(items)) { string[] newItems = items.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); if (newItems != null) { // Add all new items to user foreach (string item in newItems) { int categoryId = ValidationHelper.GetInteger(item, 0); // Make sure, that category still exists if (CategoryInfoProvider.GetCategoryInfo(categoryId) != null) { DocumentCategoryInfoProvider.AddDocumentToCategory(mDocumentID, categoryId); } } // Find all categories which child categories are bound to edited document DataSet catsToRemove = CategoryInfoProvider.GetDocumentCategories(mDocumentID, "EXISTS (SELECT CategoryID FROM CMS_Category AS CC WHERE CC.CategoryIDPath LIKE CMS_Category.CategoryIDPath + '/%' AND CC.CategoryID IN (SELECT CategoryID FROM CMS_DocumentCategory WHERE DocumentID = " + mDocumentID + "))", null, 0, "CMS_Category.CategoryID AS ID"); if (!DataHelper.DataSourceIsEmpty(catsToRemove)) { foreach (DataRow dr in catsToRemove.Tables[0].Rows) { // Remove categories covered by their children from document DocumentCategoryInfoProvider.RemoveDocumentFromCategory(mDocumentID, ValidationHelper.GetInteger(dr["ID"], 0)); } // Prepare selected values selectCategory.Value = ""; DataSet ds = CategoryInfoProvider.GetDocumentCategories(DocumentID, GetWhereCondition(), null, 0, "CMS_Category.CategoryID"); if (!DataHelper.DataSourceIsEmpty(ds)) { mCurrentValues = TextHelper.Join(";", SystemDataHelper.GetStringValues(ds.Tables[0], "CategoryID")); selectCategory.Value = mCurrentValues; selectCategory.Reload(true); } } } } // Raise on after save if (OnAfterSave != null) { OnAfterSave(); } isSaved = true; }
/// <summary> /// Shows forms acording to mode of control and initializes breadcrumbs. /// </summary> private void ShowForms() { plcNew.Visible = IsCreating; plcEdit.Visible = IsEditing && SelectedCategory != null; plcInfo.Visible = !plcNew.Visible && !plcEdit.Visible; if (plcNew.Visible || plcEdit.Visible) { string[] idSplits = { }; // Figure out breadcrumbs count int breadcrumbsCount = plcNew.Visible ? 2 : 1; if (SelectedCategory != null) { idSplits = SelectedCategory.CategoryIDPath.Trim('/').Split('/'); breadcrumbsCount += idSplits.Length; } // Init breadcrumbs string[,] breadcrumbs = new string[breadcrumbsCount, 4]; int bi = 0; // Prepare root item if (CustomCategoriesRootSelected || ((SelectedCategory != null) && (SelectedCategory.CategoryUserID > 0))) { breadcrumbs[bi, 0] = GetString("categories.rootpersonalcategory"); breadcrumbs[bi, 3] = "SelectNode('PersonalCategoriesRoot'); if (NodeSelected) { NodeSelected(0, -2);} return false;"; } else { breadcrumbs[bi, 0] = GetString("categories.rootcategory"); breadcrumbs[bi, 3] = "SelectNode('CategoriesRoot'); if (NodeSelected) { NodeSelected(0, -1);} return false;"; } breadcrumbs[bi, 1] = " "; breadcrumbs[bi, 2] = ""; bi++; // Create bradcrumbs for whole path if (SelectedCategory != null) { CategoryInfo currentCategory = null; int[] ids = ValidationHelper.GetIntegers(idSplits, 0); foreach (int id in ids) { currentCategory = CategoryInfoProvider.GetCategoryInfo(id); if ((currentCategory != null) && (bi < breadcrumbsCount)) { breadcrumbs[bi, 0] = ResHelper.LocalizeString(currentCategory.CategoryDisplayName); breadcrumbs[bi, 1] = " "; breadcrumbs[bi, 2] = ""; breadcrumbs[bi, 3] = GetCategorySelectionScript(currentCategory); bi++; } } } // Add new category item if (plcNew.Visible) { breadcrumbs[bi, 0] = GetString("categories.new"); breadcrumbs[bi, 1] = ""; breadcrumbs[bi, 2] = ""; } titleElem.Breadcrumbs = breadcrumbs; } // Display title when creating a new category if (plcNew.Visible) { titleElem.TitleText = GetString("categories.new"); titleElem.TitleImage = GetImageUrl("Objects/CMS_Category/new.png"); } }
/// <summary> /// Saves the values. /// </summary> public void Save() { if (!RaiseOnCheckPermissions(CMSAdminControl.PERMISSION_MODIFY, this)) { CurrentUserInfo cui = CMSContext.CurrentUser; if ((cui == null) || ((this.UserID != cui.UserID) && !cui.IsAuthorizedPerResource("CMS.Users", CMSAdminControl.PERMISSION_MODIFY))) { RedirectToAccessDenied("CMS.Users", CMSAdminControl.PERMISSION_MODIFY); } } // Remove old items string newValues = ValidationHelper.GetString(selectCategory.Value, null); string items = DataHelper.GetNewItemsInList(newValues, mCurrentValues); if (!String.IsNullOrEmpty(items)) { string[] newItems = items.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); if (newItems != null) { // Add all new items to user foreach (string item in newItems) { int categoryId = ValidationHelper.GetInteger(item, 0); DocumentCategoryInfoProvider.RemoveDocumentFromCategory(this.mDocumentID, categoryId); } } } // Add new items items = DataHelper.GetNewItemsInList(mCurrentValues, newValues); if (!String.IsNullOrEmpty(items)) { string[] newItems = items.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); if (newItems != null) { // Add all new items to user foreach (string item in newItems) { int categoryId = ValidationHelper.GetInteger(item, 0); // Make sure, that category still exists if (CategoryInfoProvider.GetCategoryInfo(categoryId) != null) { DocumentCategoryInfoProvider.AddDocumentToCategory(this.mDocumentID, categoryId); } } } } // Raise on after save if (OnAfterSave != null) { OnAfterSave(); } if (!this.FormControlMode) { // Refresh page URLHelper.Redirect(URLHelper.AddParameterToUrl(URLHelper.CurrentURL, "saved", "1")); } isSaved = true; }
/// <summary> /// Creates breadcrumbs /// </summary> private void CreateBreadcrumbs() { // Init breadcrumbs data string text; string script; string[] idSplits = { }; // Split category path if (SelectedCategory != null) { idSplits = SelectedCategory.CategoryIDPath.Trim('/').Split('/'); } // Prepare root item if (CustomCategoriesRootSelected || ((SelectedCategory != null) && (SelectedCategory.CategoryUserID > 0))) { text = GetString("categories.rootpersonalcategory"); script = "SelectNode('PersonalCategoriesRoot'); if (NodeSelected) { NodeSelected(0, -2);} return false;"; } else { text = GetString("categories.rootcategory"); script = "SelectNode('CategoriesRoot'); if (NodeSelected) { NodeSelected(0, -1);} return false;"; } titleElem.Breadcrumbs.AddBreadcrumb(new BreadcrumbItem { Text = text, OnClientClick = script }); if (SelectedCategory != null) { if (IsLiveSite) { // Show full breadcrumbs path on live site int[] ids = ValidationHelper.GetIntegers(idSplits, 0); foreach (int id in ids) { CategoryInfo currentCategory = CategoryInfoProvider.GetCategoryInfo(id); if (currentCategory != null) { titleElem.Breadcrumbs.AddBreadcrumb(new BreadcrumbItem { Text = ResHelper.LocalizeString(currentCategory.CategoryDisplayName), RedirectUrl = " ", OnClientClick = GetCategorySelectionScript(currentCategory) }); } } } else if (!plcNew.Visible) { // Set edited object EditedObject = SelectedCategory; string displayName = SelectedCategory.CategoryDisplayName + (SelectedCategory.CategoryIsGlobal && !SelectedCategory.CategoryIsPersonal ? " " + GetString("general.global") : String.Empty); // Show only selected category display name in breadcrumb in UI titleElem.Breadcrumbs.AddBreadcrumb(new BreadcrumbItem { Text = ResHelper.LocalizeString(displayName), }); UIHelper.SetBreadcrumbsSuffix(GetString("objecttype.cms_category")); } } // Add new category item if (plcNew.Visible) { titleElem.Breadcrumbs.AddBreadcrumb(new BreadcrumbItem { Text = GetString("categories.new") }); } }
/// <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 CategoryInfoProvider.GetCategories().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 = CategoryInfoProvider.GetCategoryInfo(RootCategory, SiteContext.CurrentSiteName); if (rootCategory == null && int.TryParse(RootCategory, out RootCategoryID)) { rootCategory = CategoryInfoProvider.GetCategoryInfo(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); } } }