Friday, January 14, 2005

Mutil Tier Structure .Net Sample


Solution: Projects Name Space Objects File

----------Portal Corp.Portal Login Login.aspx.cs
----------Common Corp.Portal.Common CommonUtil CommonUtil.cs
SqlHelper SqlHelper.cs
----------AdminInfo Corp.Portal.Admin.Info UserInfo UserInfo.cs
UserProfile UserProfile.cs
LoginResults EnumInfo.cs
MenuInfo MeneInfo.cs
RoleInfo RoleInfo.cs
GroupInfo GroupInfo.cs
----------AdminBAL Corp.Portal.Admin.BAL UserBAL UserBAL.cs
----------AdminDAL Corp.Portal.Admin.DAL UserDAL UserDAL.cs


=================================================
Login.aspx.cs Corp.Portal
=================================================
protected void btnLogin_Click(Object sender, EventArgs e)
{
UserInfo oUser = new UserInfo(UserDAL.GetUserByEmail(null,null,UserEmail.Text));
if (oUser.us_login == null) {
//Login failed
}
LoginResults result = UserBAL.LoginUser(username, password, "W");
//LoginResults.LoginOK, LoginClientNotAllowed, LoginInvalidUser ...
//if good
UserProfile oUP = UserBAL.GetUserProfile(oUser.us_login, "W");
//Set Session and more process
}

=================================================
EnumInfo.cs Corp.Portal.Admin.Info
=================================================
public enum LoginResults
{
LoginOK = 0,
LoginFailed,
LoginException,
LoginInvalidUser,
LoginNotAllowed,
LoginClientNotAllowed
}

=================================================
UserInfo.cs Corp.Portal.Admin.Info
=================================================
public class UserInfo
{
//Properties
public string us_login;
public string us_online;
...
//A valid DataSet containing a User record in a DataTable
public UserInfo(DataSet ds)
{
LoadUserInfo(ds.Tables[0].Rows[0]);
}
//A valid DataRow representing a User record
public UserInfo(DataRow dr)
{
LoadUserInfo(dr);
}
private void LoadUserInfo(DataRow dr)
{
this.us_login = dr["us_login"].ToString();
...
}
public bool IsOnline();

}


=================================================
UserProfile.cs Corp.Portal.Admin.Info
=================================================
public class UserProfile
{
//Properties
public UserInfo User;
public Hashtable Roles;
public Hashtable Groups;
public Hashtable Applications;
public Stack History;

public UserProfile()
{
this.User = new UserInfo();
this.Roles = new Hashtable();
this.History = new Stack(5);
}
public bool IsInRole(string sRoleCode);
public bool IsInGroup(string sGrpCode);
...
}

=================================================
UserBal.cs Corp.Portal.Admin.BAL
=================================================
public static LoginResults LoginUser(string sLogin, string sPwd, string sClientType)
{
UserInfo oUser = UserDAL.GetUserInfo(null,null,sLogin);
//if good, update user last login
UserDAL.UpdateUserLastLogin(null,sLogin);
//validate the supplied password
string pwdHash = CommonUtil.CreatePasswordHash(sPws, oUser.us_pwdsalt);
if (!pwdHash.Equals(oUser.us_password)) return LoginResults.LoginFailed;
}

public static UserProfile GetUserProfile(string sLogin, string sClientType)
{
SqlConnection cn = null;
DataSet dsGroup = null;
DataSet dsMenu = null;
GroupInfo oGroup = null;
MenuInfo oMenu = null;
UserProfile oProfile = new UserProfile();
cn = new SqlConnection(SqlHelper.GetConnectionString(null));
cn.Open();
oProfile.User = UserDAL.GetUserInfo(null, cn, sLogin);
dsGroup = GroupDAL.GetGroupListByUser(null, cn, sLogin);
//for each row in dsGroup
oGroup = new GroupInfo(dsGroup.Tables[0].Rows[i]);
oProfile.Groups.Add(oGroup.gr_code, oGroup);
}

=================================================
UserDal.cs Corp.Portal.Admin.DAL
=================================================
public static DataSet GetUserByEmail(SqlTransaction tr, SqlConnection cn, string sEmail)
{
bool mustDisposeConnection = false;
SqlCommand cmd = null;
StringBuilder sb = new StringBuilder();
sb.Append("SELECT * from Users ");
sb.Append("WHERE us_email = @us_email");
cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = sb.ToString();
cmd.Parameters.Add("@us_email", SqlDbType.VarChar, 128).Value = sEmail;
if (tr == null)
{
if (cn == null)
{
try
{
cn = SqlHelper.GetConnection(SqlHelper.GetConnectionString(null));
mustDisposeConnection = true;
}
catch (Exception ex)
{
...
}
}
try
{
return SqlHelper.ExecuteDataset(cn, cmd);
}
catch
{
...
}
finally
{
if (mustDisposeConnection)
{
if (cn.State == ConnectionState.Open)
cn.Close();
cn.Dispose();
}
}
}
else
{
try
{
return SqlHelper.ExecuteDataset(tr, cmd);
}
catch (Exception ex)
{
...
}
}
}

Tuesday, December 21, 2004

Tech Link

Microsoft 社区
http://www.microsoft.com/china/MSDN/library/default.mspx MSDN技术资源库
http://www.microsoft.com/china/technet/default.mspx Microsoft Tectnet
http://blog.joycode.com/ 博客堂 http://www.cnblogs.com/ 博客园
http://www.cnblogs.com/team/DesignPattern.html DotNet Design & Pattern团队
http://www.microsoft.com/China/Community/ Microsoft中国社区
http://www.gotdotnet.com/ GotDotNet: The Microsoft .NET Framework Community
http://www.csdn.net/ 中国开发者网络
http://msdn.microsoft.com/library/chs/ MSDN Library 简体中文
http://www.blogcn.com/ 博客中文站
http://www.umlchina.com/

http://www.tianyaclub.com/new/Publicforum/Content.asp?idWriter=0&Key=0&strItem=itinfo&idArticle=8161&flag=1 站长必去的10个网站


分层开发思想与小笼包
三层开发中容易犯的错误

星火燎原

Fire3’s Blog:Linux,Open Source,Google

[TDD开发的全过程]


.Net
ASP.NET Forms Authentication Basics
.NET设计模式系列文章
http://www.royaloo.com/articles/articles_2002/dotNetFAQ_content.htm
.NET Framework FAQ 作者Andy McMullan 译者 荣耀
http://www.dotnettools.org/2005/doc/entlib/EntLib001.htm 将Enterprise Library 放到你的应用或产品中
通过 Web 服务传递数据 http://www.microsoft.com/china/MSDN/library/data/dataAccess/hcvb04vb04i7.mspx
卢彦——利用XML实现通用WEB报表打印
讨论创建基于WSE的报表打印服务及其实现 http://msdnportal.csdn.net/Read.aspx?C=6&S=1ce99830-e58b-4729-9e1b-7e4a9c7fe580
WSE Step by Step (1)
WSE2.0 比起 WSE2.0 Tech PreView 最大的变化就是安全性。
WSE2已经发布,我今天才了解什么是WSE
COM+ Web 服务:通过复选框路由到 XML Web Services http://www.cnblogs.com/cowbird/archive/2004/06/17/16320.html
关于MTS和COM+的区别
使用Visual C#制作可伸缩个性化窗体 http://msdnportal.csdn.net/Read.aspx?C=6&S=705706c8-7013-4730-9a98-93b4639726f3
Working with the C# 2.0 Command Line Compiler http://msdn.microsoft.com/vcsharp/default.aspx?pull=/library/en-us/dnvs05/html/csharpcompiler.asp
Web Caching and Expiration, Connection Pools, and More http://msdn.microsoft.com/msdnmag/issues/05/01/WebQA/default.aspx
非.NET语言调用.NET XML Web Services返回的数据集合的两个方法 http://www.microsoft.com/China/Community/program/originalarticles/TechDoc/callwebs.mspx
在 .NET 中使用 COM+ 服务 http://www.microsoft.com/China/Community/program/originalarticles/TechDoc/usecom.mspx
身份验证和授权 http://www.microsoft.com/china/msdn/library/architecture/architecture/architecturetopic/BuildSucApp/BSAAsecmod03.mspx FlyTreeView for ASP.NET 3.2 破解攻略 DotNet控件破解

Form with Validators Not Submitting on a Rebuilt ASP.NET 1.1 Box
http://support.microsoft.com/default.aspx?scid=kb%3Ben-us%3B889877 The Submit button on ASP.NET pages does not work after you install the .NET Framework 1.1 Service Pack 1

使用C#进行点对点通讯和文件传输(通讯基类部分)
使用C#进行点对点通讯和文件传输(发送接收部分)



网站
一个很好的CRM项目网站
http://www.salesforce.com/

C++
VC常用数据类型列表 及字符类型转换
CString,string,char*的综合比较(一)
CString,string,char*的综合比较(二)
CString,string,char*的综合比较(三)
http://www.vckbase.com/ VC知识库
http://www.vchome.net/ 阿蒙编程之家
http://www.vczx.com/ VC在线
http://www.china-askpro.com/ 问专家
http://www.vcfan.com/
http://www.vchelp.net/


IT从业人员必看的10个论坛
IT技术开发综合类
http://community.csdn.net/
适合人群:只适合软件开发者
技术开发最全面的论坛,里面可以遇到很多牛人,版面也很全,什么J2EE,.NET啊,该有的全上,在这里基本上可以提出任何问题,人气也是最旺的,不过一般提出的意见都有正方两面的,所以最终解决问题,还是靠自己。
评价:专业,很牛逼,就是速度慢。
http://www.itpub.net/
适合人群:数据库开发人员
数据库方面是非常著名的,牛人不少,不过,现在比较杂,什么都做,网络,操作系统,行业应用,到体育贴图,当然有些也不错,人气非常高,特别是灌水方面,^_*.
评价:强,速度一般;
http://bbs.chinaunix.net/forum/
适合人员:系统工程师
这里的特色就是操作系统方面在业界是最著名的,牛人不少,目前,在数据库,网络方面也颇有建树,当然灌水方面也不赖,呵呵,属于温柔性
评价:强,速度还可以
bbs.chinajavaworld.com/
适合人员:JAVA开发
JAVA方面非常综合的论坛了,牛人也很多,是一个难得的JAVA论坛,涉及你想象的关于JAVA目前任何技术。
评论:强,速度还可以。
http://www.huihoo.com/forum/
适合人员:中间件开发者
人气不错,版面风格独特,在开源,中间件,工作流方面非常不错,问题讨论都非常深刻、也很专业。
评价:很好,速度一般;
IT售前技术顾问综合类
http://www.sysvs.com/bbs
适合人员:IT售前及技术顾问
业界知名的售前技术顾问论坛,比较新异的知识点,各个IT行业版快划分也比较好,也非常专业,绝对是我稀饭(喜欢)的风格,网站风格业内罕见,也有很多专业文章,没有地方灌水,厉害。
评价:很好,速度比较快
网络工程类
http://www.1000bbs.com/
适合人员:布线/网络工程师
人气很旺,特色是版面比较紧凑,综合布线这一块很权威,很窄很专,时间非常久了,颜色比较明快,就是太低端了,
评价:不错,速度一般
http://www.sharecenter.net/
适合人员:网络工程师
之所以我喜欢是这个网站很多做CISCO工程都知道,也是别人介绍我去的,时间非常久了,颜色比较暗谈,属于忧郁型。
评价:不错,速度也还可以
IT管理综合类
http://club.amteam.org/
适合人员:企业策划,CIO
业界知名的知识站点,信息化管理顾问可以去看看,人也很多,可惜,都是下载,实质性内容需要改观,我记得以前是非常专业的网站,现在需要加油。
评价:不错,速度一般。
IT评论类
http://www.tianyaclub.com/ it视角
适合人群:大多数,
评论类比较多,基本上在其他媒体上看到的评论,这里都会有,要想了解IT发展的情况,就来这里看看。
评价:很好,休闲工作都可以看。

