Example #1
0
        public TreeNode rSortedListToBST(ListNode head, int size, out ListNode tail)
        {
            if (size == 1)
            {
                tail = head.next;
                return new TreeNode(head.val);
            }
            else
            {
                int left = size / 2;
                int right = size - 1 - left;

                var ltree = rSortedListToBST(head, left, out tail);

                var root = new TreeNode(tail.val);
                root.left = ltree;

                if (right > 0) {
                    var rtree = rSortedListToBST (tail.next, right, out tail);
                    root.right = rtree;
                } else {
                    tail = tail.next;
                }

                return root;
            }
        }
Example #2
0
        private static void BuildFromDirectory(string baseDir, Control level)
        {
            foreach (string idxDir in Directory.GetDirectories(baseDir))
            {
                string dir = idxDir.Replace(baseDir, "");

                // Skipping .svn and similar directories...
                if (dir.IndexOf(".") == 0)
                {
                    continue;
                }
                TreeNode n = new TreeNode {ID = level.ID + dir, Xtra = idxDir, Text = dir};
                level.Controls.Add(n);
                string[] childDirectories = Directory.GetDirectories(idxDir);
                if (childDirectories.Length > 0)
                {
                    // Skipping .svn and similar directories...
                    if (childDirectories.Length == 1)
                    {
                        string tmpDir = childDirectories[0];
                        tmpDir = tmpDir.Substring(tmpDir.LastIndexOf("\\") + 1);
                        if (tmpDir.IndexOf(".") == 0)
                        {
                            continue;
                        }
                    }
                    TreeNodes children = new TreeNodes {ID = "ch" + n.ID};
                    n.Controls.Add(children);
                    BuildFromDirectory(idxDir + "\\", children);
                }
            }
        }
      protected override bool Checked(WinForms::ToolStripMenuItem clickedItem, TreeView treeView, TreeNode clickedTn)
      {
         IEnumerable<IMaxNode> selNodes = TreeMode.GetMaxNodes(treeView.SelectedNodes);

         return selNodes.OfType<XRefSceneRecord>()
                        .Any(x => x.HasFlags(this.Flags));
      }
 public static void GetPathWithGivenSum(TreeNode<int> startupNode, int sum)
 {
     var pathsWithGivenSum = new List<List<int>>();
     var currentPath = new LinkedList<int>();
     ConnectPathsWithGivenSum (startupNode, currentPath, pathsWithGivenSum, sum);
     PrintPathsWithGivenSum(pathsWithGivenSum,sum);
 }
