仓酷云

 找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 1029|回复: 8
打印 上一主题 下一主题

[学习教程] ASP.NET网站制作之10 Tips for Great .NET Programming(...

[复制链接]
再现理想 该用户已被删除
跳转到指定楼层
楼主
发表于 2015-1-16 22:53:47 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有帐号?立即注册

x
J2EE比较成熟一点,一些比较出名的企业应用软件都是基于J2EE的。以后的发展就不好说了。不过java比较烦,学.net的话,微软把很多工具都封装好了,学起来可能容易一点。10TipsforGreat.NETProgramming
WhetheryoureinterestedinWindowsForms,ASP.NET,WebServices,orthe.NETFramework,thesetipshelpyouexploitthestillyoung.NETtechnology.
byDinoEsposito
The.NETFrameworkislargerthaneverandfilledwithahugenumberofclassesandmethods,butthedevelopercommunityhasyettoexploreandunderstandmostofthisincrediblevolumeofsoftwarefeatures.Whatmightappeartobeabugoradesignflawatfirstmightbeconsideredasignificantstrengthafterasecond,morethoughtfullook.
Inlightofthisinevitablerefinementprocess,sharingtipswithotherdevelopers,althoughfarfromprovidingthedefinitivesolutionyoumightbelookingfor,isawaytosteeryouintherightdirectionwhenyoubuildyourthefirst.NETapplication.Ivecompiledalistof10tipstomakeyour.NETdevelopmentmoreeffectiveandproductive.Tohelpasmanydevelopersaspossible,thetipsspanthetechnologyswholespectrum―fromADO.NETtoASP.NET,fromtheCLRtotheFramework,andfromWindowsFormstoWebServices.Heretheyare,countinguptotheonesIanticipatewillhavethemostimpact.
Tip1:ShapeUpYourDataGridsFooter
TheDataGridcontrolmightfeatureafooter―thatis,arowthatsummarizespartofthecontentshowninthepage.ThefooterishiddenunlessyouenableitbysettingtheShowFooterpropertytoTrue.Onceyoudo,thefooterappears,butithasexactlythesamenumberofcolumnsasotherrows.Ifthisisfinewithyou,itisntaproblem.Otherwise,youllneedtoaddmorefieldstothefooterorremoveexistingones.
OnItemCreatedisthekeyeventtohookup.Itstheeventhandlerssignature:
  1. voidItemCreated(Objects,DataGridItemEventArgse)
复制代码
ThiscodeletsyoucontrolthecreationprocessforthefooterandanyotherDataGriditem:
  1. ListItemTypeitemType=e.Item.ItemType;if(itemType==ListItemType.Footer){e.Item.Cells.RemoveAt(1);e.Item.Cells.RemoveAt(1);cellSummary.ColumnSpan=3;e.Item.Cells[0].Text="...";}
复制代码
Makesureyouintervenewhenthefooterisbeingcreated,thengrabthecontrolinstancerepresentingthefooterrow.Thenyoucanremoveoraddasmanycellsasyouneed.DontforgettosettheColumnSpanpropertytotheoriginalnumberofcolumnstoavoidrenderingproblemssuchashavingthefooterlinelookshorterorlongerthantherestofthegrid.


Tip2:UsetheCacheObject
InActiveServerPages(ASP),youwereusedtoemployingtheApplicationobjecttodetectglobaleventsandstoreapplication-widedata.Givenmanyusersfromdifferentpagescanaccessthesamedatacell,youmustuseLockandUnlockmethodstoserializeaccessandavoidconflictsandunpredictableresults.InASP.NET,togetherwiththeApplicationobject,youhavetheCacheobject,whichhassimilarcharacteristicsbutendsupreplacingtheApplicationobjectinmorethanoneinstance.
BoththeCacheandApplicationobjectsarecollectiondatacontainersthatmakecontentvisibleacrosspageandsessionboundaries.BothdontfullysupportWebfarmandWebgardenscenarios.AWebfarmisaWebserverarchitectureinwhichmultipleservershostanapplication.InaWebgardenscenario,multipleprocessesonthesameserverhostanapplication.
UnliketheApplicationobject,theCacheobjectisntinstantiatedassoonasthefirstpageoftheapplicationisloaded.TheCacheobjectgetsintothegameonlywhenyouuseit.Inaddition,theCacheobjecthasfeaturestominimizetheamountofmemoryitsdataitemsoccupy.Youcansetarelativeorabsoluteexpirationdateforcacheditemsaswellasassociatethemwithapriorityandadecayfactor.Thenyouhavegreatercontroloverthestatusofyourglobaldataandcanimplementaspecialpolicytodegradegracefullyunderlowmemoryconditions.Additionally,theCacheobjectmanagesthread-safeobjectsanddoesntrequireLockandUnlock.


Tip3:CallaServiceWithGETorPOST
AWebServiceisprimarilyaURLthatyouconnecttousingHTTP.WhenyoucreateaproxyclassforagivenWebService,unlessyouspecifyotherwise,thecommand-linetoolwsdl.exeservesyouaclassthatusestheSOAPprotocoltomakeremotecallstotheWebService.
AlthoughtheSOAPprotocolistheexpectedstandardforremoteprocedurecalls,nothingpreventsyoufrommakingcallstoa.NETWebServiceusingplainGETorPOSTrequests.Incidentally,POSTcommandstransportSOAPpayloads.
Youcanbuildthisfeatureintotheproxyclassdirectlybysettingthe/protocolswitchtohttpgetorhttppostwhencallingthewsdl.exeutility.Thesourcecodeforthewrapperclassbehavesaccordingly.YoucanalsocallaWebServiceusingtheXmlHttpRequestobject(seeResources)andeitherplainscriptorcompiledcode:
  1. Sethttp=CreateObject("Microsoft.XMLHTTP")http.open"GET",_"http://server/service.asmx/MethodName",falsehttp.send""MsgBoxhttp.responseText
复制代码
ByusingXmlHttpRequest,youhavethechancetoconnecttoWebServicesfromWin32,script,and,ingeneral,non-.NETcode.


Tip4:UseCookielessSessions
InASP.NET,theSessionobjectreferstoaconfigurablesoftwareentityyoucanmaptoanin-processorout-of-processmodule.TheSessionobjectreadsanumberofruntimesettingsyoucanstoreintheWebserversframeworkinstallationtreeorintheapplicationsBINdirectoryfromtheweb.configfile.ThisfiledeterminesthesettingsforanumberofASP.NETcomponents.Ifyouputacopyofconfig.webinyourapplicationslocalsubtree,thesettingsendupoverridingthedefaultonessetintheframeworkpath.
OnethingyoucancustomizeiswhethertheSessionManagershouldidentifyclientsessionsusingcookies(thedefault)ornot.Thislineintheapplicationlocalconfig.webfilesetstheSessionManagertoworkwithoutcookies:
<sessionStatecookieless="true"/>


Tip5:UseCustomGridPagination
TheWebFormDataGridcontrolhasbuilt-insupportforpagination.Itdisplaysapagerbarautomaticallyand,withlimitedhelpfromyourcode,itshowspagesofrecordsofthegivensize.However,bydefault,allthenecessaryrecordsarecachedintheDataGridobjectsDataSourceproperty.Thismeansyoumustfetchthedataallatonce.Althoughthisisntsuchabigissuewithafewdozenrecords,itbecomesaproblemwiththousandsofrecords.Inthiscase,youmightwanttofetchrecordsmanuallyandcachethemondisk,butofftheDBMS.
YoumustinformtheDataGridcontrolofthisparticularbehavior.Fortunately,theDataGridprovidesforanAllowCustomPaginationpropertythat,whensettoTrue,changestheinternalbehaviorofthecontrolquiteabit.WhenyousetthispropertytoTrue,thegridalwaysreadsrecordsfoundintheDataSourcepropertyfromfirsttolast.Itsyourresponsibilitytoreplenishthiscontainerwithfreshdatabelongingtothecurrentpage.Normally,thegriditselffetchesonlytherecordsthatpertaintothepagefromtheDataSourceproperty.


Tip6:LoadKeyInfoFromDatabase
TheDataTableobjectletsyousetin-memoryprimarykeysonagiventable.ThisactionspeedsupthesearchonboththeDataTableandrelatedDataViewobjects.Anothergoodreasontohavein-memorykeysistoautomaticallypreventduplicateinsertionsthatviolatetableintegrity.Thenyouhaveplentyoftimetofixthetable,evenproperlywarntheuser,beforethedataisactuallysubmittedtothedatabaseserverforabatchupdate.
10TipsforGreat.NETProgramming(Continued)
Youcansetthisinformationmanuallyinyourfetchingcode:
//dsisanexistingdataset
DataColumn[]keys==newDataColumn[1];
DataTabledt=ds.Tables["MyTable"];
keys[0]==dt.Columns["ID"];
dt.PrimaryKey=keys;

Youcanhavetheprimarykeyinformationdetectedandsetautomaticallywhilefillingthedataset.Youautomatethediscoveryofthisinformation,andconsequentlytheexecutionofyourfetchingcode,bysettingtheMissingSchemaActionpropertyofthedataadapterthatperformsthequery:
  1. SqlDataAdapterda=newSqlDataAdapter(strCmd,strConn);DataSetds=newDataSet();da.MissingSchemaAction=MissingSchemaAction.AddWithKey;da.Fill(ds,"MyTable");
复制代码


Tip7:RequestSelectedCheckboxes
InanyASPapplication,youhaveseveralcheckboxes,allwiththesamename:
  1. <inputtype="checkbox"name="foo"value="...">
复制代码
Youcangetthecorrespondingvaluesofthecheckboxesthathavebeenselecteduponformpostingwithasinglelineofcode:
  1. <%a=split(Request.Form("foo"),",")%>
复制代码
Request.Form("foo")returnsacomma-separatedstringformedbythevaluestringsofallcheckeditems.YoupassthisstringtotheVBScriptssplitfunctionandgetaneasilymanageablestructure,suchasanarray.
ThesamecodewontworkinASP.NETifyouusethe<asp:checkbox>servercontrol.Tomakeitwork,stickwiththeHtmlInputCheckBoxcontrolandwritecodesuchasthis:
  1. <inputtype="checkbox"runat="server"name="foo"value="...">
复制代码
Eventhoughtheasp:checkboxandinputtype="checkbox"servertagsevaluatetothesameHTMLcode,ASP.NETensuresuniqueIDsandnamesforthetagsoutputbyasp:checkboxandanyothercontrolinthe<asp>namespace.


Tip8:AutomateMaster/DetailViews
IfyouhaveaWindowsFormsapplicationthatusestheDataGridcontroltodisplaymaster/detailtables,chancesareyoucanhavetheframeworksynchronizetheviewsautomaticallyforyou.
Thekeyiscreatingadatarelationbetweenthetwotablesandusingacomposedexpressiontodefinethedatasourceforthedetailtable.LetsassumeyouhaveCustomersandOrderstableswithaCustIDfieldincommon.YoucreatearelationintermsofanADO.NETDataRelationobject:
  1. //dsisanexistingDataSetDimdc1,dc2AsDataColumndc1=ds.Tables("Customers").Columns("custid")dc2=ds.Tables("Orders").Columns("custid")DimrAsDataRelationr=NewDataRelation("OrdersByCustomer",dc1,dc2)ds.Relations.Add(r)
复制代码
WheneveryouhaveaDataRowobjectrepresentingonerowonthemastertable―Customers,inthiscase―youcanobtainanarraywiththechildrowsaccordingtotherelationusingtheDataRowsGetChildRowsmethod.ForWindowsForms,thisprogrammaticapproachisburiedinthiscode:
  1. dGrid.DataSource=dsdGrid.DataMember="Customers.OrdersByCustomer"
复制代码
WhenyouassociatethedetailgridwithanexpressionsuchasMasterTable.Relation,itscontentisrefreshedautomaticallyandproperly.


Tip9:HandleFileChangeNotification
.NETintegratesthefunctionalityofWin32filenotificationobjectsintotheFileSystemWatcherclass.Thosekernelobjectsareresponsiblefornotifyingclientapplicationsaboutchangesdetectedatthefilesystemlevel.Accordingtothespecifiedparameters,anotificationobjectsignalsthestatusoftheapplicationswheneverafileiscreated,modified,renamed,ordeleted.
ItsdifficultforWin32toknowthenameofthefilebeinginvolvedandthereasonforitsinvolvementwiththeeventunderWindowsNTandWindows2000.Allthishasbeensupersededin.NETthankstotheFileSystemWatcherclass:
  1. FileSystemWatcherwatcher=newFileSystemWatcher();watcher.Path="c:";watcher.Filter="*.txt";watcher.NotifyFilter=NotifyFilters.LastWrite;
复制代码
10TipsforGreat.NETProgramming(Continued)
Oncetheobjectisconfigured,youbeginwatching:
watcher.EnableRaisingEvents=true;
Anydetectedeventcausesanapplicationeventtofire.Youregisterfortheeventsyouneedlikethis:
  1. watcher.Changed+=newFileSystemEventHandler(OnChanged);
复制代码
Thehandlerseventargumentssupplyallthefileandeventinformationyouneed.


Tip10:CompileCodeontheFly
The.NETFrameworkexposesclassesthatletyoucompilecodeinaspecifiedlanguage.TheseclassesliveintheSystem.CodeDom.Compilernamespace.Thiscodesnippetshowshowtoobtainanin-memoryrunninginstanceoftheC#compiler:
  1. CSharpCodeProvidercsc=newCSharpCodeProvider();ICodeCompilericc=csc.CreateCompiler();
复制代码
Next,youllsetsomeinputparametersthroughtheCompilerParametersclass:
  1. CompilerParametersco=newCompilerParameters();co.OutputAssembly="foo.exe";co.ReferencedAssemblies.Add("system.dll");
复制代码
Youmustspecifyatleastthenameoftheexecutable,setGenerateExecutabletoFalseifyouwantaDLL,andaddthelistofassembliestoreference:
  1. icc.CompileAssemblyFromFile(co,csfile);
复制代码
Torunthecompilingprocess,useCompileAssemblyFromFile()andpassittheparametersandthesourcefilename.YoucanusetheclassCompilerResultstolearnmoreaboutthenewlygeneratedassem
[img=1border=0style=,1src=]http://www.ckuyun.com/[/img]

说句实话,Java跨平台根本就不是外行人想想的那种,一次编译,处处运行。
飘灵儿 该用户已被删除
沙发
发表于 2015-1-20 05:58:18 | 只看该作者
是指转换后的Servlet程序代码的行数。这给调试代码带来一定困难。所以,在排除错误时,可以采取分段排除的方法(在可能出错的代码前后输出一些字符串,用字符串是否被输出来确定代码段从哪里开始出错)。
活着的死人 该用户已被删除
板凳
发表于 2015-1-28 19:39:38 | 只看该作者
能产生和执行动态、交互式、高效率的站占服务器的应用程序。运用ASP可将VBscript、javascript等脚本语言嵌入到HTML中,便可快速完成网站的应用程序,无需编译,可在服务器端直接执行。容易编写。
地板
发表于 2015-2-5 22:18:48 | 只看该作者
ASP是把代码交给VBScript解释器或Jscript解释器来解释,当然速度没有编译过的程序快了。
小妖女 该用户已被删除
5#
发表于 2015-2-13 22:10:10 | 只看该作者
以上是语言本身的弱点,在功能方面ASP同样存在问题,第一是功能太弱,一些底层操作只能通过组件来完成,在这点上是远远比不上PHP/JSP,其次就是缺乏完善的纠错/调试功能,这点上ASP/PHP/JSP差不多。
因胸联盟 该用户已被删除
6#
发表于 2015-3-4 02:17:27 | 只看该作者
网页从开始简单的hmtl到复杂的服务语言,走过了10多个年头,各种技术层出不穷,单个的主流技术也在不断翻新的版本,现在分析下各种语言的区别、优势、劣势、开发注意事项!
谁可相欹 该用户已被删除
7#
发表于 2015-3-11 15:27:43 | 只看该作者
以上是语言本身的弱点,在功能方面ASP同样存在问题,第一是功能太弱,一些底层操作只能通过组件来完成,在这点上是远远比不上PHP/JSP,其次就是缺乏完善的纠错/调试功能,这点上ASP/PHP/JSP差不多。
简单生活 该用户已被删除
8#
发表于 2015-3-19 01:19:31 | 只看该作者
但是目前在CGI中使用的最为广泛的是Perl语言。所以,狭义上所指的CGI程序一般都是指Perl程序,一般CGI程序的后缀都是.pl或者.cgi。
不帅 该用户已被删除
9#
发表于 2015-3-27 00:49:22 | 只看该作者
PHP的源代码完全公开,在OpenSource意识抬头的今天,它更是这方面的中流砥柱。不断地有新的函数库加入,以及不停地更新,使得PHP无论在UNIX或是Win32的平台上都可以有更多新的功能。它提供丰富的函数,使得在程式设计方面有着更好的资源。目前PHP的最新版本为4.1.1,它可以在Win32以及UNIX/Linux等几乎所有的平台上良好工作。PHP在4.0版后使用了全新的Zend引擎,其在最佳化之后的效率,比较传统CGI或者ASP等技术有了更好的表现。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|手机版|仓酷云 鄂ICP备14007578号-2

GMT+8, 2024-5-4 20:55

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表