public BranchEditor(CategoryNode root)
        {
            InitializeComponent();

            this.root = root;
            nameBox.Focus();
            nodeListView.SetObjects(root.branches);
        }
Exemple #2
0
        public void CategoryNode_renames_itself()
        {
            // ARRANGE

            var category       = DefaultCategory();
            var parentCategory = DefaultCategory(WithSubCategory(category));

            this.ProviderContextMock
            .Setup(c => c.Persistence)
            .Returns(this.PersistenceMock.Object);

            this.PersistenceMock
            .Setup(m => m.Categories)
            .Returns(this.CategoryRepositoryMock.Object);

            Category?renamedCategory = null;

            this.CategoryRepositoryMock
            .Setup(r => r.Upsert(It.IsAny <Category>()))
            .Callback <Category>(c => renamedCategory = c)
            .Returns(category);

            this.CategoryRepositoryMock
            .Setup(r => r.FindByParentAndName(parentCategory, "cc"))
            .Returns((Category)null);

            this.PersistenceMock
            .Setup(p => p.Entities)
            .Returns(this.EntityRepositoryMock.Object);

            this.EntityRepositoryMock
            .Setup(p => p.FindByCategoryAndName(parentCategory, "cc"))
            .Returns((Entity?)null);

            var categoryNode = new CategoryNode(category);

            // ACT

            categoryNode.RenameItem(this.ProviderContextMock.Object, "c", "cc");

            // ASSERT

            Assert.Equal("cc", renamedCategory !.Name);
        }
    /// <summary>
    /// Renders tree specified by root node into supplied string builder.
    /// </summary>
    /// <param name="builder">String builder to render to.</param>
    /// <param name="root">Root of the rendered subtree.</param>
    private void RenderTree(StringBuilder builder, CategoryNode root)
    {
        bool itemStarted = false;

        // Render node title
        if ((root.Category != null) || (!string.IsNullOrEmpty(root.AlternativeText)))
        {
            builder.Append("<li class=\"CategoryListItem\">");
            itemStarted = true;

            if (root.Category != null)
            {
                builder.Append(CreateCategoryPartLink(root.Category));
            }
            else
            {
                builder.Append(FormatCategoryDisplayName(root.AlternativeText));
            }
        }

        // Recursively render child nodes
        if (root.Nodes.Count > 0)
        {
            if (itemStarted)
            {
                builder.AppendLine("<ul class=\"CategoryListList\">");
            }

            foreach (CategoryNode child in root.Nodes)
            {
                RenderTree(builder, child);
            }

            if (itemStarted)
            {
                builder.AppendLine("</ul>");
            }
        }

        if (itemStarted)
        {
            builder.Append("</li>");
        }
    }
Exemple #4
0
        public void CategoryNode_copying_fails_if_entity_name_already_exists(string initialName, string destinationName, string resultName)
        {
            // ARRANGE

            this.ArrangeSubCategory(out var rootCategory, out var subCategory);

            this.CategoryRepositoryMock
            .Setup(r => r.Root())
            .Returns(rootCategory);

            this.ProviderContextMock
            .Setup(p => p.Persistence)
            .Returns(this.PersistenceMock.Object);

            this.PersistenceMock
            .Setup(p => p.Categories)
            .Returns(this.CategoryRepositoryMock.Object);

            this.CategoryRepositoryMock
            .Setup(r => r.FindByParentAndName(rootCategory, resultName))
            .Returns((Category?)null);

            this.PersistenceMock
            .Setup(p => p.Entities)
            .Returns(this.EntityRepositoryMock.Object);

            this.EntityRepositoryMock
            .Setup(r => r.FindByCategoryAndName(rootCategory, resultName))
            .Returns(DefaultEntity(e => e.Name = resultName));

            var entitiesNode = new EntitiesNode();
            var category     = DefaultCategory(c => subCategory.AddSubCategory(c));
            var node         = new CategoryNode(category);

            // ACT

            var result = Assert.Throws <InvalidOperationException>(
                () => node.CopyItem(this.ProviderContextMock.Object, initialName, destinationName, entitiesNode));

            // ASSERT

            Assert.Equal($"Destination container contains already an entity with name '{resultName}'", result.Message);
        }
Exemple #5
0
 private void addCategoryToRepository(RepositoryNode repository)
 {
     try
     {
         foreach (CategoryInfo category in OfficeApplication.OfficeApplicationProxy.getCategories(repository.Repository.name))
         {
             CategoryNode categoryNode = new CategoryNode(category, repository.Repository);
             repository.Nodes.Add(categoryNode);
             if (category.childs > 0)
             {
                 TreeNode dummyNode = new DummyNode();
                 categoryNode.Nodes.Add(dummyNode);
             }
         }
     }
     catch
     {
     }
 }
Exemple #6
0
 private void addCategory(CategoryNode parentcategoryNode)
 {
     try
     {
         foreach (CategoryInfo category in OfficeApplication.OfficeApplicationProxy.getCategories(parentcategoryNode.Repository.name, parentcategoryNode.Category.UDDI))
         {
             CategoryNode categoryNode = new CategoryNode(category, parentcategoryNode.Repository);
             parentcategoryNode.Nodes.Add(categoryNode);
             if (category.childs > 0)
             {
                 TreeNode dummyNode = new DummyNode();
                 categoryNode.Nodes.Add(dummyNode);
             }
         }
     }
     catch
     {
     }
 }
        void PopulatePrototypeList()
        {
            RootCategory = new CategoryNode("", null);
            int count = 1;

            foreach (var prototype in PrototypeManager.EnumeratePrototypes <ConstructionPrototype>())
            {
                var currentNode = RootCategory;

                foreach (var category in prototype.CategorySegments)
                {
                    if (!currentNode.ChildCategories.TryGetValue(category, out var subNode))
                    {
                        count++;
                        subNode = new CategoryNode(category, currentNode);
                        currentNode.ChildCategories.Add(category, subNode);
                    }

                    currentNode = subNode;
                }

                currentNode.Prototypes.Add(prototype);
            }

            // Do a pass to sort the prototype lists and flatten the hierarchy.
            void Recurse(CategoryNode node)
            {
                // I give up we're using recursion to flatten this.
                // There probably IS a way to do it.
                // I'm too stupid to think of what that way is.
                foreach (var child in node.ChildCategories.Values)
                {
                    Recurse(child);
                }

                node.Prototypes.Sort(ComparePrototype);
                FlattenedCategories.Add(node);
                node.FlattenedIndex = FlattenedCategories.Count - 1;
            }

            FlattenedCategories = new List <CategoryNode>(count);
            Recurse(RootCategory);
        }