Example #5
0
    public void PopulateTreeView(string directoryValue, TreeNode parentNode )
    {
        string[] directoryArray =
           Directory.GetDirectories( directoryValue );

          try
          {
             if ( directoryArray.Length != 0 )
             {
                foreach ( string directory in directoryArray )
                {
                  substringDirectory = directory.Substring(
                  directory.LastIndexOf( '\\' ) + 1,
                  directory.Length - directory.LastIndexOf( '\\' ) - 1 );

                  TreeNode myNode = new TreeNode( substringDirectory );

                  parentNode.Nodes.Add( myNode );

                  PopulateTreeView( directory, myNode );
               }
             }
          } catch ( UnauthorizedAccessException ) {
            parentNode.Nodes.Add( "Access denied" );
          } // end catch
    }
 public static void PrintTreeByLevel(TreeNode<int> root)
 {
     var newLevelNode = new TreeNode<int>(int.MinValue);
     Console.WriteLine("\nLevel by Level Travesal: ");
     var queue = new Queue<TreeNode<int>>();
     queue.Enqueue(root);
     queue.Enqueue(newLevelNode);
     while (queue.Count > 0)
     {
         TreeNode<int> n = queue.Dequeue();
         if (n == null)
         {
             Console.Write("- ");
         }
         else if (n == newLevelNode)
         {
             Console.WriteLine(" ");
             if (queue.Count > 0)
             {
                 queue.Enqueue(newLevelNode);
             }
         }
         else
         {
             Console.Write("{0} ", n.Value);
             queue.Enqueue(n.Left);
             queue.Enqueue(n.Right);
         }
     }
 }
        public async Task<TreeNode<NavigationNode>> GetTree()
        {
            // ultimately we will need to cache sitemap per site
            // we will implement a custom ICacheKeyResolver to resolve multi tenant cache keys

            if (rootNode == null)
            {
                log.LogDebug("rootnode was null so checking cache");
                string cacheKey = cacheKeyResolver.ResolveCacheKey(options.CacheKey);

                rootNode = (TreeNode<NavigationNode>)cache.Get(cacheKey);
               
                if(rootNode == null)
                {
                    log.LogDebug("rootnode was not in cache so building");
                    rootNode = await implementation.GetTree();
                    if (rootNode != null)
                    {
                        cache.Set(
                            cacheKey,
                            rootNode,
                            new MemoryCacheEntryOptions()
                            .SetSlidingExpiration(TimeSpan.FromSeconds(options.CacheDurationInSeconds)));
                    }
                }
                else
                {
                    log.LogDebug("rootnode was found in cache");
                }
                
            }

            return rootNode;
        }
        /// <summary>
        /// Build a tree for testing purpose.
        /// </summary>
        /// <returns>The root node of the tree</returns>
        public static TreeNode<int> BuildTree()
        {
            TreeNode<int> root = new TreeNode<int>(5);
            TreeNode<int> l2l = new TreeNode<int>(3);
            TreeNode<int> l2r = new TreeNode<int>(6);
            root.Left = l2l;
            root.Right = l2r;

            TreeNode<int> l31 = new TreeNode<int>(1);
            TreeNode<int> l32 = new TreeNode<int>(4);
            TreeNode<int> l33 = new TreeNode<int>(7);

            l2l.Left = l31;
            l2l.Right = l32;
            l2r.Right = l33;

            TreeNode<int> l41 = new TreeNode<int>(2);
            TreeNode<int> l51 = new TreeNode<int>(3);
            TreeNode<int> l61 = new TreeNode<int>(4);
            TreeNode<int> l62 = new TreeNode<int>(5);

            l31.Left = l41;
            l41.Left = l51;
            l51.Left = l61;
            l51.Right = l62;

            return root;
        }
    private TreeNode BuildTree()
    {
        this.root = new TreeNode((char)0);
        this.maxTreeDepth = 0;

        for (int stringIndex = 0; stringIndex < this.searchStrings.Length; ++stringIndex)
        {
            string s = this.searchStrings[stringIndex];
            this.maxTreeDepth = Math.Max(this.maxTreeDepth, s.Length);

            var node = this.root;
            for (int charIndex = 0; charIndex < s.Length; ++charIndex)
            {
                char c = s[charIndex];
                TreeNode newNode = node.GetTransition(c);
                if (newNode == null)
                {
                    int terminal = (charIndex == s.Length - 1) ? stringIndex : -1;
                    newNode = node.AddTransition(c, terminal);
                }
                else if (charIndex == s.Length - 1)
                {
                    newNode.Terminal = stringIndex;
                }

                node = newNode;
            }
        }

        ++this.maxTreeDepth;
        return this.root;
    }
    private void BindTree()
    {
        try
        {
            string TypeFlag = Request["TypeFlag"].ToString();
            if (!string.IsNullOrEmpty(TypeFlag))
            {
                DataTable dt = ApprovalFlowSetBus.GetBillTypeByType(TypeFlag);
                if (dt != null && dt.Rows.Count > 0)
                {
                    TreeNode node = new TreeNode();
                    node.Value = dt.Rows[0]["TypeFlag"].ToString();
                    node.Text = dt.Rows[0]["ModuleName"].ToString();
                    node.NavigateUrl = string.Format("javascript:javascript:void(0)");
                    BindTreeChildNodes(node);
                    Tree_BillTpye.Nodes.Add(node);
                    node.Expanded = true;
                }

                Tree_BillTpye.DataBind();
                Tree_BillTpye.Nodes[0].Selected = true;
            }
        }
        catch (Exception)
        {
            
            throw;
        }
     
    
    }
        static TreeNode<int> ConvertBST2DLL(TreeNode<int> root, out TreeNode<int> tail)
        {
            // No null root will be passed in. So no need to check

            // Handle head.
            TreeNode<int> head;

            if (root.Left == null)
            {
                head = root;
            }
            else
            {
                head = ConvertBST2DLL(root.Left, out tail);
                tail.Right = root;
                root.Left = tail;
            }

            // Handle tail.
            if (root.Right == null)
            {
                tail = root;
            }
            else
            {
                root.Right = ConvertBST2DLL(root.Right, out tail);
                root.Right.Left = root;
            }

            // clean up tail end
            tail.Right = null;

            return head;
        }
 public Tree(Coord root)
 {
     this.rootNode = new TreeNode();
     this.rootNode.SetRoot(root,new List<Coord>());
     this.nodes = new List<TreeNode>();
     this.nodes.Add(rootNode);
 }
 private void Process(TreeNode root, List<Tuple<PropertyInfo, List<String>>> input)
 {
     List<List<String>> output = new List<List<string>>();
     ISet<String> children = new HashSet<String>();
     foreach(var item in input)
     {
         children.Add(item.Item2[item.Item2.Count - 1]);
     }
     foreach(var child in children)
     {
         List<Tuple<PropertyInfo, List<String>>> owners = input.Where(item => item.Item2[item.Item2.Count - 1] == child).ToList();
         List<Tuple<PropertyInfo, List<String>>> removeds = new List<Tuple<PropertyInfo, List<string>>>();
         PropertyInfo childProp = null;
         foreach(var owner in owners)
         {
             var removed = new List<string>(owner.Item2);
             removed.RemoveAt(removed.Count - 1);
             if (removed.Count > 0)
                 removeds.Add(Tuple.Create(owner.Item1, removed));
             else
                 childProp = owner.Item1;
         }
         TreeNode childNode = new TreeNode(child);
         childNode.Parent = root;
         childNode.Property = childProp;
         root.Children.Add(childNode);
         Process(childNode, removeds);
     }
 }
Example #14
0
 public Form1()
 {
     InitializeComponent();
     buildQuestionTree();
     currNode = questionTree.root;
     labelQuestion.Text = "Are you ready?";
 }
Example #15
0
    protected void Page_Load(object sender, EventArgs e)
    {
		if (!Page.IsPostBack)
		{
			DataSet ds = GetProductsAndCategories();

			// Loop through the category records.
			foreach (DataRow row in ds.Tables["Categories"].Rows)
			{
				// Use the constructor that requires just text
				// and a non-displayed value.
				TreeNode nodeCategory = new TreeNode(
					row["CategoryName"].ToString(),
					row["CategoryID"].ToString());

				TreeView1.Nodes.Add(nodeCategory);

				// Get the children (products) for this parent (category).
				DataRow[] childRows = row.GetChildRows(ds.Relations[0]);

				// Loop through all the products in this category.
				foreach (DataRow childRow in childRows)
				{
					TreeNode nodeProduct = new TreeNode(
						childRow["ProductName"].ToString(),
						childRow["ProductID"].ToString());
					nodeCategory.ChildNodes.Add(nodeProduct);
				}

				// Keep all categories collapsed (initially).
				nodeCategory.Collapse();
			}
		}
    }
Example #16
0
 private void recursiceRemoveSelectedItemImage(TreeNode node)
 {
     foreach (TreeNode subnode in node.ChildNodes) {
         subnode.ImageUrl = string.Empty;
         recursiceRemoveSelectedItemImage(subnode);
     }
 }