http://vipbio.blogchina.com/blog/article_180765.1051334.html windows XP 系统服务“关闭”详细列表,内存128的足够了

Tuesday, December 07, 2004

Credit Card Payment Gateway API

Four major credit card payment gateway:
1. Verisign => http://verisign.com/
2. Psigate => http://psigate.com/
3. Linkpoint => http://linkpoint.com/
4. Authorize => http://authorize.net/

Another two payment gateway:
5. 2CheckOut => http://2checkout.com/
6. Paypal => http://paypal.com/

Five Transaction Type:
0(S). Sale
1(A). Authorisation
2(D). Delayed Capture
3(C). Credit
9(V). Void

API
1. Verisign Payment Services: Payflow Pro
The Payflow Pro client resides on your computer system and is available on all major Web server platforms in a variety of formats to support integration requirements. It comes as a binary executable, activated via a Common Gateway Interface (CGI) script, or integrated as a C-interface application library. It is also available as DLL, COM, Site Server, Java Native Interface, or Perl Module
Interface

Config:
Host=test-payflow.verisign.com
Port=443

Set ccObj = CreateObject("PFProCOMControl.PFProCOMControl.1")
Query = "USER=MerchantLogin&VENDOR=MerchantLogin&PARTNER=MerchantPartner
&PWD=MerchantPassword&TRXTYPE=transactionType&TENDER=C&ACCT=accountNumber
&EXPDATE=expDate&AMT=Amount&COMMENT1=UserName&MERCHDESCR=CompanyName&MERCHSVC=CustomerTel"
Ctx = creditcardObj.CreateContext(HostAddress, HostPort, 30, "", 0, "", "")
Response = ccObj.SubmitTransaction(Ctx, Query , Len(Query))
'RESULT=0&RESPMSG=Approved&PNREF=V53A53032326
ccObj.DestroyContext (Ctx)

2. PsiGate
Config:
Host=secure.psigate.com
Port=1139

Set ccObj = CreateObject("MyServer.PsiGate")
ccObj.ConfigFile = MerchantConfig
ccObj.KeyFile = MerchantKeyFile
ccObj.Host = HostAddress
ccObj.Port = HostPort
ccObj.Result = TestMode
ccObj.Bname = cardName
ccObj.CardNumber = accountNumber
ccObj.expMonth = expMonth
ccObj.expYear = expYear
ccObj.ChargeType = transactionType
ccObj.userID = clientType
ccObj.Email = clientType
ret = ccObj.AddItem("cc transaction for CompanyName", "total price", Amount, 1, "", 0, "")
if ret = 1 then
ret = ccObj.ProcessOrder()
if ret = 1 then
Appr = ccObj.Appr 'APPROVED
Err = ccObj.Err '
OrdNo = ccObj.OrdNo '69.158.48.111-1102444389-363202-15893-7
end if
end if

3.LinkPoint: API
a collection of functions for processing payment transactions over the Internet in a highly secure manner.
Transition between COM Object versions 5.4(using 1139) and 6.0(using 1129) before Feb 2005.

Config:
Host=staging.linkpt.net
Port=1129

'=================V5.4===================================================
Set ccObj= Server.CreateObject("ComApi_3_8.ComApi")
OrderCtx = ccObj.csi_order_alloc()
ItemCtx = ccObj.csi_item_alloc()
ReqCtx = ccObj.csi_req_alloc()
Flag = ccObj.csi_req_set(ReqCtx, ReqField_Configfile, merchantconfig)
Flag = ccObj.csi_req_set(ReqCtx, ReqField_Keyfile, keylocation)
Flag = ccObj.csi_req_set(ReqCtx, ReqField_Host, hostaddress)
Flag = ccObj.csi_req_set(ReqCtx, ReqField_Port, hostport)

Flag = ccObj.csi_order_setrequest(OrderCtx, ReqCtx)
if ccObj.bStat <> Succeed Then
'Error
End If

Flag = ccObj.csi_order_set(OrderCtx, OrderField_Bname, cardname)
Flag = ccObj.csi_order_set(OrderCtx, OrderField_Cardnumber, accountnumber)
Flag = ccObj.csi_order_set(OrderCtx, OrderField_ChargeType, transactiontype)
Flag = ccObj.csi_order_set(OrderCtx, OrderField_Expmonth, expmonth)
Flag = ccObj.csi_order_set(OrderCtx, OrderField_Expyear, expyear)
Flag = ccObj.csi_order_set(OrderCtx, OrderField_Email, email)
Flag = ccObj.csi_order_set(OrderCtx, OrderField_Result, status)
Flag = ccObj.csi_item_set(ItemCtx, ItemField_Itemid, "total price")
Flag = ccObj.csi_item_set(ItemCtx, ItemField_Description, "cc transaction for companyname")
Flag = ccObj.csi_item_set(ItemCtx, ItemField_Price, amount)
Flag = ccObj.csi_item_set(ItemCtx, ItemField_Quantity, 1)
Flag = ccObj.csi_order_additem(OrderCtx, ItemCtx)
if ccObj.bStat <> Succeed Then
'Error
End If

Flag = ccObj.csi_item_drop(ItemCtx)
Flag = ccObj.csi_order_set(OrderCtx, OrderField_Subtotal, amount)
Flag = ccObj.csi_order_set(OrderCtx, OrderField_Chargetotal, amount)

Flag = ccObj.csi_order_process(OrderCtx)
if ccObj.bStat <> Succeed Then
'Error
End If

Ref = ccObj.csi_order_get(OrderCtx, OrderField_R_Ref)
Appr = ccObj.csi_order_get(OrderCtx, OrderField_R_Approved)
Err = ccObj.csi_order_get(OrderCtx, OrderField_R_Error)
Ord = ccObj.csi_order_get(OrderCtx, OrderField_R_Ordernum)

Flag = ccObj.csi_order_drop(OrderCtx)
Flag = ccObj.csi_req_drop(ReqCtx)
Set ccObj = nothing

'=================V6.0===================================================
Set order = Server.CreateObject("LpiCom_6_0.LPOrderPart")
order.setPartName("order")
Set ccObj = Server.CreateObject("LpiCom_6_0.LPOrderPart")
res=ccObj.put("ordertype", "SALE") 'PREAUTH, POSTAUTH, VOID
res=order.addPart("orderccObjtions", ccObj)

res=ccObj.put("name", bname)
res=ccObj.put("email", bemail)

res=ccObj.clear()
res=ccObj.put("zip", bzip)
res=ccObj.put("addrnum", baddrnum)
res=order.addPart("billing", ccObj)
'res=ccObj.put("oid", oid)
'res=order.addPart("transactiondetails", ccObj)

res=ccObj.clear()
res=ccObj.put("configfile", configfile)
res=order.addPart("merchantinfo", ccObj)

res=ccObj.clear()
res=ccObj.put("cardnumber", cardnumber)
res=ccObj.put("cardexpmonth", expmonth)
res=ccObj.put("cardexpyear", expyear)
res=order.addPart("creditcard", ccObj)

res=ccObj.clear()
res=ccObj.put("chargetotal", total)
res=order.addPart("payment", ccObj)

Set LPTxn = Server.CreateObject("LpiCom_6_0.LinkPointTxn")

outXml = order.toXML()
Response = LPTxn.send(keyfile, host, port, outXml)
'CSITue Dec 7 10:43:16 20040000017747459E306F-41B5F9C3-627-14FD240088730000017747:YNAM:12345678901234567890123:1102444996APPROVEDYNAM

Set LPTxn = Nothing
Set order = Nothing
Set ccObj = Nothing

4. Authorize:
The Standard Transaction Submission API defines how transactions should be submitted to the gateway using AIM. The gateway response API describes the gateway’s responses to transactions submitted to the gateway.

Config:
Host=https://secure.authorize.net/gateway/transact.dll
Port=1139

query = "x_login=MerchantLogin&amp;x_tran_key=MerchantKey&x_type=
x_type&x_amount=total&x_card_num=cardnumber&x_exp_date=
x_exp_date&x_trans_id=x_trans_id&x_first_name=x_first_name &x_last_name=x_last_name &x_email=emailaddress"
Set objsxh = Server.CreateObject("Msxml2.ServerXMLHTTP.4.0")
objsxh.open "POST", HostAddress ,false
objsxh.setRequestHeader "Content-Type","application/x-www-form-urlencoded"
objsxh.setRequestHeader "Content-Length",len(query)
objsxh.send query
Response = objsxh.responseText
'1,1,1,This transaction has been approved.,000000,P,0,,,1.00,CC,auth_capture,,,,,,,,,,,,,,,,,,,,,,,,,,C8CCAF620C1287B7C2713F10E5D1FC54,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,

Friday, November 19, 2004

利用 Microsoft 的 HTML 分析器来获得 Web 站点的数据

拆取 Web 页


.Net 2.0实例学习:WebBrowser页面与WinForm交互技巧 这一篇也很不错

利用 Microsoft 的 HTML 分析器来获得 Web 站点的数据

http://www.microsoft.com/china/msdn/Archives/workshop/scrape.asp


Jeremy Rule
Microsoft Corporation
2000年5月



摘要: 本文讨论如何收集来自 Web 的信息,并借助 Internet Explorer 的可重用分析器组件,将它分布到其他 Web 页或数据库。(打印共 7 页)



程序员面临的一个共同任务就是收集 Web 站点的数据,并将它分布到数据库或其他 Web 页。例如,程序员可能需要从气象站点获得天气预报图,从在线股票经纪人那里获得股票报价,以及从新闻站点获得行业新闻。然后,这些信息被放在一个 Web 页上,供 CIO、商人或销售经理使用。或者,也许程序员需要跟踪历来的气象资料,并需要每天将来自气象站的天气预报信息存入数据库。其应用不胜枚举。



过去,这些选择相当受限制。现在,通过使用象 WinInet.dll 这样的 HTTP 组件或许多其他第三方组件,您就可以获取 Web 页,并利用几百种字符串处理功能来获得网页中您所感兴趣的部分。这一技术已在应用,但很不理想。如果您致力于计算机科学(或者有足够的时间),就会为 HTML 创建一个分析器,以标记 Web 页,然后分析您需要的网页部分。不过,由于 Internet Explorer 的体系结构中已包含了可重复使用的用分析器,这些都不需要了。



Internet Explorer 不只是一个程序,更是许多可重复使用组件的集合与容器。在拆取 Web 页时,最有意思的两个组件是 shdocvw.dllmshtml.dll。第一个组件 shdocvw.dll,包含称为 WebBrowser 的 Microsoft(R) ActiveX(R) 控件,它真实地显示 Web 页。在运行 Internet Explorer 时,显示 Web 页的主窗口就是这样的控件。第二个组件 mshtml.dll,含有能分析 WebBrowser 控件中所包含文档的 HTML 分析器。



