您的位置:首页 > 编程语言 > ASP

ASP.NET开发人员经常使用的三十三种代码

2011-12-01 09:40 337 查看
几年前,一篇《ASP.NET开发人员经常使用的三十三种代码》非常流行,它总结了一些经常在ASP.NET开发中使用到的代码,直接可以拿来使用。今天重读这篇文章,有感而发,善于总结也是进步,于是我也从我的项目中总结一些常用的代码片段,分享给各位园友。1.打开新的窗口并传送参数:  传送参数:response.write("<script>window.open(’*.aspx?id="+this.DropDownList1.SelectIndex+"&id1="+...+"’)</script>")  接收参数:stringa=Request.QueryString("id");stringb=Request.QueryString("id1");  2.为按钮添加对话框Button1.Attributes.Add("onclick","returnconfirm(’确认?’)");button.attributes.add("onclick","if(confirm(’areyousure...?’)){returntrue;}else{returnfalse;}")  3.删除表格选定记录intintEmpID=(int)MyDataGrid.DataKeys[e.Item.ItemIndex];stringdeleteCmd="DELETEfromEmployeewhereemp_id="+intEmpID.ToString()  4.删除表格记录警告privatevoidDataGrid_ItemCreated(Objectsender,DataGridItemEventArgse){ switch(e.Item.ItemType) {  caseListItemType.Item:  caseListItemType.AlternatingItem:  caseListItemType.EditItem:   TableCellmyTableCell;   myTableCell=e.Item.Cells[14];   LinkButtonmyDeleteButton;   myDeleteButton=(LinkButton)myTableCell.Controls[0];   myDeleteButton.Attributes.Add("onclick","returnconfirm(’您是否确定要删除这条信息’);");   break;  default:   break; }}  5.点击表格行链接另一页privatevoidgrdCustomer_ItemDataBound(objectsender,System.Web.UI.WebControls.DataGridItemEventArgse){ //点击表格打开 if(e.Item.ItemType==ListItemType.Item  e.Item.ItemType==ListItemType.AlternatingItem)  e.Item.Attributes.Add("onclick","window.open(’Default.aspx?id="+e.Item.Cells[0].Text+"’);");}  双击表格连接到另一页  在itemDataBind事件中if(e.Item.ItemType==ListItemType.Item  e.Item.ItemType==ListItemType.AlternatingItem){ stringOrderItemID=e.item.cells[1].Text; ... e.item.Attributes.Add("ondblclick","location.href=’../ShippedGrid.aspx?id="+OrderItemID+"’");}  双击表格打开新一页if(e.Item.ItemType==ListItemType.Item  e.Item.ItemType==ListItemType.AlternatingItem){ stringOrderItemID=e.item.cells[1].Text; ... e.item.Attributes.Add("ondblclick","open(’../ShippedGrid.aspx?id="+OrderItemID+"’)");}  ★特别注意:【?id=】处不能为【?id=】  6.表格超连接列传递参数<asp:HyperLinkColumnTarget="_blank"headertext="ID号"DataTextField="id"NavigateUrl="aaa.aspx?id=’ <%#DataBinder.Eval(Container.DataItem,"数据字段1")%>’&name=’<%#DataBinder.Eval(Container.DataItem,"数据字段2")%>’/>  7.表格点击改变颜色if(e.Item.ItemType==ListItemType.Item  e.Item.ItemType==ListItemType.AlternatingItem){ e.Item.Attributes.Add("onclick","this.style.backgroundColor=’#99cc00’;   this.style.color=’buttontext’;this.style.cursor=’default’;");}  写在DataGrid的_ItemDataBound里if(e.Item.ItemType==ListItemType.Item  e.Item.ItemType==ListItemType.AlternatingItem){e.Item.Attributes.Add("onmouseover","this.style.backgroundColor=’#99cc00’;   this.style.color=’buttontext’;this.style.cursor=’default’;");e.Item.Attributes.Add("onmouseout","this.style.backgroundColor=’’;this.style.color=’’;");}  8.关于日期格式  日期格式设定DataFormatString="{0:yyyy-MM-dd}"  我觉得应该在itembound事件中e.items.cell["你的列"].text=DateTime.Parse(e.items.cell["你的列"].text.ToString("yyyy-MM-dd"))  9.获取错误信息并到指定页面  不要使用Response.Redirect,而应该使用Server.Transfer  e.g//inglobal.asaxprotectedvoidApplication_Error(Objectsender,EventArgse){if(Server.GetLastError()isHttpUnhandledException)Server.Transfer("MyErrorPage.aspx");//其余的非HttpUnhandledException异常交给ASP.NET自己处理就okay了:)}  Redirect会导致post-back的产生从而丢失了错误信息,所以页面导向应该直接在服务器端执行,这样就可以在错误处理页面得到出错信息并进行相应的处理  10.清空CookieCookie.Expires=[DateTime];Response.Cookies("UserName").Expires=0  11.自定义异常处理//自定义异常处理类usingSystem;usingSystem.Diagnostics;namespaceMyAppException{ ///<summary> ///从系统异常类ApplicationException继承的应用程序异常处理类。 ///自动将异常内容记录到WindowsNT/2000的应用程序日志 ///</summary> publicclassAppException:System.ApplicationException {  publicAppException()  {   if(ApplicationConfiguration.EventLogEnabled)LogEvent("出现一个未知错误。");  } publicAppException(stringmessage) {  LogEvent(message); } publicAppException(stringmessage,ExceptioninnerException) {  LogEvent(message);  if(innerException!=null)  {   LogEvent(innerException.Message);  } } //日志记录类 usingSystem; usingSystem.Configuration; usingSystem.Diagnostics; usingSystem.IO; usingSystem.Text; usingSystem.Threading; namespaceMyEventLog {  ///<summary>  ///事件日志记录类,提供事件日志记录支持  ///<remarks>  ///定义了4个日志记录方法(error,warning,info,trace)  ///</remarks>  ///</summary>  publicclassApplicationLog  {   ///<summary>   ///将错误信息记录到Win2000/NT事件日志中   ///<paramname="message">需要记录的文本信息</param>   ///</summary>   publicstaticvoidWriteError(Stringmessage)   {    WriteLog(TraceLevel.Error,message);   }   ///<summary>   ///将警告信息记录到Win2000/NT事件日志中   ///<paramname="message">需要记录的文本信息</param>   ///</summary>   publicstaticvoidWriteWarning(Stringmessage)   {    WriteLog(TraceLevel.Warning,message);     }   ///<summary>   ///将提示信息记录到Win2000/NT事件日志中   ///<paramname="message">需要记录的文本信息</param>   ///</summary>   publicstaticvoidWriteInfo(Stringmessage)   {    WriteLog(TraceLevel.Info,message);   }   ///<summary>   ///将跟踪信息记录到Win2000/NT事件日志中   ///<paramname="message">需要记录的文本信息</param>   ///</summary>   publicstaticvoidWriteTrace(Stringmessage)   {    WriteLog(TraceLevel.Verbose,message);   }   ///<summary>   ///格式化记录到事件日志的文本信息格式   ///<paramname="ex">需要格式化的异常对象</param>   ///<paramname="catchInfo">异常信息标题字符串.</param>   ///<retvalue>   ///<para>格式后的异常信息字符串,包括异常内容和跟踪堆栈.</para>   ///</retvalue>   ///</summary>   publicstaticStringFormatException(Exceptionex,StringcatchInfo)   {    StringBuilderstrBuilder=newStringBuilder();    if(catchInfo!=String.Empty)    {     strBuilder.Append(catchInfo).Append("\r\n");    }    strBuilder.Append(ex.Message).Append("\r\n").Append(ex.StackTrace);    returnstrBuilder.ToString();   }   ///<summary>   ///实际事件日志写入方法   ///<paramname="level">要记录信息的级别(error,warning,info,trace).</param>   ///<paramname="messageText">要记录的文本.</param>   ///</summary>   privatestaticvoidWriteLog(TraceLevellevel,StringmessageText)   {    try    {     EventLogEntryTypeLogEntryType;     switch(level)     {      caseTraceLevel.Error:       LogEntryType=EventLogEntryType.Error;       break;      caseTraceLevel.Warning:       LogEntryType=EventLogEntryType.Warning;       break;      caseTraceLevel.Info:       LogEntryType=EventLogEntryType.Information;       break;      caseTraceLevel.Verbose:       LogEntryType=EventLogEntryType.SuccessAudit;       break;      default:       LogEntryType=EventLogEntryType.SuccessAudit;       break;     }     EventLogeventLog=newEventLog("Application",ApplicationConfiguration.EventLogMachineName,ApplicationConfiguration.EventLogSourceName);     //写入事件日志     eventLog.WriteEntry(messageText,LogEntryType);    }   catch{}//忽略任何异常  } }//classApplicationLog}  12.Panel横向滚动,纵向自动扩展<asp:panel></asp:panel>  13.回车转换成Tab<scriptlanguage="javascript"for="document"event="onkeydown"> if(event.keyCode==13&&event.srcElement.type!=’button’&&event.srcElement.type!=’submit’&&    event.srcElement.type!=’reset’&&event.srcElement.type!=’’&&event.srcElement.type!=’textarea’);   event.keyCode=9;</script>onkeydown="if(event.keyCode==13)event.keyCode=9"  14.DataGrid超级连接列DataNavigateUrlField="字段名"DataNavigateUrlFormatString="http://xx/inc/delete.aspx?ID={0}"  15.DataGrid行随鼠标变色privatevoidDGzf_ItemDataBound(objectsender,System.Web.UI.WebControls.DataGridItemEventArgse){ if(e.Item.ItemType!=ListItemType.Header) {  e.Item.Attributes.Add("onmouseout","this.style.backgroundColor=\""+e.Item.Style["BACKGROUND-COLOR"]+"\"");  e.Item.Attributes.Add("onmouseover","this.style.backgroundColor=\""+"#EFF3F7"+"\""); }}  16.模板列<ASP:TEMPLATECOLUMNvisible="False"sortexpression="demo"headertext="ID"><ITEMTEMPLATE><ASP:LABELtext=’<%#DataBinder.Eval(Container.DataItem,"ArticleID")%>’runat="server"width="80%"id="lblColumn"/></ITEMTEMPLATE></ASP:TEMPLATECOLUMN><ASP:TEMPLATECOLUMNheadertext="选中"><HEADERSTYLEwrap="False"horizontalalign="Center"></HEADERSTYLE><ITEMTEMPLATE><ASP:CHECKBOXid="chkExport"runat="server"/></ITEMTEMPLATE><EDITITEMTEMPLATE><ASP:CHECKBOXid="chkExportON"runat="server"enabled="true"/></EDITITEMTEMPLATE></ASP:TEMPLATECOLUMN>  后台代码protectedvoidCheckAll_CheckedChanged(objectsender,System.EventArgse){ //改变列的选定,实现全选或全不选。 CheckBoxchkExport; if(CheckAll.Checked) {  foreach(DataGridItemoDataGridIteminMyDataGrid.Items)  {   chkExport=(CheckBox)oDataGridItem.FindControl("chkExport");   chkExport.Checked=true;  } } else {  foreach(DataGridItemoDataGridIteminMyDataGrid.Items)  {   chkExport=(CheckBox)oDataGridItem.FindControl("chkExport");   chkExport.Checked=false;  } }}  17.数字格式化  【<%#Container.DataItem("price")%>的结果是500.0000,怎样格式化为500.00?】<%#Container.DataItem("price","{0:¥#,##0.00}")%>inti=123456;strings=i.ToString("###,###.00");  18.日期格式化  【aspx页面内:<%#DataBinder.Eval(Container.DataItem,"Company_Ureg_Date")%>  显示为:2004-8-1119:44:28  我只想要:2004-8-11】<%#DataBinder.Eval(Container.DataItem,"Company_Ureg_Date","{0:yyyy-M-d}")%>  应该如何改?  【格式化日期】  取出来,一般是object((DateTime)objectFromDB).ToString("yyyy-MM-dd");  【日期的验证表达式】  A.以下正确的输入格式:[2004-2-29],[2004-02-2910:29:39pm],[2004/12/31]^((\d{2}(([02468][048]) ([13579][26]))[\-\/\s]?((((0?[13578]) (1[02]))[\-\/\s]?((0?[1-9]) ([1-2][0-9]) (3[01]))) (((0?[469]) (11))[\-\/\s]?((0?[1-9]) ([1-2][0-9]) (30))) (0?2[\-\/\s]?((0?[1-9]) ([1-2][0-9]))))) (\d{2}(([02468][1235679]) ([13579][01345789]))[\-\/\s]?((((0?[13578]) (1[02]))[\-\/\s]?((0?[1-9]) ([1-2][0-9]) (3[01]))) (((0?[469]) (11))[\-\/\s]?((0?[1-9]) ([1-2][0-9]) (30))) (0?2[\-\/\s]?((0?[1-9]) (1[0-9]) (2[0-8]))))))(\s(((0?[1-9]) (1[0-2]))\:([0-5][0-9])((\s) (\:([0-5][0-9])\s))([AM PM am pm]{2,2})))?$  B.以下正确的输入格式:[0001-12-31],[99990930],[2002/03/03]^\d{4}[\-\/\s]?((((0[13578]) (1[02]))[\-\/\s]?(([0-2][0-9]) (3[01]))) (((0[469]) (11))[\-\/\s]?(([0-2][0-9]) (30))) (02[\-\/\s]?[0-2][0-9]))$  【大小写转换】HttpUtility.HtmlEncode(string);HttpUtility.HtmlDecode(string)  19.如何设定全局变量  Global.asax中  Application_Start()事件中  添加Application[属性名]=xxx;  就是你的全局变量  20.怎样作到HyperLinkColumn生成的连接后,点击连接,打开新窗口?  HyperLinkColumn有个属性Target,将器值设置成"_blank"即可.(Target="_blank")  【ASPNETMENU】点击菜单项弹出新窗口  在你的menuData.xml文件的菜单项中加入URLTarget="_blank",如:<?xmlversion="1.0"encoding="GB2312"?><MenuDataImagesBaseURL="images/"><MenuGroup><MenuItemLabel="内参信息"URL="Infomation.aspx"><MenuGroupID="BBC"><MenuItemLabel="公告信息"URL="Infomation.aspx"URLTarget="_blank"LeftIcon="file.gif"/><MenuItemLabel="编制信息简报"URL="NewInfo.aspx"LeftIcon="file.gif"/>......  最好将你的aspnetmenu升级到1.2版  21.读取DataGrid控件TextBox值foreach(DataGriddgiinyourDataGrid.Items){ TextBoxtb=(TextBox)dgi.FindControl("yourTextBoxId"); tb.Text....}  23.在DataGrid中有3个模板列包含Textbox分别为DG_ShuLiang(数量)DG_DanJian(单价)DG_JinE(金额)分别在5.6.7列,要求在录入数量及单价的时候自动算出金额即:数量*单价=金额还要求录入时限制为数值型.我如何用客户端脚本实现这个功能?  〖思归〗<asp:TemplateColumnHeaderText="数量"><ItemTemplate><asp:TextBoxid="ShuLiang"runat=’server’Text=’<%#DataBinder.Eval(Container.DataItem,"DG_ShuLiang")%>’onkeyup="javascript:DoCal()"/><asp:RegularExpressionValidatorid="revS"runat="server"ControlToValidate="ShuLiang"ErrorMessage="mustbeinteger"ValidationExpression="^\d+$"/></ItemTemplate></asp:TemplateColumn><asp:TemplateColumnHeaderText="单价"><ItemTemplate><asp:TextBoxid="DanJian"runat=’server’Text=’<%#DataBinder.Eval(Container.DataItem,"DG_DanJian")%>’onkeyup="javascript:DoCal()"/><asp:RegularExpressionValidatorid="revS2"runat="server"ControlToValidate="DanJian"ErrorMessage="mustbenumeric"ValidationExpression="^\d+(\.\d*)?$"/></ItemTemplate></asp:TemplateColumn><asp:TemplateColumnHeaderText="金额"><ItemTemplate><asp:TextBoxid="JinE"runat=’server’Text=’<%#DataBinder.Eval(Container.DataItem,"DG_JinE")%>’/></ItemTemplate></asp:TemplateColumn><scriptlanguage="javascript">functionDoCal(){ vare=event.srcElement; varrow=e.parentNode.parentNode; vartxts=row.all.tags("INPUT"); if(!txts.length  txts.length<3)  return; varq=txts[txts.length-3].value; varp=txts[txts.length-2].value; if(isNaN(q)  isNaN(p))  return; q=parseInt(q); p=parseFloat(p); txts[txts.length-1].value=(q*p).toFixed(2);}</script>  24.datagrid选定比较底下的行时,为什么总是刷新一下,然后就滚动到了最上面,刚才选定的行因屏幕的关系就看不到了。page_loadpage.smartNavigation=true  25.在Datagrid中修改数据,当点击编辑键时,数据出现在文本框中,怎么控制文本框的大小?privatevoidDataGrid1_ItemDataBound(objsender,DataGridItemEventArgse){ for(inti=0;i<e.Item.Cells.Count-1;i++)  if(e.Item.ItemType==ListItemType.EditType)  {   e.Item.Cells[i].Attributes.Add("Width","80px")  }}  26.对话框privatestaticstringScriptBegin="<scriptlanguage=\"JavaScript\">";privatestaticstringScriptEnd="</script>";publicstaticvoidConfirmMessageBox(stringPageTarget,stringContent){ stringConfirmContent="varretValue=window.confirm(’"+Content+"’);"+"if(retValue){window.location=’"+PageTarget+"’;}"; ConfirmContent=ScriptBegin+ConfirmContent+ScriptEnd; PageParameterPage=(Page)System.Web.HttpContext.Current.Handler; ParameterPage.RegisterStartupScript("confirm",ConfirmContent); //Response.Write(strScript);}  27.将时间格式化:stringaa=DateTime.Now.ToString("yyyy年MM月dd日");  1.1取当前年月日时分秒currentTime=System.DateTime.Now;  1.2取当前年int年=DateTime.Now.Year;  1.3取当前月int月=DateTime.Now.Month;  1.4取当前日int日=DateTime.Now.Day;  1.5取当前时int时=DateTime.Now.Hour;  1.6取当前分int分=DateTime.Now.Minute;  1.7取当前秒int秒=DateTime.Now.Second;  1.8取当前毫秒int毫秒=DateTime.Now.Millisecond; 28.自定义分页代码:  先定义变量:publicstaticintpageCount;//总页面数publicstaticintcurPageIndex=1;//当前页面  下一页:if(DataGrid1.CurrentPageIndex<(DataGrid1.PageCount-1)){ DataGrid1.CurrentPageIndex+=1; curPageIndex+=1;}bind();//DataGrid1数据绑定函数  上一页:if(DataGrid1.CurrentPageIndex>0){ DataGrid1.CurrentPageIndex+=1; curPageIndex-=1;}bind();//DataGrid1数据绑定函数  直接页面跳转:inta=int.Parse(JumpPage.Value.Trim());//JumpPage.Value.Trim()为跳转值if(a<DataGrid1.PageCount){ this.DataGrid1.CurrentPageIndex=a;}bind();  29.DataGrid使用:  添加删除确认:privatevoidDataGrid1_ItemCreated(objectsender,System.Web.UI.WebControls.DataGridItemEventArgse){ foreach(DataGridItemdiinthis.DataGrid1.Items) {  if(di.ItemType==ListItemType.Item  di.ItemType==ListItemType.AlternatingItem)  {   ((LinkButton)di.Cells[8].Controls[0]).Attributes.Add("onclick","returnconfirm(’确认删除此项吗?’);");  } }}  样式交替:ListItemTypeitemType=e.Item.ItemType;if(itemType==ListItemType.Item){ e.Item.Attributes["onmouseout"]="javascript:this.style.backgroundColor=’#FFFFFF’;"; e.Item.Attributes["onmouseover"]="javascript:this.style.backgroundColor=’#d9ece1’;cursor=’hand’;";}elseif(itemType==ListItemType.AlternatingItem){ e.Item.Attributes["onmouseout"]="javascript:this.style.backgroundColor=’#a0d7c4’;"; e.Item.Attributes["onmouseover"]="javascript:this.style.backgroundColor=’#d9ece1’;cursor=’hand’;";}  添加一个编号列:DataTabledt=c.ExecuteRtnTableForAccess(sqltxt);//执行sql返回的DataTableDataColumndc=dt.Columns.Add("number",System.Type.GetType("System.String"));for(inti=0;i<dt.Rows.Count;i++){ dt.Rows[i]["number"]=(i+1).ToString();}DataGrid1.DataSource=dt;DataGrid1.DataBind();  DataGrid1中添加一个CheckBox,页面中添加一个全选框privatevoidCheckBox2_CheckedChanged(objectsender,System.EventArgse){ foreach(DataGridItemthisiteminDataGrid1.Items) {  ((CheckBox)thisitem.Cells[0].Controls[1]).Checked=CheckBox2.Checked; }}  将当前页面中DataGrid1显示的数据全部删除foreach(DataGridItemthisiteminDataGrid1.Items){ if(((CheckBox)thisitem.Cells[0].Controls[1]).Checked) {  stringstrloginid=DataGrid1.DataKeys[thisitem.ItemIndex].ToString();  Del(strloginid);//删除函数 }}  30.当文件在不同目录下,需要获取数据库连接字符串(如果连接字符串放在Web.config,然后在Global.asax中初始化)  在Application_Start中添加以下代码:Application["ConnStr"]=this.Context.Request.PhysicalApplicationPath+ConfigurationSettings.   AppSettings["ConnStr"].ToString();  31.变量.ToString()  字符型转换转为字符串12345.ToString("n");//生成12,345.0012345.ToString("C");//生成¥12,345.0012345.ToString("e");//生成1.234500e+00412345.ToString("f4");//生成12345.000012345.ToString("x");//生成3039(16进制)12345.ToString("p");//生成1,234,500.00%  32、变量.Substring(参数1,参数2);  截取字串的一部分,参数1为左起始位数,参数2为截取几位。如:strings1=str.Substring(0,2);  33.在自己的网站上登陆其他网站:(如果你的页面是通过嵌套方式的话,因为一个页面只能有一个FORM,这时可以导向另外一个页面再提交登陆信息)<SCRIPTlanguage="javascript"><!-- functiongook(pws) {  frm.submit(); }//--></SCRIPT><bodyleftMargin="0"topMargin="0"onload="javascript:gook()"marginwidth="0"marginheight="0"><formname="frm"action="http://220.194.55.68:6080/login.php?retid=7259"method="post"><tr><td><inputid="f_user"type="hidden"size="1"name="f_user"runat="server"><inputid="f_domain"type="hidden"size="1"name="f_domain"runat="server"><inputclass="box"id="f_pass"type="hidden"size="1"name="pwshow"runat="server"><INPUTid="lng"type="hidden"maxLength="20"size="1"value="5"name="lng"><INPUTid="tem"type="hidden"size="1"value="2"name="tem"></td></tr></form>  文本框的名称必须是你要登陆的网页上的名称,如果源码不行可以用vsniffer看看。  下面是获取用户输入的登陆信息的代码:stringname;name=Request.QueryString["EmailName"];try{ inta=name.IndexOf("@",0,name.Length); f_user.Value=name.Substring(0,a); f_domain.Value=name.Substring(a+1,name.Length-(a+1)); f_pass.Value=Request.QueryString["Psw"];}catch{ Script.Alert("错误的邮箱!"); Server.Transfer("index.aspx");}

写文本文件

TextWritertw=newStreamWriter("date.txt");
tw.WriteLine(DateTime.Now);
tw.Close();

读文本文件

写法一
Textreadertr=newStreamReader("date.txt");
Console.WriteLine(tr.ReadLine());
tr.Close();
写法二
Textreadertr=newStreamReader("date.txt");
Console.WriteLine(tr.ReadLine());
tr.Close();
其实,上面的写文本文件和读文本文件,都有一个bug,当程序中有代码改变当前目录时,date.txt的目录就是这个被改变的目录,而不是我们期待的当前应用程序所有的目录。所以,推荐的写法是这样的
stringfile="Cnblogs.txt";stringcnblogs=Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory,file);if(File.Exists(cnblogs)){using(StreamReaderreader=File.OpenText(cnblogs)){rtfCnblogs.Text=reader.ReadToEnd();}}
加入了完整的文件名路径,这样才是正确的读写文件的方法。如果是ASP.NET应用程序,可以用Server.MapPath代替,或是HttpContext.Current.Request.PhysicalApplicationPath。