Example #17
0
 private void expandAllParents(TreeNode node)
 {
     while (node.Parent != null) {
         node.Parent.Expanded = true;
         node = node.Parent;
     }
 }
Example #18
0
    protected void Page_Load(object sender, EventArgs e)
    {
        string currentTypeUri = WebDialogueContext.GetDialogueParameter<string>("SelectedTypeUri");
           // string currentPropUri = WebDialogueContext.GetDialogueParameter<string>("SelectedPropUri");
        schemaOrgTypeTree.SelectedNodeChanged += new EventHandler(schemaOrgTypeTree_SelectedNodeChanged);
        _allTypes = SchemaOrgRepository.GetSchemaOrgTypesCached(HttpContext.Current.Cache);

        litSubheading.Text = Local.Text("Web.WAF.Dialogues.OntologySchemaOrgTypePickerListingAllTypes");
        if (!IsPostBack) {
            inputHidden.Value = currentTypeUri;
            TreeNode rootnode = new TreeNode("Thing");
            rootnode.ImageUrl = WAFContext.UrlFromHostToApp + SchemaOrgSettings.TypeIconUrl;
            rootnode.Expanded = true;
            SchemaOrgOwlType rootNode = _allTypes["http://schema.org/Thing"];

            foreach (SchemaOrgOwlType item in _allTypes.Values) {
                if (item.ParentTypes.Contains(rootNode)) {
                    TreeNode childnode = new TreeNode(item.Name, item.URI);
                    rootnode.ChildNodes.Add(childnode);
                    childnode.Expanded = false;
                    childnode.ImageUrl = WAFContext.UrlFromHostToApp + SchemaOrgSettings.TypeIconUrl;
                    HighlightIfSelected(currentTypeUri, item, childnode);
                    recursiveReadClasses(item, ref childnode, currentTypeUri);
                }
            }

            schemaOrgTypeTree.Nodes.Add(rootnode);

           // schemaOrgTypeTree.SelectedNodeStyle.BorderColor = System.Drawing.Color.Red;
        }
    }
        /// <summary>
        /// Build a Binary search tree for testing purpose
        /// </summary>
        /// <returns>The root node of the tree</returns>
        public static TreeNode<int> BuildBinarySearchTree()
        {
            TreeNode<int> root = new TreeNode<int>(15);
            TreeNode<int> l2l = new TreeNode<int>(13);
            TreeNode<int> l2r = new TreeNode<int>(20);
            root.Left = l2l;
            root.Right = l2r;

            TreeNode<int> l31 = new TreeNode<int>(11);
            TreeNode<int> l32 = new TreeNode<int>(14);
            TreeNode<int> l33 = new TreeNode<int>(17);

            l2l.Left = l31;
            l2l.Right = l32;
            l2r.Right = l33;

            TreeNode<int> l41 = new TreeNode<int>(9);
            TreeNode<int> l51 = new TreeNode<int>(6);
            TreeNode<int> l61 = new TreeNode<int>(5);
            TreeNode<int> l62 = new TreeNode<int>(7);

            l31.Left = l41;
            l41.Left = l51;
            l51.Left = l61;
            l51.Right = l62;

            return root;
        }
 public static void PrintTreeByInOrder(TreeNode<int> root)
 {
     if (root == null) return;
     PrintTreeByInOrder(root.Left);
     Console.Write("{0} ", root.Value);
     PrintTreeByInOrder(root.Right);
 }
Example #21
0
   public override int GetHeight(TreeNode tn)
   {
      if (this.Layout == null)
         return 0;

      return this.Layout.ItemHeight - 4;
   }
        public async Task<TreeNode<NavigationNode>> GetTree()
        {
            // ultimately we will need to cache sitemap per site

            if (rootNode == null)
            {
                NavigationTreeXmlConverter converter = new NavigationTreeXmlConverter();

                await cache.ConnectAsync();
                byte[] bytes = await cache.GetAsync(cacheKey);
                if (bytes != null)
                {
                    string xml = Encoding.UTF8.GetString(bytes);
                    XDocument doc = XDocument.Parse(xml);
                    
                    rootNode = converter.FromXml(doc);
                }
                else
                {
                    rootNode = await BuildTree();
                    string xml2 = converter.ToXmlString(rootNode);

                    await cache.SetAsync(
                                        cacheKey,
                                        Encoding.UTF8.GetBytes(xml2),
                                        new DistributedCacheEntryOptions().SetSlidingExpiration(
                                            TimeSpan.FromSeconds(100))
                                            );
                                        }

                
            }

            return rootNode;
        }
 private void BuildTree()
 {
     foreach(Node idx in Data)
     {
         if(idx.Name == "Controllers")
         {
             TreeNode node = new TreeNode();
             node.ID = "idController";
             node.Text = LanguageRecords.Language.Instance["Controllers", null, "Controllers"];
             root.Controls.Add(node);
             BuildChildren(idx, node);
         }
         else if(idx.Name == "Modules")
         {
             TreeNode node = new TreeNode();
             node.ID = "idModules";
             node.Text = LanguageRecords.Language.Instance["Modules", null, "Modules"];
             root.Controls.Add(node);
             BuildChildren(idx, node);
         }
         else if(idx.Name == "Types")
         {
             TreeNode node = new TreeNode();
             node.ID = "idTypes";
             node.Text = LanguageRecords.Language.Instance["Types", null, "Types"];
             root.Controls.Add(node);
             BuildChildren(idx, node);
         }
     }
 }
		public void FindNode_NodeThere_ReturnsTheNode()
		{
			var node = new TreeNode("AnotherNode");
			service.PushNode(node);
			service.PopNode();
			Assert.AreEqual(node, service.FindNode("AnotherNode"));
		}
        static void InOrderTraverseLoop(TreeNode<int> root)
        {
            Stack<TreeNode<int>> stack = new Stack<TreeNode<int>>();

            TreeNode<int> cur = root;

            while (cur != null)
            {
                if (cur.Visited == false && cur.Left != null)
                {
                    stack.Push(cur);
                    cur = cur.Left;
                    continue;
                }

                Console.Write(cur.Value);
                Console.Write(" ");

                if (cur.Right != null)
                {
                    cur = cur.Right;
                    continue;
                }

                if (!stack.IsEmpty())
                {
                    cur = stack.Pop();
                    cur.Visited = true;
                }
                else
                    cur = null;
            }
        }
    public int MinDepth(TreeNode root)
    {
        int depth = 0;
        Queue<TreeNode> nodes = new Queue<TreeNode>();

        if(root != null)
        {
            nodes.Enqueue(root);
        }

        while(nodes.Count != 0)
        {
            depth++;
            int noNodesInLevel = nodes.Count;
            for(int i = 0; i < noNodesInLevel; i++)
            {
                TreeNode node = nodes.Dequeue();
                if(node.left == null && node.right == null)
                {
                    return depth;
                }
                if(node.left != null)
                {
                    nodes.Enqueue(node.left);
                }
                if(node.right != null)
                {
                    nodes.Enqueue(node.right);
                }
            }
        }

        return depth;
    }
