• 推荐
  • 评论
  • 收藏

Extjs入门之动态加载树

2022-11-26    9223次浏览

最近做个一个EntityFramework的DEMO,刚开始做的时候在删除跟修改数据时采取的是根据ID查询到对应实体,然后再删除和更新实体,发现这样做多查询了一次数据库。尤其是做修改的时候,还得每个属性进行赋值修改,加大了代码量。 因此寻找另一条出路,思路大概是这样的:首先获取需要修改或者删除的对象,根据EntityKey判断上下文中是否存在,假如存在,则移除上下文中的对象。然后把获取到的对象附加到对象上下文中,再将上下文更新保存的数据库。

 1 public void Update(Student entity)
 2         {
 3             entity.EntityKey = Session.CreateEntityKey("Students", entity);
 4             object s=new Student();
 5             if (Session.TryGetObjectByKey(entity.EntityKey, out s))
 6             {
 7                 Session.ObjectStateManager.ChangeObjectState(s, System.Data.EntityState.Deleted);
 8                 Session.Detach(s);
 9             }
10             Session.Attach(entity);
11             Session.ObjectStateManager.ChangeObjectState(entity, System.Data.EntityState.Modified);
12             Session.SaveChanges();
13        
public void Delete(Student entity)
        {
            entity.EntityKey 
= Session.CreateEntityKey("Students", entity);
            
object s = new Student();
            
if (Session.TryGetObjectByKey(entity.EntityKey, out s))
            {
                Session.Students.DeleteObject((Student)s);
            }
            
else
            {
                Session.AttachTo(
"Students", entity);
                Session.Students.DeleteObject(entity);
            }
            Session.SaveChanges();
        }
 }

此代码可能存在着各种漏洞。