Exemple #8
0
        public void EntityNode_rejects_moving_itself_to_category_if_entity_name_already_exists(string initialName, string destinationName, string resultName)
        {
            // ARRANGE

            this.ProviderContextMock
            .Setup(p => p.Persistence)
            .Returns(this.PersistenceMock.Object);

            this.PersistenceMock
            .Setup(p => p.Categories)
            .Returns(this.CategoryRepositoryMock.Object);

            var c = DefaultCategory();

            this.CategoryRepositoryMock
            .Setup(r => r.FindById(c.Id))
            .Returns(c);

            this.CategoryRepositoryMock
            .Setup(r => r.FindByParentAndName(c, resultName))
            .Returns((Category?)null);

            this.PersistenceMock
            .Setup(p => p.Entities)
            .Returns(this.EntityRepositoryMock.Object);

            this.EntityRepositoryMock
            .Setup(r => r.FindByCategoryAndName(c, resultName))
            .Returns(DefaultEntity(e => e.Name = resultName));

            var categoryNode = new CategoryNode(c);
            var e            = DefaultEntity(e => e.Name = initialName);
            var node         = new EntityNode(e);

            // ACT

            var result = Assert.Throws <InvalidOperationException>(
                () => node.MoveItem(this.ProviderContextMock.Object, initialName, destinationName, categoryNode));

            // ASSERT

            Assert.Equal($"Destination container contains already an entity with name '{resultName}'", result.Message);
        }
Exemple #9
0
        public void CategoryNode_copies_itself_to_category(string initialName, string destinationName, string resultName)
        {
            // ARRANGE

            this.ArrangeSubCategory(out var rootCategory, out var subCategory);

            this.CategoryRepositoryMock
            .Setup(r => r.FindById(subCategory.Id))
            .Returns(subCategory);

            var category = DefaultCategory(c => rootCategory.AddSubCategory(c));

            this.CategoryRepositoryMock // destination name is unused
            .Setup(r => r.FindByParentAndName(subCategory, resultName))
            .Returns((Category?)null);

            this.ProviderContextMock
            .Setup(c => c.Persistence)
            .Returns(this.PersistenceMock.Object);

            this.PersistenceMock
            .Setup(m => m.Entities)
            .Returns(this.EntityRepositoryMock.Object);

            this.EntityRepositoryMock // detsinatin name is unused
            .Setup(r => r.FindByCategoryAndName(subCategory, resultName))
            .Returns((Entity?)null);

            this.ProviderContextMock
            .Setup(p => p.Recurse)
            .Returns(true);

            this.PersistenceMock
            .Setup(p => p.CopyCategory(category, subCategory, true));

            var categoryContainer = new CategoryNode(subCategory);

            // ACT

            new CategoryNode(category)
            .CopyItem(this.ProviderContextMock.Object, initialName, destinationName, categoryContainer);
        }
Exemple #10
0
 private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
 {
     this.toolStripButtonDelete.Enabled = false;
     this.toolStripButtonSee.Enabled    = false;
     this.listView1.Items.Clear();
     if (this.treeView1.SelectedNode != null && this.treeView1.SelectedNode is CategoryNode)
     {
         CategoryNode node = this.treeView1.SelectedNode as CategoryNode;
         this.toolStripButtonDelete.Enabled = true;
         this.Cursor = Cursors.WaitCursor;
         try
         {
             loadContens(node, new ContentTitleComparator());
         }
         finally
         {
             this.Cursor = Cursors.Default;
         }
     }
 }
Exemple #11
0
        public void DistributorSettingsPropertiesTest()
        {
            CategoryData categoryData = new CategoryData();

            categoryData.Name = SR.DefaultCategory;
            CategoryNode      defaultCategory = new CategoryNode(categoryData);
            TextFormatterData formatterData   = new TextFormatterData();

            formatterData.Name = SR.DefaultFormatter;
            TextFormatterNode defaultFormatter = new TextFormatterNode(formatterData);

            DistributorSettingsNode distributorSettings = new DistributorSettingsNode();

            applicationNode.Nodes.Add(distributorSettings);
            distributorSettings.DefaultFormatter = defaultFormatter;
            distributorSettings.DefaultCategory  = defaultCategory;

            Assert.AreEqual(defaultCategory.Name, distributorSettings.DefaultCategory.Name);
            Assert.AreEqual(defaultFormatter, distributorSettings.DefaultFormatter);
        }
Exemple #12
0
 private static string GetLabelText(CategoryNode categoryNode, DataPoint dataPoint, Series series, DataPointAttributes dataPointAttributes)
 {
     if (dataPoint != null)
     {
         if (TreeMapChart.IsLabelVisible(dataPoint))
         {
             string labelText = PieChart.GetLabelText(dataPoint);
             if (!string.IsNullOrEmpty(labelText))
             {
                 return(labelText);
             }
             return(GetCategoryNodeLabelText(categoryNode, series, dataPoint));
         }
     }
     else if (TreeMapChart.IsLabelVisible(dataPointAttributes))
     {
         return(GetCategoryNodeLabelText(categoryNode, series, dataPointAttributes));
     }
     return(string.Empty);
 }