可能有这种情况,在您的应用程序内部,已经用 WebBrowser 控件来驻留 Web 页,但仍需要重新创建一个小浏览器来启动 Web 页的拆取。


  1. 文件菜单上,请单击新建工程,以创建“标准 EXE”,然后在工程菜单上单击部件,以添加 Microsoft HTML Object LibraryMicrosoft Internet Controls。(见图 1。)


    图 1.



  2. 在工具箱中,可看见 WebBrowser 组件。拖动其中之一,文本框和主窗体上的命令按钮。将此文本框的 Text 属性设置为 “http://moneycentral.msn.com/”,将此命令按钮的 Caption 属性设置为“浏览(&B)”。(见图 2。)


    图 2.



  3. 双击该命令按钮,然后在事件处理器中放入下列代码,导航至文本框中命名的 Web 站点:
    Private Sub Command1_Click()
    WebBrowser1.Navigate Text1.Text
    End Sub



  4. 保存并运行该程序。试着按浏览按钮,导航到文本框中指定的站点。您已经创建了一个基本的 Web 浏览器 — 就其本身而言没什么用,甚至没什么意义,但它却是迈向 Web 拆取技术的第一步。



  5. 回到工程中,在代码窗口中选择 WebBrowser1 对象,然后选择 DocumentComplete 的事件处理器。一旦整个 Web 页下载到此浏览器中,即触发该事件:
    Private Sub WebBrowser1_DocumentComplete_
    (ByVal pDisp As Object, URL As Variant)

    End Sub


    传递到该事件中的 URL 就是我们导航所至的位置,它在日后确定浏览器所在的页面时将更为有用。WebBrowser 控件有一个属性称为 Document(文档),可将其视为 IHTMLDocument 来处理:


    Private Sub WebBrowser1_DocumentComplete(_ ByVal pDisp As Object, URL As Variant)
    Dim Doc As IHTMLDocument2
    Set Doc = WebBrowser1.Document
    //下一步:分析该文档
    End Sub


    较新的 IHTMLDocument2 具有 IHTMLDocument 中无法使用的特性。可对系统使用 IHTMLDocument 替代老版本的 Internet Explorer,如果您有勇气的话,甚至可以使用 IHTMLDocument3。补充说明一下,我们假设您已经导航到 Word 文档或 XML 文档,而非 HTML 文档。不要将变量 doc 声明为 IHTMLDocument2,可将其声明为 Word 的文档或 XML 的 DOMDocument


    在进行下一步之前,理解 HTML 文档的结构是非常重要的。和 XML 不一样,HTML 文档的组合有一定的自由度。例如,您会遇到未关闭标记的 HTML 文档。HTML 文档确实有某种结构。结构好的 HTML 文档通常具有下列元素:


    <HTML>
    <HEAD>
    header information like the <TITLE>
    </HEAD>
    <BODY>
    elements like <TABLE> and <A> and <IMG>
    </BODY>
    </HTML>


    请注意 HTML 的树状结构。标记包含标记又包含标记,如此等等。特别是,每一个标记元素都包含一个 0 到 n 个标记元素的集合。<TABLE> 标记可以包含 <TR> 标记。每个 <TR> 标记可以包含 <TD> 标记,后者又可以包含其他标记如锚或图像等。



  6. 现在,分析整个 http://moneycentral.msn.com/,并在带 MSFT 符号的页填上第二个 <INPUT> 标记。然后,调用此窗体上的提交
    Private Sub WebBrowser1_DocumentComplete(ByVal pDisp As Object, URL As Variant)
    Dim doc As IHTMLDocument2
    Set doc = WebBrowser1.Document

    If URL = _
    "http://moneycentral.msn.com/home.asp" Then
    '填充带输入标记的元素集合
    Dim Inputs As IHTMLElementCollection
    Set Inputs = doc.All.tags("INPUT")
    '选择第一个输入标记
    Dim Element As IHTMLElement
    Set Element = Inputs.Item(1, 1)

    '使用正确的界面
    Dim InputElement As IHTMLInputElement
    Set InputElement = Element
    InputElement.Value = Text1.Text

    '调用此页第一个窗体上的提交
    doc.Forms.Item(0, 0).submit
    End Sub


    在此您会看到,标记集合如何包含可视为其特定类型的标记。每一个标记都可用 IHTMLElement 界面表示,或用指定为该标记类型的界面表示。例如,<TABLE> 标记可用 IHTMLTableElement 或 IHTMLElement 表示。


    标记的集合都包含下列重要的方法和属性:



    • 长度。可将其理解为计数,或集合中项目的数量。



    • 项目。用于选择集合中的特殊元素。“项目”有两个参数,第二个参数即命名的标记。



    • 标记。将要过滤的元素传递给标记。标记 ("A") 将返回集合内所有锚的集合。要想有效地拆取页,就需要学会使用标记集合。



    现在可能您会问,“为什么不直接转到 http://moneycentral.msn.com/scripts/webquote.dll?ipage=qd&Symbol=msft?”当然是可以的,但这个例子告诉大家如何在更复杂的情况下操纵 HTML 窗体。


    如果您未做进一步的改动即运行该程序,就会注意到它将陷入无休止的循环,没完没了地下载同一个页面。程序不断地寻找要填充的窗体,并反复调用 DocumentComplete。要修正这个缺陷,应在 DocumentComplete 中置入一些逻辑,告诉分析器,只有在正确的页面上才提交窗体。



  7. 接下来,让我们放入这个逻辑,并引入实际的股票报价。另外,我们不捕获文本框中的 URL,而是捕获股票符号:
    Private Sub Command1_Click()
    WebBrowser1.Navigate _
    "http://moneycentral.msn.com/home.asp"
    End Sub
    Private Sub WebBrowser1_DocumentComplete(ByVal pDisp As Object, URL As Variant)
    Dim doc As IHTMLDocument2
    Set doc = WebBrowser1.Document

    If URL = "http://moneycentral.msn.com/home.asp" Then
    '填充带输入标记的元素集合
    Dim Inputs As IHTMLElementCollection
    Set Inputs = doc.All.tags("INPUT")
    '选择第一个输入标记
    Dim Element As IHTMLElement
    Set Element = Inputs.Item(1, 1)

    '使用正确的界面
    Dim InputElement As IHTMLInputElement
    Set InputElement = Element
    InputElement.Value = Text1.Text

    '调用该页第一个窗体上的提交
    doc.Forms.Item(0, 0).submit
    ElseIf URL = _
    "http://moneycentral.msn.com/scripts/webquote.dll?ipage=qd&Symbol=" _
    & Text1.Text Then
    Dim Tables As IHTMLElementCollection
    Set Tables = doc.All.tags("TABLE")
    '获得第 14 个表的第二个项目(基于 0)
    Dim Quote As IHTMLElement
    Set Quote = _
    Tables.Item(14, 14).All.tags("TD").Item(2, 2)
    '显示开始标记和结束标记之间的文本
    MsgBox Quote.innerText
    End If
    End Sub



    图 3.

    到了这最后一步,自定义的浏览器已被转入有效的 Web 拆取器。重要的是,要注意有了 IHTMLElement 之后获得文本的可用选项。有 4 个属性:



    • innerText:开始标记和结束标记之间的文本。



    • innerHTML:开始标记和结束标记之间的文本和 HTML。



    • outerText:对象的文本。



    • outerHTML:对象的文本和 HTML。



    还要注意从 4 个表(基于 0)的 11 个元素中检索到的最终报价字符串。如果 MoneyCentral? 决定重新调整该页怎么办?您最好的策略是根据合理的假定来查询页面。如果您知道报价几乎总是放在新闻标题的前面,那么就从新闻标题往回查询那个表。还有一种策略是,当更改页面的格式时,有一种简单的方法来更新分析器。一种方法就是将分析的职能细分为较小的组件。每个组件可以实现一个预定义的界面,接受要分析的 IHTMLDocument。与实际的 Web 页失去同步的分析组件可被替换。这样带来的好处是,多个编程人员都可以编写分析器,只需给定要实现的界面和要拆取的 Web 站点即可。


    为了避免复杂,将 IHTMLDocument 从 DocumentComplete 函数传递 COM DLL,后者可以分析 IHTMLDocument 并返回想要的有效负载。这有利于程序的模块化,并易于更新与 Web 站点失去同步的分析部分。它还使多个开发者能同时处理这个项目,因为他们有一个干净的界面来编写分析器。




在把新的程序推向市场以前,还有几个实际问题要考虑。首先,很可能 MoneyCentral 和其他许多站点不愿意别人下载他们的内容,也不喜欢看广告。您可能得与摘取其内容的站点签订一份协议。



还有很重要的一点要注意,即如果您是 Web 站点的操作员,那么还有更好的办法将您的内容提供给其他系统。虽然可以让其他人来拆取您的 Web 页,但这仍很笨拙。还有一个更好的方法是,提供 XML 来表现内容。并且,随着 XML 被广泛采用,Web 站点开始提供其数据的 XML 表现形式以及 HTML 界面,也不值得大惊小怪。在这样的时刻到来之前,您也许还得拆取 Web 页。Web 页的拆取往往失之笨拙,但 Microsoft HTML 分析器可令其稍微好一些。

Tuesday, October 26, 2004

在加拿大找IT专业工作的经历分享(ZT)

这个星期刚刚找到专业工作,是在donntown的一家e-business公司里的Java Programmer。想跟大家分享一下经历,因为在这个过程中的确得到不少认识和不认识的人无私的帮助,自己也说过如果有那么一天自己找到了专业工作,也会尽自己所能帮助别人。今天就从如何找到这份工作开始。   

我在国内5年工作经验,4年Java相关工作,基本是在外企,从申请到过来足足花了4年,期间也经常学习英文,但现在才确确实实知道跟西人的差别有多大,我相信这是接下来的重要任务。   

来加多伦多4个多月,其间去过LINC(level 5)班,但没有上完就准备找专业工作,所以就没有拿到英文benchmark level 6的证书,这对以后参加政府资助的一些program没有好处,不过听说ESL的语言测试可以代替,但我最后也没有去考。一开始从LINC班出来直接向Monster.ca和Workopolis.com上的工作职位发简历,用的也是中国带来的简历(以为一直都在一些外企,格式差不多),结果一两个星期没有一丝一毫的反应,才确信格式很有问题,于是参加了一个政府资助的为期三天的改简历program,期间从图书馆也借了一些书参考书,从网上http://www.scguild.com参考了其IT人士的简历(不要去骗简历,我也发现google上的确有人发布的职位就是骗简历,没有必要也不好,我们既然来到这里就要注重我们的诚信),由txt格式改成了word格式,倒弄了一两个星期后基本定型,接着给了朋友参考给意见,作了一些修改,听说最好给西人检查,包括格式,语病,习惯等等,但我也没有,听说教会里,政府资助的Programe有这样的服务的。简历改的差不多了,就接着发,除了Monster.ca和Workopolis.com外我还在google的新闻组里找工作机会(因为新闻组不要花钱发布,小公司也许会在上面发布信息,而且大家都在Monster.ca和Workopolis.com上面找,竞争比较激烈,不过正如我刚刚说,上面不少骗简历的,不要被他们给骗了,我想一般他们的网站建立的很好,而且电话,地址在网站上也有的话就比较可信)。其间我也去过图书馆的scott数据库查找多伦多软件公司的联系方式,接着打cool call(YMCA有一些教如何cool call的program),只打了两天,效果不好,我想这个方法本身不是最好的,但实在没办法了,也可以试一试,重要的是keep trying。也就是在打call call的那段时间,通过http://www.google.com/advanced_group_search?hl=en上查找tor.job news group(sort by date)我的cover letter改为找volunteer机会为主,当然也说自己如何符合他们的职位等等,但重点是告诉他们我主要是找volunteer机会,取得到canadian experience。结果有两家公司找我,一加是中国人公司,说一个星期两天(好像很想我去3天),连续3个月(我说2个月他们还不愿意),说干完以后如果公司有新项目,有条件的话可以留下,这3个月有$100/month作为交通费用。因为接下来还有一个机会,而且我觉得他们的诚意不是很够,加上中国人的公司在这个方面一般来讲的确没有西人公司好,所以我就回绝了。到了另外一家公司,发觉是downtown的一家西人公司,准备让我协助他们做web service的项目,两个星期,9:00am~5:00pm,我就坚持下来了。结束的时候manager告诉我可以pick my stuff,但可以给我开reference的时候,我其实是非常难受的,因为一直还是想着就直接留下来的。但也没办法,留了manager和team leader的名片就离开了。发了Thank You Letter(刚得到volunteer机会发了一次,结束后再发了一次)后安慰自己两个星期换个reference也不错,要接着move on。就在我开始上另外一个找工program的第一天,好消息来了,说他的一个programmer要离开,有一个immediately openning,通知我第二天上班,那一天我一直觉得unreal,too good to be true,告诉他那是gift from heaven。接下来是要顺利通过他们的3个月考核。   