跨线程访问控件

delegatevoiddSetText(stringtext);privatevoidSetText(stringtext){
if(InvokeRequired)
{
dSetTextd=newdSetText(SetText);
this.Invoke(d);
}
else{
this.textBox1.Text=text;
}}

调用CodeSmith模板

CodeTemplateCompilercompiler=newCodeTemplateCompiler(@"c:\test.cst");compiler.Compile();if(compiler.Errors.Count==0){CodeTemplatet=compiler.CreateInstance();this.txtSql.Text=t.RenderToString();}compiler.Cleanup();compiler=null;
如果是x64的系统,请设置Target为x86(needtosettheprogramtocompileasX86)。

设置程序集运行时版本

当旧的程序是以.NET2.0编译的,又无法升级到.NET4.0,而有部分组件是以.NET编译的,在运行时,会抛出混合程序集的异常,需要修改配置文件,请参考这个片段
<?xmlversion="1.0"?><configuration><startupuseLegacyV2RuntimeActivationPolicy="true"><requiredRuntimesafemode="true"imageVersion="v4.0.30319"version="v4.0.30319"/></startup></configuration>
这个需求源于,CodeSmith5.0是以.NET2.0编译的。在我的代码生成可器中,它用来反射读取程序集信息,生成代码,而这个被读取的程序集的Target是.NET4.0,这时,你需要这个技巧来解决运行时的问题。另一个场景是ILMerge,用于合并.NET程序集的工具,只有.NET2.0的版本,要可以合并.NET4.0的程序集,也需要运用这个技巧(ILMergeconfigfileforexecutingwithintheCLRv4.0runtime)。

