ASP.NET的常用技巧等

来源:互联网 发布:国际黄金价格数据 编辑:程序博客网 时间:2024/06/10 14:33
网络日志
.bvSection{display:none;}
2006/10/17

ASP.NET的常用技巧(转)

ASP.NET的常用技巧

Asp.Net细节性问题技巧精萃
1.Asp.Net中几种相似的标记符号: < %=...%>< %#... %>< % %>< %@ %>解释及用法

   答:  < %#... %>: 是在绑定控件DataBind()方法执行时被执行,用于数据绑定
          如: < %# Container.DataItem("tit") %>


        < %= %>: 在程序执行时被调用,可以显示后台变量值
          如:  
           *.aspx中: < %= aaa %>
           *.cs中:   protected string aaa="姓名";


        < % %>: 内联代码块里面可以在页面文件*.aspx或*.ascx文件里面嵌入后台代码
          如:
            < %
             for(int i=0;i<100;i++)
             {
                   Reaponse.Write(i.ToString());
             }
            %>


        < %@  %>是在*.aspx页面前台代码导入命名空间,
           如: 
            < %@ Import namespace="System.Data"%>


2.控件接收哪些类型数据?
      答:接收Bind的控件,一般有DropDownList,DataList,DataGrid,ListBox这些集合性质的控件,而被捆绑   的主要是ArrayList(数组),Hashtable(哈稀表),DataView(数据视图),DataReader这四个,以后我们就可以   对号入座,不会出现DataTable被捆绑的错误了:)

DropDownList------ArrayList(数组)
DataList-------Hashtable(哈稀表)
DataGrid-------DataView(数据视图)
ListBox-------DataView(数据视图)

 


3.DataBind,获得的数据,系统会将其默认为String,怎样转化为其它的类型?
  DataBinder.Eval(Container.DataItem,"转换的类型","格式")
  最后一个"格式"是可选的,一般不用去管他,Container.DataItem是捆绑的数据项,"转换类型"指的是    Integer,String,Boolean这一类东西.

4.主要命名空间:
  < % @ Import Namespace="System.Data" %>    处理数据时用到
  < % @ Import Namespace="System.Data.ADO" % >  使用ADO.net ; 时用到
  < % @ Import Namespace="System.Data.SQL" %>   SQL Server 数据库专用
  < % @ Import Namespace="System.Data.XML" %>   不用看处理XML用到
  < % @ Import Namespace="System.IO" %>   处理文件时用到
  < % @ Import Namespace="System.Web.Util" %>   发邮件时大家会用到
  < % @ Import Namespace="System.Text" %>    文本编码时用到

5.Connections(SQLConection 或者 ADOConnection)的常用属性和方法:
  | ConnectionString 取得或设置连结数据库的语句
  | ConnectionTimeout 取得或设置连结数据库的最长时间,也是就超时时间
  | DataBase 取得或设置在数据库服务器上要打开的数据库名
  | DataSource 取得或设置DSN,大家不会陌生吧:)
  | Password 取得或设置密码
  | UserID 取得或设置登陆名
  | State 取得目前联结的状态
  | Open() 打开联结
  | Close() 关闭联结
  | Clone() 克隆一个联结。(呵呵,绵羊可以Connection我也可以)
 示例:
     SQLConnection myConnection = new SQLConnection();
     myConnection.DataSource = "mySQLServer";
     myConnection.Password = "";
     myConnection.UserID = "sa";
     myConnection.ConnectionTimeout = 30;
     myConnection.Open();
     myConnection.Database = "northwind";
     myConnection.IsolationLevel = IsolationLevel.ReadCommitted
6.Command常用的方法和属性
   | ActiveConnection 取得或设置联结Connections
   | CommandText 执行的SQL语句或储存过程(StoredProcedure)名
   | CommandTimeout 执行的最长时间
   | CommandType Command操作的类型(StoredProcedure,Text,TableDirect)三种,默认Text
   | Parameters 操作储存过程时使用
   | Execute() 执行SQL语句或储存过程
   | ExecuteNonQuery() 同上,区别在于不返回记录集
   | Clone() 克隆Command
  示例:
     string mySelectQuery = "SELECT * FROM Categories ORDER BY CategoryID";
     stringmyConnectString="userid=sa;password=;database=northwind;server=mySQLServer";
     SQLCommand myCommand = new SQLCommand(mySelectQuery);
     myCommand.ActiveConnection = new SQLConnection(myConnectString);
     myCommand.CommandTimeout = 15;
     myCommand.CommandType = CommandType.Text;< /FONT >


7.打开和关闭数据库两种方法:
      1.MyConnection.Open();    //打开联结
        MyConnection.Close();
      2.MyCommand.ActiveConnection.Open();
        MyCommand.ActiveConnection.Close() 

8.使用DataSet,在数据库中增加、修改、删除一个数据
      a.添加数据
            DataRow dr=MyDataSet.Tables["UserList"].NewRow();
            dr["UserName"] = "周讯";
            dr["ReMark"] = "100";
            dr["Comment"] = "漂亮MM";
            MyDataSet.Tables.Rows.Add(dr);

      b.修改数据
            MyDataSet.Tables["UserList"].Rows[0]["UserName"]="飞刀大哥";

      c.删除数据
            MyDataSet.Tables["UserList"],Rows[0].Delete();

      d.恢复数据
            if(MyDataSet.HasErrors)
             {
               MyDataSet.RejectChanges();
             }
     
      e.探测DataSet是否有改动
            if(MyDataSet.HasChanges)
             {
                //保存代码
             }else{
                //因为没有变化,所以不用保存,以节省时间
             }

      f.更新数据库
            MyComm.Update(MyDataSet);   //更新数据库中所有的表
            MyComm.Update(MyDataSet,"UserList");  //更新某个表
9.DataGrid实现分页功能
     AllowPaging="True"   //是指允许分页,这个是最主要的。有了它,我们才能分页。
     PageSize="5"         //是指定每页显示的记录数,如果不写,就会默认为10条。
     PagerStyle-HorizontalAlign="Right"  //是指定分面显示的定位,默认是Left

     PagerStyle-NextPageText="下一页"    //把<>改为上一页和下一页字符串
     PagerStyle-PrevPageText="上一页"

     PagerStyle-Mode="NumericPages"       //把<>改为123数字显示
10.显示一共有多少页,并且报告当前为第几页
     当前页是:< %=DataGrid1.CurrentPageIndex+1%>

     总页数是:< %=DataGrid1.PageCount%>

11.个性化分页
     程序员大本营之"亲密接触ASP.Net(14)"有完整代码

12.要将页面重置为有效的状态
 IValidator val;
        foreach(val in Validators)
         {
            Val.IsValid = true;
         }
13.重新执行整个验证序列   
        IValidator val;
        foreach(val in Validators)
         {
            Val.Validate();
         }
14.禁用客户端验证
 < %@ Page Language="c#" clienttarget=downlevel %>
15.Repeater、DataList和DataGrid控件用途"
     这些控件可以简化几种常见的 Web 应用程序方案,包括报表、购物车、产品列表、查询
 结果和导航菜单。  Repeater是唯一允许在其模板中存在 HTML片段的控件.
16.Server.Execute("another.aspx")和Server.Transfer("another.aspx")区别:
       Execute是从当前页面转移到指定页面,并将执行返回到当前页面
 Transfer是将执行完全转移到指定页面
17.XML文件中可以自己存有架构,也可以存在于*.xsl文件中,但必须通过xmlns属性在xml文档的根节点中指定该信息,如下所示:
 
18.XML文件的读取
 FileStream myfs=new Filestream(Server.MapPath("xmldtagrid.xml"),FileMode.Open,FileAccess.Read);
 StreamReader myreader=new StreamReader(myfs);
 DataSet myds=new DataSet();
 myds.ReadXml(myreader);
19.正则表达式 控件RegularExpressionValidator
 符号   含义
 ^   指定检查开始处
 $   指定检查结束处
 []   检查输入的值是否与方括弧中的字符之一相匹配
 /W   允许输入任何值
 /d{}   "/d"指定输入的值是一个数字,{}表示已指定数据类型的出现次数
 +   表明一个或多个元素将被添加到正在检查的表达式
    示例:电子邮件格式(具有@号,且以.com/.net/.org/.edu结尾)
     validationexpression="^[/w-]+@[/w-]+/.(com|net|org|edu)$"
20.DataGrid控件中数据操作重要语句:
 属性:DataKeyField="userid"  //设userid为表的主键,无法将该字段的值更新到数据库,最好设表的主键为DataGrid的主键
 SqlCommand.Parameters["@userid"].Value=dg.DataKeys[(int)e.Item.ItemIndex]; //检索所要更新的行的主键(将当前选定的行的               主键值赋给命令的一个参)数
 SqlCommand.Parameters["@fname"].Value=((TextBox)e.Item.Cells[2].Controls[0]).Text; //为参数赋予已修改的行值
21.自定义控件:
 a.用户控件(ASP创建页面一样)
  (I).  创建页面,拖入控件,设置属性/方法.   < % @Control Language="C#" Debug="True" %>中的@Control指令来定义此页         将包含控件代码
  (II)  保存为*.ascx文件,如a.ascx.
  (III).使用: 头<%@Register Tagprefix="MyFirstControl" TagName="MyLbl" Src="a.axcs" %>
    //Tagprefix为控件的前缀,像ASP:TextBox中的ASP
    //TagName用于指定自定义控件的名称
    //Src指定控件文件源
      身体:   
 b.使用C#创建自定义控件
  (I). 创建纯代码文件,继承基类Control,并保存为*.cs,如a.cs.
  (II).将代码编译生成程序集: csc /t:library /r:System.dll,System.Web.Dll a.cs 
      //library告诉C#编译器生成程序集
      //  /r:System.dll System.Web.Dll告诉C#编译器引用指定的程序集
  (III).将生成dll文件放在bin目录中
  (IV).使用: < % @Register TagPrefix="Mine" Namespace="MyOwnControls" Assembly="a" %>
22.复合控件注意事项:
 public class MyCompositin:Control,INamingContainer   //INamingContainer:如果在页面上有多个此控件实例,则此结口可以给每         {}           //个实例有唯一标志

 this.EnsureChildControls();//表示将复合控件的子控件都呈现到页面上,此方法检查服务器控件是否包含子控件

 CreateChildControls
23.Button/LinkButton/ImageButton/HyperLink什么时候用?
         1.Button和ImageButton用于将数据传递回服务器.
         2.Hyperlink用于在页面之间导航
         3.LinkButton用于将数据保存到服务器或访问服务器上的数据
24.跟踪调试
     跟踪:
 1.页级别跟踪: 在页的开头包括如下的页指令< %@ Page Trace="True" TraceMode="SortByCategory/SortByTime" %>
  自定义消息:
        Trace.Write("这里为要显示的字符串");
        Trace.Warn("这里为要显示的字符串");   //与Trace.Write相同,只是字体为红色
                检查是否使用了跟踪
        例句: if(Trace.IsEnabled) { Trace.Warn("已启用跟踪")}  
 2.应用程序级别跟踪: 在Web.config文件的节中
25.设置缓存:
 1.输出缓存:
            I.页面设置: 将  < %@ OutputCache Duration="120" VaryByParam="none" %>  加在需要缓存页的开头 
                               注释:在请求该页的后两分钟之内,输出内容不变
     II.编程方式设置:
                   主要使用类System.Web.HttpCachePolicy类下的方法
         (1). Response.Cache.SetExpires(DateTime.Now.AddSeconds(120));  //在此方法中必须指定到期时间,如本语                                                                                       //句为两分钟
         (2). Response.Cache.SetExpires(DateTime.Now.AddSeconds(120));
                            Response.Cache.SetSlidingExpiration(true);  //"可调到期",主要用于那些开始访问量大,但随后访问                                                                              //量平衡的情况
                            功能:第一句设置缓存到期时间,第二行打开 sliding expiration(可调到期).
         2.数据缓存:
               (1).DataView mySource; (2).给mySource赋值;
               (3).Cache["myCache"]=mySource; (4).mySource=(DataView)Cache["myCache"]
26.部署: 直接复制到产品服务器即可 复制语句: XCOPY //XOPY只接受物理路径,不接受虚拟路径