总的来说,对于要找IT专业工作的朋友,我有以下建议(特别是来了不久或准备在短期类来的):   

1.强烈建议从volunteer/co-op开始(除非有信心能直接找到工作),其中以西人中小型企业为主要对象,又以自己联系为主(因为即使你去一些co-op,最终还是以你自己找为主,即使是他们帮你找,还存在那家公司是否已经养成使用volunteer习惯的风险),目标是通过volunteer/co-op建立与雇主的联系,让manager看到你的能力,能让他们一有openning,就想到你是一个很好的选择。如果不能直接得到offer,留下他们的名片,隔一段时间就要联系他们,让他们知道你还在找工作,跟他们聊一聊,保持联系,networking很重要的,我有一种感觉,他们一般还是很愿意帮助人的(当然不能过于频繁的骚扰或超出他们的能力范围),但你要ask for it,他们也不会很主动的送一份工作给我们,得到帮助或一些有用的信息后,要多谢一些他们,写一写thank you letter。   

2.如果短时间内不能自己找到工作或volunteer/co-op,而英语水平过关的话,参加以下co-op/work placement,政府资助的关于找工作的program中,我觉得下面的最有价值,时间太短的内容不多而且没有canadian experience,下面的program就提供了所有的你能免费获得的帮助:   http://www.dpcdsb.org/coopcentre/register.coop.html(可能是中国人最多去的,也可能是是几个中最好的,但在Mississauga,我自己没去过,但本来是想去这个的)http://www.dpcdsb.org/alcmeslcoop/coopmain.html(Mississauga另外一个,好像没有那么多人去,不知道效果)NOW: http://www.tdsb.on.ca/business/cspd/now.htm(777 Bloor Street West, Room 122, Toronto,也有不少人去,不是到效果)Yorkdale: http://www.yorkdale.net/main/yorkdale_coop_programs.htm(38 Orfus Road North York, Ontario,但听说留下的不多)STIC: http://skillsforchange.org/stic/index.html(可能是唯一一个有专门为IT人士分组的,但听说accounting分组效果比较好,IT分组效果一般)   

3.Keep Trying,这几个月是觉得辛苦,在国内从来没有受过这个苦,但只要有恒心和毅力,我们还是可以争取到的。开始怀疑自己的时候,告诉自己坚持就是胜利。我们在国内都不会如此,但现在的确比不上2000年了,我们刚过来找工作难是正常的,语言的差距是确确实实存在的,但也要记住还是有很多人坚持下来了,再加上一些运气(也可能是很大一部分),我们最终会得到的,但如果我们已经放弃了,那一点机会都不会有。今年听说IT比2003年要好不少,难度还有,但大家要加油啊!   

4.参考IT简历: http://www.scguild.com

5.Google new group: http://www.google.com/advanced_group_search?hl=ensort by date, Newsgroup中填tor.jobs

6.每天更新Monster.ca和Workopolis.com上简历的状态。   

如果有什么可以帮得上忙得话,可以给我留言,416-763-9913,因为我也得到过不少其他人的帮助,也的确体会到了其过程的压力,体会到在这个地球另外一边得到一些无私帮助时的喜悦。感谢所有多年来帮助过我的朋友,认识的和不认识的,也希望我的经历能够帮助一些朋友。

---------------------------------------------------------------------------------
---------------------------------------------------------------------------------

Behavioural questions万变不离其宗


no matter what question the HR mgr asks, these are the aspects they want to know about you. So for each aspect listed below, prepare for some good examples. Tell the story in the formate of " this is what happens"--->" this is how I handled it"---> conclusion : "from this experience, i learned that... /I developed my skills in @@@ further."

1. your management style and you team work style

2. your time management skills

3. your conflict resolution skills

4. you skills to convince or influence people (make sure you give a well balanced response)

5. your strengs and weakness

7. you career orientation

8. you communication and presentation skills (how do you convey a difficult idea? how to you coach people? how do you make your point across clearly and effectively?) ---------------------------------------------------------------------------------
---------------------------------------------------------------------------------

Behavior Interview


来源: 梅影 于 07-09-29

1.Tell me about yourself.

What the hiring manager really wants is a quick, two- to three-minute snapshot of who you are and why you’re the best candidate for this position.
So as you answer this question, talk about what you’ve done to prepare yourself to be the very best candidate for the position. Use an example or two to back it up. Then ask if they would like more details. If they do, keep giving them example after example of your background and experience. Always point back to an example when you have the opportunity.
“Tell me about yourself” does not mean tell me everything. Just tell me what makes you the best.

sample answer:

I have been working in the field of civil engineering for the past 6 years. My most recent experience has been with an engineering consulting firm where I’ve worked for the last 2 years. I enjoy my job because it’s challenging and I like interacting with a variety of people. In my most recent assignment I was on a project that lasted nine months. I made a significant contribution to the project because of my expertise in sanitary engineering. One of my strengths is my attention to detail. I am known for being extremely thorough and meeting or exceeding deadlines and goals. My boss knows that I work well under minimal supervision, that I am very conscientious and that the job will be done right the first time. I’m looking for a new opportunity where I can contribute to the growth of the company by helping educate customers on the benefits of using our consulting services.

My background to date has been centered on preparing myself to become the very best _____ I can become. Let me tell you specifically how I've prepared myself...

Tell about your major, what you plan on doing when you get out of college, what other jobs you have had.
Answer in about two minutes. Avoid details, don’t ramble. Touch on these four areas:
How many years, doing what function
Education – credentials
Major responsibility and accomplishments
Personal summary of work style (plus career goals if applicable)

2.Did you bring your resume?
Yes. Be prepared with two or three extra copies. Do not offer them unless you’re asked for one.

3.What is your long-range objective?
The key is to focus on your achievable objectives and what you are doing to reach those objectives.

For example: “Within five years, I would like to become the very best accountant your company has on staff. I want to work toward becoming the expert that others rely upon. And in doing so, I feel I’ll be fully prepared to take on any greater responsibilities which might be presented in the long term. For example, here is what I’m presently doing to prepare myself . . .”

Then go on to show by your examples what you are doing to reach your goals and objectives.

Although it's certainly difficult to predict things far into the future, I know what direction I want to develop toward. Within five years, I would like to become the very best _____ your company has. I would like to become the expert that others rely upon. And in doing so, I feel I will be fully prepared to take on any greater responsibilities that might be presented in the long term.

4.Are you a team player?
Describe what would be an ideal working environment?

Team work is the key.
Almost everyone says yes to this question. But it is not just a yes/no question. You need to provide behavioral examples to back up your answer.
A sample answer: “Yes, I’m very much a team player. In fact, I’ve had opportunities in my work, school and athletics to develop my skills as a team player. For example, on a recent project . . .”

Emphasize teamwork behavioral examples and focus on your openness to diversity of backgrounds. Talk about the strength of the team above the individual. And note that this question may be used as a lead in to questions around how you handle conflict within a team, so be prepared
You are, of course, a team player. Be sure to have examples ready. Specifics that show you often perform for the good of the team rather than for yourself are good evidence of your team attitude. Do not brag, just say it in a matter-of-fact tone. This is a key point.

5.What is your greatest weakness?

Most career books tell you to select strength and present it as a weakness. Such as: “I work too much. I just work and work and work.” Wrong. First of all, using strength and presenting it as a weakness is deceiving. Second, it misses the point of the question.

You should select a weakness that you have been actively working to overcome. For example: “I have had trouble in the past with planning and prioritization. However, I’m now taking steps to correct this. I just started using a pocket planner . . .” then show them your planner and how you are using it.

Talk about a true weakness and show what you are doing to overcome it.
I would say my greatest weakness has been my lack of proper planning in the past. I would overcommit myself with too many variant tasks, then not be able to fully accomplish each as I would like. However, since I've come to recognize that weakness, I've taken steps to correct it. For example, I now carry a planning calendar in my pocket so that I can plan all of my appointments and "to do" items. Here, let me show you how I have this week planned out...

6.What is your greatest strength?

Numerous answers are good, just stay positive. A few good examples: Your ability to prioritize, Your problem-solving skills, Your ability to work under pressure, Your ability to focus on projects, Your professional expertise, Your leadership skills, Your positive attitude.

You know that your key strategy is to first uncover your interviewer's greatest wants and needs before you answer questions. And from Question 1, you know how to do this.

Prior to any interview, you should have a list mentally prepared of your greatest strengths. You should also have, a specific example or two, which illustrates each strength, an example chosen from your most recent and most impressive achievements.

You should, have this list of your greatest strengths and corresponding examples from your achievements so well committed to memory that you can recite them cold after being shaken awake at 2:30AM.

Then, once you uncover your interviewer's greatest wants and needs, you can choose those achievements from your list that best match up.

As a general guideline, the 10 most desirable traits that all employers love to see in their employees are:
1. A proven track record as an achiever...especially if your achievements match up with the employer's greatest wants and needs.
2. Intelligence...management "savvy".
3. Honesty...integrity...a decent human being.
4. Good fit with corporate culture...someone to feel comfortable with...a team player who meshes well with interviewer's team.
5. Likeability...positive attitude...sense of humor.
6. Good communication skills.
7. Dedication...willingness to walk the extra mile to achieve excellence.
8. Definiteness of purpose...clear goals.
9. Enthusiasm...high level of motivation.
10. Confident...healthy...a leader.

7.If you had to live your life over again, what one thing would you change?

Focus on a key turning point in your life or missed opportunity. Yet also tie it forward to what you are doing to still seek to make that change.

For example: “Although I’m overall very happy with where I’m at in my life, the one aspect I likely would have changed would be focusing earlier on my chosen career. I had a great internship this past year and look forward to more experience in the field. I simply wish I would have focused here earlier. For example, I learned on my recent internship…” …then provide examples.

Stay focused on positive direction in your life and back it up with examples.

8.How did you prepare for this interview?

When I found this position posted on the internet (monster.com) I was immediately interested. I checked out the company website and mission statement, looked at the bios of company founders and executives, and was impressed. Once I had the interview appointment, I talked with friends and acquaintances in the industry. And, I’m sure I’ll find out a lot more in today’s meetings.”

9.What kinds of people do you have difficulties working with?

In my last three jobs I have worked with men and women from very diverse backgrounds and cultures. The only time I had difficulty was with people who were dishonest about work issues. I worked with one woman who was taking credit for work that her team accomplished. I had an opportunity to talk with her one day and explained how she was affecting the morale. She became very upset that others saw her that way, and said she was unaware of her behavior or the reactions of others. Her behavior changed after our talk. What I learned from that experience is that sometimes what we perceive about others is not always the case if we check it out.

