ASP.NET网站制作之10 Tips for Great .NET Programming(...
J2EE比较成熟一点,一些比较出名的企业应用软件都是基于J2EE的。以后的发展就不好说了。不过java比较烦,学.net的话,微软把很多工具都封装好了,学起来可能容易一点。10TipsforGreat.NETProgrammingWhetheryoureinterestedinWindowsForms,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:voidItemCreated(Objects,DataGridItemEventArgse)
ThiscodeletsyoucontrolthecreationprocessforthefooterandanyotherDataGriditem:ListItemTypeitemType=e.Item.ItemType;if(itemType==ListItemType.Footer){e.Item.Cells.RemoveAt(1);e.Item.Cells.RemoveAt(1);cellSummary.ColumnSpan=3;e.Item.Cells.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: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;
DataTabledt=ds.Tables["MyTable"];
keys==dt.Columns["ID"];
dt.PrimaryKey=keys;
Youcanhavetheprimarykeyinformationdetectedandsetautomaticallywhilefillingthedataset.Youautomatethediscoveryofthisinformation,andconsequentlytheexecutionofyourfetchingcode,bysettingtheMissingSchemaActionpropertyofthedataadapterthatperformsthequery:SqlDataAdapterda=newSqlDataAdapter(strCmd,strConn);DataSetds=newDataSet();da.MissingSchemaAction=MissingSchemaAction.AddWithKey;da.Fill(ds,"MyTable");
Tip7:RequestSelectedCheckboxes
InanyASPapplication,youhaveseveralcheckboxes,allwiththesamename:<inputtype="checkbox"name="foo"value="...">
Youcangetthecorrespondingvaluesofthecheckboxesthathavebeenselecteduponformpostingwithasinglelineofcode:<%a=split(Request.Form("foo"),",")%>
Request.Form("foo")returnsacomma-separatedstringformedbythevaluestringsofallcheckeditems.YoupassthisstringtotheVBScriptssplitfunctionandgetaneasilymanageablestructure,suchasanarray.
ThesamecodewontworkinASP.NETifyouusethe<asp:checkbox>servercontrol.Tomakeitwork,stickwiththeHtmlInputCheckBoxcontrolandwritecodesuchasthis:<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://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:dGrid.DataSource=dsdGrid.DataMember="Customers.OrdersByCustomer"
WhenyouassociatethedetailgridwithanexpressionsuchasMasterTable.Relation,itscontentisrefreshedautomaticallyandproperly.
Tip9:HandleFileChangeNotification
.NETintegratesthefunctionalityofWin32filenotificationobjectsintotheFileSystemWatcherclass.Thosekernelobjectsareresponsiblefornotifyingclientapplicationsaboutchangesdetectedatthefilesystemlevel.Accordingtothespecifiedparameters,anotificationobjectsignalsthestatusoftheapplicationswheneverafileiscreated,modified,renamed,ordeleted.
ItsdifficultforWin32toknowthenameofthefilebeinginvolvedandthereasonforitsinvolvementwiththeeventunderWindowsNTandWindows2000.Allthishasbeensupersededin.NETthankstotheFileSystemWatcherclass:FileSystemWatcherwatcher=newFileSystemWatcher();watcher.Path="c:";watcher.Filter="*.txt";watcher.NotifyFilter=NotifyFilters.LastWrite;
10TipsforGreat.NETProgramming(Continued)
Oncetheobjectisconfigured,youbeginwatching:
watcher.EnableRaisingEvents=true;
Anydetectedeventcausesanapplicationeventtofire.Youregisterfortheeventsyouneedlikethis:watcher.Changed+=newFileSystemEventHandler(OnChanged);
Thehandlerseventargumentssupplyallthefileandeventinformationyouneed.
Tip10:CompileCodeontheFly
The.NETFrameworkexposesclassesthatletyoucompilecodeinaspecifiedlanguage.TheseclassesliveintheSystem.CodeDom.Compilernamespace.Thiscodesnippetshowshowtoobtainanin-memoryrunninginstanceoftheC#compiler:CSharpCodeProvidercsc=newCSharpCodeProvider();ICodeCompilericc=csc.CreateCompiler();
Next,youllsetsomeinputparametersthroughtheCompilerParametersclass:CompilerParametersco=newCompilerParameters();co.OutputAssembly="foo.exe";co.ReferencedAssemblies.Add("system.dll");
Youmustspecifyatleastthenameoftheexecutable,setGenerateExecutabletoFalseifyouwantaDLL,andaddthelistofassembliestoreference:icc.CompileAssemblyFromFile(co,csfile);
Torunthecompilingprocess,useCompileAssemblyFromFile()andpassittheparametersandthesourcefilename.YoucanusetheclassCompilerResultstolearnmoreaboutthenewlygeneratedassem
http://www.ckuyun.com/
说句实话,Java跨平台根本就不是外行人想想的那种,一次编译,处处运行。 是指转换后的Servlet程序代码的行数。这给调试代码带来一定困难。所以,在排除错误时,可以采取分段排除的方法(在可能出错的代码前后输出一些字符串,用字符串是否被输出来确定代码段从哪里开始出错)。 能产生和执行动态、交互式、高效率的站占服务器的应用程序。运用ASP可将VBscript、javascript等脚本语言嵌入到HTML中,便可快速完成网站的应用程序,无需编译,可在服务器端直接执行。容易编写。 ASP是把代码交给VBScript解释器或Jscript解释器来解释,当然速度没有编译过的程序快了。 以上是语言本身的弱点,在功能方面ASP同样存在问题,第一是功能太弱,一些底层操作只能通过组件来完成,在这点上是远远比不上PHP/JSP,其次就是缺乏完善的纠错/调试功能,这点上ASP/PHP/JSP差不多。 网页从开始简单的hmtl到复杂的服务语言,走过了10多个年头,各种技术层出不穷,单个的主流技术也在不断翻新的版本,现在分析下各种语言的区别、优势、劣势、开发注意事项! 以上是语言本身的弱点,在功能方面ASP同样存在问题,第一是功能太弱,一些底层操作只能通过组件来完成,在这点上是远远比不上PHP/JSP,其次就是缺乏完善的纠错/调试功能,这点上ASP/PHP/JSP差不多。 但是目前在CGI中使用的最为广泛的是Perl语言。所以,狭义上所指的CGI程序一般都是指Perl程序,一般CGI程序的后缀都是.pl或者.cgi。 PHP的源代码完全公开,在OpenSource意识抬头的今天,它更是这方面的中流砥柱。不断地有新的函数库加入,以及不停地更新,使得PHP无论在UNIX或是Win32的平台上都可以有更多新的功能。它提供丰富的函数,使得在程式设计方面有着更好的资源。目前PHP的最新版本为4.1.1,它可以在Win32以及UNIX/Linux等几乎所有的平台上良好工作。PHP在4.0版后使用了全新的Zend引擎,其在最佳化之后的效率,比较传统CGI或者ASP等技术有了更好的表现。
页:
[1]