枚举类型的反射调用

在有些场景,我们需要把反射的参数值传到对象的方法中,而参数值是enum类型,这实现起来并不简单。请参考codeproject中这的篇文章《SettingEnum'sThroughReflection》,它的经典代码是这样的
intenumValue1=(int)enumItem1.GetValue(enumType);intenumValue2=(int)enumItem2.GetValue(enumType);intcurrentValue=(int)flagsInfo.GetValue(remoteObject,null);intnewValue=currentValue|enumValue1|enumValue2;
举例说明,我需要反射生成ReportViewer控件的对象实例,并且要传一个Mode值给它(Server,LocalReport)以表示是本地报表,还是取服务器报表。这种情况下,非得用反射的方式传入值。在我的.NET通用平台中,也应用到这项技术,以反射方式创建CrystalReportViewer报表控件,再传入参数值。这种方式稍微复杂一些,但是对比它带来的灵活性,是非常值得的。

目录选择功能

FolderBrowserDialogdlg=newFolderBrowserDialog();if(!string.IsNullOrEmpty(txtPath.Text))dlg.SelectedPath=txtPath.Text;if(dlg.ShowDialog()==DialogResult.OK){txtPath.Text=dlg.SelectedPath;}

文件选择功能

OpenFileDialogdlg=newOpenFileDialog();dlg.Filter="AllFile(*.*)|*.*";if(dlg.ShowDialog()==DialogResult.OK){txtPath.Text=dlg.FileName;}
Filter是经常容易忘记的选项,再举一个例子dlg.Filter="Xmlfile(*.xml)|*.xml|AllFiles|*.*";

