public TreeNodeCollection GetNodes(string node)
        {
            TreeNodeCollection nodes = new TreeNodeCollection(false);

            if (!string.IsNullOrEmpty(node))
            {
                for (int i = 1; i < 6; i++)
                {
                    AsyncTreeNode asyncNode = new AsyncTreeNode();
                    asyncNode.Text = node + i;
                    asyncNode.NodeID = node + i;
                    nodes.Add(asyncNode);
                }

                for (int i = 6; i < 11; i++)
                {
                    TreeNode treeNode = new TreeNode();
                    treeNode.Text = node + i;
                    treeNode.NodeID = node + i;
                    treeNode.Leaf = true;
                    nodes.Add(treeNode);
                }
            }

            return nodes;
        }
        /// <summary>
        /// Returns all section tree nodes
        /// </summary>
        /// <param name="id">Node's id.</param>
        /// <param name="queryStrings">Query strings</param>
        /// <returns>Collection of tree nodes</returns>
        protected override TreeNodeCollection GetTreeNodes(string id, FormDataCollection queryStrings)
        {
            var nodes = new TreeNodeCollection();
            var ctrl = new WebsiteApiController();            

            if (id == Constants.System.Root.ToInvariantString())
            {
                var item = CreateTreeNode("0", "-1", queryStrings, "Websites", "icon-folder", true);
                nodes.Add(item);
                
                return nodes;
            }
            else if (id == "0")
            {
                foreach (var website in ctrl.GetAll())
                {
                    var node = CreateTreeNode(
                        website.Id.ToString(),
                        "0",
                        queryStrings,
                        website.ToString(),
                        "icon-document",
                        false);
                    
                    nodes.Add(node);
                }

                return nodes;
            }
            throw new NotSupportedException();
        }
Exemple #3
0
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/json";
            string nodeId = context.Request["node"];

            if (!string.IsNullOrEmpty(nodeId))
            {
                TreeNodeCollection nodes = new TreeNodeCollection(false);

                for (int i = 1; i < 6; i++)
                {
                    AsyncTreeNode asyncNode = new AsyncTreeNode();
                    asyncNode.Text = nodeId + i;
                    asyncNode.NodeID = nodeId + i;
                    nodes.Add(asyncNode);
                }

                for (int i = 6; i < 11; i++)
                {
                    TreeNode node = new TreeNode();
                    node.Text = nodeId + i;
                    node.NodeID = nodeId + i;
                    node.Leaf = true;
                    nodes.Add(node);
                }

                context.Response.Write(nodes.ToJson());
                context.Response.End();
            }
        }
        protected override TreeNodeCollection GetTreeNodes(string id, FormDataCollection queryStrings)
        {
            var nodes = new TreeNodeCollection();

            if (id == Constants.System.Root.ToInvariantString())
            {
                //list out all the letters
                for (var i = 97; i < 123; i++)
                {
                    var charString = ((char) i).ToString(CultureInfo.InvariantCulture);
                    var folder = CreateTreeNode(charString, id, queryStrings, charString, "icon-folder-close", true);
                    folder.NodeType = "member-folder";
                    nodes.Add(folder);
                }
                //list out 'Others' if the membership provider is umbraco
                if (Membership.Provider.Name == Constants.Conventions.Member.UmbracoMemberProviderName)
                {
                    var folder = CreateTreeNode("others", id, queryStrings, "Others", "icon-folder-close", true);
                    folder.NodeType = "member-folder";
                    nodes.Add(folder);
                }
            }
            else
            {
                //if it is a letter
                if (id.Length == 1 && char.IsLower(id, 0))
                {
                    if (Membership.Provider.Name == Constants.Conventions.Member.UmbracoMemberProviderName)
                    {
                        //get the members from our member data layer
                        nodes.AddRange(
                            Member.getMemberFromFirstLetter(id.ToCharArray()[0])
                                        .Select(m => CreateTreeNode(m.UniqueId.ToString("N"), id, queryStrings, m.Text, "icon-user")));
                    }
                    else
                    {
                        //get the members from the provider
                        int total;
                        nodes.AddRange(
                            FindUsersByName(char.Parse(id)).Cast<MembershipUser>()
                                      .Select(m => CreateTreeNode(GetNodeIdForCustomProvider(m.ProviderUserKey), id, queryStrings, m.UserName, "icon-user")));
                    }
                }
                else if (id == "others")
                {
                    //others will only show up when in umbraco membership mode
                    nodes.AddRange(
                        Member.getAllOtherMembers()
                                    .Select(m => CreateTreeNode(m.Id.ToInvariantString(), id, queryStrings, m.Text, "icon-user")));
                }
            }
            return nodes;
        }
        public void AddNodeTestCase3()
        {
            var parent = new TreeNode<String>();
            var target = new TreeNodeCollection<String>( parent );

            var item = new TreeNode<String>();
            target.Add( item );
            target.Add( item );

            Assert.IsTrue( target.Contains( item ) );
            Assert.AreEqual( 1, target.Count );

            Assert.AreSame( parent, item.Parent );
            Assert.AreEqual( 1, item.Depth );
        }
Exemple #6
0
        public static TreeNodeCollection BuildFirstLevel()
        {
            string path = HttpContext.Current.Server.MapPath("~/Examples/");
            DirectoryInfo root = new DirectoryInfo(path);
            DirectoryInfo[] folders = root.GetDirectories();
            folders = SortFolders(root, folders);

            TreeNodeCollection nodes = new TreeNodeCollection(false);

            foreach (DirectoryInfo folder in folders)
            {
                if ((folder.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden ||
                    excludeList.Contains(folder.Name) || folder.Name.StartsWith("_"))
                {
                    continue;
                }

                ExampleConfig cfg = new ExampleConfig(folder.FullName + "\\config.xml", false);

                string iconCls = string.IsNullOrEmpty(cfg.IconCls) ? "" : cfg.IconCls;
                AsyncTreeNode node = new AsyncTreeNode();

                node.Text = MarkNew(folder.FullName, folder.Name.Replace("_", " "));
                node.IconCls = iconCls;
                string url = PhysicalToVirtual(folder.FullName + "/");
                node.NodeID = "e" + Math.Abs(url.ToLower().GetHashCode());

                nodes.Add(node);
            }

            return nodes;
        }
 protected override TreeNodeCollection GetTreeNodes(string id, FormDataCollection queryStrings)
 {
     var nodes = new TreeNodeCollection();
     var item = this.CreateTreeNode("dashboard", id, queryStrings, "Applicaion Forms", "icon-truck", true);
     nodes.Add(item);
     return nodes;
 }
 protected override TreeNodeCollection GetTreeNodes(string id, FormDataCollection queryStrings)
 {
     TreeNodeCollection nodes = new TreeNodeCollection();
     TreeNode item = this.CreateTreeNode("-1", "-1", queryStrings, "");
     nodes.Add(item);
     return nodes;
 }
        private TreeNodeCollection AddFiles(string folder, FormDataCollection queryStrings)
        {
            var pickerApiController = new FileSystemPickerApiController();
            //var str = queryStrings.Get("startfolder");

            if (string.IsNullOrWhiteSpace(folder))
                return null;

            var filter = queryStrings.Get("filter").Split(',').Select(a => a.Trim().EnsureStartsWith(".")).ToArray();

            var path = IOHelper.MapPath(folder);
            var rootPath = IOHelper.MapPath(queryStrings.Get("startfolder"));
            var treeNodeCollection = new TreeNodeCollection();

            foreach (FileInfo file in pickerApiController.GetFiles(folder, filter))
            {
                string nodeTitle = file.Name;
                string filePath = file.FullName.Replace(rootPath, "").Replace("\\", "/");

                //if (file.Extension.ToLower() == ".gif" || file.Extension.ToLower() == ".jpg" || file.Extension.ToLower() == ".png")
                //{
                //    nodeTitle += "<div><img src=\"/umbraco/backoffice/FileSystemPicker/FileSystemThumbnailApi/GetThumbnail?width=150&imagePath="+ HttpUtility.UrlPathEncode(filePath) +"\" /></div>";
                //}

                TreeNode treeNode = CreateTreeNode(filePath, path, queryStrings, nodeTitle, "icon-document", false);
                treeNodeCollection.Add(treeNode);
            }

            return treeNodeCollection;
        }
        protected override Umbraco.Web.Models.Trees.TreeNodeCollection GetTreeNodes(string id, System.Net.Http.Formatting.FormDataCollection queryStrings)
        {
            //check if we're rendering the root node's children
            if (id == Constants.System.Root.ToInvariantString())
            {
                var ctrl = new PersonApiController();
                var nodes = new TreeNodeCollection();

                foreach (var person in ctrl.GetAll())
                {
                    var node = CreateTreeNode(
                        person.Id.ToString(),
                        "-1",
                        queryStrings,
                        person.ToString(),
                        "icon-user",
                        false);

                    nodes.Add(node);

                }
                return nodes;
            }

            //this tree doesn't suport rendering more than 1 level
            throw new NotSupportedException();
        }
Exemple #11
0
    public void BindBuMenTree(TreeNodeCollection Nds, int IDStr)
    {
        DataSet MYDT=ZWL.DBUtility.DbHelperSQL.GetDataSet("select * from ERPBuMen where DirID=" + IDStr.ToString() + " order by ID asc");
        for(int i=0;i<MYDT.Tables[0].Rows.Count;i++)
        {
            TreeNode OrganizationNode = new TreeNode();
            string CharManStr = "";
            if (MYDT.Tables[0].Rows[i]["ChargeMan"].ToString().Trim().Length <= 0)
            {
                CharManStr = "<font color=\"Red\">[未设置负责人]</font>";
            }
            else
            {
                CharManStr = MYDT.Tables[0].Rows[i]["ChargeMan"].ToString().Trim();
            }

            OrganizationNode.Text = MYDT.Tables[0].Rows[i]["BuMenName"].ToString() + "&nbsp;部门主管:" + CharManStr;
            OrganizationNode.ToolTip = "部门主管:" + MYDT.Tables[0].Rows[i]["ChargeMan"].ToString() + "\n电话:" + MYDT.Tables[0].Rows[i]["TelStr"].ToString() + "\n传真:" + MYDT.Tables[0].Rows[i]["ChuanZhen"].ToString() + "\n备注:" + MYDT.Tables[0].Rows[i]["BackInfo"].ToString();

            OrganizationNode.Value = MYDT.Tables[0].Rows[i]["ID"].ToString();
            int strId = int.Parse(MYDT.Tables[0].Rows[i]["ID"].ToString());
            OrganizationNode.ImageUrl = "~/images/user_group.gif";
            OrganizationNode.SelectAction = TreeNodeSelectAction.Expand;

            OrganizationNode.Expand();
            Nds.Add(OrganizationNode);
            //递归循环
            BindBuMenTree(Nds[Nds.Count - 1].ChildNodes, strId);
        }
    }
Exemple #12
0
        private TreeNodeCollection BuildTree(List<TypedTreeNodeItem<SystemDepartmentWrapper>> items)
        {
            TreeNodeCollection nodes = new TreeNodeCollection();

            TreeNode root = new TreeNode();
            root.Text = "All Department";
            root.Icon = Icon.Group;

            nodes.Add(root);

            if (items == null || items.Count == 0)
                return nodes;

            foreach (TypedTreeNodeItem<SystemDepartmentWrapper> menu in items)
            {
                TreeNode mainNode = new TreeNode();
                mainNode.Text = menu.Name;
                mainNode.NodeID = menu.Id;

                mainNode.Icon = Icon.Group;

                mainNode.CustomAttributes.Add(new ConfigItem("ID", menu.Id, ParameterMode.Value));
                GenerateSubTreeNode(mainNode, menu);
                root.Nodes.Add(mainNode);
            }

            return nodes;
        }
Exemple #13
0
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/json";

            // "node" will be a comma-separated list of nodes that are going to be deleted.
            string node = context.Request["node"];

            if (!string.IsNullOrEmpty(node))
            {
                string[] nodeIDsTemp = node.Split(',');
                var nodeIDs = nodeIDsTemp.Select(s => Convert.ToInt32(s));

                TreeNodeCollection treeNodes = new TreeNodeCollection();

                foreach (int nodeID in nodeIDs)
                {
                    ContentItem selectedItem = Context.Persister.Get(nodeID);

                    SiteTree tree = SiteTree.From(selectedItem, int.MaxValue);

                    TreeNodeBase treeNode = tree.Filter(items => items.Authorized(context.User, Context.SecurityManager, Operations.Read))
                        .ToTreeNode(false);

                    treeNodes.Add(treeNode);
                }

                string json = treeNodes.ToJson();
                context.Response.Write(json);
                context.Response.End();
            }
        }
        protected override TreeNodeCollection GetTreeNodes(string id, FormDataCollection queryStrings)
        {
            // check if we're rendering the root node's children
            if (id == Constants.System.Root.ToInvariantString())
            {
                var tree = new TreeNodeCollection();
                var ctrl = new EasyADApiController();

                foreach (var g in ctrl.GetAll())
                {
                    var node = CreateTreeNode(
                                    g.Id.ToInvariantString(),
                                    Constants.System.Root.ToInvariantString(),
                                    queryStrings,
                                    g.Name,
                                    "icon-users-alt");
                    tree.Add(node);
                }

                return tree;
            }

            // this tree doesn't support rendering more than 1 level
            throw new NotSupportedException();
        }
        protected override TreeNodeCollection GetTreeNodes(string id, FormDataCollection queryStrings)
        {
            // check if we're rendering the root node's children
            var items = id == RealUmbraco.Core.Constants.System.Root.ToInvariantString()
                ? DefinedContent.Cache.GetRootDefinedContentItems()
                : DefinedContent.Cache.GetDefinedContentItem(id).Children;
            
            // empty tree
            //var tree = new TreeNodeCollection()
            //{
            //    CreateTreeNode("Bobs Something", id, new FormDataCollection("somequerystring=2"), "Bob's News Root", "icon-anchor")
            //};

            var tree = new TreeNodeCollection();
            foreach (var item in items)
            {
                tree.Add(CreateTreeNode(item.Key, item.Key, null, item.Key, "icon-anchor", item.Children.Any()));
            }

            // but if we wanted to add nodes - 
            /*  var tree = new TreeNodeCollection
            {
                CreateTreeNode("1", id, queryStrings, "My Node 1"), 
                CreateTreeNode("2", id, queryStrings, "My Node 2"), 
                CreateTreeNode("3", id, queryStrings, "My Node 3")
            };*/
            return tree;
        }
    protected override TreeNodeCollection GetTreeNodes(string id, FormDataCollection queryStrings)
    {
        if (id == Constants.System.Root.ToInvariantString())
        {
            var ctrl = new ClientApiController();
            var nodes = new TreeNodeCollection();

            foreach (var client in ctrl.GetAll())
            {
                var node = CreateTreeNode(
                    client.Id.ToString(),
                    "-1",
                    queryStrings,
                    client.ToString(),
                    "icon-user",
                    false);

                nodes.Add(node);
            }

            return nodes;
        }

        throw new NotSupportedException();
    }