Exemple #13
0
        /// <summary>
        /// Append child tree nodes to parent tree node.
        /// </summary>
        /// <param name="nd">Parent tree node</param>
        /// <param name="cat">Parent category node</param>
        private void AddCategoryChildNodes(TreeNode nd, CategoryNode cat)
        {
            foreach (CategoryNode child in cat.Children.ToList())
            {
                TreeNode node = CreateNode(child.Id.ToString(), child.Title);

                //If categoryNode is not authorized node then don't allow selection.
                if (_authorizedCategoryNodeIds != null && !_authorizedCategoryNodeIds.Contains(child.Id))
                {
                    node.SelectAction = TreeNodeSelectAction.None;
                }

                //AddOnClickToNode(node);
                nd.ChildNodes.Add(node);
                if (child.Children.Count > 0)
                {
                    AddCategoryChildNodes(node, child);
                }
            }
        }
        public IActionResult Put([FromRoute] int id, [FromBody] CategoryNode categoryNode)
        {
            // Must be a Super Administrator to call this Method
            if (!UtilitySecurity.IsSuperUser(this.User.Identity.Name, GetConnectionString()))
            {
                return(BadRequest());
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != categoryNode.Id)
            {
                return(BadRequest());
            }

            return(Ok(UpdateCategory(id, categoryNode, GetConnectionString())));
        }
Exemple #15
0
        async Task BuildIndexCategory()
        {
            var kwroot = Dist.CreateSubdirectory("categories");
            Dictionary <string, CategoryNode> mapper = new Dictionary <string, CategoryNode>();
            CategoryNode all = new CategoryNode(new Category());

            foreach (var v in Data)
            {
                CategoryNode node = all;
                foreach (var k in v.Category)
                {
                    if (!node.Children.ContainsKey(k))
                    {
                        Category c = new Category
                        {
                            Id   = Guid.NewGuid().ToString(),
                            Name = k,
                        };
                        if (node != all)
                        {
                            c.ParentId = node.Category.Id;
                        }
                        var tn = new CategoryNode(c);
                        mapper.Add(c.Id, tn);
                        node.Children.Add(k, tn);
                        node = tn;
                    }
                    else
                    {
                        node = node.Children[k];
                    }
                    node.Data.Add(v);
                }
                v.Raw.CategoryId = node.Category.Id;
            }
            foreach (var v in mapper)
            {
                await BuildPaging(v.Value.Data, kwroot.CreateSubdirectory(v.Key));
            }
            Categories = mapper.Select(x => x.Value.Category).ToList();
        }
Exemple #16
0
        public void CategoryNode_rejects_creating_EntityNodeValue_with_duplicate_entity_name()
        {
            // ARRANGE

            //todo: create entity with tag
            //this.ProviderContextMock
            //    .Setup(c => c.DynamicParameters)
            //    .Returns((object?)null);

            this.ProviderContextMock
            .Setup(c => c.Persistence)
            .Returns(this.PersistenceMock.Object);

            var category = DefaultCategory();

            this.PersistenceMock
            .Setup(p => p.Categories)
            .Returns(this.CategoryRepositoryMock.Object);

            this.CategoryRepositoryMock
            .Setup(r => r.FindByParentAndName(category, "Entity"))
            .Returns((Category?)null);

            this.PersistenceMock
            .Setup(m => m.Entities)
            .Returns(this.EntityRepositoryMock.Object);

            this.EntityRepositoryMock
            .Setup(r => r.FindByCategoryAndName(category, "Entity"))
            .Returns(DefaultEntity());

            var node = new CategoryNode(category);

            // ACT

            var result = Assert.Throws <InvalidOperationException>(() => node.NewItem(this.ProviderContextMock.Object, newItemName: "Entity", itemTypeName: nameof(TreeStoreItemType.Entity), newItemValue: null !));

            // ASSERT

            Assert.Equal($"Name is already used by and item of type '{nameof(TreeStoreItemType.Entity)}'", result.Message);
        }
Exemple #17
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Initializes categories in the hierarchy.
        /// </summary>
        /// <param name="categoryList">The list of categories for a Scripture note.</param>
        /// <param name="lgwsf">The language writing system factory.</param>
        /// <exception cref="ArgumentOutOfRangeException">thrown when the category list is empty.
        /// </exception>
        /// ------------------------------------------------------------------------------------
        private void InitializeCategory(List <CategoryNode> categoryList, ILgWritingSystemFactory lgwsf)
        {
            XmlNoteCategory curCategory = this;
            CategoryNode    node        = null;

            for (int i = 0; i < categoryList.Count; i++)
            {
                node = categoryList[i];
                curCategory.CategoryName = node.CategoryName;
                curCategory.IcuLocale    = lgwsf.GetStrFromWs(node.Ws);
                if (categoryList.Count > i + 1)
                {
                    curCategory.SubCategory = new XmlNoteCategory();
                    curCategory             = curCategory.SubCategory;
                }
                else
                {
                    curCategory.SubCategory = null;
                }
            }
        }
Exemple #18
0
 private void toolStripButtonSee_Click(object sender, EventArgs e)
 {
     if (this.listView1.SelectedItems.Count > 0 && this.treeView1.SelectedNode != null && this.treeView1.SelectedNode is CategoryNode)
     {
         CategoryNode  category   = this.treeView1.SelectedNode as CategoryNode;
         ListViewItem  selected   = this.listView1.SelectedItems[0];
         ContentInfo   content    = selected.Tag as ContentInfo;
         string        repository = category.Repository.name;
         VersionInfo[] versions   = OfficeDocument.OfficeDocumentProxy.getVersions(category.Repository.name, content.id);
         VersionInfo   version    = versions[versions.Length - 1]; // last version
         String        name       = null;
         try
         {
             name = OfficeApplication.OfficeDocumentProxy.createPreview(repository, version.contentId, version.nameOfVersion, this.documentType.ToString());
             String urlproxy = OfficeApplication.OfficeDocumentProxy.WebAddress.ToString();
             if (!urlproxy.EndsWith("/gtw"))
             {
                 if (!urlproxy.EndsWith("/"))
                 {
                     urlproxy += "/";
                 }
                 if (!urlproxy.EndsWith("gtw"))
                 {
                     urlproxy += "gtw";
                 }
             }
             Uri         url         = new Uri(urlproxy + "?contentId=" + version.contentId + "&versionName=" + version.nameOfVersion + "&repositoryName=" + repository + "&name=" + name + "&type=" + documentType.ToString());
             String      title       = OfficeApplication.OfficeDocumentProxy.getTitle(repository, version.contentId);
             FormPreview formPreview = new FormPreview(url, false, title);
             formPreview.ShowDialog(this);
         }
         finally
         {
             if (name != null)
             {
                 OfficeApplication.OfficeDocumentProxy.deletePreview(name);
             }
         }
     }
 }