10.How do you handle conflict? (How would you evaluate your ability to deal with conflict?)

On the job, there are many possible sources of conflict. Conflicts with: fellow employees management rules, procedures clients, customers demands of work vs. personal life, family The best way to approach a good answer is to look at if from the employers point of view—they want to be your first priority and they want you to solve problems (not bring them any). “I know everything cannot run smoothly at work all the time. When there is a conflict I usually try to determine the source of the problem and see if it can be solved. This might involve other members of the work team discussing the problem and offering possible solutions. I would then try to pick the solution which appears to have the best outcome and put it into action.” A natural follow-up to this would be: Tell me when you solved a conflict at work. So, have a brief example… a short story… to illustrate your approach. Even if not asked, you can offer your story! If it proves your point and accentuates a skill needed for the position, go with it.

I believe I am quite good at handling conflict. Working in retail and in the residence halls required that I make many unpopular decisions at times, whether it was terminating an associate or taking judicial action on a resident. Often the person in conflict with me would be upset and sometimes physically outraged. I would always make sure that I fully explained the situation, the policies behind my decision, and why those policies exist. Usually by the end of the conversation, the person could see the other side of the situation.

11. How do you handle rejection?

Rejection is part of business. People don’t always buy what you sell. The tick here is to separate rejection of your product from rejection of yourself: “I see rejection as an opportunity. I learn from it. When a customer takes a pass, I ask him what we could do to the product, price or service to make it possible for him to say yes. Don’t get me wrong: You’ve got to makes sales. But rejection is valuable, too. It’s a good teacher.”

12.Tell me about a time when you tried and failed?

Has this ever happened to you? No one expects perfection actually, employers are more interested in your ability to cope, to learn from mistakes, and to deal with others who are less than perfect. If you have an example, certainly pick one that happened a while back, was not earth shattering in the results, and one which you learned and applied this knowledge recently. This is a version of ‘damning with faint praise’ by picking an incident that was minor in scope but, since you are so wise and are always willing to learn, has taught you a valuable lesson.

13.What are some of the things you find difficult to do?
The interviewer is looking to determine how well you know yourself, how you react to difficult situations/tasks and credibility. Look back over your work experience for examples of challenges… speaking in public at a meeting, disagreeing with a manager over an important issue, being asked to use a software program you have not had an opportunity to learn… These ’stories’ should illustrate a lesson learned, a problem overcome or a weakness being dealt with. “I always seem to need a day or two to prepare myself to give a presentation to department heads. When I know I have to give a report on my projects, I plan out all the details in advance and rehearse. One time, there was a problem with a supplier and I was asked to update senior management… immediately. The supply chain was crucial to the completion of an important project we had been working on for 5 months and decisions had to be made based on the information I had to prepare and present on a moment’s notice. I gathered the information and presented it simply and in detail. It was much easier than I thought without the hours of concern and practice. The facts spoke for themselves. Since I understood the situation, I was able to make it clear to management and get a rapid decision. I still prefer advance notice but I know I can deliver when asked to.”

14.What are your short and long term goals?

No one can make goals for you. It comes down to where you are in your professional life and what you want to do. Most people have 5-6 careers in their working lifetime—some with 2 careers going at the same time (like us). The best advice is to be certain to relate your answers to the organization that interviews you. Do not make a point of having goals that cannot be realized there (”I want to work in Paris.” Organization is strictly domestic.) If you do your research into the organization, and into what you truly want to do in the future, you will be able to come up with reasonable responses. No one is going to come back to you in five years and chastise you for not meeting these goals! You will not be held to them… it is only an interview and they are interested in how you see yourself (and they want to see you in the job.)

My primary objectives are to learn as much as possible about your company's product offering, organizational structure, and professional sales techniques so that I may become the most productive member of your sales team.

What are your short-term goals?

Many executives in a position to hire you are strong believers in goal-setting. (It's one of the reasons they've achieved so much.) They like to hire in kind.
If you're vague about your career and personal goals, it could be a big turnoff to many people you will encounter in your job search.
Be ready to discuss your goals for each major area of your life: career, personal development and learning, family, physical (health), community service, and (if your interviewer is clearly a religious person) you could very briefly and generally allude to your spiritual goals (showing you are a well-balanced individual with your values in the right order).
Be prepared to describe each goal in terms of specific milestones you wish to accomplish along the way, time periods you're allotting.

My short-term objectives are to graduate from the Professional Development Program before the standard two years and begin developing a clientele. As an intern, I prepared ahead of time by studying for the Series 7 and Series 64 exams that constitute a majority of a beginning financial consultant's time. I'd like to make make the company that hires me wonder what it ever did without me.


15.Where do you see yourself in five years?

This is the interviewer trying to see how you are in making long range plans and if you have goals that mesh with the organizations. One way to answer this question is to look back on your accomplishments to date: “I started out in my profession as a junior clerk while I completed my college studies during the evenings. Once I had my degree, I applied for a transfer to a more advanced position, citing my on-the-job training. This has been my pattern for my career with my past 2 employers. I learn quickly on the job and am willing to take classes and workshops to augment my experience. I have been able to assume greater responsibilities and add more value to the organization. I do not think in terms of titles… I think more in terms of “How can I solve this problem? Since this has been my career style to date, I do not imagine it to change. In five years, I feel I will have continued to learn, to grow into a position of more responsibility and will have made a significant contribution to the organization.”

Although it is hard to predict the future, I sincerely believe that I will become a very good financial consultant. I believe that my abilities will allow me to excel to the point that I can seek other opportunities as a portfolio manager (the next step) and possibly even higher. My ultimate goal continues to be -- and will always be -- to be the best at whatever level I am working at within Merrill Lynch's corporate structure.

16.Where do you want to become ten years from now?

Ten years from now I see myself as a successful consultant for a world-class firm like yours. I want to have developed a wonderful bond with my employer I will have proven myself a highly competent systems analyst and will represent my company in helping others find solutions to their information-systems needs in a professional and timely manner.

17.Would you rather work with information or with people?

I like the validity of information and also like the energy that comes with working with people. The best thing about working in a group is combining the great minds from different perspectives and coming up with something extremely great, compared with when you're working alone. At the same time, information can generate vitality in the project you're working on. No matter how many heads you've got together, without information, you can't go very far. The perfect situation would be a combination of working with information and people, and I'm confident of my abilities in both areas.

18.Do you have the qualifications and personal characteristics necessary for success in your chosen career?

I believe I have a combination of qualities to be successful in this career. First, I have a strong interest, backed by a solid, well-rounded, state-of-the-art education, especially in a career that is technically oriented. This basic ingredient, backed by love of learning, problem-solving skills, well-rounded interests, determination to succeed and excel, strong communication skills, and the ability to work hard, are the most important qualities that will help me succeed in this career. To succeed, you also need a natural curiosity about how systems work -- the kind of curiosity I demonstrated when I upgraded my two computers recently. Technology is constantly changing, so you must a fast learner just to keep up or you will be overwhelmed. All of these traits combine to create a solid team member in the ever-changing field of information systems. I am convinced that I possess these characteristics and am ready to be a successful team member for your firm.

19.What are your weak points?

Don’t say you have one, but give one that is really a “positive in disguise.” I am sometimes impatient and do to much work myself when we are working against tight deadlines.” Or “I compliment and praise my staff, but feel I can improve.”

20.What personal weakness has caused you the greatest difficulty in school or on the job?

My greatest weakness had been delegation. I would take it upon myself to do many small projects throughout my shift as a manager that could have been done by others in an attempt to improve my workers' efficiency. Once I realized that I was doing more work than the other assistant managers, and they were achieving better results, I reevaluated what I was doing. I quickly realized that if I assigned each person just one small project at the beginning of their shift, clearly state expectations for the project, and then follow up that everything would get done, and I could manage much more efficiently and actually accomplish much more.

21.How has your education prepared you for your career?

This is a broad question and you need to focus on the behavioral examples in your educational background which specifically align to the required competencies for the career.

An example: “My education has focused on not only the learning the fundamentals, but also on the practical application of the information learned within those classes. For example, I played a lead role in a class project where we gathered and analyzed best practice data from this industry. Let me tell you more about the results . . .”

Focus on behavioral examples supporting the key competencies for the career. Then ask if they would like to hear more examples.

As you will note on my resume, I've taken not only the required core classes in the _____ field, I've also gone above and beyond. I've taken every class the college has to offer in the field and also completed an independent study project specifically in this area. But it's not just taking the classes to gain academic knowledge I've taken each class, both inside and outside of my major, with this profession in mind. So when we're studying _____ in _____, I've viewed it from the perspective of _____. In addition, I've always tried to keep a practical view of how the information would apply to my job. Not just theory, but how it would actually apply. My capstone course project in my final semester involved developing a real-world model of _____, which is very similar to what might be used within your company...


22.Have you ever had a conflict with a boss or professor? How was it resolved?

Note that if you say no, most interviewers will keep drilling deeper to find a conflict. The key is how you behaviorally reacted to conflict and what you did to resolve it.

For example: “Yes, I have had conflicts in the past. Never major ones, but there have been disagreements that needed to be resolved. I've found that when conflict occurs, it helps to fully understand the other person’s perspective, so I take time to listen to their point of view, and then I seek to work out a collaborative solution. For example . . .”

Focus your answer on the behavioral process for resolving the conflict and working collaboratively.

23.If I were to ask your professors to describe you, what would they say?

This is a threat of reference check question. Do not wait for the interview to know the answer. Ask any prior bosses or professors in advance. And if they’re willing to provide a positive reference, ask them for a letter of recommendation.

Then you can answer the question like this:
“I believe she would say I'm a very energetic person, that I’m results oriented and one of the best people she has ever worked with. Actually, I know she would say that, because those are her very words. May I show you her letter of recommendation?”

So be prepared in advance with your letters of recommendation.

24.Tell me about a time when you had to plan and coordinate a project from start to finish.

I headed up a project which involved customer service personnel and technicians. I organized a meeting to get everyone together to brainstorm and get his or her input. From this meeting I drew up a plan, taking the best of the ideas. I organized teams, balancing the mixture of technical and non-technical people. We had a deadline to meet, so I did periodic checks with the teams. After three weeks, we were exceeding expectations, and were able to begin implementation of the plan. It was a great team effort, and a big success. I was commended by management for my leadership, but I was most proud of the team spirit and cooperation which it took to pull it off.

25.Describe a situation where others you were working with on a project disagreed with your ideas. What did you do?

I was on a project team in a business class in my freshman year in college, The group brainstormed ideas for the video we were assigned to produce, and everyone but me was leaning toward an idea that would be easy. I suggested instead an idea that would be more difficult but would be something different that no other group would be doing. I used my communications skills to persuade the rest of the group to use my idea. During the project, we really learned what teamwork was all about, became a close team, and ended up putting a lot of hard work into the project. All the team members ended up feeling very proud of the video, and they thanked me for the idea -- for which we earned an A.

26.Why did you choose to attend your college?

My college has always had a reputation as having an excellent accounting department, so I knew that if I enrolled there, I would achieve first-class preparation for my chosen career field. It is also a highly accredited school known for satisfying employers with the preparation of its graduates -- that's why companies like yours recruit at my school -- the school produces top graduates. The school offers an excellent liberal-arts background, which research shows equips graduates with numerous qualities, such as versatility and strong critical-thinking skills. Finally, having visited the campus before enrolling, I knew that the business school emphasized group projects. During my four years in the school, I participated in more than 35 group projects, which taught me invaluable teamwork, communication, and interpersonal skills.