Exemple #17
0
    private void BindTree(TreeNodeCollection Nds, int IDStr)
    {
        SqlConnection Conn = new SqlConnection(ConfigurationManager.AppSettings["SQLConnectionString"].ToString());
        Conn.Open();
        SqlCommand MyCmd = new SqlCommand("select * from ERPBuMen where DirID=" + IDStr.ToString() + " order by ID asc", Conn);
        SqlDataReader MyReader = MyCmd.ExecuteReader();
        while (MyReader.Read())
        {
            TreeNode OrganizationNode = new TreeNode();
            OrganizationNode.Text = MyReader["BuMenName"].ToString();
            OrganizationNode.Value = MyReader["ID"].ToString();
            int strId = int.Parse(MyReader["ID"].ToString());
            OrganizationNode.ImageUrl = "~/images/user_group.gif";
            OrganizationNode.SelectAction =  TreeNodeSelectAction.Expand ;

            string ChildID = ZWL.DBUtility.DbHelperSQL.GetSHSLInt("select top 1 ID from ERPBuMen where DirID=" + MyReader["ID"].ToString() + " order by ID asc");
            if (ChildID.Trim() != "0")
            {
                //需要父项目一起选中,如果父项目不需要的话,请不要注释掉下面的行
                //HaveChild = HaveChild + "|" + MyReader["BuMenName"].ToString() + "|";
            }
            OrganizationNode.ToolTip = MyReader["BuMenName"].ToString();
            OrganizationNode.Expand();
            Nds.Add(OrganizationNode);
            //递归循环
            BindTree(Nds[Nds.Count - 1].ChildNodes, strId);
        }
        MyReader.Close();
        Conn.Close();
    }
        protected override TreeNodeCollection GetTreeNodes(string id, FormDataCollection queryStrings)
        {
            //we only support one tree level for data types
            //if (id != Constants.System.Root.ToInvariantString())
            //{
            //    throw new HttpResponseException(HttpStatusCode.NotFound);
            //}
            var collection = new TreeNodeCollection();
            if (id == "settings")
            {
                collection.Add(CreateTreeNode("shipping", "settings", queryStrings, "Shipping", "icon-truck", false, "merchello/merchello/Shipping/manage"));
                collection.Add(CreateTreeNode("taxation", "settings", queryStrings, "Taxation", "icon-piggy-bank", false, "merchello/merchello/Taxation/manage"));
                collection.Add(CreateTreeNode("payment", "settings", queryStrings, "Payment", "icon-bill-dollar", false, "merchello/merchello/Payment/manage"));
                collection.Add(CreateTreeNode("gateways", "settings", queryStrings, "Gateway Providers", "icon-trafic", false, "merchello/merchello/GatewayProviders/manage"));
                //collection.Add(CreateTreeNode("vendors", "settings", queryStrings, "Vendors", "icon-handshake", false, "merchello/merchello/Vendors/manage"));
                //collection.Add(CreateTreeNode("notifications", "settings", queryStrings, "Notifications", "icon-chat", false, "merchello/merchello/Notifications/manage"));
                //collection.Add(CreateTreeNode("debuglog", "settings", queryStrings, "Debug Log", "icon-alert", false, "merchello/merchello/Debug/manage"));
            }
            else if (id == "reports")
            {
                collection.Add(CreateTreeNode("salesOverTime", "reports", queryStrings, "Sales Over Time", "icon-loading", false, "merchello/merchello/SalesOverTime/manage"));
                collection.Add(CreateTreeNode("salesByItem", "reports", queryStrings, "Sales By Item", "icon-barcode", false, "merchello/merchello/SalesByItem/manage"));
                collection.Add(CreateTreeNode("taxesByDestination", "reports", queryStrings, "Taxes By Destination", "icon-piggy-bank", false, "merchello/merchello/TaxesByDestination/manage"));
            }
            else
            {
                collection.Add(CreateTreeNode("catalog", "", queryStrings, "Catalog", "icon-barcode", false, "merchello/merchello/ProductList/manage"));
                collection.Add(CreateTreeNode("orders", "", queryStrings, "Orders", "icon-receipt-dollar", false, "merchello/merchello/OrderList/manage"));
                //collection.Add(CreateTreeNode("customers", "", queryStrings, "Customers", "icon-user", false, "merchello/merchello/CustomerList/manage"));
                //collection.Add(CreateTreeNode("reports", "", queryStrings, "Reports", "icon-bar-chart", true, "merchello/merchello/Reports/manage"));
                collection.Add(CreateTreeNode("settings", "", queryStrings, "Settings", "icon-settings", true, "merchello/merchello/Settings/manage"));
            }

            //collection.AddRange(
            //    Services.DataTypeService.GetAllDataTypeDefinitions()
            //            .OrderBy(x => x.Name)
            //            .Select(dt =>
            //                    CreateTreeNode(
            //                        dt.Id.ToInvariantString(),
            //                        queryStrings,
            //                        dt.Name,
            //                        "icon-autofill",
            //                        false)));
            return collection;
        }
 protected override Umbraco.Web.Models.Trees.TreeNodeCollection GetTreeNodes(string id, System.Net.Http.Formatting.FormDataCollection queryStrings)
 {
     if (id != Constants.System.Root.ToInvariantString())
     {
         throw new HttpResponseException(HttpStatusCode.NotFound);
     }
     var node = CreateTreeNode("0", "-1", queryStrings, "Заказы", "icon-ordered-list");
     var nodes = new TreeNodeCollection();
     nodes.Add(node);
     return nodes;
 }
	public void WriteTree (TreeNodeCollection list)
	{
		foreach (LaneTreeNode n in Children) {
			//TreeMenuNode tn = new TreeMenuNode ();
			TreeNode tn = new TreeNode ();
			tn.Text = n.Lane.lane;
			tn.NavigateUrl = "index.aspx?lane=" + HttpUtility.UrlEncode (n.Lane.lane);
			list.Add (tn);
			n.WriteTree (tn.ChildNodes);
		}
	}
 protected override Umbraco.Web.Models.Trees.TreeNodeCollection GetTreeNodes(string id, FormDataCollection queryStrings)
 {
     var nodes = new TreeNodeCollection();
     IContentType ct = Services.ContentTypeService.GetContentType("ProductElement");
     IEnumerable<IContent> contents = Services.ContentService.GetContentOfContentType(ct.Id).Where(c => c.Status != ContentStatus.Trashed);
     foreach (IContent item in contents)
     {
         nodes.Add(CreateTreeNode(item.Id.ToString(), ct.Id.ToString(), queryStrings, item.Name, ct.Icon, false));
     }
     return nodes;
 }
    private void addNode(TreeNodeCollection treeNodeCollection, List<int> ids, int index)
    {
        if (ids.Count == index) return;
        var pessoa = new Pessoa(ids[index]);
        pessoa.Get();

        var node = new TreeNode(pessoa.Nome + " - " + pessoa.GetCargo().Descricao, pessoa.IDPessoa.ToString());
        node.Expanded = true;
        treeNodeCollection.Add(node);

        addNode(node.ChildNodes, ids, index + 1);
    }
        protected override TreeNodeCollection GetTreeNodes(string id, FormDataCollection queryStrings)
        {
            if (id == "-1")
            {
                var nodes = new TreeNodeCollection();

                var allContacts = this.CreateTreeNode("dashboard", id, queryStrings, "All Contact Message", "icon-list", false);
                var repliedContacts = this.CreateTreeNode("replied", id, queryStrings, "Replied Contact Message", "icon-check", false);
                var unRepliedContacts = this.CreateTreeNode("unreplied", id, queryStrings, "Un-Replied Contact Message", "icon-time", false);
                var spamContacts = this.CreateTreeNode("spam", id, queryStrings, "Spam", "icon-squiggly-line", false);
                var trashedContacts = this.CreateTreeNode("deleted", id, queryStrings, "Deleted", "icon-trash", false);
                var settingsContacts = this.CreateTreeNode("settings", id, queryStrings, "Settings", "icon-wrench", false);

                repliedContacts.RoutePath = "/uContactor/uContactorSection/replied/0";
                unRepliedContacts.RoutePath = "/uContactor/uContactorSection/unreplied/0";
                spamContacts.RoutePath = "/uContactor/uContactorSection/spam/0";
                trashedContacts.RoutePath = "/uContactor/uContactorSection/deleted/0";
                settingsContacts.RoutePath = "/uContactor/uContactorSection/settings/0";

                nodes.Add(allContacts);
                nodes.Add(repliedContacts);
                nodes.Add(unRepliedContacts);
                nodes.Add(spamContacts);
                nodes.Add(trashedContacts);
                nodes.Add(settingsContacts);

                return nodes;
            }

            throw new NotImplementedException();
        }
Exemple #24
0
        public static TreeNodeCollection FromPageCache(PageCache cache)
        {
            var rootNodes = new TreeNodeCollection(null);
            foreach (var page in cache.RootPages)
            {
                var node = CreateNode(page);
                rootNodes.Add(node);

                AddNode(page, node);
            }

            return rootNodes;
        }
        protected override Umbraco.Web.Models.Trees.TreeNodeCollection GetTreeNodes(string id, System.Net.Http.Formatting.FormDataCollection queryStrings)
        {
            //check if we're rendering the root node's children
            if (id == "-1")
            {
                var nodes = new TreeNodeCollection();
                nodes.Add(CreateTreeNode("people", id, queryStrings, "People", "icon-people", false, FormDataCollectionExtensions.GetValue<string>(queryStrings, "application") + StringExtensions.EnsureStartsWith(this.TreeAlias, '/') + "/overviewPeople/all"));
                return nodes;
            }

            //this tree doesn't suport rendering more than 2 levels
            throw new NotSupportedException();
        }
        private TreeNodeCollection BuildTree(string path, FormDataCollection queryStrings, string parentId)
        {
            var treeNodeCollection = new TreeNodeCollection();

            try
            {
                var viewsFolder = new DirectoryInfo(HttpContext.Current.Server.MapPath("~/Views/")).FullName;

                var dir = new DirectoryInfo(path);
                var subDirs = dir.GetDirectories();

                var files = dir.GetFiles().Where(x => x.Name.InvariantEndsWith(".cshtml"));

                foreach (var fi in files)
                {
                    var id = fi.FullName.Replace(viewsFolder, string.Empty);
                    var fileNameWithoutExtension = fi.Name.Substring(0, fi.Name.LastIndexOf('.'));
                    var treeNode = CreateTreeNode(id, parentId, queryStrings, fileNameWithoutExtension, "icon-document");
                    treeNodeCollection.Add(treeNode);
                }

                foreach (var sd in subDirs)
                {
                    var hasChildren = sd.GetFiles().Any(x => x.Name.InvariantEndsWith(".cshtml"));

                    var id = sd.FullName.Replace(viewsFolder, string.Empty);
                    var dirNode = CreateTreeNode(id, parentId, queryStrings, sd.Name, "icon-folder", hasChildren);
                    treeNodeCollection.Add(dirNode);
                }

            }
            catch (Exception ex)
            {
                //TODO: log this
            }

            return treeNodeCollection;
        }
    void BindTree(TreeNodeCollection nds, int parentId)
    {
        TreeNode tn = null;

        foreach (DataRow dr in _dataTable.Select("parentId=" + parentId))
        {
            tn = new TreeNode(dr["name"].ToString(), dr["id"].ToString());
            tn.ShowCheckBox = true;

            nds.Add(tn);

            BindTree(tn.ChildNodes, Convert.ToInt32(dr["id"]));
        }
    }
        protected override TreeNodeCollection GetTreeNodes(string id, FormDataCollection queryStrings)
        {
            TreeNodeCollection nodes = new TreeNodeCollection();
              if (id == Constants.System.Root.ToInvariantString())
              {
            foreach (IContent content in UserContentHelper.GetAllAppealed())
            {
              TreeNode appeal = this.CreateTreeNode(content.Id.ToString(), "-1", queryStrings, content.Name, "icon-user", false);
              nodes.Add(appeal);
            }
              }

              return nodes;
        }
        protected override TreeNodeCollection GetTreeNodes(string id, FormDataCollection queryStrings)
        {
            var ctrl = new MediaEditorController();
            var nodes = new TreeNodeCollection();

            //var item = this.CreateTreeNode("dashboard", id, queryStrings, "My item", "icon-truck", true);
            foreach(IMedia folder in ctrl.GetMediaFolders(int.Parse(id)))
            {
                var item = this.CreateTreeNode(folder.Id.ToString(), folder.ParentId.ToString(), queryStrings, folder.Name, "icon-folder", (folder.Children()!=null && folder.Children().Where(m => m.ContentType.Alias == "Folder").Count() > 0));
                nodes.Add(item);
            }

            return nodes;
        }
        protected override TreeNodeCollection GetTreeNodes(string id, FormDataCollection queryStrings)
        {
            var nodes = new TreeNodeCollection();

            // [Custom form setup]: Put your forms in web.config - the name must be unique
            var config = CustomFormsConfig.GetConfig();
            foreach (Form form in config.Forms)
            {           
                var formNode = this.CreateTreeNode(form.Name, "-1", queryStrings, form.DisplayName, "icon-conversation-alt", false);

                nodes.Add(formNode);
            }

            return nodes;
        }