Example #27
0
    private void getCountries(SqlConnection conn)
    {
        string country0 = "", country, id, state;
        TreeNode countryNode = null;

        string cmdText = "select Country, ID, State FROM V_CountryStates";
        using (SqlCommand cmd = new SqlCommand(cmdText, conn)) {
            using (SqlDataReader sdr = cmd.ExecuteReader()) {
                int ct = 0;
                while (sdr.Read()) {
                    country = ClsUtil.ObjToStr(sdr[0]);
                    id = ClsUtil.ObjToStr(sdr[1]);
                    state = ClsUtil.ObjToStr(sdr[2]);

                    if (country != country0)
                    {
                        countryNode = new TreeNode(country, country);
                        countryNode.ToolTip = country;
                        countryNode.SelectAction = TreeNodeSelectAction.Expand;
                        tvContent.Nodes.Add(countryNode);
                        country0 = country;
                        ct = 0;
                    }

                    TreeNode stateNode = new TreeNode("[" + (++ct) + "] " + state, state);
                    //stateNode.NavigateUrl = "?";
                    stateNode.ToolTip = state;
                    countryNode.ChildNodes.Add(stateNode);
                }
            }
        }
    }
 public void TestMethod(int maxSize, int repeatTimes)
 {
     Repeat(repeatTimes, () =>
     {
         var size = Random.Next(2, maxSize + 1);
         var allNodes = new TreeNode[size];
         var root = CreateTree(allNodes, 0, size - 1);
         var value1 = Random.Next(0, size - 1);
         var value2 = Random.Next(value1 + 1, size);
         Assert.IsTrue(value1 < value2);
         allNodes[value1].val = value2;
         allNodes[value2].val = value1;
         var testData = string.Format("value1: {0}. value2: {1}.\r\ntree:\r\n {2}",
             value1, value2, JsonConvert.SerializeObject(root, Formatting.Indented, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }));
         try
         {
             new Solution().RecoverTree(root);
         }
         catch (Exception ex)
         {
             Assert.Fail("{0}\r\nException: {1}", testData, ex);
         }
         Assert.AreEqual(value1, allNodes[value1].val, testData);
         Assert.AreEqual(value2, allNodes[value2].val, testData);
     });
 }
        public async Task<TreeNode<NavigationNode>> BuildTree(
            NavigationTreeBuilderService service)
        {
            // ultimately we will need to cache sitemap per site

            if (rootNode == null)
            {
                
                //await cache.ConnectAsync();
                byte[] bytes = await cache.GetAsync(cacheKey);
                if (bytes != null)
                {
                    string json = Encoding.UTF8.GetString(bytes);
                    rootNode = BuildTreeFromJson(json);
                }
                else
                {
                    rootNode = await BuildTree();
                    string json = rootNode.ToJsonCompact();

                    await cache.SetAsync(
                                        cacheKey,
                                        Encoding.UTF8.GetBytes(json),
                                        new DistributedCacheEntryOptions().SetSlidingExpiration(
                                            TimeSpan.FromSeconds(100))
                                            );
                }
            }

            return rootNode;
        }
Example #30
0
    private void RefTV()
    {
        DataSet ds = new DataSet();
        string sql = "Select ID,PageName,PageUrl,PageDes From TbRight Where XianShiFlag=1 And NodeLevel=0 And ID IN (select distinct RightID from RoleRight where RoleID in (select RoleID from UserRole where UserID='" + Session["UserID"] + "')) Order BY XianShiShunXu ASC,ID ASC";
        ds = DBA.DbAccess.GetDataSet(CommandType.Text, sql);

        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
        {
            TreeNode node = new TreeNode(ds.Tables[0].Rows[i]["PageDes"].ToString().Trim(), ds.Tables[0].Rows[i]["ID"].ToString().Trim());
            // node.NavigateUrl = ds.Tables[0].Rows[i]["PageUrl"].ToString().Trim();

            node.SelectAction = TreeNodeSelectAction.None;
            tTV.Nodes.Add(node);
        }

        AddNode2TV();

        for (int i = 0; i < tTV.Nodes.Count; i++)
        {
            for (int j = 0; j < tTV.Nodes[i].ChildNodes.Count; j++)
            {
                if (tTV.Nodes[i].ChildNodes[j].NavigateUrl.ToString().Trim() == Request.RawUrl.ToString().Trim().Substring(Request.RawUrl.ToString().Trim().LastIndexOf("/") + 1))
                {
                    tTV.Nodes[i].ChildNodes[j].Selected = true;
                }
            }
        }
    }