27.What changes would you make at your college?

My major department had a wonderful internship program, and I was able to complete three valuable internships with my department's guidance. Some other departments in the business school don't have internship programs that are as strong as my department's. I'd like to see all the departments have strong internship programs so all my school's business grads would have the same opportunities that I had.

28.How will the academic program and coursework you've taken benefit your career?

As you will note on my resume, I've taken not only the required core classes for the finance field, I've also gone above and beyond by double majoring in accounting. I doubled majored since I knew that the financial consulting field requires much knowledge of portfolio analysis and understanding of the tax laws. I believe that my success in both areas of study have specifically prepared me for this area. But it's not just taking the classes in these two areas that allow me to offer Merrill Lynch clients more. I minored in Spanish to understand the growing Hispanic clientele in the Central Florida area, which as you are well aware, is a growing source of revenue for the industry. If you like, I can elaborate on other aspects of my education further.


29.What were your favorite classes? Why?

My favorite classes have been the ones pertaining to my major, which is marketing. These classes have laid the groundwork for my career in marketing. They have also taught me skills that I can bring to my employer, ranging from communication skills to interacting with others.

30. Do you enjoy doing independent research?
Are you the type of student for whom conducting independent research has been a positive experience?

Yes, I love it. I thoroughly enjoyed my senior research in college while many others in my class were miserable. I was never tired of learning more about my topic and found it exhilarating to be researching something that had not been studied before.


31.Who were your favorite professors? Why? Describe the type of professor that has created the most beneficial learning experience for you.

My favorite professors were the ones who gave me hands-on learning experiences that I can apply to my career. Any person can make you memorize the quadratic equation, but someone who can show you how to use it, and why, were the professors I liked. I liked teachers who realized that sometimes there is more then one answer and everyone thinks differently.

32.Why is your GPA not higher? Do you think that your grades are a indication of your academic achievement?

I have focused much of my energy on work and obtaining real-world experience. I commend my classmates who have earned high GPAs, but I also feel it's important to be well-rounded. In addition to work experience, I participated in sports and extracurricular activities in school. These activities taught me leadership, communication, and teamwork skills. Sometimes my heavy load has not allowed me to keep up with some of my studies, but I have learned an enormous amount that I can apply in my future industry. As you will discover if you talk to my supervisors, my ability to work effectively is much more reflective of my future potential than is my GPA.


33.Do you have any plans for further education? What plans do you have for continued study? An advanced degree?

I plan to continue my education for the rest of my life. In any technology-related field, keeping up to date through continuing education is of the utmost importance. Continuing education can include on-the-job training, courses sponsored by the employer, and courses taken in new technologies as they emerge. I plan to be not only a career employee but a career student so that I can be the best information systems analyst I can be. I will ensure, however, that any education I pursue not only doesn't interfere with my job or the company's policies, but will enhance my value as an employee.

34.Give an example of how you applied knowledge from previous coursework to a project in another class.

Last semester I was taking a microeconomics and a statistics course. One of the microeconomics projects dealt with showing the relationship between the probability that customers would stop buying a product if the price was raised a certain amount. Through what I learned in statistics I could find the median where the price was the highest and still kept most of the customers happy.

35. Describe a situation in which you found that your results were not up to your professor's or supervisor's expectations. What happened? What action did you take?

Recently I was asked to put together a proposal for a migration of network systems. Misunderstanding my boss, I thought it was just an informal paper. When I presented it to him days later, he was upset with the quality since it had to be presented to our VP. I explained my misunderstanding, apologized, reworked the paper, and had it back to him with enough time for him to review it before he presented it successfully at the meeting

36.What do you know about our organization?

Research the target company before the interview. Basic research is the only way to prepare for this question. Do your homework, and you’ll score big on this question. Talk about products, services, history and people, especially any friends that work there. “But I would love to know more, particularly from your point of view. Do we have time to cover that now?

This question is one reason to do some research on the organization before the interview. Find out where they have been and where they are going. What are the current issues and who are the major players?

37.What experience do you have?

Try to cite experience relevant to the company’s concerns. Also, try answering these questions with a question: “Are you looking for overall experience or experience in some specific area of special interest to you?” Let the interviewer’s response guide your answer.

What experience do you have in this field? Speak about specifics that relate to the position you are applying for. If you do not have specific experience, get as close as you can.

I think I have my current job because of my experiences abroad. Those experiences gave me greater self-confidence and a greater understanding of myself, which led to my willingness to uproot myself and try new work in a new location.”

38.According to your definition of success, how successful have you been so far?

Be prepared to define success, and then respond (consistent record of responsibility)
You should always answer yes and briefly explain why. A good explanation is that you have set goals, and you have met some and are on track to achieve the others.

39. How has your college experience prepared you for a business career?

Emphasize your best and favorite subjects. If grades were average, talk about leadership or jobs you took to finance your education. Talk about extra-curricular activities (clubs, sports, volunteer work)

I have prepared myself to transition into the the work force through real-world experience involving travel abroad, internship, and entrepreneurial opportunities. While interning with a private organization in Ecuador, I developed a 15-page marketing plan composed in Spanish that recommended more effective ways the company could promote its services. I also traveled abroad on two other occasions in which I researched the indigenous culture of the Mayan Indians in Todos Santos, Guatemala, and participate din a total language immersion program in Costa Rica. As you can see from my academic, extracurricular, and experiential background, I have unconditionally committed myself to success as a marketing professional.

40.What do you look for in a job?

Flip this one over. Despite the question, the employer isn’t really interested in what you are looking for. He’s interested in what he is looking for. Address his interests, rather than yours. Use words like “contribute,” “enhance,” “improve,” and “team environment.” Fit your answer to their needs Relate your preferences and satisfiers/dissatisfiers to the job opening. ---------------------------------------------------------------------------------
---------------------------------------------------------------------------------

Friday, October 01, 2004

AutoNumber And Identity Functionality in Oracle

Developers who are used to AutoNumber columns in MS Access or Identity columns in SQL Server often complain when they have to manually populate primary key columns using sequences. This type of functionality is easily implemented in Oracle using triggers.First we create a table with a suitable primary key column and a sequence to support it:
CREATE TABLE departments (
ID NUMBER(10) NOT NULL,
DESCRIPTION VARCHAR2(50) NOT NULL);
ALTER TABLE departments ADD (
CONSTRAINT dept_pk PRIMARY KEY (ID));
CREATE SEQUENCE dept_seq;Next we create a trigger to populate the ID column if it's not specified in the insert:
CREATE OR REPLACE TRIGGER dept_bir
BEFORE INSERT ON departments
FOR EACH ROW
WHEN (:new.id IS NULL)
BEGIN
SELECT dept_seq.NEXTVAL
INTO :new.id
FROM dual;
END;
/Finally we can test it using the automatic and manual population methods:
SQL> INSERT INTO departments (description)
2 VALUES ('Development');
1 row created.
SQL> SELECT * FROM departments;
ID DESCRIPTION
---------- --------------------------------------------------
1 Development
1 row selected.
SQL> INSERT INTO departments (id, description)
2 VALUES (dept_seq.NEXTVAL, 'Accounting');
1 row created.
SQL> SELECT * FROM departments;
ID DESCRIPTION
---------- --------------------------------------------------
1 Development
2 Accounting
2 rows selected.
SQL>The trigger can be modified to give slightly different results. If the insert trigger needs to perform more functionality than this one task you may wish to do something like:
CREATE OR REPLACE TRIGGER dept_bir
BEFORE INSERT ON departments
FOR EACH ROW
BEGIN
SELECT NVL(:new.id, dept_seq.NEXTVAL)
INTO :new.id
FROM dual;

-- Do more processing here.
END;
/To overwrite any values passed in you should do the following:
CREATE OR REPLACE TRIGGER dept_bir
BEFORE INSERT ON departments
FOR EACH ROW
BEGIN
SELECT dept_seq.NEXTVAL
INTO :new.id
FROM dual;
END;
/To error if a value is passed in you should do the following:
CREATE OR REPLACE TRIGGER dept_bir
BEFORE INSERT ON departments
FOR EACH ROW
BEGIN
IF :new.is IS NOT NULL THEN
RAISE_APPLICATION_ERROR(-20000, 'ID cannot be specified');
ELSE
SELECT dept_seq.NEXTVAL
INTO :new.id
FROM dual;
END IF;
END;
/Hope this helps.
http://www.oracle-base.com/articles/8i/AutoNumber.php

Tuesday, September 07, 2004

10 Tools for Dot Net Developer

http://www.microsoft.com/china/MSDN/library/enterprisedevelopment/softwaredev/TenMHToolEDevShouDN.mspx欢迎来到 MSDN > 企业开发
每个开发人员现在应该下载的十种必备工具
发布日期: 7/20/2004 更新日期: 7/20/2004
本文自发布以来已经增加了新信息。
请参阅下面的编辑更新。
本文讨论:

用于编写单元测试的 NUnit

用于创建代码文档资料的 NDoc

用于生成解决方案的 NAnt

用于生成代码的 CodeSmith

用于监视代码的 FxCop

用于编译少量代码的 Snippet Compiler

两种不同的转换器工具:ASP.NET 版本转换器和 Visual Studio .NET 项目转换器

用于生成正则表达式的 Regulator

用于分析程序集的 .NET Reflector
本文使用了下列技术:
.NET、C# 或 Visual Basic .NET、Visual Studio .NET
除非您使用能够获得的最佳工具,否则您无法期望生成一流的应用程序。除了像 Visual Studio®.NET 这样的著名工具以外,还可以从 .NET 社区获得许多小型的、不太为人所知的工具。在本文中,我将向您介绍一些目前可以获得的、面向 .NET 开发的最佳免费工具。我将引导您完成一个有关如何使用其中每种工具的快速教程 — 一些工具在许多时候可以使您节约一分钟,而另一些工具则可能彻底改变您编写代码的方式。因为我要在本篇文章中介绍如此之多的不同工具,所以我无法详尽讨论其中每种工具,但您应该了解到有关每种工具的足够信息,以便判断哪些工具对您的项目有用。
本页内容

Snippet Compiler

Regulator

CodeSmith

生成自定义模板

NUnit

编写 NUnit 测试

FxCop

Lutz Roeder 的 .NET Reflector

NDoc

NAnt

实际运行的 NAnt

转换工具