Exemple #31
0
        private void IterateContent(TreeNodeCollection root, ModObject mod, string currPath, string acceptExt, bool isBase = false)
        {
            if (!Directory.Exists(currPath))
            {
                return;
            }

            if (isBase)
            {
                var node = root.Add("folder", Path.GetFileName(currPath), "folder", "folder");
                IterateContent(node.Nodes, mod, currPath, acceptExt);
                return;
            }
            foreach (string path in Directory.GetFiles(currPath, "*.*"))
            {
                Debug.WriteLine(GameFinder.GetCookedPcDir());
                var exts      = acceptExt.Split('|');
                var extension = Path.GetExtension(path);
                var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(path);
                if (!exts.Contains(acceptExt))
                {
                    var treeNode = root.Add("", Path.GetFileName(path), "error", "error");
                    var text     = "This asset does not belong here.";
                    foreach (var a in Adict)
                    {
                        if (exts.Contains(a.Key))
                        {
                            text += Environment.NewLine + a.Value;
                        }
                    }

                    foreach (var b in BDict)
                    {
                        if (extension == b.Key)
                        {
                            text += Environment.NewLine + b.Value;
                        }
                    }

                    treeNode.Tag    = new ContentTreeViewInfo(Path.GetFileName(path), text);
                    HasContentError = true;
                }
                else if (fileNameWithoutExtension.ToLower() == mod.GetDirectoryName().ToLower() && !exts.Contains(".int") && !exts.Contains(".umap"))
                {
                    var treeNode = root.Add("", Path.GetFileName(path), "error", "error");
                    treeNode.Tag    = new ContentTreeViewInfo(Path.GetFileName(path), "Packages can't have the same name as your mod folder.\nAdd a _Content suffix or something. Example:\n" + fileNameWithoutExtension + "_Content" + extension);
                    HasContentError = true;
                }
                else if (Utils.FileExists(GameFinder.GetCookedPcDir(), Path.GetFileName(path)))
                {
                    var treeNode = root.Add("", Path.GetFileName(path), "error", "error");
                    treeNode.Tag    = new ContentTreeViewInfo(Path.GetFileName(path), "There's an asset with an identical name in CookedPC.\nPlease give your asset another name.\n(btw don't put your own stuff in CookedPC. Keep it to the mods folder.)");
                    HasContentError = true;
                }
                else
                {
                    var ext      = exts.Contains(".int") ? "localization" : "package";
                    var treeNode = root.Add("", Path.GetFileName(path), ext, ext);
                    treeNode.Tag = new ContentTreeViewInfo(Path.GetFileName(path), "");
                }
            }
            foreach (var file in Directory.GetDirectories(currPath))
            {
                var node = root.Add("", Path.GetFileName(file), "folder", "folder");
                IterateContent(node.Nodes, mod, file, acceptExt);
            }
        }
        public bool FRAMEParser(ref TreeNodeCollection mNode, byte [] PacketData, ref int Index, ref ListViewItem LItem)
        {
            TreeNode mNodex;
            string   Tmp = "";
            int      i   = 0;

            mNode.Clear();

            mNodex = new TreeNode();

            try
            {
                PItem.Seconds = Function.Get4Bytes(PacketData, ref Index, Const.VALUE);
                Tmp           = " Seconds : " + PItem.Seconds.ToString();
                mNodex.Nodes.Add(Tmp);

                PItem.MicroSeconds = Function.Get4Bytes(PacketData, ref Index, Const.VALUE);
                Tmp = " Microseconds : " + PItem.MicroSeconds.ToString();
                mNodex.Nodes.Add(Tmp);

                PItem.CaptureLength = Function.Get4Bytes(PacketData, ref Index, Const.VALUE);
                Tmp = " Captured Length : " + PItem.CaptureLength.ToString();
                mNodex.Nodes.Add(Tmp);

                PItem.PacketLength = Function.Get4Bytes(PacketData, ref Index, Const.VALUE);
                Tmp = " Packet Length : " + PItem.PacketLength.ToString();
                mNodex.Nodes.Add(Tmp);

                PItem.Reserved = 0;
                if (PacketOnOff)
                {
                    PItem.Reserved = Function.Get4Bytes(PacketData, ref Index, Const.VALUE);
                }

                Tmp = "FRAME ( Captured : " + PItem.CaptureLength.ToString() +
                      " , Original : " + PItem.PacketLength.ToString() + " )";
                mNodex.Text = Tmp;
                mNodex.Tag  = "0," + PItem.CaptureLength.ToString();

                PItem.CaptureTimeStr = "";

                if (!PacketOnOff)
                {
                    Index          -= 16;
                    PItem.FrameData = new byte[16];
                    for (i = 0; i < 16; i++)
                    {
                        PItem.FrameData[i] = PacketData[Index++];
                    }
                }
                else
                {
                    Index          -= 20;
                    PItem.FrameData = new byte[20];
                    for (i = 0; i < 20; i++)
                    {
                        PItem.FrameData[i] = PacketData[Index++];
                    }
                }

                PItem.Data = new byte[PItem.CaptureLength];

                for (i = 0; i < PItem.CaptureLength; i++)
                {
                    PItem.Data[i] = PacketData[Index++];
                }

                LItem.SubItems[Const.LIST_VIEW_INFO_INDEX].Text = "Fram Data";

                mNode.Add(mNodex);
            }
            catch (Exception Ex)
            {
                mNode.Add(mNodex);
                Tmp = "[ Malformed FRAME packet. Remaining bytes don't fit an FRAME packet. Possibly due to bad decoding ]";
                mNode.Add(Tmp);
                Tmp = "[ Exception raised is <" + Ex.GetType().ToString() + "> at packet index <" + Index.ToString() + "> ]";
                mNode.Add(Tmp);
                LItem.SubItems[Const.LIST_VIEW_INFO_INDEX].Text = "[ Malformed FRAME packet. Remaining bytes don't fit an FRAME packet. Possibly due to bad decoding ]";

                return(false);
            }

            return(true);
        }
        /// <summary>
        /// Loads children items for the provided item in to the specified nodes.
        /// Loaded children are cached until <see cref="ResetCache"/> method is called.
        /// For file type items it also loads icons associated with these types at the OS level.
        /// </summary>
        /// <remarks>The method DOES NOT check any input parameters for performance reasons.</remarks>
        public void LoadChildren(IGitItem item, TreeNodeCollection nodes, ImageList.ImageCollection imageCollection)
        {
            var childrenItems = _cachedItems.GetOrAdd(item.Guid, _revisionInfoProvider.LoadChildren(item));

            if (childrenItems is null)
            {
                return;
            }

            string workingDir = null;

            foreach (var childItem in childrenItems.OrderBy(gi => gi, new GitFileTreeComparer()))
            {
                var subNode = nodes.Add(childItem.Name);
                subNode.Tag = childItem;

                if (!(childItem is GitItem gitItem))
                {
                    subNode.Nodes.Add(new TreeNode());
                    continue;
                }

                switch (gitItem.ObjectType)
                {
                case GitObjectType.Tree:
                {
                    subNode.ImageIndex = subNode.SelectedImageIndex = TreeNodeImages.Folder;
                    subNode.Nodes.Add(new TreeNode());
                    break;
                }

                case GitObjectType.Commit:
                {
                    subNode.ImageIndex = subNode.SelectedImageIndex = TreeNodeImages.Submodule;
                    subNode.Text       = $@"{childItem.Name} (Submodule)";
                    break;
                }

                case GitObjectType.Blob:
                {
                    var extension = PathUtil.GetExtension(gitItem.FileName);

                    if (string.IsNullOrWhiteSpace(extension))
                    {
                        continue;
                    }

                    if (!imageCollection.ContainsKey(extension))
                    {
                        // lazy - initialise the first time used
                        workingDir ??= _getWorkingDir();

                        var fileIcon = _iconProvider.Get(workingDir, gitItem.FileName);
                        if (fileIcon is null)
                        {
                            continue;
                        }

                        imageCollection.Add(extension, fileIcon);
                    }

                    subNode.ImageKey = subNode.SelectedImageKey = extension;
                    break;
                }
                }
            }
        }
