public CompanyInfo SavePlaceTreeRootNode()
        {
            ObjectQuery oqTree = new ObjectQuery();

            oqTree.AddCriterion(Expression.Eq("Name", "公司管理"));
            IList listTree = dao.ObjectQuery(typeof(CategoryTree), oqTree);

            CategoryTree tree = null;

            if (listTree.Count > 0)
            {
                tree = listTree[0] as CategoryTree;
            }

            CompanyInfo oCompanyInfo = new CompanyInfo();

            oCompanyInfo.Name             = "公司信息";
            oCompanyInfo.ParentNode       = null;
            oCompanyInfo.CategoryNodeType = VirtualMachine.Patterns.CategoryTreePattern.Domain.NodeType.RootNode;
            oCompanyInfo.CreateDate       = DateTime.Now;
            oCompanyInfo.Level            = 1;
            oCompanyInfo.OrderNo          = 1;
            oCompanyInfo.State            = 1;
            oCompanyInfo.TheTree          = tree;
            oCompanyInfo.Author           = Dao.Get(typeof(BusinessOperators), "428") as IBusinessOperators;
            dao.Save(oCompanyInfo);
            oCompanyInfo.SysCode = oCompanyInfo.Id + ".";
            dao.Update(oCompanyInfo);
            return(oCompanyInfo);
        }
Beispiel #2
0
        private void treeList1_MouseDown(object sender, MouseEventArgs e)
        {
            _HitInfo = treeList1.CalcHitInfo(new Point(e.X, e.Y));
            if (_HitInfo.Node == null)
            {
                return;
            }
            _CurrentCategory        = (CategoryTree)treeList1.GetDataRecordByNode(_HitInfo.Node);
            lblCurrentCategory.Text = _CurrentCategory.Name;

            mAddNewCategory.Enabled = _CurrentCategory.IsCategory;
            if (_CurrentCategory.IsCategory)
            {
                mRemove.Text = "Remove category";
            }
            else
            {
                mRemove.Text = "Remove rule";
            }
            treeList1.SetFocusedNode(_HitInfo.Node);

            if (e.Button == System.Windows.Forms.MouseButtons.Left)
            {
                treeList1.DoDragDrop(_CurrentCategory, DragDropEffects.Move);
            }
        }
        /// <summary>
        /// Inits this instance.
        /// </summary>
        public void Initialize()
        {
            var categories = new CategoryTree();

            DropCategory.DataSource = categories.GetCategoryTreeByProjectId(ProjectId);
            DropCategory.DataBind();
        }