Exemple #19
0
        public void CategoryNode_creates_category()
        {
            // ARRANGE

            this.ProviderContextMock
            .Setup(c => c.Persistence)
            .Returns(this.PersistenceMock.Object);

            this.PersistenceMock
            .Setup(m => m.Categories)
            .Returns(this.CategoryRepositoryMock.Object);

            var category = DefaultCategory();

            this.CategoryRepositoryMock
            .Setup(r => r.FindByParentAndName(category, "c"))
            .Returns((Category?)null);

            this.CategoryRepositoryMock
            .Setup(r => r.Upsert(It.Is <Category>(c => c.Name.Equals("c"))))
            .Returns <Category>(c => c);

            this.PersistenceMock
            .Setup(p => p.Entities)
            .Returns(this.EntityRepositoryMock.Object);

            this.EntityRepositoryMock
            .Setup(r => r.FindByCategoryAndName(category, "c"))
            .Returns((Entity?)null);

            var node = new CategoryNode(category);

            // ACT

            var result = node.NewItem(this.ProviderContextMock.Object, newItemName: "c", itemTypeName: nameof(TreeStoreItemType.Category), newItemValue: null !);

            // ASSERT

            Assert.IsType <CategoryNode>(result);
        }
Exemple #20
0
        public void CategoryNode_renaming_rejects_duplicate_entity_name(string existingName)
        {
            // ARRANGE

            var category       = DefaultCategory();
            var parentCategory = DefaultCategory(WithSubCategory(category));

            this.ProviderContextMock
            .Setup(c => c.Persistence)
            .Returns(this.PersistenceMock.Object);

            var entity = DefaultEntity(e => e.Name = existingName);

            this.PersistenceMock
            .Setup(p => p.Entities)
            .Returns(this.EntityRepositoryMock.Object);

            this.EntityRepositoryMock
            .Setup(p => p.FindByCategoryAndName(parentCategory, existingName))
            .Returns(entity);

            this.PersistenceMock
            .Setup(p => p.Categories)
            .Returns(this.CategoryRepositoryMock.Object);

            this.CategoryRepositoryMock
            .Setup(r => r.FindByParentAndName(parentCategory, existingName))
            .Returns((Category?)null);

            var categoryNode = new CategoryNode(category);

            // ACT

            categoryNode.RenameItem(this.ProviderContextMock.Object, "c", existingName);

            // ASSERT

            Assert.Equal("c", category.Name);
        }
Exemple #21
0
        public void CategoryNode_retrieves_categories_and_entities_as_childnodes()
        {
            // ARRANGE

            var subcategory = DefaultCategory(c => c.Name = "cc");
            var category    = DefaultCategory(WithSubCategory(subcategory));
            var entity      = DefaultEntity(e => e.Category = category);

            this.ProviderContextMock
            .Setup(c => c.Persistence)
            .Returns(this.PersistenceMock.Object);

            this.PersistenceMock
            .Setup(p => p.Categories)
            .Returns(this.CategoryRepositoryMock.Object);

            this.CategoryRepositoryMock
            .Setup(p => p.FindByParent(category))
            .Returns(subcategory.Yield());

            this.PersistenceMock
            .Setup(p => p.Entities)
            .Returns(this.EntityRepositoryMock.Object);

            this.EntityRepositoryMock
            .Setup(r => r.FindByCategory(category))
            .Returns(entity.Yield());

            var node = new CategoryNode(category);

            // ACT

            var result = node.GetChildNodes(this.ProviderContextMock.Object).ToArray();

            // ASSERT

            Assert.Equal(2, result.Length);
        }
        public async Task <ActionResult> Edit([FromForm] CategoryNode category, [FromForm] int id)
        {
            if (ModelState.IsValid)
            {
                var cat = _repository.Categories.FirstOrDefault(c => c.ID == id);
                cat.Name = category.Name;

                try
                {
                    _repository.SaveChanges();
                }
                catch (DbUpdateConcurrencyException ex)
                {
                    return(BadRequest("Информация сейчас редактируется другим пользователем. Пожалуйста, попробуйте позже."));
                }

                return(Ok());
            }
            else
            {
                return(BadRequest("List"));
            }
        }
Exemple #23
0
        public JObject AddChild(CategoryNode node)
        {
            JObject JNode = new JObject();

            if (node.ChildrenCount > 0)
            {
                JNode = new JObject(
                    new JProperty("id", node.alias),
                    new JProperty("name", node.title),
                    new JProperty("isParent", "true"),
                    new JProperty("nocheck", "true")
                    );
            }
            else
            {
                JNode = new JObject(
                    new JProperty("id", node.alias),
                    new JProperty("name", node.title),
                    new JProperty("isParent", "false")
                    );
            }
            return(JNode);
        }
Exemple #24
0
        public FormGeoProcessor()
        {
            InitializeComponent();

            PlugInManager compMan = new PlugInManager();

            foreach (XmlNode activityNode in compMan.GetPluginNodes(Plugins.Type.IActivity))
            {
                IActivity activity = compMan.CreateInstance(activityNode) as IActivity;
                if (activity == null)
                {
                    continue;
                }

                CategoryNode catNode = TreeCategoryNode(activity.CategoryName);
                catNode.Nodes.Add(new ActivityNode(activity));
            }

            if (tvActivity.Nodes.Count > 0)
            {
                tvActivity.Nodes[0].Expand();
            }
        }