Exemple #34
0
        //方法需传入绝对路径,以及Treeview的Name的Nodes属性
        private void GetNodeValue(string path, TreeNodeCollection tc, bool IsFirst = true)
        {
            try
            {
                //加载选定文件夹下的文件的名字
                string[] FilePath = Directory.GetDirectories(path);
                tv.ImageList = filesIcons;
                //获得文件的名字
                string filename = string.Empty;
                //获得文件夹的名字
                for (int i = 0; i < FilePath.Length; i++)
                {
                    filename = Path.GetFileNameWithoutExtension(FilePath[i]);
                    if (filename == "temp")
                    {
                        continue;
                    }
                    if (IsFirst)
                    {
                        if (!Global.userMsgData.FilePermission.Contains(filename))
                        {
                            continue;
                        }
                    }
                    TreeNode tn = new TreeNode
                    {
                        Text               = filename,
                        ImageIndex         = IconIndexes.ClosedFolder,
                        SelectedImageIndex = IconIndexes.ClosedFolder,
                        Tag = CommonData.FileType.Folder
                    };
                    //在treeview节点下存下每个节点的路径
                    tc.Add(tn);
                    //if()
                    //这里遇到了递归,遇到文件夹,先进入文件夹里面去遍历,将大的tr,替换为小的tr
                    GetNodeValue(FilePath[i], tn.Nodes, false);
                }
                //因为目录名不能被点击,获得目录下的文件
                //获得文件夹下文件的名字,
                string[] Newfilepath = Directory.GetFiles(path);
                for (int i = 0; i < Newfilepath.Length; i++)
                {
                    //filename = Path.GetFileName(Newfilepath[i]);
                    CommonData.MainFormFile myfile = new CommonData.MainFormFile();
                    filename = Path.GetFileNameWithoutExtension(Newfilepath[i]);
                    if (Path.GetExtension(Newfilepath[i]) != ".temp")
                    {
                        continue;
                    }
                    TreeNode tn = new TreeNode
                    {
                        ImageIndex = -1
                    };

                    //取出文件拓展名
                    string filenameExtension     = filename.Substring(filename.IndexOf('.') + 1);
                    CommonData.FileType fileType = GetFileType(filenameExtension);
                    switch (fileType)
                    {
                    case CommonData.FileType.Pdf:
                    {
                        tn.ImageIndex         = IconIndexes.PDFFile;
                        tn.SelectedImageIndex = IconIndexes.PDFFile;
                    }
                    break;

                    case CommonData.FileType.Video:
                    {
                        tn.ImageIndex         = IconIndexes.VideoFile;
                        tn.SelectedImageIndex = IconIndexes.VideoFile;
                    }
                    break;

                    case CommonData.FileType.TXT:
                    {
                        tn.ImageIndex         = IconIndexes.TXTFile;
                        tn.SelectedImageIndex = IconIndexes.TXTFile;
                    }
                    break;

                    case CommonData.FileType.Image:
                    {
                        tn.ImageIndex         = IconIndexes.PicFile;
                        tn.SelectedImageIndex = IconIndexes.PicFile;
                    }
                    break;

                    case CommonData.FileType.PCB:
                    {
                        tn.ImageIndex         = IconIndexes.PCBFile;
                        tn.SelectedImageIndex = IconIndexes.PCBFile;
                    }
                    break;

                    case CommonData.FileType.Web:
                    {
                        tn.ImageIndex         = IconIndexes.WebFile;
                        tn.SelectedImageIndex = IconIndexes.WebFile;
                    }
                    break;
                    }
                    tn.Text = Path.GetFileNameWithoutExtension(filename);
                    tn.Name = Newfilepath[i];
                    //在treeview节点下存下每个节点的路径
                    tn.Tag = fileType;
                    myfile.FileLocalPath = Newfilepath[i];
                    myfile.FileName      = Path.GetFileNameWithoutExtension(filename);
                    myfile.FileType      = fileType;
                    tc.Add(tn);
                    LocalFileList.Add(myfile);
                    //fileInfo.Add(tn.Text)
                    //}
                }
            }
            catch (Exception ex)
            {
                Log.Error("[" + System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "][" + System.Reflection.MethodBase.GetCurrentMethod().Name + "] err" + ex);
                MessageBox.Show(ex.Message);
            }
        }
 private void AddDummyNode(TreeNodeCollection tnc)
 {
     tnc.Add(new DummyTreeNode( ));
 }
        public static bool Parser(ref TreeNodeCollection mNode,
                                  byte [] PacketData,
                                  ref int Index,
                                  ref ListViewItem LItem, ref uint PreviousHttpSequence)
        {
            TreeNode   mNodex;
            TreeNode   mNode1;
            string     Tmp = "";
            PACKET_TCP PTcp;

            mNodex      = new TreeNode();
            mNodex.Text = "TCP ( Transmission Control Protocol )";
            Function.SetPosition(ref mNodex, Index, Const.LENGTH_OF_TCP, true);

            if ((Index + Const.LENGTH_OF_TCP) > PacketData.Length)
            {
                mNode.Add(mNodex);
                Tmp = "[ Malformed TCP packet. Remaining bytes don't fit an TCP packet. Possibly due to bad decoding ]";
                mNode.Add(Tmp);
                LItem.SubItems[Const.LIST_VIEW_INFO_INDEX].Text = Tmp;

                return(false);
            }

            try
            {
                PTcp.SourcePort = Function.Get2Bytes(PacketData, ref Index, Const.NORMAL);
                Tmp             = "Source Port : " + Function.ReFormatString(PTcp.SourcePort, Const.GetPortStr(PTcp.SourcePort));
                mNodex.Nodes.Add(Tmp);
                Function.SetPosition(ref mNodex, Index - 2, 2, false);

                PTcp.DestinationPort = Function.Get2Bytes(PacketData, ref Index, Const.NORMAL);
                Tmp = "Destination Port : " + Function.ReFormatString(PTcp.DestinationPort, Const.GetPortStr(PTcp.DestinationPort));
                mNodex.Nodes.Add(Tmp);
                Function.SetPosition(ref mNodex, Index - 2, 2, false);

                PTcp.SequenceNumber = Function.Get4Bytes(PacketData, ref Index, Const.NORMAL);
                Tmp = "Sequence Number : " + Function.ReFormatString(PTcp.SequenceNumber, null);
                mNodex.Nodes.Add(Tmp);
                Function.SetPosition(ref mNodex, Index - 4, 4, false);

                PTcp.Acknowledgement = Function.Get4Bytes(PacketData, ref Index, Const.NORMAL);
                Tmp = "Acknowledgement : " + Function.ReFormatString(PTcp.Acknowledgement, null);
                mNodex.Nodes.Add(Tmp);
                Function.SetPosition(ref mNodex, Index - 4, 4, false);

                PTcp.HeaderLength = PacketData[Index++];
                PTcp.HeaderLength = (byte)(((int)PTcp.HeaderLength >> 4) * 4);
                Tmp = "Length : " + Function.ReFormatString(PTcp.HeaderLength, null);
                mNodex.Nodes.Add(Tmp);
                Function.SetPosition(ref mNodex, Index - 1, 1, false);

                PTcp.Falgs  = PacketData[Index++];
                mNode1      = new TreeNode();
                mNode1.Text = "Flags : " + Function.ReFormatString(PTcp.Falgs, null);
                Function.SetPosition(ref mNode1, Index - 1, 1, true);
                mNode1.Nodes.Add(Function.DecodeBitField(PTcp.Falgs, 0x80, "Congestion window reduced ( CWR ) : Set", "Congestion window reduced ( CWR ) : Not set"));
                Function.SetPosition(ref mNode1, Index - 1, 1, false);
                mNode1.Nodes.Add(Function.DecodeBitField(PTcp.Falgs, 0x40, "ECN-Echo : Set", "ECN-Echo : Not set"));
                Function.SetPosition(ref mNode1, Index - 1, 1, false);
                mNode1.Nodes.Add(Function.DecodeBitField(PTcp.Falgs, 0x20, "Urgent : Set", "Urgent : Not set"));
                Function.SetPosition(ref mNode1, Index - 1, 1, false);
                mNode1.Nodes.Add(Function.DecodeBitField(PTcp.Falgs, 0x10, "Acknowldegement : Set", "Acknowldegement : Not set"));
                Function.SetPosition(ref mNode1, Index - 1, 1, false);
                mNode1.Nodes.Add(Function.DecodeBitField(PTcp.Falgs, 0x08, "Push : Set", "Push : Not set"));
                Function.SetPosition(ref mNode1, Index - 1, 1, false);
                mNode1.Nodes.Add(Function.DecodeBitField(PTcp.Falgs, 0x04, "Reset : Set", "Reset : Not set"));
                Function.SetPosition(ref mNode1, Index - 1, 1, false);
                mNode1.Nodes.Add(Function.DecodeBitField(PTcp.Falgs, 0x02, "Sync : Set", "Sync : Not set"));
                Function.SetPosition(ref mNode1, Index - 1, 1, false);
                mNode1.Nodes.Add(Function.DecodeBitField(PTcp.Falgs, 0x01, "Fin : Set", "Fin : Not set"));
                Function.SetPosition(ref mNode1, Index - 1, 1, false);
                mNodex.Nodes.Add(mNode1);

                PTcp.WindowSize = Function.Get2Bytes(PacketData, ref Index, Const.NORMAL);
                Tmp             = "Window Size : " + Function.ReFormatString(PTcp.WindowSize, null);
                mNodex.Nodes.Add(Tmp);
                Function.SetPosition(ref mNodex, Index - 2, 2, false);

                PTcp.Checksum = Function.Get2Bytes(PacketData, ref Index, Const.NORMAL);
                Tmp           = "Checksum : " + Function.ReFormatString(PTcp.Checksum, null);
                mNodex.Nodes.Add(Tmp);
                Function.SetPosition(ref mNodex, Index - 2, 2, false);

                PTcp.Options = Function.Get2Bytes(PacketData, ref Index, Const.NORMAL);
                Tmp          = "Options : " + Function.ReFormatString(PTcp.Options, null);
                mNodex.Nodes.Add(Tmp);
                Function.SetPosition(ref mNodex, Index - 2, 2, false);

                LItem.SubItems[Const.LIST_VIEW_PROTOCOL_INDEX].Text = "TCP";
                LItem.SubItems[Const.LIST_VIEW_INFO_INDEX].Text     = "Source Port = " + PTcp.SourcePort.ToString() + " ( " + Const.GetPortStr(PTcp.SourcePort) + " ) , Destination Port = " + PTcp.DestinationPort.ToString() + " ( " + Const.GetPortStr(PTcp.DestinationPort) + " )";

                mNode.Add(mNodex);

                bool IsCifs = false;

                if ((PTcp.SourcePort == Const.IPPORT_HTTP) ||
                    (PTcp.DestinationPort == Const.IPPORT_HTTP) ||
                    (PTcp.SourcePort == Const.IPPORT_HTTP2) ||
                    (PTcp.DestinationPort == Const.IPPORT_HTTP2))
                {
                    if (PreviousHttpSequence == (PTcp.SequenceNumber - (PacketData.Length - 54)))
                    {
                        PreviousHttpSequence = PTcp.SequenceNumber;
                        PacketHTTP.Parser(ref mNode, PacketData, ref Index, ref LItem, false);
                    }
                    else
                    {
                        PreviousHttpSequence = 0;
                        PacketHTTP.Parser(ref mNode, PacketData, ref Index, ref LItem, true);
                    }
                }
                else if ((PTcp.SourcePort == Const.IPPORT_NBSSN) ||
                         (PTcp.DestinationPort == Const.IPPORT_NBSSN))
                {
                    if ((PTcp.SourcePort == Const.TCP_PORT_CIFS) || (PTcp.DestinationPort == Const.TCP_PORT_CIFS))
                    {
                        IsCifs = true;
                    }
                    else
                    {
                        IsCifs = false;
                    }

                    PacketNBSS.Parser(ref mNode, PacketData, ref Index, ref LItem, IsCifs);
                }
            }
            catch (Exception Ex)
            {
                mNode.Add(mNodex);
                Tmp = "[ Malformed TCP packet. Remaining bytes don't fit an TCP packet. Possibly due to bad decoding ]";
                mNode.Add(Tmp);
                Tmp = "[ Exception raised is <" + Ex.GetType().ToString() + "> at packet index <" + Index.ToString() + "> ]";
                mNode.Add(Tmp);
                LItem.SubItems[Const.LIST_VIEW_INFO_INDEX].Text = "[ Malformed TCP packet. Remaining bytes don't fit an TCP packet. Possibly due to bad decoding ]";

                return(false);
            }

            return(true);
        }
Exemple #37
0
 private TreeNode AddLoadingNode(TreeNodeCollection nodes)
 {
     return(nodes.Add("Loading ...", "Loading ...", (int)ObjImage.Loading));
 }
Exemple #38
0
        private void runCheckButton_Click(object sender, EventArgs e)
        {
            var checkDups  = checkDuplicates.Checked;
            var checkLen   = checkLength.Checked;
            var lenToCheck = Convert.ToInt32(lengthToCheckInput.Value);
            var checkComp  = checkComplexity.Checked;
            var comp       = (PasswordScore)complexitySlider.Value;

            if (!checkDups && !checkLen && !checkComp)
            {
                MessageBox.Show("You must select at least one criteria to check.", "Error");
                return;
            }

            runCheckButton.Enabled     = false;
            checkDuplicates.Enabled    = false;
            checkLength.Enabled        = false;
            lengthToCheckInput.Enabled = false;
            checkComplexity.Enabled    = false;
            complexitySlider.Enabled   = false;

            try
            {
                this.statusLabel.Text = "Starting Check...";
                PwDatabase pwdb = m_host.Database;

                if (!pwdb.IsOpen)
                {
                    statusLabel.Text = "Please open database first...";
                    return;
                }

                PwObjectList <PwEntry> entries = pwdb.RootGroup.GetEntries(true);

                if (entries != null)
                {
                    statusLabel.Text = "Database opened, " + entries.UCount + " entries to check...";
                }
                else
                {
                    statusLabel.Text = "No entries in Database.";
                    return;
                }

                //Used to check for Duplicate Passwords
                Dictionary <string, List <string> > results = new Dictionary <string, List <string> >(entries.Count <PwEntry>());
                //Used to check password length
                List <string> shortPasses = new List <string>();
                //Used to check password complexity
                List <string> simplePasses = new List <string>();

                foreach (var entry in entries)
                {
                    string pass = entry.Strings.Get(PwDefs.PasswordField).ReadString();
                    if (pass.Equals(""))
                    {
                        continue;
                    }
                    if (checkDups)
                    {
                        if (results.ContainsKey(pass))
                        {
                            results[pass].Add(entry.Strings.Get(PwDefs.TitleField).ReadString());
                        }
                        else
                        {
                            List <string> list = new List <string>();
                            var           xx   = entry.Strings.Get(PwDefs.TitleField);
                            if (xx != null)
                            {
                                list.Add(xx.ReadString());
                            }
                            else
                            {
                                var urlxx = entry.Strings.Get(PwDefs.UrlField);
                                if (urlxx != null)
                                {
                                    list.Add(urlxx.ReadString());
                                }
                                else
                                {
                                    list.Add(entry.ToString());
                                }
                            }
                            results.Add(pass, list);
                        }
                    }
                    if (checkLen)
                    {
                        if (pass.Length < lenToCheck)
                        {
                            shortPasses.Add(entry.Strings.Get(PwDefs.TitleField).ReadString() + " (" + pass.Length + ")");
                        }
                    }

                    if (checkComp)
                    {
                        var tcomp = PasswordAdvisor.CheckStrength(pass);
                        if (tcomp < comp)
                        {
                            simplePasses.Add(entry.Strings.Get(PwDefs.TitleField).ReadString() + " (" + Enum.GetName(typeof(PasswordScore), tcomp) + ")");
                        }
                    }
                }

                checkResultsView.BeginUpdate();

                TreeNodeCollection nodes = checkResultsView.Nodes;

                checkResultsView.Nodes.Clear();

                if (checkDups)
                {
                    int dupPass = 1;
                    foreach (KeyValuePair <string, List <string> > result in results)
                    {
                        if (result.Value.Count > 1)
                        {
                            List <TreeNode> children = new List <TreeNode>();
                            foreach (var title in result.Value)
                            {
                                children.Add(new TreeNode(title));
                            }
                            TreeNode node = new TreeNode(string.Format("Duplicated Password [{0}] ({1})", result.Key, children.Count), children.ToArray());
                            nodes.Add(node);
                            dupPass++;
                        }
                    }
                }

                if (checkLen)
                {
                    if (shortPasses.Count > 0)
                    {
                        List <TreeNode> children = new List <TreeNode>();
                        foreach (var title in shortPasses)
                        {
                            children.Add(new TreeNode(title));
                        }
                        TreeNode node = new TreeNode("Short Passwords", children.ToArray());
                        nodes.Add(node);
                    }
                }

                if (checkComp)
                {
                    if (simplePasses.Count > 0)
                    {
                        List <TreeNode> children = new List <TreeNode>();
                        foreach (var title in simplePasses)
                        {
                            children.Add(new TreeNode(title));
                        }
                        TreeNode node = new TreeNode("Simple Passwords", children.ToArray());
                        nodes.Add(node);
                    }
                }

                checkResultsView.EndUpdate();

                statusLabel.Text = "Check complete.";
            }
            catch (NullReferenceException nre)
            {
                MessageBox.Show(string.Format("I tried to read a null value.\n{0}", nre.StackTrace));
                throw;
            }
            runCheckButton.Enabled     = true;
            checkDuplicates.Enabled    = true;
            checkLength.Enabled        = true;
            lengthToCheckInput.Enabled = true;
            checkComplexity.Enabled    = true;
            complexitySlider.Enabled   = true;
        }
 public void Add(TreeNode item)
 {
     _collection.Add(item);
 }