Example #31
0
 internal void OnDeactivated()
 {
     _deactivatedNode = _optionsTree.SelectedNode;
 }
        /// <summary>
        ///     将数据库放入Node
        /// </summary>
        /// <param name="strDbName"></param>
        /// <param name="mongoSvrKey"></param>
        /// <param name="client"></param>
        /// <returns></returns>
        public static TreeNode FillDataBaseInfoToTreeNode(string strDbName, string mongoSvrKey,
                                                          MongoClient client = null)
        {
            var strShowDbName = strDbName;

            if (!GuiConfig.IsUseDefaultLanguage)
            {
                if (StringResource.LanguageType == "Chinese")
                {
                    switch (strDbName)
                    {
                    case ConstMgr.DatabaseNameAdmin:
                        strShowDbName = "管理员权限(admin)";
                        break;

                    case "local":
                        strShowDbName = "本地(local)";
                        break;

                    case "config":
                        strShowDbName = "配置(config)";
                        break;
                    }
                }
            }
            var mongoDbNode = new TreeNode(strShowDbName);

            mongoDbNode.Tag = TagInfo.CreateTagInfo(mongoSvrKey, strDbName);

            var userNode = new TreeNode("User", (int)GetSystemIcon.MainTreeImageType.UserIcon,
                                        (int)GetSystemIcon.MainTreeImageType.UserIcon);

            userNode.Tag = ConstMgr.UserListTag + ":" + mongoSvrKey + "/" + strDbName + "/" +
                           ConstMgr.CollectionNameUser;
            mongoDbNode.Nodes.Add(userNode);

            var jsNode = new TreeNode("JavaScript", (int)GetSystemIcon.MainTreeImageType.JavaScriptList,
                                      (int)GetSystemIcon.MainTreeImageType.JavaScriptList);

            jsNode.Tag = ConstMgr.JavascriptTag + ":" + mongoSvrKey + "/" + strDbName + "/" +
                         ConstMgr.CollectionNameJavascript;
            mongoDbNode.Nodes.Add(jsNode);

            var gfsNode = new TreeNode("Grid File System", (int)GetSystemIcon.MainTreeImageType.Gfs,
                                       (int)GetSystemIcon.MainTreeImageType.Gfs);

            gfsNode.Tag = ConstMgr.GridFileSystemTag + ":" + mongoSvrKey + "/" + strDbName + "/" +
                          ConstMgr.CollectionNameGfsFiles;
            mongoDbNode.Nodes.Add(gfsNode);

            var mongoSysColListNode = new TreeNode("Collections(System)",
                                                   (int)GetSystemIcon.MainTreeImageType.SystemCol, (int)GetSystemIcon.MainTreeImageType.SystemCol);

            mongoSysColListNode.Tag = ConstMgr.SystemCollectionListTag + ":" + mongoSvrKey + "/" + strDbName;
            mongoDbNode.Nodes.Add(mongoSysColListNode);

            var mongoColListNode = new TreeNode("Collections(General)",
                                                (int)GetSystemIcon.MainTreeImageType.CollectionList,
                                                (int)GetSystemIcon.MainTreeImageType.CollectionList);

            mongoColListNode.Tag = ConstMgr.CollectionListTag + ":" + mongoSvrKey + "/" + strDbName;
            var colNameList = GetConnectionInfo.GetCollectionList(client, strDbName);

            //Collection按照名称排序
            colNameList.Sort((x, y) =>
            {
                return(x.GetElement("name").Value.ToString().CompareTo(y.GetElement("name").Value.ToString()));
            });
            foreach (var colDoc in colNameList)
            {
                var strColName = colDoc.GetElement("name").Value.ToString();
                switch (strColName)
                {
                case ConstMgr.CollectionNameUser:
                    //system.users,fs,system.js这几个系统级别的Collection不需要放入
                    break;

                case ConstMgr.CollectionNameJavascript:
                    //foreach (var doc in  MongoHelper.NewUtility.GetConnectionInfo.GetCollectionInfo(client, strDBName, ConstMgr.COLLECTION_NAME_JAVASCRIPT).Find<BsonDocument>(null,null))
                    //{
                    //    var js = new TreeNode(doc.GetValue(ConstMgr.KEY_ID).ToString());
                    //    js.ImageIndex = (int) GetSystemIcon.MainTreeImageType.JsDoc;
                    //    js.SelectedImageIndex = (int) GetSystemIcon.MainTreeImageType.JsDoc;
                    //    js.Tag = ConstMgr.JAVASCRIPT_DOC_TAG + ":" + mongoSvrKey + "/" + strDBName + "/" +
                    //             ConstMgr.COLLECTION_NAME_JAVASCRIPT + "/" + doc.GetValue(ConstMgr.KEY_ID);
                    //    JsNode.Nodes.Add(js);
                    //}

                    FillJavaScriptInfoToTreeNode(jsNode,
                                                 GetConnectionInfo.GetCollectionInfo(client, strDbName, strColName), mongoSvrKey, strDbName);

                    break;

                default:
                    TreeNode mongoColNode;
                    try
                    {
                        var col = GetConnectionInfo.GetCollectionInfo(client, strDbName, strColName);
                        mongoColNode = FillCollectionInfoToTreeNode(col, mongoSvrKey);
                    }
                    catch (Exception ex)
                    {
                        mongoColNode                    = new TreeNode(strColName + "[exception:]");
                        mongoColNode.ImageIndex         = (int)GetSystemIcon.MainTreeImageType.Err;
                        mongoColNode.SelectedImageIndex = (int)GetSystemIcon.MainTreeImageType.Err;
                        Utility.ExceptionDeal(ex);
                    }
                    if (Operater.IsSystemCollection(strDbName, strColName))
                    {
                        switch (strColName)
                        {
                        case ConstMgr.CollectionNameGfsChunks:
                        case ConstMgr.CollectionNameGfsFiles:
                            gfsNode.Nodes.Add(mongoColNode);
                            break;

                        default:
                            mongoSysColListNode.Nodes.Add(mongoColNode);
                            break;
                        }
                    }
                    else
                    {
                        mongoColListNode.Nodes.Add(mongoColNode);
                    }
                    break;
                }
            }
            mongoDbNode.Nodes.Add(mongoColListNode);
            mongoDbNode.ImageIndex         = (int)GetSystemIcon.MainTreeImageType.Database;
            mongoDbNode.SelectedImageIndex = (int)GetSystemIcon.MainTreeImageType.Database;
            return(mongoDbNode);
        }
        private void assertObjectsTree(cmisObjectInFolderContainerType[] receivedTree, TreeNode <string> expectedTreeRoot)
        {
            Assert.IsNotNull(receivedTree, "Objects from response are null");
            Assert.IsTrue(receivedTree.Length > 0, "No one Object was returned in response");

            TreeNode <string> currentTreeNode = expectedTreeRoot;
            Stack <KeyValuePair <cmisObjectInFolderContainerType, TreeNode <string> > > elementsStack = new Stack <KeyValuePair <cmisObjectInFolderContainerType, TreeNode <string> > >();
            cmisObjectInFolderContainerType root = new cmisObjectInFolderContainerType();

            root.children = receivedTree;
            elementsStack.Push(new KeyValuePair <cmisObjectInFolderContainerType, TreeNode <string> >(root, expectedTreeRoot));

            while (elementsStack.Count > 0)
            {
                KeyValuePair <cmisObjectInFolderContainerType, TreeNode <string> > element = elementsStack.Pop();
                Assert.IsNotNull(element.Key, "Expected tree element not found");
                Assert.IsNotNull(element.Value, "Received tree element not found");
                currentTreeNode = element.Value;
                Assert.IsTrue(getSize(element.Key.children) == getSize(currentTreeNode.Children), "Count of returned childs are not equal to expected count of childs");
                if (element.Key.children != null && currentTreeNode.Children != null)
                {
                    HashSet <string> receivedIds = new HashSet <string>();
                    foreach (cmisObjectInFolderContainerType objectInFolderContainer in element.Key.children)
                    {
                        string objectId = getAndAssertObjectId(objectInFolderContainer);
                        Assert.IsFalse(receivedIds.Contains(objectId), "Returned tree childs are not equal to expected childs");
                        receivedIds.Add(objectId);
                        TreeNode <string> childTreeNode = (TreeNode <string>)currentTreeNode.Children[objectId];
                        elementsStack.Push(new KeyValuePair <cmisObjectInFolderContainerType, TreeNode <string> >(objectInFolderContainer, childTreeNode));
                    }
                }
            }
        }