小结
Snippet Compiler
Snippet Compiler 是一个基于 Windows® 的小型应用程序,您可以通过它来编写、编译和运行代码。如果您具有较小的代码段,并且您不希望为其创建完整的 Visual Studio .NET 项目(以及伴随该项目的所有文件),则该工具将很有用。
例如,假设我希望向您说明如何从 Microsoft?.NET 框架中启动另一个应用程序。在 Snippet Compiler 中,我将通过新建一个能够创建小型控制台应用程序的文件开始。可以在该控制台应用程序的 Main 方法内部创建代码片段,而这正是我要在这里做的事情。下面的代码片段演示了如何从 .NET 框架中创建记事本实例: System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.FileName= "notepad.exe";
proc.Start();
proc.WaitForExit();
当然该代码片段本身无法编译,而这正是 Snippet Compiler 的用武之地。图 1 显示了 Snippet Compiler 中的这一代码示例。
图 1 Snippet Compiler
要测试该代码片段,只须按 play(运行)按钮(绿色三角形),它就会在调试模式下运行。该代码片段将生成一个弹出式控制台应用程序,并且将显示记事本。当您关闭记事本时,该控制台应用程序也将关闭。
就我个人而言,我是在尝试为某位向我求助的人士创建一个小型示例时,才发现 Snippet Compiler 是如此宝贵的 — 如果不使用该工具,则我通常必须新建一个项目,确保每个部分都能编译通过,然后将代码片段发送给求助者,并删除该项目。Snippet Compiler 使得这一过程变得更加容易、更加愉快。
Snippet Compiler 由 Jeff Key 编写,并且可以从 http://www.sliver.com/dotnet/SnippetCompiler 下载。
返回页首
Regulator
Regulator 是最后一个添加到我的头等工具清单中的。它是一种很有特色的工具,能够使生成和测试正则表达式变得很容易。人们对正则表达式重新产生了兴趣,因为它们在 .NET 框架中受到很好的支持。正则表达式用来基于字符、频率和字符顺序定义字符串中的模式。它们最常见的用途是作为验证用户输入有效性的手段或者作为在较大字符串中查找字符串的方法 — 例如,在 Web 页上查找 URL 或电子邮件地址。
Regulator 使您可以输入一个正则表达式以及一些针对其运行该表达式的输入内容。这样,在应用程序中实现该正则表达式之前,您可以了解它将产生什么效果以及它将返回哪些种类的匹配项。图 2 显示了带有简单正则表达式的 Regulator。
文档中包含该正则表达式 — 在该示例中,它是 [0-9]*,应该匹配一行中任意数量的数字。右下侧的框中含有针对该正则表达式的输入,而左下侧的框显示了该正则表达式在输入内容中找到的匹配项。在这样的单独应用程序中编写和测试正则表达式,要比尝试在您的应用程序中处理它们容易得多。
Regulator 中的最佳功能之一是能够在 regexlib.com 搜索联机正则表达式库。例如,如果您在搜索框中输入字符串“phone”,您将找到 20 种以上能够匹配各种电话号码的不同的正则表达式,包括用于英国、澳大利亚的表达式以及其他许多电话号码。Regulator 由 Roy Osherove 编写,并且可以在 http://royo.is-a-geek.com/regulator 下载。
返回页首
CodeSmith
CodeSmith 是一种基于模板的代码生成工具,它使用类似于 ASP.NET 的语法来生成任意类型的代码或文本。与其他许多代码生成工具不同,CodeSmith 不要求您订阅特定的应用程序设计或体系结构。使用 CodeSmith,可以生成包括简单的强类型集合和完整应用程序在内的任何东西。
当您生成应用程序时,您经常需要重复完成某些特定的任务,例如编写数据访问代码或者生成自定义集合。CodeSmith 在这些时候特别有用,因为您可以编写模板自动完成这些任务,从而不仅提高您的工作效率,而且能够自动完成那些最为乏味的任务。CodeSmith 附带了许多模板,包括对应于所有 .NET 集合类型的模板以及用于生成存储过程的模板,但该工具的真正威力在于能够创建自定义模板。为了使您能够入门,我将快速介绍一下如何生成自定义模板。
返回页首
生成自定义模板
CodeSmith 模板只是一些可以在任意文本编辑器中创建的文本文件。它们的唯一要求是用 .cst 文件扩展名来保存它们。我将要生成的示例模板将接受一个字符串,然后基于该字符串生成一个类。创建模板的第一步是添加模板头,它可声明模板的语言、目标语言以及简要模板说明:
模板的下一部分是属性声明,在这里可声明将在模板每次运行时指定的属性。就该模板而言,我要使用的唯一属性只是一个字符串,因此属性声明如下所示:
该属性声明将使 ClassName 属性出现在 CodeSmith 属性窗口中,以便可以在模板运行时指定它。下一步是实际生成模板主体,它非常类似于用 ASP.NET 进行编码。您可以在图 3 中查看该模板的主体。[编辑更新 — 6/16/2004:图 3 中的代码已被更新,以便对多线程操作保持安全。]
正如您所见,该模板接受字符串输入并使用该类名生成单独的类。在模板主体中,使用与 ASP.NET 中相同的起始和结束标记。在该模板中,我只是插入属性值,但您还可以在这些标记内部使用任意类型的 .NET 代码。在该模板完成之后,您就可以通过双击它或者从 CodeSmith 应用程序中打开它将其加载到 CodeSmith 中。图 4 显示了已经加载到 CodeSmith 中的该模板。
您可以看到左侧的属性正是我在该模板中声明的属性。如果我输入“SingletonClass”作为类名,并单击 Generate 按钮,则将生成图 3 的底部显示的类。
CodeSmith 使用起来相当容易,如果能够正确应用,则可以产生一些令人难以置信的结果。面向代码生成的应用程序中最常见的部分之一是数据访问层。CodeSmith 包括一个名为 SchemaExplorer 的特殊的程序集,可用来从表、存储过程或几乎任何其他 SQL Server? 对象生成模板。
CodeSmith 由 Eric J. Smith 编写,并且可以在 http://www.ericjsmith.net/codesmith 下载。
返回页首
NUnit
NUnit 是为 .NET 框架生成的开放源代码单元测试框架。NUnit 使您可以用您喜欢的语言编写测试,从而测试应用程序的特定功能。当您首次编写代码时,单元测试是一种测试代码功能的很好方法,它还提供了一种对应用程序进行回归测试的方法。NUnit 应用程序提供了一个用于编写单元测试的框架,以及一个运行这些测试和查看结果的图形界面。
返回页首
编写 NUnit 测试
作为示例,我将测试 .NET 框架中 Hashtable 类的功能,以确定是否可以添加两个对象并且随后检索这些对象。我的第一步是添加对 NUnit.Framework 程序集的引用,该程序集将赋予我对 NUnit 框架的属性和方法的访问权。接下来,我将创建一个类并用 TestFixture 属性标记它。该属性使 NUnit 可以知道该类包含 NUnit 测试: using System;
using System.Collections;
using NUnit.Framework;
namespace NUnitExample
{
[TestFixture]
public class HashtableTest {
public HashtableTest() {

}
}
}
下一步,我将创建一个方法并用 [Test] 属性标记它,以便 NUnit 知道该方法是一个测试。然后,我将建立一个 Hashtable 并向其添加两个值,再使用 Assert.AreEqual 方法查看我是否可以检索到与我添加到 Hashtable 的值相同的值,如下面的代码所示: [Test]
public void HashtableAddTest()
{
Hashtable ht = new Hashtable();

ht.Add("Key1", "Value1");
ht.Add("Key2", "Value2");
Assert.AreEqual("Value1", ht["Key1"], "Wrong object returned!");
Assert.AreEqual("Value2", ht["Key2"], "Wrong object returned!");
}
这将确认我可以首先向 Hashtable 中添加值并随后检索相应的值 — 这是一个很简单的测试,但能够表现 NUnit 的功能。存在许多测试类型以及各种 Assert 方法,可使用它们来测试代码的每个部分。
要运行该测试,我需要生成项目,在 NUnit 应用程序中打开生成的程序集,然后单击 Run 按钮。图 5 显示了结果。当我看到那个大的绿色条纹时,我有一种兴奋和头晕的感觉,因为它让我知道测试已经通过了。这个简单的示例表明 NUnit 和单元测试是多么方便和强大。由于能够编写可以保存的单元测试,并且每当您更改代码时都可以重新运行该单元测试,您不仅可以更容易地检测到代码中的缺陷,而且最终能够交付更好的应用程序。
图 5 NUnit
NUnit 是一个开放源代码项目,并且可以从 http://www.nunit.org/ 下载。还有一个优秀的 NUnit Visual Studio .NET 外接程序,它使您可以直接从 Visual Studio 中运行单元测试。您可以在 http://sourceforge.net/projects/nunitaddin 找到它。有关 NUnit 及其在测试驱动开发中的地位的详细信息,请参阅文章“Test-Driven C#: Improve the Design and Flexibility of Your Project with Extreme Programming Techniques”(MSDN ®Magazine 2004 年 4 月刊)。
返回页首
FxCop
.NET 框架非常强大,这意味着存在创建优秀应用程序的极大可能,但是也同样存在创建劣质程序的可能。FxCop 是有助于创建更好的应用程序的工具之一,它所采用的方法是:使您能够分析程序集,并使用一些不同的规则来检查它是否符合这些规则。FxCop 随附了由 Microsoft 创建的固定数量的规则,但您也可以创建并包括您自己的规则。例如,如果您决定所有的类都应该具有一个不带任何参数的默认构造函数,则可以编写一条规则,以确保程序集的每个类上都具有一个构造函数。这样,无论是谁编写该代码,您都将获得一定程度的一致性。如果您需要有关创建自定义规则的详细信息,请参阅 John Robbins 的有关该主题的 Bugslayer 专栏文章(MSDN ® Magazine 2004 年 6 月刊)。
那么,让我们观察一下实际运行的 FxCop,并且看一下它在我一直在处理的 NUnitExample 程序集中找到哪些错误。当您打开 FxCop 时,您首先需要创建一个 FxCop 项目,然后向其添加您要测试的程序集。在将该程序集添加到项目以后,就可以按 Analyze,FxCop 将分析该程序集。图 6 中显示了在该程序集中找到的错误和警告。
FxCop 在我的程序集中找到了几个问题。您可以双击某个错误以查看详细信息,包括规则说明以及在哪里可以找到更多信息。(您可以做的一件有趣的事情是在框架程序集上运行 FxCop 并查看发生了什么事情。)
FxCop 可以帮助您创建更好的、更一致的代码,但它无法补偿低劣的应用程序设计或非常简单拙劣的编程。FxCop 也不能替代对等代码检查,但是因为它可以在进行代码检查之前捕获大量错误,所以您可以花费更多时间来解决严重的问题,而不必担心命名约定。FxCop 由 Microsoft 开发,并且可以从 http://www.gotdotnet.com/team/fxcop 下载。
返回页首
Lutz Roeder 的 .NET Reflector
下一个必不可少的工具称为 .NET Reflector,它是一个类浏览器和反编译器,可以分析程序集并向您展示它的所有秘密。.NET 框架向全世界引入了可用来分析任何基于 .NET 的代码(无论它是单个类还是完整的程序集)的反射概念。反射还可以用来检索有关特定程序集中包含的各种类、方法和属性的信息。使用 .NET Reflector,您可以浏览程序集的类和方法,可以分析由这些类和方法生成的 Microsoft 中间语言 (MSIL),并且可以反编译这些类和方法并查看 C# 或 Visual Basic ®.NET 中的等价类和方法。
为了演示 .NET Reflector 的工作方式,我将加载和分析前面已经显示的 NUnitExample 程序集。图 7 显示了 .NET Reflector 中加载的该程序集。
图 7 NUnitExample 程序集
在 .NET Reflector 内部,有各种可用来进一步分析该程序集的工具。要查看构成某个方法的 MSIL,请单击该方法并从菜单中选择 Disassembler。
除了能够查看 MSIL 以外,您还可以通过选择 Tools 菜单下的 Decompiler 来查看该方法的 C# 形式。通过在 Languages 菜单下更改您的选择,您还可以查看该方法被反编译到 Visual Basic .NET 或 Delphi 以后的形式。以下为 .NET Reflector 生成的代码: public void HashtableAddTest()
{
Hashtable hashtable1;
hashtable1 = new Hashtable();
hashtable1.Add("Key1", "Value1");
hashtable1.Add("Key2", "Value2");
Assert.AreEqual("Value1", hashtable1["Key1"],
"Wrong object returned!");
Assert.AreEqual("Value2", hashtable1["Key2"],
"Wrong object returned!");
}
前面的代码看起来非常像我为该方法实际编写的代码。以下为该程序集中的实际代码: public void HashtableAddTest()
{
Hashtable ht = new Hashtable();

ht.Add("Key1", "Value1");
ht.Add("Key2", "Value2");
Assert.AreEqual("Value1", ht["Key1"],
"Wrong object returned!");
Assert.AreEqual("Value2", ht["Key2"],
"Wrong object returned!");
}
尽管上述代码中存在一些小的差异,但它们在功能上是完全相同的。
虽然该示例是一种显示实际代码与反编译代码之间对比的好方法,但在我看来,它并不代表 .NET Reflector 所具有的最佳用途 — 分析 .NET 框架程序集和方法。.NET 框架提供了许多执行类似操作的不同方法。例如,如果您需要从 XML 中读取一组数据,则存在多种使用 XmlDocument、XPathNavigator 或 XmlReader 完成该工作的不同方法。通过使用 .NET Reflector,您可以查看 Microsoft 在编写数据集的 ReadXml 方法时使用了什么,或者查看他们在从配置文件读取数据时做了哪些工作。.NET Reflector 还是一个了解以下最佳实施策略的优秀方法:创建诸如 HttpHandlers 或配置处理程序之类的对象,因为您可以了解到 Microsoft 工作组实际上是如何在框架中生成这些对象的。
.NET Reflector 由 Lutz Roeder 编写,并且可以从 http://www.aisto.com/roeder/dotnet 下载。
返回页首
NDoc
编写代码文档资料几乎总是一项令人畏惧的任务。我所说的不是早期设计文档,甚至也不是更为详细的设计文档;我说的是记录类上的各个方法和属性。NDoc 工具能够使用反射来分析程序集,并使用从 C# XML 注释生成的 XML 自动为代码生成文档资料。XML 注释仅适用于 C#,但有一个名为 VBCommenter 的 Visual Studio .NET Power Toy,它能够为 Visual Basic .NET 完成类似的工作。此外,下一版本的 Visual Studio 将为更多语言支持 XML 注释。
使用 NDoc 时,您仍然在编写代码的技术文档,但您是在编写代码的过程中完成了文档编写工作(在 XML 注释中),而这更容易忍受。使用 NDoc 时,第一步是为您的程序集打开 XML 注释生成功能。右键单击该项目并选择 Properties Configuration Properties Build,然后在 XML Documentation File 选项中输入用于保存 XML 文件的路径。当该项目生成时,将创建一个 XML 文件,其中包含所有 XML 注释。下面是 NUnit 示例中的一个用 XML 编写了文档的方法: ///
/// This test adds a number of values to the Hashtable collection
/// and then retrieves those values and checks if they match.
///