Exemple #40
0
        protected override TreeNodeCollection GetTreeNodes(string id, System.Net.Http.Formatting.FormDataCollection queryStrings)
        {
            var  ctrl        = new PipelineApiController();
            var  nodes       = new TreeNodeCollection();
            var  mainRoute   = "/pipelineCrm/pipelineCrmTree";
            bool useBoard    = PipelineConfig.GetConfig().AppSettings.UseBoard;
            var  customAreas = GetCustomAreas();

            if (id == Constants.System.Root.ToInvariantString())
            {
                nodes.Add(
                    CreateTreeNode(
                        "pipelines",
                        null,
                        queryStrings,
                        GetTranslation("pipeline/opportunities"),
                        "icon-dashboard",
                        true,
                        useBoard ? "/pipelineCrm" : "/pipelineCrm/pipelineCrmTree/browse/0"
                        )
                    );

                nodes.Add(
                    CreateTreeNode(
                        "tasks",
                        null,
                        queryStrings,
                        GetTranslation("pipeline/tasks"),
                        "icon-checkbox",
                        false,
                        mainRoute + "/tasks/0"
                        )
                    );

                nodes.Add(
                    CreateTreeNode(
                        "contacts",
                        null,
                        queryStrings,
                        GetTranslation("pipeline/contacts"),
                        "icon-user",
                        true,
                        mainRoute + "/contacts/0"
                        )
                    );

                nodes.Add(
                    CreateTreeNode(
                        "organisations",
                        "-1",
                        queryStrings,
                        GetTranslation("pipeline/organisations"),
                        "icon-company",
                        true,
                        mainRoute + "/organisations/0"
                        )
                    );

                nodes.Add(
                    CreateTreeNode(
                        "segments",
                        "-1",
                        queryStrings,
                        GetTranslation("pipeline/segments"),
                        "icon-users",
                        true,
                        mainRoute + "/segments/0"
                        )
                    );

                // get custom building blocks
                foreach (var type in customAreas)
                {
                    nodes.Add(
                        CreateTreeNode(
                            type.Alias,
                            "-1",
                            queryStrings,
                            type.Name,
                            type.Icon,
                            type.Folders.Any(),
                            mainRoute + "/" + type.Url
                            )
                        );
                }

                nodes.Add(
                    CreateTreeNode(
                        "recyclebin",
                        null,
                        queryStrings,
                        GetTranslation("general/recycleBin"),
                        "icon-trash",
                        true,
                        "/pipelineCrm/pipelineCrmTree/browse/-1"
                        )
                    );

                nodes.Add(
                    CreateTreeNode(
                        "settings",
                        null,
                        queryStrings,
                        GetTranslation("pipeline/settings"),
                        "icon-settings",
                        false,
                        mainRoute + "/settings/0"
                        )
                    );
            }
            else if (id == "pipelines")
            {
                // list all opp statuses
                foreach (var status in GetStatuses())
                {
                    var newTreeNode = CreateTreeNode(
                        status.Id.ToString() + "_pipelines",
                        id,
                        queryStrings,
                        status.Name,
                        "icon-dashboard",
                        false,
                        "/pipelineCrm/pipelineCrmTree/browse/" + status.Id.ToString());
                    nodes.Add(newTreeNode);
                }

                // get unassigned pipelines
                var unassigned = ctrl.GetByStatusId(0);
                nodes.Add(
                    CreateTreeNode(
                        "0",
                        id,
                        queryStrings,
                        GetTranslation("pipeline/none"),
                        "icon-dashboard",
                        false,
                        "/pipelineCrm/pipelineCrmTree/browse/-2"
                        )
                    );
            }
            else if (id == "organisations")
            {
                // list all org types
                foreach (var type in GetOrgTypes())
                {
                    var newTreeNode = CreateTreeNode(
                        type.Id.ToString() + "_organisations",
                        id,
                        queryStrings,
                        type.Name,
                        "icon-company",
                        false,
                        mainRoute + "/organisations/" + type.Id.ToString());
                    nodes.Add(newTreeNode);
                }

                // get unassigned orgs
                var unassigned = ctrl.GetByStatusId(0);
                nodes.Add(
                    CreateTreeNode(
                        "0",
                        id,
                        queryStrings,
                        GetTranslation("pipeline/none"),
                        "icon-company",
                        false,
                        mainRoute + "/organisations/-2"
                        )
                    );
            }
            else if (id == "contacts")
            {
                // list all orgs
                foreach (var type in new ContactTypeApiController().GetAll())
                {
                    var newTreeNode = CreateTreeNode(
                        type.Id.ToString() + "_contacts",
                        id,
                        queryStrings,
                        type.Name,
                        "icon-user",
                        false,
                        mainRoute + "/contacts/" + type.Id.ToString());
                    nodes.Add(newTreeNode);
                }

                // get contacts with no groups
                nodes.Add(
                    CreateTreeNode(
                        "0",
                        id,
                        queryStrings,
                        GetTranslation("pipeline/none"),
                        "icon-user",
                        false,
                        mainRoute + "/contacts/-2"
                        )
                    );
            }

            // segments
            else if (id == "segments")
            {
                // list all segment types
                foreach (var type in new SegmentTypeApiController().GetAll())
                {
                    var newTreeNode = CreateTreeNode(
                        type.Id.ToString() + "_segments",
                        id,
                        queryStrings,
                        type.Name,
                        "icon-users",
                        false,
                        mainRoute + "/segments/" + type.Id.ToString());
                    nodes.Add(newTreeNode);
                }
            }

            else if (id == "recyclebin")
            {
                // pipelines
                nodes.Add(
                    CreateTreeNode(
                        "0",
                        id,
                        queryStrings,
                        GetTranslation("pipeline/opportunities"),
                        "icon-dashboard",
                        false,
                        "/pipelineCrm/pipelineCrmTree/browse/-1"
                        )
                    );

                // contacts
                nodes.Add(
                    CreateTreeNode(
                        "0",
                        id,
                        queryStrings,
                        GetTranslation("pipeline/contacts"),
                        "icon-user",
                        false,
                        mainRoute + "/contacts/-1"
                        )
                    );

                // groups
                nodes.Add(
                    CreateTreeNode(
                        "0",
                        id,
                        queryStrings,
                        GetTranslation("pipeline/organisations"),
                        "icon-company",
                        false,
                        mainRoute + "/organisations/-1"
                        )
                    );


                nodes.Add(
                    CreateTreeNode(
                        "0",
                        id,
                        queryStrings,
                        GetTranslation("pipeline/segments"),
                        "icon-users",
                        false,
                        mainRoute + "/segments/-1"
                        )
                    );
            }

            else if (customAreas.Any(x => x.Alias == id))
            {
                var area = customAreas.FirstOrDefault(x => x.Alias == id);

                // list all orgs
                foreach (var folder in area.Folders)
                {
                    var newTreeNode = CreateTreeNode(
                        folder.Url + "_" + area.Alias,
                        id,
                        queryStrings,
                        folder.Name,
                        area.Icon,
                        false,
                        mainRoute + "/" + folder.Url);
                    nodes.Add(newTreeNode);
                }
            }

            return(nodes);

            //this tree doesn't suport rendering more than 1 level
            throw new NotSupportedException();
        }
Exemple #41
0
 private void BuildXML(string filename)
 {
     coll.Add(Helper.ToTreeNode(filename, filename));
 }
        protected override TreeNodeCollection GetTreeNodes(string id,
                                                           FormDataCollection queryStrings)
        {
            var entityId          = GuidHelper.GetGuid(id);
            var nodes             = new TreeNodeCollection();
            var rootId            = CoreConstants.System.Root.ToInvariantString();
            var rootFormsId       = GuidHelper.GetGuid(FormConstants.Id);
            var rootLayoutsId     = GuidHelper.GetGuid(LayoutConstants.Id);
            var rootValidationsId = GuidHelper.GetGuid(
                ValidationConstants.Id);
            var rootDataValueId = GuidHelper.GetGuid(DataValueConstants.Id);

            if (id.InvariantEquals(rootId))
            {
                // Get root nodes.
                var formatUrl    = "/formulate/formulate/{0}/{1}";
                var hasRootForms = Persistence
                                   .RetrieveChildren(rootFormsId).Any();
                var formsNode = this.CreateTreeNode(FormConstants.Id, id,
                                                    queryStrings, LocalizationHelper.GetTreeName(FormConstants.Title),
                                                    FormConstants.TreeIcon, hasRootForms,
                                                    string.Format(formatUrl, "forms", FormConstants.Id));
                nodes.Add(formsNode);
                var hasRootLayouts = Persistence
                                     .RetrieveChildren(rootLayoutsId).Any();
                var layoutsNode = this.CreateTreeNode(LayoutConstants.Id,
                                                      id, queryStrings, LocalizationHelper.GetTreeName(LayoutConstants.Title),
                                                      LayoutConstants.TreeIcon, hasRootLayouts,
                                                      string.Format(formatUrl, "layouts", LayoutConstants.Id));
                nodes.Add(layoutsNode);
                var dataSourcesNode = this.CreateTreeNode(
                    DataSourceConstants.Id, id, queryStrings,
                    LocalizationHelper.GetTreeName(DataSourceConstants.Title),
                    DataSourceConstants.TreeIcon, false,
                    string.Format(formatUrl, "dataSources", DataSourceConstants.Id));
                nodes.Add(dataSourcesNode);
                var hasRootDataValues = Persistence
                                        .RetrieveChildren(rootDataValueId).Any();
                var dataValuesNode = this.CreateTreeNode(
                    DataValueConstants.Id, id, queryStrings,
                    LocalizationHelper.GetTreeName(DataValueConstants.Title),
                    DataValueConstants.TreeIcon, hasRootDataValues,
                    string.Format(formatUrl, "dataValues", DataValueConstants.Id));
                nodes.Add(dataValuesNode);
                var hasRootValidations = Persistence
                                         .RetrieveChildren(rootValidationsId).Any();
                var validationsNode = this.CreateTreeNode(
                    ValidationConstants.Id, id, queryStrings,
                    LocalizationHelper.GetTreeName(ValidationConstants.Title),
                    ValidationConstants.TreeIcon, hasRootValidations,
                    string.Format(formatUrl, "validationLibrary", ValidationConstants.Id));
                nodes.Add(validationsNode);
            }
            else if (id.InvariantEquals(LayoutConstants.Id))
            {
                // Get root nodes under layouts.
                var entities = Persistence
                               .RetrieveChildren(rootLayoutsId);
                LayoutHelper.AddLayoutChildrenToTree(nodes, queryStrings,
                                                     entities.OrderBy(x => x.Name));
            }
            else if (id.InvariantEquals(ValidationConstants.Id))
            {
                // Get root nodes under validations.
                var entities = Persistence
                               .RetrieveChildren(rootValidationsId);
                ValidationHelper.AddValidationChildrenToTree(
                    nodes, queryStrings, entities.OrderBy(x => x.Name));
            }
            else if (id.InvariantEquals(FormConstants.Id))
            {
                // Get root nodes under forms.
                var entities = Persistence
                               .RetrieveChildren(rootFormsId);
                FormHelper.AddFormChildrenToTree(nodes, queryStrings,
                                                 entities.OrderBy(x => x.Name));
            }
            else if (id.InvariantEquals(DataValueConstants.Id))
            {
                // Get root nodes under data values.
                var entities = Persistence
                               .RetrieveChildren(rootDataValueId);
                DataValueHelper.AddChildrenToTree(nodes, queryStrings,
                                                  entities.OrderBy(x => x.Name));
            }
            else
            {
                // Variables.
                var entity     = Persistence.Retrieve(entityId);
                var ancestorId = entity.Path.First();
                var children   = Persistence
                                 .RetrieveChildren(entityId);


                // Add children of folder.
                if (entity is Folder)
                {
                    // Which subtree?
                    if (ancestorId == rootFormsId)
                    {
                        FormHelper.AddFormChildrenToTree(nodes, queryStrings,
                                                         children.OrderBy(x => x.Name));
                    }
                    else if (ancestorId == rootLayoutsId)
                    {
                        LayoutHelper.AddLayoutChildrenToTree(nodes,
                                                             queryStrings, children.OrderBy(x => x.Name));
                    }
                    else if (ancestorId == rootValidationsId)
                    {
                        ValidationHelper.AddValidationChildrenToTree(
                            nodes, queryStrings, children.OrderBy(x => x.Name));
                    }
                    else if (ancestorId == rootDataValueId)
                    {
                        DataValueHelper.AddChildrenToTree(nodes,
                                                          queryStrings, children.OrderBy(x => x.Name));
                    }
                }
                else if (entity is Form)
                {
                    ConfiguredFormHelper.AddConfiguredFormChildrenToTree(nodes,
                                                                         queryStrings, children.OrderBy(x => x.Name));
                }
            }
            return(nodes);
        }
Exemple #43
0
    private void BindTree(TreeNodeCollection Nds, int IDStr)
    {
        //SqlConnection Conn = new SqlConnection(DecryptDBStr(ConfigurationManager.AppSettings["SQLConnectionString"].ToString(),"zhangweilong"));
        SqlConnection Conn = new SqlConnection(ConfigurationManager.AppSettings["SQLConnectionString"].ToString());

        Conn.Open();

        string DepartmentID = "";
        string SuperiorID   = ZWL.Common.PublicMethod.GetSessionValue("DepartmentID");;

        while (SuperiorID != "0")
        {
            DepartmentID = SuperiorID;
            SuperiorID   = GetSuperiorDepartmentID(SuperiorID);
        }


        SqlCommand MyCmd;

        if (ZWL.Common.PublicMethod.GetSessionValue("UserName") == "admin")
        {
            MyCmd = new SqlCommand("select * from hx_vERPBuMen where DirID=" + IDStr.ToString() + " and CHARINDEX('" + DepartmentID + "',p_depart_ids)>0 order by ID asc", Conn);
        }
        else
        {
            MyCmd = new SqlCommand("select * from hx_vERPBuMen where DirID=" + IDStr.ToString() + " and CHARINDEX('," + ZWL.Common.PublicMethod.GetSessionValue("DepartmentID") + ",',p_depart_ids)>0 order by ID asc", Conn);
        }
        SqlDataReader MyReader = MyCmd.ExecuteReader();

        while (MyReader.Read())
        {
            TreeNode OrganizationNode = new TreeNode();
            OrganizationNode.Text  = MyReader["BuMenName"].ToString();
            OrganizationNode.Value = MyReader["ID"].ToString();
            int strId = int.Parse(MyReader["ID"].ToString());
            OrganizationNode.ImageUrl     = "~/images/user_group.gif";
            OrganizationNode.SelectAction = TreeNodeSelectAction.Expand;
            OrganizationNode.Expanded     = true;

            /////////////////////////////////////////////////////////////////////////////////////////////////////
            //在当前节点下加入用户
            SqlConnection Conn1 = new SqlConnection(ConfigurationManager.AppSettings["SQLConnectionString"].ToString());
            Conn1.Open();
            //SqlCommand MyCmd1 = new SqlCommand("select * from ERPUser where Department like '%" + MyReader["BuMenName"].ToString() + "%' order by ID asc", Conn1);
            SqlCommand    MyCmd1    = new SqlCommand("select * from ERPUser where Department = '" + MyReader["BuMenName"].ToString() + "' order by ID asc", Conn1);
            SqlDataReader MyReader1 = MyCmd1.ExecuteReader();
            while (MyReader1.Read())
            {
                TreeNode UserNode = new TreeNode();
                //UserNode.Text = MyReader1["UserName"].ToString();
                UserNode.Text        = MyReader1["TrueName"].ToString();
                UserNode.Value       = MyReader1["ID"].ToString();
                UserNode.ToolTip     = MyReader1["UserName"].ToString();
                UserNode.ImageUrl    = OnLinePic(MyReader1["ID"].ToString());
                UserNode.NavigateUrl = "../LanEmail/LanEmailAdd.aspx?UserName="******"UserName"].ToString();
                OrganizationNode.ChildNodes.Add(UserNode);
            }
            MyReader1.Close();
            Conn1.Close();
            /////////////////////////////////////////////////////////////////////////////////////////////////////

            Nds.Add(OrganizationNode);

            //递归循环
            BindTree(Nds[Nds.Count - 1].ChildNodes, strId);
        }
        MyReader.Close();
        Conn.Close();
    }
