|
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有帐号?立即注册
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:- 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[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:- 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:- 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
[img=1border=0style=,1src=]http://www.ckuyun.com/[/img]
说句实话,Java跨平台根本就不是外行人想想的那种,一次编译,处处运行。 |
|