本文将使用C#来获取系统的基本信息。

  结果如图所示:

  为了获取系统信息,我将调用windows自带的kernel32.dll程序。代码如下所示:

 1 using System;
  2 using System.Collections.Generic;
  3 using System.ComponentModel;
  4 using System.Data;
  5 using System.Drawing;
  6 using System.Linq;
  7 using System.Text;
  8 using System.Windows.Forms;
  9 using System.Runtime.InteropServices;
 10 
 11 namespace getSystemInfo
 12 {
 13     
 14 
 15     public partial class Form1 : Form
 16     {
 17         public Form1()
 18         {
 19             InitializeComponent();
 20         }
 21 
 22         [DllImport("kernel32")]
 23         public static extern void GetWindowsDirectory(StringBuilder WinDir, int count);
 24 
 25         [DllImport("kernel32")]
 26         public static extern void GetSystemDirectory(StringBuilder SysDir, int count);
 27 
 28         [DllImport("kernel32")]
 29         public static extern void GetSystemInfo(ref CPU_INFO cpuinfo);
 30 
 31         [DllImport("kernel32")]
 32         public static extern void GlobalMemoryStatus(ref MEMORY_INFO meminfo);
 33 
 34         [DllImport("kernel32")]
 35         public static extern void GetSystemTime(ref SYSTEMTIME_INFO stinfo);
 36 
 37         //定义以下各结构
 38         //定义CPU的信息结构
 39         [StructLayout(LayoutKind.Sequential)]
 40         public struct CPU_INFO
 41         {
 42             public uint dwOemId;
 43             public uint dwPageSize;
 44             public uint lpMinimumApplicationAddress;
 45             public uint lpMaximumApplicationAddress;
 46             public uint dwActiveProcessorMask;
 47             public uint dwNumberOfProcessors;
 48             public uint dwProcessorType;
 49             public uint dwAllocationGranularity;
 50             public uint dwProcessorLevel;
 51             public uint dwProcessorRevision;
 52         }
 53 
 54         //定义内存的信息结构
 55         [StructLayout(LayoutKind.Sequential)]
 56         public struct MEMORY_INFO
 57         {
 58             public uint dwLength;
 59             public uint dwMemoryLoad;
 60             public uint dwTotalPhys;
 61             public uint dwAvailPhys;
 62             public uint dwTotalPageFile;
 63             public uint dwAvailPageFile;
 64             public uint dwTotalVirtual;
 65             public uint dwAvailVirtual;
 66         }
 67 
 68         //定义系统时间的信息结构
 69         [StructLayout(LayoutKind.Sequential)]
 70         public struct SYSTEMTIME_INFO
 71         {
 72             public ushort wYear;
 73             public ushort wMonth;
 74             public ushort wDayOfWeek;
 75             public ushort wDay;
 76             public ushort wHour;
 77             public ushort wMinute;
 78             public ushort wSecond;
 79             public ushort wMilliseconds;
 80         }
 81 
 82         private void button1_Click(object sender, EventArgs e)
 83         {
 84             string strResult = null;
 85             //调用GetWindowsDirectory和GetSystemDirectory函数分别取得Windows路径和系统路径
 86             const int nChars = 128;
 87             StringBuilder Buff = new StringBuilder(nChars);
 88             GetWindowsDirectory(Buff, nChars);
 89             labWindowPath.Text = "Windows路径:" + Buff.ToString();
 90             GetSystemDirectory(Buff, nChars);
 91             lbSystemPath.Text = "系统路径:" + Buff.ToString();
 92 
 93             //调用GetSystemInfo函数获取CPU的相关信息
 94             CPU_INFO CpuInfo;
 95             CpuInfo = new CPU_INFO();
 96             GetSystemInfo(ref CpuInfo);
 97             lbCupCount.Text = "本计算机中有" + CpuInfo.dwNumberOfProcessors.ToString() + "个CPU";
 98             lbCpuType.Text = "CPU的类型为" + CpuInfo.dwProcessorType.ToString();
 99             strResult  += "CPU等级为" + CpuInfo.dwProcessorLevel.ToString();
100             lbCpuEom.Text = "CPU的OEM ID为" + CpuInfo.dwOemId.ToString();
101             strResult  += "CPU中的页面大小为" + CpuInfo.dwPageSize.ToString();
102 
103             //调用GlobalMemoryStatus函数获取内存的相关信息
104             MEMORY_INFO MemInfo;
105             MemInfo = new MEMORY_INFO();
106             GlobalMemoryStatus(ref MemInfo);
107             lbNcsyl.Text = MemInfo.dwMemoryLoad.ToString() + "%的内存正在使用";
108             LbNCTotal.Text = "物理内存共有" + MemInfo.dwTotalPhys.ToString() + "字节";
109             LbNcKy.Text = "可使用的物理内存有" + MemInfo.dwAvailPhys.ToString() + "字节";
110             strResult  += "交换文件总大小为" + MemInfo.dwTotalPageFile.ToString() + "字节";
111             strResult  += "尚可交换文件大小为" + MemInfo.dwAvailPageFile.ToString() + "字节";
112             LbXnncTotal.Text = "总虚拟内存有" + MemInfo.dwTotalVirtual.ToString() + "字节";
113             LbKyxnnc.Text = "未用虚拟内存有" + MemInfo.dwAvailVirtual.ToString() + "字节";
114 
115             //调用GetSystemTime函数获取系统时间信息
116             SYSTEMTIME_INFO StInfo;
117             StInfo = new SYSTEMTIME_INFO();
118             GetSystemTime(ref StInfo);
119             LabRq.Text = StInfo.wYear.ToString() + "年" + StInfo.wMonth.ToString() + "月" + StInfo.wDay.ToString() + "日";
120             lbXtrq.Text = (StInfo.wHour + 8).ToString() + "点" + StInfo.wMinute.ToString() + "分" + StInfo.wSecond.ToString() + "秒";
121            // label1.Text = strResult.ToString();
122 
123             //获取计算机名称
124             lbCompName.Text += System.Environment.UserName;
125             lbMaName.Text += System.Environment.MachineName;
126             lbOSInfo.Text += System.Environment.OSVersion;
127             lbNetName.Text += System.Environment.UserDomainName;
128         }
129     }
130 }
131 

Extjs入门之动态加载树

Extjs动态加载树,首先在数据库里面设计存放树信息的表

1 USE [KimiExtjs]
 2 GO
 3 /****** 对象:  Table [dbo].[Trees]    脚本日期: 04/08/2010 22:12:25 ******/
 4 SET ANSI_NULLS ON
 5 GO
 6 SET QUOTED_IDENTIFIER ON
 7 GO
 8 SET ANSI_PADDING ON
 9 GO