Exemple #44
0
        private static TreeNodeCollection BuildTreeLevel(DirectoryInfo root, int level, int maxLevel, XmlElement siteMap)
        {
            DirectoryInfo[] folders = root.GetDirectories();

            folders = SortFolders(root, folders);

            TreeNodeCollection nodes = new TreeNodeCollection(false);

            foreach (DirectoryInfo folder in folders)
            {
                if ((folder.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden ||
                    excludeList.Contains(folder.Name) || folder.Name.StartsWith("_"))
                {
                    continue;
                }

                ExampleConfig cfg = new ExampleConfig(folder.FullName + "\\config.xml", false);

                string     iconCls  = string.IsNullOrEmpty(cfg.IconCls) ? "" : cfg.IconCls;
                TreeNode   node     = new TreeNode();
                XmlElement siteNode = null;

                string folderName = folder.Name.Replace("_", " ");
                if (level < maxLevel)
                {
                    node.Text    = MarkNew(folder.FullName, folderName);
                    node.IconCls = iconCls;
                    //node.NodeID = "e" + Math.Abs(url.ToLower().GetHashCode());
                    //node.SingleClickExpand = true;

                    if (siteMap != null)
                    {
                        siteNode = siteMap.OwnerDocument.CreateElement("siteMapNode");
                        siteNode.SetAttribute("title", folderName);
                        siteMap.AppendChild(siteNode);
                    }

                    node.Nodes.AddRange(BuildTreeLevel(folder, level + 1, maxLevel, siteNode));
                }
                else
                {
                    node.Text    = MarkNew(folder.FullName, folderName);
                    node.IconCls = iconCls;
                    string url = PhysicalToVirtual(folder.FullName + "/");
                    node.NodeID = "e" + Math.Abs(url.ToLower().GetHashCode());
                    node.Href   = Regex.Replace(url, "^/Examples", "");

                    node.Leaf = true;

                    if (siteMap != null)
                    {
                        siteNode = siteMap.OwnerDocument.CreateElement("siteMapNode");
                        siteNode.SetAttribute("title", folderName);
                        siteNode.SetAttribute("description", string.IsNullOrEmpty(cfg.Description) ? "No description" : cfg.Description);
                        siteNode.SetAttribute("url", "~" + PhysicalToVirtual(folder.FullName + "/"));
                        siteMap.AppendChild(siteNode);
                    }
                }

                nodes.Add(node);
            }

            return(nodes);
        }
 void AddTo(TreeNodeCollection nodes)
 {
     nodes.Add(this);
     Refresh();
 }
Exemple #46
0
        /// <summary>
        /// Recursively updates the TreeView control with a new tree structure.
        /// </summary>
        /// <param name="targetNodeCollection">The target tree for the changes.</param>
        /// <param name="sourceNodeCollection">The source tree containing the new structure.</param>
        private void RecurseRefresh(TreeNodeCollection targetNodeCollection, TreeNodeCollection sourceNodeCollection)
        {
            // The main idea here is to run through all the nodes looking for Adds, Deletes and Updates.  When we find a Node that
            // shouldn't be in the structure, it's deleted from the tree.  Since the tree is made up of linked lists, we can't
            // rightly delete the current link in the list.  For this reason we need to use the index into the list for spanning
            // the structure instead of the collection operations.  When we find an element that needs to be removed, we can delete
            // it and the index will get us safely to the next element in the list. The first loop scans the list already in the
            // TreeView structure.
            for (int targetIndex = 0; targetIndex < targetNodeCollection.Count; targetIndex++)
            {
                // Get a reference to the current node in the target (older) list of nodes.
                TreeNode childTargetNode = (TreeNode)targetNodeCollection[targetIndex];

                // If we don't find the target (older) element in the source (newer) list, it will be deleted.
                bool found = false;

                // Cycle through all of the source (newer) elements looking for changes and removing any elements that
                // exist in both lists.
                for (int sourceIndex = 0; sourceIndex < sourceNodeCollection.Count; sourceIndex++)
                {
                    // Get a reference to the current node in the source (newer) list of nodes.
                    TreeNode childSourceNode = (TreeNode)sourceNodeCollection[sourceIndex];

                    // If the elements are equal (as defined by the equality operator of the object), then recurse into the
                    // structure looking for changes to the children.  After that, check the Node for any changes since it was
                    // added to the tree.
                    if (childTargetNode.Tag.Equals(childSourceNode.Tag))
                    {
                        // Recurse down into the tree structures bringing all the children in sync with the new structure.
                        RecurseRefresh(childTargetNode.Nodes, childSourceNode.Nodes);

                        // Check the Nodes Name.  Update it if there's a change.  Note that checking the names before the copy
                        // reduces the number of events that might be associated with updating a tree control.
                        if (childTargetNode.Text != childSourceNode.Text)
                        {
                            childTargetNode.Text = childSourceNode.Text;
                        }

                        // At this point, we've checked all the children and applied any changes to the node.  Remove it from the
                        // list.  Any elements left in the source list are assumed to be new members and will be added to the tree
                        // structure.  That's why it's important to remove the ones already in the tree.
                        sourceNodeCollection.Remove(childSourceNode);
                        sourceIndex--;

                        // This will signal the target loop that this element still exists in the structure.  If it isn't found,
                        // it'll be deleted.
                        found = true;
                    }
                }

                // If the target (older) element isn't found in the source (newer) tree, it's deleted.
                if (!found)
                {
                    targetNodeCollection.Remove(childTargetNode);
                    targetIndex--;
                }
            }

            // Any element that doesn't already exist in the target (older) tree, is copied from the source (newer) tree, along
            // with all it's children.
            for (int nodeIndex = 0; nodeIndex < sourceNodeCollection.Count; nodeIndex++)
            {
                TreeNode treeNode = (TreeNode)sourceNodeCollection[nodeIndex--];
                sourceNodeCollection.Remove(treeNode);
                targetNodeCollection.Add(treeNode);
            }
        }
        public static void CreateTreeView(TreeView treeView)
        {
            const int RemovableDisk = 2;
            const int LocalDisk     = 3;
            const int NetworkDisk   = 4;
            const int CDDisk        = 5;

            TreeNode tnMyComputer = new TreeNode("My Computer", 0, 0);

            //Make sure the treeView is clear before adding to it.
            treeView.Nodes.Clear();
            treeView.Nodes.Add(tnMyComputer);

            TreeNodeCollection nodeCollection = tnMyComputer.Nodes;

            //Retrieve Logical Disks
            ManagementObjectSearcher   query           = new ManagementObjectSearcher("Select * From Win32_LogicalDisk");
            ManagementObjectCollection queryCollection = query.Get();

            TreeNode diskTreeNode;

            foreach (ManagementObject mo in queryCollection)
            {
                int imageIndex, selectIndex;
                switch (int.Parse(mo["DriveType"].ToString()))
                {
                case RemovableDisk:
                {
                    imageIndex  = 1;
                    selectIndex = 1;
                    break;
                }

                case LocalDisk:
                {
                    imageIndex  = 2;
                    selectIndex = 2;
                    break;
                }

                case CDDisk:
                {
                    imageIndex  = 3;
                    selectIndex = 3;
                    break;
                }

                case NetworkDisk:
                {
                    imageIndex  = 4;
                    selectIndex = 4;
                    break;
                }

                default:
                {
                    imageIndex  = 5;
                    selectIndex = 6;
                    break;
                }
                }


                diskTreeNode = new TreeNode(mo["Name"].ToString() + "\\", imageIndex, selectIndex);
                nodeCollection.Add(diskTreeNode);
            }
        }
        /// <summary>
        /// Returns the tree nodes for an application
        /// </summary>
        /// <param name="application">The application to load tree for</param>
        /// <param name="tree">An optional single tree alias, if specified will only load the single tree for the request app</param>
        /// <param name="queryStrings"></param>
        /// <param name="use">Tree use.</param>
        /// <returns></returns>
        public async Task <TreeRootNode> GetApplicationTrees(string application, string tree, [System.Web.Http.ModelBinding.ModelBinder(typeof(HttpQueryStringModelBinder))] FormDataCollection queryStrings, TreeUse use = TreeUse.Main)
        {
            application = application.CleanForXss();

            if (string.IsNullOrEmpty(application))
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }

            var section = _sectionService.GetByAlias(application);

            if (section == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }

            //find all tree definitions that have the current application alias
            var groupedTrees = _treeService.GetBySectionGrouped(application, use);
            var allTrees     = groupedTrees.Values.SelectMany(x => x).ToList();

            if (allTrees.Count == 0)
            {
                //if there are no trees defined for this section but the section is defined then we can have a simple
                //full screen section without trees
                var name = Services.TextService.Localize("sections", application);
                return(TreeRootNode.CreateSingleTreeRoot(Constants.System.RootString, null, null, name, TreeNodeCollection.Empty, true));
            }

            // handle request for a specific tree / or when there is only one tree
            if (!tree.IsNullOrWhiteSpace() || allTrees.Count == 1)
            {
                var t = tree.IsNullOrWhiteSpace()
                    ? allTrees[0]
                    : allTrees.FirstOrDefault(x => x.TreeAlias == tree);

                if (t == null)
                {
                    throw new HttpResponseException(HttpStatusCode.NotFound);
                }

                var treeRootNode = await GetTreeRootNode(t, Constants.System.Root, queryStrings);

                if (treeRootNode != null)
                {
                    return(treeRootNode);
                }

                throw new HttpResponseException(HttpStatusCode.NotFound);
            }

            // handle requests for all trees
            // for only 1 group
            if (groupedTrees.Count == 1)
            {
                var nodes = new TreeNodeCollection();
                foreach (var t in allTrees)
                {
                    var node = await TryGetRootNode(t, queryStrings);

                    if (node != null)
                    {
                        nodes.Add(node);
                    }
                }

                var name = Services.TextService.Localize("sections", application);

                if (nodes.Count > 0)
                {
                    var treeRootNode = TreeRootNode.CreateMultiTreeRoot(nodes);
                    treeRootNode.Name = name;
                    return(treeRootNode);
                }

                // otherwise it's a section with all empty trees, aka a fullscreen section
                // todo is this true? what if we just failed to TryGetRootNode on all of them? SD: Yes it's true but we should check the result of TryGetRootNode and throw?
                return(TreeRootNode.CreateSingleTreeRoot(Constants.System.RootString, null, null, name, TreeNodeCollection.Empty, true));
            }

            // for many groups
            var treeRootNodes = new List <TreeRootNode>();

            foreach (var(groupName, trees) in groupedTrees)
            {
                var nodes = new TreeNodeCollection();
                foreach (var t in trees)
                {
                    var node = await TryGetRootNode(t, queryStrings);

                    if (node != null)
                    {
                        nodes.Add(node);
                    }
                }

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

                // no name => third party
                // use localization key treeHeaders/thirdPartyGroup
                // todo this is an odd convention
                var name = groupName.IsNullOrWhiteSpace() ? "thirdPartyGroup" : groupName;

                var groupRootNode = TreeRootNode.CreateGroupNode(nodes, application);
                groupRootNode.Name = Services.TextService.Localize("treeHeaders", name);
                treeRootNodes.Add(groupRootNode);
            }

            return(TreeRootNode.CreateGroupedMultiTreeRoot(new TreeNodeCollection(treeRootNodes.OrderBy(x => x.Name))));
        }
        protected override int reAddNodes(int indxLevel, TreeNode nodeParent, string strId_parent)
        //protected override int reAddNodes(TreeNode node_parent)
        {
            int iRes = 0;

            TreeNode node            = null
            , node_par               = null
            , node_norm              = null
            , node_mkt               = null;
            TreeNodeCollection nodes = null;
            bool bTaskTep            = false;
            string //strId_parent = node_parent == null ? string.Empty : node_parent.Name,
                strId = string.Empty
            , strKey  = string.Empty
            , strItem = string.Empty;

            DataRow[] rows;
            int //indxLevel = node_parent == null ? 0 : node_parent.Level + 1,
                iAdd = 0
            , iId    = -1;

            if (indxLevel < m_listLevelParameters.Count)
            {
                #region код для учета особенности структуры для задачи с ИД = 1 (Расчет ТЭП)
                bTaskTep = ((indxLevel == ((int)ID_LEVEL.TASK + 1)) &&
                            (getIdNodePart(nodeParent.Name, ID_LEVEL.TASK).Equals(((int)ID_TASK.TEP).ToString()) == true));
                #endregion

                if (nodeParent == null)
                {
                    nodes = m_ctrlTreeView.Nodes;
                }
                else
                {
                    #region код для учета особенности структуры для задачи с ИД = 1 (Расчет ТЭП)
                    if (bTaskTep == true)
                    {
                        node_norm = nodeParent.Nodes.Add(concatIdNode(nodeParent.Name, @"norm"), @"Норматив");
                        node_mkt  = nodeParent.Nodes.Add(concatIdNode(nodeParent.Name, @"mkt"), @"Макет");
                    }
                    else
                    #endregion
                    {
                        node_par = nodeParent;
                        nodes    = node_par.Nodes;
                    }
                }

                rows = m_listLevelParameters[indxLevel].Select(strId_parent);

                foreach (DataRow r in rows)
                {
                    //Строка с идентификатором задачи
                    strId = m_listLevelParameters[indxLevel].GetId(r).Trim();

                    #region код для учета особенности структуры для задачи с ИД = 1 (Расчет ТЭП)
                    if (bTaskTep == true)
                    {
                        iId = int.Parse(strId);
                        if ((!(iId < (int)ID_START_RECORD.ALG)) &&
                            (iId < (int)ID_START_RECORD.ALG_NORMATIVE))
                        {
                            node_par = node_mkt;
                        }
                        else
                        if ((!(iId < (int)ID_START_RECORD.ALG_NORMATIVE)) &&
                            (iId < (int)ID_START_RECORD.PUT))
                        {
                            node_par = node_norm;
                        }
                        else
                        {
                            throw new Exception(@"PanelPrjOutParameters::reAddNodes (ID_NODE=" + iId + @") - неизвестный диапазон");
                        }

                        nodes = node_par.Nodes;
                    }
                    else
                    {
                        ;
                    }
                    #endregion

                    //
                    if (strId.Equals(string.Empty) == false)
                    {
                        strKey = concatIdNode(node_par, strId);
                    }
                    else
                    {
                        strKey = strId_parent;
                    }

                    if (nodes.Find(strKey, false).Length == 0)
                    {
                        //Элемент дерева для очередной задачи
                        if (m_listLevelParameters[indxLevel].desc.Equals(string.Empty) == false)
                        {
                            strItem = r[m_listLevelParameters[indxLevel].desc].ToString().Trim();
                            if (m_listLevelParameters[indxLevel].desc_detail.Equals(string.Empty) == false)
                            {
                                strItem += @" (" + r[m_listLevelParameters[indxLevel].desc_detail].ToString().Trim() + @")";
                            }
                            else
                            {
                                ;
                            }
                            node = nodes.Add(strKey, strItem);
                            iRes++;
                        }
                        else
                        {
                            node = node_par;
                        }

                        if ((indxLevel + 1) < m_listLevelParameters.Count)
                        {
                            iAdd =
                                reAddNodes(indxLevel + 1, node, strKey)
                                //reAddNodes(node)
                            ;
                            if (iAdd == 0)
                            {
                                if (indxLevel > 0)
                                {
                                    nodes.Remove(node);
                                    iRes--;
                                }
                                else
                                {
                                    addNodeNull(node);
                                }
                            }
                            else
                            {
                                iRes += iAdd;
                            }
                        }
                        else
                        {
                            ;
                        }
                    }
                    else
                    {
                        ; // нельзя добавить элемент с имеющимся ключом
                    }
                }
            }
            else
            {
                ;
            }

            return(iRes);
        }