26.自定义分页按钮

      1. 

           protected void ItemCreated(object sender, System.Web.UI.WebControls.DataGridItemEventArgs  e)
   {
          System.Web.UI.WebControls.ListItemType elemType = e.Item.ItemType;
          if (elemType == System.Web.UI.WebControls.ListItemType.Pager)
          {
                 TableCell pager = (TableCell) e.Item.Controls[0];
                 for (int i=0; i                 {
                            Object o = pager.Controls[i];
                            if (o is LinkButton)
                            {
                                    LinkButton h = (LinkButton) o;
                                    h.Text = " " + h.Text + " ";
                            }
                            else
                            {
                                      Label l = (Label) o;
                                      l.Text = String.Format("[第{0}页]", l.Text);
                             }
                   }
           }
    }

   2.  引用:zhangzs8896(小二)

    private void MyDataGrid_ItemCreated(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
     {
            ListItemType lit_item=e.Item.ItemType;
            TableCell tc_item=(TableCell)e.Item.Controls[0];
            if (lit_item==ListItemType.Pager)
            {
                   for (int i=0;i                   {
                          object obj_item=tc_item.Controls[i];
                   
                          if (obj_item is LinkButton)
                          {
                                    LinkButton lbn_item=(LinkButton)obj_item;
                                    lbn_item.Text=lbn_item.Text;
                                    lbn_item.Font.Size=10;
                                    lbn_item.ForeColor=Color.FromName("#666666");
                                    lbn_item.Attributes.Add ("onmouseover","currentcolor=this.style.color;this.style.color='#14AC05'");
                                    lbn_item.Attributes.Add("onmouseout","this.style.color=currentcolor");
                          }
                          else
                          {
                                    Label lbl_item=(Label)obj_item;
                                    lbl_item.ForeColor=Color.Blue;
                                    lbl_item.Font.Bold=true;
                                    lbl_item.Font.Underline=true;
                                    lbl_item.Text="" + lbl_item.Text + "";
                                    lbl_item.Font.Size=10;

                           }
                  }
              }

          }

固定链接
单击隐藏此项的固定链接。
http://zjhuan.spaces.live.com/blog/cns!7771FF7C39DE7784!287.entry
添加评论
单击隐藏此项的评论。
2006/10/13

http://hi.baidu.com/benyong/blog/item/7f79ea2400ffa2014c088dd4.html

固定链接
单击隐藏此项的固定链接。
http://zjhuan.spaces.live.com/blog/cns!7771FF7C39DE7784!286.entry
添加评论
单击隐藏此项的评论。
2006/10/9

Window.Open详解(转)

一、window.open()支持环境:
JavaScript1.0+/JScript1.0+/Nav2+/IE3+/Opera3+
二、基本语法:
window.open(pageURL,name,parameters)
其中:
pageURL 为子窗口路径
name 为子窗口句柄
parameters 为窗口参数(各参数用逗号分隔)
三、示例:
<SCRIPT>
<!--
window.open ('page.html','newwindow','height=100,width=400,top=0,left=0,toolbar=no,menubar=no,scrollbars=no, resizable=no,location=no, status=no')
//写成一行
-->
</SCRIPT>
  脚本运行后,page.html将在新窗体newwindow中打开,宽为100,高为400,距屏顶0象素,屏左0象素,无工具条,无菜单条,无滚动条,不可调整大小,无地址栏,无状态栏。请对照。
  上例中涉及的为常用的几个参数,除此以外还有很多其他参数,请见四。
四、各项参数
  其中yes/no也可使用1/0;pixel value为具体的数值,单位象素。
参数 | 取值范围 | 说明
alwaysLowered | yes/no | 指定窗口隐藏在所有窗口之后
alwaysRaised | yes/no | 指定窗口悬浮在所有窗口之上
depended | yes/no | 是否和父窗口同时关闭
directories | yes/no | Nav2和3的目录栏是否可见
height | pixel value | 窗口高度
hotkeys | yes/no | 在没菜单栏的窗口中设安全退出热键
innerHeight | pixel value | 窗口中文档的像素高度
innerWidth | pixel value | 窗口中文档的像素宽度
location | yes/no | 位置栏是否可见
menubar | yes/no | 菜单栏是否可见
outerHeight | pixel value | 设定窗口(包括装饰边框)的像素高度
outerWidth | pixel value | 设定窗口(包括装饰边框)的像素宽度
resizable | yes/no | 窗口大小是否可调整
screenX | pixel value | 窗口距屏幕左边界的像素长度
screenY | pixel value | 窗口距屏幕上边界的像素长度
scrollbars | yes/no | 窗口是否可有滚动栏
titlebar | yes/no | 窗口题目栏是否可见
toolbar | yes/no | 窗口工具栏是否可见
Width | pixel value | 窗口的像素宽度
z-look | yes/no | 窗口被激活后是否浮在其它窗口之上
=====================================================
【1、最基本的弹出窗口代码】
  其实代码非常简单:
<SCRIPT LANGUAGE="javascript">
<!--
window.open ('page.html')
-->
</SCRIPT>
  因为着是一段javascripts代码,所以它们应该放在<SCRIPT LANGUAGE="javascript">标签和</script>之间。<!-- 和 -->是对一些版本低的浏览器起作用,在这些老浏览器中不会将标签中的代码作为文本显示出来。要养成这个好习惯啊。
  Window.open ('page.html') 用于控制弹出新的窗口page.html,如果page.html不与主窗口在同一路径下,前面应写明路径,绝对路径(http://)和相对路径(../)均可。用单引号和双引号都可以,只是不要混用。
  这一段代码可以加入HTML的任意位置,<head>和</head>之间可以,<body>间</body>也可以,越前越早执行,尤其是页面代码长,又想使页面早点弹出就尽量往前放。
【2、经过设置后的弹出窗口】
  下面再说一说弹出窗口的设置。只要再往上面的代码中加一点东西就可以了。
  我们来定制这个弹出的窗口的外观,尺寸大小,弹出的位置以适应该页面的具体情况。
<SCRIPT LANGUAGE="javascript">
<!--
window.open ('page.html', 'newwindow', 'height=100, width=400, top=0,left=0, toolbar=no, menubar=no, scrollbars=no, resizable=no,location=no, status=no')
//写成一行
-->
</SCRIPT>
参数解释:
<SCRIPT LANGUAGE="javascript"> js脚本开始;
window.open 弹出新窗口的命令;
'page.html' 弹出窗口的文件名;
'newwindow' 弹出窗口的名字(不是文件名),非必须,可用空''代替;
height=100 窗口高度;
width=400 窗口宽度;
top=0 窗口距离屏幕上方的象素值;
left=0 窗口距离屏幕左侧的象素值;
toolbar=no 是否显示工具栏,yes为显示;
menubar,scrollbars 表示菜单栏和滚动栏。
Resizable=no 是否允许改变窗口大小,yes为允许;
location=no 是否显示地址栏,yes为允许;
status=no 是否显示状态栏内的信息(通常是文件已经打开),yes为允许;
</SCRIPT> js脚本结束
【3、用函数控制弹出窗口】
  下面是一个完整的代码。
<html>
<head>
<script LANGUAGE="JavaScript">
<!--
function openwin() { window.open ("page.html", "newwindow", "height=100, width=400, toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, status=no")
//写成一行
}
//-->
</script>
</head>
<body onload="openwin()">
…任意的页面内容…
</body>
</html>
这里定义了一个函数openwin(),函数内容就是打开一个窗口。在调用它之前没有任何用途。
怎么调用呢?
方法一:<body onload="openwin()"> 浏览器读页面时弹出窗口;
方法二:<body onunload="openwin()"> 浏览器离开页面时弹出窗口;
方法三:用一个连接调用:
<a href="#" onclick="openwin()">打开一个窗口</a>
注意:使用的"#"是虚连接。
方法四:用一个按钮调用:
<input type="button" onclick="openwin()" value="打开窗口">
【4、同时弹出2个窗口】
  对源代码稍微改动一下:
<script LANGUAGE="JavaScript">
<!--
function openwin()
{ window.open ("page.html", "newwindow", "height=100, width=100, top=0,left=0,toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, status=no")
//写成一行
window.open ("page2.html", "newwindow2", "height=100, width=100, top=100, left=100,toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, status=no")
//写成一行
}
//-->
</script>
  为避免弹出的2个窗口覆盖,用top和left控制一下弹出的位置不要相互覆盖即可。最后用上面说过的四种方法调用即可。
注意:2个窗口的name(newwindows和newwindow2)不要相同,或者干脆全部为空。OK?
【5、主窗口打开文件1.htm,同时弹出小窗口page.html】
  如下代码加入主窗口<head>区:
<script language="javascript">
<!--
function openwin()
{window.open("page.html","","width=200,height=200")
}
//-->
</script>
  加入<body>区:
<a href="1.htm" onclick="openwin()">open</a>即可。
【6、弹出的窗口之定时关闭控制】
  下面我们再对弹出的窗口进行一些控制,效果就更好了。如果我们再将一小段代码加入弹出的页面(注意是加入到page.html的HTML中,可不是主页面中,否则…),让它10秒后自动关闭是不是更酷了?
  首先,将如下代码加入page.html文件的<head>区:
<script language="JavaScript">
function closeit()
{setTimeout("self.close()",10000) //毫秒}
</script>
  然后,再用<body onload="closeit()"> 这一句话代替page.html中原有的<BODY>这一句就可以了。(这一句话千万不要忘记写啊!这一句的作用是调用关闭窗口的代码,10秒钟后就自行关闭该窗口。)
【7、在弹出窗口中加上一个关闭按钮】
<FORM>
<INPUT TYPE='BUTTON' VALUE='关闭' onClick='window.close()'>
</FORM>
  呵呵,现在更加完美了!
【8、内包含的弹出窗口-一个页面两个窗口】
  上面的例子都包含两个窗口,一个是主窗口,另一个是弹出的小窗口。
  通过下面的例子,你可以在一个页面内完成上面的效果。
<html>
<head>
<SCRIPT LANGUAGE="JavaScript">
function openwin()
{OpenWindow=window.open("", "newwin", "height=250, width=250,toolbar=no,scrollbars="+scroll+",menubar=no");
//写成一行
OpenWindow.document.write("<TITLE>例子</TITLE>")
OpenWindow.document.write("<BODY BGCOLOR=#ffffff>")
OpenWindow.document.write("<h1>Hello!</h1>")
OpenWindow.document.write("New window opened!")
OpenWindow.document.write("</BODY>")
OpenWindow.document.write("</HTML>")
OpenWindow.document.close()}
</SCRIPT>
</head>
<body>
<a href="#" onclick="openwin()">打开一个窗口</a>
<input type="button" onclick="openwin()" value="打开窗口">
</body>
</html>
  看看 OpenWindow.document.write()里面的代码不就是标准的HTML吗?只要按照格式写更多的行即可。千万注意多一个标签或少一个标签就会出现错误。记得用OpenWindow.document.close()结束啊。
【9、终极应用--弹出的窗口之Cookie控制】
  回想一下,上面的弹出窗口虽然酷,但是有一点小毛病(沉浸在喜悦之中,一定没有发现吧?)比如你将上面的脚本放在一个需要频繁经过的页面里(例如首页),那么每次刷新这个页面,窗口都会弹出一次,是不是非常烦人?:-(有解决的办法吗?Yes! ;-) Follow me.
  我们使用cookie来控制一下就可以了。
  首先,将如下代码加入主页面HTML的<HEAD>区:
<script>
function openwin()
{window.open("page.html","","width=200,height=200")}
function get_cookie(Name)
{var search = Name + "="
var returnvalue = "";
if (document.cookie.length > 0) {
offset = document.cookie.indexOf(search)
if (offset != -1) {
offset += search.length
end = document.cookie.indexOf(";", offset);
if (end == -1)
end = document.cookie.length;
returnvalue=unescape(document.cookie.substring(offset,end))
}
}
return returnvalue;
}
function loadpopup(){
if (get_cookie('popped')==''){
openwin()
document.cookie="popped=yes"
}
}
</script>
  然后,用<body onload="loadpopup()">(注意不是openwin而是loadpop啊!)替换主页面中原有的<BODY>这一句即可。你可以试着刷新一下这个页面或重新进入该页面,窗口再也不会弹出了。真正的Pop-Only-Once!
  写到这里弹出窗口的制作和应用技巧基本上算是完成了,俺也累坏了,一口气说了这么多,希望对正在制作网页的朋友有所帮助俺就非常欣慰了。
  需要注意的是,JS脚本中的的大小写最好前后保持一致。
固定链接
单击隐藏此项的固定链接。
http://zjhuan.spaces.live.com/blog/cns!7771FF7C39DE7784!285.entry
添加评论
单击隐藏此项的评论。
2006/10/8

http://submaie.cnblogs.com/archive/2006/02/07/326538.html

http://submaie.cnblogs.com/archive/2006/02/07/326538.html
固定链接
单击隐藏此项的固定链接。
http://zjhuan.spaces.live.com/blog/cns!7771FF7C39DE7784!284.entry
添加评论
单击隐藏此项的评论。
2006/9/17

视频链接

http://www.aspxboy.com/private/showthread.asp?threadid=659
http://community.csdn.net/Expert/topic/4886/4886791.xml?temp=.5477564
固定链接
单击隐藏此项的固定链接。
http://zjhuan.spaces.live.com/blog/cns!7771FF7C39DE7784!283.entry
添加评论
单击隐藏此项的评论。
2006/9/10

滚动条样式

滚动条样式
BODY {
SCROLLBAR-FACE-COLOR: #dff4fd;
SCROLLBAR-HIGHLIGHT-COLOR: #ffffff;
SCROLLBAR-SHADOW-COLOR: #ffffff;
SCROLLBAR-3DLIGHT-COLOR: #a8cbf1;
SCROLLBAR-ARROW-COLOR: #a8cbf1;
SCROLLBAR-TRACK-COLOR: #ffffff;
SCROLLBAR-DARKSHADOW-COLOR: #a8cbf1;
SCROLLBAR-BASE-COLOR: #a8cbf1
}



SCROLLBAR-ARROW-COLOR:三角的颜色
SCROLLBAR-SHADOW-COLOR:右边的颜色
SCROLLBAR-HIGHLIGHT-COLOR:左边的颜色
SCROLLBAR-FACE-COLOR:可拖动区域的背景色
SCROLLBAR-TRACK-COLOR:不能动的颜色
scrollbar-3dlight-color:color;设置或检索滚动条亮边框颜色;
scrollbar-highlight-color:color;设置或检索滚动条3D界面的亮边颜色;
scrollbar-face-color:color;设置或检索滚动条3D表面的颜色;
scrollbar-arrow-color:color;设置或检索滚动条方向箭头的颜色;当滚动条出现但不可用时,此属性失效;
scrollbar-shadow-color:color;设置或检索滚动条3D界面的暗边颜色;
scrollbar-darkshadow-color:color;设置或检索滚动条暗边框颜色;
scrollbar-base-color:color;设置或检索滚动条基准颜色。其它界面颜色将据此自动调整。
scrollbar-track-color:color;设置或检索滚动条的拖动区域颜色

固定链接
单击隐藏此项的固定链接。
http://zjhuan.spaces.live.com/blog/cns!7771FF7C39DE7784!279.entry
添加评论
单击隐藏此项的评论。
2006/9/2

Asp.NET中常用的一些性能优化方法,性能优化(抄)

ASP.NET 的缓存机制相比ASP有很大的改进,本文档除对常用优化方法进行总结介绍外,强调了如何使用ASP.NET的缓存来获得最佳性能。

1:不要使用不必要的session
和ASP中一样,在不必要的时候不要使用Session。

可以针对整个应用程序或者页面禁用会话状态:

l 禁用页面的会话状态


l 禁用应用程序的会话状态

在应用程序的Web.Config文件的sessionstate配置节中,将mode属性设置为off。

即:。



2:不使用不必要的Server Control
ASP.net中,大量的服务器端控件方便了程序开发,但也可能带来性能的损失,因为用户每操作一次服务器端控件,就产生一次与服务器端的往返过程。因此,非必要,应当少使用Server Control。



3:不使用不必要的ViewState
默认情况下,ASP.Net对所有的Server Control都启用了ViewState(视图状态)。但ViewState需要在客户端保存一些信息,这会造成性能的消耗。当必须使用Server Control时,可以考虑禁止ViewState。

有两种方式禁止ViewState:针对整个页面或者单个控件禁用ViewState。

l 针对控件


l 针对页面


4:不要用Exception控制程序流程
有些程序员可能会使用异常来实现一些流程控制。例如:



try{

result=100/num;

}

Catch(Exception e)

{

result=0;

}

但实际上,Exception是非常消耗系统性能的。除非必要,不应当使用异常控制来实现程序流程。

上面的代码应当写为:



if(num!=0)

result=100/num;

else

result=0;

5:禁用VB和Jscript动态数据类型
应当始终显示地申明变量数据类型,这能够节约程序的执行时间。为此,可以在页面前面写明:

6:使用存储过程完成数据访问
7:只读数据访问不要使用DataSet。
DataSet作为一个功能强大的、支持离线的数据库,其对性能的开销也相对较大。在特定的场合可以使用.Net中的其它数据集作为替代。

n 使用SqlDataReader代替DataSet;

n SqlDataReader是read-only,forward-only。

8:关闭ASP.NET的Debug模式
为了方便开发调试,VS.net中对于Debug模式默认是开启的,在部署应用程序时,应该关闭Debug模式,这将有效提高应用程序性能。

9:使用ASP.Net Output Cache缓冲数据;
提供缓冲功能是ASP.net中非常强大的一种功能。曾看到过某些评测说:ASP.net程序的性能比SUN的JSP应用程序性能快上几倍,实际上,该评测程序非常重要的一点就是使用了很多ASP.net的缓冲功能。

ASP.net中常用的缓冲方式有:

n 页面缓冲

一个例子:查询北京市的天气。因为天气数据在一定的时间内是相对规定的。

当Web程序中第一次查询北京市的天气时,应用程序可能是调用一个远程的WebService获取天气信息。而其后的用户就可以从缓冲中得到当前的天气信息。这将大大提高性能,减少服务器的压力。

方式:

u :指明页面使用缓冲

u Duration:控制缓冲有效的时间,单位为分钟。

u VaryByParam:用于指明是否缓冲的判断依据。例如,如果第一个用户查询的是北京的天气,则缓冲中存储了北京市的天气。当第二个用户查询上海的天气时,为避免读取到错误的缓冲,可以用这样的代码缓冲多个城市的天气:


这就指明了根据页面URL中的cityName参数来缓冲多份数据。

n 片断缓冲

在ASP.net中,除了在页面范围内使用缓冲,也还可以针对User Control使用Output Cache参数实现对用户控件的缓冲。同样的,一个页面中相同类型的控件也可以有多个不同的缓冲。可以根据参数来实现不同的缓冲。

例如:对于控件可以根据Control 的C属性的不同实现不同的缓冲。



n 数据缓冲



n 缓冲的过期依赖条件

某种意义上,Cache和Application是一样的,都是一种公有的对象。为了取得缓冲与数据有效性之间的平衡,可以根据需要对缓冲过期策略进行合理的设置。

u 文件依赖

Cache.Insert (“Mydata”, Source

, New CacheDependency(Server.MapPath(“authors.xml”)))

此代码的含义是当authors.xml文件不发生变化的时候,缓冲MyData始终有效。



u 时间依赖

设定1小时后过期,这是一种绝对过期。

Cache.Insert(“Mydata”,Source,null

,DateTime.Now.AddHours(1),TimeSpan.Zero);



u 相对过期依赖

当DataSet不再发生变化20分钟以后,缓冲过期。

Cache.Insert(“MyData”,Source,null

,DateTime.MaxValue,TimeSpan.FromMinutes(20));

固定链接
单击隐藏此项的固定链接。
http://zjhuan.spaces.live.com/blog/cns!7771FF7C39DE7784!278.entry
添加评论
单击隐藏此项的评论。
2006/9/1

ifram调整高度

<SCRIPT LANGUAGE="JavaScript">

function f_frameStyleResize(targObj){

var targWin = targObj.parent.document.all[targObj.name];

if(targWin != null) {

var HeightValue = targObj.document.body.scrollHeight

if(HeightValue < 600){HeightValue = 600} file://不小于600

targWin.style.pixelHeight = HeightValue;

}

}

function f_iframeResize(){

bLoadComplete = true; f_frameStyleResize(self);

}

var bLoadComplete = false;

window.onload = f_iframeResize;

</SCRIPT>

  注意:iframe必须要有name属性,否则无效。

固定链接
单击隐藏此项的固定链接。
http://zjhuan.spaces.live.com/blog/cns!7771FF7C39DE7784!277.entry
添加评论
单击隐藏此项的评论。
2006/7/14

IE页面控制

禁止右键弹出:
1,<script>  
  function   click(e)   {  
  if(document.all)   {  
  if(event.button==2)   {  
  alert();  
  }  
  }  
   
  }  
   
  document.onmousedown   =   click;  
  </script>  
  <body   >  
  </body>  
   
  2,用document的onconttextmenu(document的右键菜单)  
  <body   oncontextmenu="return   false;">  
  </body>
去除IE的菜单、按钮
open方法中有各种属性可以去掉ie的菜单和toolsbar、地址栏、statusbar等
  var   sFeatures   =   "menubar=no,toolbar=no,location=no,status=no"  
  window.open("new.asp",   null,   sFeatures)
固定链接
单击隐藏此项的固定链接。
http://zjhuan.spaces.live.com/blog/cns!7771FF7C39DE7784!273.entry
添加评论
单击隐藏此项的评论。
2006/7/4

[转载]Meta标签详解

  引言

  您的个人网站即使做得再精彩,在“浩瀚如海”的网络空间中,也如一叶扁舟不易为人发现,如何推广
个人网站,人们首先想到的方法无外乎以下几种:
  
  ● 在搜索引擎中登录自己的个人网站
  
  ● 在知名网站加入你个人网站的链接


  ● 在论坛中发帖子宣传你的个人网站


  很多人却忽视了HTML标签META的强大功效,一个好的META标签设计可以大大提高你的个人网站被搜索到的可能性,有兴趣吗,谁我来重新认识一下META标签吧!


  META标签是HTML语言HEAD区的一个辅助性标签,它位于HTML文档头部的<HEAD>标记和<TITLE>标记之间,它提供用户不可见的信息。meta标签通常用来为搜索引擎robots定义页面主题,或者是定义用户浏览器上的cookie;它可以用于鉴别作者,设定页面格式,标注内容提要和关键字;还可以设置页面使其可以根据你定义的时间间隔刷新自己,以及设置RASC内容等级,等等。

 

  详细介绍


  下面介绍一些有关 标记的例子及解释。


  META标签分两大部分:HTTP标题信息(HTTP-EQUIV)和页面描述信息(NAME)。

 

  ★HTTP-EQUIV


  HTTP-EQUIV类似于HTTP的头部协议,它回应给浏览器一些有用的信息,以帮助正确和精确地显示网页内容。常用的HTTP-EQUIV类型有:

 

  1、Content-Type和Content-Language (显示字符集的设定)


  说明:设定页面使用的字符集,用以说明主页制作所使用的文字已经语言,浏览器会根据此来调用相应的字符集显示page内容。


  用法:<Meta http-equiv="Content-Type" Content="text/html; Charset=gb2312">
      <Meta http-equiv="Content-Language" Content="zh-CN">


  注意: 该META标签定义了HTML页面所使用的字符集为GB2132,就是国标汉字码。如果将其中的“charset=GB2312”替换成“BIG5”,则该页面所用的字符集就是繁体中文Big5码。当你浏览一些国外的站点时,IE浏览器会提示你要正确显示该页面需要下载xx语支持。这个功能就是通过读取HTML页面META标签的Content-Type属性而得知需要使用哪种字符集显示该页面的。如果系统里没有装相应的字符集,则IE就提示下载。其他的语言也对应不同的charset,比如日文的字符集是“iso-2022-jp ”,韩文的是“ks_c_5601”。
      
  Content-Type的Content还可以是:text/xml等文档类型;
  Charset选项:ISO-8859-1(英文)、BIG5、UTF-8、SHIFT-Jis、Euc、Koi8-2、us-ascii, x-mac-roman, iso-8859-2, x-mac-ce, iso-2022-jp, x-sjis, x-euc-jp,euc-kr, iso-2022-kr, gb2312, gb_2312-80, x-euc-tw, x-cns11643-1,x-cns11643-2等字符集;Content-Language的Content还可以是:EN、FR等语言代码。


  2、Refresh (刷新)


   说明:让网页多长时间(秒)刷新自己,或在多长时间后让网页自动链接到其它网页。
   用法:<Meta http-equiv="Refresh" Content="30">
      <Meta http-equiv="Refresh" Content="5; Url=http://www.xia8.net">
   注意:其中的5是指停留5秒钟后自动刷新到URL网址。


  3、Expires (期限)


   说明:指定网页在缓存中的过期时间,一旦网页过期,必须到服务器上重新调阅。
   用法:<Meta http-equiv="Expires" Content="0">
      <Meta http-equiv="Expires" Content="Wed, 26 Feb 1997 08:21:57 GMT">
   注意:必须使用GMT的时间格式,或直接设为0(数字表示多少时间后过期)。


  4、Pragma (cach模式)


   说明:禁止浏览器从本地机的缓存中调阅页面内容。
   用法:<Meta http-equiv="Pragma" Content="No-cach">
   注意:网页不保存在缓存中,每次访问都刷新页面。这样设定,访问者将无法脱机浏览。


  5、Set-Cookie (cookie设定)


  说明:浏览器访问某个页面时会将它存在缓存中,下次再次访问时就可从缓存中读取,以提高速度。当你希望访问者每次都刷新你广告的图标,或每次都刷新你的计数器,就要禁用缓存了。通常HTML文件没有必要禁用缓存,对于ASP等页面,就可以使用禁用缓存,因为每次看到的页面都是在服务器动态生成的,缓存就失去意义。如果网页过期,那么存盘的cookie将被删除。
   用法:<Meta http-equiv="Set-Cookie" Content="cookievalue=xxx; expires=Wednesday,
       21-Oct-98 16:14:21 GMT; path=/">
   注意:必须使用GMT的时间格式。


  6、Window-target (显示窗口的设定)


   说明:强制页面在当前窗口以独立页面显示。
   用法:<Meta http-equiv="Widow-target" Content="_top">
   注意:这个属性是用来防止别人在框架里调用你的页面。Content选项:_blank、_top、_self、_parent。


  7、Pics-label (网页RSAC等级评定)
   说明:在IE的Internet选项中有一项内容设置,可以防止浏览一些受限制的网站,而网站的限制级
      别就是通过该参数来设置的。
   用法:<META http-equiv="Pics-label" Contect=
               "(PICS-1.1'http://www.rsac.org/ratingsv01.html'
       I gen comment 'RSACi North America Sever' by 'inet@microsoft.com'
       for 'http://www.microsoft.com' on '1997.06.30T14:21-0500' r(n0 s0 v0 l0))">


   注意:不要将级别设置的太高。RSAC的评估系统提供了一种用来评价Web站点内容的标准。用户可以设置Microsoft Internet Explorer(IE3.0以上)来排除包含有色情和暴力内容的站点。上面这个例子中的HTML取自Microsoft的主页。代码中的(n 0 s 0 v 0 l 0)表示该站点不包含不健康内容。级别的评定是由RSAC,即美国娱乐委员会的评级机构评定的,如果你想进一步了解RSAC评估系统的等级内容,或者你需要评价自己的网站,可以访问RSAC的站点:http://www.rsac.org/


  8、Page-Enter、Page-Exit (进入与退出)


   说明:这个是页面被载入和调出时的一些特效。
   用法:<Meta http-equiv="Page-Enter" Content="blendTrans(Duration=0.5)">
      <Meta http-equiv="Page-Exit" Content="blendTrans(Duration=0.5)">
   注意:blendTrans是动态滤镜的一种,产生渐隐效果。另一种动态滤镜RevealTrans也可以用于页面进入与退出效果:


      <Meta http-equiv="Page-Enter" Content="revealTrans(duration=x, transition=y)">
      <Meta http-equiv="Page-Exit" Content="revealTrans(duration=x, transition=y)">


       Duration  表示滤镜特效的持续时间(单位:秒)
       Transition 滤镜类型。表示使用哪种特效,取值为0-23。


       0 矩形缩小
       1 矩形扩大
       2 圆形缩小
       3 圆形扩大
       4 下到上刷新
       5 上到下刷新
       6 左到右刷新
       7 右到左刷新
       8 竖百叶窗
       9 横百叶窗
       10 错位横百叶窗
       11 错位竖百叶窗
       12 点扩散
       13 左右到中间刷新
       14 中间到左右刷新
       15 中间到上下
       16 上下到中间
       17 右下到左上
       18 右上到左下
       19 左上到右下
       20 左下到右上
       21 横条
       22 竖条
       23 以上22种随机选择一种


  9、MSThemeCompatible (XP主题)
   说明:是否在IE中关闭 xp 的主题
   用法:<Meta http-equiv="MSThemeCompatible" Content="Yes">
   注意:关闭 xp 的蓝色立体按钮系统显示样式,从而和win2k 很象。


  10、IE6 (页面生成器)
   说明:页面生成器generator,是ie6
   用法:<Meta http-equiv="IE6" Content="Generator">
   注意:用什么东西做的,类似商品出厂厂商。


  11、Content-Script-Type (脚本相关)
   说明:这是近来W3C的规范,指明页面中脚本的类型。
   用法:<Meta http-equiv="Content-Script-Type" Content="text/javascript">
   注意:


  ★NAME变量


  name是描述网页的,对应于Content(网页内容),以便于搜索引擎机器人查找、分类(目前几乎所有的搜索引擎都使用网上机器人自动查找meta值来给网页分类)。
  name的value值(name="")指定所提供信息的类型。有些值是已经定义好的。例如description(说明)、keyword(关键字)、refresh(刷新)等。还可以指定其他任意值,如:creationdate(创建日期) 、
document ID(文档编号)和level(等级)等。
  name的content指定实际内容。如:如果指定level(等级)为value(值),则Content可能是beginner(初级)、intermediate(中级)、advanced(高级)。

 

  1、Keywords (关键字)
   说明:为搜索引擎提供的关键字列表
   用法:<Meta name="Keywords" Content="关键词1,关键词2,关键词3,关键词4,……">
   注意:各关键词间用英文逗号“,”隔开。META的通常用处是指定搜索引擎用来提高搜索质量的关键词。当数个META元素提供文档语言从属信息时,搜索引擎会使用lang特性来过滤并通过用户的语言优先参照来显示搜索结果。例如:
      <Meta name="Kyewords" Lang="EN" Content="vacation,greece,sunshine">
      <Meta name="Kyewords" Lang="FR" Content="vacances,grè:ce,soleil">


  2、Description (简介)
   说明:Description用来告诉搜索引擎你的网站主要内容。
   用法:<Meta name="Description" Content="你网页的简述">
   注意:


  3、Robots (机器人向导)
   说明:Robots用来告诉搜索机器人哪些页面需要索引,哪些页面不需要索引。Content的参数有all、none、index、noindex、follow、nofollow。默认是all。
   用法:<Meta name="Robots" Content="All|None|Index|Noindex|Follow|Nofollow">
   注意:许多搜索引擎都通过放出robot/spider搜索来登录网站,这些robot/spider就要用到meta元素的一些特性来决定怎样登录。


    all:文件将被检索,且页面上的链接可以被查询;
    none:文件将不被检索,且页面上的链接不可以被查询;(和 "noindex, no follow" 起相同作用)
    index:文件将被检索;(让robot/spider登录)
    follow:页面上的链接可以被查询;
    noindex:文件将不被检索,但页面上的链接可以被查询;(不让robot/spider登录)
   nofollow:文件将不被检索,页面上的链接可以被查询。(不让robot/spider顺着此页的连接往下探找)


  4、Author (作者)
   说明:标注网页的作者或制作组
   用法:<Meta name="Author" Content="张三,abc@sina.com">
   注意:Content可以是:你或你的制作组的名字,或Email


  5、Copyright (版权)
   说明:标注版权
   用法:<Meta name="Copyright" Content="本页版权归Zerospace所有。All Rights Reserved">
   注意:


  6、Generator (编辑器)
   说明:编辑器的说明
   用法:<Meta name="Generator" Content="PCDATA|FrontPage|">
   注意:Content="你所用编辑器"


  7、revisit-after (重访)
   说明:
   用法:<META name="revisit-after" CONTENT="7 days" >
   注意:


  ★Head中的其它一些用法

 

  1、scheme (方案)
   说明:scheme can be used when name is used to specify how the value of content should
      be interpreted.
   用法:<meta scheme="ISBN" name="identifier" content="0-14-043205-1" />
   注意:


  2、Link (链接)
   说明:链接到文件
   用法:<Link href="soim.ico" rel="Shortcut Icon">
   注意:很多网站如果你把她保存在收件夹中后,会发现它连带着一个小图标,如果再次点击进入之后还会发现地址栏中也有个小图标。现在只要在你的页头加上这段话,就能轻松实现这一功能。<LINK> 用来将目前文件与其它 URL 作连结,但不会有连结按钮,用於 <HEAD> 标记间, 格式如下:
       <link href="URL" rel="relationship">
       <link href="URL" rev="relationship">


  3、Base (基链接)
   说明:插入网页基链接属性
   用法:<Base href="http://www.xia8.net/" target="_blank">
   注意:你网页上的所有相对路径在链接时都将在前面加上“http://www.cn8cn.com/”。其中target="_blank"是链接文件在新的窗口中打开,你可以做其他设置。将“_blank”改为“_parent”是链接文件将在当前窗口的父级窗口中打开;改为“_self”链接文件在当前窗口(帧)中打开;改为“_top”链接文件全屏显示。

 

  以上是META标签的一些基本用法,其中最重要的就是:Keywords和Description的设定。为什么呢?道理很简单,这两个语句可以让搜索引擎能准确的发现你,吸引更多的人访问你的站点!根据现在流行搜索引擎(Google,Lycos,AltaVista等)的工作原理,搜索引擎先派机器人自动在WWW上搜索,当发现新的网站时,便于检索页面中的Keywords和Description,并将其加入到自己的数据库,然后再根据关键词的密度将网站排序。


  由此看来,我们必须记住添加Keywords和Description的META标签,并尽可能写好关键字和简介。否则,
后果就会是:
  
  ● 如果你的页面中根本没有Keywords和Description的META标签,那么机器人是无法将你的站点加入数
    据库,网友也就不可能搜索到你的站点。


  ● 如果你的关键字选的不好,关键字的密度不高,被排列在几十甚至几百万个站点的后面被点击的可
    能性也是非常小的。


  写好Keywords(关键字)要注意以下几点:

 

  ● 不要用常见词汇。例如www、homepage、net、web等。


  ● 不要用形容词,副词。例如最好的,最大的等。


  ● 不要用笼统的词汇,要尽量精确。例如“爱立信手机”,改用“T28SC”会更好。

 

  “三人之行,必有我师”,寻找合适关键词的技巧是:到Google、Lycos、Alta等著名搜索引擎,搜索与
你的网站内容相仿的网站,查看排名前十位的网站的META关键字,将它们用在你的网站上,效果可想而知了。


  ★小窍门


  为了提高搜索点击率,这里还有一些“捷径”可以帮得到你:


  ● 为了增加关键词的密度,将关键字隐藏在页面里(将文字颜色定义成与背景颜色一样)。


  ● 在图像的ALT注释语句中加入关键字。如:<IMG SRC="xxx.gif" Alt="Keywords">


  ● 利用HTML的注释语句,在页面代码里加入大量关键字。用法: <!-- 这里插入关键字 -->

 

<head>  <title>文件头,显示在浏览器标题区</title>  <meta http-equiv="Content-Language" content="zh-cn">  <meta http-equiv="Content-Type" content="text/html; charset=gb2312">  <meta name="GENERATOR" content="Microsoft FrontPage 4.0">  <meta name="ProgId" content="FrontPage.Editor.Document">  <meta name="制作人" content="唐蓉生">  <meta name="主题词" content="HTML 网页制作 课件"></head>

固定链接
单击隐藏此项的固定链接。
http://zjhuan.spaces.live.com/blog/cns!7771FF7C39DE7784!272.entry
添加评论
单击隐藏此项的评论。
2006/6/30

.net Framework 是什么?

 Framework一个语言开发软件 ,是对.net技术的统称,可以分为四层来理解:应用程序(例如ASP.NET)、框架类库(FCL)、基类库(BCL)和最下面的CLR。
Microsoft® .NET Framework 1.1 版可再发行组件包.

NET Framework通过COM Interop(COM互操作)技术支持COM+和MTS。一个传统的COM应用程序能够调用一个.NET组件,同时.NET组件(在.NET中称为.NET Assembly)也能够调用一个COM组件。这一非常强大的双向互操作特性使你可以在应用程序中混合使用两类技术。

NET Framework 是微软的几个开发团队一起努力发展的成果,最主要用来产生一个可以用来快速开发、部署网站服务及应用程序的开发平台。这个架构是两个项目的结果:第一个项目的目的是用来改善Windows 作业平台上的程序开发,特别是改善COM(Component Object Model,组件对象模块。一种微软所制定的软件技术;让对象的功能可以被其它软件所叫用,可以让组件重复使用、容易更新及维护);第二个项目则是制作一个以发展服务(Service)软件为目标的开发平台。这两个项目团队三年多前就已经在一起工作,他们希望可以发展出一种可以快速开发出以因特网为基础,而且易学易用的开发平台。
固定链接
单击隐藏此项的固定链接。
http://zjhuan.spaces.live.com/blog/cns!7771FF7C39DE7784!271.entry
添加评论
单击隐藏此项的评论。

批处理教程

扩展名是bat(在nt/2000/xp/2003下也可以是cmd)的文件就是批处理文件。 ==== 注 ======================================= .bat是dos下的批处理文件 .cmd是nt内核命令行环境的另一种批处理文件 从更广义的角度来看,unix的shell脚本以及其它操作系统甚至应用程序中由外壳进行解释执行的文本,都具有与批处理文件十分相似的作用,而且同样是由专用解释器以行为单位解释执行,这种文本形式更通用的称谓是脚本语言。所以从某个程度分析,batch, unix shell, awk, basic, perl 等脚本语言都是一样的,只不过应用的范围和解释的平台各有不同而已。甚至有些应用程序仍然沿用批处理这一称呼,而其内容和扩展名与dos的批处理却又完全不同。 =================================== 首先批处理文件是一个文本文件,这个文件的每一行都是一条DOS命令(大部分时候就好象我们在DOS提示符下执行的命令行一样),你可以使用DOS下的Edit或者Windows的记事本(notepad)等任何文本文件编辑工具创建和修改批处理文件。 ==== 注 =================== 批处理文件中完全可以使用非dos命令,甚至可以使用不具有可执行特性的普通数据性文件,这缘于windows系统这个新型解释平台的涉入,使得批处理的应用越来越"边缘化"。所以我们讨论的批处理应该限定在dos环境或者命令行环境中,否则很多观念和设定都需要做比较大的变动。 ======================== 其次,批处理文件是一种简单的程序,可以通过条件语句(if)和流程控制语句(goto)来控制命令运行的流程,在批处理中也可以使用循环语句(for)来循环执行一条命令。当然,批处理文件的编程能力与C语言等编程语句比起来是十分有限的,也是十分不规范的。批处理的程序语句就是一条条的DOS命令(包括内部命令和外部命令),而批处理的能力主要取决于你所使用的命令。 ==== 注 ================== 批处理文件(batch file)也可以称之为批处理程序(batch program),这一点与编译型语言有所不同,就c语言来说,扩展名为c或者cpp的文件可以称之为c语言文件或者c语言源代码,但只有编译连接后的exe文件才可以称之为c语言程序。因为批处理文件本身既具有文本的可读性,又具有程序的可执行性,这些称谓的界限是比较模糊的。 =========================== 第三,每个编写好的批处理文件都相当于一个DOS的外部命令,你可以把它所在的目录放到你的DOS搜索路径(path)中来使得它可以在任意位置运行。一个良好的习惯是在硬盘上建立一个bat或者batch目录(例如C:/BATCH),然后将所有你编写的批处理文件放到该目录中,这样只要在path中设置上c:/batch,你就可以在任意位置运行所有你编写的批处理程序。 ==== 注 ===== 纯以dos系统而言,可执行程序大约可以细分为五类,依照执行优先级由高到低排列分别是:DOSKEY宏命令(预先驻留内存),COMMAND.COM中的内部命令(根据内存的环境随时进驻内存),以com为扩展名的可执行程序(由command.com 直接载入内存),以exe位扩展名的可执行程序(由command.com 重定位后载入内存),以bat位扩展名的批处理程序(由command.com 解释分析,根据其内容按优先级顺序调用第2,3,4,5种可执行程序,分析一行,执行一行,文件本身不载入内存) ============ 第四,在DOS和Win9x/Me系统下,C:盘根目录下的AUTOEXEC.BAT批处理文件是自动运行批处理文件,每次系统启动时会自动运行该文件,你可以将系统每次启动时都要运行的命令放入该文件中,例如设置搜索路径,调入鼠标驱动和磁盘缓存,设置系统环境变量等。下面是一个运行于Windows 98下的autoexec.bat的示例: @ECHO OFF PATH C:/WINDOWS;C:/WINDOWS/COMMAND;C:/UCDOS;C:/DOSTools; C:/SYSTOOLS;C:/WINTOOLS;C:/BATCH LH SMARTDRV.EXE /X LH DOSKEY.COM /insert LH CTMOUSE.EXE SET TEMP=D:/TEMP SET TMP=D:/TEMP ==== 注 ===== AUTOEXEC.BAT为DOS系统的自动运行批处理文件,由COMMAND.COM启动时解释执行; 而在Win9x环境中,不仅增加支持了 DOSSTART.BAT, WINSTART.BAT 等许多其它自动运行的批处理文件,对AUTOEXEC.BAT 也增加了 .DOS .W40 .BAK .OLD .PWS 等许多变体以适应复杂的环境和多变的需求。 ==== willsort 编注 ============= 以下关于命令的分类,有很多值得推敲的地方。常用命令中的@本不是命令,而dir、copy等也很常用的命令却没有列入, 而特殊命令中所有命令对我来说都是常用命令。建议将批处理所引用的命令分为内部命令、外部命令、第三方程序三类。而内部命令和外部命令中别有一类是专用于或常用于批处理中的命令可称之为"批处理命令"。 以下摘录MS-DOS 6.22 帮助文档中关于"批处理命令"的文字,当然,其中有些概念和定义已经有些落后了。 批处理命令 批处理文件或批处理程序是一个包含若干MS-DOS命令的正文文件,扩展名为.BAT。当在命令提示符下敲入批处理程序的名称时,MS-DOS成组执行此批处理程序中的命令。 任何在命令提示符下可使用的命令都可用在批处理程序中。此外,下面MS-DOS命令是专门在批处理程序中使用的。 ========== 常用命令 echo、@、call、pause、rem(小技巧:用::代替rem)是批处理文件最常用的几个命令,我们就从他们开始学起。 ==== 注 =========== 首先, @ 不是一个命令, 而是DOS 批处理的一个特殊标记符, 仅用于屏蔽命令行回显. 下面是DOS命令行或批处理中可能会见到的一些特殊标记符: CR(0D) 命令行结束符 Escape(1B) ANSI转义字符引导符 Space(20) 常用的参数界定符 Tab(09) ; = 不常用的参数界定符 + COPY命令文件连接符 * ? 文件通配符 "" 字符串界定符 | 命令管道符 < > >> 文件重定向符 @ 命令行回显屏蔽符 / 参数开关引导符 : 批处理标签引导符 % 批处理变量引导符 其次, :: 确实可以起到rem 的注释作用, 而且更简洁有效; 但有两点需要注意: 第一, 除了 :: 之外, 任何以 :开头的字符行, 在批处理中都被视作标号, 而直接忽略其后的所有内容, 只是为了与正常的标号相区别, 建议使用 goto 所无法识别的标号, 即在 :后紧跟一个非字母数字的一个特殊符号. 第二, 与rem 不同的是, ::后的字符行在执行时不会回显, 无论是否用echo on打开命令行回显状态, 因为命令解释器不认为他是一个有效的命令行, 就此点来看, rem 在某些场合下将比 :: 更为适用; 另外, rem 可以用于 config.sys 文件中. ===================== echo 表示显示此命令后的字符 echo off 表示在此语句后所有运行的命令都不显示命令行本身 @与echo off相象,但它是加在每个命令行的最前面,表示运行时不显示这一行的命令行(只能影响当前行)。 call 调用另一个批处理文件(如果不用call而直接调用别的批处理文件,那么执行完那个批处理文件后将无法返回当前文件并执行当前文件的后续命令)。 pause 运行此句会暂停批处理的执行并在屏幕上显示Press any key to continue...的提示,等待用户按任意键后继续 rem 表示此命令后的字符为解释行(注释),不执行,只是给自己今后参考用的(相当于程序中的注释)。 ==== 注 ===== 此处的描述较为混乱, 不如直接引用个命令的命令行帮助更为条理 ------------------------- ECHO 当程序运行时,显示或隐藏批处理程序中的正文。也可用于允许或禁止命令的回显。 在运行批处理程序时,MS-DOS一般在屏幕上显示(回显)批处理程序中的命令。 使用ECHO命令可关闭此功能。 语法 ECHO [ON|OFF] 若要用echo命令显示一条命令,可用下述语法: echo [message] 参数 ON|OFF 指定是否允许命令的回显。若要显示当前的ECHO的设置,可使用不带参数的ECHO 命令。 message 指定让MS-DOS在屏幕上显示的正文。 ------------------- CALL 从一个批处理程序中调用另一个批处理程序,而不会引起第一个批处理的中止。 语法 CALL [drive:][path]filename [batch-parameters] 参数 [drive:][path]filename 指定要调用的批处理程序的名字及其存放处。文件名必须用.BAT作扩展名。 batch-parameters 指定批处理程序所需的命令行信息。 ------------------------------- PAUSE 暂停批处理程序的执行并显示一条消息,提示用户按任意键继续执行。只能在批处 理程序中使用该命令。 语法 PAUSE REM 在批处理文件或CONFIG.SYS中加入注解。也可用REM命令来屏蔽命令(在CONFIG.SYS 中也可以用分号 ; 代替REM命令,但在批处理文件中则不能替代)。 语法 REM [string] 参数 string 指定要屏蔽的命令或要包含的注解。 ======================= 例1:用edit编辑a.bat文件,输入下列内容后存盘为c:/a.bat,执行该批处理文件后可实现:将根目录中所有文件写入 a.txt中,启动UCDOS,进入WPS等功能。   批处理文件的内容为:         命令注释:     @echo off           不显示后续命令行及当前命令行     dir c:/*.* >a.txt       将c盘文件列表写入a.txt     call c:/ucdos/ucdos.bat    调用ucdos     echo 你好            显示"你好"     pause              暂停,等待按键继续     rem 准备运行wps         注释:准备运行wps     cd ucdos            进入ucdos目录     wps               运行wps   批处理文件的参数 批处理文件还可以像C语言的函数一样使用参数(相当于DOS命令的命令行参数),这需要用到一个参数表示符"%"。 %[1-9]表示参数,参数是指在运行批处理文件时在文件名后加的以空格(或者Tab)分隔的字符串。变量可以从%0到%9,%0表示批处理命令本身,其它参数字符串用%1到%9顺序表示。 例2:C:根目录下有一批处理文件名为f.bat,内容为: @echo off format %1 如果执行C:/>f a: 那么在执行f.bat时,%1就表示a:,这样format %1就相当于format a:,于是上面的命令运行时实际执行的是format a: 例3:C:根目录下一批处理文件名为t.bat,内容为: @echo off type %1 type %2 那么运行C:/>t a.txt b.txt %1 : 表示a.txt %2 : 表示b.txt 于是上面的命令将顺序地显示a.txt和b.txt文件的内容。 ==== 注 =============== 参数在批处理中也作为变量处理, 所以同样使用百分号作为引导符, 其后跟0-9中的一个数字构成参数引用符. 引用符和参数之间 (例如上文中的 %1 与 a: ) 的关系类似于变量指针与变量值的关系. 当我们要引用第十一个或更多个参数时, 就必须移动DOS 的参数起始指针. shift 命令正充当了这个移动指针的角色, 它将参数的起始指针移动到下一个参数, 类似C 语言中的指针操作. 图示如下: 初始状态, cmd 为命令名, 可以用 %0 引用 cmd arg1 arg2 arg3 arg4 arg5 arg6 arg7 arg8 arg9 arg10 ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ | | | | | | | | | | %0 %1 %2 %3 %4 %5 %6 %7 %8 %9 经过1次shift后, cmd 将无法被引用 cmd arg1 arg2 arg3 arg4 arg5 arg6 arg7 arg8 arg9 arg10 ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ | | | | | | | | | | %0 %1 %2 %3 %4 %5 %6 %7 %8 %9 经过2次shift后, arg1也被废弃, %9指向为空, 没有引用意义 cmd arg1 arg2 arg3 arg4 arg5 arg6 arg7 arg8 arg9 arg10 ^ ^ ^ ^ ^ ^ ^ ^ ^ | | | | | | | | | %0 %1 %2 %3 %4 %5 %6 %7 %8 遗憾的是, win9x 和DOS下均不支持 shift 的逆操作. 只有在 nt 内核命令行环境下, shift 才支持 /n 参数, 可以以第一参数为基准返复移动起始指针. ================= 特殊命令 if goto choice for是批处理文件中比较高级的命令,如果这几个你用得很熟练,你就是批处理文件的专家啦。 一、if 是条件语句,用来判断是否符合规定的条件,从而决定执行不同的命令。 有三种格式: 1、if [not] "参数" == "字符串" 待执行的命令 参数如果等于(not表示不等,下同)指定的字符串,则条件成立,运行命令,否则运行下一句。 例:if "%1"=="a" format a: ==== if 的命令行帮助中关于此点的描述为: IF [NOT] string1==string2 command 在此有以下几点需要注意: 1. 包含字符串的双引号不是语法所必须的, 而只是习惯上使用的一种"防空"字符 2. string1 未必是参数, 它也可以是环境变量, 循环变量以及其他字符串常量或变量 3. command 不是语法所必须的, string2 后跟一个空格就可以构成一个有效的命令行 ============================= 2、if [not] exist [路径/]文件名 待执行的命令 如果有指定的文件,则条件成立,运行命令,否则运行下一句。 如: if exist c:/config.sys type c:/config.sys 表示如果存在c:/config.sys文件,则显示它的内容。 ****** 注 ******** 也可以使用以下的用法: if exist command device 是指DOS系统中已加载的设备, 在win98下通常有: AUX, PRN, CON, NUL COM1, COM2, COM3, COM4 LPT1, LPT2, LPT3, LPT4 XMSXXXX0, EMMXXXX0 A: B: C: ..., CLOCK$, CONFIG$, DblBuff$, IFS$HLP$ 具体的内容会因硬软件环境的不同而略有差异, 使用这些设备名称时, 需要保证以下三点: 1. 该设备确实存在(由软件虚拟的设备除外) 2. 该设备驱动程序已加载(aux, prn等标准设备由系统缺省定义) 3. 该设备已准备好(主要是指a: b: ..., com1..., lpt1...等) 可通过命令 mem/d | find "device" /i 来检阅你的系统中所加载的设备 另外, 在DOS系统中, 设备也被认为是一种特殊的文件, 而文件也可以称作字符设备; 因为设备(device)与文件都是使用句柄(handle)来管理的, 句柄就是名字, 类似于文件名, 只不过句柄不是应用于磁盘管理, 而是应用于内存管理而已, 所谓设备加载也即指在内存中为其分配可引用的句柄. ================================== 3、if errorlevel <数字> 待执行的命令 很多DOS程序在运行结束后会返回一个数字值用来表示程序运行的结果(或者状态),通过if errorlevel命令可以判断程序的返回值,根据不同的返回值来决定执行不同的命令(返回值必须按照从大到小的顺序排列)。如果返回值等于指定的数字,则条件成立,运行命令,否则运行下一句。 如if errorlevel 2 goto x2 ==== 注 =========== 返回值从大到小的顺序排列不是必须的, 而只是执行命令为 goto 时的习惯用法, 当使用 set 作为执行命令时, 通常会从小到大顺序排列, 比如需将返回码置入环境变量, 就需使用以下的顺序形式: if errorlevel 1 set el=1 if errorlevel 2 set el=2 if errorlevel 3 set el=3 if errorlevel 4 set el=4 if errorlevel 5 set el=5 ... 当然, 也可以使用以下循环来替代, 原理是一致的: for %%e in (1 2 3 4 5 6 7 8...) do if errorlevel %%e set el=%%e 更高效简洁的用法, 可以参考我写的另一篇关于获取 errorlevel 的文章 出现此种现象的原因是, if errorlevel 比较返回码的判断条件并非等于, 而是大于等于. 由于 goto 的跳转特性, 由小到大排序会导致在较小的返回码处就跳出; 而由于 set命令的 "重复" 赋值特性, 由大到小排序会导致较小的返回码 "覆盖" 较大的返回码. 另外, 虽然 if errorlevel=<数字> command 也是有效的命令行, 但也只是 command.com 解释命令行时将 = 作为命令行切分符而忽略掉罢了 =========================== 二、goto 批处理文件运行到这里将跳到goto所指定的标号(标号即label,标号用:后跟标准字符串来定义)处,goto语句一般与if配合使用,根据不同的条件来执行不同的命令组。 如: goto end :end echo this is the end 标号用":字符串"来定义,标号所在行不被执行。 ==== willsort 编注 label 常被译为 "标签" , 但是这并不具有广泛的约定性. goto 与 : 联用可实现执行中途的跳转, 再结合 if 可实现执行过程的条件分支, 多个 if 即可实现命令的分组, 类似 C 中 switch case 结构或者 Basic 中的 select case 结构, 大规模且结构化的命令分组即可实现高级语言中的函数功能. 以下是批处理和C/Basic在语法结构上的对照: Batch C / Basic goto&: goto&: goto&:&if if{}&else{} / if&elseif&endif goto&:&if... switch&case / select case goto&:&if&set&envar... function() / function(),sub() ================================== 三、choice 使用此命令可以让用户输入一个字符(用于选择),从而根据用户的选择返回不同的errorlevel,然后于if errorlevel配合,根据用户的选择运行不同的命令。 注意:choice命令为DOS或者Windows系统提供的外部命令,不同版本的choice命令语法会稍有不同,请用choice /?查看用法。 choice的命令语法(该语法为Windows 2003中choice命令的语法,其它版本的choice的命令语法与此大同小异): CHOICE [/C choices] [/N] [/CS] [/T timeout /D choice] [/M text] 描述: 该工具允许用户从选择列表选择一个项目并返回所选项目的索引。 参数列表: /C choices 指定要创建的选项列表。默认列表是 "YN"。 /N 在提示符中隐藏选项列表。提示前面的消息得到显示, 选项依旧处于启用状态。 /CS 允许选择分大小写的选项。在默认情况下,这个工具 是不分大小写的。 /T timeout 做出默认选择之前,暂停的秒数。可接受的值是从 0 到 9999。如果指定了 0,就不会有暂停,默认选项 会得到选择。 /D choice 在 nnnn 秒之后指定默认选项。字符必须在用 /C 选 项指定的一组选择中; 同时,必须用 /T 指定 nnnn。 /M text 指定提示之前要显示的消息。如果没有指定,工具只 显示提示。 /? 显示帮助消息。 注意: ERRORLEVEL 环境变量被设置为从选择集选择的键索引。列出的第一个选 择返回 1,第二个选择返回 2,等等。如果用户按的键不是有效的选择, 该工具会发出警告响声。如果该工具检测到错误状态,它会返回 255 的 ERRORLEVEL 值。如果用户按 Ctrl+Break 或 Ctrl+C 键,该工具会返回 0 的 ERRORLEVEL 值。在一个批程序中使用 ERRORLEVEL 参数时,将参数降 序排列。 示例: CHOICE /? CHOICE /C YNC /M "确认请按 Y,否请按 N,或者取消请按 C。" CHOICE /T 10 /C ync /CS /D y CHOICE /C ab /M "选项 1 请选择 a,选项 2 请选择 b。" CHOICE /C ab /N /M "选项 1 请选择 a,选项 2 请选择 b。" ==== willsort 编注 =============================== 我列出win98下choice的用法帮助, 已资区分 Waits for the user to choose one of a set of choices. 等待用户选择一组待选字符中的一个 CHOICE [/C[:]choices] [/N] [/S] [/T[:]c,nn] [text] /C[:]choices Specifies allowable keys. Default is YN 指定允许的按键(待选字符), 默认为YN /N Do not display choices and ? at end of prompt string. 不显示提示字符串中的问号和待选字符 /S Treat choice keys as case sensitive. 处理待选字符时大小写敏感 /T[:]c,nn Default choice to c after nn seconds 在 nn 秒后默认选择 c text Prompt string to display 要显示的提示字符串 ERRORLEVEL is set to offset of key user presses in choices. ERRORLEVEL 被设置为用户键入的字符在待选字符中的偏移值 如果我运行命令:CHOICE /C YNC /M "确认请按 Y,否请按 N,或者取消请按 C。" 屏幕上会显示: 确认请按 Y,否请按 N,或者取消请按 C。 [Y,N,C]? 例:test.bat的内容如下(注意,用if errorlevel判断返回值时,要按返回值从高到低排列): @echo off choice /C dme /M "defrag,mem,end" if errorlevel 3 goto end if errorlevel 2 goto mem if errorlevel 1 goto defrag :defrag c:/dos/defrag goto end :mem mem goto end :end echo good bye 此批处理运行后,将显示"defrag,mem,end[D,M,E]?" ,用户可选择d m e ,然后if语句根据用户的选择作出判断,d表示执行标号为defrag的程序段,m表示执行标号为mem的程序段,e表示执行标号为end的程序段,每个程序段最后都以goto end将程序跳到end标号处,然后程序将显示good bye,批处理运行结束。 四、for 循环命令,只要条件符合,它将多次执行同一命令。 语法: 对一组文件中的每一个文件执行某个特定命令。 FOR %%variable IN (set) DO command [command-parameters] %%variable 指定一个单一字母可替换的参数。 (set) 指定一个或一组文件。可以使用通配符。 command 指定对每个文件执行的命令。 command-parameters 为特定命令指定参数或命令行开关。 例如一个批处理文件中有一行: for %%c in (*.bat *.txt) do type %%c 则该命令行会显示当前目录下所有以bat和txt为扩展名的文件的内容。 ==== willsort 编注 ===================================================== 需要指出的是, 当()中的字符串并非单个或多个文件名时, 它将单纯被当作字符串替换, 这个特性再加上()中可以嵌入多个字符串的特性, 很明显 for 可以被看作一种遍历型循环. 当然, 在 nt/2000/xp/2003 系列的命令行环境中, for 被赋予了更多的特性, 使之可以分析命令输出或者文件中的字符串, 也有很多开关被用于扩展了文件替换功能. ======================================================================== 批处理示例 1. IF-EXIST 1) 首先用记事本在C:/建立一个test1.bat批处理文件,文件内容如下: @echo off IF EXIST /AUTOEXEC.BAT TYPE /AUTOEXEC.BAT IF NOT EXIST /AUTOEXEC.BAT ECHO /AUTOEXEC.BAT does not exist 然后运行它: C:/>TEST1.BAT 如果C:/存在AUTOEXEC.BAT文件,那么它的内容就会被显示出来,如果不存在,批处理就会提示你该文件不存在。 2) 接着再建立一个test2.bat文件,内容如下: @ECHO OFF IF EXIST /%1 TYPE /%1 IF NOT EXIST /%1 ECHO /%1 does not exist 执行: C:/>TEST2 AUTOEXEC.BAT 该命令运行结果同上。 说明: (1) IF EXIST 是用来测试文件是否存在的,格式为 IF EXIST [路径+文件名] 命令 (2) test2.bat文件中的%1是参数,DOS允许传递9个批参数信息给批处理文件,分别为%1~%9(%0表示test2命令本身) ,这有点象编程中的实参和形参的关系,%1是形参,AUTOEXEC.BAT是实参。 ==== willsort 编注 ===================================================== DOS没有 "允许传递9个批参数信息" 的限制, 参数的个数只会受到命令行长度和所调用命令处理能力的限制. 但是, 我们在批处理程序中, 在同一时刻只能同时引用10个参数, 因为 DOS只给出了 %0~%9这十个参数引用符. ======================================================================== 3) 更进一步的,建立一个名为TEST3.BAT的文件,内容如下: @echo off IF "%1" == "A" ECHO XIAO IF "%2" == "B" ECHO TIAN IF "%3" == "C" ECHO XIN 如果运行: C:/>TEST3 A B C 屏幕上会显示: XIAO TIAN XIN 如果运行: C:/>TEST3 A B 屏幕上会显示 XIAO TIAN 在这个命令执行过程中,DOS会将一个空字符串指定给参数%3。 2、IF-ERRORLEVEL 建立TEST4.BAT,内容如下: @ECHO OFF XCOPY C:/AUTOEXEC.BAT D:/ IF ERRORLEVEL 1 ECHO 文件拷贝失败 IF ERRORLEVEL 0 ECHO 成功拷贝文件 然后执行文件: C:/>TEST4 如果文件拷贝成功,屏幕就会显示"成功拷贝文件",否则就会显示"文件拷贝失败"。 IF ERRORLEVEL 是用来测试它的上一个DOS命令的返回值的,注意只是上一个命令的返回值,而且返回值必须依照从大到小次序顺序判断。 因此下面的批处理文件是错误的: @ECHO OFF XCOPY C:/AUTOEXEC.BAT D:/ IF ERRORLEVEL 0 ECHO 成功拷贝文件 IF ERRORLEVEL 1 ECHO 未找到拷贝文件 IF ERRORLEVEL 2 ECHO 用户通过ctrl-c中止拷贝操作 IF ERRORLEVEL 3 ECHO 预置错误阻止文件拷贝操作 IF ERRORLEVEL 4 ECHO 拷贝过程中写盘错误无论拷贝是否成功,后面的: 未找到拷贝文件 用户通过ctrl-c中止拷贝操作 预置错误阻止文件拷贝操作 拷贝过程中写盘错误 都将显示出来。 以下就是几个常用命令的返回值及其代表的意义: backup 0 备份成功 1 未找到备份文件 2 文件共享冲突阻止备份完成 3 用户用ctrl-c中止备份 4 由于致命的错误使备份操作中止 diskcomp 0 盘比较相同 1 盘比较不同 2 用户通过ctrl-c中止比较操作 3 由于致命的错误使比较操作中止 4 预置错误中止比较 diskcopy 0 盘拷贝操作成功 1 非致命盘读/写错 2 用户通过ctrl-c结束拷贝操作 3 因致命的处理错误使盘拷贝中止 4 预置错误阻止拷贝操作 format 0 格式化成功 3 用户通过ctrl-c中止格式化处理 4 因致命的处理错误使格式化中止 5 在提示"proceed with format(y/n)?"下用户键入n结束 xcopy 0 成功拷贝文件 1 未找到拷贝文件 2 用户通过ctrl-c中止拷贝操作 4 预置错误阻止文件拷贝操作 5 拷贝过程中写盘错误 chkdsk 0 未找到错误 255 找到一个或多个错误 choice 0 用户按下ctrl+c/break 1 用户按下第一个键 255 检测到命令行中的错误条件 其它 用户按下的有效字符在列表中的位置 defrag 0 碎片压缩成功 1 出现内部错误 2 磁盘上没有空簇。要运行DEFRAG,至少要有一个空簇 3 用户用Ctrl+C退出了DEFRAG 4 出现一般性错误 5 DEFRAG在读簇时遇到错误 6 DEFRAG在写簇时遇到错误 7 分配空间有错 8 内存错 9 没有足够空间来压缩磁盘碎片 deltree 0 成功地删除一个目录 diskcomp 0 两盘相同 1 发现不同 2 按CTRL+C 终止了比较 3 出现严重错误 4 出现初始化错误 find 0 查找成功且至少找到了一个匹配的字符串 1 查找成功但没找到匹配的字符串 2 查找中出现了错误 keyb 0 键盘定义文件装入成功 1 使用了非法的键盘代码,字符集或语法 2 键盘定义文件坏或未找到 4 键盘、监视器通讯时出错 5 要求的字符集未准备好 move 0 成功地移动了指定的文件 1 发生了错误 msav /N 86 检查到了病毒 replace 0 REPLACE成功地替换或加入了文件 1 MS-DOS版本和REPLACE不兼容 2 REPLACE找不到源文件 3 REPLACE找不到源路径或目标路径 5 不能存取要替换的文件 8 内存不够无法执行REPLACE 11 命令行句法错误 restore 0 RESTORE成功地恢复了文件 1 RESTORE找不到要恢复的文件 3 用户按CTRL+C终止恢复过程 4 RESTORE因错误而终止 scandisk 0 ScanDisk在它检查的驱动器上未检测到任何错误 1 由于命令行的语法不对,不能运行ScanDisk 2 由于内存用尽或发生内部错误,ScanDisk意外终止 3 用户让ScanDisk中途退出 4 进行盘面扫描时,用户决定提前退出 254 ScanDisk找到磁盘故障并已全部校正 255 ScanDisk找到磁盘故障,但未能全部校正 setver 0 SETVER成功地完成了任务 1 用户指定了一个无效的命令开关 2 用户指定了一个非法的文件名 3 没有足够的系统内存来运行命令 4 用户指定了一个非法的版本号格式 5 SETVER在版本表中未找到指定的项 6 SETVER未找到SETVER.EXE文件 7 用户指定了一个非法的驱动器 8 用户指定了太多的命令行参数 9 SETVER检测到丢失了命令行参数 10 在读SETVER.EXE文件时,SETVER检测到发生错误 11 SETVER.EXE文件损坏 12 指定的SETVER.EXE文件不支持版本表 13 版本表中没有足够的空间存放新的项 14 在写SETVER.EXE文件时SETVER检测到发生错误 ======================================================================== 3、IF STRING1 == STRING2 建立TEST5.BAT,文件内容如下: @echo off IF "%1" == "A" FORMAT A: 执行: C:/>TEST5 A 屏幕上就出现是否将A:盘格式化的内容。 注意:为了防止参数为空的情况,一般会将字符串用双引号(或者其它符号,注意不能使用保留符号)括起来。 如:if [%1]==[A] 或者 if %1*==A* 5、GOTO 建立TEST6.BAT,文件内容如下: @ECHO OFF IF EXIST C:/AUTOEXEC.BAT GOTO _COPY GOTO _DONE :_COPY COPY C:/AUTOEXEC.BAT D:/ :_DONE 注意: (1) 标号前是ASCII字符的冒号":",冒号与标号之间不能有空格。 (2) 标号的命名规则与文件名的命名规则相同。 (3) DOS支持最长八位字符的标号,当无法区别两个标号时,将跳转至最近的一个标号。 ==== willsort 编注 ===================================================== 1)标号也称作标签(label) 2)标签不能以大多数的非字母数字字符开始, 而文件名中则可以使用很多 3)当无法区别两个标签时, 将跳转至位置最靠前的标签 ======================================================================== 6、FOR 建立C:/TEST7.BAT,文件内容如下: @ECHO OFF FOR %%C IN (*.BAT *.TXT *.SYS) DO TYPE %%C 运行: C:/>TEST7 执行以后,屏幕上会将C:盘根目录下所有以BAT、TXT、SYS为扩展名的文件内容显示出来(不包括隐藏文件)。
固定链接
单击隐藏此项的固定链接。
http://zjhuan.spaces.live.com/blog/cns!7771FF7C39DE7784!270.entry
添加评论
单击隐藏此项的评论。
2006/6/15

What's New in Microsoft Office Outlook 2003 for Developers?

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/odc_ol2003_ta/html/odc_OLWhatsNew2k3.asp
 
固定链接
单击隐藏此项的固定链接。
http://zjhuan.spaces.live.com/blog/cns!7771FF7C39DE7784!269.entry
添加评论
单击隐藏此项的评论。

Attachment File Types Restricted by Outlook 2003

By default, access is restricted to certain e-mail message attachments in Microsoft® Outlook®. In determining which attachments are blocked, Outlook checks the file type of the attachment. Files with certain file types can be completely blocked (Level 1) or the user may be required to save a file to disk before opening the file (Level 2).

By default, Outlook classifies a number of file type extensions as Level 1 and blocks files with those extensions from being received by the users. There are no Level 2 file types by default, but you can create a list of Level 2 file types by using the Outlook Security template. You can demote file types from being categorized as Level 1 to being Level 2, or you can add other file types to create a Level 2 list.

Note  To learn more about why some attachments are blocked, see Blocked attachments: The Outlook feature you love to hate. In addition, users can find methods for sharing files that are blocked by Outlook by reading About unblocking attachments.

Level 1 file types blocked by Outlook

The following table lists the Level 1 file types that are blocked under a default installation of Microsoft Office Outlook 2003. You can add or remove items from the default list through the Outlook Security Settings tab of the Outlook Security template.

File extension File type .ade Access Project Extension (Microsoft) .adp Access Project (Microsoft) .app Executable Application .asp Active Server Page .bas BASIC Source Code .bat Batch Processing .cer Internet Security Certificate File .chm Compiled HTML Help .cmd DOS CP/M Command File, Command File for Windows NT .com Command .cpl Windows Control Panel Extension (Microsoft) .crt Certificate File .csh csh Script .exe Executable File .fxp FoxPro Compiled Source (Microsoft) .hlp Windows Help File .hta Hypertext Application .inf Information or Setup File .ins IIS Internet Communications Settings (Microsoft) .isp IIS Internet Service Provider Settings (Microsoft) .its Internet Document Set, Internation Translation .js JavaScript Source Code .jse JScript Encoded Script File .ksh UNIX Shell Script .lnk Windows Shortcut File .mad Access Module Shortcut (Microsoft) .maf Access (Microsoft) .mag Access Diagram Shortcut (Microsoft) .mam Access Macro Shortcut (Microsoft) .maq Access Query Shortcut (Microsoft) .mar Access Report Shortcut (Microsoft) .mas Access Stored Procedures (Microsoft) .mat Access Table Shortcut (Microsoft) .mau Media Attachment Unit .mav Access View Shortcut (Microsoft) .maw Access Data Access Page (Microsoft) .mda Access Add-in (Microsoft), MDA Access 2 Workgroup (Microsoft) .mdb Access Application (Microsoft), MDB Access Database (Microsoft) .mde Access MDE Database File (Microsoft) .mdt Access Add-in Data (Microsoft) .mdw Access Workgroup Information (Microsoft) .mdz Access Wizard Template (Microsoft) .msc Microsoft Management Console Snap-in Control File (Microsoft) .msi Windows Installer File (Microsoft) .msp Windows Installer Patch .mst Windows SDK Setup Transform Script .ops Office Profile Settings File .pcd Visual Test (Microsoft) .pif Windows Program Information File (Microsoft) .prf Windows System File .prg Program File .pst MS Exchange Address Book File, Outlook Personal Folder File (Microsoft) .reg Registration Information/Key for W95/98, Registry Data File .scf Windows Explorer Command .scr Windows Screen Saver .sct Windows Script Component, Foxpro Screen (Microsoft) .shb Windows Shortcut into a Document .shs Shell Scrap Object File .tmp Temporary File/Folder .url Internet Location .vb VBScript File or Any VisualBasic Source .vbe VBScript Encoded Script File .vbs VBScript Script File, Visual Basic for Applications Script .vsmacros Visual Studio .NET Binary-based Macro Project (Microsoft) .vss Visio Stencil (Microsoft) .vst Visio Template (Microsoft) .vsw Visio Workspace File (Microsoft) .ws Windows Script File .wsc Windows Script Component .wsf Windows Script File .wsh Windows Script Host Settings File

Level 2 file types restricted by Outlook

There are no Level 2 file types by default, but you can create a list of Level 2 file types for your deployment. Level 2 file types are restricted (under a default installation of Outlook 2003) and you must first save a Level 2 file to disk before you can open it —Level 2 file types cannot be opened directly from an item in an e-mail message.

As an administrator, you can add or remove attachment types from the list of Level 2 file types through the Outlook Security Settings tab of the Outlook Security form. Also, you can demote attachment file types from Level 1 to Level 2 by using the Level1Remove registry key. For more information about setting the Level1Remove registry key, see Administrator-Controlled Settings vs. User-Controlled Settings.

固定链接
单击隐藏此项的固定链接。
http://zjhuan.spaces.live.com/blog/cns!7771FF7C39DE7784!268.entry
添加评论
单击隐藏此项的评论。

Administrator-Controlled Settings vs. User-Controlled Settings

In general, security settings defined by the user through the Microsoft® Office Outlook® 2003 user interface work as if they were added to the settings defined by the administrator. When there is a conflict between the two, the settings with a higher security level will override settings with a lower level of security.

Note  If you are a user who wants to learn more about why some Outlook attachments are blocked, see Blocked attachments: The Outlook feature you love to hate. In addition, you can find methods for sharing files that are blocked by Outlook by reading About unblocking attachments.

Interactions between administrator settings and user settings

The following list describes some specific interactions between administrator security settings defined by using the Outlook Security template and security settings that a user defines in Outlook.

Show Level 1 attachments. When this option is set on the Outlook Security Settings tab in the Outlook Security template, all file types that were set to Level 1 security are set to Level 2 security. If a user wants to block a file type, the user can customize the list to block access to specific types of attachments.

Level 1 file extensions — Add. When set by the administrator, this list overrides the user's settings. Even if users are allowed to remove extensions from the default Level 1 group of excluded extensions, they cannot remove any extensions that were added to the list by using the Security template. For example, if the user wants to remove EXE, REG, and COM from the Level 1 group, but the administrator explicitly adds EXE into the Level 1 Add box, then the user would only be able to remove REG and COM files from the Level 1 group.

Level 1 file extensions — Remove. The user's list is combined with the list set by the administrator to determine which Level 1 items are set to Level 2.

Level 2 file extensions — Add. If a user turns Level 1 files into Level 2 files, and those file types are listed in the Add box, the files are treated as Level 2 attachments.

Level 2 file extensions — Remove. There is no interaction with this setting.

Allow users to lower attachments to Level 2. This setting allows a user to demote a Level 1 attachment to Level 2. If this option is unchecked, the user's list is ignored and the administrative settings help to control the security.

How security settings are controlled within the registry

The option to help prevent users from customizing their security settings is controlled either by a policy or by an option in the security template.

If the following registry key and value name are present, users cannot customize their security settings:

HKCU/Software/Policies/Microsoft/Office/11.0/Outlook
Value name: DisallowAttachmentCustomization

If the policy is present, end-user customization is disallowed. If the policy is not set on the computer, end-user customization is allowed only if it's not prohibited by an option in the Outlook Security template. The value of the key has no effect.

The registry key to set the exception list contains a semicolon-delimited list of file extensions. The value of the key is as follows:

HKCU/Software/Policies/Microsoft/Office/11.0/Outlook/Security
Value name: Level1Remove

If the value of the key is formatted incorrectly, the restrictions are ignored.

固定链接
单击隐藏此项的固定链接。
http://zjhuan.spaces.live.com/blog/cns!7771FF7C39DE7784!267.entry
添加评论
单击隐藏此项的评论。

Deploying Customized Outlook Security Settings to Client Computers

After you configure customized Microsoft® Outlook® client security features by using the Microsoft Outlook security template and saving the settings in the special Microsoft Exchange public folder, you must enable the customized settings for your users. To enable the changed settings, you might need to deploy a new registry key to the client computers.

To enable the customized security settings, you create the following registry subkey, which is of type DWORD:

HKEY_CURRENT_USER/Software/Policies/Microsoft/Security/CheckAdminSettings

The following table describes the subkey values.

Key value Description No key Outlook uses default security settings. Set to 0 Outlook uses default security settings. Set to 1 Outlook looks for custom administrative settings in the Outlook Security Settings folder. Set to 2 Outlook looks for custom administrative settings in the Outlook 10 Security Settings folder. Set to anything else Outlook uses default administrative settings.

To create a new registry subkey for distribution to client computers

  1. Start the registry editor and expand the following key:

    HKEY_CURRENT_USER/Software/Policies/Microsoft/Security

  2. From the Edit menu, choose New, then click DWORD value to add a new registry key.

    The value name for the key must be CheckAdminSettings.

  3. Select the new key name, and then from the Registry menu, choose Export Registry File.
  4. In the Export Registry File dialog box, type a name for the registry file and select the option for Selected Branch under the Export Range group, then click Save to create the registry file.

    Registry files have an .reg extension.

固定链接
单击隐藏此项的固定链接。
http://zjhuan.spaces.live.com/blog/cns!7771FF7C39DE7784!266.entry
添加评论
单击隐藏此项的评论。

Outlook Security Template Settings

The Microsoft® Outlook® Security template has three tabs: Outlook Security Settings, Outlook Programmatic Settings, and Trusted Code. The following sections describe the configurations you can specify on each of these tabs.

Note  If you are a user who wants to learn more about why some Outlook attachments are blocked, see Blocked attachments: The Outlook feature you love to hate. In addition, you can find methods for sharing files that are blocked by Outlook by reading About unblocking attachments.

Outlook Security Settings tab

The Outlook Security Settings tab enables you to configure settings related to attachments, the types of files to which users can gain access, and scripting.

General settings

You can specify one or more groups of users whose members will have the same security settings. The following table describes the settings that specify security groups and members on the Outlook Security Settings tab.

Item Description Default Security Settings for All Users Applies the default Outlook security settings to everyone. Security Settings for Exception Group Enables you to create custom Outlook security settings for some users. Security Group Name Specifies a name for the security group to which these customizations will apply; for example: Object model access approved. Members Lists the names of members in this security group. If you are using an Exchange 2000 or later server, you can use distribution lists (that is, server-based security groups). You must type names individually, separating each name by a semicolon. If a user's name is entered as a member of more than one security group, the settings of the most recently created group will apply, because Outlook looks for the first item that has the user's name in the To field. Administrators should not use the address book to enter an alias into the Members field when creating a security form. The only way to enter an alias into the Members field is by directly entering it into the field.

Miscellaneous attachment settings

You can specify how users will experience access to restricted (Level 1 and Level 2) e-mail message attachments. For example, you might allow users to change an attachment they receive that is specified as Level 1 (user cannot view the file) to Level 2 (user can open the file after saving it to disk).

The following table describes the security options for e-mail attachments.

Item Description Show Level 1 attachments Enables users to gain access to attachments with Level 1 file types. Allow users to lower attachments to
Level 2 Enables users to demote a Level 1 attachment to Level 2. Do not prompt about Level 1 attachments when sending an item Prevents users from receiving a warning when they send an item containing a Level 1 attachment. This option affects only the warning. Once the item is sent, the user will not be able to view or gain access to the attachment. If you want users to be able to post items to a public folder without receiving this prompt, you must select both this check box and the Do not prompt about Level 1 attachments when closing an item check box. Do not prompt about Level 1 attachments when closing an item Prevents users from receiving a warning when they close an e-mail message, appointment, or other item containing a Level 1 attachment. This option affects only the warning. Once the item is closed, the user will not be able to see or gain access to the attachment. If you want users to be able to post items to a public folder without receiving this prompt, you must select both this check box and the Do not prompt about Level 1 attachments when sending an item check box. Allow in-place activation of embedded OLE objects Allows users to double-click an embedded object, such as a Microsoft Excel spreadsheet, and open it in the program. However, if you are using Microsoft Word as your e-mail editor, clearing this check box will still allow OLE objects to be opened when the embedded object is double-clicked. Show OLE package objects Displays OLE objects that have been packaged. A package is an icon that represents an embedded or linked OLE object. When you double-click the package, the program used to create the object either plays the object (for example, if it's a sound file) or opens and displays the object. Caution should be used in displaying OLE package objects, because the icon can easily be changed and used to disguise malicious files.

Modifying the list of Level 1 file extensions

Level 1 files are hidden from the user in all items. The user cannot open, save, or print a Level 1 attachment. (If you specify that users can demote a Level 1 attachment to a Level 2 attachment, then Level 2 restrictions apply to the file.) The InfoBar at the top of the item will display a list of the blocked files. The InfoBar does not appear on a custom form. For information on a default list of Level 1 file types, see the topic Attachment File Types Restricted by Outlook 2003.

When you remove a file extension from the Level 1 list, attachments with that file extension will no longer be blocked.

The following table describes how to add or remove Level 1 file extensions from the default list.

Action Description Add Specifies the file extensions (usually three letters) of the file types you want to add to the Level 1 file list. Do not enter a period before each file extension. If you enter multiple extensions, separate them with semicolons. Remove Specifies the file extensions (usually three letters) of file types you want to remove from the Level 1 file list. Do not enter a period before each file extension. If you enter multiple extensions, separate them with semicolons.

Modifying the list of Level 2 file extensions

With a Level 2 file, the user is required to save the file to the hard disk before opening it. A Level 2 file cannot be opened directly from an item in an e-mail message. The following table describes how to add or remove Level 2 file extensions from the default list.

When you remove a file extension from the Level 2 list, it becomes a normal file type. You can open it, print it, and so on in Outlook; there are no restrictions on the file.

Action Description Add Specifies the file extensions (usually three letters) of the file types you want to add to the Level 2 file list. Do not enter a period before each file extension. If you enter multiple extensions, separate them with semicolons. Remove Specifies the file extensions (usually three letters) of file types you want to remove from the Level 2 file list. Do not enter a period before each file extension. If you enter multiple extensions, separate them with semicolons.

Miscellaneous custom template settings

You can specify security settings for scripts, custom controls, and custom actions. For example, you can specify that when a program tries to run a custom action, users can decide whether to allow programmatic access for sending an e-mail message.

The following table describes the security settings for scripts, custom controls, and custom actions. (Scroll down in the Outlook Security template to see the full set of options.)

Item Description Enable scripts in one-off Outlook forms Select this check box to run scripts in forms where the script and the layout are contained in the message itself. If users receive a one-off form that contains script, users will be prompted to ask if they want to run the script. When executing a custom action via the Outlook object model Specifies what happens when a program attempts to run a custom action using the Outlook object model. A custom action can be created to reply to a message and circumvent the programmatic send protections just described. Select one of the following:

Prompt user enables the user to receive a message and decide whether to allow programmatic send access.

Automatically approve always allows programmatic send access without displaying a message.

Automatically deny always denies programmatic send access without displaying a message.

When accessing the ItemProperty property of a control on an Outlook custom form Specifies what happens when a user adds a control to a custom Outlook form and then binds that control directly to any of the Address Information fields. By doing this, code can be used to indirectly retrieve the value of the Address Information field by getting the Value property of the control. Select one of the following:

Prompt user enables the user to receive a message and decide whether to allow access to Address Information fields.

Automatically approve always allows access to Address Information fields without displaying a message.

Automatically deny always denies access to Address Information fields without displaying a message.

Programmatic Settings tab

The Programmatic Settings tab enables you to configure settings related to your use of the Outlook object model, Collaboration Data Objects (CDO), and Simple MAPI. These technologies are defined as follows:

  • Outlook object model — The Outlook object model allows you to programmatically manipulate data stored in Outlook folders.
  • CDO — Collaboration Data Object (CDO) libraries are used to implement messaging and collaboration functionality in a custom application. CDO is a COM wrapper of the MAPI library and can be called from any development language that supports Automation. CDO implements most but not all MAPI functionality (but more than Simple MAPI).
  • Simple MAPI — Simple MAPI enables developers to add basic messaging functionality, such as sending and receiving messages, to their Microsoft Windows®-based applications. It is a subset of MAPI, which provides complete access to messaging and information exchange systems.

The following table lists descriptions for each option on the Programmatic Settings tab. For each item, you can choose one of the following settings:

  • Prompt user — Users receive a message allowing them to choose whether to allow or deny the operation. For some prompts, users can choose to allow or deny the operation without prompts for up to 10 minutes.
  • Automatically approve — The operation will be allowed and the user will not receive a prompt.
  • Automatically deny — The operation will not be allowed and the user will not receive a prompt.

The following table describes the available options. You will need to scroll down in the template to see the full set of options.

Item Description When sending items via Outlook object model Specifies what happens when a program attempts to send mail programmatically by using the Outlook object model. When sending items via CDO Specifies what happens when a program attempts to send mail programmatically by using CDO. When sending items via Simple MAPI Specifies what happens when a program attempts to send mail programmatically by using Simple MAPI. When accessing the address book via Outlook object model Specifies what happens when a program attempts to gain access to an address book by using the Outlook object model. When accessing the address book via CDO Specifies what happens when a program attempts to gain access to an address book by using CDO. When resolving names via Simple MAPI Specifies what happens when a program attempts to gain access to an address book by using Simple MAPI. When accessing address information via the Outlook object model Specifies what happens when a program attempts to gain access to a recipient field, such as To, by using the Outlook object model. When accessing address information via CDO Specifies what happens when a program attempts to gain access to a recipient field, such as To, by using CDO. When opening messages via Simple MAPI Specifies what happens when a program attempts to gain access to a recipient field, such as To, by using Simple MAPI. When responding to meeting and task requests via the Outlook object model Specifies what happens when a program attempts to send mail programmatically by using the Respond method on task requests and meeting requests. This method is similar to the Send method on mail messages. When executing Save As via the Outlook object model Specifies what happens when a program attempts to programmatically use the Save As command on the File menu to save an item. Once an item has been saved, a malicious program could search the file for e-mail addresses. When accessing the Formula property of a UserProperty object in the Outlook object model Specifies what happens when a user adds a Combination or Formula custom field to a custom form and binds it to an Address Information field. By doing this, code can be used to indirectly retrieve the value of the Address Information field by getting the Value property of the field. When accessing address information via UserProperties.Find in the Outlook object model Specifies what happens when a program attempts to search mail folders for address information using the Outlook object model.

Trusted Code tab

The Trusted Code tab is used to specify which Component Object Model (COM) add-ins are trusted and can be run without encountering the Outlook object model blocks. The following procedure describes how to use this feature.


Note   Before you can use the Trusted Code tab, you must first install the Trusted Code Control on the computer you are using to modify the security settings. For more information, see Installing the Outlook Trusted Code Control. You can obtain the Trusted Code Control from the Office Resource Kit. Details are included in “Obtaining the files required to customize security settings” in Configuring Outlook Security Features to Help Prevent Viruses.


To specify a trusted add-in

  1. Copy the dynamic-link library (DLL) or other file that is used to load the COM add-in to a location where the administrator creating the security setting has access to it.

    This file must be the same file used on the client computers that will run the COM add-in.

  2. On the Trusted Code tab, click Add and select the name of the DLL you want to add.
  3. Click Close on the form when you have finished.

The COM add-in can now run without prompts for Microsoft Office Outlook 2003 users who use this security setting. To remove a file from the Trusted Code list on the Trusted Code tab, select the file name and click Remove.


Note   The COM add-in must be coded to take advantage of the Outlook trust model in order for the add-in to run without prompts after being included in the Trusted Code list. If an add-in shows security prompts to users after being added to the Trusted Code list, you must work with the COM add-in developer to resolve the problem.

固定链接
单击隐藏此项的固定链接。
http://zjhuan.spaces.live.com/blog/cns!7771FF7C39DE7784!265.entry
添加评论
单击隐藏此项的评论。

Customizing Security Settings by Using the Outlook Security Template

You can modify default security settings for the Microsoft® Office Outlook® 2003 client by using the Outlook Security template, which you install as a form in Outlook. The template contains three tabs:

  • Outlook Security Settings
  • Programmatic Settings
  • Trusted Code

The settings on each of these tabs are described in Outlook Security Template Settings.

Note  If you are a user who wants to learn more about why some Outlook attachments are blocked, see Blocked attachments: The Outlook feature you love to hate. In addition, you can find methods for sharing files that are blocked by Outlook by reading About unblocking attachments.

When you first load the template, the settings are configured to enforce default security settings on the client.

Outlook Security Settings tab in the Default Security Settings dialog box

Creating a public folder for the security settings

Before modifying the security settings, you must create a public folder named Outlook Security Settings or Outlook 10 Security Settings on the Microsoft Exchange server on which you keep public folders. You create this folder by using one of those names exactly, in the root folder of the Public Folder tree. You must set the folder access control lists (ACLs) so that all users can read all items in the folder. However, only those users for whom you want to create or change security settings should have permission to create, edit, or delete items in the folder.

If you want multiple users to be able to edit or create items, and if the list of users can change at any time, you must create a security group that includes all users for whom you want to give permission to create or change security settings. This security group should have Owner permissions on the security folder.

After you create the folder, you can install the Outlook Security template and then make the changes you need.

Installing the Outlook Security template

Before you can modify security settings by using the Outlook Security template, you must publish the template as a form in the special public folder you created.

To install the Outlook Security template

  1. On a computer running Outlook, open OutlookSecurity.oft from the working directory where you installed the Outlook security tools.
  2. When prompted to select a folder, select the Outlook Security Settings or Outlook 10 Security Settings public folder that you created on the Exchange server, and then click the Open button.

    The template opens in Compose mode.

  3. On the Tools menu of the template, point to Forms, and then click Publish Form.

    The folder selected should be your current folder: Outlook Security Settings or Outlook 10 Security Settings.

  4. In the Form Name box, type Outlook Security Form.

    If you are using the security form from Outlook 2000, and if you are updating the form by publishing the newer form to the Outlook Security Settings folder, then in the Form Name box, type the same name as the previous security form (that is, you overwrite the previous security form). For more information about publishing a new security form over a previous one, see the next section.

  5. Click the Publish button to publish the security template in the Security Settings folder.

    You can now close the Outlook Security template. Do not save when prompted to save while closing the template.

Publishing a new security form over a previous version

There are two versions of the Outlook security form. The first version was released with the Outlook 2000 SR-1 security patch. The second version was released with later versions of Outlook, starting with Outlook 2002.

If you installed the security update for Outlook 2000, you may have an earlier version of the security form already published to the security folder. In this scenario, you should overwrite the previous form with the new copy, using the same name and message class. This installs the new form in place of the old one in the security folder.

If there are other forms in the security folder, you must open these forms and close them by using the Close button to correctly register any changes.

Modifying the default security settings

Use one of the following procedures to modify the default security settings in Outlook and store the new settings configuration in the special public folder you created for saving the settings. You can create a configuration for all Outlook users, or you can set up a configuration for a specific set of users.

To specify a default Outlook security setting for all users by using the Outlook Security template

  1. In Outlook, click the drop-down arrow next to New on the toolbar, and select Choose Form.
  2. Navigate to the template you created earlier (in the "Installing the Outlook Security Form" section), select the template by name, and then click Open.
  3. Click Default Security Settings for All Users, and specify the security settings you want.
  4. Scroll to the bottom of the template, and then click Close.

Alternatively, you may choose to create a group of customized security settings for a specific set of Outlook users.

To specify a group of custom security settings for a set of Outlook users by using the Outlook Security template

  1. In Microsoft Outlook, click the drop-down arrow next to New on the toolbar, and select Choose Form from the list.
  2. Navigate to the template you created earlier (in the "Installing the Outlook Security Template" section), select the template by name, and then click Open.
  3. Click Security Settings for Exception Group, and then type a name in the Security Group Name box that describes the group.
  4. In the Members box , type the name of each user who must have custom security settings.

    If the Exchange server you are running is an Exchange 2000 or later server, you can use distribution lists (only server-created security groups, not Outlook Contacts distribution lists) in the Members box. Otherwise, you cannot use distribution lists, and adding users from the Contacts Address Book is not supported.

  5. Specify the settings you need, and then click Close.

Note   For a security setting to apply to a user who is an administrator of the security settings public folder, the user (administrator) must be added to the member list of the security setting. It is not sufficient to have the administrator be a member of a distribution list that is listed in the member's box of the setting. You must add each administrator's name to the security setting. If you are using only a single default security group, you do not need to add the administrators' names.


The method that Outlook uses to determine which security settings to apply depends on the version of the Exchange server. Note that in all versions, however, Outlook finds custom security settings items based on the time the item was created, not the time it was last modified. If a user's name is entered as a member of more than one security group, the settings of the most recently created group apply.

If you are using Microsoft Exchange 5.5, item-level permissions are not applied to the custom security settings, so every user sees all of the custom security settings in the folder. When Outlook determines which item to use, it selects the most recently created item that applies for that user. Note that if the Default Security Settings item is the last item created, it is applied to the user even if the user is a member of an exception item. So that this problem does not occur, make sure that the Default Security Settings item is always the first item created in the folder. Any exception items—created later— take precedence over the Default Security Settings item.

If you are using Microsoft Exchange 2000 or later, item-level permissions are applied to the custom security settings, so users only see those items that apply to them. Unlike with Exchange 5.5, Outlook used with Exchange 2000 and later finds the correct custom security settings item, regardless of when the Default Security Settings item was created.

Details on all fields, values, and settings for the template can be found in the topic Outlook Security Template Settings.

Ensuring that security settings are properly created

In previous versions of Outlook, every time a setting was created you were prompted twice for credentials. This is no longer the case. In Outlook 2003, you are prompted for credentials only the first time you save a setting. You are not prompted for credentials on subsequent saves until you shut down and restart Outlook. Also, Outlook must be running in classic online mode, not cached mode or offline mode, in order to save security settings.

If no credentials are entered or if the wrong credentials are entered, an Operation Failed error message appears. At this point, the security setting has been created but does not work correctly because item-level permissions have not been applied. You must delete the security item and re-create it. If the item created is not deleted, the item is applied to everybody, including users to whom you did not intend to apply the item.

Editing security settings

If you add a user to the Members field of an existing security form, make sure that all aliases already present in the form are current and active.


Note   If you add the alias of a new member to an existing security form, the change may not be correctly registered unless you make other changes to the form as well. For example, you might toggle another setting on and off, or otherwise activate the form through some interaction. After you have added the new alias and activated the form, you can select Save from the File menu of the form to save your changes.

 
固定链接
单击隐藏此项的固定链接。
http://zjhuan.spaces.live.com/blog/cns!7771FF7C39DE7784!262.entry
添加评论
单击隐藏此项的评论。

Installing the Outlook Trusted Code Control

From:http://office.microsoft.com/en-us/assistance/HA011402921033.aspx
 

In Microsoft® Office Outlook® 2003, administrators can specify COM add-ins that are trusted by Outlook's security features and can be run without encountering the Outlook Object Model security blocks. In order to specify a COM add-in, administrators must first install the Trusted Code Control on the computer they are using to modify the security settings. The control does not need to be installed on client computers.


Note  You can obtain the Trusted Code Control from the Office Resource Kit. Details are included in “Obtaining the files required to customize security settings” in Configuring Outlook Security Features to Help Prevent Viruses.


To install and register the Trusted Code Control

  1. Copy Hashctl.dll from your working directory to the Windows® System32 folder on your administrative computer. For example, /Windows/system32.
  2. From the Start menu, click Run, then type the following command line in the box to register the control:

    regsvr32 hashctl.dll

  3. Copy the file Comdlg32.ocx from your working directory to the Windows System32 folder on your administrative computer.
  4. From the Start menu, choose Run, then type the following command line in the box to register the control:

    regsvr32 comdlg32.ocx

固定链接
单击隐藏此项的固定链接。
http://zjhuan.spaces.live.com/blog/cns!7771FF7C39DE7784!260.entry
添加评论
单击隐藏此项的评论。

How to Configuring Outlook Security Features to Help Prevent Viruses

From:http://office.microsoft.com/en-us/assistance/HA011402911033.aspx

Configuring Outlook Security Features to Help Prevent Viruses

The Microsoft® Outlook® security model includes a number of features to help protect users against viruses and worms that can be propagated through e-mail messages. The security-related features include object model blocks (such as limiting automated address book access), access to attachments, and so on. Security-related features are included in the product, but they can be customized. You can customize most of the features relating to security by using the Outlook security template. Your users must be using Outlook with an Exchange server to take advantage of the customizations that are modified by using the security template.


Note  You can also customize several features by using the registry instead of the Exchange Server security template. These features include the following: read as plain text, automatic picture download, and HTML mail zones. You can also lock down the settings by using policies. For more information about modifying these settings, see Helping Users Avoid Junk E-mail Messages in Outlook 2003. You can also customize how Outlook loads ActiveX controls in one-off forms. More information is provided later in this topic under Customizing how ActiveX controls behave in one-off forms.


Security settings are controlled by a custom form that is stored in a designated folder on the Microsoft Exchange server. After the form is published in the folder, you can use it create items in the folder to store the security settings. You can use a registry key setting to cause Outlook to reference these settings. To update these settings, you must be an authorized administrator.

The settings that you can configure by using the template can help provide a high level of security. However, the higher the level of security, the more limitations there are to Outlook functionality. Restrictions enforced by the Outlook security form include limits to specific types of attachments, heightened default security settings, and controlled access to the Outlook automation code.

Note  To learn more about how Outlook virus protection features work, see How Outlook helps to protect your computer from viruses.

Requirements for customized security settings

As an administrator, you can use the template to customize the Outlook security settings to help meet your organization's needs. For example, you can help control the types of attached files blocked by Outlook, modify the Outlook object model security and warning levels, and specify user or group security levels. However, to customize these settings, your users must have the appropriate Outlook configuration.

To enable custom security settings, your users must be using Outlook with an Exchange server. You cannot modify most of these settings if your organization is using Outlook with a third-party e-mail service. (The exception is for attachment-blocking settings, which can be configured when using a third-party e-mail service.)


Caution   Lowering any default security settings may increase your risk of virus execution or propagation. Use caution and read the documentation before you modify these settings.


Enabling customized security settings for users

When you create custom security settings for Outlook by using the Outlook security template, the settings are stored in messages in a top-level folder in the Public Folders tree. Users who need these settings must have a special registry key set on their computers for the settings to apply.

When the key is present, Outlook searches the Exchange server for custom security settings to apply to a user. If these settings are found, they are applied. Otherwise, the default security settings in Outlook are used.

Users without the special key have the default Outlook security settings that are in the product.

Note that in some cases, administrator-defined security settings may interact with security settings defined by the user. Specifically, users can customize attachment-blocking behavior, if you, as administrator, have given permission.

Obtaining the files required to customize security settings

The files you need to configure the security settings and publish the form to enforce the settings are included in a self-extracting executable named Admpack.exe. You can find this downloadable file on the Office XP Resource Kit Downloads page. It is not installed by default from the Office Resource Kit Setup program. The four administrative files are as follows:

  • OutlookSecurity.oft

    An Outlook template that enables you to customize Outlook client security settings that are saved in a public folder on the Exchange server. The OFT is the form that you publish into the special public folder that Outlook can be directed to reference for client security settings.

  • Hashctl.dll and Comdlg32.ocx

    Two controls used by the form.

  • Readme.doc

    A document that provides information on the values and settings available in the template and describes how to deploy the new settings on the Exchange server.

Customized security settings caveats

There are a couple caveats to keep in mind when deploying customized security settings for Outlook 2003:

  • Outlook must be restarted to get the customized settings.

    The first time a user starts Outlook after the customized security settings have been applied, the user sees default administrative settings and not the exception or default form that has been set. The user needs to close Outlook and then restart Outlook again to get the correct security settings and permissions.

  • No customized settings are applied in Personal Information Manager (PIM)-only mode.

    In PIM mode, Outlook uses the default security settings. No administrator settings are looked for or used in this mode.

Customizing how ActiveX controls behave in one-off forms

When Outlook receives a message containing a form definition, the item is considered to be a one-off form. To help prevent unwanted script and controls from running in one-off forms, Outlook does not load ActiveX® controls in one-off forms by default. You can control this behavior by setting a registry key or policy in HKCU/Software/Policies/Microsoft/Office/11.0/Outlook/Security or HKCU/Software/Microsoft/Office/11.0/Outlook/Security.


Note   This policy is not provided in the Outlk11.adm file in the original retail product but is included in the updated ADM files released later. You can download the updated Office 2003 Policy Template Files and Deployment Planning Tools (Office-2003-SP1-ADMs-OPAs-and-Explain-Text.exe). You can find this downloadable file on the Office 2003 Resource Kit Downloads page.


Value name: AllowActiveXOneOffForms

Value type: DWORD

Value data: [ 0 | 1 | 2 ]

0 - Only load controls that are in the following list.

1 - Allow only safe controls.

2 - Allow all ActiveX controls.

If the registry key is not present, Outlook loads only controls listed here. This is the default behavior. The following controls can be used in one-off forms:

  • Controls from fm20.dll
  • Microsoft Office Outlook Rich Format Control
  • Microsoft Office Outlook Recipient Control
  • Microsoft Office Outlook View Control
固定链接
单击隐藏此项的固定链接。
http://zjhuan.spaces.live.com/blog/cns!7771FF7C39DE7784!259.entry
添加评论
单击隐藏此项的评论。
2006/5/26

用OutLook宏将邮件转存到sql数据库

  通过编写outlook宏来实现将邮件数据存储到sql数据库中。
Private Sub Application_NewMail()
    Dim myFolder As Outlook.MAPIFolder
    Dim x As Integer
    Dim i As Integer
   
    Dim attatchmentstr As String
    Dim com As ADODB.Command
    Set com = New ADODB.Command
    Dim prm As ADODB.Parameter
    Dim cn As ADODB.Connection
    Set cn = New ADODB.Connection
   
    'Set Connection properties
    cn.ConnectionString = "Data Source=192.168.5.37;Initial Catalog=MailTest;Persist Security Info=True;User ID=sa;Password=password123"
    cn.ConnectionTimeout = 30
    cn.Open
    If cn.State = adStateOpen Then _
        Set com.ActiveConnection = cn
    com.CommandText = "InsertPersonBasicInfoFromNotes"
    com.CommandType = adCmdStoredProc
    com.CommandTimeout = 30
   
    Dim MailAttachments As Outlook.Attachments
   
    Set myFolder = Application.GetNamespace("MAPI").GetDefaultFolder(6)
       
    For x = myFolder.Items.Count To 1 Step -1
    If (myFolder.Items.Item(x).UnRead = True) Then
       
        Set MailAttachments = myFolder.Items.Item(x).Attachments
        attatchmentstr = ""
        If MailAttachments.Count > 0 Then
            Dim FolderPath As String
            FolderPath = "d:/OA"
            Set fs = CreateObject("Scripting.FileSystemObject")
            If fs.FolderExists(FolderPath) = False Then
                fs.CreateFolder (FolderPath)
            End If
            If (myFolder.Items.Item(x).To = "test21") Then
                FolderPath = "d:/OA/HR"
            Else
                FolderPath = "d:/OA/resume"
            End If
            If fs.FolderExists(FolderPath) = False Then
                fs.CreateFolder (FolderPath)
            End If
            Dim mailDate As Date
            mailDate = myFolder.Items.Item(x).CreationTime
            FolderPath = FolderPath + "/" + Format(mailDate, "yyyyMM")
            If fs.FolderExists(FolderPath) = False Then
                fs.CreateFolder (FolderPath)
            End If
        End If
               
        If (com.Parameters.Count = 0) Then
            Set prm = com.CreateParameter("ApplyJob", adBSTR, adParamInput, 1024, myFolder.Items.Item(x).Subject)
            com.Parameters.Append prm
            Set prm = com.CreateParameter("PersonName", adBSTR, adParamInput, 1024, myFolder.Items.Item(x).Subject)
            com.Parameters.Append prm
            Set prm = com.CreateParameter("ApplyDate", adDate)
            prm.Value = myFolder.Items.Item(x).CreationTime
            com.Parameters.Append prm
            Set prm = com.CreateParameter("Body", adBSTR)
            prm.Value = myFolder.Items.Item(x).HTMLBody
            com.Parameters.Append prm
            Set prm = com.CreateParameter("AttachFilePath", adBSTR, adParamInput, 1024, "")
            com.Parameters.Append prm
            Set prm = com.CreateParameter("Status", adInteger, adParamInput, 4, 0)
            com.Parameters.Append prm
            If (myFolder.Items.Item(x).To = "test21") Then
                Set prm = com.CreateParameter("FromNotes", adInteger, adParamInput, 4, 1)
            Else
                Set prm = com.CreateParameter("FromNotes", adInteger, adParamInput, 4, 2)
            End If
            com.Parameters.Append prm
            Set prm = com.CreateParameter("PersonBasicInfoID", adInteger, adParamInput, 4, 0)
            com.Parameters.Append prm
        Else
            For i = 0 To com.Parameters.Count - 1
                Select Case com.Parameters.Item(i).Name
                        Case "@ApplyJob"
                            com.Parameters.Item(i).Value = myFolder.Items.Item(x).Subject
                        Case "@PersonName"
                            com.Parameters.Item(i).Value = myFolder.Items.Item(x).SenderName
                        Case "@ApplyDate"
                            com.Parameters.Item(i).Value = myFolder.Items.Item(x).CreationTime
                        Case "@Body"
                            com.Parameters.Item(i).Value = myFolder.Items.Item(x).HTMLBody
                        Case "@AttachFilePath"
                            com.Parameters.Item(i).Value = attatchmentstr
                        Case "@Status"
                            com.Parameters.Item(i).Value = 0
                        Case "@FromNotes"
                            If (myFolder.Items.Item(x).To = "test21") Then
                                com.Parameters.Item(i).Value = 1
                            Else
                                com.Parameters.Item(i).Value = 2
                            End If
                End Select
            Next i
        End If
       
        Dim rs As New ADODB.Recordset
        Set rs = com.Execute
        Dim fld As ADODB.Field
        Set Flds = rs.Fields
        If MailAttachments.Count > 0 Then
             While (Not rs.EOF)
                For Each fld In Flds
                    FolderPath = FolderPath + "/" + CStr(fld.Value)
                Next
                rs.MoveNext
            Wend
       
            If fs.FolderExists(FolderPath) = False Then
                    fs.CreateFolder (FolderPath)
            End If
            For i = 1 To MailAttachments.Count
                MailAttachments.Item(i).SaveAsFile (FolderPath + "/" + MailAttachments.Item(i).FileName)
                attatchmentstr = attatchmentstr + MailAttachments.Item(i).FileName + ";"
            Next i
        End If
        rs.Close
        myFolder.Items.Item(x).UnRead = False
    Else
        'myFolder.Items.Item(x).UnRead = True
        Exit For
    End If
    Next x
   
    If cn.State = adStateOpen Then _
        cn.Close
   
   
   
   
End Sub
固定链接
单击隐藏此项的固定链接。
http://zjhuan.spaces.live.com/blog/cns!7771FF7C39DE7784!258.entry
添加评论
单击隐藏此项的评论。
2006/4/30

ASC码对照表


asc码对照表

 
固定链接
单击隐藏此项的固定链接。
http://zjhuan.spaces.live.com/blog/cns!7771FF7C39DE7784!255.entry
添加评论
单击隐藏此项的评论。
2006/4/27

asp.net数据格式的Format-- DataFormatString

asp.net数据格式的Format-- DataFormatString 转自:  编辑:dagger  
    我们在呈现数据的时候,不要将未经修饰过的数据呈现给使用者。例如金额一万元,如果我们直接显示「10000」,可能会导致使用者看成一千或十万,造成使用者阅读数据上的困扰。若我们将一万元润饰后输出为「NT$10,000」,不但让使比较好阅读,也会让使用者减少犯错的机会。
下列画面为润饰过的结果:
上述数据除了将DataGrid Web 控件以颜色来区隔记录外,最主要将日期、单价以及小计这三个计字段的数据修饰的更容易阅读。要修饰字段的输出,只要设定字段的DataFormatString 属性即可;其使用语法如下:

DataFormatString="{0:格式字符串}"

我们知道在DataFormatString 中的 {0} 表示数据本身,而在冒号后面的格式字符串代表所们希望数据显示的格式;另外在指定的格式符号后可以指定小数所要显示的位数。例如原来的数据为「12.34」,若格式设定为 {0:N1},则输出为「12.3」。其常用的数值格式如下表所示:

格式字符串 资料 结果
"{0:C}" 12345.6789 $12,345.68
"{0:C}" -12345.6789 ($12,345.68)
"{0:D}" 12345 12345
"{0:D8}" 12345 00012345
"{0:E}" 12345.6789 1234568E+004
"{0:E10}" 12345.6789 1.2345678900E+004
"{0:F}" 12345.6789 12345.68
"{0:F0}" 12345.6789 12346
"{0:G}" 12345.6789 12345.6789
"{0:G7}" 123456789 1.234568E8
"{0:N}" 12345.6789 12,345.68
"{0:N4}" 123456789 123,456,789.0000
"Total: {0:C}" 12345.6789 Total: $12345.68

其常用的日期格式如下表所示:

格式 说明 输出格式
d 精简日期格式 MM/dd/yyyy
D 详细日期格式 dddd, MMMM dd, yyyy
f 完整格式 (long date + short time) dddd, MMMM dd, yyyy HH:mm
F
完整日期时间格式
(long date + long time)
dddd, MMMM dd, yyyy HH:mm:ss
g 一般格式 (short date + short time) MM/dd/yyyy HH:mm
G 一般格式 (short date + long time) MM/dd/yyyy HH:mm:ss
m,M 月日格式 MMMM dd
s 适中日期时间格式 yyyy-MM-dd HH:mm:ss
t 精简时间格式 HH:mm
T 详细时间格式 HH:mm:ss
固定链接
单击隐藏此项的固定链接。
http://zjhuan.spaces.live.com/blog/cns!7771FF7C39DE7784!253.entry
添加评论
单击隐藏此项的评论。
2006/3/31

(转)JavaScript应用:Iframe自适应其加载的内容高度

<script  language=javascript>
   function iframeAutoFit()
   {
      try
      {
         if(window!=parent)
         {
          var a = parent.document.getElementsByTagName("IFRAME");
            for(var i=0; i<a.length; i++) //author:meizz
            {
               if(a[i].contentWindow==window)
               {
                   var h = document.body.scrollHeight;
                   if(document.all) {h += 4;}
                   if(window.opera) {h += 1;}
                   a[i].style.height = h;
               }
            }
         }
      }
      catch (ex)
      {
         alert("脚本无法跨域操作!");
      }
   }
   if(document.attachEvent)  window.attachEvent("onload",  iframeAutoFit); 
   else  window.addEventListener('load',  iframeAutoFit,  false); 
   </script> 
固定链接
单击隐藏此项的固定链接。
http://zjhuan.spaces.live.com/blog/cns!7771FF7C39DE7784!252.entry
添加评论
单击隐藏此项的评论。
2006/3/10

.NET架构与模式

作者:微软架构与模式小组

http://editblog.csdn.net/msdncolumn/archive/2004/12/30/1101.aspx

什么是架构

    软件体系结构通常被称为架构,指可以预制和可重构的软件框架结构。架构尚处在发展期,对于其定义,学术界尚未形成一个统一的意见,而不同角度的视点也会造成软件体系结构的不同理解,以下是一些主流的标准观点。

    ANSI/IEEE 610.12-1990软件工程标准词汇对于体系结构定义是:“体系架构是以构件、构件之间的关系、构件与环境之间的关系为内容的某一系统的基本组织结构以及知道上述内容设计与演化的原理(principle)”。

    Mary Shaw和David Garlan认为软件体系结构是软件设计过程中,超越计算中的算法设计和数据结构设计的一个层次。体系结构问题包括各个方面的组织和全局控制结构,通信协议、同步,数据存储,给设计元素分配特定功能,设计元素的组织,规模和性能,在各设计方案之间进行选择。Garlan & Shaw模型[1]的基本思想是:软件体系结构={构件(component),连接件(connector),约束(constrain)}.其中构件可以是一组代码,如程序的模块;也可以是一个独立的程序,如数据库服务器。连接件可以是过程调用、管道、远程过程调用(RPC)等,用于表示构件之间的相互作用。约束一般为对象连接时的规则,或指明构件连接的形式和条件,例如,上层构件可要求下层构件的服务,反之不行;两对象不得递规地发送消息;代码复制迁移的一致性约束;什么条件下此种连接无效等。

    关于架构的定义还有很多其他观点,比如Bass定义、Booch & Rumbaugh &Jacobson定义、Perry & Wolf模型[7]、Boehm模型等等,虽然各种定义关键架构的角度不同,研究对象也略有侧重,但其核心的内容都是软件系统的结构,其中以Garlan & Shaw模型为代表,强调了体系结构的基本要素是构件、连接件及其约束(或者连接语义),这些定义大部分是从构造的角度来甚至软件体系结构,而IEEE的定义不仅强调了系统的基本组成,同时强调了体系结构的环境即和外界的交互。

什么是模式

    模式(Pattern)的概念最早由建筑大师Christopher Alexander于二十世纪七十年代提出,应用于建筑领域,八十年代中期由Ward Cunningham和Kent Beck将其思想引入到软件领域,Christopher Alexander将模式分为三个部分:首先是周境(Context,也可以称着上下文),指模式在何种状况下发生作用;其二是动机(System of Forces),意指问题或预期的目标;其三是解决方案(Solution),指平衡各动机或解决所阐述问题的一个构造或配置(Configuration)。他提出,模式是表示周境、动机、解决方案三个方面关系的一个规则,每个模式描述了一个在某种周境下不断重复发生的问题,以及该问题解决方案的核心所在,模式即是一个事物(thing)又是一个过程(process),不仅描述该事物本身,而且提出了通过怎样的过程来产生该事物。这一定义已被软件界广为接受。

    软件模式的应用对软件开发产生了重大的作用,主要表现在:

  • 软件模式是人们在长期的设计软件、管理组织软件开发等实践中大量经验的提炼和抽象,是复用软件设计方法、过程管理经验的有力工具。模式类似于拳击中的组合拳,它提供了一系列软件开发中的思维套路。如,通过模式的使用,有利于在复杂的系统中产生简洁、精巧的设计。
  • 软件模式为我们提供了一套简洁通用的设计、管理、组织方面的词汇,同时模式也为我们提供了一个描述抽象事物的规范标准,可大大促进软件开发过程中人与人之间的交流,而软件开发中的交流是至关重要的,“软件项目失败的原因最终都可追溯到信息没有及时准确地传递到应该接收它的人”。

架构和模式的关系

    因为架构(Architecture)和模式(Pattern)在当前的软件开发中经常地被提及,可是很多人容易混淆这两个术语,而对此,学术界也没有一个非常统一的定义。

    架构和模式应该是一个属于相互涵盖的过程,但是总体来说Architecture更加关注的是所谓的High-Level Design,而模式关注的重点在于通过经验提取的“准则或指导方案”在设计中的应用,因此在不同层面考虑问题的时候就形成了不同问题域上的Pattern。模式的目标是,把共通问题中的不变部分和变化部分分离出来。不变的部分,就构成了模式,因此,模式是一个经验提取的“准则”,并且在一次一次的实践中得到验证,在不同的层次有不同的模式,小到语言实现(如Singleton)大到架构。在不同的层面上,模式提供不同层面的指导。根据处理问题的粒度不同,从高到低,模式分为3个层次:架构模式(Architectural Pattern)、设计模式(Design Pattern)、实现模式(Implementation Pattern).架构模式是模式中的最高层次,描述软件系统里的基本的结构组织或纲要,通常提供一组事先定义好的子系统,指定它们的责任,并给出把它们组织在一起的法则和指南。比如,用户和文件系统安全策略模型,N-层结构,组件对象服务等,我们熟知的MVC结构也属于架构模式的层次。一个架构模式常常可以分解成很多个设计模式的联合使用。设计模式是模式中的第二层次,用来处理程序设计中反复出现的问题。例如,[GOF95][2]总结的23个基本设计模式——Factory Pattern, Observer Pattern等等。实现模式是最低也是最具体的层次,处理具体到编程语言的问题。比如,类名,变量名,函数名的命名规则;异常处理的规则等等。

    相对于系统分析或者设计模式来说,体系结构从更高的层面去考虑问题,所以关注的问题就体现在“不变”因素上,比如系统部署中,更加关心应用程序的分层分级设计,而在这个基础之上提出的部署方案,才是架构考虑的重点。体系结构关心应用程序模式,更加体现在通过技术去解决这些业务差异带来的影响,关心是否是分布式应用程序,关心系统分层是如何设计,也关心性能和安全,因此在这样的情况之下,会考虑集群,负载平衡,故障迁移等等一系列技术。

    希望通过定义的方式来区分架构和模式是不太可能的,因为本来就是交互交叉和提供服务的,它实际上是架构模式,而不是设计模式。在大部份情况下,表现为下面几个设计模式之一:Strategy模式、Mediator模式、Composite模式、Observer模式。对于熟悉架构设计的系统架构师而言,似乎可以用如下来解释架构和模式之间的关系:架构是Hight-Level Design,着眼于不同业务中共性的解决方案,而模式是General Principle(通用原理)。

企业解决方案的构建模式

    企业级业务解决方案是公司实现其业务的赌注,它们通常极其复杂,而且性能必须不负众望。它们不仅必须具有高可用性和伸缩性以应对不可预知的使用,而且还必须具有适应性和预见性以适应快速变化的业务要求。最佳解决方案是那些由一组更小的、简单的、能够可靠且有效地解决简单问题的机制组成的解决方案。在构建更大、更复杂的系统过程中,将这些简单的机制组合在一起,从而形成更大的系统。对这些简单机制的认识来之不易。它通常存在于有经验的开发人员和体系结构设计者的头脑中,并且是他们潜意识中自然带到项目中的重要知识。

    模式对于开发人员和体系结构设计者非常有用,因为它们:

  • 记录能够正常工作的简单机制。
  • 为开发人员和体系结构设计者提供通用的词汇和分类法。
  • 允许以模式组合的方式简明扼要地描述方案。
  • 允许重复使用体系结构、设计和实现决策。

模式可以记录简单机制

    模式描述给定上下文中反复出现的问题,并基于一组指导性影响因素来建议解决方案。解决方案通常是一种简单的机制,是为了解决模式中所标示出的问题而一起工作的两个或多个类、对象、服务、进程、线程、组件或节点之间的协作。

    您正在构建一个报价应用程序,其中有一个类负责管理系统中的所有报价。很重要的一点是,所有报价都应与该类的一个(而且只与一个)实例进行交互。如何构造您的设计,以便从该应用程序中只能访问该类的一个实例?

    解决该问题最简单的方案就是创建一个具有私用构造函数的QuoteManager类,以便任何其他类都不能实例化它。此类包含QuoteManager的一个静态实例,并使用名为GetInstance()的静态方法返回。此代码大体如下所示:

public class QuoteManager
{
    //注意:仅适用于单线程应用程序
    private static QuoteManager _Instance = null;

    private QuoteManager() {}

    public static QuoteManager GetInstance()
    {
        if (_Instance==null)
        {
            _Instance = new QuoteManager ();
        }
        return _Instance;
    }

    //... QuoteManager提供的函数
}

    您可能已经像其他许多开发人员那样通过类似的方式解决过类似的问题。实际上,注意反复出现的问题并寻求解决方案的模式作者已经屡次发现了这种实现,提取出了通用解决方案并将这种问题-解决方案对称为Singleton模式[GOF95]。

问题-解决方案对模式


图1 简化的Singleton模式

    通过将图1中简化的模式示例与QuoteManager源代码进行比较,阐明了模式(通用问题-解决方案对)和模式应用程序(针对非常具体的问题的具体解决方案)之间的区别。模式级别的解决方案是多个类之间简单但极其顺畅的协作。模式中的通用协作专门适用于QuoteManager类,提供了用来控制报价应用程序中实例化的机制。显然,您可以稍微修改一下某种模式以满足局部的特定要求,所以同一种模式可以应用于无数个应用程序。

    所编写的模式提供了一种记录简单且经过证实的机制的有效方法。模式是以特定格式编写的,这一点对于装载复杂思想的容器非常有用。这些模式在被记载和起名之前,就早已存在于开发人员的大脑及其代码中。

位于不同级别的模式

    模式存在于多个不同的抽象级别中。考虑另一个示例(这次所处的抽象级别比源代码要高一级):

    您要设计一个基于Web的报价应用程序,其中包含大量业务和表示逻辑,这些逻辑反过来依赖大量平台软件组件来提供适当的执行环境。如何在高级别组织系统以使其在具有灵活、松耦合性的同时仍具有高内聚性?

    此问题的解决方案之一涉及到按一系列层来组织系统,每层包含大致位于同一抽象级别的元素。随后,确定每一层中的依赖性,并确定采用严格还是宽松的分层策略。接着,决定是打算创建自定义的分层方案,还是采用以前由其他人记录的分层方案。在本例中,假设您决定使用众所周知的分层策略:表示、业务逻辑和数据访问各占一层。图2显示了分层方案的可能外观。


图2 报价应用程序的层

    如果您总是按这种方式设计系统,说明您已经在不依赖于任何广义模式的情况下使用该模式。即便如此,您还可能因多种原因而希望了解支撑这种设计方法的模式。您可能迫切想知道为何经常以这种方式构建系统,或者可能在寻找更理想的方法来解决此模式不能完全解决的问题。使用层作为高级别组织方法是Layers(层)模式[Buschmann96][3]中描述的完善模式。图3显示了该模式的简化版本。


图3 简化的Layers模式

    这个简单的应用程序组织策略有助于解决软件开发中面临的两个挑战:依存关系的管理和对可交换组件的需求。如果在构建应用程序时没有一个考虑周全的依存关系管理策略,会导致组件易损坏且不牢靠,从而导致对它们进行维护、扩展和替代时存在较大的困难,而且成本较高。

    Layers模式中的工作机制比Singleton中的工作机制更精细。对于Layers,首次协作是在设计时发生在类之间,这是由于分层组织将对更改源代码所带来的影响局部化,从而防止所做的更改贯穿到整个系统。第二次协作发生在运行时:某层中相对独立的组件变得可与其他组件交换,再一次使系统其余部分不受影响。

    尽管Layers模式的通用性足以应用于诸如网络协议、平台软件和虚拟机之类的领域,但是它无法解决企业类业务解决方案中存在的某些特定问题。例如,除通过分解来管理复杂性(由Layers解决的基本问题)外,业务解决方案开发人员还需要进行适当组织,以便有效地重复使用业务逻辑并保留与昂贵资源(如数据库)的重要连接。解决此问题的方法之一就是使用Three-Layered Application(三层应用程序)模式。图4显示了该模式的简化说明。


图4 简化的Three-Layered Application

    同样,在模式(Three-Layered Application)和模式应用程序(报价应用程序分层模型)之间存在区别。模式是有关应用程序组织主题的通用问题-解决方案对,而模式应用程序是通过创建具体的层来解决非常具体的问题。

模式的优化

    Three-Layered Application实际上是在Layers的基础上进行的简单优化;在Layers中确定的上下文、影响因素和解决方案仍适用于Three-Layered Application,但反之不行。也就是说,Layers模式约束着Three-Layered Application模式,而Three-Layered Application模式优化了Layers模式。

    您为某个发展迅速的成功企业构建了一个报价应用程序。现在,您希望通过向业务合作伙伴公开自己的报价引擎并将其他合作伙伴服务(如配送)集成到该报价应用程序中来扩展该应用程序。您将如何构造自己的业务应用程序以提供和享受服务?

    此问题的解决方案之一是通过将其他与服务相关的职责添加到每一层中来扩展Three-Layered Application。在业务层添加了以下职责:通过Service Interfaces(服务接口)向客户应用程序提供一组简化的操作。数据访问层的职责拓宽到了数据库和主机集成之外,以包括与其他服务提供者的通信。将数据访问层中的这个附加功能封装到服务接口组件中,这些组件负责连接到服务(同步和异步)、管理服务的基本会话状态并向业务流程组件通知与服务相关的重大事件。

    Three-Layered Services Application(三层服务应用程序)(图5)记录了该问题-解决方案对。


图5 简化的Three-Layered Services Application

    将Three-Layered Services Application模式应用于报价应用程序示例将形成如下模型。


图6 应用于报价应用程序的Three-Layered Services Application

    请注意这些模式之间的关系(请参阅图7)。Layers引进了一个用来组织软件应用程序的基本策略。Three-Layered Application优化了此概念,并将它限制在需要重复使用业务逻辑、灵活部署和高效使用连接的业务系统的范围内。Three-Layered Services Application又在Three-Layered Application的基础上进行了优化,并对设计进行了扩展,以便在提供和使用其来源千差万别的数据和逻辑时,将这些数据和逻辑处理为粒状元素。


图7 相关模式的优

    向特定层中添加其他类型的组件并不是管理这种日益增长的复杂性的唯一方法。正如复杂性所证实的那样,设计人员通常在应用程序中创建其他层来承担该职责。例如,一些设计人员将服务接口移到一个单独的层中。而另外一些设计人员将业务层分隔成域层和应用程序层。在任何情况下,您有时可能会看到某些设计人员在使用此模式来满足复杂要求时,有时会将这三层扩展到四层、五层或者甚至六层。与之相反,Layers模式也用在相对简单的客户端-服务器应用程序中。

    解决方案简述:术语“解决方案”有两种截然不同的含义:其一是表示模式本身的一部分(如某上下文中包含的问题-解决方案对);其二是表示业务解决方案。在使用“业务解决方案”这一术语时,它是指专用来满足一组特定的功能和操作业务要求的软件密集型系统。软件密集型系统意味着您不只是关心软件,而且还必须将该软件部署到硬件处理节点以提供整体的技术解决方案。而且,所考虑的软件不仅包括自定义开发的软件,而且包括购买的软件基础结构和平台组件,所有这些都被集成在了一起。

结束语

    以.NET为代表的Microsoft产品线向我们展示了“架构为基础,模式为指导”的企业解决方案设计理念,秉承微软产品一贯以来的简单易用以外,同时我们将看到使用.NET构建企业应用平台上使用.NET的优势。毫不夸张地说,.NET不是第一个体现架构和模式的软件应用平台,确是目前为止最后的实现了架构和模式的平台,在随后的文章介绍中,你将会发现,架构设计和模式应用会是如此简单。


[1] 《软件体系结构(影印版)》,科学出版社2004年1月1日出版。Mary Shaw、David Garlan合著,原文书名《Software Architecture: Perspectives on an Emerging Discipline》。

[2] GoF95,《设计模式——可复用面向对象软件的基础》,Erich Gamma、Richard Helm等著,英文版本《Design Patterns: Elements of Reusable Object-Oriented Software》,这是设计模式领域的经典之作,它结合设计实例从面向对象的设计中精选出23个设计模式,总结了面向对象设计中最有价值的经验,并且用简洁可复用的形式表达出来。

[3] [Buschmann96] Buschmann,Frank,《Pattern-Oriented Software Architecture》,John Wiley & Sons Ltd,1996。中文版《面向模式的软件体系结构》,2003年1月机械工业出版社出版。

 
原创粉丝点击