[Test]
public void HashtableAddTest()
{
//Method Body Here
}
有关该方法的 XML 文档资料将被提取并保存在 XML 文件中,如下所示:
This test adds a number of values to the Hashtable collection
and then retrieves those values and checks if they match.


NDoc 使用反射来考察您的程序集,然后读取该文档中的 XML,并且将它们进行匹配。NDoc 使用该数据来创建任意数量的不同文档格式,包括 HTML 帮助文件 (CHM)。在生成 XML 文件以后,下一步是将程序集和 XML 文件加载到 NDoc 中,以便可以对它们进行处理。通过打开 NDoc 并单击 Add 按钮,可以容易地完成该工作。
在将程序集和 XML 文件加载到 NDoc 中并且使用可用的属性范围自定义输出以后,单击 Generate 按钮将启动生成文档资料的过程。使用默认的属性,NDoc 可以生成一些非常吸引人并且实用的 .html 和 .chm 文件,从而以快速有效的方式自动完成原来非常乏味的任务。
NDoc 是一个开放源代码项目,并且可以从 http://ndoc.sourceforge.net/ 下载。
返回页首
NAnt
NAnt 是一个基于 .NET 的生成工具,与当前版本的 Visual Studio .NET 不同,它使得为您的项目创建生成过程变得非常容易。当您拥有大量从事单个项目的开发人员时,您不能依赖于从单个用户的座位进行生成。您也不希望必须定期手动生成该项目。您更愿意创建每天晚上运行的自动生成过程。NAnt 使您可以生成解决方案、复制文件、运行 NUnit 测试、发送电子邮件,等等。遗憾的是,NAnt 缺少漂亮的图形界面,但它的确具有可以指定应该在生成过程中完成哪些任务的控制台应用程序和 XML 文件。注意,MSBuild(属于 Visual Studio 2005 的新的生成平台)为每种健壮的生成方案进行了准备,并且由基于 XML 的项目文件以类似的方式驱动。
返回页首
实际运行的 NAnt
在该示例中,我将为前面创建的 NUnitExample 解决方案创建一个 NAnt 版本文件。首先,我需要创建一个具有 .build 扩展名的 XML 文件,将其放在我的项目的根目录中,然后向该文件的顶部添加一个 XML 声明。我需要添加到该文件的第一个标记是 project 标记:

The NUnit Example Project

项目标记还用于设置项目名称、默认目标以及基目录。Description 标记用于设置该项目的简短说明。
接下来,我将添加 property 标记,该标记可用于将设置存储到单个位置(随后可以从文件中的任意位置访问该位置)。在该例中,我将创建一个名为 debug 的属性,我可以随后将其设置为 true 或 false,以反映我是否要在调试配置下编译该项目。(最后,这一特定属性并未真正影响如何生成该项目;它只是您设置的一个变量,当您真正确定了如何生成该项目时将读取该变量。)
接下来,我需要创建一个 target 标记。一个项目可以包含多个可在 NAnt 运行时指定的 target。如果未指定 target,则使用默认 target(我在 project 元素中设置的 target)。在该示例中,默认 target 是 build。让我们观察一下 target 元素,它将包含大多数生成信息:

在 target 元素内,我将把 target 的名称设置为 build,并且创建有关该 target 将做哪些工作的说明。我还将创建一个 csc 元素,该元素用于指定应该传递给 csc C# 编译器的数据。让我们看一下该 csc 元素:







首先,我必须设置该 csc 元素的 target。在该例中,我将创建一个 .dll 文件,因此我将 target 设置为 library。接下来,我必须设置 csc 元素的 output,它是将要创建 .dll 文件的位置。最后,我需要设置 debug 属性,它确定了是否在调试中编译该项目。因为我在前面创建了一个用于存储该值的属性,所以我可以使用下面的字符串来访问该属性的值:${debug}。Csc 元素还包含一些子元素。我需要创建两个元素:references 元素将告诉 NAnt 需要为该项目引用哪些程序集,sources 元素告诉 NAnt 要在生成过程中包含哪些文件。在该示例中,我引用了 NUnit.Framework.dll 程序集并包含了 HashtableTest.cs 文件。图 8 中显示了完整的生成文件。(您通常还要创建一个干净的 target,用于删除生成的文件,但为了简洁起见,我已经将其省略。)
要生成该文件,我需要转到我的项目的根目录(生成文件位于此处),然后从该位置执行 nant.exe。如果生成成功,您可以在该应用程序的 bin 目录中找到 .dll 和 .pdb 文件。尽管使用 NAnt 肯定不像在 Visual Studio 中单击 Build 那样简单,但它仍然是一种非常强大的工具,可用于开发按自动计划运行的生成过程。NAnt 还包括一些有用的功能,例如能够运行单元测试或者复制附加文件(这些功能没有受到当前 Visual Studio 生成过程的支持)。
NAnt 是一个开放源代码项目,并且可以从 http://nant.sourceforge.net/ 下载。
返回页首
转换工具
我已经将两个独立的工具合在一起放在标题“转换工具”下面。这两个工具都非常简单,但又可能极为有用。第一个工具是 ASP.NET 版本转换器,它可用于转换 ASP.NET(虚拟目录在它下面运行)的版本。第二个工具是 Visual Studio Converter,它可用于将项目文件从 Visual Studio .NET 2002 转换到 Visual Studio .NET 2003。
当 IIS 处理请求时,它会查看正在请求的文件的扩展名,然后基于该 Web 站点或虚拟目录的扩展名映射,将请求委派给 ISAPI 扩展或者自己处理该请求。这正是 ASP.NET 的工作方式;将为所有 ASP.NET 扩展名注册扩展名映射,并将这些扩展名映射导向 aspnet_isapi.dll。这种工作方式是完美无缺的,除非您安装了 ASP.NET 1.1 — 它会将扩展名映射升级到新版本的 aspnet_isapi.dll。当在 ASP.NET 1.0 上生成的应用程序试图用 1.1 版运行时,这会导致错误。要解决该问题,可以将所有扩展名映射重新转换到 1.0 版的 aspnet_isapi.dll,但是由于有 18 种扩展名映射,所以手动完成这一工作将很枯燥。这正是 ASP.NET 版本转换器可以发挥作用的时候。使用这一小型实用工具,可以转换任何单个 ASP.NET 应用程序所使用的 .NET 框架的版本。
图 9 ASP.NET 版本转换器
图 9 显示了实际运行的 ASP.NET 版本转换器。它的使用方法非常简单,只须选择相应的应用程序,然后选择您希望该应用程序使用的 .NET 框架版本。该工具随后将使用 aspnet_regiis.exe 命令行工具将该应用程序转换到所选版本的框架。随着将来版本的 ASP.NET 和 .NET 框架的发布,该工具将变得更为有用。
ASP.NET 版本转换器由 Denis Bauer 编写,并且可以从 http://www.denisbauer.com/NETTools/ASPNETVersionSwitcher.aspx 下载。
Visual Studio .NET 项目转换器(参见图 10)非常类似于 ASP.NET 版本转换器,区别在于它用于转换 Visual Studio 项目文件的版本。尽管在 .NET 框架的 1.0 版和 1.1 版之间只有很小的差异,但一旦将项目文件从 Visual Studio .NET 2002 转换到 Visual Studio .NET 2003,将无法再把它转换回去。虽然这在大多数时候可能不会成为问题(因为在 .NET 框架 1.0 版和 1.1 版之间几乎没有什么破坏性的更改),但在某些时刻您可能需要将项目转换回去。该转换器可以将任何解决方案或项目文件从 Visual Studio 7.1 (Visual Studio .NET 2003) 转换到 Visual Studio 7.0 (Visual Studio .NET 2002),并在必要时进行反向转换。
图 10 Visual Studio .NET 项目转换器
Visual Studio .NET 项目转换器由 Dacris Software 编写。该工具可以从 http://www.codeproject.com/macro/vsconvert.asp 下载。
返回页首
小结
本文采用走马观花的方式介绍了上述工具,但我已经试图起码向您提供足够的信息以激起您的好奇心。我相信本文已经让您在某种程度上领悟了几个免费工具,您可以立即开始使用这些工具来编写更好的项目。同时,我还要敦促您确保自己拥有所有其他可以获得的合适工具,无论是最新版本的 Visual Studio、功能强大的计算机还是免费的实用工具。拥有合适的工具将使一切变得大不相同。
James Avery 是一位使用 .NET 和其他 Microsoft 技术的顾问。他已经撰写了许多书籍和文章,他的最新著作是《ASP.NET Setup and Configuration Pocket Reference》(Microsoft Press, 2003)。您可以通过 javery@infozerk.com 向他发送电子邮件,并且在 http://www.dotavery.com/blog 阅读他的网络日记。
本文摘自 MSDN Magazine2004 年 7 月刊。
该杂志可在各地的报摊购买,也可以订阅
转到原英文页面
返回页首
适合打印机打印的版本 通过电子邮件发送此页面 添加到收藏夹 备注