Exemple #50
0
        public string SaveGroup(TreeView myTreeView, string myGroupId, bool isUpdate, XDocument xv, XDocument xb, TreeView treeViewSource, DataGridView dataGridViewGroupVanilla)
        {
            errorMessage = "";
            TreeNodeCollection newTreeNodeCollection    = myTreeView.Nodes;
            TreeNodeCollection treeViewSourceCollection = treeViewSource.Nodes;

            if (isUpdate)
            {
                string nodeToDelete = "";
                bool   swFound      = false;

                foreach (TreeNode node in newTreeNodeCollection)
                {
                    try
                    {
                        nodeToDelete = Shared.GetElementValue(node.Text);
                        if (nodeToDelete.Trim() == myGroupId)
                        {
                            // Start "EditControls" ver: 1.0.8 date: 03-03-16
                            int nodeIndex = node.Index;
                            // End "EditControls" ver: 1.0.8 date: 03-03-16
                            // Remove old Group Id
                            newTreeNodeCollection.Remove(node);
                            swFound = true;
                            // Add the updated Group Id
                            XElement group           = FillNewXelement(myGroupId, groupPairs);
                            TreeNode groupParentNode = FillNewTreeNode(myGroupId, groupPairs);
                            // Compares current group with base and source
                            string nodeTag = "";
                            if (xv != null)
                            {
                                // Compares with source
                                bool isDiffFromSource = CompareGroups(myGroupId, group, xb);
                                // Compares with base
                                bool isDiffFromBase = CompareGroups(myGroupId, group, xv);
                                if (isDiffFromSource && isDiffFromBase)
                                {
                                    nodeTag = "DiffFromSourceAndBase";
                                }
                                else
                                {
                                    if (isDiffFromSource)
                                    {
                                        nodeTag = "DiffFromSource";
                                    }
                                    else
                                    {
                                        if (isDiffFromBase)
                                        {
                                            nodeTag = "DiffFromBase";
                                        }
                                    }
                                }
                            }
                            else
                            {
                                // Compares with source
                                if (CompareGroups(myGroupId, group, xb))
                                {
                                    nodeTag = "DiffFromSource";
                                }
                                else
                                {
                                    nodeTag = "NoDiff";
                                }
                            }
                            groupParentNode.Tag = nodeTag;
                            // Start "EditControls" ver: 1.0.8 date: 03-03-16
                            //newTreeNodeCollection.Add(groupParentNode);
                            newTreeNodeCollection.Insert(nodeIndex, groupParentNode);
                            // End "EditControls" ver: 1.0.8 date: 03-03-16
                            // Compare dataGridViewVanilla with current group to highlight the differences
                            //Shared.CompareVanillaGroupToCurrentGroupHighlightDifferences(groupParentNode, dataGridViewGroupVanilla);
                            break;
                        }
                    }
                    catch (Exception err)
                    {
                        errorMessage = "There was a problem when trying to update " + myGroupId + "." + err.Message;
                    }
                }
                if (!swFound)
                {
                    errorMessage = myGroupId + " was not updated because it was not found.";
                }
            }
            else
            {
                try
                {
                    bool doUpdate = true;
                    // Check if the group already exist on the target treeview
                    foreach (TreeNode node in newTreeNodeCollection)
                    {
                        if (Shared.GetElementValue(node.Text) == myGroupId)
                        {
                            errorMessage = "The group " + myGroupId + " already exist.";
                            doUpdate     = false;
                            break;
                        }
                    }
                    // Check if the group already exist on the source treeview
                    foreach (TreeNode node in treeViewSourceCollection)
                    {
                        if (Shared.GetElementValue(node.Text) == myGroupId)
                        {
                            errorMessage = "The group " + myGroupId + " already exist on the source signature.";
                            doUpdate     = false;
                            break;
                        }
                    }
                    if (doUpdate)
                    {
                        // Add the new Group Id
                        TreeNode groupParentNode = FillNewTreeNode(myGroupId, groupPairs);
                        if (xv != null)
                        {
                            XElement group = FillNewXelement(myGroupId, groupPairs);
                            // Compares with base
                            bool isDiffFromBase = CompareGroups(myGroupId, group, xv);
                            //
                            if (isDiffFromBase)
                            {
                                groupParentNode.Tag = "DiffFromSourceAndBase";
                            }
                            else
                            {
                                groupParentNode.Tag = "DiffFromSource";
                            }
                        }
                        else
                        {
                            groupParentNode.Tag = "DiffFromSource";
                        }
                        //
                        newTreeNodeCollection.Add(groupParentNode);
                    }
                }
                catch (Exception err)
                {
                    errorMessage = "The new group " + myGroupId + " was not added." + err.Message;
                }
            }
            return(errorMessage);
        }
Exemple #51
0
 public void Add(ITreeNode item)
 {
     nodes.Add((WrappedNode)item);
 }
Exemple #52
0
        protected override Models.Trees.TreeNodeCollection GetTreeNodes(string id, System.Net.Http.Formatting.FormDataCollection queryStrings)
        {
            string orgPath = "";
            string path    = "";

            if (!string.IsNullOrEmpty(id) && id != "-1")
            {
                orgPath  = id;
                path     = IOHelper.MapPath(FilePath + "/" + orgPath);
                orgPath += "/";
            }
            else
            {
                path = IOHelper.MapPath(FilePath);
            }

            DirectoryInfo dirInfo = new DirectoryInfo(path);

            DirectoryInfo[] dirInfos = dirInfo.GetDirectories();

            var nodes = new TreeNodeCollection();

            foreach (DirectoryInfo dir in dirInfos)
            {
                if ((dir.Attributes & FileAttributes.Hidden) == 0)
                {
                    var HasChildren = dir.GetFiles().Length > 0 || dir.GetDirectories().Length > 0;
                    var node        = CreateTreeNode(orgPath + dir.Name, orgPath, queryStrings, dir.Name, "icon-folder", HasChildren);

                    OnRenderFolderNode(ref node);
                    if (node != null)
                    {
                        nodes.Add(node);
                    }
                }
            }

            //this is a hack to enable file system tree to support multiple file extension look-up
            //so the pattern both support *.* *.xml and xml,js,vb for lookups
            string[] allowedExtensions          = new string[0];
            bool     filterByMultipleExtensions = FileSearchPattern.Contains(",");

            FileInfo[] fileInfo;

            if (filterByMultipleExtensions)
            {
                fileInfo          = dirInfo.GetFiles();
                allowedExtensions = FileSearchPattern.ToLower().Split(',');
            }
            else
            {
                fileInfo = dirInfo.GetFiles(FileSearchPattern);
            }

            foreach (FileInfo file in fileInfo)
            {
                if ((file.Attributes & FileAttributes.Hidden) == 0)
                {
                    if (filterByMultipleExtensions && Array.IndexOf <string>(allowedExtensions, file.Extension.ToLower().Trim('.')) < 0)
                    {
                        continue;
                    }

                    var node = CreateTreeNode(orgPath + file.Name, orgPath, queryStrings, file.Name, "icon-file", false);

                    OnRenderFileNode(ref node);

                    if (node != null)
                    {
                        nodes.Add(node);
                    }
                }
            }

            return(nodes);
        }
Exemple #53
0
        private static void Recurse(TreeNodeCollection nodes, string path)
        {
            try
            {
                string[] macros = Directory.GetFiles(path, "*.macro");
                for (int i = 0; i < macros.Length; i++)
                {
                    Macro m = null;
                    for (int j = 0; j < m_List.Count; j++)
                    {
                        Macro check = (Macro)m_List[j];

                        if (check.Filename == macros[i])
                        {
                            m = check;
                            break;
                        }
                    }

                    if (m == null)
                    {
                        Add(m = new Macro(macros[i]));
                    }

                    if (nodes != null)
                    {
                        TreeNode node = new TreeNode(Path.GetFileNameWithoutExtension(m.Filename));
                        node.Tag = m;
                        nodes.Add(node);
                    }
                }
            }
            catch
            {
            }

            try
            {
                string[] dirs = Directory.GetDirectories(path);
                for (int i = 0; i < dirs.Length; i++)
                {
                    if (dirs[i] != "" && dirs[i] != "." && dirs[i] != "..")
                    {
                        if (nodes != null)
                        {
                            TreeNode node = new TreeNode(String.Format("[{0}]", Path.GetFileName(dirs[i])));
                            node.Tag = dirs[i];
                            nodes.Add(node);
                            Recurse(node.Nodes, dirs[i]);
                        }
                        else
                        {
                            Recurse(null, dirs[i]);
                        }
                    }
                }
            }
            catch
            {
            }
        }
Exemple #54
0
    private void AddObjectsToTree(Element elem, TreeNodeCollection nodes)
    {
        var rootNode1 = new TreeNode("Undefined View");

        nodes.Add(rootNode1);
        foreach (ViewDetailLevel detailLevel in Enum.GetValues(typeof(ViewDetailLevel)))
        {
            var treeNode = new TreeNode($"Detail Level: {detailLevel}");
            // IMPORTANT!!! Need to create options each time when you are
            // getting geometry. In other case, all the geometry you got at the
            // previous step will be overridden according with the latest DetailLevel
            var options1 = new Options
            {
                DetailLevel       = detailLevel,
                ComputeReferences = true
            };
            treeNode.Tag = elem.get_Geometry(options1);
            rootNode1.Nodes.Add(treeNode);
        }

        var rootNode2 = new TreeNode("Undefined View, including non-visible objects");

        nodes.Add(rootNode2);
        foreach (ViewDetailLevel detailLevel in Enum.GetValues(typeof(ViewDetailLevel)))
        {
            var treeNode = new TreeNode($"Detail Level: {detailLevel}");
            var options2 = new Options
            {
                DetailLevel              = detailLevel,
                ComputeReferences        = true,
                IncludeNonVisibleObjects = true
            };
            treeNode.Tag = elem.get_Geometry(options2);
            rootNode2.Nodes.Add(treeNode);
        }

        if (elem.Document.ActiveView is null)
        {
            return;
        }

        var options3 = new Options
        {
            View = elem.Document.ActiveView,
            ComputeReferences = true
        };

        var rootNode3 = new TreeNode("Active View")
        {
            Tag = elem.get_Geometry(options3)
        };

        nodes.Add(rootNode3);

        var options4 = new Options
        {
            View = elem.Document.ActiveView,
            ComputeReferences        = true,
            IncludeNonVisibleObjects = true
        };

        var rootNode4 = new TreeNode("Active View, including non-visible objects");

        nodes.Add(rootNode4);
        rootNode4.Tag = elem.get_Geometry(options4);
    }