10 CREATE TABLE [dbo].[Trees](
11     [Tid] [varchar](40) COLLATE Chinese_PRC_CI_AS NOT NULL,---节点ID 主键 Guid
12     [ParentId] [varchar](40) COLLATE Chinese_PRC_CI_AS NULL,---父亲节点ID 0表示为根目录
13     [ContentText] [varchar](800) COLLATE Chinese_PRC_CI_AS NULL,---节点现实内容
14     [StrHref] [varchar](800) COLLATE Chinese_PRC_CI_AS NULL,---节点链接地址
15     [hrefTarget] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,---Target
16  CONSTRAINT [PK_Trees] PRIMARY KEY CLUSTERED 
17 (
18     [Tid] ASC
19 )WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
20 ) ON [PRIMARY]
21 
22 GO
23 SET ANSI_PADDING OFF
构建完数据表后,我们将开始应运程序的开发,首先页面的设计,html代码如下:
1 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Main.aspx.cs" Inherits="Com.KimiYang.Web.Main" %>
 2 
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 4 
 5 <html xmlns="http://www.w3.org/1999/xhtml">
 6 <head id="Head1" runat="server">
 7     <title>无标题页</title>
 8     <link href="css/css/StyleSheet.css" rel="stylesheet" type="text/css" />
 9     
10     <link href="Extjs3.2.0/resources/css/ext-all.css" rel="stylesheet" type="text/css" />
11     <link href="Extjs3.2.0/resources/css/xtheme-gray.css" rel="stylesheet" type="text/css" />
12     <script src="Extjs3.2.0/adapter/ext/ext-base.js" type="text/javascript"></script>
13     <script src="Extjs3.2.0/ext-all.js" type="text/javascript"></script>
14     <script src="Extjs3.2.0/src/locale/ext-lang-zh_CN.js" type="text/javascript"></script>
15 
16     <script src="JS/Main.js" type="text/javascript"></script>
17     <script src="JS/NowTime.js" type="text/javascript"></script>
18     <base target="_self" />
19 </head>
20 <body onload="getCurrentTime()">
21     <form id="form1" runat="server">
22      <div id="loading-mask" style=""></div>
23       <div id="loading">
24         <div class="loading-indicator"><img src="Extjs3.2.0/resources/images/vista/s.gif" width="32" height="32" style="margin-right:8px;" align="absmiddle"/>Loading...</div>
25       </div>
26   <div id="header"><h1>KimiYang</h1></div>
27   <div class="menu">
28                 <span style="float: left">欢迎  <b>admin  <span id="myTime"/></span></b>  
29                    </span>
30                 <span id="aLoginOut" runat="server" style="float: right"><a onclick="if (!window.confirm('您确认要注消当前登录用户吗?')){return false;}"
31                     href="#">注销</a></span>
32             </div>
33             <div id="north"></div>
34   <div id="west">
35     
36   </div>
37   <div id="center">
38     
39   </div>
40   <div id="west_content" style="height:300px; ">
41 
42   </div>
43     </form>
44 </body>
45 </html>
46 

js代码如下所示:

1 Ext.onReady(function(){
 2        Ext.BLANK_IMAGE_URL="Extjs3.2.0/resources/images/default/s.gif";
 3        var Tree = Ext.tree;
 4        var tree = new Tree.TreePanel({
 5             el:'west_content',//渲染到
 6             useArrows:true,
 7             autoHeight:true,
 8             split:true,
 9             lines:true,
10             autoScroll:true,
11             animate:true,
12             enableDD:true,
13             border:false,
14             containerScroll: true, 
15             loader: new Tree.TreeLoader({
16                 dataUrl:'ServletHandlers/GetTrees.ashx'
17                 })
18         });
19         var root = new Tree.AsyncTreeNode({
20             text: 'KimiYang',
21             draggable:true,
22             id:'0' 
23         });
24         tree.setRootNode(root);
25         tree.render();
26         root.expand();
27         
28        var viewport = new Ext.Viewport({
29             layout:'border',
30             items:[{
31                 region:'west',
32                 id:'west',
33                 title:'菜单导航',
34                 split:true,
35                  200,
36                 minSize: 200,
37                 maxSize: 400,
38                 collapsible: true,
39                 margins:'60 0 2 2',
40                 cmargins:'60 5 2 2',
41                 layout:'fit',
42                 layoutConfig:{ activeontop:true},
43                 defaults: { bodyStyle: 'margin:0;padding:0;'},
44                 items:
45                     new Ext.TabPanel({
46                         border:false,
47                         activeTab:0,
48                         tabPosition:'bottom',
49                         items:[{
50                                 contentEl:'west_content',
51                                 title:'系统管理',
52                                 autoScroll:true,
53                                 bodyStyle:'padding:5px;'
54                                },
55                                {
56                                 title:'网上办公',
57                                 autoScroll:true,
58                                 bodyStyle:'padding:5px;'
59                                }]
60                      })
61             },{
62                 region:'center',
63                 el:'center',
64                 deferredRender:false,
65                 margins:'60 0 2 0',
66                 html:'<iframe id="center-iframe" width="100%" height=100% name="main"  frameborder="0" scrolling="auto" style="border:0px none; background-color:#BBBBBB; "  ></iframe>',
67                 autoScroll:true 
68             },
69             {
70                 region:'south',
71                 margins:'0 0 0 2',
72                 border:false,
73                 html:'<div class="menu south">Copyright © 2009 浙江新昌 Kimi Yang All Rights Reserved</div>'
74                }
75             ]
76         });
77         
78         setTimeout(function(){
79         Ext.get('loading').remove();
80         Ext.get('loading-mask').fadeOut({remove:true});
81         }, 250)
82     });

C#代码如下图所示:

1 using System;
 2 using System.Collections;
 3 using System.Data;
 4 using System.Linq;
 5 using System.Web;
 6 using System.Web.Services;
 7 using System.Web.Services.Protocols;
 8 using System.Xml.Linq;
 9 
10 namespace Com.KimiYang.Web.ServletHandlers
11 {
12     /// <summary>
13     /// $codebehindclassname$ 的摘要说明
14     /// </summary>
15     [WebService(Namespace = "http://tempuri.org/")]
16     [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
17     public class GetTrees : IHttpHandler
18     {
19 
20         public void ProcessRequest(HttpContext context)
21         {
22             string strSql = "select Tid,ParentId,ContentText,StrHref,hrefTarget from Trees";
23             dbOperator db = new dbOperator();
24             DataTable dt = db.Execute(strSql);
25             string strResult = "[";
26             if (dt.Rows.Count > 0)
27             {
28                 DataRow[] dr = dt.Select("ParentId='0'");
29                 strResult = DtTreeToJson(dt, strResult, dr);
30             }
31             strResult += "]";
32             context.Response.ContentType = "text/plain";
33             context.Response.Write(strResult.ToString());
34             context.Response.End();
35         }
36 
37         private static string DtTreeToJson(DataTable dt, string strResult, DataRow[] dr)
38         {
39             if (dr.Length > 0)
40             {
41                 for (int i = 0; i < dr.Length; i++)
42                 {
43 
44                     strResult += "{";
45                     strResult += "text:'" + dr[i]["ContentText"] + "',";
46                     strResult += "id:'" + dr[i]["Tid"] + "',";
47                     DataRow[] drChild = dt.Select("ParentId='" + dr[i]["Tid"] + "'");
48                     if (drChild.Length > 0)
49                     {
50                         strResult += "leaf:false,";
51                         strResult += "children:[";
52                         strResult = DtTreeToJson(dt, strResult, drChild);
53                         strResult += "]";
54                     }
55                     else
56                     {
57                         strResult += "href:'" + dr[i]["StrHref"] + "',";
58                         strResult += "hrefTarget:'" + dr[i]["hrefTarget"] + "',";
59                         strResult += "leaf:true";
60                     }
61 
62                     strResult += "}";
63 
64                     if (i != dr.Length - 1)
65                         strResult += ",";
66                 }
67             }
68             return strResult;
69         }
70 
71         public bool IsReusable
72         {
73             get
74             {
75                 return false;
76             }
77         }
78     }
79 }
80 

页面效果图:

源代码下载ExtjsTree.rar

原文地址:https://www.cnblogs.com/Leo_wl/p/2041684.html