Example #34
0
        private void treeDrugMsg_AfterCheck(object sender, TreeViewEventArgs e)
        {
            try
            {
                DataTable dt = (DataTable)dgrdRecipeInfo.DataSource;
                if (e.Node != null)
                {
                    this.Cursor = GWMHIS.BussinessLogicLayer.Classes.PublicStaticFun.WaitCursor();
                    if (e.Node.Level == 2 && e.Node.Checked)
                    {
                        ZY_PatList currentMsg = (ZY_PatList)(e.Node.Tag);
                        _selectDeptId = Convert.ToInt32(currentMsg.CurrDeptCode);
                        selectPat.Remove(currentMsg);
                        selectPat.Add(currentMsg);
                        TreeNode rootNode = treeDrugMsg.Nodes[0];
                        foreach (TreeNode node in rootNode.Nodes)
                        {
                            foreach (TreeNode msgNode in node.Nodes)
                            {
                                if (((ZY_PatList)msgNode.Tag).CurrDeptCode != currentMsg.CurrDeptCode &&
                                    msgNode.Checked == true)
                                {
                                    msgNode.Parent.Checked = false;
                                    break;
                                }
                            }
                        }
                        _allDispPats.Remove(currentMsg.CureNo);
                        if (dt != null)
                        {
                            DataTable recipeDt = IN_InterFace.QueryRecipeOrder(currentMsg, (int)_currentDeptId);
                            _allDispPats.Add(currentMsg.CureNo, recipeDt);
                            DataTable recipeCopy = recipeDt.Clone();
                            recipeCopy.Clear();

                            for (int index = 0; index < recipeDt.Rows.Count; index++)
                            {
                                // _recipeOrder.Rows.Add(recipeDt.Rows[index].ItemArray);
                                recipeCopy.Rows.Add(recipeDt.Rows[index].ItemArray);
                                decimal presamount = (recipeCopy.Rows[index]["presamount"] == null || recipeCopy.Rows[index]["presamount"].ToString() == "0" ? 1 : Convert.ToDecimal(recipeCopy.Rows[index]["presamount"].ToString()));
                                recipeCopy.Rows[index]["amount"] = Convert.ToDecimal(recipeCopy.Rows[index]["amount"].ToString()) / presamount;
                                dt.Rows.Add(recipeCopy.Rows[index].ItemArray);
                            }
                            dgrdRecipeInfo.DataSource = dt;
                        }
                        else
                        {
                            _recipeOrder = IN_InterFace.QueryRecipeOrder(currentMsg, (int)_currentDeptId);
                            _allDispPats.Add(currentMsg.CureNo, _recipeOrder);
                            DataTable dtCopy = _recipeOrder.Clone();
                            dtCopy.Clear();
                            for (int i = 0; i < _recipeOrder.Rows.Count; i++)
                            {
                                dtCopy.Rows.Add(_recipeOrder.Rows[i].ItemArray);
                                decimal presamount = (dtCopy.Rows[i]["presamount"] == null || dtCopy.Rows[i]["presamount"].ToString() == "0" ? 1 : Convert.ToDecimal(dtCopy.Rows[i]["presamount"].ToString()));
                                dtCopy.Rows[i]["amount"] = Convert.ToDecimal(dtCopy.Rows[i]["amount"].ToString()) / presamount;
                            }
                            dgrdRecipeInfo.DataSource = dtCopy;
                        }
                    }
                    if (e.Node.Level == 2 && !e.Node.Checked)
                    {
                        ZY_PatList currentMsg = (ZY_PatList)(e.Node.Tag);
                        selectPat.Remove(currentMsg);
                        _allDispPats.Remove(currentMsg.CureNo);
                        if (_recipeOrder != null)
                        {
                            DataRow[] removeRows = dt.Select("cureno=" + "'" + currentMsg.CureNo.ToString() + "'");
                            foreach (DataRow removeRow in removeRows)
                            {
                                dt.Rows.Remove(removeRow);
                            }
                        }
                        dgrdRecipeInfo.DataSource = dt;
                    }
                    if ((e.Node.Level == 2 && e.Node.Checked) ||
                        (e.Node.Level == 1 && e.Node.Checked))
                    {
                        e.Node.Parent.Checked = true;
                    }
                    if ((e.Node.Level == 1 && !e.Node.Checked) ||
                        (e.Node.Level == 0 && !e.Node.Checked))
                    {
                        foreach (TreeNode node in e.Node.Nodes)
                        {
                            node.Checked = false;
                        }
                    }
                }
            }
            catch (Exception error)
            {
                MessageBox.Show(error.Message);
            }
            finally
            {
                this.Cursor = DefaultCursor;
            }
        }