Exemple #55
0
        private void ParseData(byte[] data, ref int parseOffset, ProtoSpecSubset format, TreeNodeCollection nodes)
        {
            foreach (ProtoSpecColumn column in format.Columns)
            {
                string columnName = column.Name + " : " + ColumnTypeToString(column) + " = ";

                switch (column.ColumnType)
                {
                case ProtoSpecColumnType.Byte:
                    columnName += data[parseOffset++].ToString();
                    break;

                case ProtoSpecColumnType.Short:
                {
                    byte[] bytes = new byte[2];

                    bytes[1] = data[parseOffset++];
                    bytes[0] = data[parseOffset++];

                    columnName += BitConverter.ToInt16(bytes, 0).ToString();
                }
                break;

                case ProtoSpecColumnType.Int:
                {
                    byte[] bytes = new byte[4];

                    bytes[3] = data[parseOffset++];
                    bytes[2] = data[parseOffset++];
                    bytes[1] = data[parseOffset++];
                    bytes[0] = data[parseOffset++];

                    columnName += BitConverter.ToInt32(bytes, 0).ToString();
                }
                break;

                case ProtoSpecColumnType.Long:
                {
                    byte[] bytes = new byte[8];

                    bytes[7] = data[parseOffset++];
                    bytes[6] = data[parseOffset++];
                    bytes[5] = data[parseOffset++];
                    bytes[4] = data[parseOffset++];
                    bytes[3] = data[parseOffset++];
                    bytes[2] = data[parseOffset++];
                    bytes[1] = data[parseOffset++];
                    bytes[0] = data[parseOffset++];

                    columnName += BitConverter.ToInt64(bytes, 0).ToString();
                }
                break;

                case ProtoSpecColumnType.String:
                {
                    byte[] packhead = new byte[2];

                    packhead[1] = data[parseOffset++];
                    packhead[0] = data[parseOffset++];

                    short len = BitConverter.ToInt16(packhead, 0);

                    string text = Encoding.UTF8.GetString(data, parseOffset, len);

                    parseOffset += len;

                    columnName += "\"" + text + "\"";
                }
                break;

                case ProtoSpecColumnType.Enum:
                {
                    byte value = data[parseOffset++];

                    columnName += column.Values.GetNameByValue(value);
                }
                break;

                case ProtoSpecColumnType.List:
                {
                    byte[] packhead = new byte[2];

                    packhead[1] = data[parseOffset++];
                    packhead[0] = data[parseOffset++];

                    short len = BitConverter.ToInt16(packhead, 0);

                    columnName += len.ToString();

                    TreeNode node = nodes.Add(columnName);

                    for (int i = 0; i < len; i++)
                    {
                        TreeNode subnode = node.Nodes.Add("[" + i + "]");

                        ParseData(data, ref parseOffset, column.Format, subnode.Nodes);
                    }
                }
                break;

                case ProtoSpecColumnType.TypeOf:
                {
                    TreeNode node = nodes.Add(columnName);

                    ParseData(data, ref parseOffset, column.Format, node.Nodes);
                }
                break;
                }

                if (column.ColumnType != ProtoSpecColumnType.List)
                {
                    nodes.Add(columnName);
                }
            }
        }
Exemple #56
0
        private void FillTreeNodes(
            TemplateNodeInfo parent,
            TreeNodeCollection treeNodes
            )
        {
            List <Tuple <TreeNode, ConcreteTemplateNodeDefinition> > pendingUpdateNodes =
                new List <Tuple <TreeNode, ConcreteTemplateNodeDefinition> >();

            Action action = () =>
            {
                treeNodes.Clear();

                treeNodes.AddRange(parent.Childs.Select(n =>
                {
                    ConcreteTemplateNodeDefinition nodedef;
                    TreeNode node = this._treeControl.CreateTreeViewNode(n, out nodedef);

                    pendingUpdateNodes.Add(new Tuple <TreeNode, ConcreteTemplateNodeDefinition>(node, nodedef));

                    return(node);
                }).ToArray());

                if (parent.ChildrenAreLoadingNow)
                {
                    treeNodes.Add(new TreeNode(this._treeControl._model.LocaleManager.GetLocalizedText(
                                                   "common", "NodesQueryingTreeNodeText")
                                               )
                    {
                        ImageKey         = "NodesQuerying",
                        SelectedImageKey = "NodesQuerying"
                    });
                }
            };

            this._treeControl.SafeInvoke(action);

            foreach (Tuple <TreeNode, ConcreteTemplateNodeDefinition> pendingNode in pendingUpdateNodes)
            {
                TreeNode node = pendingNode.Item1;
                ConcreteTemplateNodeDefinition nodeDef = pendingNode.Item2;

                if (parent.IsDisabled)
                {
                    nodeDef.TemplateNode.IsDisabled = true;
                    nodeDef.NodeActivated           = false;
                }

                nodeDef.NodeAvailable = nodeDef.IsAvailableForDatabase(Program.Model) ?? true;

                if (!nodeDef.NodeAvailable)
                {
                    this._treeControl.SetNotAvailableNode(node);
                }
                else
                {
                    this._treeControl.SetNodeLoaded(node);

                    List <TemplateNodeUpdateJob> refreshJobs = nodeDef.TemplateNode.GetRefreshJob(true);

                    nodeDef.TemplateNode.HasActiveJobs = refreshJobs.Any(
                        job =>
                        job != null &&
                        !job.IsEmpty() &&
                        job.Enabled
                        );

                    UpdateTreeCounts(node, NodeUpdatingSource.LocallyOnly);
                }
            }
        }
        protected override TreeNodeCollection GetTreeNodes(string id, FormDataCollection queryStrings)
        {
            var nodes = new TreeNodeCollection();

            var alias             = id;
            var currentItemConfig = alias == "-1" ? TreeConfig : TreeConfig.FlattenedTreeItems[alias];

            var currentFolderConfig = currentItemConfig as FluidityContainerTreeItemConfig;

            if (currentFolderConfig != null)
            {
                // Render the folder contents
                foreach (var treeItem in currentFolderConfig.TreeItems.Values.OrderBy(x => x.Ordinal))
                {
                    var folderTreeItem = treeItem as FluidityFolderConfig;
                    if (folderTreeItem != null)
                    {
                        // Render folder
                        var node = CreateTreeNode(
                            folderTreeItem.Alias,
                            folderTreeItem.ParentAlias,
                            queryStrings,
                            folderTreeItem.Name,
                            folderTreeItem.Icon,
                            true,
                            SectionAlias); // Tree mode so just show the default dashboard

                        if (!currentFolderConfig.IconColor.IsNullOrWhiteSpace())
                        {
                            node.SetColorStyle(currentFolderConfig.IconColor);
                        }

                        node.Path = folderTreeItem.Path;

                        nodes.Add(node);
                    }

                    var collectionTreeItem = treeItem as FluidityCollectionConfig;
                    if (collectionTreeItem != null && collectionTreeItem.IsVisibleInTree)
                    {
                        // Render collection folder
                        var node = CreateTreeNode(
                            collectionTreeItem.Alias,
                            collectionTreeItem.ParentAlias,
                            queryStrings,
                            collectionTreeItem.NamePlural,
                            collectionTreeItem.IconPlural,
                            collectionTreeItem.ViewMode == FluidityViewMode.Tree,
                            collectionTreeItem.ViewMode == FluidityViewMode.Tree
                                ? SectionAlias // Tree mode so just show the default dashboard
                                : SectionAlias + "/fluidity/list/" + collectionTreeItem.Alias);

                        node.Path = collectionTreeItem.Path;

                        if (collectionTreeItem.ViewMode == FluidityViewMode.List)
                        {
                            node.SetContainerStyle();
                        }

                        if (!collectionTreeItem.IconColor.IsNullOrWhiteSpace())
                        {
                            node.SetColorStyle(collectionTreeItem.IconColor);
                        }

                        nodes.Add(node);
                    }
                }
            }

            var currentCollectionConfig = currentItemConfig as FluidityCollectionConfig;

            if (currentCollectionConfig != null && currentCollectionConfig.IsVisibleInTree && currentCollectionConfig.ViewMode == FluidityViewMode.Tree)
            {
                // Render collection items
                var items = Context.Services.EntityService.GetAllEntities(currentCollectionConfig);
                nodes.AddRange(items.Select(item => CreateEntityTreeNode(currentCollectionConfig, item, queryStrings)));
            }

            return(nodes);
        }
        private void IterateContainers(DtsContainer parent, TreeNodeCollection nodes, string selectedContainerId)
        {
            TreeNode node = new TreeNode();

            node.Name = parent.Name;
            node.Text = parent.Name;
            node.Tag  = parent;
            SetNodeIcon(parent, node);
            nodes.Add(node);

            if (parent.ID == selectedContainerId)
            {
                node.TreeView.SelectedNode = node;
            }

            IDTSSequence seq = parent as IDTSSequence;

            if (seq != null)
            {
                foreach (Executable e in seq.Executables)
                {
                    if (e is IDTSSequence || e is EventsProvider)
                    {
                        IterateContainers((DtsContainer)e, node.Nodes, selectedContainerId);
                    }
                    else
                    {
                        DtsContainer task      = (DtsContainer)e;
                        TreeNode     childNode = new TreeNode();
                        childNode.Name = task.Name;
                        childNode.Text = task.Name;
                        childNode.Tag  = task;
                        SetNodeIcon(task, childNode);
                        node.Nodes.Add(childNode);

                        if (task.ID == selectedContainerId)
                        {
                            node.TreeView.SelectedNode = childNode;
                        }
                    }
                }
            }

            EventsProvider prov = parent as EventsProvider;

            if (prov != null)
            {
                foreach (DtsEventHandler p in prov.EventHandlers)
                {
                    DtsContainer task      = (DtsContainer)p;
                    TreeNode     childNode = new TreeNode();
                    childNode.Name = string.Format(CultureInfo.InvariantCulture, "{0} Event", p.Name);
                    childNode.Text = string.Format(CultureInfo.InvariantCulture, "{0} Event", p.Name);
                    childNode.Tag  = task;
                    SetNodeIcon(task, childNode);
                    node.Nodes.Add(childNode);

                    if (task.ID == selectedContainerId)
                    {
                        node.TreeView.SelectedNode = childNode;
                    }
                }
            }
            return;
        }
Exemple #59
0
        private void FillTreeRec(TreeNodeCollection tNodes, XmlNode xNode, int resLevel)
        {
            foreach (XmlNode node in xNode.ChildNodes)
            {
                if (node.Name == "LogResult")
                {
                    BubbleIconUp((TestCaseResult)Enum.Parse(typeof(TestCaseResult), node.InnerText));
                    nodesStack.Pop();
                    if (nodesStack.Count > 0)
                    {
                        currentTestCaseNodes = nodesStack.Peek();
                    }
                }
                else if (node.Name == "TestStep")
                {
                    LogEntry logEntry = new LogEntry()
                    {
                        Message   = node.Attributes["name"].Value,
                        Time      = DateTime.ParseExact(node.Attributes["startTimeUtc"].Value, "s", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal),
                        Body      = BodyType.Text,
                        Verbosity = EntryVerbosity.Normal,
                        Type      = EntryType.Info
                    };

                    if (node.Attributes["description"] != null)
                    {
                        logEntry.ExtendedMessage = node.Attributes["description"].Value;
                    }

                    TreeNode newNode = new TreeNode(logEntry.Message);
                    newNode.Tag = logEntry;
                    newNode.SelectedImageKey = newNode.ImageKey = GetImageKeyByEntry(logEntry);
                    newNode.ContextMenuStrip = nodeMenuStrip;

                    List <TreeNode> newList = new List <TreeNode>();
                    currentTestCaseNodes = newList;
                    nodesStack.Push(newList);

                    tNodes.Add(newNode);

                    currentTestCaseNodes.Add(newNode);
                    FillTreeRec(newNode.Nodes, node, resLevel + 1);
                }
                else if (node.Name == "Folder")
                {
                    LogEntry logEntry = GetEntry(node.FirstChild);
                    if (logEntry != null)
                    {
                        TreeNode newNode = new TreeNode(logEntry.Message);
                        newNode.Tag = logEntry;
                        newNode.SelectedImageKey = newNode.ImageKey = GetImageKeyByEntry(logEntry);
                        newNode.ContextMenuStrip = nodeMenuStrip;

                        tNodes.Add(newNode);

                        currentTestCaseNodes.Add(newNode);
                        node.RemoveChild(node.FirstChild);
                        FillTreeRec(newNode.Nodes, node, resLevel + 1);
                    }
                }
                else
                {
                    LogEntry logEntry = GetEntry(node);
                    if (logEntry != null)
                    {
                        TreeNode newNode = new TreeNode(logEntry.Message);
                        newNode.Tag = logEntry;

                        newNode.SelectedImageKey = newNode.ImageKey = GetImageKeyByEntry(logEntry);

                        newNode.ContextMenuStrip = nodeMenuStrip;
                        tNodes.Add(newNode);

                        currentTestCaseNodes.Add(newNode);
                    }
                }
            }
        }
Exemple #60
0
        private void ReadWayPointList(List <clsWayPoint> wayPoints)
        {
            TreeNodeCollection tncWayPointRoot = tvWayPoint.Nodes;

            tncWayPointRoot.Clear();

            clsWayPoint wpLast = null;

            foreach (clsWayPoint wp in wayPoints)
            {
                //从星系开始记录
                if (wpLast == null)
                {
                    if (!wp.PointName.StartsWith("J"))
                    {
                        wpLast = wp;
                    }
                    continue;
                }
                //虫洞
                if (wp.PointName.StartsWith("J"))
                {
                    if (!wpLast.PointName.StartsWith("J"))
                    {
                        //洞外→洞内
                        TreeNode tnRoot = SearchTreeNode(tncWayPointRoot, wpLast.PointName);
                        TreeNode tnNow  = SearchTreeNode(tncWayPointRoot, wp.PointName);

                        if (tnRoot == null)
                        {
                            //排除回洞
                            tnRoot = new TreeNode(wpLast.PointName);
                            tnRoot.Nodes.Add(wp.PointName);
                            tncWayPointRoot.Add(tnRoot);
                        }
                        else
                        {
                            //排除重复进洞
                        }
                    }
                    else
                    {
                        //洞内→洞内
                        TreeNode tnLast = SearchTreeNode(tncWayPointRoot, wpLast.PointName);
                        TreeNode tnNow  = SearchTreeNode(tncWayPointRoot, wp.PointName);
                        if (tnNow == null)
                        {
                            tnLast.Nodes.Add(wp.PointName);
                        }
                    }
                }
                else
                {
                    if (!wpLast.PointName.StartsWith("J"))
                    {
                        //洞外→洞外
                    }
                    else
                    {
                        //洞内→洞外
                        TreeNode tnLast = SearchTreeNode(tncWayPointRoot, wpLast.PointName);
                        TreeNode tnNow  = SearchTreeNode(tncWayPointRoot, wp.PointName);
                        if (tnNow == null)
                        {
                            tnLast.Nodes.Add(wp.PointName);
                        }
                        else if (tnNow != null && SearchTreeNode(tnLast.Nodes, wp.PointName) != null)
                        {
                            //排除重复探头记录
                        }
                        else if (tnLast != null && SearchTreeNode(tnNow.Nodes, wpLast.PointName) != null)
                        {
                            //排除原地出洞
                        }
                    }
                }
                wpLast = wp;
            }

            tvWayPoint.ExpandAll();
        }