Exemple #25
0
        public void CategoryNode_resolves_child_name_as_Category(string name)
        {
            // ARRANGE

            var subCategory = DefaultCategory(c => c.Name = "cc");
            var category    = DefaultCategory(WithSubCategory(subCategory));

            this.ProviderContextMock
            .Setup(p => p.Persistence)
            .Returns(this.PersistenceMock.Object);

            this.PersistenceMock
            .Setup(p => p.Entities)
            .Returns(this.EntityRepositoryMock.Object);

            this.PersistenceMock
            .Setup(p => p.Categories)
            .Returns(this.CategoryRepositoryMock.Object);

            this.CategoryRepositoryMock
            .Setup(r => r.FindByParentAndName(category, name))
            .Returns(subCategory);

            this.EntityRepositoryMock
            .Setup(r => r.FindByCategoryAndName(category, name))
            .Returns((Entity?)null);

            var node = new CategoryNode(category);

            // ACT

            var result = node.Resolve(this.ProviderContextMock.Object, name).Single();

            // ASSERT

            Assert.Equal(subCategory.Id, ((CategoryNode.Item)result.GetItem(this.ProviderContextMock.Object).ImmediateBaseObject).Id);
        }
        private void Setup()
        {
            int iRowCount = 0;

            foreach (manModelMatchType manModelMatchType in SelectedManModelMatchTypes)
            {
                CategoryNode cnCategoryNodeWalker = DesktopSession.CategoryXML.GetMerchandiseCategory(manModelMatchType.categoryCode.ToString());

                if (!cnCategoryNodeWalker.Error)
                {
                    RadioButton modTypeRadioButton = new RadioButton
                    {
                        AutoSize  = true,
                        ForeColor = Color.Black,
                        Text      = cnCategoryNodeWalker.Description,
                        Tag       = cnCategoryNodeWalker.CategoryCode,
                        TabIndex  = iRowCount
                    };
                    modTypeRadioButton.Checked = iRowCount == 0 ? true : false;
                    optionsTableLayoutPanel.Controls.Add(modTypeRadioButton, 0, iRowCount);
                    iRowCount++;
                }
            }

            verticalScrollBar.Minimum = 0;
            verticalScrollBar.Maximum = optionsTableLayoutPanel.Height - optionPanel.Height;

            string sTitleText = "Several categories were found.  Please choose which category ";

            sTitleText       += "you would like to continue with";
            lblTitleText.Text = sTitleText;

            if (optionsTableLayoutPanel.Controls.Count > 0)
            {
                optionsTableLayoutPanel.Controls[0].Focus();
            }
        }
Exemple #27
0
        public void CategoryNode_removes_itself(bool recurse)
        {
            // ARRANGE

            var category = DefaultCategory();

            this.ProviderContextMock
            .Setup(c => c.Persistence)
            .Returns(this.PersistenceMock.Object);

            this.ProviderContextMock
            .Setup(p => p.Recurse)
            .Returns(recurse);

            this.PersistenceMock
            .Setup(r => r.DeleteCategory(category, recurse))
            .Returns(true);

            var node = new CategoryNode(category);

            // ACT

            node.RemoveItem(this.ProviderContextMock.Object, "c");
        }
        public ProblemCSV(CategoryNode editingNode)
        {
            InitializeComponent();

            node = editingNode;
        }