Example #35
0
        private void GetFriend()
        {
            treeView1.Nodes.Clear();
            
            TreeNode tn2 = new TreeNode("分组");
            tn2.Name = "WardS";
            treeView1.Nodes.Add(tn2);
           

            //TreeNode tn1 = new TreeNode("我的好友");
            //tn1.Name = "Friends";
            //treeView1.Nodes.Add(tn1);

            TreeNode tn3 = new TreeNode("公告");
            tn3.Name = "AllWard";
            tn3.Tag = "AllWard";
            tn2.Nodes.Add(tn3);
            if (loginType == "PivasNurse")
            {
                TreeNode tn5 = new TreeNode();
                tn5.Text = "配置中心";
                tn5.Name = "PivasMate";
                tn5.Tag = "PivasMate";
                tn2.Nodes.Add(tn5);

                TreeNode tn4 = new TreeNode();
                tn4.Text = label4.Text;
                tn4.Name = WardCode;
                tn4.Tag = WardCode;
                tn2.Nodes.Add(tn4);

            
            }
            else if(loginType=="PivasMate")
            {
                DataSet ds1 = db.GetPIVAsDB("select WardCode,WardName from DWard where IsOpen=1 order by wardcode");
             
                for (int i = 0; i < ds1.Tables[0].Rows.Count; i++)
                {
                    TreeNode tn = new TreeNode();
                    tn.Text = ds1.Tables[0].Rows[i]["WardName"].ToString();
                    tn.Name = ds1.Tables[0].Rows[i]["WardCode"].ToString();
                    tn.Tag = ds1.Tables[0].Rows[i]["WardCode"].ToString();
                    tn2.Nodes.Add(tn);
                }
            }

            //DataSet ds = db.GetPIVAsDB(sql.GetFriend(Demployeeid));
            //if (ds != null)
            //{
            //    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            //    {
            //        if (ds.Tables[0].Rows[i]["GroupNo"].ToString() == "0")
            //        {
            //            TreeNode tn = new TreeNode();
            //            tn.Text = ds.Tables[0].Rows[i]["Name"].ToString();
            //            tn.Tag = ds.Tables[0].Rows[i]["FriendId"].ToString();
            //            tn1.Nodes.Add(tn);
            //        }
          
            //    }
            //}
        }
        public TreeNode <MediaFolderNode> GetRootNode()
        {
            var cacheKey = FolderTreeKey;

            var root = _cache.Get(cacheKey, () =>
            {
                var query = from x in _folderRepository.TableUntracked
                            orderby x.ParentId, x.Name
                select x;

                var unsortedNodes = query.ToList().Select(x =>
                {
                    var item = new MediaFolderNode
                    {
                        Id              = x.Id,
                        Name            = x.Name,
                        ParentId        = x.ParentId,
                        CanDetectTracks = x.CanDetectTracks,
                        FilesCount      = x.FilesCount,
                        Slug            = x.Slug
                    };

                    if (x is MediaAlbum album)
                    {
                        item.IsAlbum     = true;
                        item.AlbumName   = album.Name;
                        item.Path        = album.Name;
                        item.ResKey      = album.ResKey;
                        item.IncludePath = album.IncludePath;
                        item.Order       = album.Order ?? 0;

                        var albumInfo = _albumRegistry.GetAlbumByName(album.Name);
                        if (albumInfo != null)
                        {
                            var displayHint   = albumInfo.DisplayHint;
                            item.Color        = displayHint.Color;
                            item.OverlayColor = displayHint.OverlayColor;
                            item.OverlayIcon  = displayHint.OverlayIcon;
                        }
                    }

                    return(item);
                });

                var nodeMap  = unsortedNodes.ToMultimap(x => x.ParentId ?? 0, x => x);
                var rootNode = new TreeNode <MediaFolderNode>(new MediaFolderNode {
                    Name = "Root", Id = 0
                });

                AddChildTreeNodes(rootNode, 0, nodeMap);

                return(rootNode);
            }, FolderTreeCacheDuration);

            return(root);

            void AddChildTreeNodes(TreeNode <MediaFolderNode> parentNode, int parentId, Multimap <int, MediaFolderNode> nodeMap)
            {
                var parent = parentNode?.Value;

                if (parent == null)
                {
                    return;
                }

                var nodes = Enumerable.Empty <MediaFolderNode>();

                if (nodeMap.ContainsKey(parentId))
                {
                    nodes = parentId == 0
                        ? nodeMap[parentId].OrderBy(x => x.Order)
                        : nodeMap[parentId].OrderBy(x => x.Name);
                }

                foreach (var node in nodes)
                {
                    var newNode = new TreeNode <MediaFolderNode>(node);

                    // Inherit some props from parent node
                    if (!node.IsAlbum)
                    {
                        node.AlbumName       = parent.AlbumName;
                        node.CanDetectTracks = parent.CanDetectTracks;
                        node.IncludePath     = parent.IncludePath;
                        node.Path            = (parent.Path + "/" + (node.Slug.NullEmpty() ?? node.Name)).Trim('/').ToLower();
                    }

                    // We gonna query nodes by path also, therefore we need 2 keys per node (FolderId and computed path)
                    newNode.Id = new object[] { node.Id, node.Path };

                    parentNode.Append(newNode);

                    AddChildTreeNodes(newNode, node.Id, nodeMap);
                }
            }
        }