Beispiel #4
0
 private void mRemove_Click(object sender, EventArgs e)
 {
     if (_CurrentCategory.IsCategory == false)
     {
         //Obtengo el padre
         _ParentFwkCategory = _CategoryTreeList.Where(p => p.Id.Equals(_CurrentCategory.ParentId)).FirstOrDefault <CategoryTree>();
         _ParentFwkCategory.RemoveRule(_CurrentCategory.Name);
         _CategoryTreeList.RemoveItem(_CurrentCategory.Id);//No es necesario ya que se ejecurara luego --> PopulateAsync
         try
         {
             FwkMembership.CreateRuleInCategory(_ParentFwkCategory.FwkCategory, frmAdmin.Provider.Name);
             MessageViewInfo.Show("Rule was successfully removed from category");
             PopulateAsync();
         }
         catch (Exception ex)
         { throw ex; }
     }
     else
     {
         DialogResult r = MessageBox.Show("Will have to delete the category and recursively all its subcategories", "Rules mannager", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
         if (r == DialogResult.Yes)
         {
             try
             {
                 FwkMembership.RemoveCategory(_CurrentCategory.FwkCategory.CategoryId, frmAdmin.Provider.Name);
                 MessageViewInfo.Show("Category was successfully removed ");
                 PopulateAsync();
             }
             catch (Exception ex)
             { throw ex; }
         }
     }
 }
Beispiel #5
0
        /// <summary>
        /// Creates an RSS news feed for Issues By category
        /// </summary>
        /// <param name="feed">The feed.</param>
        private void CategoryFeed(ref SyndicationFeed feed)
        {
            var             objComps = new CategoryTree();
            List <Category> al       = objComps.GetCategoryTreeByProjectId(_projectId);

            var     feedItems = new List <SyndicationItem>();
            Project p         = ProjectManager.GetById(_projectId);

            foreach (Category c in al)
            {
                var item = new SyndicationItem();

                item.Title = SyndicationContent.CreatePlaintextContent(c.Name);
                item.Links.Add(
                    SyndicationLink.CreateAlternateLink(
                        new Uri(
                            GetFullyQualifiedUrl(string.Format("~/Issues/IssueList.aspx?pid={0}&c={1}", _projectId,
                                                               c.Id)))));
                item.Summary =
                    SyndicationContent.CreatePlaintextContent(
                        string.Format(GetLocalResourceObject("OpenIssues").ToString(), IssueManager.GetCountByProjectAndCategoryId(_projectId, c.Id)));
                item.PublishDate = DateTime.Now;
                // Add the item to the feed
                feedItems.Add(item);
            }
            feed.Title =
                SyndicationContent.CreatePlaintextContent(
                    string.Format(GetLocalResourceObject("IssuesByCategoryTitle").ToString(), p.Name));
            feed.Description =
                SyndicationContent.CreatePlaintextContent(
                    string.Format(GetLocalResourceObject("IssuesByCategoryDescription").ToString(), p.Name));
            feed.Items = feedItems;
        }
Beispiel #6
0
        public List <CategorySummary> MainCategories()
        {
            var availableCategories = GetAvailableCategories();
            var mainCategories      = availableCategories.Where(x => x.ParentCategoryId == null).ToList();
            var expenses            = context.Expenses.Where(x => x.UserId == userId && x.Date >= dateFrom && x.Date <= dateTo).ToList();

            List <CategorySummary> categorySummaries = new List <CategorySummary>();

            foreach (var item in mainCategories)
            {
                CategoryTree tree                  = new CategoryTree(item.Id, availableCategories);
                var          catAndSubcatsIds      = tree.Root.ToList().Select(x => x.Id).ToList();                         //id of main category and id of all subcategories of main category
                var          catAndSubcatsExpenses = expenses.Where(x => catAndSubcatsIds.Contains(x.CategoryId)).ToList(); //expenses in main category and in all subcategories of main category

                if (catAndSubcatsExpenses.Count() == 0)
                {
                    continue;
                }

                CategorySummary summary = new CategorySummary(tree.Root, catAndSubcatsExpenses);

                categorySummaries.Add(summary);
            }

            categorySummaries = categorySummaries.OrderByDescending(x => x.ExpensesCost).ToList();

            return(categorySummaries);
        }
        public CategoryTreesGridViewModel <SiteSettingCategoryTreeViewModel> Execute(CategoryTreesFilter request)
        {
            request.SetDefaultSortingOptions("Title");

            CategoryTree alias = null;
            SiteSettingCategoryTreeViewModel modelAlias = null;

            var query = UnitOfWork.Session.QueryOver(() => alias).Where(() => !alias.IsDeleted);

            if (!string.IsNullOrWhiteSpace(request.SearchQuery))
            {
                var searchQuery = string.Format("%{0}%", request.SearchQuery);
                query = query.Where(Restrictions.Disjunction().Add(Restrictions.InsensitiveLike(NHibernate.Criterion.Projections.Property(() => alias.Title), searchQuery)));
            }

            query =
                query.SelectList(
                    select =>
                    select.Select(() => alias.Id)
                    .WithAlias(() => modelAlias.Id)
                    .Select(() => alias.Version)
                    .WithAlias(() => modelAlias.Version)
                    .Select(() => alias.Title)
                    .WithAlias(() => modelAlias.Title)).TransformUsing(Transformers.AliasToBean <SiteSettingCategoryTreeViewModel>());

            var count = query.ToRowCountFutureValue();

            var sitemaps = query.AddSortingAndPaging(request).Future <SiteSettingCategoryTreeViewModel>();

            return(new CategoryTreesGridViewModel <SiteSettingCategoryTreeViewModel>(sitemaps.ToList(), request, count.Value));
        }
        public void Init()
        {
            // Arrange
            var categoryRepo = new CategoryRepository();

            _categoryTree = categoryRepo.GetCategoryTree();
        }
        private static void createTestData()
        {
            //var prod = new Product() { Name = "TestProduct", Price = 10.0, Store = new Store() { Name = "TestStore" } };
            //var prodGroup = new ProductGroup() { Name = "TestGroup", Products = new List<Product>() { prod } };


            var subCategory1 = new Category()
            {
                Name = "SubCategory1"
            };
            var subCategory2 = new Category()
            {
                Name = "SubCategory2"
            };
            var root = new Category()
            {
                Name = "Root", SubCategories = new List <Category>()
                {
                    subCategory1, subCategory2
                }
            };

            _testData = new CategoryTree()
            {
                Root = root
            };
        }
        public GetCategoryTreeResponse Get(GetCategoryTreeRequest request)
        {
            var          response = new GetCategoryTreeResponse();
            CategoryTree alias    = null;

            var query = Repository.AsQueryOver(() => alias).Where(() => !alias.IsDeleted);

            if (!string.IsNullOrWhiteSpace(request.SearchQuery))
            {
                var searchQuery = string.Format("%{0}%", request.SearchQuery);
                query =
                    query.Where(Restrictions.Disjunction().Add(Restrictions.InsensitiveLike(NHibernate.Criterion.Projections.Property(() => alias.Title), searchQuery)));
            }

            if (request.WithOrder)
            {
                query = query.AddOrder(request);
            }

            if (request.WithPaging)
            {
                query = query.AddPaging(request);
            }

            response.Items      = query.AddSortingAndPaging(request).Future <CategoryTree>();
            response.TotalCount = query.ToRowCountFutureValue().Value;
            return(response);
        }
        void BindOptions()
        {
            CategoryTree objCats = new CategoryTree();

            dropCats.DataSource = objCats.GetCategoryTreeByProjectId(ProjectId);
            dropCats.DataBind();

            ITUserCollection colUsers = ITUser.GetUsersByProjectId(ProjectId);

            dropAssigned.DataSource = colUsers;
            dropAssigned.DataBind();

            dropOwned.DataSource = colUsers;
            dropOwned.DataBind();

            dropStatus.DataSource = Status.GetStatusByProjectId(ProjectId);
            dropStatus.DataBind();

            dropPriority.DataSource = Priority.GetPrioritiesByProjectId(ProjectId);
            dropPriority.DataBind();


            dropMilestone.DataSource = Milestone.GetMilestoneByProjectId(ProjectId);
            dropMilestone.DataBind();

            lblDateCreated.Text = DateTime.Now.ToString("f");
        }
Beispiel #12
0
 private void CategoryTree_MouseDown(object sender, MouseEventArgs e)
 {
     if (e.Button == MouseButtons.Right)
     {
         CategoryTree.SelectedNode = CategoryTree.GetNodeAt(new Point(e.X, e.Y));
     }
 }
        private void SaveCategoryTreeNodes(CategoryTree categoryTree,
                                           IEnumerable <CategoryNodeModel> categories,
                                           Category parentCategory,
                                           ICollection <Category> existingCategories,
                                           IList <Category> createdCategories,
                                           IList <Category> updatedCategories)
        {
            if (categories == null)
            {
                return;
            }

            foreach (var categoryNodeModel in categories)
            {
                bool updatedInDB;
                var  category = CategoryNodeService.SaveCategory(out updatedInDB, categoryTree, categoryNodeModel, parentCategory, existingCategories);

                if (categoryNodeModel.Id.HasDefaultValue() && updatedInDB)
                {
                    createdCategories.Add(category);
                }
                else if (updatedInDB)
                {
                    updatedCategories.Add(category);
                }
                var existingCategory = existingCategories.FirstOrDefault(c => c.Id == categoryNodeModel.Id);
                if (existingCategory != null)
                {
                    existingCategories.Remove(existingCategory);
                }

                SaveCategoryTreeNodes(categoryTree, categoryNodeModel.ChildNodes, category, existingCategories, createdCategories, updatedCategories);
            }
        }
Beispiel #14
0
        public IActionResult GetCategoryAndSubcategories(int?id, int page = 1)
        {
            Category current;

            var tree = new CategoryTree(db.Category);

            if (id == null)
            {
                current = null;
            }
            else
            {
                current = tree.FindCategoryNode(id.Value)?.Category;
                if (current == null)
                {
                    return(View("NotFound"));
                }
            }

            var subtrees = tree.Subtrees(id).ToList();
            var products = ShowProductsInCategory(tree, id, page);

            return(View(new CategoryViewModel()
            {
                CategoryPath = tree.FindPath(current),
                Subtrees = subtrees,
                Products = products,
            }));
        }
Beispiel #15
0
        void BindCategories()
        {
            CategoryTree objCats = new CategoryTree();

            dropCats.DataSource = objCats.GetCategoryTreeByProjectId(ProjectId);
            dropCats.DataBind();
        }
        private CategoryTreeNode createNode(string key, object node)
        {
            var    keys = key.Split(';');
            string name = keys[0];
            Uri    icon = null;

            if (keys.Length > 1)
            {
                icon = new Uri("/Assets/Categories/" + keys[1], UriKind.Relative);
            }

            if (node is CategoryTree)
            {
                CategoryTree root = node as CategoryTree;
                return(new CategoryTreeInnerNode
                {
                    Name = name,
                    Icon = icon,
                    Children = root.Select(x => createNode(x.Key, x.Value)).ToList()
                });
            }
            else
            {
                return(new CategoryTreeLeaf
                {
                    Name = name,
                    Icon = icon,
                    RouteSelector = node as RouteSelector
                });
            }
        }
        public IFutureValue <int> CheckIsUsed(IRepository repository, CategoryTree categoryTree)
        {
            var query = repository.AsQueryable <WidgetCategory>().Where(ec => ec.Category.CategoryTree == categoryTree &&
                                                                        !ec.Widget.IsDeleted &&
                                                                        (ec.Widget.Status == ContentStatus.Draft || ec.Widget.Status == ContentStatus.Published)).ToRowCountFutureValue();

            return(query);
        }
Beispiel #18
0
 public System.Collections.IEnumerable Enumerate(CommerceInstance instance, CultureInfo culture)
 {
     foreach (var data in new BatchedQuery <Product>(Query(instance), 1000))
     {
         var product = data as Product;
         yield return(ProductModel.Create(product, culture, CategoryTree.Get(instance.Name)));
     }
 }
        public IFutureValue<int> CheckIsUsed(IRepository repository, CategoryTree categoryTree)
        {
            var query = repository.AsQueryable<WidgetCategory>().Where(ec => ec.Category.CategoryTree == categoryTree
            && !ec.Widget.IsDeleted
            && (ec.Widget.Status == ContentStatus.Draft || ec.Widget.Status == ContentStatus.Published)).ToRowCountFutureValue();

            return query;
        }
        public async Task Consume(ConsumeContext <CreateCategoryTree> context)
        {
            var tree = new CategoryTree(context.Message.Id, userId: context.Message.UserId, nodes: context.Message.Nodes);

            await _session.Add(tree);

            await _session.Commit();
        }
Beispiel #21
0
 private void Index(Product product, IEnumerable <CultureInfo> cultures)
 {
     foreach (var culture in cultures)
     {
         var indexer = IndexStores.Get <ProductModel>(CommerceInstance.Current.Name, culture);
         indexer.Index(ProductModel.Create(product, culture, CategoryTree.Get(CommerceInstance.Current.Name)));
         indexer.Commit();
     }
 }
        public IActionResult Index()
        {
            string path = _configuration["WebApiUrl"].ToString() + "api/Product";

            string json = RequestHelper.Get(path);

            var products = JsonConvert.DeserializeObject <List <BillOfMaterials.Web.Models.Product> >(json);

            List <ProductTree> productTreeList = new List <ProductTree>();

            foreach (var product in products)
            {
                List <CategoryTree> mainCategoryTreeList = new List <CategoryTree>();

                foreach (var category in product.categories)
                {
                    string path2 = _configuration["WebApiUrl"].ToString() + "api/Product/" + category.id.ToString();

                    string json2 = RequestHelper.Get(path2);

                    var subcategories = JsonConvert.DeserializeObject <List <SubCategory> >(json2);

                    List <CategoryTree> categoryTreeList = new List <CategoryTree>();
                    foreach (var subcategory in subcategories)
                    {
                        CategoryTree categoryTree = new CategoryTree()
                        {
                            id         = subcategory.id,
                            name       = subcategory.name,
                            categories = new List <CategoryTree>()
                        };

                        categoryTreeList.Add(categoryTree);
                    }

                    CategoryTree mainCategoryTree = new CategoryTree()
                    {
                        id         = category.id,
                        name       = category.name,
                        categories = categoryTreeList
                    };

                    mainCategoryTreeList.Add(mainCategoryTree);
                }

                ProductTree tree = new ProductTree()
                {
                    id         = product.id,
                    name       = product.name,
                    categories = mainCategoryTreeList
                };

                productTreeList.Add(tree);
            }

            return(new JsonResult(productTreeList));
        }
 private void PrepareEditor(CategoryEditorModel model)
 {
     ViewBag.ParentPath = "None".Localize();
     if (model.ParentId != null)
     {
         var parent = CategoryTree.Get(CurrentInstance.Name).Find(model.ParentId.Value);
         ViewBag.ParentPath = String.Join(" >> ", parent.PathFromRoot().Select(c => c.Name));
     }
 }
Beispiel #24
0
        public CategoryTree CreateNewCategoryTree()
        {
            var entity = new CategoryTree();

            PopulateBaseFields(entity);

            entity.Title      = ProvideRandomString(MaxLength.Name);
            entity.Categories = new List <Category>();

            return(entity);
        }
Beispiel #25
0
        public List <CategoryTree> GetCategoryTrees()
        {
            var categories = GetCategoryList();
            var list       = new List <CategoryTree>();

            foreach (var cat in categories.Where(c => c.ParentCategoryID == null))
            {
                list.Add(CategoryTree.GenerateTree(cat));
            }
            return(list);
        }
Beispiel #26
0
        public IActionResult Categories()
        {
            var tree = new CategoryTree(db.Category);

            var subtrees = tree.Subtrees(null).ToList();

            return(View(new CategoryViewModel()
            {
                CategoryPath = tree.FindPath(null),
                Subtrees = subtrees
            }));
        }
Beispiel #27
0
        public (CategoryExpensesSummary summary, List <Categories> availableCategories, Categories selectedCategory) CategoryExpenses(int categoryId)
        {
            Categories        selectedCategory    = context.Categories.First(x => x.Id == categoryId);
            List <Categories> availableCategories = GetAvailableCategories();
            CategoryTree      categoryTree        = new CategoryTree(categoryId, availableCategories);
            List <int>        idOfCatWithSubcats  = categoryTree.Root.ToList().Select(x => x.Id).ToList();
            List <Expenses>   expenses            = context.Expenses.Where(x => x.UserId == userId && idOfCatWithSubcats.Contains(x.CategoryId) && x.Date >= dateFrom && x.Date <= dateTo).ToList();
            List <Units>      allUnits            = context.Units.ToList();

            CategoryExpensesSummary summary = new CategoryExpensesSummary(categoryId, expenses, allUnits);

            return(summary, availableCategories, selectedCategory);
        }
        private List <BlogPost> GetFakeBlogPosts()
        {
            var blog = new BlogPost
            {
                Id     = Guid.NewGuid(),
                Author = new Author {
                    Id = Guid.NewGuid(), Name = "Test Author"
                },
                PageUrl      = "/test/url/",
                Title        = "Test title",
                MetaTitle    = "Test Meta Title",
                CreatedOn    = new DateTime(2012, 10, 9),
                ModifiedOn   = new DateTime(2012, 10, 15),
                Description  = "Intro Text",
                PageContents =
                    new List <PageContent>
                {
                    new PageContent {
                        Content = new BlogPostContent {
                            Html = "Unpbulished content <p>with HTML</p>"
                        }
                    },
                    new PageContent {
                        Content = new BlogPostContent {
                            Html = "Test content <p>with HTML</p>", Status = ContentStatus.Published
                        }
                    }
                }
            };
            var categoryTree = new CategoryTree {
                Title = "Test Category Tree"
            };
            var category = new Category {
                Id = Guid.NewGuid(), Name = "Test Category", CategoryTree = categoryTree
            };

            category.CategoryTree = categoryTree;
            var pageCategory = new PageCategory {
                Category = category, Page = blog
            };

            categoryTree.Categories = new List <Category> {
                pageCategory.Category
            };
            blog.Categories = new List <PageCategory> {
                pageCategory
            };
            return(new List <BlogPost> {
                blog
            });
        }
Beispiel #29
0
        public Category CreateNewCategory(CategoryTree tree)
        {
            var entity = new Category();

            PopulateBaseFields(entity);

            entity.Name = ProvideRandomString(MaxLength.Name);

            entity.CategoryTree = tree;

            tree.Categories.Add(entity);

            return(entity);
        }
Beispiel #30
0
 private static void AddChildernForNode(HMO_PROGECTEntities db, CategoryTree categoryTree, List <CATEGORIES_TBL> allCategoriesList)
 {
     foreach (var item in allCategoriesList.Where(i => i.parentCategory == categoryTree.id).ToList())
     {
         var category = new CategoryTree()
         {
             id       = item.categoriesId,
             name     = item.categoryName,
             children = new List <CategoryTree>()
         };
         AddChildernForNode(db, category, allCategoriesList);
         categoryTree.children.Add(category);
     }
 }
        /// <summary>
        /// Binds the options.
        /// </summary>
        private void BindOptions()
        {
            List <ITUser> users = UserManager.GetUsersByProjectId(ProjectId, true);

            //Get Type
            DropIssueType.DataSource = IssueTypeManager.GetByProjectId(ProjectId);
            DropIssueType.DataBind();

            //Get Priority
            DropPriority.DataSource = PriorityManager.GetByProjectId(ProjectId);
            DropPriority.DataBind();

            //Get Resolutions
            DropResolution.DataSource = ResolutionManager.GetByProjectId(ProjectId);
            DropResolution.DataBind();

            //Get categories
            var categories = new CategoryTree();

            DropCategory.DataSource = categories.GetCategoryTreeByProjectId(ProjectId);
            DropCategory.DataBind();

            //Get milestones
            DropMilestone.DataSource = MilestoneManager.GetByProjectId(ProjectId);
            DropMilestone.DataBind();

            DropAffectedMilestone.DataSource = MilestoneManager.GetByProjectId(ProjectId);
            DropAffectedMilestone.DataBind();

            //Get Users
            DropAssignedTo.DataSource = users;
            DropAssignedTo.DataBind();

            DropOwned.DataSource = users;
            DropOwned.DataBind();

            DropStatus.DataSource = StatusManager.GetByProjectId(ProjectId);
            DropStatus.DataBind();

            lblDateCreated.Text  = DateTime.Now.ToString("f");
            lblLastModified.Text = DateTime.Now.ToString("f");

            if (!User.Identity.IsAuthenticated)
            {
                return;
            }

            lblReporter.Text       = Security.GetDisplayName();
            lblLastUpdateUser.Text = Security.GetDisplayName();
        }
        public CategoryTree Save(SaveCategoryTreeRequest request)
        {
            IList<Category> createdCategories = new List<Category>();

            IList<Category> updatedCategories = new List<Category>();

            IList<Category> deletedCategories = new List<Category>();

            var createNew = request.Id.HasDefaultValue();

            var selectedCategorizableItemsFuture = Repository.AsQueryable<CategoryTreeCategorizableItem>()
                .Where(i => i.CategoryTree.Id == request.Id)
                .ToFuture();

            IEnumerable<Category> existingCategories;
            CategoryTree categoryTree;
            if (createNew)
            {
                existingCategories = new List<Category>();
                categoryTree = new CategoryTree();
            }
            else
            {
                existingCategories = Repository.AsQueryable<Category>().Where(node => node.CategoryTree.Id == request.Id).ToFuture();
                categoryTree = Repository.AsQueryable<CategoryTree>().Where(s => s.Id == request.Id).ToFuture().First();
            }

            List<CategoryTreeCategorizableItem> itemsToRemove = null;
            List<Guid> itemsToAdd = null;
            if (request.UseForCategorizableItems != null)
            {
                var selectedItems = selectedCategorizableItemsFuture.ToList();
                itemsToRemove = selectedItems.Where(s => !request.UseForCategorizableItems.Exists(c => c == s.CategorizableItem.Id)).ToList();
                if (!createNew)
                {
                    foreach (var categoryTreeCategorizableItem in itemsToRemove)
                    {
                        var categorizableItemName = categoryTreeCategorizableItem.CategorizableItem.Name;
                        var accessor = CategoryAccessors.Accessors.First(ca => ca.Name == categorizableItemName);
                        if (accessor.CheckIsUsed(Repository, categoryTree).Value > 0)
                        {
                            throw new CmsException("Cannot deselect categorizable items that have usages");
                        }
                    }
                }
                itemsToAdd = request.UseForCategorizableItems.Where(id => !selectedItems.Exists(s => s.CategorizableItem.Id == id)).ToList();
            }

            UnitOfWork.BeginTransaction();

            categoryTree.Title = request.Title;
            categoryTree.Version = request.Version;
            categoryTree.Macro = request.Macro;

            Repository.Save(categoryTree);

            if (itemsToRemove != null)
            {
                itemsToRemove.ForEach(Repository.Delete);
                itemsToAdd.ForEach(
                    id =>
                    Repository.Save(new CategoryTreeCategorizableItem { CategoryTree = categoryTree, CategorizableItem = Repository.AsProxy<CategorizableItem>(id) }));
            }

            var existingCategoryList = existingCategories.ToList();
            SaveCategoryTreeNodes(categoryTree, request.RootNodes, null, existingCategoryList, createdCategories, updatedCategories);

            foreach (var category in existingCategoryList)
            {
                CategoryNodeService.DeleteRelations(category);
                Repository.Delete(category);
                deletedCategories.Add(category);
            }

            UnitOfWork.Commit();

            foreach (var category in createdCategories)
            {
                RootEvents.Instance.OnCategoryCreated(category);
            }

            foreach (var category in updatedCategories)
            {
                RootEvents.Instance.OnCategoryUpdated(category);
            }

            foreach (var category in deletedCategories)
            {
                RootEvents.Instance.OnCategoryDeleted(category);
            }

            if (createNew)
            {
                RootEvents.Instance.OnCategoryTreeCreated(categoryTree);
            }
            else
            {
                RootEvents.Instance.OnCategoryTreeUpdated(categoryTree);
            }

            return categoryTree;
        }
        private void SaveCategoryTreeNodes(CategoryTree categoryTree, 
            IEnumerable<CategoryNodeModel> categories, 
            Category parentCategory, 
            ICollection<Category> existingCategories, 
            IList<Category> createdCategories,
            IList<Category> updatedCategories)
        {
            if (categories == null)
            {
                return;
            }

            foreach (var categoryNodeModel in categories)
            {
                bool updatedInDB;
                var category = CategoryNodeService.SaveCategory(out updatedInDB, categoryTree, categoryNodeModel, parentCategory, existingCategories);

                if (categoryNodeModel.Id.HasDefaultValue() && updatedInDB)
                {
                    createdCategories.Add(category);
                }
                else if (updatedInDB)
                {
                    updatedCategories.Add(category);
                }
                var existingCategory = existingCategories.FirstOrDefault(c => c.Id == categoryNodeModel.Id);
                if (existingCategory != null)
                {
                    existingCategories.Remove(existingCategory);
                }

                SaveCategoryTreeNodes(categoryTree, categoryNodeModel.ChildNodes, category, existingCategories, createdCategories, updatedCategories);
            }
        }
        public Category SaveCategory(
            out bool categoryUpdated,
            CategoryTree categoryTree,
            CategoryNodeModel categoryNodeModel,
            Category parentCategory,
            IEnumerable<Category> categories = null)
        {
            categoryUpdated = false;

            Category category = null;
            if (categoryNodeModel.Id.HasDefaultValue())
            {
                category = new Category();
            }
            else
            {
                if (categories != null)
                {
                    category = categories.FirstOrDefault(c => c.Id == categoryNodeModel.Id);
                }
                if (category == null)
                {
                    category = Repository.First<Category>(categoryNodeModel.Id);
                }
            }

            var updated = false;
            if (category.CategoryTree == null)
            {
                category.CategoryTree = categoryTree;
            }

            if (category.Name != categoryNodeModel.Title)
            {
                updated = true;
                category.Name = categoryNodeModel.Title;
            }

            if (category.DisplayOrder != categoryNodeModel.DisplayOrder)
            {
                updated = true;
                category.DisplayOrder = categoryNodeModel.DisplayOrder;
            }

            if (category.ParentCategory != parentCategory)
            {
                updated = true;
                category.ParentCategory = parentCategory;
            }

            if (cmsConfiguration.EnableMacros && category.Macro != categoryNodeModel.Macro)
            {
                category.Macro = categoryNodeModel.Macro;
                updated = true;
            }

            if (updated)
            {
                category.Version = categoryNodeModel.Version;
                Repository.Save(category);
                categoryUpdated = true;
            }

            return category;
        }
 private List<BlogPost> GetFakeBlogPosts()
 {
     var blog = new BlogPost
     {
         Id = Guid.NewGuid(),
         Author = new Author { Id = Guid.NewGuid(), Name = "Test Author" },
         PageUrl = "/test/url/",
         Title = "Test title",
         MetaTitle = "Test Meta Title",
         CreatedOn = new DateTime(2012, 10, 9),
         ModifiedOn = new DateTime(2012, 10, 15),
         Description = "Intro Text",
         PageContents =
             new List<PageContent>
             {
                 new PageContent { Content = new BlogPostContent { Html = "Unpbulished content <p>with HTML</p>" } },
                 new PageContent { Content = new BlogPostContent { Html = "Test content <p>with HTML</p>", Status = ContentStatus.Published } }
             }
     };
     var categoryTree = new CategoryTree { Title = "Test Category Tree" };
     var category = new Category { Id = Guid.NewGuid(), Name = "Test Category", CategoryTree = categoryTree };
     category.CategoryTree = categoryTree;
     var pageCategory = new PageCategory { Category = category, Page = blog };
     categoryTree.Categories = new List<Category> { pageCategory.Category };
     blog.Categories = new List<PageCategory> { pageCategory };
     return new List<BlogPost> { blog };
 }
Beispiel #36
0
        private void treeList1_DragDrop(object sender, DragEventArgs e)
        {
            FwkAuthorizationRule rule = null;
            CategoryTree wCategoryTree_ToMove = null;
            TreeListHitInfo wHitInfo = treeList1.CalcHitInfo(treeList1.PointToClient(new Point(e.X, e.Y)));
            if (wHitInfo.Node == null)
                return;

            rule = e.Data.GetData(typeof(FwkAuthorizationRule)) as FwkAuthorizationRule;

            if (rule == null)
            {
                wCategoryTree_ToMove = e.Data.GetData(typeof(CategoryTree)) as CategoryTree;
            }
            //List<FwkAuthorizationRule> wRuleList = e.Data.GetData(typeof(List<FwkAuthorizationRule>)) as List<FwkAuthorizationRule>;
            //FwkAuthorizationRule rule = e.Data.GetData(typeof(FwkAuthorizationRule)) as FwkAuthorizationRule;
            #region Move rule
            if (rule != null)
            {

                _CurrentCategory = (CategoryTree)treeList1.GetDataRecordByNode(wHitInfo.Node);
                lblCurrentCategory.Text = _CurrentCategory.Name;
                if (_CurrentCategory.IsCategory == false)
                {
                    //Obtengo el padre
                    _ParentFwkCategory = _CategoryTreeList.Where(p => p.Id.Equals(_CurrentCategory.ParentId)).FirstOrDefault<CategoryTree>();
                    _CurrentCategory = _ParentFwkCategory;
                }

                #region Add Rules to Category

                if (!_CurrentCategory.AnyRule(rule.Name))
                {

                    _CurrentCategory.AddRule(rule);
                    FwkMembership.CreateRuleInCategory(_CurrentCategory.FwkCategory, frmAdmin.Provider.Name);
                }

                #endregion

                PopulateAsync();
            }

            #endregion


            if (wCategoryTree_ToMove != null)
            {
                if (wCategoryTree_ToMove.Id == _CurrentCategory.Id)
                {
                    Cursor = Cursors.Default;
                    return;
                }

                #region Mueve una categoria
                if (wCategoryTree_ToMove.IsCategory)
                {
                    if (_CurrentCategory.IsCategory == false)
                    {
                        //Obtengo el padre de la categoria destino 
                        _ParentFwkCategory = _CategoryTreeList.Where(p => p.Id.Equals(_CurrentCategory.ParentId)).FirstOrDefault<CategoryTree>();
                        _CurrentCategory = _ParentFwkCategory;
                    }
                    if (wCategoryTree_ToMove.ParentId == _CurrentCategory.Id)
                    {
                        Cursor = Cursors.Default;
                        return;
                    }

                    FwkMembership.UpdateParentCategory(
                        wCategoryTree_ToMove.FwkCategory.CategoryId,
                        wCategoryTree_ToMove.FwkCategory.ParentId.Value,
                        _CurrentCategory.FwkCategory.CategoryId,
                        frmAdmin.Provider.Name);
                }
                #endregion

                #region Mueve una regla a otra categoria
                if (wCategoryTree_ToMove.IsCategory == false)
                {
                    if (_CurrentCategory.IsCategory == false)
                    {
                        //Obtengo el padre de la categoria destino 
                        _CurrentCategory = _CategoryTreeList.Where(p => p.Id.Equals(_CurrentCategory.ParentId)).FirstOrDefault<CategoryTree>();

                    }
                    if (wCategoryTree_ToMove.ParentId == _CurrentCategory.Id)
                    {
                        Cursor = Cursors.Default;
                        return;
                    }

                    if (!_CurrentCategory.AnyRule(wCategoryTree_ToMove.Name))
                    {

                        _CurrentCategory.AddRule(wCategoryTree_ToMove.FwkAuthorizationRule);
                        FwkMembership.CreateRuleInCategory(_CurrentCategory.FwkCategory, frmAdmin.Provider.Name);

                        //Obtengo el padre de la regla a mover para eliminarle la regla
                        _ParentFwkCategory = _CategoryTreeList.Where(p => p.Id.Equals(wCategoryTree_ToMove.ParentId)).FirstOrDefault<CategoryTree>();
                        _ParentFwkCategory.RemoveRule(wCategoryTree_ToMove.Name);
                        FwkMembership.CreateRuleInCategory(_ParentFwkCategory.FwkCategory, frmAdmin.Provider.Name);

                    }


                }
                #endregion

                PopulateAsync();
            }
            Cursor = Cursors.Default;
        }
 public IFutureValue<int> CheckIsUsed(IRepository repository, CategoryTree categoryTree)
 {
     var query = repository.AsQueryable<PageCategory>().Where(p => p.Page is BlogPost && p.Category.CategoryTree == categoryTree);
     return query.ToRowCountFutureValue();
 }
Beispiel #38
0
        private void mRemove_Click(object sender, EventArgs e)
        {
            if (_CurrentCategory.IsCategory == false)
            {
                //Obtengo el padre
                _ParentFwkCategory = _CategoryTreeList.Where(p => p.Id.Equals(_CurrentCategory.ParentId)).FirstOrDefault<CategoryTree>();
                _ParentFwkCategory.RemoveRule(_CurrentCategory.Name);
                _CategoryTreeList.RemoveItem(_CurrentCategory.Id);//No es necesario ya que se ejecurara luego --> PopulateAsync
                try
                {
                    FwkMembership.CreateRuleInCategory(_ParentFwkCategory.FwkCategory, frmAdmin.Provider.Name);
                    MessageViewInfo.Show("Rule was successfully removed from category");
                    PopulateAsync();
                }
                catch (Exception ex)
                { throw ex; }
            }
            else
            {
                DialogResult r = MessageBox.Show("Will have to delete the category and recursively all its subcategories", "Rules mannager", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (r == DialogResult.Yes)
                {
                    try
                    {
                        FwkMembership.RemoveCategory(_CurrentCategory.FwkCategory.CategoryId, frmAdmin.Provider.Name);
                        MessageViewInfo.Show("Category was successfully removed ");
                        PopulateAsync();
                    }
                    catch (Exception ex)
                    { throw ex; }
                }

            }
        }
        private IDictionary<string, Guid> ImportCategories(BlogMLBlog.CategoryCollection categories, 
                                                           IEnumerable<BlogMLPost> blogs,
                                                           ref List<CategoryTree> newCategoriesTreeList,
                                                           ref List<Category> newCategoriesList, 
                                                           bool ReuseExistingCategories, 
                                                           bool RecreateCategoryTree)
        {
            var dictionary = new Dictionary<string, Guid>();
            if (categories.Count == 0)
            {
                // old export method when only categories ids are exported
                var oldExistingCategoriesIds = new List<Guid>();
                blogs.Select(t => t.Categories).ForEach(
                    t =>
                    {
                        for (int i = 0; i < t.Count; i++)
                        {
                            Guid parsedGuid;
                            if (Guid.TryParse(t[i].Ref, out parsedGuid) && !oldExistingCategoriesIds.Contains(parsedGuid))
                            {
                                oldExistingCategoriesIds.Add(parsedGuid);
                            }
                        }
                    });
                oldExistingCategoriesIds = repository.AsQueryable<Category>().Where(t => oldExistingCategoriesIds.Contains(t.Id)).Select(t => t.Id).ToList();
                oldExistingCategoriesIds.ForEach(t => dictionary.Add(t.ToString(), t));
                return dictionary;
            }


            if (RecreateCategoryTree)
            {
                // sort categories that parents would be first
                for (int i = 0; i < categories.Count; i++)
                {
                    for (int j = 0; j < categories.Count; j++)
                    {
                        if (categories[i].ID == categories[j].ParentRef && i > j)
                        {
                            var tmp = categories[j];
                            categories[j] = categories[i];
                            categories[i] = tmp;
                        }
                    }
                }
                var newIdsForCategories = new Dictionary<string, Guid>();
                // regenerate new ids for category tree
                foreach (var category in categories)
                {
                    if (!newIdsForCategories.ContainsKey(category.ID))
                    {
                        newIdsForCategories.Add(category.ID, Guid.NewGuid());
                    }
                    if (!string.IsNullOrEmpty(category.ParentRef) && !newIdsForCategories.ContainsKey(category.ParentRef))
                    {
                        newIdsForCategories.Add(category.ParentRef, Guid.NewGuid());
                    }
                }
                foreach (var category in categories)
                {
                    category.ID = newIdsForCategories[category.ID].ToString();
                    if (!string.IsNullOrEmpty(category.ParentRef))
                    {
                        category.ParentRef = newIdsForCategories[category.ParentRef].ToString();
                    }
                }
                var refrencedCategoriesIds = new List<Guid>();
                foreach (var blog in blogs)
                {
                    for (int i = 0; i < blog.Categories.Count; i++)
                    {
                        var category = blog.Categories[i];
                        // it may be that category is deleted but it is still linked to blog and that link is not deleted
                        if (newIdsForCategories.ContainsKey(category.Ref))
                        {
                            var newCategoryId = newIdsForCategories[category.Ref];
                            category.Ref = newCategoryId.ToString();
                            refrencedCategoriesIds.Add(newCategoryId);
                        }
                    }
                }

                Guid testParseGuid;
                var oldIdsCategories = newIdsForCategories.Keys.Where(t => Guid.TryParse(t, out testParseGuid)).Select(t => new Guid(t)).ToList();
                var existingCategoriesIdsFuture = repository.AsQueryable<Category>().Select(t => t.Id).Where(t => oldIdsCategories.Contains(t)).ToFuture();
                var availableFor = repository.AsQueryable<CategorizableItem>().ToFuture().ToList();
                var existingCategoriesIds = existingCategoriesIdsFuture.ToList();

                // creates categories trees
                foreach (var categoryTree in categories.Where(c => string.IsNullOrEmpty(c.ParentRef)))
                {
                    var newTree = new CategoryTree
                    {
                        Title = categoryTree.Title,
                        CreatedOn = categoryTree.DateCreated,
                        ModifiedOn = categoryTree.DateModified,
                        Id = new Guid(categoryTree.ID)
                    };
                    newTree.AvailableFor = new List<CategoryTreeCategorizableItem>();
                    foreach (var categorizableItem in availableFor)
                    {
                        newTree.AvailableFor.Add(new CategoryTreeCategorizableItem { CategorizableItem = categorizableItem, CategoryTree = newTree });
                    }
                    newCategoriesTreeList.Add(newTree);
                }

                // create categories
                foreach (var category in categories.Where(t => !string.IsNullOrEmpty(t.ParentRef)))
                {
                    var categoryParentId = new Guid(category.ParentRef);
                    var newParentCategoryTree = newCategoriesTreeList.FirstOrDefault(t => t.Id == categoryParentId);
                    var newCategory = new Category
                    {
                        Name = category.Title,
                        CreatedOn = category.DateCreated,
                        ModifiedOn = category.DateModified,
                        Id = new Guid(category.ID),
                        CategoryTree = newParentCategoryTree
                    };
                    newCategoriesList.Add(newCategory);
                }

                // set references for category, category tree
                foreach (var category in newCategoriesList.Where(t => t.CategoryTree == null))
                {
                    category.CategoryTree = newCategoriesList.First(t => t.Id.ToString() == categories.First(c => c.ID == category.Id.ToString()).ParentRef).CategoryTree;
                }
                foreach (var tree in newCategoriesTreeList)
                {
                    tree.Categories = newCategoriesList.Where(t => t.CategoryTree != null && t.CategoryTree.Id == tree.Id).ToList();
                }
                foreach (var child in newCategoriesList)
                {
                    var parentId = new Guid(categories.First(t => t.ID == child.Id.ToString()).ParentRef);
                    var parentCategory = newCategoriesList.FirstOrDefault(t => t.Id == parentId);
                    if (parentCategory != null)
                    {
                        child.ParentCategory = parentCategory;
                        parentCategory.ChildCategories = parentCategory.ChildCategories ?? new List<Category>();
                        parentCategory.ChildCategories.Add(child);
                    }
                }

                // generate category for empty category tree
                foreach (var categoryTree in newCategoriesTreeList.Where(t => t.Categories != null && t.Categories.Count == 0))
                {
                    var category = new Category
                    {
                        Id = categoryTree.Id,
                        CreatedOn = categoryTree.CreatedOn,
                        ModifiedOn = categoryTree.ModifiedOn,
                        Name = categoryTree.Title,
                        CategoryTree = categoryTree
                    };
                    categoryTree.Id = Guid.NewGuid();
                    categoryTree.Categories.Add(category);
                    newCategoriesList.Add(category);
                }

                // removing referenced categories that they would not be saved and adding existing category id from db
                foreach (var existingCategoriesId in existingCategoriesIds)
                {
                    refrencedCategoriesIds.Remove(newIdsForCategories[existingCategoriesId.ToLowerInvariantString()]);
                    dictionary.Add(existingCategoriesId.ToString(), existingCategoriesId);
                    foreach (var blog in blogs)
                    {
                        for (int i = 0; i < blog.Categories.Count; i++)
                        {
                            if (blog.Categories[i].Ref == newIdsForCategories[existingCategoriesId.ToLowerInvariantString()].ToLowerInvariantString())
                            {
                                blog.Categories[i].Ref = existingCategoriesId.ToLowerInvariantString();
                            }
                        }
                    }
                }

                // filter, save only categories who are related to imported blogs
                newCategoriesTreeList = newCategoriesTreeList.Where(t => t.Categories.Any(z => refrencedCategoriesIds.Contains(z.Id))).ToList();
                newCategoriesList =
                    newCategoriesList.Where(t => t.CategoryTree != null && t.CategoryTree.Categories.Any(z => refrencedCategoriesIds.Contains(z.Id))).ToList();
                // save new records
                foreach (var category in newCategoriesList)
                {
                    dictionary.Add(category.Id.ToString(), category.Id);
                    unitOfWork.Session.Save(category);
                }
                foreach (var tree in newCategoriesTreeList)
                {
                    unitOfWork.Session.Save(tree);
                }
            } else if (ReuseExistingCategories)
            {
                // Get used categories names and ids (key id, value name)
                var catNames = new Dictionary<string, string>();
                foreach (var blog in blogs)
                {
                    for (int i = 0; i < blog.Categories.Count; i++)
                    {
                        var categoryId = blog.Categories[i].Ref;
                        if (!catNames.ContainsKey(categoryId) && blogs.Any(t => BlogHasCategory(t, categoryId)))
                        {
                            catNames.Add(categoryId, (categories.FirstOrDefault(t => t.ID == categoryId) ?? new BlogMLCategory()).Title);
                        }
                    }
                }

                var existingCategoriesByIdsFuture = repository.AsQueryable<Category>().Where(t => catNames.Keys.Contains(t.Id.ToString())).ToFuture();
                var existingCategoriesByNamesFuture = repository.AsQueryable<Category>().Where(t => catNames.Values.Contains(t.Name)).ToFuture();
                // Get categories by ids
                var existingCategoriesByIds = existingCategoriesByIdsFuture.ToList();
                // Get categories by names
                var existingCategoriesByNames = existingCategoriesByNamesFuture.ToList();
                foreach (var catName in catNames)
                {
                    var category = existingCategoriesByIds.FirstOrDefault(t => t.Id.ToLowerInvariantString() == catName.Key);
                    category = category ?? existingCategoriesByNames.FirstOrDefault(t => t.Name == catName.Value);
                    if (category != null)
                    {
                        dictionary.Add(catName.Key, category.Id);
                    }
                }
            }

            return dictionary;
        }
Beispiel #40
0
        private void treeList1_DragOver(object sender, DragEventArgs e)
        {

            TreeListHitInfo hi = treeList1.CalcHitInfo(treeList1.PointToClient(new Point(e.X, e.Y)));
            _CurrentCategory = (CategoryTree)treeList1.GetDataRecordByNode(hi.Node);
            if (_CurrentCategory == null)
                e.Effect = DragDropEffects.None;
            if (_CurrentCategory != null)
            {
                lblCurrentCategory.Text = _CurrentCategory.Name;

                e.Effect = DragDropEffects.Move;
            }


            SetDragCursor(DragDropEffects.Move);
        }
Beispiel #41
0
 public void AddToCategoryTrees(CategoryTree categoryTree)
 {
     base.AddObject("CategoryTrees", categoryTree);
 }
 public CategoryTreeData(IEnumerable<CategoryTree> categories, CategoryTree currentCategory)
 {
     _categories = categories;
     _current = currentCategory;
 }
Beispiel #43
0
 public static CategoryTree CreateCategoryTree(global::System.Guid ID)
 {
     CategoryTree categoryTree = new CategoryTree();
     categoryTree.Id = ID;
     return categoryTree;
 }
 public IFutureValue<int> CheckIsUsed(IRepository repository, CategoryTree categoryTree)
 {
     var query = repository.AsQueryable<MediaCategory>().Where(mc => mc.Media is MediaImage && mc.Category.CategoryTree == categoryTree && mc.Media.Original == null);
     return query.ToRowCountFutureValue();
 }
Beispiel #45
0
        private void treeList1_MouseDown(object sender, MouseEventArgs e)
        {

            _HitInfo = treeList1.CalcHitInfo(new Point(e.X, e.Y));
            if (_HitInfo.Node == null) return;
            _CurrentCategory = (CategoryTree)treeList1.GetDataRecordByNode(_HitInfo.Node);
            lblCurrentCategory.Text = _CurrentCategory.Name;

            mAddNewCategory.Enabled = _CurrentCategory.IsCategory;
            if (_CurrentCategory.IsCategory)
                mRemove.Text = "Remove category";
            else
                mRemove.Text = "Remove rule";
            treeList1.SetFocusedNode(_HitInfo.Node);

            if (e.Button == System.Windows.Forms.MouseButtons.Left)
            {

                treeList1.DoDragDrop(_CurrentCategory, DragDropEffects.Move);
            }
        }
 public IFutureValue<int> CheckIsUsed(IRepository repository, CategoryTree categoryTree)
 {
     return repository.AsQueryable<MediaCategory>().Where(m => m.Media is MediaFile && m.Category.CategoryTree == categoryTree && m.Media.Original == null).ToRowCountFutureValue();
 }
Beispiel #47
0
 private void addRootcategoryToolStripMenuItem_Click(object sender, EventArgs e)
 {
     using (frmAddName frm = new frmAddName())
     {
         if (frm.ShowDialog() == DialogResult.OK)
         {
             if (!string.IsNullOrEmpty(frm.Tag.ToString()))
                 if (FwkMembership.ExistCategory(frm.Tag.ToString().Trim(), 0, frmAdmin.Provider.Name))
                 {
                     MessageViewInfo.Show(string.Format("Category {0} already exist", frm.Tag.ToString()));
                     return;
                 }
                 else
                 {
                     _CurrentCategory = null;
                     Create_Categoty(frm.Tag.ToString());
                 }
         }
     }
 }