Exemple #29
0
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        public void Run(GoogleAdsClient client, long customerId)
        {
            // Get the GoogleAdsServiceClient .
            GoogleAdsServiceClient googleAdsService =
                client.GetService(Services.V10.GoogleAdsService);

            // Creates the query.
            string query = "SELECT product_bidding_category_constant.localized_name, " +
                           "product_bidding_category_constant.product_bidding_category_constant_parent " +
                           "FROM product_bidding_category_constant WHERE " +
                           "product_bidding_category_constant.country_code IN ('US') ORDER BY " +
                           "product_bidding_category_constant.localized_name ASC";

            // Creates the request.
            SearchGoogleAdsRequest request = new SearchGoogleAdsRequest()
            {
                CustomerId = customerId.ToString(),
                Query      = query
            };

            // Creates a list of top level category nodes.
            List <CategoryNode> rootCategories = new List <CategoryNode>();

            // Creates a map of category ID to category node for all categories found in the
            // results.
            // This Map is a convenience lookup to enable fast retrieval of existing nodes.
            Dictionary <string, CategoryNode> biddingCategories =
                new Dictionary <string, CategoryNode>();

            try
            {
                // Performs the search request.
                foreach (GoogleAdsRow googleAdsRow in googleAdsService.Search(request))
                {
                    ProductBiddingCategoryConstant productBiddingCategory =
                        googleAdsRow.ProductBiddingCategoryConstant;

                    string localizedName = productBiddingCategory.LocalizedName;
                    string resourceName  = productBiddingCategory.ResourceName;

                    CategoryNode node = null;
                    if (biddingCategories.ContainsKey(resourceName))
                    {
                        node = biddingCategories[resourceName];
                    }
                    else
                    {
                        node = new CategoryNode(resourceName, localizedName);
                        biddingCategories[resourceName] = node;
                    }

                    if (string.IsNullOrEmpty(node.LocalizedName))
                    {
                        // Ensures that the name attribute for the node is set. Name will be null for
                        //nodes added to biddingCategories as a result of being a parentNode below.
                        node.LocalizedName = localizedName;
                    }

                    if (!string.IsNullOrEmpty(
                            productBiddingCategory.ProductBiddingCategoryConstantParent))
                    {
                        string parentResourceName =
                            productBiddingCategory.ProductBiddingCategoryConstantParent;
                        CategoryNode parentNode = null;

                        if (biddingCategories.ContainsKey(parentResourceName))
                        {
                            parentNode = biddingCategories[parentResourceName];
                        }
                        else
                        {
                            parentNode = new CategoryNode(parentResourceName);
                            biddingCategories[parentResourceName] = parentNode;
                        }
                        parentNode.Children.Add(node);
                    }
                    else
                    {
                        rootCategories.Add(node);
                    }
                }
                DisplayCategories(rootCategories, "");
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
        }
 public ProblemBatch(CategoryNode nod)
 {
     InitializeComponent();
     this.node = nod;
 }
 public CategoryNode(string name, CategoryNode parent)
 {
     Name   = name;
     Parent = parent;
 }
Exemple #32
0
        /// <summary>
        /// turn the loaded category and subcategory nodes into useable data
        /// </summary>
        private void ProcessFilterDefinitions()
        {
            foreach (ConfigNode node in GameDatabase.Instance.GetConfigNodes("CATEGORY"))
            {
                var C = new CategoryNode(node, this);
                if (C.SubCategories == null)
                {
                    Logger.Log($"no subcategories present in {C.CategoryName}", Logger.LogLevel.Error);
                    continue;
                }
                CategoryNodes.AddUnique(C);
            }
            //load all subCategory configs
            foreach (ConfigNode node in GameDatabase.Instance.GetConfigNodes("SUBCATEGORY"))
            {
                var sC = new SubcategoryNode(node, this);
                if (!sC.HasFilters || string.IsNullOrEmpty(sC.SubCategoryTitle))
                {
                    Logger.Log($"subcategory format error: {sC.SubCategoryTitle}", Logger.LogLevel.Error);
                    continue;
                }
                else if (subCategoriesDict.ContainsKey(sC.SubCategoryTitle)) // if something does have the same title
                {
                    Logger.Log($"subcategory name duplicated: {sC.SubCategoryTitle}", Logger.LogLevel.Error);
                    continue;
                }
                else // if nothing else has the same title
                {
                    subCategoriesDict.Add(sC.SubCategoryTitle, sC);
                }
            }

            CategoryNode Cat = CategoryNodes.Find(C => C.CategoryName == "Filter by Resource");

            if (Cat != null && Cat.Type == CategoryNode.CategoryType.STOCK)
            {
                foreach (string s in resources)
                {
                    // add spaces before each capital letter
                    string name = System.Text.RegularExpressions.Regex.Replace(s, @"\B([A-Z])", " $1");
                    if (subCategoriesDict.ContainsKey(name))
                    {
                        Logger.Log($"resource name already exists, abandoning generation for {name}", Logger.LogLevel.Debug);
                        continue;
                    }
                    else if (!string.IsNullOrEmpty(name))
                    {
                        ConfigNode checkNode = CheckNodeFactory.MakeCheckNode(CheckResource.ID, s);
                        ConfigNode filtNode  = FilterNode.MakeFilterNode(false, new List <ConfigNode>()
                        {
                            checkNode
                        });
                        ConfigNode subcatNode = SubcategoryNode.MakeSubcategoryNode(name, name, false, new List <ConfigNode>()
                        {
                            filtNode
                        });
                        subCategoriesDict.Add(name, new SubcategoryNode(subcatNode, this));
                        Cat.SubCategories.AddUnique(new SubCategoryItem(name));
                    }
                }
            }

            foreach (CategoryNode C in CategoryNodes)
            {
                if (!C.All)
                {
                    continue;
                }
                var filterList = new List <FilterNode>();
                if (C.SubCategories != null)
                {
                    foreach (SubCategoryItem s in C.SubCategories)
                    {
                        if (subCategoriesDict.TryGetValue(s.SubcategoryName, out SubcategoryNode subcategory))
                        {
                            filterList.AddUniqueRange(subcategory.Filters);
                        }
                    }
                }
                var filternodes = new List <ConfigNode>();
                foreach (FilterNode f in filterList)
                {
                    filternodes.Add(f.ToConfigNode());
                }
                var newSub = new SubcategoryNode(SubcategoryNode.MakeSubcategoryNode("All parts in " + C.CategoryName, C.IconName, false, filternodes), this);
                subCategoriesDict.Add(newSub.SubCategoryTitle, newSub);
                C.SubCategories.Insert(0, new SubCategoryItem(newSub.SubCategoryTitle));
            }
        }
        private void FillCategory(TmNode node, int catId)
        {
            //  A category can have categories and/or themes for children.
            List<Category> cats;
            _categoriesInCategories.TryGetValue(catId, out cats);
            if (cats != null)
                foreach (Category cat in cats)
                {
                    TmNode newNode = new CategoryNode(
                        cat.Name,
                        node,
                        MakeMetadataForCategory(cat.Link),
                        cat.Description
                        );
                    node.Add(newNode);
                    FillCategory(newNode, cat.Id);
                }

            List<Theme> themes;
            _themesInCategories.TryGetValue(catId, out themes);
            if (themes != null)
                foreach (Theme theme in themes)
                {
                    TmNode newNode = new ThemeNode(
                        theme.Name,
                        node,
                        MakeThemeData(theme.Name, theme.DataSource, theme.Type),
                        MakeMetadataForTheme(theme.Metadata),
                        null,
                        theme.PubDate
                        );
                    node.Add(newNode);
                    FillTheme(newNode, theme.Id);
                }
        }
        static void downloadCPBook(int ed)
        {
            string url = "http://uhunt.felix-halim.net/api/cpbook/" + ed.ToString();
            string path = @"J:\Projects\GitHub\uva-problem-category\data\CP Book" + ed.ToString() + ".cat";

            //download data
            Console.WriteLine("Downloading \"" + url + "\" ...");
            var client = new System.Net.WebClient();
            byte[] data = client.DownloadData(url);

            //parse data
            Console.WriteLine("Parsing ...");
            string json = System.Text.Encoding.UTF8.GetString(data);
            object alldat = Newtonsoft.Json.JsonConvert.DeserializeObject(json);

            //build category branch
            Console.WriteLine("Building ...");
            CategoryNode cb = new CategoryNode();
            cb.name = "Context Programming Book " + ed.ToString();
            cb.note = "Contains category description from uHunt server";
            cb.branches = new System.Collections.Generic.List<CategoryNode>();

            //getting top branches
            foreach (var o in (Newtonsoft.Json.Linq.JArray)alldat)
            {
                //add new branch
                CategoryNode b1 = new CategoryNode();
                b1.branches = new System.Collections.Generic.List<CategoryNode>();
                cb.branches.Add(b1);
                //extract name of the branch
                b1.name = o.Value<string>("title");
                //get sub branches
                foreach (var o2 in o.Value<Newtonsoft.Json.Linq.JArray>("arr"))
                {
                    //add new branch
                    CategoryNode b2 = new CategoryNode();
                    b2.branches = new System.Collections.Generic.List<CategoryNode>();
                    b1.branches.Add(b2);
                    //extract name of the branch
                    b2.name = o2.Value<string>("title");
                    //get sub branches
                    foreach (var o3 in o2.Value<Newtonsoft.Json.Linq.JArray>("arr"))
                    {
                        //add new branch
                        CategoryNode b3 = new CategoryNode();
                        b3.problems = new System.Collections.Generic.List<CategoryProblem>();
                        b2.branches.Add(b3);
                        //extract name
                        var o4 = (Newtonsoft.Json.Linq.JArray)o3;
                        b3.name = o4[0].ToString();
                        for (int i = 1; i < o4.Count; ++i)
                        {
                            //add category problem
                            CategoryProblem p1 = new CategoryProblem();
                            b3.problems.Add(p1);
                            //extract values
                            int pn = (int)o4[i].ToObject(typeof(int));
                            p1.pnum = (pn < 0 ? -pn : pn);
                            p1.star = (pn < 0);
                        }
                    }

                }
            }

            Console.WriteLine("Saving Data...");
            json = Newtonsoft.Json.JsonConvert.SerializeObject(cb, Newtonsoft.Json.Formatting.Indented);
            System.IO.File.WriteAllText(path, json);
            Console.WriteLine("Process completed.\n");
        }
    public void AddFitFunctionList(string rootname, Altaxo.Main.Services.IFitFunctionInformation[] entries, FitFunctionContextMenuStyle menustyle)
    {
      // The key of the entries is the FitFunctionAttribute, the value is the type of the fitting function

      this._twFitFunctions.BeginUpdate();
      

      RootNode rnode = new RootNode(rootname, RootNodeType.Builtin);
      this._twFitFunctions.Nodes.Add(rnode);
      TreeNodeCollection root = rnode.Nodes;


      foreach (Altaxo.Main.Services.IFitFunctionInformation entry in entries)
      {

        string[] path = entry.Category.Split(new char[]{'\\','/'});

        TreeNodeCollection where = root;
        for(int j=0;j<path.Length;j++)
        {
          TreeNode node = GetPathNode(where,path[j]);
          if(node==null)
          {
            node = new CategoryNode(path[j]);
            where.Add(node);
          }
          where = node.Nodes;
        }

        BuiltinLeafNode leaf = new BuiltinLeafNode(entry.Name,entry);

        switch (menustyle)
        {
          case FitFunctionContextMenuStyle.None:
            break;
          case FitFunctionContextMenuStyle.EditAndDelete:
            leaf.ContextMenu = _userFileLeafNodeContextMenu;
            break;
          case FitFunctionContextMenuStyle.Edit:
            leaf.ContextMenu = _appFileLeafNodeContextMenu;
            break;
        }
        where.Add(leaf);
      }
      this._twFitFunctions.EndUpdate();
    }
 public CategoriesTreeNodeViewModel(CategoryNode dto)
 {
     Name = dto.Name;
     ParentName = dto.ParentName;
     ChildNodes = new List<CategoriesTreeNodeViewModel>();
 }
		public void AddFitFunctionList(string rootname, Altaxo.Main.Services.IFitFunctionInformation[] info, FitFunctionContextMenuStyle menustyle)
		{
			if (_twFitFunctions.ItemsSource == null)
			{
				_twFitFunctions.ItemsSource = new NGTreeNode().Nodes;
			}
			var mainRoot = (NGTreeNodeCollection)_twFitFunctions.ItemsSource;

			// The key of the entries is the FitFunctionAttribute, the value is the type of the fitting function
			RootNode rnode = new RootNode(rootname, RootNodeType.RootNodeBuiltin);
			mainRoot.Add(rnode);
			NGTreeNodeCollection root = rnode.Nodes;

			foreach (Altaxo.Main.Services.IFitFunctionInformation entry in info)
			{
				string[] path = entry.Category.Split(new char[] { '\\', '/' });

				var where = root;
				for (int j = 0; j < path.Length; j++)
				{
					var node = GetPathNode(where, path[j]);
					if (node == null)
					{
						node = new CategoryNode(path[j]);
						where.Add(node);
					}
					where = node.Nodes;
				}

				BuiltinLeafNode leaf = new BuiltinLeafNode(entry.Name, entry);

				switch (menustyle)
				{
					case FitFunctionContextMenuStyle.None:
						leaf.SetMenuEnabled(false, false);
						break;

					case FitFunctionContextMenuStyle.EditAndDelete:
						//	leaf.ContextMenu = _userFileLeafNodeContextMenu;
						leaf.SetMenuEnabled(true, true);
						break;

					case FitFunctionContextMenuStyle.Edit:
						//	leaf.ContextMenu = _appFileLeafNodeContextMenu;
						leaf.SetMenuEnabled(true, false);
						break;
				}
				where.Add(leaf);
			}
		}
    /// <summary>
    /// Renders tree specified by root node into supplied string builder. 
    /// </summary>
    /// <param name="builder">String builder to render to.</param>
    /// <param name="root">Root of the rendered subtree.</param>
    private void RenderTree(StringBuilder builder, CategoryNode root)
    {
        bool itemStarted = false;

        // Render node title
        if ((root.Category != null) || (!string.IsNullOrEmpty(root.AlternativeText)))
        {
            builder.Append("<li class=\"CategoryListItem\">");
            itemStarted = true;

            if (root.Category != null)
            {
                builder.Append(CreateCategoryPartLink(root.Category));
            }
            else
            {
                builder.Append(FormatCategoryDisplayName(root.AlternativeText));
            }
        }

        // Recursively render child nodes
        if (root.Nodes.Count > 0)
        {
            if (itemStarted)
            {
                builder.AppendLine("<ul class=\"CategoryListList\">");
            }

            foreach (CategoryNode child in root.Nodes)
            {
                RenderTree(builder, child);
            }

            if (itemStarted)
            {
                builder.AppendLine("</ul>");
            }
        }

        if (itemStarted)
        {
            builder.Append("</li>");
        }
    }
 private AccessPermissionTree BuileAccessTree(List<AccessPermission> permissions)
 {
     AccessPermissionTree accessTree = new AccessPermissionTree();
     foreach (ModuleCategoryType catetype in Enum.GetValues(typeof(ModuleCategoryType)))
     {
         CategoryNode category = new CategoryNode();
         category.CategoryType = catetype;
         List<AccessPermission> moduleList = permissions.FindAll(delegate(AccessPermission access) { return access.CategotyType == catetype; });
         List<ModuleType> moduleInCategory = new List<ModuleType>();
         foreach (ModuleType moduleType in Enum.GetValues(typeof(ModuleType)))
         {
             AccessPermission accesssss = moduleList.Find(delegate(AccessPermission per)
             {
                 return per.ModuleType == moduleType;
             });
             if (moduleList.Find(delegate(AccessPermission per) { return per.ModuleType == moduleType; }) != null)
             {
                 moduleInCategory.Add(moduleType);
             }
         }
         foreach (ModuleType moduleType in moduleInCategory)
         {
             ModuleNode module = new ModuleNode();
             module.Type = moduleType;
             foreach (AccessPermission access in moduleList)
             {
                 if (access.ModuleType == moduleType)
                 {
                     OperationNode node = new OperationNode();
                     node.Id = access.OperationId;
                     node.OperationDescription = access.OperationName;
                     module.OperationNodes.Add(node);
                 }
             }
             category.ModuleNodes.Add(module);
         }
         if (category.ModuleNodes.Count != 0)
         {
             accessTree.CategoryNodes.Add(category);
         }
     }
     return accessTree;
 }
        //
        // Category Branch
        //
        void loadCategoryBranch(CategoryIndex catIndx)
        {
            try
            {
                if (selectedIndex == catIndx) return;

                //first close previous branch
                closeOpenedBranch();

                //open content
                string filename = getCategoryFile(catIndx.file);
                if (filename == null || !File.Exists(filename)) return;
                string content = File.ReadAllText(filename);

                //parse data
                selectedBranch = JsonConvert.DeserializeObject<CategoryNode>(content);
                selectedBranch.updateParent();
                treeList.SetObjects(new CategoryNode[] { selectedBranch });
                treeList.Expand(selectedBranch);
                treeList.SelectObject(selectedBranch);

                //set others
                selectedIndex = catIndx;
                splitContainer1.Enabled = true;
                catFileLabel.Text = string.Format("{0} : Version {1}", catIndx.file, catIndx.ver);
            }
            catch (Exception ex)
            {
                Console.Write(ex.Message + "\r\n" + ex.StackTrace);
            }
        }
    /// <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);
                        }
                    }
                }
            }
        }
    }
        //
        // Branch Editor
        //
        void loadEditorData(CategoryNode node)
        {
            try
            {
                //check if this is already opened
                if (editingNode == node) return;

                //close previously opened node
                closeEditing();

                editingNode = node;
                loadBranchWizard();
                loadBranchEditor();

                //set the current node
                pathLabel.Text = node.getPath();
                backTableLayout.ColumnStyles[0].Width = node.isTop() ? 0 : 100;

                tabControl1.Enabled = true;
            }
            catch (Exception ex)
            {
                Console.Write(ex.Message + "\r\n" + ex.StackTrace);
            }
        }