Example #37
0
        private void TreeViewAfterSelect(object sender, TreeViewEventArgs e)
        {
            TreeNode node = e.Node;

            if (node.FullPath == "我的电脑")//当前选择了我的电脑根目录
            {
                currentFolderType = FolderType.COMPUTER;

                InitListViewDrive();
                listView1.Items.Clear();
                DriveInfo[] allDirves = DriveInfo.GetDrives();
                //检索计算机上的所有逻辑驱动器名称
                foreach (DriveInfo item in allDirves)
                {
                    //Fixed 硬盘
                    //Removable 可移动存储设备,如软盘驱动器或USB闪存驱动器。
                    if (item.IsReady)
                    {
                        string driveName = string.Format("{0} ({1})", item.VolumeLabel, item.Name.Replace("\\", ""));

                        ListViewItem li = new ListViewItem();
                        li.Text       = driveName;
                        li.ImageIndex = (int)ImageFileType.DRIVE;
                        li.SubItems.Add(item.DriveFormat);
                        li.SubItems.Add(Util.FormatSize(item.TotalSize));
                        li.SubItems.Add(Util.FormatSize(item.TotalSize - item.TotalFreeSpace));
                        li.SubItems.Add(Util.FormatSize(item.TotalFreeSpace));
                        if (item.TotalFreeSpace * 10 < item.TotalSize)//剩余空间不足10%背景显示红色
                        {
                            li.BackColor = Color.Red;
                        }
                        listView1.Items.Add(li);
                    }
                    else
                    {
                        Console.Write("没有就绪");
                    }
                }
            }
            else
            {
                InitListView();
                bool        isdriveRoot = false;
                DriveInfo[] allDirves   = DriveInfo.GetDrives();
                //检索计算机上的所有逻辑驱动器名称
                foreach (DriveInfo item in allDirves)
                {
                    string driveName = string.Format("{0} ({1})", item.VolumeLabel, item.Name.Replace("\\", ""));
                    if (node.Text == driveName)
                    {
                        currentFolderType = FolderType.Driver;
                        AddListItemByFullPath(item.Name);
                        isdriveRoot = true;
                        break;
                    }
                }
                if (!isdriveRoot && treeNodeDic.ContainsKey(node.FullPath) && (CurSelectNode == null || CurSelectNode.TreeNode != node))
                {
                    CurSelectNode     = treeNodeDic[node.FullPath];
                    currentFolderType = FolderType.DIRECTORY;
                    AddListItem(node);
                }
            }
        }
Example #38
0
        public void LoadXmlFileInTreeView(TreeView treeView, string fileName)
        {
            XmlTextReader reader = null;

            try
            {
                treeView.BeginUpdate();
                reader = new XmlTextReader(fileName);

                TreeNode n = new TreeNode(fileName);
                treeView.Nodes.Add(n);
                while (reader.Read())
                {
                    if (reader.NodeType == XmlNodeType.Element)
                    {
                        bool          isEmptyElement = reader.IsEmptyElement;
                        StringBuilder text           = new StringBuilder();
                        text.Append(reader.Name);
                        int attributeCount = reader.AttributeCount;
                        if (attributeCount > 0)
                        {
                            text.Append(" ( ");
                            for (int i = 0; i < attributeCount; i++)
                            {
                                if (i != 0)
                                {
                                    text.Append(", ");
                                }
                                reader.MoveToAttribute(i);
                                text.Append(reader.Name);
                                text.Append(" = ");
                                text.Append(reader.Value);
                            }
                            text.Append(" ) ");
                        }

                        if (isEmptyElement)
                        {
                            n.Nodes.Add(text.ToString());
                        }
                        else
                        {
                            n = n.Nodes.Add(text.ToString());
                        }
                    }
                    else if (reader.NodeType == XmlNodeType.EndElement)
                    {
                        n = n.Parent;
                    }
                    else if (reader.NodeType == XmlNodeType.XmlDeclaration)
                    {
                    }
                    else if (reader.NodeType == XmlNodeType.None)
                    {
                        return;
                    }
                    else if (reader.NodeType == XmlNodeType.Text)
                    {
                        n.Nodes.Add(reader.Value);
                    }
                }
            }
            finally
            {
                treeView.EndUpdate();
                reader.Close();
            }
        }
Example #39
0
 public TreeNode(int val = 0, TreeNode left = null, TreeNode right = null)
 {
     this.val   = val;
     this.left  = left;
     this.right = right;
 }
Example #40
0
 private void RefreshViewList(TreeNode node)
 {
     listView1.Items.Clear();
     AddListItem(node);
 }