读取嵌入到程序集中的资源文件

Assemblyassm=Assembly.GetAssembly(typeof(DatabaseCleanup));stringfile="DatabaseCleanup.txt";Streaminput=assm.GetManifestResourceStream("DataLoader.Resource"+"."+file);StreamReaderreader=newStreamReader(input);stringsql=reader.ReadToEnd();reader.Close();
只要可能,对只读的不需要修改的配置选项资源(SQL语句,文本文件),尽可能的使用EmbeddedResource方式。

微软企业库的调用方式

经过一层简单的封装,以下面的这种方式来调用企业库以访问数据库
EnterpriseLibraryShared.ConnectonString=ConnectionString;Microsoft.Practices.EnterpriseLibrary.Data.Databasem_commonDb=DatabaseFactory.CreateDatabase();DbCommandcmd=m_commonDb.GetSqlStringCommand(sql);introwAffected=m_commonDb.ExecuteNonQuery(cmd);
我把企业库的连接字符串放到一个staticclass中,这样可以简化调用方式,不必要一定要加App/Web.config文件。

监控文件或目录的变化

这个功能比较常用,在DataLoader也有一个PDFWatcher的程序,以监控指定的目录是否有新加入的PDF文件(可能来自远程传输,或是从网页中下载回来),然后对它进转换,导入到文档服务器中。
publicvoidStartMonitor(stringpath){FileSystemWatcherwatcher=newFileSystemWatcher();watcher.Path=path;watcher.NotifyFilter=NotifyFilters.FileName;//Onlywatchpdffiles.watcher.Filter="*.pdf";watcher.Created+=newFileSystemEventHandler(OnChanged);watcher.EnableRaisingEvents=true;}//EventhandlerforwhenafileiscreatedinthewatchedfolderprivatevoidOnChanged(objectsource,FileSystemEventArgse){stringword=DocumentUtility.ConvertPdfToDoc(e.FullPath);}
希望可以帮助到你。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