Exemple #43
0
        public TreeNode <ICategoryNode> GetCategoryTree(int rootCategoryId = 0, bool includeHidden = false, int storeId = 0)
        {
            var storeToken = QuerySettings.IgnoreMultiStore ? "0" : storeId.ToString();
            var rolesToken = QuerySettings.IgnoreAcl || includeHidden ? "0" : _workContext.CurrentCustomer.GetRolesIdent();
            var cacheKey   = CATEGORY_TREE_KEY.FormatInvariant(includeHidden.ToString().ToLower(), rolesToken, storeToken);

            var root = _cache.Get(cacheKey, () =>
            {
                // (Perf) don't fetch every field from db
                var query = from x in BuildCategoriesQuery(showHidden: includeHidden, storeId: storeId)
                            orderby x.ParentCategoryId, x.DisplayOrder, x.Name
                select new
                {
                    x.Id,
                    x.ParentCategoryId,
                    x.Name,
                    x.Alias,
                    x.PictureId,
                    x.Published,
                    x.DisplayOrder,
                    x.UpdatedOnUtc,
                    x.BadgeText,
                    x.BadgeStyle,
                    x.LimitedToStores,
                    x.SubjectToAcl
                };

                var unsortedNodes = query.ToList().Select(x => new CategoryNode
                {
                    Id = x.Id,
                    ParentCategoryId = x.ParentCategoryId,
                    Name             = x.Name,
                    Alias            = x.Alias,
                    PictureId        = x.PictureId,
                    Published        = x.Published,
                    DisplayOrder     = x.DisplayOrder,
                    UpdatedOnUtc     = x.UpdatedOnUtc,
                    BadgeText        = x.BadgeText,
                    BadgeStyle       = x.BadgeStyle,
                    LimitedToStores  = x.LimitedToStores,
                    SubjectToAcl     = x.SubjectToAcl
                });

                var nodes     = unsortedNodes.SortCategoryNodesForTree(0, true);
                var curParent = new TreeNode <ICategoryNode>(new CategoryNode {
                    Name = "Home"
                });
                CategoryNode prevNode = null;

                foreach (var node in nodes)
                {
                    // Determine parent
                    if (prevNode != null)
                    {
                        if (node.ParentCategoryId != curParent.Value.Id)
                        {
                            if (node.ParentCategoryId == prevNode.Id)
                            {
                                // level +1
                                curParent = curParent.LastChild;
                            }
                            else
                            {
                                // level -x
                                while (!curParent.IsRoot)
                                {
                                    if (curParent.Value.Id == node.ParentCategoryId)
                                    {
                                        break;
                                    }
                                    curParent = curParent.Parent;
                                }
                            }
                        }
                    }

                    // add to parent
                    curParent.Append(node, node.Id);

                    prevNode = node;
                }

                return(curParent.Root);
            }, CategoryTreeCacheDuration);

            if (rootCategoryId > 0)
            {
                root = root.SelectNodeById(rootCategoryId);
            }

            return(root);
        }
 public void setParent(CategoryNode v)
 {
     this.parent = v;
 }