Sie sind auf Seite 1von 100

1. WriteasimpleWindowsFormsMessageBoxstatement.

2. System.Windows.Forms.MessageBox.Show("Hello,WindowsForms")

3. Canyouwriteaclasswithoutspecifyingnamespace?Which namespacedoesitbelongtobydefault?? Yes,youcan,thentheclassbelongstoglobalnamespacewhichhasno name.Forcommercialproducts,naturally,youwouldntwantglobal namespace. 4. YouaredesigningaGUIapplicationwithawindowandseveral widgetsonit.Theuserthenresizestheappwindowandseesa lotofgreyspace,whilethewidgetsstayinplace.Whatsthe problem?Oneshoulduseanchoringforcorrectresizing.Otherwisethe defaultpropertyofawidgetonaformistopleft,soitstaysatthesame locationwhenresized. 5. HowcanyousavethedesiredpropertiesofWindowsForms application?.configfilesin.NETaresupportedthroughtheAPItoallow storingandretrievinginformation.Theyarenothingmorethansimple XMLfiles,sortoflikewhat.inifileswerebeforeforWin32apps. 6. Sohowdoyouretrievethecustomizedpropertiesofa.NET applicationfromXML.configfile?Initializeaninstanceof AppSettingsReaderclass.CalltheGetValuemethodof AppSettingsReaderclass,passinginthenameofthepropertyandthe typeexpected.Assigntheresulttotheappropriatevariable. 7. Canyouautomatethisprocess?InVisualStudioyes,useDynamic Propertiesforautomatic.configcreation,storageandretrieval. 8. Myprogressbarfreezesupanddialogwindowshowsblank, whenanintensivebackgroundprocesstakesover.Yes,you shouldvemultithreadedyourGUI,withtaskbarandmainformbeing onethread,andthebackgroundprocessbeingtheother. 9. WhatsthesafestwaytodeployaWindowsFormsapp?Web deployment:theuseralwaysdownloadsthelatestversionofthecode theprogramrunswithinsecuritysandbox,properlywrittenappwillnot requireadditionalsecurityprivileges. 10. Whyisitnotagoodideatoinsertcodeinto InitializeComponentmethodwhenworkingwithVisualStudio? Thedesignerwilllikelythrowitawaymostofthecodeinside InitializeComponentisautogenerated. 11. WhatsthedifferencebetweenWindowsDefaultLocation andWindowsDefaultBounds?WindowsDefaultLocationtellstheform tostartupatalocationselectedbyOS,butwithinternallyspecifiedsize. WindowsDefaultBoundsdelegatesbothsizeandstartingpositionchoices totheOS.

smroF swodniW TEN.


001 fo 1 egaP

snoit seuQ weivretnI

12. WhatsthedifferencebetweenMoveandLocationChanged? ResizeandSizeChanged?Bothmethodsdothesame,Moveand ResizearethenamesadoptedfromVBtoeasemigrationtoC#. 13. Howwouldyoucreateanonrectangularwindow,letssay anellipse?Createarectangularform,settheTransparencyKey propertytothesamevalueasBackColor,whichwilleffectivelymakethe backgroundoftheformtransparent.ThensettheFormBorderStyleto FormBorderStyle.None,whichwillremovethecontourandcontentsof theform. 14. HowdoyoucreateaseparatorintheMenuDesigner?A hyphenwoulddoit.Also,anampersand&\wouldunderlinethenext letter. 15. Howsanchoringdifferentfromdocking?Anchoringtreatsthe componentashavingtheabsolutesizeandadjustsitslocationrelative totheparentform.Dockingtreatsthecomponentlocationasabsolute anddisregardsthecomponentsize.Soifastatusbarmustalwaysbeat thebottomnomatterwhat,usedocking.Ifabuttonshouldbeonthe topright,butchangeitspositionwiththeformbeingresized,use anchoring.

InterviewQuestions C#
1. Whatstheimplicitnameoftheparameterthatgetspassedinto theclasssetmethod?Value,anditsdatatypedependsonwhatever variablewerechanging. 2. HowdoyouinheritfromaclassinC#?Placeacolonandthenthe nameofthebaseclass.NoticethatitsdoublecoloninC++. 3. DoesC#supportmultipleinheritance?No,useinterfacesinstead. 4. Whenyouinheritaprotectedclasslevelvariable,whoisit availableto?Classesinthesamenamespace. 5. Areprivateclasslevelvariablesinherited?Yes,buttheyarenot accessible,solookingatityoucanhonestlysaythattheyarenot inherited.Buttheyare. 6. Describetheaccessibilitymodifierprotectedinternal.Itsavailable toderivedclassesandclasseswithinthesameAssembly(andnaturally fromthebaseclassitsdeclaredin). 7. C#providesadefaultconstructorforme.Iwriteaconstructor thattakesastringasaparameter,butwanttokeeptheno parameterone.HowmanyconstructorsshouldIwrite?Two.Once youwriteatleastoneconstructor,C#cancelsthefreebieconstructor, andnowyouhavetowriteoneyourself,eveniftheresno implementationinit. 8. Whatsthetop.NETclassthateverythingisderivedfrom? System.Object. 9. Howsmethodoverridingdifferentfromoverloading?When overriding,youchangethemethodbehaviorforaderivedclass. Overloadingsimplyinvolveshavingamethodwiththesamenamewithin theclass.
001 fo 2 egaP

10. Whatdoesthekeywordvirtualmeaninthemethod definition?Themethodcanbeoverridden. 11. Canyoudeclaretheoverridemethodstaticwhilethe originalmethodisnonstatic?No,youcant,thesignatureofthe virtualmethodmustremainthesame,onlythekeywordvirtualis changedtokeywordoverride. 12. Canyouoverrideprivatevirtualmethods?No,moreover,you cannotaccessprivatemethodsininheritedclasses,havetobeprotected inthebaseclasstoallowanysortofaccess. 13. Canyoupreventyourclassfrombeinginheritedand becomingabaseclassforsomeotherclasses?Yes,thatswhat keywordsealedintheclassdefinitionisfor.Thedevelopertryingto derivefromyourclasswillgetamessage:cannotinheritfromSealed classWhateverBaseClassName.Itsthesameconceptasfinalclassin Java. 14. Canyouallowclasstobeinherited,butpreventthemethod frombeingoverridden?Yes,justleavetheclasspublicandmakethe methodsealed. 15. Whatsanabstractclass?Aclassthatcannotbeinstantiated.A conceptinC++knownaspurevirtualmethod.Aclassthatmustbe inheritedandhavethemethodsoverridden.Essentially,itsablueprint foraclasswithoutanyimplementation. 16. Whendoyouabsolutelyhavetodeclareaclassasabstract (asopposedtofreewillededucatedchoiceordecisionbasedon UMLdiagram)?Whenatleastoneofthemethodsintheclassis abstract.Whentheclassitselfisinheritedfromanabstractclass,butnot allbaseabstractmethodshavebeenoverridden. 17. Whatsaninterfaceclass?Itsanabstractclasswithpublic abstractmethodsallofwhichmustbeimplementedintheinherited classes. 18. Whycantyouspecifytheaccessibilitymodifierformethods insidetheinterface?Theyallmustbepublic.Therefore,toprevent youfromgettingthefalseimpressionthatyouhaveanyfreedomof choice,youarenotallowedtospecifyanyaccessibility,itspublicby default. 19. Canyouinheritmultipleinterfaces? Yes,whynot. 20. Andiftheyhaveconflictingmethodnames?Itsuptoyouto implementthemethodinsideyourownclass,soimplementationisleft entirelyuptoyou.Thismightcauseaproblemonahigherlevelscaleif similarlynamedmethodsfromdifferentinterfacesexpectdifferentdata, butasfarascompilercaresyoureokay. 21. Whatsthedifferencebetweenaninterfaceandabstract class?Intheinterfaceallmethodsmustbeabstractintheabstract classsomemethodscanbeconcrete.Intheinterfacenoaccessibility modifiersareallowed,whichisokinabstractclasses.

001 fo 3 egaP

22. Howcanyouoverloadamethod?Differentparameterdata types,differentnumberofparameters,differentorderofparameters. 23. Ifabaseclasshasabunchofoverloadedconstructors,and aninheritedclasshasanotherbunchofoverloadedconstructors, canyouenforceacallfromaninheritedconstructortoan arbitrarybaseconstructor?Yes,justplaceacolon,andthenkeyword base(parameterlisttoinvoketheappropriateconstructor)inthe overloadedconstructordefinitioninsidetheinheritedclass. 24. WhatsthedifferencebetweenSystem.Stringand System.StringBuilderclasses?System.Stringisimmutable System.StringBuilderwasdesignedwiththepurposeofhavinga mutablestringwhereavarietyofoperationscanbeperformed. 25. WhatstheadvantageofusingSystem.Text.StringBuilder overSystem.String?StringBuilderismoreefficientinthecases,where alotofmanipulationisdonetothetext.Stringsareimmutable,soeach timeitsbeingoperatedon,anewinstanceiscreated. 26. CanyoustoremultipledatatypesinSystem.Array?No. 27. WhatsthedifferencebetweentheSystem.Array.CopyTo() andSystem.Array.Clone()?Thefirstoneperformsadeepcopyofthe array,thesecondoneisshallow. 28. Howcanyousorttheelementsofthearrayindescending order?BycallingSort()andthenReverse()methods. 29. Whatsthe.NETdatatypethatallowstheretrievalofdata byauniquekey?HashTable. 30. WhatsclassSortedListunderneath?AsortedHashTable. 31. Willfinallyblockgetexecutediftheexceptionhadnot occurred?Yes. 32. WhatstheC#equivalentofC++catch(),whichwasa catchallstatementforanypossibleexception?Acatchblockthat catchestheexceptionoftypeSystem.Exception.Youcanalsoomitthe parameterdatatypeinthiscaseandjustwritecatch{}. 33. Canmultiplecatchblocksbeexecuted?No,oncetheproper catchcodefiresoff,thecontrolistransferredtothefinallyblock(ifthere areany),andthenwhateverfollowsthefinallyblock. 34. Whyisitabadideatothrowyourownexceptions?Well,ifat thatpointyouknowthatanerrorhasoccurred,thenwhynotwritethe propercodetohandlethaterrorinsteadofpassinganewException objecttothecatchblock?Throwingyourownexceptionssignifiessome designflawsintheproject. 35. Whatsadelegate?Adelegateobjectencapsulatesareference toamethod.InC++theywerereferredtoasfunctionpointers. 36. Whatsamulticastdelegate?Itsadelegatethatpointstoand eventuallyfiresoffseveralmethods. 37. HowstheDLLHellproblemsolvedin.NET?Assembly versioningallowstheapplicationtospecifynotonlythelibraryitneeds torun(whichwasavailableunderWin32),butalsotheversionofthe assembly. 38. Whatarethewaystodeployanassembly?AnMSIinstaller,a CABarchive,andXCOPYcommand.
001 fo 4 egaP

39. Whatsasatelliteassembly?Whenyouwriteamultilingualor multiculturalapplicationin.NET,andwanttodistributethecore applicationseparatelyfromthelocalizedmodules,thelocalized assembliesthatmodifythecoreapplicationarecalledsatellite assemblies. 40. Whatnamespacesarenecessarytocreatealocalized application?System.Globalization,System.Resources. 41. Whatsthedifferencebetween//comments,/**/ commentsand///comments?Singleline,multilineandXML documentationcomments. 42. HowdoyougeneratedocumentationfromtheC#file commentedproperlywithacommandlinecompiler?Compileit witha/docswitch. 43. Whatsthedifferencebetween<c>and<code>XML documentationtag?Singlelinecodeexampleandmultiplelinecode example. 44. IsXMLcasesensitive?Yes,so<Student>and<student>are differentelements. 45. Whatdebuggingtoolscomewiththe.NETSDK?CorDBG commandlinedebugger,andDbgCLRgraphicdebugger.VisualStudio .NETusestheDbgCLR.TouseCorDbg,youmustcompiletheoriginalC# fileusingthe/debugswitch. 46. WhatdoestheThiswindowshowinthedebugger?Itpoints totheobjectthatspointedtobythisreference.Objectsinstancedatais shown. 47. Whatdoesassert()do?Indebugcompilation,asserttakesina Booleanconditionasaparameter,andshowstheerrordialogifthe conditionisfalse.Theprogramproceedswithoutanyinterruptionifthe conditionistrue. 48. WhatsthedifferencebetweentheDebugclassandTrace class?Documentationlooksthesame.UseDebugclassfordebug builds,useTraceclassforbothdebugandreleasebuilds. 49. Whyaretherefivetracinglevelsin System.Diagnostics.TraceSwitcher?Thetracingdumpscanbequite verboseandforsomeapplicationsthatareconstantlyrunningyourun theriskofoverloadingthemachineandtheharddrivethere.Fivelevels rangefromNonetoVerbose,allowingtofinetunethetracingactivities. 50. WhereistheoutputofTextWriterTraceListenerredirected? TotheConsoleoratextfiledependingontheparameterpassedtothe constructor. 51. HowdoyoudebuganASP.NETWebapplication?Attachthe aspnet_wp.exeprocesstotheDbgClrdebugger. 52. Whatarethreetestcasesyoushouldgothroughinunit testing?Positivetestcases(correctdata,correctoutput),negativetest cases(brokenormissingdata,properhandling),exceptiontestcases (exceptionsarethrownandcaughtproperly). 53. Canyouchangethevalueofavariablewhiledebugginga C#application?Yes,ifyouaredebuggingviaVisualStudio.NET,just gotoImmediatewindow.
001 fo 5 egaP

54. Explainthethreeservicesmodel(threetierapplication). Presentation(UI),business(logicandunderlyingcode)anddata(from storageorothersources). 55. WhatareadvantagesanddisadvantagesofMicrosoft provideddataproviderclassesinADO.NET?SQLServer.NETdata providerishighspeedandrobust,butrequiresSQLServerlicense purchasedfromMicrosoft.OLEDB.NETisuniversalforaccessingother sources,likeOracle,DB2,MicrosoftAccessandInformix,butitsa.NET layerontopofOLElayer,sonotthefastestthingintheworld. ODBC.NETisadeprecatedlayerprovidedforbackwardcompatibilityto ODBCengines. 56. WhatstheroleoftheDataReaderclassinADO.NET connections?Itreturnsareadonlydatasetfromthedatasourcewhen thecommandisexecuted. 57. WhatisthewildcardcharacterinSQL?Letssayyouwant toquerydatabasewithLIKEforallemployeeswhosenamestarts withLa.Thewildcardcharacteris%,theproperquerywithLIKEwould involveLa%. 58. ExplainACIDruleofthumbfortransactions.Transactionmust beAtomic(itisoneunitofworkanddoesnotdependentonprevious andfollowingtransactions),Consistent(dataiseithercommittedorroll back,noinbetweencasewheresomethinghasbeenupdatedand somethinghasnt),Isolated(notransactionseestheintermediateresults ofthecurrenttransaction),Durable(thevaluespersistifthedatahad beencommittedevenifthesystemcrashesrightafter). 59. WhatconnectionsdoesMicrosoftSQLServersupport? WindowsAuthentication(viaActiveDirectory)andSQLServer authentication(viaMicrosoftSQLServerusernameandpasswords). 60. Whichoneistrustedandwhichoneisuntrusted?Windows Authenticationistrustedbecausetheusernameandpasswordare checkedwiththeActiveDirectory,theSQLServerauthenticationis untrusted,sinceSQLServeristheonlyverifierparticipatinginthe transaction. 61. Whywouldyouuseuntrustedverificaion?WebServices mightuseit,aswellasnonWindowsapplications. 62. WhatdoestheparameterInitialCatalogdefineinside ConnectionString?Thedatabasenametoconnectto. 63. WhatsthedataprovidernametoconnecttoAccess database?Microsoft.Access. 64. WhatdoesDisposemethoddowiththeconnectionobject? Deletesitfromthememory. 65. Whatisaprerequisiteforconnectionpooling?Multiple processesmustagreethattheywillsharethesameconnection,where everyparameteristhesame,includingthesecuritysettings.

001 fo 6 egaP

InterviewQuestions .NETRemoting
1. WhatsaWindowsprocess?Itsanapplicationthatsrunningandhad beenallocatedmemory. 2. WhatstypicalaboutaWindowsprocessinregardstomemory allocation?EachprocessisallocateditsownblockofavailableRAM space,noprocesscanaccessanotherprocesscodeordata.Ifthe processcrashes,itdiesalonewithouttakingtheentireOSorabunchof otherapplicationsdown. 3. Whydoyoucallitaprocess?Whatsdifferentbetweenprocess andapplicationin.NET,notcommoncomputerusage, terminology?Aprocessisaninstanceofarunningapplication.An applicationisanexecutableontheharddriveornetwork.Therecanbe numerousprocesseslaunchedofthesameapplication(5copiesofWord running),but1processcanrunjust1application. 4. Whatdistributedprocessframeworksoutside.NETdoyouknow? DistributedComputingEnvironment/RemoteProcedureCalls(DEC/RPC), MicrosoftDistributedComponentObjectModel(DCOM),CommonObject RequestBrokerArchitecture(CORBA),andJavaRemoteMethod Invocation(RMI). 5. Whatarepossibleimplementationsofdistributedapplicationsin .NET?.NETRemotingandASP.NETWebServices.Ifwetalkaboutthe FrameworkClassLibrary,noteworthyclassesarein System.Runtime.RemotingandSystem.Web.Services. 6. Whenwouldyouuse.NETRemotingandwhenWebservices?Use remotingformoreefficientexchangeofinformationwhenyoucontrol bothendsoftheapplication.UseWebservicesforopenprotocolbased informationexchangewhenyouarejustaclientoraserverwiththe otherendbelongingtosomeoneelse. 7. Whatsaproxyoftheserverobjectin.NETRemoting?Itsafake copyoftheserverobjectthatresidesontheclientsideandbehavesasif itwastheserver.Ithandlesthecommunicationbetweenrealserver objectandtheclientobject.Thisprocessisalsoknownasmarshaling. 8. Whatareremotableobjectsin.NETRemoting?Remotableobjects aretheobjectsthatcanbemarshaledacrosstheapplicationdomains. Youcanmarshalbyvalue,whereadeepcopyoftheobjectiscreated andthenpassedtothereceiver.Youcanalsomarshalbyreference, wherejustareferencetoanexistingobjectispassed. 9. Whatarechannelsin.NETRemoting?Channelsrepresentthe objectsthattransfertheotherserializedobjectsfromoneapplication domaintoanotherandfromonecomputertoanother,aswellasone processtoanotheronthesamebox.Achannelmustexistbeforean objectcanbetransferred. 10. Whatsecuritymeasuresexistfor.NETRemotingin System.Runtime.Remoting?None.Securityshouldbetakencareofat theapplicationlevel.Cryptographyandothersecuritytechniquescanbe appliedatapplicationorserverlevel.
001 fo 7 egaP

11. Whatisaformatter?Aformatterisanobjectthatisresponsible forencodingandserializingdataintomessagesononeend,and deserializinganddecodingmessagesintodataontheotherend. 12. ChoosingbetweenHTTPandTCPforprotocolsandBinary andSOAPforformatters,whatarethetradeoffs?BinaryoverTCP isthemosteffiecient,SOAPoverHTTPisthemostinteroperable. 13. WhatsSingleCallactivationmodeusedfor?Iftheserver objectisinstantiatedforrespondingtojustonesinglerequest,the requestshouldbemadeinSingleCallmode. 14. WhatsSingletonactivationmode?Asingleobjectis instantiatedregardlessofthenumberofclientsaccessingit.Lifetimeof thisobjectisdeterminedbylifetimelease. 15. Howdoyoudefinetheleaseoftheobject?Byimplementing ILeaseinterfacewhenwritingtheclasscode. 16. Canyouconfigurea.NETRemotingobjectviaXMLfile?Yes, viamachine.configandapplicationlevel.configfile(orweb.configin ASP.NET).ApplicationlevelXMLsettingstakeprecedenceover machine.config. 17. Howcanyouautomaticallygenerateinterfaceforthe remotableobjectin.NETwithMicrosofttools?UsetheSoapsuds tool.

InterviewQuestions ASP.NET
1. Describetheroleofinetinfo.exe,aspnet_isapi.dll andaspnet_wp.exeinthepageloadingprocess.inetinfo.exeis theMicrosoftIISserverrunning,handlingASP.NETrequestsamong otherthings.WhenanASP.NETrequestisreceived(usuallyafilewith .aspxextension),theISAPIfilteraspnet_isapi.dlltakescareofitby passingtherequesttotheactualworkerprocessaspnet_wp.exe. 2. WhatsthedifferencebetweenResponse.Write() andResponse.Output.Write()?Thelatteroneallowsyoutowrite formattedoutput. 3. Whatmethodsarefiredduringthepageload?Init()whenthe pageisinstantiated,Load()whenthepageisloadedintoserver memory,PreRender()thebriefmomentbeforethepageisdisplayed totheuserasHTML,Unload()whenpagefinishesloading. 4. WheredoestheWebpagebelonginthe.NETFrameworkclass hierarchy?System.Web.UI.Page 5. Wheredoyoustoretheinformationabouttheuserslocale? System.Web.UI.Page.Culture 6. WhatsthedifferencebetweenCodebehind="MyCode.aspx.cs" andSrc="MyCode.aspx.cs"?CodeBehindisrelevanttoVisual Studio.NETonly.

001 fo 8 egaP

7. Whatsabubbledevent?Whenyouhaveacomplexcontrol,like DataGrid,writinganeventprocessingroutineforeachobject(cell, button,row,etc.)isquitetedious.Thecontrolscanbubbleuptheir eventhandlers,allowingthemainDataGrideventhandlertotakecare ofitsconstituents. 8. SupposeyouwantacertainASP.NETfunctionexecutedon MouseOveroveracertainbutton.Wheredoyouaddanevent handler? ItstheAttributesproperty,theAddfunctioninsidethatproperty. SobtnSubmit.Attributes.Add("onMouseOver","someClientCode()") 9. WhatdatatypedoestheRangeValidatorcontrolsupport? Integer,StringandDate. 10. ExplainthedifferencesbetweenServersideandClientside code? Serversidecoderunsontheserver.Clientsidecoderunsinthe clientsbrowser. 11. Whattypeofcode(serverorclient)isfoundinaCode Behindclass? Serversidecode. 12. Shouldvalidation(didtheuserenterarealdate)occur serversideorclientside?Why?Clientside.Thisreducesan additionalrequesttotheservertovalidatetheusersinput. 13. Whatdoesthe"EnableViewState"propertydo?Whywould Iwantitonoroff? Itenablestheviewstateonthepage.Itallowsthepagetosave theusersinputonaform. 14. WhatisthedifferencebetweenServer.Transferand Response.Redirect?WhywouldIchooseoneovertheother? Server.Transferisusedtopostaformtoanotherpage. Response.Redirectisusedtoredirecttheusertoanotherpageorsite. 15. CanyouexplainthedifferencebetweenanADO.NET DatasetandanADORecordset?
ADataSetcanrepresentanentirerelationaldatabaseinmemory,complete withtables,relations,andviews. ADataSetisdesignedtoworkwithoutanycontinuingconnectiontothe originaldatasource. DatainaDataSetisbulkloaded,ratherthanbeingloadedondemand. There'snoconceptofcursortypesinaDataSet. DataSetshavenocurrentrecordpointerYoucanuseForEachloopstomove throughthedata. YoucanstoremanyeditsinaDataSet,andwritethemtotheoriginaldata sourceinasingleoperation. ThoughtheDataSetisuniversal,otherobjectsinADO.NETcomeindifferent versionsfordifferentdatasources.

16. Canyougiveanexampleofwhatmightbebestsuitedto placeintheApplication_StartandSession_Startsubroutines? ThisiswhereyoucansetthespecificvariablesfortheApplicationand Sessionobjects.

001 fo 9 egaP

17. IfImdevelopinganapplicationthatmustaccommodate multiplesecuritylevelsthoughsecureloginandmyASP.NET webapplicationisspannedacrossthreewebservers(using roundrobinloadbalancing)whatwouldbethebestapproach tomaintainlogininstatefortheusers?Maintaintheloginstate securitythroughadatabase. 18. Canyouexplainwhatinheritanceisandanexampleof whenyoumightuseit?Whenyouwanttoinherit(usethe functionalityof)anotherclass.BaseClassEmployee.AManagerclass couldbederivedfromtheEmployeebaseclass. 19. Whatsanassembly? Assembliesarethebuildingblocksofthe .NETframework.OverviewofassembliesfromMSDN 20. Describethedifferencebetweeninlineandcodebehind. Inlinecodewrittenalongsidethehtmlinapage.Codebehindiscode writteninaseparatefileandreferencedbythe.aspxpage. 21. Explainwhatadiffgramis,andagooduseforone?The DiffGramisoneofthetwoXMLformatsthatyoucanusetorender DataSetobjectcontentstoXML.ForreadingdatabasedatatoanXML filetobesenttoaWebService. 22. WhatsMSIL,andwhyshouldmydevelopersneedan appreciationofitifatall?MSIListheMicrosoftIntermediate Language.All.NETcompatiblelanguageswillgetconvertedtoMSIL. 23. WhichmethoddoyouinvokeontheDataAdaptercontrolto loadyourgenerateddatasetwithdata?The.Fill()method 24. CanyoueditdataintheRepeatercontrol? No,itjustreads theinformationfromitsdatasource 25. Whichtemplatemustyouprovide,inordertodisplaydata inaRepeatercontrol?ItemTemplate 26. Howcanyouprovideanalternatingcolorschemeina Repeatercontrol?UsetheAlternatingItemTemplate 27. Whatpropertymustyouset,andwhatmethodmustyou callinyourcode,inordertobindthedatafromsomedata sourcetotheRepeatercontrol?YoumustsettheDataSource propertyandcalltheDataBindmethod. 28. WhatbaseclassdoallWebFormsinheritfrom? ThePage class. 29. Nametwopropertiescommonineveryvalidationcontrol? ControlToValidatepropertyandTextproperty. 30. Whattagsdoyouneedtoaddwithintheasp:datagridtags tobindcolumnsmanually?SetAutoGenerateColumnsPropertytofalseon
thedatagridtag

31. Whattagdoyouusetoaddahyperlinkcolumntothe DataGrid?<asp:HyperLinkColumn> 32. WhatisthetransportprotocolyouusetocallaWeb service?SOAPisthepreferredprotocol. 33. TrueorFalse:AWebservicecanonlybewrittenin.NET? False 34. WhatdoesWSDLstandfor?(WebServicesDescription Language)

001 fo 01 egaP

35. WhereontheInternetwouldyoulookforWebservices? (http://www.uddi.org) 36. WhichpropertyonaComboBoxdoyousetwithacolumn name,priortosettingtheDataSource,todisplaydatainthe combobox?DataTextFieldproperty 37. Whichcontrolwouldyouuseifyouneededtomakesure thevaluesintwodifferentcontrolsmatched? CompareValidator Control 38. TrueorFalse:TotestaWebserviceyoumustcreatea windowsapplicationorWebapplicationtoconsumethis service?False,thewebservicecomeswithatestpageanditprovidesHTTPGET
methodtotest.
.sessalc ynam niatn oc nac tI ?niatn oc LLD TEN. elgnis a nac sessalc y nam woH

39.

C#,.NET,XML,IISInterviewQuestions
Framework OOPS C#Languagefeatures Accessspecifiers Constructor ADO.NET Asp.Net WebService&Remoting COM XML IIS Controls Programming

1. Whatis.NETFramework? The.NETFrameworkhastwomaincomponents:thecommonlanguageruntimeand the.NETFrameworkclasslibrary. Youcanthinkoftheruntimeasanagentthatmanagescodeatexecutiontime, providingcoreservicessuchasmemorymanagement,threadmanagement,and remoting,whilealsoenforcingstricttypesafetyandotherformsofcodeaccuracythat ensuresecurityandrobustness. Theclasslibrary,isacomprehensive,objectorientedcollectionofreusabletypesthat youcanusetodevelopapplicationsrangingfromtraditionalcommandlineorgraphical userinterface(GUI)applicationstoapplicationsbasedonthelatestinnovations providedbyASP.NET,suchasWebFormsandXMLWebservices. 2. WhatisCLR,CTS,CLS? The.NETFrameworkprovidesaruntimeenvironmentcalledtheCommonLanguage RuntimeorCLR(similartotheJavaVirtualMachineorJVMinJava),whichhandlesthe executionofcodeandprovidesusefulservicesfortheimplementationoftheprogram. CLRtakescareofcodemanagementatprogramexecutionandprovidesvarious beneficialservicessuchasmemorymanagement,threadmanagement,security management,codeverification,compilation,andothersystemservices.Themanaged codethattargetsCLRbenefitsfromusefulfeaturessuchascrosslanguageintegration, crosslanguageexceptionhandling,versioning,enhancedsecurity,deploymentsupport, anddebugging. CommonTypeSystem(CTS)describeshowtypesaredeclared,usedandmanagedin theruntimeandfacilitatescrosslanguageintegration,typesafety,andhigh performancecodeexecution.
001 fo 11 egaP

TheCLSissimplyaspecificationthatdefinestherulestosupportlanguageintegration insuchawaythatprogramswritteninanylanguage,yetcaninteroperatewithone another,takingfulladvantageofinheritance,polymorphism,exceptions,andother features.TheserulesandthespecificationaredocumentedintheECMAproposed standarddocument,"PartitionIArchitecture",http://msdn.microsoft.com/net/ecma/ 3. WhatarethenewfeaturesofFramework1.1? 1. NativeSupportforDevelopingMobileWebApplications 2. EnableExecutionofWindowsFormsAssembliesOriginatingfromtheInternet AssembliesoriginatingfromtheInternetzoneforexample,Microsoft WindowsFormscontrolsembeddedinanInternetbasedWebpageor WindowsFormsassemblieshostedonanInternetWebserverandloadedeither throughtheWebbrowserorprogrammaticallyusingthe System.Reflection.Assembly.LoadFrom()methodnowreceivesufficient permissiontoexecuteinasemitrustedmanner.Defaultsecuritypolicyhas beenchangedsothatassembliesassignedbythecommonlanguageruntime (CLR)totheInternetzonecodegroupnowreceivetheconstrainedpermissions associatedwiththeInternetpermissionset.Inthe.NETFramework1.0Service Pack1andServicePack2,suchapplicationsreceivedthepermissions associatedwiththeNothingpermissionsetandcouldnotexecute. 3. EnableCodeAccessSecurityforASP.NETApplications Systemsadministratorscannowusecodeaccesssecuritytofurtherlockdown thepermissionsgrantedtoASP.NETWebapplicationsandWebservices. Althoughtheoperatingsystemaccountunderwhichanapplicationrunsimposes securityrestrictionsontheapplication,thecodeaccesssecuritysystemofthe CLRcanenforceadditionalrestrictionsonselectedapplicationresourcesbased onpoliciesspecifiedbysystemsadministrators.Youcanusethisfeatureina sharedserverenvironment(suchasanInternetserviceprovider(ISP)hosting multipleWebapplicationsononeserver)toisolateseparateapplicationsfrom oneanother,aswellaswithstandaloneserverswhereyouwantapplicationsto runwiththeminimumnecessaryprivileges. 4. NativeSupportforCommunicatingwithODBCandOracleDatabases 5. UnifiedProgrammingModelforSmartClientApplicationDevelopment TheMicrosoft.NETCompactFrameworkbringstheCLR,WindowsForms controls,andother.NETFrameworkfeaturestosmalldevices.The.NET CompactFrameworksupportsalargesubsetofthe.NETFrameworkclass libraryoptimizedforsmalldevices. 6. SupportforIPv6 The.NETFramework1.1supportstheemergingupdatetotheInternetProtocol, commonlyreferredtoasIPversion6,orsimplyIPv6.Thisprotocolisdesigned tosignificantlyincreasetheaddressspaceusedtoidentifycommunication endpointsintheInternettoaccommodateitsongoinggrowth. http://msdn.microsoft.com/netframework/technologyinfo/Overview/whatsnew.aspx 4. Is.NETaruntimeserviceoradevelopmentplatform? Ans:It'sbothandactuallyalotmore.Microsoft.NETincludesanewwayofdelivering softwareandservicestobusinessesandconsumers.ApartofMicrosoft.NETisthe.NET Frameworks.The.NETframeworksSDKconsistsoftwoparts:the.NETcommon languageruntimeandthe.NETclasslibrary.Inaddition,theSDKalsoincludes commandlinecompilersforC#,C++,JScript,andVB.Youusethesecompilersto buildapplicationsandcomponents.Thesecomponentsrequiretheruntimetoexecute sothisisadevelopmentplatform. 5. WhatisMSIL,IL? Whencompilingtomanagedcode,thecompilertranslatesyoursourcecodeinto Microsoftintermediatelanguage(MSIL),whichisaCPUindependentsetofinstructions thatcanbeefficientlyconvertedtonativecode.MSILincludesinstructionsforloading, storing,initializing,andcallingmethodsonobjects,aswellasinstructionsfor arithmeticandlogicaloperations,controlflow,directmemoryaccess,exception handling,andotheroperations.Microsoftintermediatelanguage(MSIL)isalanguage
001 fo 21 egaP

6.

7.

8.

9.

usedastheoutputofanumberofcompilersandastheinputtoajustintime(JIT) compiler.ThecommonlanguageruntimeincludesaJITcompilerforconvertingMSILto nativecode. CanIwriteILprogramsdirectly? Yes.PeterDraytonpostedthissimpleexampletotheDOTNETmailinglist: .assemblyMyAssembly{} .classMyApp{ .methodstaticvoidMain(){ .entrypoint ldstr "Hello,IL!" call voidSystem.Console::WriteLine(classSystem.Object) ret } } Justputthisintoafilecalledhello.il,andthenrunilasmhello.il.Anexeassemblywill begenerated. CanIdothingsinILthatIcan'tdoinC#? Yes.Acoupleofsimpleexamplesarethatyoucanthrowexceptionsthatarenot derivedfromSystem.Exception,andyoucanhavenonzerobasedarrays. WhatisJIT(justintime)?howitworks? BeforeMicrosoftintermediatelanguage(MSIL)canbeexecuted,itmustbeconverted bya.NETFrameworkjustintime(JIT)compilertonativecode,whichisCPUspecific codethatrunsonthesamecomputerarchitectureastheJITcompiler. RatherthanusingtimeandmemorytoconvertalltheMSILinaportableexecutable (PE)filetonativecode,itconvertstheMSILasitisneededduringexecutionandstores theresultingnativecodesothatitisaccessibleforsubsequentcalls. Theruntimesuppliesanothermodeofcompilationcalledinstalltimecodegeneration. TheinstalltimecodegenerationmodeconvertsMSILtonativecodejustastheregular JITcompilerdoes,butitconvertslargerunitsofcodeatatime,storingtheresulting nativecodeforusewhentheassemblyissubsequentlyloadedandexecuted. AspartofcompilingMSILtonativecode,codemustpassaverificationprocessunless anadministratorhasestablishedasecuritypolicythatallowscodetobypass verification.VerificationexaminesMSILandmetadatatofindoutwhetherthecodecan bedeterminedtobetypesafe,whichmeansthatitisknowntoaccessonlythe memorylocationsitisauthorizedtoaccess. Whatisstrongname? Anamethatconsistsofanassembly'sidentityitssimpletextname,versionnumber, andcultureinformation(ifprovided)strengthenedbyapublickeyandadigital signaturegeneratedovertheassembly. Whatisportableexecutable(PE)? Thefileformatdefiningthestructurethatallexecutablefiles(EXE)andDynamicLink Libraries(DLL)mustusetoallowthemtobeloadedandexecutedbyWindows.PEis derivedfromtheMicrosoftCommonObjectFileFormat(COFF).TheEXEandDLLfiles createdusingthe.NETFrameworkobeythePE/COFFformatsandalsoaddadditional headeranddatasectionstothefilesthatareonlyusedbytheCLR.Thespecification forthePE/COFFfileformatsisavailableat http://www.microsoft.com/whdc/hwdev/hardware/pecoffdown.mspx
fo ecnerrucco eht nopu dellac e b lliw taht etageled a y ficeps u oy stel drowy ek tneve ehT 001 fo 31 egaP marg orP ssalc et ageled tneve a gnitirw rof xatnys r aelc ?etageleD - tnevE si tahW lliw taht s dohtem detaicossa erom ro eno evah nac etageled ehT .edoc ru oy ni "tneve" emos margor p eno ni tneve nA .derrucco sah tneve eht taht setacidni edoc ruoy nehw dellac eb nomm oC krowemarF TEN. eht tegrat taht smargorp rehto ot elbaliava e dam eb nac ;)i tni(etageleDyM di ov etageled sc .etagele d_drowyek // n oitaralced etagele d // .emitn uR egaugnaL

10.

11. 12. {

13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. }

publicstaticvoidMain() { TakesADelegate(newMyDelegate(DelegateFunction)) } publicstaticvoidTakesADelegate(MyDelegateSomeFunction) { SomeFunction(21) } publicstaticvoidDelegateFunction(inti) { System.Console.WriteLine("Calledbydelegatewithnumber:{0}.",i) }

25. WhatisCodeAccessSecurity(CAS)? CASisthepartofthe.NETsecuritymodelthatdetermineswhetherornotapieceof codeisallowedtorun,andwhatresourcesitcanusewhenitisrunning.Forexample, itisCASthatwillpreventa.NETwebappletfromformattingyourharddisk. HowdoesCASwork? TheCASsecuritypolicyrevolvesaroundtwokeyconceptscodegroupsand permissions.Each.NETassemblyisamemberofaparticularcodegroup,andeach codegroupisgrantedthepermissionsspecifiedinanamedpermissionset. Forexample,usingthedefaultsecuritypolicy,acontroldownloadedfromawebsite belongstothe'ZoneInternet'codegroup,whichadherestothepermissionsdefined bythe'Internet'namedpermissionset.(Naturallythe'Internet'namedpermissionset representsaveryrestrictiverangeofpermissions.) WhodefinestheCAScodegroups? Microsoftdefinessomedefaultones,butyoucanmodifytheseandevencreateyour own.Toseethecodegroupsdefinedonyoursystem,run'caspollg'fromthe commandline.Onmysyystemitlookslikethis: 26. Level=Machine 27. CodeGroups: 28. 29. 1.Allcode:Nothing 30. 1.1.ZoneMyComputer:FullTrust 31. 1.1.1.HonorSkipVerificationrequests:SkipVerification 32. 1.2.ZoneIntranet:LocalIntranet 33. 1.3.ZoneInternet:Internet 34. 1.4.ZoneUntrusted:Nothing 35. 1.5.ZoneTrusted:Internet 1.6.StrongName Notethehierarchyofcodegroupsthetopofthehierarchyisthemostgeneral('All code'),whichisthensubdividedintoseveralgroups,eachofwhichinturncanbesub divided.Alsonotethat(somewhatcounterintuitively)asubgroupcanbeassociated withamorepermissivepermissionsetthanitsparent. HowdoIdefinemyowncodegroup? Usecaspol.Forexample,supposeyoutrustcodefromwww.mydomain.comandyou wantithavefullaccesstoyoursystem,butyouwanttokeepthedefaultrestrictions forallotherinternetsites.Toachievethis,youwouldaddanewcodegroupasasub groupofthe'ZoneInternet'group,likethis: caspolag1.3sitewww.mydomain.comFullTrust Nowifyouruncaspollgyouwillseethatthenewgrouphasbeenaddedasgroup 1.3.1: 1.3. ZoneInternet:Internet 1.3.1. Sitewww.mydomain.com:FullTrust ... Notethatthenumericlabel(1.3.1)isjustacaspolinventiontomakethecodegroups easytomanipulatefromthecommandline.Theunderlyingruntimeneverseesit.
001 fo 41 egaP

HowdoIchangethepermissionsetforacodegroup? Usecaspol.Ifyouarethemachineadministrator,youcanoperateatthe'machine' levelwhichmeansnotonlythatthechangesyoumakebecomethedefaultforthe machine,butalsothatuserscannotchangethepermissionstobemorepermissive.If youareanormal(nonadmin)useryoucanstillmodifythepermissions,butonlyto makethemmorerestrictive.Forexample,toallowintranetcodetodowhatitlikesyou mightdothis: caspolcg1.2FullTrust Notethatbecausethisismorepermissivethanthedefaultpolicy(onastandard system),youshouldonlydothisatthemachineleveldoingitattheuserlevelwill havenoeffect.

CanIcreatemyownpermissionset? Yes.Usecaspolap,specifyinganXMLfilecontainingthepermissionsinthepermission set.Tosaveyousometime,hereisasamplefilecorrespondingtothe'Everything' permissionsetjustedittosuityourneeds.Whenyouhaveeditedthesample,addit totherangeofavailablepermissionsetslikethis: caspolapsamplepermset.xml Then,toapplythepermissionsettoacodegroup,dosomethinglikethis: caspolcg1.3SamplePermSet(Bydefault,1.3isthe'Internet'codegroup) I'mhavingsometroublewithCAS.HowcanIdiagnosemyproblem? Caspolhasacoupleofoptionsthatmighthelp.First,youcanaskcaspoltotellyou whatcodegroupanassemblybelongsto,usingcaspolrsg.Similarly,youcanask whatpermissionsarebeingappliedtoaparticularassemblyusingcaspolrsp. Ican'tbebotheredwithallthisCASstuff.CanIturnitoff? Yes,aslongasyouareanadministrator.Justrun: caspolsoff http://www.codeproject.com/dotnet/UB_CAS_NET.asp 36. Whichnamespaceisthebaseclassfor.netClasslibrary? Ans:system.object 37. Whatareobjectpoolingandconnectionpoolinganddifference?Wheredowe settheMinandMaxPoolsizeforconnectionpooling? ObjectpoolingisaCOM+servicethatenablesyoutoreducetheoverheadofcreating eachobjectfromscratch.Whenanobjectisactivated,itispulledfromthepool.When theobjectisdeactivated,itisplacedbackintothepooltoawaitthenextrequest.You canconfigureobjectpoolingbyapplyingtheObjectPoolingAttributeattributetoaclass thatderivesfromtheSystem.EnterpriseServices.ServicedComponentclass. Objectpoolingletsyoucontrolthenumberofconnectionsyouuse,asopposedto connectionpooling,whereyoucontrolthemaximumnumberreached. Followingareimportantdifferencesbetweenobjectpoolingandconnectionpooling: Creation.Whenusingconnectionpooling,creationisonthesamethread,soif thereisnothinginthepool,aconnectioniscreatedonyourbehalf.Withobject pooling,thepoolmightdecidetocreateanewobject.However,ifyouhave alreadyreachedyourmaximum,itinsteadgivesyouthenextavailableobject. Thisiscrucialbehaviorwhenittakesalongtimetocreateanobject,butyoudo notuseitforverylong. Enforcementofminimumsandmaximums.Thisisnotdoneinconnection pooling.Themaximumvalueinobjectpoolingisveryimportantwhentryingto scaleyourapplication.Youmightneedtomultiplexthousandsofrequeststo justafewobjects.(TPC/Cbenchmarksrelyonthis.) COM+objectpoolingisidenticaltowhatisusedin.NETFrameworkmanagedSQL Clientconnectionpooling.Forexample,creationisonadifferentthreadandminimums andmaximumsareenforced.

001 fo 51 egaP

1. WhatisApplicationDomain? TheprimarypurposeoftheAppDomainistoisolateanapplicationfromother applications.Win32processesprovideisolationbyhavingdistinctmemoryaddress spaces.Thisiseffective,butitisexpensiveanddoesn'tscalewell.The.NETruntime enforcesAppDomainisolationbykeepingcontrolovertheuseofmemoryallmemory intheAppDomainismanagedbythe.NETruntime,sotheruntimecanensurethat AppDomainsdonotaccesseachother'smemory. Objectsindifferentapplicationdomainscommunicateeitherbytransportingcopiesof objectsacrossapplicationdomainboundaries,orbyusingaproxytoexchange messages. MarshalByRefObjectisthebaseclassforobjectsthatcommunicateacross applicationdomainboundariesbyexchangingmessagesusingaproxy.Objectsthatdo notinheritfromMarshalByRefObjectareimplicitlymarshalbyvalue.Whenaremote applicationreferencesamarshalbyvalueobject,acopyoftheobjectispassedacross applicationdomainboundaries. HowdoesanAppDomaingetcreated? AppDomainsareusuallycreatedbyhosts.ExamplesofhostsaretheWindowsShell, ASP.NETandIE.Whenyouruna.NETapplicationfromthecommandline,thehostis theShell.TheShellcreatesanewAppDomainforeveryapplication. AppDomainscanalsobeexplicitlycreatedby.NETapplications.HereisaC#sample whichcreatesanAppDomain,createsaninstanceofanobjectinsideit,andthen executesoneoftheobject'smethods.Notethatyoumustnametheexecutable 'appdomaintest.exe'forthiscodetoworkasis. usingSystem usingSystem.Runtime.Remoting publicclassCAppDomainInfo:MarshalByRefObject { publicstringGetAppDomainInfo() { return"AppDomain="+AppDomain.CurrentDomain.FriendlyName } } publicclassApp { publicstaticintMain() { AppDomainad=AppDomain.CreateDomain("Andy'snewdomain",null,null ) ObjectHandleoh=ad.CreateInstance("appdomaintest","CAppDomainInfo" ) CAppDomainInfoadInfo=(CAppDomainInfo)(oh.Unwrap()) stringinfo=adInfo.GetAppDomainInfo() Console.WriteLine("AppDomaininfo:"+info) return0 } } 2. Whatisserializationin.NET?Whatarethewaystocontrolserialization? Serializationistheprocessofconvertinganobjectintoastreamofbytes. Deserializationistheoppositeprocessofcreatinganobjectfromastreamofbytes. Serialization/Deserializationismostlyusedtotransportobjects(e.g.duringremoting), ortopersistobjects(e.g.toafileordatabase).Serializationcanbedefinedasthe processofstoringthestateofanobjecttoastoragemedium.Duringthisprocess,the publicandprivatefieldsoftheobjectandthenameoftheclass,includingtheassembly containingtheclass,areconvertedtoastreamofbytes,whichisthenwrittentoadata stream.Whentheobjectissubsequentlydeserialized,anexactcloneoftheoriginal objectiscreated.
001 fo 61 egaP

Binaryserializationpreservestypefidelity,whichisusefulforpreservingthe stateofanobjectbetweendifferentinvocationsofanapplication.Forexample, youcanshareanobjectbetweendifferentapplicationsbyserializingittothe clipboard.Youcanserializeanobjecttoastream,disk,memory,overthe network,andsoforth.Remotingusesserializationtopassobjects"byvalue" fromonecomputerorapplicationdomaintoanother. XMLserializationserializesonlypublicpropertiesandfieldsanddoesnot preservetypefidelity.Thisisusefulwhenyouwanttoprovideorconsumedata withoutrestrictingtheapplicationthatusesthedata.BecauseXMLisanopen standard,itisanattractivechoiceforsharingdataacrosstheWeb.SOAPisan openstandard,whichmakesitanattractivechoice.

Therearetwoseparatemechanismsprovidedbythe.NETclasslibraryXmlSerializer andSoapFormatter/BinaryFormatter.MicrosoftusesXmlSerializerforWebServices, andusesSoapFormatter/BinaryFormatterforremoting.Bothareavailableforusein yourowncode. WhydoIgeterrorswhenItrytoserializeaHashtable? XmlSerializerwillrefusetoserializeinstancesofanyclassthatimplementsIDictionary, e.g.Hashtable.SoapFormatterandBinaryFormatterdonothavethisrestriction. 3. Whatisexceptionhandling? Whenanexceptionoccurs,thesystemsearchesforthenearestcatchclausethatcan handletheexception,asdeterminedbytheruntimetypeoftheexception.First,the currentmethodissearchedforalexicallyenclosingtrystatement,andtheassociated catchclausesofthetrystatementareconsideredinorder.Ifthatfails,themethodthat calledthecurrentmethodissearchedforalexicallyenclosingtrystatementthat enclosesthepointofthecalltothecurrentmethod.Thissearchcontinuesuntilacatch clauseisfoundthatcanhandlethecurrentexception,bynaminganexceptionclass thatisofthesameclass,orabaseclass,oftheruntimetypeoftheexceptionbeing thrown.Acatchclausethatdoesn'tnameanexceptionclasscanhandleanyexception. Onceamatchingcatchclauseisfound,thesystempreparestotransfercontroltothe firststatementofthecatchclause.Beforeexecutionofthecatchclausebegins,the systemfirstexecutes,inorder,anyfinallyclausesthatwereassociatedwithtry statementsmorenestedthatthantheonethatcaughttheexception. Exceptionsthatoccurduringdestructorexecutionareworthspecialmention.Ifan exceptionoccursduringdestructorexecution,andthatexceptionisnotcaught,then theexecutionofthatdestructoristerminatedandthedestructorofthebaseclass(if any)iscalled.Ifthereisnobaseclass(asinthecaseoftheobjecttype)orifthereis nobaseclassdestructor,thentheexceptionisdiscarded. 4. WhatisAssembly? Assembliesarethebuildingblocksof.NETFrameworkapplicationstheyformthe fundamentalunitofdeployment,versioncontrol,reuse,activationscoping,and securitypermissions.Anassemblyisacollectionoftypesandresourcesthatarebuilt toworktogetherandformalogicalunitoffunctionality.Anassemblyprovidesthe commonlanguageruntimewiththeinformationitneedstobeawareoftype implementations.Totheruntime,atypedoesnotexistoutsidethecontextofan assembly. Assembliesareafundamentalpartofprogrammingwiththe.NETFramework.An assemblyperformsthefollowingfunctions: Itcontainscodethatthecommonlanguageruntimeexecutes.Microsoft intermediatelanguage(MSIL)codeinaportableexecutable(PE)filewillnotbe executedifitdoesnothaveanassociatedassemblymanifest.Notethateach assemblycanhaveonlyoneentrypoint(thatis,DllMain,WinMain,orMain). Itformsasecurityboundary.Anassemblyistheunitatwhichpermissionsare requestedandgranted. Itformsatypeboundary.Everytype'sidentityincludesthenameofthe assemblyinwhichitresides.AtypecalledMyTypeloadedinthescopeofone assemblyisnotthesameasatypecalledMyTypeloadedinthescopeof anotherassembly.
001 fo 71 egaP

Itformsareferencescopeboundary.Theassembly'smanifestcontains assemblymetadatathatisusedforresolvingtypesandsatisfyingresource requests.Itspecifiesthetypesandresourcesthatareexposedoutsidethe assembly.Themanifestalsoenumeratesotherassembliesonwhichitdepends. Itformsaversionboundary.Theassemblyisthesmallestversionableunitin thecommonlanguageruntimealltypesandresourcesinthesameassembly areversionedasaunit.Theassembly'smanifestdescribestheversion dependenciesyouspecifyforanydependentassemblies. Itformsadeploymentunit.Whenanapplicationstarts,onlytheassembliesthat theapplicationinitiallycallsmustbepresent.Otherassemblies,suchas localizationresourcesorassembliescontainingutilityclasses,canberetrieved ondemand.Thisallowsapplicationstobekeptsimpleandthinwhenfirst downloaded. Itistheunitatwhichsidebysideexecutionissupported.

Assembliescanbestaticordynamic.Staticassembliescaninclude.NETFramework types(interfacesandclasses),aswellasresourcesfortheassembly(bitmaps,JPEG files,resourcefiles,andsoon).StaticassembliesarestoredondiskinPEfiles.Youcan alsousethe.NETFrameworktocreatedynamicassemblies,whicharerundirectlyfrom memoryandarenotsavedtodiskbeforeexecution.Youcansavedynamicassemblies todiskaftertheyhaveexecuted. Thereareseveralwaystocreateassemblies.Youcanusedevelopmenttools,suchas VisualStudio.NET,thatyouhaveusedinthepasttocreate.dllor.exefiles.Youcan usetoolsprovidedinthe.NETFrameworkSDKtocreateassemblieswithmodules createdinotherdevelopmentenvironments.Youcanalsousecommonlanguage runtimeAPIs,suchasReflection.Emit,tocreatedynamicassemblies. 5. Whatarethecontentsofassembly? Ingeneral,astaticassemblycanconsistoffourelements: Theassemblymanifest,whichcontainsassemblymetadata. Typemetadata. Microsoftintermediatelanguage(MSIL)codethatimplementsthetypes. Asetofresources. 6. Whatarethedifferenttypesofassemblies? Private,Public/Shared,Satellite 7. Whatisthedifferencebetweenaprivateassemblyandasharedassembly? 1. Locationandvisibility:Aprivateassemblyisnormallyusedbyasingle application,andisstoredintheapplication'sdirectory,orasubdirectory beneath.Asharedassemblyisnormallystoredintheglobalassemblycache, whichisarepositoryofassembliesmaintainedbythe.NETruntime.Shared assembliesareusuallylibrariesofcodewhichmanyapplicationswillfinduseful, e.g.the.NETframeworkclasses. 2. Versioning:Theruntimeenforcesversioningconstraintsonlyonshared assemblies,notonprivateassemblies. 1. WhatareSatelliteAssemblies?Howyouwillcreatethis?Howwillyougetthe differentlanguagestrings? Satelliteassembliesareoftenusedtodeploylanguagespecificresourcesforan application.Theselanguagespecificassembliesworkinsidebysideexecutionbecause theapplicationhasaseparateproductIDforeachlanguageandinstallssatellite assembliesinalanguagespecificsubdirectoryforeachlanguage.Whenuninstalling, theapplicationremovesonlythesatelliteassembliesassociatedwithagivenlanguage and.NETFrameworkversion.Nocore.NETFrameworkfilesareremovedunlessthe lastlanguageforthat.NETFrameworkversionisbeingremoved. (Forexample,EnglishandJapaneseeditionsofthe.NETFrameworkversion1.1share thesamecorefiles.TheJapanese.NETFrameworkversion1.1addssatellite assemblieswithlocalizedresourcesina\jasubdirectory.Anapplicationthatsupports the.NETFrameworkversion1.1,regardlessofitslanguage,alwaysusesthesamecore runtimefiles.)
001 fo 81 egaP

2. 3.

4.

5.

6.

7. 8.

http://www.ondotnet.com/lpt/a/2637 ** Howwilluloaddynamicassembly?Howwillcreateassembliesatruntime? ** WhatisAssemblymanifest?whatalldetailstheassemblymanifestwill contain? Everyassembly,whetherstaticordynamic,containsacollectionofdatathatdescribes howtheelementsintheassemblyrelatetoeachother.Theassemblymanifestcontains thisassemblymetadata.Anassemblymanifestcontainsallthemetadataneededto specifytheassembly'sversionrequirementsandsecurityidentity,andallmetadata neededtodefinethescopeoftheassemblyandresolvereferencestoresourcesand classes.TheassemblymanifestcanbestoredineitheraPEfile(an.exeor.dll)with Microsoftintermediatelanguage(MSIL)codeorinastandalonePEfilethatcontains onlyassemblymanifestinformation. ItcontainsAssemblyname,Versionnumber,Culture,Strongnameinformation,Listof allfilesintheassembly,Typereferenceinformation,Informationonreferenced assemblies. Differencebetweenassemblymanifest&metadata? assemblymanifestAnintegralpartofeveryassemblythatrenderstheassembly selfdescribing.Theassemblymanifestcontainstheassembly'smetadata.Themanifest establishestheassemblyidentity,specifiesthefilesthatmakeuptheassembly implementation,specifiesthetypesandresourcesthatmakeuptheassembly,itemizes thecompiletimedependenciesonotherassemblies,andspecifiesthesetof permissionsrequiredfortheassemblytorunproperly.Thisinformationisusedatrun timetoresolvereferences,enforceversionbindingpolicy,andvalidatetheintegrityof loadedassemblies.Theselfdescribingnatureofassembliesalsohelpsmakeszero impactinstallandXCOPYdeploymentfeasible. metadataInformationthatdescribeseveryelementmanagedbythecommon languageruntime:anassembly,loadablefile,type,method,andsoon.Thiscan includeinformationrequiredfordebuggingandgarbagecollection,aswellassecurity attributes,marshalingdata,extendedclassandmemberdefinitions,versionbinding, andotherinformationrequiredbytheruntime. WhatisGlobalAssemblyCache(GAC)andwhatisthepurposeofit?(Howto makeanassemblytopublic?Steps)Howmorethanoneversionofan assemblycankeepinsameplace? Eachcomputerwherethecommonlanguageruntimeisinstalledhasamachinewide codecachecalledtheglobalassemblycache.Theglobalassemblycachestores assembliesspecificallydesignatedtobesharedbyseveralapplicationsonthe computer. Youshouldshareassembliesbyinstallingthemintotheglobalassembly cacheonlywhenyouneedto. Steps Createastrongnameusingsn.exetool eg:snkkeyPair.snk withinAssemblyInfo.csaddthegeneratedfilename eg:[assembly:AssemblyKeyFile("abc.snk")] recompileproject,theninstallittoGACbyeither drag&dropittoassemblyfolder(C:\WINDOWS\assemblyORC:\WINNT\assembly) (shfusion.dlltool) or gacutiliabc.dll IfIhavemorethanoneversionofoneassemblies,thenhow'llIuseold version(how/wheretospecifyversionnumber?)inmyapplication? ** Howtofindmethodsofaassemblyfile(notusingILDASM) Reflection WhatisGarbageCollectionin.Net?Garbagecollectionprocess? Theprocessoftransitivelytracingthroughallpointerstoactivelyusedobjectsinorder tolocateallobjectsthatcanbereferenced,andthenarrangingtoreuseanyheap memorythatwasnotfoundduringthistrace.Thecommonlanguageruntimegarbage

001 fo 91 egaP

collectoralsocompactsthememorythatisinusetoreducetheworkingspaceneeded fortheheap. 9. WhatisReflectionin.NET?Namespace? Howwillyouloadanassemblywhich isnotreferencedbycurrentassembly? All.NETcompilersproducemetadataaboutthetypesdefinedinthemodulesthey produce.Thismetadataispackagedalongwiththemodule(modulesinturnare packagedtogetherinassemblies),andcanbeaccessedbyamechanismcalled reflection.TheSystem.Reflectionnamespacecontainsclassesthatcanbeusedto interrogatethetypesforamodule/assembly. Usingreflectiontoaccess.NETmetadataisverysimilartousingITypeLib/ITypeInfoto accesstypelibrarydatainCOM,anditisusedforsimilarpurposese.g.determining datatypesizesformarshalingdataacrosscontext/process/machineboundaries. Reflectioncanalsobeusedtodynamicallyinvokemethods(see System.Type.InvokeMember),orevencreatetypesdynamicallyatruntime(see System.Reflection.Emit.TypeBuilder). 10. WhatisCustomattribute?Howtocreate?IfI'mhavingcustomattributeinan assembly,howtosaythatnameinthecode? A:Theprimarystepstoproperlydesigncustomattributeclassesareasfollows: a. ApplyingtheAttributeUsageAttribute([AttributeUsage(AttributeTargets.All, Inherited=false,AllowMultiple=true)]) b. Declaringtheattribute.(classpublicclassMyAttribute:System.Attribute{//.. .}) c. Declaringconstructors(publicMyAttribute(boolmyvalue){this.myvalue= myvalue}) d. Declaringproperties publicboolMyProperty { get{returnthis.myvalue} set{this.myvalue=value} } Thefollowingexampledemonstratesthebasicwayofusingreflectiontogetaccessto customattributes. classMainClass { publicstaticvoidMain() { System.Reflection.MemberInfoinfo=typeof(MyClass) object[]attributes=info.GetCustomAttributes() for(inti=0i<attributes.Lengthi++) { System.Console.WriteLine(attributes[i]) } } } 1. Whatisthemanagedandunmanagedcodein.net? The.NETFrameworkprovidesaruntimeenvironmentcalledtheCommonLanguage Runtime,whichmanagestheexecutionofcodeandprovidesservicesthatmakethe developmentprocesseasier.Compilersandtoolsexposetheruntime'sfunctionalityand enableyoutowritecodethatbenefitsfromthismanagedexecutionenvironment.Code thatyoudevelopwithalanguagecompilerthattargetstheruntimeiscalledmanaged codeitbenefitsfromfeaturessuchascrosslanguageintegration,crosslanguage exceptionhandling,enhancedsecurity,versioninganddeploymentsupport,asimplified modelforcomponentinteraction,anddebuggingandprofilingservices. 2. Howdoyoucreatethreadingin.NET?Whatisthenamespaceforthat? ** System.Threading.Thread 3. SerializeandMarshalByRef?
001 fo 02 egaP

4. usingdirectivevsusingstatement YoucreateaninstanceinausingstatementtoensurethatDisposeiscalledonthe objectwhentheusingstatementisexited.Ausingstatementcanbeexitedeither whentheendoftheusingstatementisreachedorif,forexample,anexceptionis thrownandcontrolleavesthestatementblockbeforetheendofthestatement. Theusingdirectivehastwouses: Createanaliasforanamespace(ausingalias). Permittheuseoftypesinanamespace,suchthat,youdonothavetoqualify theuseofatypeinthatnamespace(ausingdirective). 1. DescribetheManagedExecutionProcess? Themanagedexecutionprocessincludesthefollowingsteps: 1. Choosingacompiler. Toobtainthebenefitsprovidedbythecommonlanguageruntime,youmustuse oneormorelanguagecompilersthattargettheruntime. 2. CompilingyourcodetoMicrosoftintermediatelanguage(MSIL). CompilingtranslatesyoursourcecodeintoMSILandgeneratestherequired metadata. 3. CompilingMSILtonativecode. Atexecutiontime,ajustintime(JIT)compilertranslatestheMSILintonative code.Duringthiscompilation,codemustpassaverificationprocessthat examinestheMSILandmetadatatofindoutwhetherthecodecanbe determinedtobetypesafe. 4. Executingyourcode. Thecommonlanguageruntimeprovidestheinfrastructurethatenables executiontotakeplaceaswellasavarietyofservicesthatcanbeusedduring execution. 1. WhatisActiveDirectory?WhatisthenamespaceusedtoaccesstheMicrosoft ActiveDirectories?WhatareADSIDirectories? ActiveDirectoryServiceInterfaces(ADSI)isaprogrammaticinterfaceforMicrosoft WindowsActiveDirectory.Itenablesyourapplicationstointeractwithdiverse directoriesonanetwork,usingasingleinterface.VisualStudio.NETandthe.NET FrameworkmakeiteasytoaddADSIfunctionalitywiththeDirectoryEntryand DirectorySearchercomponents. UsingADSI,youcancreateapplicationsthatperformcommonadministrativetasks, suchasbackingupdatabases,accessingprinters,andadministeringuseraccounts. ADSImakesitpossibleforyouto: Logononcetoworkwithdiversedirectories.TheDirectoryEntrycomponent classprovidesusernameandpasswordpropertiesthatcanbeenteredat runtimeandcommunicatedtotheActiveDirectoryobjectyouarebindingto. Useasingleapplicationprogramminginterface(API)toperformtaskson multipledirectorysystemsbyofferingtheuseravarietyofprotocolstouse.The DirectoryServicesnamespaceprovidestheclassestoperformmost administrativefunctions. Perform"richquerying"ondirectorysystems.ADSItechnologyallowsfor searchingforanobjectbyspecifyingtwoquerydialects:SQLandLDAP. Accessanduseasingle,hierarchicalstructureforadministeringandmaintaining diverseandcomplicatednetworkconfigurationsbyaccessinganActiveDirectory tree. IntegratedirectoryinformationwithdatabasessuchasSQLServer.The DirectoryEntrypathmaybeusedasanADO.NETconnectionstringprovided thatitisusingtheLDAPprovider. usingSystem.DirectoryServices 1. HowGarbageCollector(GC)Works? Themethodsinthisclassinfluencewhenanobjectisgarbagecollectedandwhen resourcesallocatedbyanobjectarereleased.Propertiesinthisclassprovide
001 fo 12 egaP

informationaboutthetotalamountofmemoryavailableinthesystemandtheage category,orgeneration,ofmemoryallocatedtoanobject.Periodically,thegarbage collectorperformsgarbagecollectiontoreclaimmemoryallocatedtoobjectsforwhich therearenovalidreferences.Garbagecollectionhappensautomaticallywhenarequest formemorycannotbesatisfiedusingavailablefreememory.Alternatively,an applicationcanforcegarbagecollectionusingtheCollectmethod. Garbagecollectionconsistsofthefollowingsteps: 1. Thegarbagecollectorsearchesformanagedobjectsthatarereferencedin managedcode. 2. Thegarbagecollectorattemptstofinalizeobjectsthatarenotreferenced. 3. Thegarbagecollectorfreesobjectsthatarenotreferencedandreclaimstheir memory. 1. WhydoweneedtocallCG.SupressFinalize? Requeststhatthesystemnotcallthefinalizermethodforthespecifiedobject. publicstaticvoidSuppressFinalize( objectobj )Themethodremovesobjfromthesetofobjectsthatrequirefinalization.Theobj parameterisrequiredtobethecallerofthismethod. ObjectsthatimplementtheIDisposableinterfacecancallthismethodfromthe IDisposable.Disposemethodtopreventthegarbagecollectorfromcalling Object.Finalizeonanobjectthatdoesnotrequireit. 2. Whatisnmaketool? TheNmaketool(Nmake.exe)isa32bittoolthatyouusetobuildprojectsbasedon commandscontainedina.makfile. usage:nmakeaall 3. WhatareNamespaces? Thenamespacekeywordisusedtodeclareascope.Thisnamespacescopeletsyou organizecodeandgivesyouawaytocreategloballyuniquetypes.Evenifyoudonot explicitlydeclareone,adefaultnamespaceiscreated.Thisunnamednamespace, sometimescalledtheglobalnamespace,ispresentineveryfile.Anyidentifierinthe globalnamespaceisavailableforuseinanamednamespace.Namespacesimplicitly havepublicaccessandthisisnotmodifiable. 4. WhatisthedifferencebetweenCONSTandREADONLY? Botharemeantforconstantvalues.Aconstfieldcanonlybeinitializedatthe declarationofthefield.Areadonlyfieldcanbeinitializedeitheratthedeclarationorin aconstructor.Therefore,readonlyfieldscanhavedifferentvaluesdependingonthe constructorused. readonlyintb publicX() { b=1 } publicX(strings) { b=5 } publicX(strings,inti) { b=i } Also,whileaconstfieldisacompiletimeconstant,thereadonlyfieldcanbeusedfor runtimeconstants,asinthefollowingexample: publicstaticreadonlyuintl1=(uint)DateTime.Now.Ticks(thiscan'tbepossiblewith const) 5. Whatisthedifferencebetweenref&outparameters? Anargumentpassedtoarefparametermustfirstbeinitialized.Comparethistoanout parameter,whoseargumentdoesnothavetobeexplicitlyinitializedbeforebeing passedtoanoutparameter.
001 fo 22 egaP

6. WhatisthedifferencebetweenArrayandLinkedList? 7. WhatisthedifferencebetweenArrayandArraylist? AselementsareaddedtoanArrayList,thecapacityisautomaticallyincreasedas requiredthroughreallocation.ThecapacitycanbedecreasedbycallingTrimToSizeor bysettingtheCapacitypropertyexplicitly. 8. WhatisJaggedArrays? Ajaggedarrayisanarraywhoseelementsarearrays.Theelementsofajaggedarray canbeofdifferentdimensionsandsizes.Ajaggedarrayissometimescalledan"array ofarrays." 9. Whatareindexers? Indexersaresimilartoproperties,exceptthatthegetandsetaccessorsofindexers takeparameters,whilepropertyaccessorsdonot. 10. WhatisAsynchronouscallandhowitcanbeimplementedusingdelegates? 11. Howtocreateeventsforacontrol?Whatiscustomevents?Howtocreateit? 12. Ifyouwanttowriteyourowndotnetlanguage,whatstepsyouwillutake care? 13. Describethedifferencebetweeninlineandcodebehindwhichisbestina looselycoupledsolution? 14. howdotnetcompiledcodewillbecomeplatformindependent? 15. withoutmodifyingsourcecodeifwecompileagain,willitbegeneratedMSIL again? 16. C++&C#differences ** (COM) 17. InteropServices? Thecommonlanguageruntimeprovidestwomechanismsforinteroperatingwith unmanagedcode: Platforminvoke,whichenablesmanagedcodetocallfunctionsexportedfroman unmanagedlibrary. COMinterop,whichenablesmanagedcodetointeractwithCOMobjectsthrough interfaces. BothplatforminvokeandCOMinteropuseinteropmarshalingtoaccuratelymove methodargumentsbetweencallerandcalleeandback,ifrequired. 1. HowdoesuhandlethisCOMcomponentsdevelopedinotherprogramming languagesin.NET? 2. WhatisRCW(RuntimeCallableWrappers)? ThecommonlanguageruntimeexposesCOMobjectsthroughaproxycalledthe runtimecallablewrapper(RCW).AlthoughtheRCWappearstobeanordinaryobjectto .NETclients,itsprimaryfunctionistomarshalcallsbetweena.NETclientandaCOM object. 3. WhatisCCW(COMCallableWrapper) AproxyobjectgeneratedbythecommonlanguageruntimesothatexistingCOM applicationscanusemanagedclasses,including.NETFrameworkclasses, transparently. 4. HowCCWandRCWisworking? ** 5. Howwillyouregistercom+services? The.NETFrameworkSDKprovidesthe.NETFrameworkServicesInstallationTool (Regsvcs.exeacommandlinetool)tomanuallyregisteranassemblycontaining servicedcomponents.Youcanalsoaccesstheseregistrationfeaturesprogrammatically withtheSystem.EnterpriseServicesRegistrationHelperclassbycreatinganinstanceof classRegistrationHelperandusingthemethodInstallAssembly 6. WhatisuseofContextUtilclass? ContextUtilisthepreferredclasstouseforobtainingCOM+contextinformation.
001 fo 32 egaP

7. WhatisthenewthreefeaturesofCOM+services,whicharenotthereinCOM (MTS)? ** 8. IstheCOMarchitecturesameas.Netarchitecture? Whatisthedifference betweenthem? ** 9. CanwecopyaCOMdlltoGACfolder? ** 10. WhatisPinvoke? Platforminvokeisaservicethatenablesmanagedcodetocallunmanagedfunctions implementedindynamiclinklibraries(DLLs),suchasthoseintheWin32API.It locatesandinvokesanexportedfunctionandmarshalsitsarguments(integers,strings, arrays,structures,andsoon)acrosstheinteroperationboundaryasneeded. 11. IsittruethatCOMobjectsnolongerneedtoberegisteredontheserver? Answer:YesandNo.LegacyCOMobjectsstillneedtoberegisteredontheserver beforetheycanbeused.COMdevelopedusingthenew.NETFrameworkwillnotneed toberegistered.Developerswillbeabletoautoregistertheseobjectsjustbyplacing theminthe'bin'folderoftheapplication. 12. Can.NETFrameworkcomponentsusethefeaturesofComponentServices? Answer:Yes,youcanusethefeaturesandfunctionsofComponentServicesfroma .NETFrameworkcomponent. http://msdn.microsoft.com/library/techart/Pahlcompserv.htm (OOPS) 13. WhataretheOOPSconcepts? 1)Encapsulation:Itisthemechanismthatbindstogethercodeanddatain manipulates,andkeepsbothsafefromoutsideinterferenceandmisuse.Inshortit isolatesaparticularcodeanddatafromallothercodesanddata.Awelldefined interfacecontrolstheaccesstothatparticularcodeanddata. 2)Inheritance:Itistheprocessbywhichoneobjectacquiresthepropertiesofanother object.Thissupportsthehierarchicalclassification.Withouttheuseofhierarchies,each objectwouldneedtodefineallitscharacteristicsexplicitly.However,byuseof inheritance,anobjectneedonlydefinethosequalitiesthatmakeituniquewithinits class.Itcaninherititsgeneralattributesfromitsparent.Anewsubclassinheritsallof theattributesofallofitsancestors. 3)Polymorphism:Itisafeaturethatallowsoneinterfacetobeusedforgeneralclass ofactions.Thespecificactionisdeterminedbytheexactnatureofthesituation.In generalpolymorphismmeans"oneinterface,multiplemethods",Thismeansthatitis possibletodesignagenericinterfacetoagroupofrelatedactivities.Thishelpsreduce complexitybyallowingthesameinterfacetobeusedtospecifyageneralclassof action.Itisthecompiler'sjobtoselectthespecificaction(thatis,method)asitapplies toeachsituation. 14. WhatisthedifferencebetweenaStructandaClass? ThestructtypeissuitableforrepresentinglightweightobjectssuchasPoint, Rectangle,andColor.Althoughitispossibletorepresentapointasaclass,a structismoreefficientinsomescenarios.Forexample,ifyoudeclareanarray of1000Pointobjects,youwillallocateadditionalmemoryforreferencingeach object.Inthiscase,thestructislessexpensive. Whenyoucreateastructobjectusingthenewoperator,itgetscreatedandthe appropriateconstructoriscalled.Unlikeclasses,structscanbeinstantiated withoutusingthenewoperator.Ifyoudonotusenew,thefieldswillremain unassignedandtheobjectcannotbeuseduntilallofthefieldsareinitialized. Itisanerrortodeclareadefault(parameterless)constructorforastruct.A defaultconstructorisalwaysprovidedtoinitializethestructmemberstotheir defaultvalues. Itisanerrortoinitializeaninstancefieldinastruct. Thereisnoinheritanceforstructsasthereisforclasses.Astructcannotinherit fromanotherstructorclass,anditcannotbethebaseofaclass.Structs,

001 fo 42 egaP

however,inheritfromthebaseclassObject.Astructcanimplementinterfaces, anditdoesthatexactlyasclassesdo. Astructisavaluetype,whileaclassisareferencetype. 15. Valuetype&referencetypesdifference?Examplefrom.NET.Integer&struct arevaluetypesorreferencetypesin.NET? Mostprogramminglanguagesprovidebuiltindatatypes,suchasintegersandfloating pointnumbers,thatarecopiedwhentheyarepassedasarguments(thatis,theyare passedbyvalue).Inthe.NETFramework,thesearecalledvaluetypes.Theruntime supportstwokindsofvaluetypes: Builtinvaluetypes The.NETFrameworkdefinesbuiltinvaluetypes,suchasSystem.Int32and System.Boolean,whichcorrespondandareidenticaltoprimitivedatatypes usedbyprogramminglanguages. Userdefinedvaluetypes Yourlanguagewillprovidewaystodefineyourownvaluetypes,whichderive fromSystem.ValueType.Ifyouwanttodefineatyperepresentingavaluethat issmall,suchasacomplexnumber(usingtwofloatingpointnumbers),you mightchoosetodefineitasavaluetypebecauseyoucanpassthevaluetype efficientlybyvalue.Ifthetypeyouaredefiningwouldbemoreefficiently passedbyreference,youshoulddefineitasaclassinstead. Variablesofreferencetypes,referredtoasobjects,storereferencestotheactualdata. Thisfollowingarethereferencetypes: class interface delegate

Thisfollowingarethebuiltinreferencetypes: object string 16. WhatisInheritance,MultipleInheritance,SharedandRepeatable Inheritance? ** 17. WhatisMethodoverloading? Methodoverloadingoccurswhenaclasscontainstwomethodswiththesamename, butdifferentsignatures. 18. WhatisMethodOverriding?HowtooverrideafunctioninC#? Usetheoverridemodifiertomodifyamethod,aproperty,anindexer,oranevent.An overridemethodprovidesanewimplementationofamemberinheritedfromabase class.Themethodoverriddenbyanoverridedeclarationisknownastheoverridden basemethod.Theoverriddenbasemethodmusthavethesamesignatureasthe overridemethod. Youcannotoverrideanonvirtualorstaticmethod.Theoverriddenbasemethodmust bevirtual,abstract,oroverride. 19. Canwecallabaseclassmethodwithoutcreatinginstance? ItspossibleIfitsastaticmethod. Itspossiblebyinheritingfromthatclassalso. Itspossiblefromderivedclassesusingbasekeyword. 20. Youhaveonebaseclassvirtualfunctionhowwillcallthatfunctionfrom derivedclass? Ans: 21. classa 22. { 23. publicvirtualintm() 24. { 25. return1 26. }
001 fo 52 egaP

27. 28. 29. 30. 31. 32. 33. }

} classb:a { publicintj() { returnm() }

34. Inwhichcasesyouuseoverrideandnewbase? Usethenewmodifiertoexplicitlyhideamemberinheritedfromabaseclass.Tohide aninheritedmember,declareitinthederivedclassusingthesamename,andmodify itwiththenewmodifier. C#Languagefeatures 35. WhatareSealedClassesinC#? Thesealedmodifierisusedtopreventderivationfromaclass.Acompiletimeerror occursifasealedclassisspecifiedasthebaseclassofanotherclass.(Asealedclass cannotalsobeanabstractclass) 36. WhatisPolymorphism?HowdoesVB.NET/C#achievepolymorphism? ** 37. classToken 38. { 39. publicstringDisplay() 40. { 41. //Implementationgoeshere 42. return"base" 43. } 44. } 45. classIdentifierToken:Token 46. { 47. publicnewstringDisplay()//Whatistheuseofnewkeyword 48. { 49. //Implementationgoeshere 50. return"derive" 51. } 52. } 53. staticvoidMethod(Tokent) 54. { 55. Console.Write(t.Display()) 56. } 57. publicstaticvoidMain() 58. { 59. IdentifierTokenVariable=newIdentifierToken() 60. Method(Variable)//WhichClassMethodiscalledhere 61. Console.ReadLine() 62. } 63. FortheabovecodeWhatisthe"new"keywordandWhichClassMethodis 64. calledhere A:itwillcallbaseclassDisplaymethod 65. classToken 66. { 67. 68. 69. 70.

publicvirtualstringDisplay() { //Implementationgoeshere return"base"


001 fo 62 egaP

71. } 72. } 73. classIdentifierToken:Token 74. { 75. publicoverridestringDisplay()//Whatistheuseofnewkeyword 76. { 77. //Implementationgoeshere 78. return"derive" 79. } 80. } 81. staticvoidMethod(Tokent) 82. { 83. Console.Write(t.Display()) 84. } 85. publicstaticvoidMain() 86. { 87. IdentifierTokenVariable=newIdentifierToken() 88. Method(Variable)//WhichClassMethodiscalledhere 89. Console.ReadLine() 90. } 91. A:Derive 92. InwhichScenarioyouwillgoforInterfaceorAbstractClass? Interfaces,likeclasses,defineasetofproperties,methods,andevents.Butunlike classes,interfacesdonotprovideimplementation.Theyareimplementedbyclasses, anddefinedasseparateentitiesfromclasses.Eventhoughclassinheritanceallows yourclassestoinheritimplementationfromabaseclass,italsoforcesyoutomake mostofyourdesigndecisionswhentheclassisfirstpublished. Abstractclassesareusefulwhencreatingcomponentsbecausetheyallowyouspecify aninvariantleveloffunctionalityinsomemethods,butleavetheimplementationof othermethodsuntilaspecificimplementationofthatclassisneeded.Theyalsoversion well,becauseifadditionalfunctionalityisneededinderivedclasses,itcanbeaddedto thebaseclasswithoutbreakingcode. Interfacesvs.AbstractClasses Feature Interface Abstractclass Multiple Aclassmayimplement Aclassmayextendonlyone inheritance severalinterfaces. abstractclass. Anabstractclasscanprovide Aninterfacecannot Default completecode,defaultcode, provideanycodeatall, implementation and/orjuststubsthathaveto muchlessdefaultcode. beoverridden. Staticfinalconstantsonly, canusethemwithout qualificationinclassesthat implementtheinterface. Bothinstanceandstatic Ontheotherpaw,these constantsarepossible.Both Constants unqualifiednamespollute staticandinstanceintialiser thenamespace.Youcan codearealsopossibleto usethemanditisnot computetheconstants. obviouswheretheyare comingfromsincethe qualificationisoptional. Aninterface Athirdpartyclassmustbe Thirdparty implementationmaybe rewrittentoextendonlyfrom convenience addedtoanyexistingthird theabstractclass. partyclass. Interfacesareoftenused Anabstractclassdefinesthe isavsableor todescribetheperipheral coreidentityofitsdescendants. cando abilitiesofaclass,notits IfyoudefinedaDogabstract
001 fo 72 egaP

classthenDamamation descendantsareDogs,theyare notmerelydogable. Implementedinterfaces enumeratethegeneralthingsa classcando,notthethingsa classis. Youmustusetheabstractclass asisforthecodebase,withall itsattendantbaggage,goodor bad.Theabstractclassauthor Youcanwriteanew hasimposedstructureonyou. replacementmoduleforan Dependingontheclevernessof interfacethatcontainsnot theauthoroftheabstractclass, onestickofcodein thismaybegoodorbad. commonwiththeexisting Anotherissuethat'simportantis implementations.When whatIcall"heterogeneousvs. youimplementthe homogeneous."If interface,youstartfrom implementors/subclassesare scratchwithoutany Plugin homogeneous,tendtowardsan defaultimplementation. abstractbaseclass.Iftheyare Youhavetoobtainyour heterogeneous,useaninterface. toolsfromotherclasses (NowallIhavetodoiscomeup nothingcomeswiththe withagooddefinitionof interfaceotherthanafew hetero/homogeneousinthis constants.Thisgivesyou context.)Ifthevariousobjects freedomtoimplementa areallofakind,andsharea radicallydifferentinternal commonstateandbehavior, design. thentendtowardsacommon baseclass.Ifalltheyshareisa setofmethodsignatures,then tendtowardsaninterface. Ifallthevarious Ifthevariousimplementations implementationsshareis areallofakindandsharea Homogeneity themethodsignatures, commonstatusandbehavior, thenaninterfaceworks usuallyanabstractclassworks best. best. Ifyourclientcodetalks Justlikeaninterface,ifyour onlyintermsofan clientcodetalksonlyintermsof interface,youcaneasily anabstractclass,youcaneasily Maintenance changetheconcrete changetheconcrete implementationbehindit, implementationbehindit,using usingafactorymethod. afactorymethod. Slow,requiresextra indirectiontofindthe correspondingmethodin Speed theactualclass.Modern Fast JVMsarediscoveringways toreducethisspeed penalty. Theconstantdeclarations Youcanputsharedcodeintoan inaninterfaceareall abstractclass,whereyoucannot presumedpublicstatic intoaninterface.Ifinterfaces final,soyoumayleave wanttosharecode,youwill Terseness thatpartout.Youcan't havetowriteotherbubblegum callanymethodsto toarrangethat.Youmayuse computetheinitialvalues methodstocomputetheinitial ofyourconstants.You valuesofyourconstantsand neednotdeclareindividualvariables,bothinstanceand
001 fo 82 egaP

centralidentity,e.g.an Automobileclassmight implementtheRecyclable interface,whichcould applytomanyotherwise totallyunrelatedobjects.

methodsofaninterface abstract.Theyareall presumedso. Ifyouaddanewmethod toaninterface,youmust trackdownall Adding implementationsofthat functionality interfaceintheuniverse andprovidethemwitha concreteimplementation ofthatmethod.

static.Youmustdeclareallthe individualmethodsofan abstractclassabstract. Ifyouaddanewmethodtoan abstractclass,youhavethe optionofprovidingadefault implementationofit.Thenall existingcodewillcontinueto workwithoutchange.

93. seethecode 94. interfaceICommon 95. { 96. intgetCommon() 97. } 98. interfaceICommonImplements1:ICommon 99. { 100. } 101. interfaceICommonImplements2:ICommon 102. { 103. } 104. publicclassa:ICommonImplements1,ICommonImplements2 105. { } HowtoimplementgetCommonmethodinclassa?Areyouseeinganyprobleminthe implementation? Ans: publicclassa:ICommonImplements1,ICommonImplements2 { publicintgetCommon() { return1 } } 106. interfaceIWeather 107. { 108. voiddisplay() 109. } 110. publicclassA:IWeather 111. { 112. publicvoiddisplay() 113. { 114. MessageBox.Show("A") 115. } 116. } 117. publicclassB:A 118. { 119. } 120. publicclassC:B,IWeather 121. { 122. publicvoiddisplay() 123. { 124. MessageBox.Show("C") 125. } 126. }
001 fo 92 egaP

127. WhenIinstantiateC.display(),willitwork? 128. interfaceIPrint 129. { 130. stringDisplay() 131. } 132. interfaceIWrite 133. { 134. stringDisplay() 135. } 136. classPrintDoc:IPrint,IWrite 137. { 138. //Hereisimplementation 139. } howtoimplementtheDisplayintheclassprintDoc(Howtoresolvethenaming Conflict)A:nonamingconflicts classPrintDoc:IPrint,IWrite { publicstringDisplay() { return"s" } } 140. interfaceIList 141. { 142. intCount{getset} 143. } 144. interfaceICounter 145. { 146. voidCount(inti) 147. } 148. interfaceIListCounter:IList,ICounter{} 149. classC 150. { 151. voidTest(IListCounterx) 152. { 153. x.Count(1) //Error 154. x.Count=1 //Error 155. ((IList)x).Count=1 //Ok,invokesIList.Count.set 156. ((ICounter)x).Count(1) //Ok,invokesICounter.Count 157. } 158. } 159. Writeonecodeexampleforcompiletimebindingandoneforruntime binding?Whatisearly/latebinding? Anobjectisearlyboundwhenitisassignedtoavariabledeclaredtobeofaspecific objecttype.Earlyboundobjectsallowthecompilertoallocatememoryandperform otheroptimizationsbeforeanapplicationexecutes. 'Createavariabletoholdanewobject. DimFSAsFileStream 'Assignanewobjecttothevariable. FS=NewFileStream("C:\tmp.txt",FileMode.Open) Bycontrast,anobjectislateboundwhenitisassignedtoavariabledeclaredtobeof typeObject.Objectsofthistypecanholdreferencestoanyobject,butlackmanyof theadvantagesofearlyboundobjects. DimxlAppAsObject xlApp=CreateObject("Excel.Application") 160. Canyouexplainwhatinheritanceisandanexampleofwhenyoumight useit?
001 fo 03 egaP

161. Howcanyouwriteaclasstorestrictthatonlyoneobjectofthisclass canbecreated(Singletonclass)? (Accessspecifiers) 162. Whataretheaccessspecifiersavailableinc#? Private,Protected,Public,Internal,ProtectedInternal. 163. ExplainaboutProtectedandprotectedinternal,internalaccess specifier? protectedAccessislimitedtothecontainingclassortypesderivedfromthe containingclass. internalAccessislimitedtothecurrentassembly. protectedinternalAccessislimitedtothecurrentassemblyortypesderivedfromthe containingclass. (Constructor/Destructor) 164. Differencebetweentypeconstructorandinstanceconstructor?Whatis staticconstructor,whenitwillbefired?Andwhatisitsuse? (Classconstructormethodisalsoknownastypeconstructorortypeinitializer) Instanceconstructorisexecutedwhenanewinstanceoftypeiscreatedandtheclass constructorisexecutedafterthetypeisloadedandbeforeanyoneofthetype membersisaccessed.(Itwillgetexecutedonly1sttime,whenwecallanystatic methods/fieldsinthesameclass.)Classconstructorsareusedforstaticfield initialization.Onlyoneclassconstructorpertypeispermitted,anditcannotusethe vararg(variableargument)callingconvention. Astaticconstructorisusedtoinitializeaclass.Itiscalledautomaticallytoinitializethe classbeforethefirstinstanceiscreatedoranystaticmembersarereferenced. 165. WhatisPrivateConstructor?anditsuse?Canyoucreateinstanceofa classwhichhasPrivateConstructor? A:Whenaclassdeclaresonlyprivateinstanceconstructors,itisnotpossiblefor classesoutsidetheprogramtoderivefromtheclassortodirectlycreateinstancesof it.(ExceptNestedclasses) Makeaconstructorprivateif: Youwantittobeavailableonlytotheclassitself.Forexample,youmighthavea specialconstructorusedonlyintheimplementationofyourclass'Clonemethod. Youdonotwantinstancesofyourcomponenttobecreated.Forexample,youmay haveaclasscontainingnothingbutSharedutilityfunctions,andnoinstancedata. Creatinginstancesoftheclasswouldwastememory. 166. Ihave3overloadedconstructorsinmyclass.Inordertoavoidmaking instanceoftheclassdoIneedtomakeallconstructorstoprivate? (yes) 167. Overloadedconstructorwillcalldefaultconstructorinternally? (no) 168. Whatarevirtualdestructors? 169. Destructorandfinalize GenerallyinC++thedestructoriscalledwhenobjectsgetsdestroyed.Andonecan explicitlycallthedestructorsinC++.Andalsotheobjectsaredestroyedinreverse orderthattheyarecreatedin.SoinC++youhavecontroloverthedestructors. InC#youcannevercallthem,thereasonisonecannotdestroyanobject.Sowhohas thecontroloverthedestructor(inC#)?it'sthe.NetframeworksGarbageCollector (GC).GCdestroystheobjectsonlywhennecessary.Somesituationsofnecessityare memoryisexhaustedoruserexplicitlycallsSystem.GC.Collect()method. Pointstoremember: 1.Destructorsareinvokedautomatically,andcannotbeinvokedexplicitly. 2.Destructorscannotbeoverloaded.Thus,aclasscanhave,atmost,onedestructor. 3.Destructorsarenotinherited.Thus,aclasshasnodestructorsotherthantheone, whichmaybedeclaredinit. 4.Destructorscannotbeusedwithstructs.Theyareonlyusedwithclasses. 5.Aninstancebecomeseligiblefordestructionwhenitisnolongerpossibleforany
001 fo 13 egaP

codetousetheinstance. 6.Executionofthedestructorfortheinstancemayoccuratanytimeaftertheinstance becomeseligiblefordestruction. 7.Whenaninstanceisdestructed,thedestructorsinitsinheritancechainarecalled,in order,frommostderivedtoleastderived. http://msdn.microsoft.com/library/default.asp?url=/library/en us/cpguide/html/cpconfinalizemethodscdestructors.asp 170. WhatisthedifferencebetweenFinalizeandDispose(Garbage collection) Classinstancesoftenencapsulatecontroloverresourcesthatarenotmanagedbythe runtime,suchaswindowhandles(HWND),databaseconnections,andsoon. Therefore,youshouldprovidebothanexplicitandanimplicitwaytofreethose resources.ProvideimplicitcontrolbyimplementingtheprotectedFinalizeMethodonan object(destructorsyntaxinC#andtheManagedExtensionsforC++).Thegarbage collectorcallsthismethodatsomepointaftertherearenolongeranyvalidreferences totheobject. Insomecases,youmightwanttoprovideprogrammersusinganobjectwiththeability toexplicitlyreleasetheseexternalresourcesbeforethegarbagecollectorfreesthe object.Ifanexternalresourceisscarceorexpensive,betterperformancecanbe achievediftheprogrammerexplicitlyreleasesresourceswhentheyarenolongerbeing used.Toprovideexplicitcontrol,implementtheDisposemethodprovidedbythe IDisposableInterface.Theconsumeroftheobjectshouldcallthismethodwhenitis doneusingtheobject.Disposecanbecalledevenifotherreferencestotheobjectare alive. NotethatevenwhenyouprovideexplicitcontrolbywayofDispose,youshould provideimplicitcleanupusingtheFinalizemethod.Finalizeprovidesabackupto preventresourcesfrompermanentlyleakingiftheprogrammerfailstocallDispose. 171. Whatisclosemethod?HowitsdifferentfromFinalize&Dispose? ** 172. Whatisboxing&unboxing? 173. Whatischeck/uncheck? 174. Whatistheuseofbasekeyword?Tellmeapracticalexampleforbase keywordsusage? 175. Whatarethedifferent.nettoolswhichuusedinprojects? 176. try { ... } catch { ...//exceptionoccurredhere.What'llhappen? } finally { .. } Ans:Itwillthrowexception. 177. Whatwilldotoavoidpriorcase? Ans: 178. try 179. { 180. try 181. { 182. ... 183. } 184. catch 185. { 186. ... 187. //exceptionoccurredhere.

001 fo 23 egaP

188. } 189. finally 190. { 191. ... 192. } 193. } 194. catch 195. { 196. ... 197. } 198. finally 199. { 200. ... } 201. try 202. { 203. ... 204. } 205. catch 206. { 207. ... 208. } 209. finally 210. { 211. .. 212. } 213. Willitgotofinallyblockifthereisnoexceptionhappened? Ans:Yes.Thefinallyblockisusefulforcleaningupanyresourcesallocatedinthetry block.Controlisalwayspassedtothefinallyblockregardlessofhowthetryblock exits. 214. IsgotostatementsupportedinC#?HowaboutJava? GotosaresupportedinC#tothefullest.InJavagotoisareservedkeywordthat providesabsolutelynofunctionality. 215. WhatsdifferentaboutswitchstatementsinC#? Nofallthroughsallowed.UnliketheC++switchstatement,C#doesnotsupportan explicitfallthroughfromonecaselabeltoanother.Ifyouwant,youcanusegotoa switchcase,orgotodefault. case1: cost+=25 break case2: cost+=25 gotocase1 (ADO.NET) 216. AdvantageofADO.Net? ADO.NETDoesNotDependOnContinuouslyLiveConnections DatabaseInteractionsArePerformedUsingDataCommands DataCanBeCachedinDatasets DatasetsAreIndependentofDataSources DataIsPersistedasXML SchemasDefineDataStructures 217. Howwoulduconnecttodatabaseusing.NET? SqlConnectionnwindConn=newSqlConnection("DataSource=localhostIntegrated Security=SSPI"+ "InitialCatalog=northwind") nwindConn.Open() 218. Whatarerelationobjectsindatasetandhow&wheretousethem? InaDataSetthatcontainsmultipleDataTableobjects,youcanuseDataRelation

001 fo 33 egaP

objectstorelateonetabletoanother,tonavigatethroughthetables,andtoreturn childorparentrowsfromarelatedtable. AddingaDataRelationtoaDataSetadds, bydefault,aUniqueConstrainttotheparenttableandaForeignKeyConstraintto thechildtable. ThefollowingcodeexamplecreatesaDataRelationusingtwoDataTableobjectsina DataSet.EachDataTablecontainsacolumnnamedCustID,whichservesasalink betweenthetwoDataTableobjects.TheexampleaddsasingleDataRelationtothe RelationscollectionoftheDataSet.Thefirstargumentintheexamplespecifiesthe nameoftheDataRelationbeingcreated.Thesecondargumentsetstheparent DataColumnandthethirdargumentsetsthechildDataColumn. custDS.Relations.Add("CustOrders", custDS.Tables["Customers"].Columns["CustID"], custDS.Tables["Orders"].Columns["CustID"]) OR privatevoidCreateRelation() { //GettheDataColumnobjectsfromtwoDataTableobjectsinaDataSet. DataColumnparentCol DataColumnchildCol //CodetogettheDataSetnotshownhere. parentCol=DataSet1.Tables["Customers"].Columns["CustID"] childCol=DataSet1.Tables["Orders"].Columns["CustID"] //CreateDataRelation. DataRelationrelCustOrder relCustOrder=newDataRelation("CustomersOrders",parentCol,childCol) //AddtherelationtotheDataSet. DataSet1.Relations.Add(relCustOrder) } 219. DifferencebetweenOLEDBProviderandSqlClient? Ans:SQLClient.NETclassesarehighlyoptimizedforthe.net/sqlservercombination andachieveoptimalresults.TheSqlClientdataproviderisfast.It'sfasterthanthe Oracleprovider,andfasterthanaccessingdatabaseviatheOleDblayer.It'sfaster becauseitaccessesthenativelibrary(whichautomaticallygivesyoubetter performance),anditwaswrittenwithlotsofhelpfromtheSQLServerteam. 220. Whatarethedifferentnamespacesusedintheprojecttoconnectthe database?Whatdataprovidersavailablein.nettoconnecttodatabase? System.Data.OleDbclassesthatmakeupthe.NETFrameworkDataProvider forOLEDBcompatibledatasources.Theseclassesallowyoutoconnecttoan OLEDBdatasource,executecommandsagainstthesource,andreadthe results. System.Data.SqlClientclassesthatmakeupthe.NETFrameworkData ProviderforSQLServer,whichallowsyoutoconnecttoSQLServer7.0,execute commands,andreadresults.TheSystem.Data.SqlClientnamespaceissimilar totheSystem.Data.OleDbnamespace,butisoptimizedforaccesstoSQL Server7.0andlater. System.Data.Odbcclassesthatmakeupthe.NETFrameworkDataProviderfor ODBC.TheseclassesallowyoutoaccessODBCdatasourceinthemanaged space. System.Data.OracleClientclassesthatmakeupthe.NETFrameworkData ProviderforOracle.TheseclassesallowyoutoaccessanOracledatasourcein themanagedspace. 221. DifferencebetweenDataReaderandDataAdapter/DataSetand DataAdapter? YoucanusetheADO.NETDataReadertoretrieveareadonly,forwardonlystreamof datafromadatabase.UsingtheDataReadercanincreaseapplicationperformanceand reducesystemoverheadbecauseonlyonerowatatimeiseverinmemory. AftercreatinganinstanceoftheCommandobject,youcreateaDataReaderby

001 fo 43 egaP

callingCommand.ExecuteReadertoretrieverowsfromadatasource,asshownin thefollowingexample. SqlDataReadermyReader=myCommand.ExecuteReader() YouusetheReadmethodoftheDataReaderobjecttoobtainarowfromtheresults ofthequery. while(myReader.Read()) Console.WriteLine("\t{0}\t{1}",myReader.GetInt32(0),myReader.GetString(1)) myReader.Close() TheDataSetisamemoryresidentrepresentationofdatathatprovidesaconsistent relationalprogrammingmodelregardlessofthedatasource.Itcanbeusedwith multipleanddifferingdatasources,usedwithXMLdata,orusedtomanagedatalocal totheapplication.TheDataSetrepresentsacompletesetofdataincludingrelated tables,constraints,andrelationshipsamongthetables.Themethodsandobjectsina DataSetareconsistentwiththoseintherelationaldatabasemodel.TheDataSetcan alsopersistandreloaditscontentsasXMLanditsschemaasXMLSchemadefinition language(XSD)schema. TheDataAdapterservesasabridgebetweenaDataSetandadatasourceforretrieving andsavingdata.TheDataAdapterprovidesthisbridgebymappingFill,whichchanges thedataintheDataSettomatchthedatainthedatasource,andUpdate,which changesthedatainthedatasourcetomatchthedataintheDataSet.Ifyouare connectingtoaMicrosoftSQLServerdatabase,youcanincreaseoverallperformance byusingtheSqlDataAdapteralongwithitsassociatedSqlCommandandSqlConnection. ForotherOLEDBsupporteddatabases,usetheDataAdapterwithitsassociated OleDbCommandandOleDbConnectionobjects. 222. WhichmethoddoyouinvokeontheDataAdaptercontroltoloadyour generateddatasetwithdata? Fill() 223. ExplaindifferentmethodsandPropertiesofDataReaderwhichyouhave usedinyourproject? Read GetString GetInt32 while(myReader.Read()) Console.WriteLine("\t{0}\t{1}",myReader.GetInt32(0),myReader.GetString(1)) myReader.Close() 224. WhathappenswhenweissueDataset.ReadXmlcommand? ReadsXMLschemaanddataintotheDataSet. 225. Inhowmanywayswecanretrievetablerecordscount?Howtofindthe countofrecordsinadataset? foreach(DataTablethisTableinmyDataSet.Tables){ //Foreachrow,printthevaluesofeachcolumn. foreach(DataRowmyRowinthisTable.Rows){ 226. Howtocheckifadatareaderisclosedoropened? IsClosed() 227. Whathappenswhenutrytoupdatedatainadatasetin.NETwhilethe recordisalreadydeletedinSQLSERVERasbackend? ORWhatisconcurrency?Howwillyouavoidconcurrencywhendealingwith dataset?(Oneuserdeletedonerowafterthatanotheruserthroughhis datasetwastryingtoupdatesamerow.Whatwillhappen?Howwillyouavoid theproblem?) ** 228. Howdoyoumerge2datasetsintothethirddatasetinasimplemanner? ORIfyouareexecutingthesestatementsincommandObject."Select*from Table1Select*fromTable2howyouwilldealresultset? ** 229. Howdoyousortadataset? **

001 fo 53 egaP

230. Ifadatasetcontains100rows,howtofetchrowsbetween5and15 only? ** 231. Differencesbetweendataset.cloneanddataset.copy? CloneCopiesthestructureoftheDataSet,includingallDataTableschemas,relations, andconstraints.Doesnotcopyanydata. CopyCopiesboththestructureanddataforthisDataSet. 232. Whatistheuseofparameterobject? ** 233. HowtogenerateXMLfromadatasetandviceversa? ** 234. WhatismethodtogetXMLandschemafromDataset? ans:getXML()andgetSchema() 235. Howdouimplementlockingconceptfordataset? ** (ASP.NET) 236. Asp.netandaspdifferences? CodeRenderBlock CodeDeclarationBlock Compiled Request/Response EventDriven ObjectOriented Constructors/Destructors, Inheritance,overloading.. ExceptionHandlingTry,Catch, Finally DownlevelSupport Cultures UserControls Inbuiltclientsidevalidation Itcanspanacrossservers,Itcan Sessionweren'ttransferableacross surviveservercrashes,canworkwith servers browsersthatdon'tsupportcookies itsanintegralpartofOSunderthe .netframework.Itsharesmanyof builtontopofthewindow&IIS,it thesameobjectsthattraditional wasalwaysaseparateentity&its applicationswoulduse,andall.net functionalitywaslimited. objectsareavailableforasp.net's consumption. GarbageCollection Declarevariablewithdatatype Inbuiltgraphicssupport Cultures

237. HowASPandASP.NETpageworks?Explainaboutasp.netpagelife cycle? ** 238. Orderofeventsinanasp.netpage?ControlExecutionLifecycle? Phase Initialize Whatacontrolneedstodo Methodoreventtooverride

InitializesettingsneededduringtheInitevent(OnInitmethod) lifetimeoftheincomingWeb request. Attheendofthisphase,the LoadViewStatemethod ViewStatepropertyofacontrolis


001 fo 63 egaP

Loadview state

automaticallypopulatedas describedinMaintainingStateina Control.Acontrolcanoverridethe defaultimplementationofthe LoadViewStatemethodto customizestaterestoration. Process Processincomingformdataand postbackdata updatepropertiesaccordingly. Load LoadPostDatamethod(if IPostBackDataHandleris implemented)

Performactionscommontoall Loadevent requests,suchassettingupa databasequery.Atthispoint, (OnLoadmethod) servercontrolsinthetreeare createdandinitialized,thestateis restored,andformcontrolsreflect clientsidedata.

Sendpostback Raisechangeeventsinresponseto RaisePostDataChangedEvent change statechangesbetweenthecurrent method(if notifications andpreviouspostbacks. IPostBackDataHandleris implemented) Handle postback events Prerender Handletheclientsideeventthat causedthepostbackandraise appropriateeventsontheserver. RaisePostBackEventmethod(if IPostBackEventHandleris implemented)

Performanyupdatesbeforethe PreRenderevent outputisrendered.Anychanges (OnPreRendermethod) madetothestateofthecontrolin theprerenderphasecanbesaved, whilechangesmadeinthe renderingphasearelost. TheViewStatepropertyofa SaveViewStatemethod controlisautomaticallypersistedto astringobjectafterthisstage.This stringobjectissenttotheclient andbackasahiddenvariable.For improvingefficiency,acontrolcan overridetheSaveViewState methodtomodifytheViewState property. Generateoutputtoberenderedto Rendermethod theclient. Performanyfinalcleanupbefore Disposemethod thecontrolistorndown. Referencestoexpensiveresources suchasdatabaseconnectionsmust bereleasedinthisphase. Performanyfinalcleanupbefore UnLoadevent(OnUnLoad thecontrolistorndown.Control method) authorsgenerallyperformcleanup inDisposeanddonothandlethis event.

Savestate

Render Dispose

Unload

239. Note TooverrideanEventNameevent,overridetheOnEventNamemethod (andcallbase.OnEventName). 240. Whatareservercontrols? ASP.NETservercontrolsarecomponentsthatrunontheserverandencapsulateuser


001 fo 73 egaP

interfaceandotherrelatedfunctionality.TheyareusedinASP.NETpagesandin ASP.NETcodebehindclasses. 241. WhatisthedifferencebetweenWebUserControlandWebCustom Control? CustomControls Webcustomcontrolsarecompiledcomponentsthatrunontheserverandthat encapsulateuserinterfaceandotherrelatedfunctionalityintoreusablepackages.They canincludeallthedesigntimefeaturesofstandardASP.NETservercontrols,including fullsupportforVisualStudiodesignfeaturessuchasthePropertieswindow,thevisual designer,andtheToolbox. ThereareseveralwaysthatyoucancreateWebcustomcontrols: Youcancompileacontrolthatcombinesthefunctionalityoftwoormore existingcontrols.Forexample,ifyouneedacontrolthatencapsulatesabutton andatextbox,youcancreateitbycompilingtheexistingcontrolstogether. Ifanexistingservercontrolalmostmeetsyourrequirementsbutlackssome requiredfeatures,youcancustomizethecontrolbyderivingfromitand overridingitsproperties,methods,andevents. IfnoneoftheexistingWebservercontrols(ortheircombinations)meetyour requirements,youcancreateacustomcontrolbyderivingfromoneofthebase controlclasses.TheseclassesprovideallthebasicfunctionalityofWebserver controls,soyoucanfocusonprogrammingthefeaturesyouneed. IfnoneoftheexistingASP.NETservercontrolsmeetthespecificrequirementsofyour applications,youcancreateeitheraWebusercontroloraWebcustomcontrolthat encapsulatesthefunctionalityyouneed.Themaindifferencebetweenthetwocontrols liesineaseofcreationvs.easeofuseatdesigntime. Webusercontrolsareeasytomake,buttheycanbelessconvenienttousein advancedscenarios.YoudevelopWebusercontrolsalmostexactlythesamewaythat youdevelopWebFormspages.LikeWebForms,usercontrolscanbecreatedinthe visualdesigner,theycanbewrittenwithcodeseparatedfromtheHTML,andtheycan handleexecutionevents.However,becauseWebusercontrolsarecompiled dynamicallyatruntimetheycannotbeaddedtotheToolbox,andtheyarerepresented byasimpleplaceholderglyphwhenaddedtoapage.ThismakesWebusercontrols hardertouseifyouareaccustomedtofullVisualStudio.NETdesigntimesupport, includingthePropertieswindowandDesignviewpreviews.Also,theonlywaytoshare theusercontrolbetweenapplicationsistoputaseparatecopyineachapplication, whichtakesmoremaintenanceifyoumakechangestothecontrol. Webcustomcontrolsarecompiledcode,whichmakesthemeasiertousebutmore difficulttocreateWebcustomcontrolsmustbeauthoredincode.Onceyouhave createdthecontrol,however,youcanaddittotheToolboxanddisplayitinavisual designerwithfullPropertieswindowsupportandalltheotherdesigntimefeaturesof ASP.NETservercontrols.Inaddition,youcaninstallasinglecopyoftheWebcustom controlintheglobalassemblycacheandshareitbetweenapplications,whichmakes maintenanceeasier. Webusercontrols Webcustomcontrols Easiertocreate Hardertocreate Limitedsupportforconsumerswhousea Fullvisualdesigntoolsupportforconsumers visualdesigntool Aseparatecopyofthecontrolisrequired Onlyasinglecopyofthecontrolisrequired, ineachapplication intheglobalassemblycache CannotbeaddedtotheToolboxinVisual CanbeaddedtotheToolboxinVisualStudio Studio Goodforstaticlayout Goodfordynamiclayout

(Session/State)

001 fo 83 egaP

242. ApplicationandSessionEvents TheASP.NETpageframeworkprovideswaysforyoutoworkwitheventsthatcanbe raisedwhenyourapplicationstartsorstopsorwhenanindividualuser'ssessionstarts orstops: Applicationeventsareraisedforallrequeststoanapplication.Forexample, Application_BeginRequestisraisedwhenanyWebFormspageorXMLWeb serviceinyourapplicationisrequested.Thiseventallowsyoutoinitialize resourcesthatwillbeusedforeachrequesttotheapplication.Acorresponding event,Application_EndRequest,providesyouwithanopportunitytocloseor otherwisedisposeofresourcesusedfortherequest. Sessioneventsaresimilartoapplicationevents(thereisaSession_OnStart andaSession_OnEndevent),butareraisedwitheachuniquesessionwithin theapplication.Asessionbeginswhenauserrequestsapageforthefirsttime fromyourapplicationandendseitherwhenyourapplicationexplicitlyclosesthe sessionorwhenthesessiontimesout. YoucancreatehandlersforthesetypesofeventsintheGlobal.asaxfile. 243. DifferencebetweenASPSessionandASP.NETSession? asp.netsessionsupportscookielesssession&itcanspanacrossmultipleservers. 244. Whatiscookielesssession?Howitworks? Bydefault,ASP.NETwillstorethesessionstateinthesameprocessthatprocessesthe request,justasASPdoes.Ifcookiesarenotavailable,asessioncanbetrackedby addingasessionidentifiertotheURL.Thiscanbeenabledbysettingthefollowing: <sessionStatecookieless="true"/> http://samples.gotdotnet.com/quickstart/aspplus/doc/stateoverview.aspx 245. Howyouwillhandlesessionwhendeployingapplicationinmorethana server?Describesessionhandlinginawebfarm,howdoesitworkandwhat arethelimits? Bydefault,ASP.NETwillstorethesessionstateinthesameprocessthatprocessesthe request,justasASPdoes.Additionally,ASP.NETcanstoresessiondatainanexternal process,whichcanevenresideonanothermachine.Toenablethisfeature: StarttheASP.NETstateservice,eitherusingtheServicessnapinorby executing"netstartaspnet_state"onthecommandline.Thestateservicewill bydefaultlistenonport42424.Tochangetheport,modifytheregistrykeyfor theservice: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\aspnet_state\Para meters\Port Setthemodeattributeofthe<sessionState>sectionto"StateServer". ConfigurethestateConnectionStringattributewiththevaluesofthemachine onwhichyoustartedaspnet_state. Thefollowingsampleassumesthatthestateserviceisrunningonthesamemachineas theWebserver("localhost")andusesthedefaultport(42424): <sessionStatemode="StateServer"stateConnectionString="tcpip=localhost:42424"/> Notethatifyoutrythesampleabovewiththissetting,youcanresettheWebserver (enteriisresetonthecommandline)andthesessionstatevaluewillpersist. ** 246. Whatmethoddoyouusetoexplicitlykillauserssession? Abandon() 247. Whatarethedifferentwaysyouwouldconsidersendingdataacross pagesinASP(i.ebetween1.aspto2.asp)? Session publicproperties 248. WhatisStateManagementin.Netandhowmanywaysarethereto maintainastatein.Net?Whatisviewstate? Webpagesarerecreatedeachtimethepageispostedtotheserver.IntraditionalWeb
001 fo 93 egaP

programming,thiswouldordinarilymeanthatallinformationassociatedwiththepage andthecontrolsonthepagewouldbelostwitheachroundtrip. ToovercomethisinherentlimitationoftraditionalWebprogramming,theASP.NET pageframeworkincludesvariousoptionstohelpyoupreservechangesthatis,for managingstate.Thepageframeworkincludesafacilitycalledviewstatethat automaticallypreservespropertyvaluesofthepageandallthecontrolsonitbetween roundtrips. However,youwillprobablyalsohaveapplicationspecificvaluesthatyouwantto preserve.Todoso,youcanuseoneofthestatemanagementoptions. ClientBasedStateManagementOptions: ViewState HiddenFormFields Cookies QueryStrings ServerBasedStateManagementOptions ApplicationState SessionState DatabaseSupport 249. Whatarethedisadvantagesofviewstate/whatarethebenefits? Automaticviewstatemanagementisafeatureofservercontrolsthatenablesthemto repopulatetheirpropertyvaluesonaroundtrip(withoutyouhavingtowriteany code).Thisfeaturedoesimpactperformance,however,sinceaservercontrol'sview stateispassedtoandfromtheserverinahiddenformfield.Youshouldbeawareof whenviewstatehelpsyouandwhenithindersyourpage'sperformance. 250. WhenmaintainingsessionthroughSqlserver,whatistheimpactof ReadandWriteoperationonSessionobjects?willperformancedegrade? Maintainingstateusingdatabasetechnologyisacommonpracticewhenstoringuser specificinformationwheretheinformationstoreislarge.Databasestorageis particularlyusefulformaintaininglongtermstateorstatethatmustbepreservedeven iftheservermustberestarted. ** 251. Whatarethecontentsofcookie? ** 252. Howdoyoucreateapermanentcookie? ** 253. WhatisViewState?Whatdoesthe"EnableViewState"propertydo?Why wouldIwantitonoroff? ** 254. ExplainthedifferencesbetweenServersideandClientsidecode? Serversidecodewillprocessatserverside&itwillsendtheresulttoclient.Clientside code(javascript)willexecuteonlyatclientside. 255. Canyougiveanexampleofwhatmightbebestsuitedtoplaceinthe Application_StartandSession_Startsubroutines? **

256. WhichASP.NETconfigurationoptionsaresupportedinthe ASP.NETimplementationonthesharedwebhostingplatform? A: ManyoftheASP.NETconfigurationoptionsarenotconfigurableat thesite,applicationorsubdirectorylevelonthesharedhosting platform. Certainoptionscanaffectthesecurity,performanceand stabilityoftheserverand,thereforecannotbechanged. Thefollowing settingsaretheonlyonesthatcanbechangedinyoursitesweb.config file(s): browserCaps clientTarget pages customErrors globalization
001 fo 04 egaP

authorization authentication webControls webServices http://msdn.microsoft.com/library/default.asp?url=/library/en us/cpguide/html/cpconaspnetconfiguration.asp


257. Brieflydescribetheroleofglobal.asax? 258. Howcanudebugyour.netapplication? 259. Howdoudeployyourasp.netapplication? 260. Wheredowestoreourconnectionstringinasp.netapplication? 261. Variousstepstakentooptimizeawebbasedapplication(caching, storedprocedureetc.) 262. HowdoesASP.NETframeworkmapsclientsideeventstoServerside events. (Security) 263. SecuritytypesinASP/ASP.NET?DifferentAuthenticationmodes? 264. How.Nethasimplementedsecurityforwebapplications? 265. HowtodoFormsauthenticationinasp.net? 266. Explainauthenticationlevelsin.net? 267. Explainautherizationlevelsin.net? 268. WhatisRoleBasedsecurity? Aroleisanamedsetofprincipalsthathavethesameprivilegeswithrespectto security(suchasatelleroramanager).Aprincipalcanbeamemberofoneormore roles.Therefore,applicationscanuserolemembershiptodeterminewhethera principalisauthorizedtoperformarequestedaction. ** 269. Howwillyoudowindowsauthenticationandwhatisthenamespace?If auserisloggedunderintegratedwindowsauthenticationmode,butheisstill notabletologon,whatmightbethepossiblecauseforthis?InASP.Net applicationhowdoyoufindthenameoftheloggedinpersonunderwindows authentication? 270. Whatarethedifferentauthenticationmodesinthe.NETenvironment? 271. <authenticationmode="Windows|Forms|Passport|None"> 272. <formsname="name" 273. loginUrl="url" 274. protection="All|None|Encryption|Validation" 275. timeout="30"path="/"> 276. requireSSL="true|false" 277. slidingExpiration="true|false"> 278. <credentialspasswordFormat="Clear|SHA1|MD5"> 279. <username="username"password="password"/> 280. </credentials> 281. </forms> 282. <passportredirectUrl="internal"/> </authentication> Attribute Option Description mode Controlsthedefaultauthenticationmodeforanapplication. WindowsSpecifiesWindowsauthenticationasthedefaultauthentication mode.UsethismodewhenusinganyformofMicrosoftInternet InformationServices(IIS)authentication:Basic,Digest, IntegratedWindowsauthentication(NTLM/Kerberos),or certificates. Forms SpecifiesASP.NETformsbasedauthenticationasthedefault authenticationmode.

Passport SpecifiesMicrosoftPassportauthenticationasthedefault

001 fo 14 egaP

authenticationmode. None Specifiesnoauthentication.Onlyanonymoususersareexpected orapplicationscanhandleeventstoprovidetheirown authentication.

283. HowdoyouspecifywhetheryourdatashouldbepassedasQuerystring andForms(MainlyaboutPOSTandGET) Throughattributetagofformtag. 284. Whatistheothermethod,otherthanGETandPOST,inASP.NET? 285. Whatarevalidator?NametheValidationcontrolsinasp.net?Howdou disablethem?Willtheasp.netvalidatorsruninserversideorclientside?How doyoudoClientsidevalidationin.Net?Howtodisablevalidatorcontrolby clientsideJavaScript? AsetofservercontrolsincludedwithASP.NETthattestuserinputinHTMLandWeb servercontrolsforprogrammerdefinedrequirements.Validationcontrolsperforminput checkinginservercode.IftheuserisworkingwithabrowserthatsupportsDHTML,the validationcontrolscanalsoperformvalidation("EnableClientScript"propertysetto true/false)usingclientscript. Thefollowingvalidationcontrolsareavailableinasp.net: RequiredFieldValidatorControl,CompareValidatorControl,RangeValidatorControl, RegularExpressionValidatorControl,CustomValidatorControl,ValidationSummary Control. 286. Whichtwopropertiesarethereoneveryvalidationcontrol? ControlToValidate,ErrorMessage 287. Howdoyouusecssinasp.net? Withinthe<HEAD>sectionofanHTMLdocumentthatwillusethesestyles,addalink tothisexternalCSSstylesheetthat followsthisform: <LINKREL="STYLESHEET"TYPE="text/css"HREF="MyStyles.css"> MyStyles.cssisthenameofyourexternalCSSstylesheet. 288. Howdoyouimplementpostbackwithatextbox?Whatispostbackand usestate? MakeAutoPostBackpropertytotrue 289. HowcanyoudebuganASPpage,withouttouchingthecode? 290. WhatisSQLinjection? AnSQLinjectionattack"injects"ormanipulatesSQLcodebyaddingunexpectedSQL toaquery. Manywebpagestakeparametersfromwebuser,andmakeSQLquerytothe database.Takeforinstancewhenauserlogin,webpagethatusernameandpassword andmakeSQLquerytothedatabasetocheckifauserhasvalidnameandpassword. Username:'or1=1 Password:[Empty] Thiswouldexecutethefollowingqueryagainsttheuserstable: selectcount(*)fromuserswhereuserName=''or1=1'anduserPass='' 291. HowcanuhandleExceptionsinAsp.Net? 292. HowcanuhandleUnManagedCodeExceptionsinASP.Net? 293. Asp.netHowtofindlasterrorwhichoccurred? A:Server.GetLastError() [C#] ExceptionLastError StringErrMessage LastError=Server.GetLastError() if(LastError!=null) ErrMessage=LastError.Message else ErrMessage="NoErrors" Response.Write("LastError="+ErrMessage)

001 fo 24 egaP

294. HowtodoCachinginASP?
A:<%@OutputCacheDuration="60"VaryByParam="None"%> VaryByParam Description value none Oneversionofpagecached(onlyrawGET) nversionsofpagecachedbasedonquerystringand/or * POSTbody nversionsofpagecachedbasedonvalueofv1variable v1 inquerystringorPOSTbody nversionsofpagecachedbasedonvalueofv1andv2 v1v2 variablesinquerystringorPOSTbody 295. <%@OutputCacheDuration="60"VaryByParam="none"%> <%@OutputCacheDuration="60"VaryByParam="*"%> <%@OutputCacheDuration="60"VaryByParam="nameage"%> TheOutputCachedirectivesupportsseveralothercachevaryingoptions VaryByHeadermaintainseparatecacheentryforheaderstringchanges (UserAgent,UserLanguage,etc.) VaryByControlforusercontrols,maintainseparatecacheentryforproperties ofausercontrol VaryByCustomcanspecifyseparatecacheentriesforbrowsertypesand versionorprovideacustomGetVaryByCustomStringmethodin HttpApplicationderivedclass 296. WhatistheGlobalASA(X)File? 297. AnyalternativetoavoidnamecollisionsotherthenNamespaces. AscenariothattwonamespacesnamedN1andN2aretherebothhavingthesame classsayA.nowinanotherclassivewritten usingN1usingN2 andiaminstantiatingclassAinthisclass.Thenhowwilluavoidnamecollisions? Ans:usingalias Eg:usingMyAlias=MyCompany.Proj.Nested 298. WhichisthenamespaceusedtowriteerrormessageineventLogFile? 299. Whatarethepageleveltransactionandclassleveltransaction? 300. Whataredifferenttransactionoptions? 301. Whatisthenamespaceforencryption? 302. Whatisthedifferencebetweenapplicationandcachevariables? 303. Whatisthedifferencebetweencontrolandcomponent? 304. Youvedefinedonepage_loadeventinaspxpageandsamepage_load eventincodebehindhowwillprogrun? 305. WherewouldyouuseanIHttpModule,andwhatarethelimitationsof anyapproachyoumighttakeinimplementingone? 306. CanyoueditdataintheRepeatercontrol?Whichtemplatemustyouprovide,in ordertodisplaydatainaRepeatercontrol?Howcanyouprovideanalternatingcolor schemeinaRepeatercontrol?Whatpropertymustyouset,andwhatmethodmustyou callinyourcode,inordertobindthedatafromsomedatasourcetotheRepeater control? 307. Whatistheuseofweb.config?Differencebetweenmachine.configand Web.config? ASP.NETconfigurationfilesareXMLbasedtextfileseachnamedweb.configthatcan appearinanydirectoryonanASP.NET Webapplicationserver.Eachweb.configfileappliesconfigurationsettingstothe directoryitislocatedinandtoall virtualchilddirectoriesbeneathit.Settingsinchilddirectoriescanoptionallyoverride ormodifysettingsspecifiedin parentdirectories.Therootconfigurationfile WinNT\Microsoft.NET\Framework\<version>\config\machine.configprovides defaultconfigurationsettingsfortheentiremachine.ASP.NETconfiguresIIStoprevent
001 fo 34 egaP

directbrowseraccesstoweb.config filestoensurethattheirvaluescannotbecomepublic(attemptstoaccessthemwill causeASP.NETtoreturn403:Access Forbidden). AtruntimeASP.NETusestheseweb.configconfigurationfilestohierarchicallycompute auniquecollectionofsettingsfor eachincomingURLtargetrequest(thesesettingsarecalculatedonlyonceandthen cachedacrosssubsequentrequestsASP.NET automaticallywatchesforfilechangesandwillinvalidatethecacheifanyofthe configurationfileschange). http://samples.gotdotnet.com/quickstart/aspplus/doc/configformat.aspx 308. Whatistheuseofsessionstatetagintheweb.configfile? Configuringsessionstate:Sessionstatefeaturescanbeconfiguredviathe <sessionState>sectioninaweb.configfile.Todoublethedefaulttimeoutof20 minutes,youcanaddthefollowingtotheweb.configfileofanapplication: <sessionState timeout="40" /> 309. Whatarethedifferentmodesforthesessionstatesintheweb.config file? Off Inproc StateServer SQLServer Indicatesthatsessionstateisnotenabled. Indicatesthatsessionstateisstoredlocally. Indicatesthatsessionstateisstoredonaremoteserver. IndicatesthatsessionstateisstoredontheSQLServer.

310. Whatissmartnavigation? WhenapageisrequestedbyanInternetExplorer5browser,orlater,smartnavigation enhancestheuser'sexperienceofthepagebyperformingthefollowing: eliminatingtheflashcausedbynavigation. persistingthescrollpositionwhenmovingfrompagetopage. persistingelementfocusbetweennavigations. retainingonlythelastpagestateinthebrowser'shistory. SmartnavigationisbestusedwithASP.NETpagesthatrequirefrequentpostbacksbut withvisualcontentthatdoesnotchangedramaticallyonreturn.Considerthiscarefully whendecidingwhethertosetthispropertytotrue. SettheSmartNavigationattributetotrueinthe@Pagedirectiveinthe.aspxfile. Whenthepageisrequested,thedynamicallygeneratedclasssetsthisproperty. 311. InwhatorderdotheeventsofanASPXpageexecute.Asadeveloperis itimportanttoundertsandtheseevents? 312. HowwouldyougetASP.NETrunninginApachewebserverswhy wouldyouevendothis? 313. Whattagsdoyouneedtoaddwithintheasp:datagridtagstobind columnsmanually 314. WhatbaseclassdoallWebFormsinheritfrom? System.Web.UI.Page 315. Howcanwecreatepiechartinasp.net? 316. Isitpossibleformetochangemyaspxfileextensiontosomeother name? Yes. OpenIIS>DefaultWebsite>Properties SelectHomeDirectorytab Clickonconfigurationbutton Clickonadd.Enteraspnet_isapidetails (C:\WINDOWS\Microsoft.NET\Framework\v1.0.3705\aspnet_isapi.dll | GET,HEAD,POST,DEBUG)

001 fo 44 egaP

Openmachine.config(C:\WINDOWS\Microsoft.NET\Framework\v1.0.3705\CONFIG)& addnewextensionunder<httpHandlers>tag <addverb="*"path="*.santhosh"type="System.Web.UI.PageHandlerFactory"/> 317. WhatisAutoEventWireupattributefor? (WEBSERVICE&REMOTING) 318. WhatisaWebServiceandwhatistheunderlyingprotocolusedin it?WhyWebServices? WebServicesareapplicationsdeliveredasaserviceontheWeb.Webservicesallowfor programmaticaccessofbusinesslogicovertheWeb.Webservicestypicallyrelyon XMLbasedprotocols,messages,andinterfacedescriptionsforcommunicationand access.Webservicesaredesignedtobeusedbyotherprogramsorapplicationsrather thandirectlybyenduser.ProgramsinvokingaWebservicearecalledclients.SOAP overHTTPisthemostcommonlyusedprotocolforinvokingWebservices. TherearethreemainusesofWebservices. 1. ApplicationintegrationWebserviceswithinanintranetarecommonlyusedto integratebusinessapplicationsrunningondisparateplatforms.Forexample,a .NETclientrunningonWindows2000caneasilyinvokeaJavaWebservice runningonamainframeorUnixmachinetoretrievedatafromalegacy application. 2. BusinessintegrationWebservicesallowtradingpartnerstoengageine businessleveragingtheexistingInternetinfrastructure.Organizationscansend electronicpurchaseorderstosuppliersandreceiveelectronicinvoices.Doinge businesswithWebservicesmeansalowbarriertoentrybecauseWebservices canbeaddedtoexistingapplicationsrunningonanyplatformwithoutchanging legacycode. 3. CommercialWebservicesfocusonsellingcontentandbusinessservicesto clientsovertheInternetsimilartofamiliarWebpages.UnlikeWebpages, commercialWebservicestargetapplicationsnothumansastheirdirectusers. ContinentalAirlinesexposesflightschedulesandstatusWebservicesfortravel Websitesandagenciestouseintheirapplications.LikeWebpages,commercial Webservicesarevaluableonlyiftheyexposeavaluableserviceorcontent.It wouldbeverydifficulttogetcustomerstopayyouforusingaWebservicethat createsbusinesschartswiththecustomers?data.Customerswouldratherbuy achartingcomponent(e.g.COMor.NETcomponent)andinstallitonthesame machineastheirapplication.Ontheotherhand,itmakessensetosellrealtime weatherinformationorstockquotesasaWebservice.Technologycanhelpyou addvaluetoyourservicesandexplorenewmarkets,butultimatelycustomers payforcontentsand/orbusinessservices,notfortechnology 1. AreWebServicesareplacementforotherdistributedcomputingplatforms? No.WebServicesisjustanewwayoflookingatexistingimplementationplatforms. 2. InaWebservice,needtodisplay10rowsfromatable.SoDataReaderor DataSetisbestchoice? A:WebServicewillsupportonlyDataSet. 3. HowtogenerateWebServiceproxy?WhatisSOAP,WSDL,UDDIandthe conceptbehindWebServices?WhatarevariouscomponentsofWSDL?What istheuseofWSDL.exeutility? SOAPisanXMLbasedmessagingframeworkspecificallydesignedforexchanging formatteddataacrosstheInternet,forexampleusingrequestandreplymessagesor sendingentiredocuments.SOAPissimple,easytouse,andcompletelyneutralwith respecttooperatingsystem,programminglanguage,ordistributedcomputing platform. AfterSOAPbecameavailableasamechanismforexchangingXMLmessagesamong enterprises(oramongdisparateapplicationswithinthesameenterprise),abetterway wasneededtodescribethemessagesandhowtheyareexchanged.TheWebServices DescriptionLanguage(WSDL)isaparticularformofanXMLSchema,developedby MicrosoftandIBMforthepurposeofdefiningtheXMLmessage,operation,and
001 fo 54 egaP

protocolmappingofawebserviceaccessedusingSOAPorotherXMLprotocol.WSDL defineswebservicesintermsof"endpoints"thatoperateonXMLmessages.TheWSDL syntaxallowsboththemessagesandtheoperationsonthemessagestobedefined abstractly,sotheycanbemappedtomultiplephysicalimplementations.Thecurrent WSDLspecdescribeshowtomapmessagesandoperationstoSOAP1.1,HTTP GET/POST,andMIME.WSDLcreateswebservicedefinitionsbymappingagroupof endpointsintoalogicalsequenceofoperationsonXMLmessages.ThesameXML messagecanbemappedtomultipleoperations(orservices)andboundtooneormore communicationsprotocols(using"ports"). TheUniversalDescription,Discovery,andIntegration(UDDI)frameworkdefinesadata model(inXML)andSOAPAPIsforregistrationandsearchesonbusinessinformation, includingthewebservicesabusinessexposestotheInternet.UDDIisanindependent consortiumofvendors,foundedbyMicrosoft,IBM,andAriba,forthepurposeof developinganInternetstandardforwebservicedescriptionregistrationanddiscovery. Microsoft,IBM,andAribaalsoarehostingtheinitialdeploymentofaUDDIservice, whichisconceptuallypatternedafterDNS(theInternetservicethattranslatesURLs intoTCPaddresses).UDDIusesaprivateagreementprofileofSOAP(i.e.UDDIdoesn't usetheSOAPserializationformatbecauseit'snotwellsuitedtopassingcompleteXML documents(it'saimedatRPCstyleinteractions).Themainideaisthatbusinessesuse theSOAPAPIstoregisterthemselveswithUDDI,andotherbusinessessearchUDDI whentheywanttodiscoveratradingpartner,forexamplesomeonefromwhomthey wishtoprocuresheetmetal,bolts,ortransistors.TheinformationinUDDIis categorizedaccordingtoindustrytypeandgeographicallocation,allowingUDDI consumerstosearchthroughlistsofpotentiallymatchingbusinessestofindthespecific onetheywanttocontact.Onceaspecificbusinessischosen,anothercalltoUDDIis madetoobtainthespecificcontactinformationforthatbusiness.Thecontact informationincludesapointertothetargetbusiness'sWSDLorotherXMLschemafile describingthewebservicethatthetargetbusinesspublishes. 4. Howtogenerateproxyclassotherthan.netappandwsdltool? ToaccessanXMLWebservicefromaclientapplication,youfirstaddaWebreference, whichisareferencetoanXMLWebservice.WhenyoucreateaWebreference,Visual StudiocreatesanXMLWebserviceproxyclassautomaticallyandaddsittoyour project.ThisproxyclassexposesthemethodsoftheXMLWebserviceandhandlesthe marshallingofappropriateargumentsbackandforthbetweentheXMLWebserviceand yourapplication.VisualStudiousestheWebServicesDescriptionLanguage(WSDL)to createtheproxy. TogenerateanXMLWebserviceproxyclass: Fromacommandprompt,useWsdl.exetocreateaproxyclass,specifying(ata minimum)theURLtoanXMLWebserviceoraservicedescription,orthepath toasavedservicedescription. Wsdl/language:language /protocol:protocol/namespace:myNameSpace /out:filename /username:username/password:password/domain:domain<urlorpath> 1. Whatisaproxyinwebservice?HowdoIuseaproxyserverwheninvokinga Webservice? 2. 3. 4. 5. asynchronouswebservicemeans? Whataretheeventsfiredwhenwebservicecalled? HowwilldotransactioninWebServices? HowdoesSOAPtransporthappenandwhatistheroleofHTTPinit?Howyou canaccessawebserviceusingsoap? 6. Whatarethedifferentformatterscanbeusedinboth?Why?..binary/soap 7. Howyouwillprotect/secureawebservice? Forthemostpart,thingsthatyoudotosecureaWebsitecanbeusedtosecureaWeb Service.Ifyouneedtoencryptthedataexchange,youuseSecureSocketsLayer(SSL) oraVirtualPrivateNetworktokeepthebitssecure.Forauthentication,useHTTPBasic orDigestauthenticationwithMicrosoftWindowsintegrationtofigureoutwhothe

001 fo 64 egaP

calleris. theseitemscannot: ParseaSOAPrequestforvalidvalues AuthenticateaccessattheWebMethodlevel(theycanauthenticateattheWeb Servicelevel) Stopreadingarequestassoonasitisrecognizedasinvalid http://msdn.microsoft.com/library/default.asp?url=/library/en us/cpguide/html/cpcontransactionsupportinaspnetwebservices.asp 8. Howwillyouexpose/publishawebservice? 9. Whatisdiscofile? 10. Whatstheattributeforwebservicemethod?Whatisthenamespacefor creatingwebservice? [WebMethod] usingSystem.Web usingSystem.Web.Services 11. WhatisRemoting? Theprocessofcommunicationbetweendifferentoperatingsystemprocesses, regardlessofwhethertheyareonthesamecomputer.The.NETremotingsystemisan architecturedesignedtosimplifycommunicationbetweenobjectslivingindifferent applicationdomains,whetheronthesamecomputerornot,andbetweendifferent contexts,whetherinthesameapplicationdomainornot. 12. Differencebetweenwebservices&remoting? ASP.NETWebServices Protocol State Management .NETRemoting

Canbeaccessedoveranyprotocol CanbeaccessedonlyoverHTTP (includingTCP,HTTP,SMTPandso on) Providesupportforbothstatefuland Webservicesworkinastateless statelessenvironmentsthrough environment SingletonandSingleCallobjects Webservicessupportonlythe datatypesdefinedintheXSD typesystem,limitingthe numberofobjectsthatcanbe serialized. Usingbinarycommunication,.NET Remotingcanprovidesupportfor richtypesystem .NETremotingrequirestheclientbe builtusing.NET,enforcing homogenousenvironment. CanalsotakeadvantageofIISfor faultisolation.IfIISisnotused, applicationneedstoprovide plumbingforensuringthereliability oftheapplication.

TypeSystem

Webservicessupport interoperabilityacross Interoperability platforms,andareidealfor heterogeneousenvironments. Highlyreliableduetothefact thatWebservicesarealways hostedinIIS

Reliability

Extensibility

Providesextensibilityby allowingustointerceptthe Veryextensiblebyallowingusto SOAPmessagesduringthe customizethedifferentcomponents serializationanddeserialization ofthe.NETremotingframework. stages. Easytocreateanddeploy. Complextoprogram.

Easeof Programming

001 fo 74 egaP

13. Thoughboththe.NETRemotinginfrastructureandASP.NETWebservicescanenable crossprocesscommunication,eachisdesignedtobenefitadifferenttargetaudience. ASP.NETWebservicesprovideasimpleprogrammingmodelandawidereach..NET Remotingprovidesamorecomplexprogrammingmodelandhasamuchnarrower reach. Asexplainedbefore,theclearperformanceadvantageprovidedbyTCPChannel remotingshouldmakeyouthinkaboutusingthischannelwheneveryoucanaffordto doso.IfyoucancreatedirectTCPconnectionsfromyourclientstoyourserverandif youneedtosupportonlythe.NETplatform,youshouldgoforthischannel.Ifyouare goingtogocrossplatformoryouhavetherequirementofsupportingSOAPviaHTTP, youshoulddefinitelygoforASP.NETWebservices. Boththe.NETremotingandASP.NETWebservicesarepowerfultechnologiesthat provideasuitableframeworkfordevelopingdistributedapplications.Itisimportantto understandhowbothtechnologiesworkandthenchoosetheonethatisrightforyour application.Forapplicationsthatrequireinteroperabilityandmustfunctionoverpublic networks,Webservicesareprobablythebestbet.Forthosethatrequire communicationswithother.NETcomponentsandwhereperformanceisakeypriority, .NETRemotingisthebestchoice.Inshort,useWebserviceswhenyouneedtosend andreceivedatafromdifferentcomputingplatforms,use.NETRemotingwhensending andreceivingdatabetween.NETapplications.Insomearchitecturalscenarios,you mightalsobeabletouse.NETRemotinginconjunctionwithASP.NETWebservicesand takeadvantageofthebestofbothworlds. TheKeydifferencebetweenASP.NETwebservicesand.NETRemotingishowthey serializedataintomessagesandtheformattheychooseformetadata. ASP.NETuses XMLserializerforserializingorMarshalling.AndXSDisusedforMetadata. .NET RemotingreliesonSystem.Runtime.Serialization.Formatter.Binaryand System.Runtime.Serialization.SOAPFormatterandrelieson.NETCLRRuntime assembliesformetadata. 14. CanyoupassSOAPmessagesthroughremoting? 15. CAOandSAO. ClientActivatedobjectsarethoseremoteobjectswhoseLifetimeisdirectlyControlled bytheclient.ThisisindirectcontrasttoSAO.Wheretheserver,nottheclienthas completecontroloverthelifetimeoftheobjects. Clientactivatedobjectsareinstantiatedontheserverassoonastheclientrequestthe objecttobecreated.UnlikeasSAOaCAOdoesntdelaytheobjectcreationuntilthe firstmethodiscalledontheobject.(InSAOtheobjectisinstantiatedwhentheclient callsthemethodontheobject) 16. singletonandsinglecall. Singletontypesneverhavemorethanoneinstanceatanyonetime.Ifaninstance exists,allclientrequestsareservicedbythatinstance. SingleCalltypesalwayshaveoneinstanceperclientrequest.Thenextmethod invocationwillbeservicedbyadifferentserverinstance,evenifthepreviousinstance hasnotyetbeenrecycledbythesystem. 17. WhatisAsynchronousWebServices? 18. WebClientclassanditsmethods? 19. Flowofremoting? 20. Whatistheuseoftraceutility? UsingtheSOAPTraceUtility TheMicrosoftSimpleObjectAccessProtocol(SOAP)Toolkit2.0includesaTCP/IP traceutility,MSSOAPT.EXE.YouusethistraceutilitytoviewtheSOAPmessagessent byHTTPbetweenaSOAPclientandaserviceontheserver. UsingtheTraceUtilityontheServer Toseeallofaservice'smessagesreceivedfromandsenttoallclients,performthe followingstepsontheserver. 1. Ontheserver,opentheWebServicesDescriptionLanguage(WSDL)file. 2. IntheWSDLfile,locatethe<soap:address>elementthatcorrespondstothe serviceandchangethelocationattributeforthiselementtoport8080.For
001 fo 84 egaP

example,ifthelocationattributespecifies <http://MyServer/VDir/Service.wsdl>changethisattributeto <http://MyServer:8080/VDir/Service.wsdl>. 3. RunMSSOAPT.exe. 4. OntheFilemenu,pointtoNew,andeitherclickFormattedTrace(ifyou don'twanttoseeHTTPheaders)orclickUnformattedTrace(ifyoudowantto seeHTTPheaders). 5. IntheTraceSetupdialogbox,clickOKtoacceptthedefaultvalues. UsingtheTraceUtilityontheClient Toseeallmessagessenttoandreceivedfromaservice,dothefollowingstepsonthe client. 6. CopytheWSDLfilefromtheservertotheclient. 7. Modifylocationattributeofthe<soap:address>elementinthelocalcopyofthe WSDLdocumenttodirecttheclienttolocalhost:8080andmakeanoteofthe currenthostandport.Forexample,iftheWSDLcontains <http://MyServer/VDir/Service.wsdl>,changeitto <http://localhost:8080/VDir/Service.wsdl>andmakenoteof"MyServer". 8. Ontheclient,runMSSOPT.exe. 9. OntheFilemenu,pointtoNew,andeitherclickFormattedTrace(ifyou don'twanttoseeHTTPheaders)orclickUnformattedTrace(ifyoudowantto seeHTTPheaders). 10. IntheDestinationhostbox,enterthehostspecifiedinStep2. 11. IntheDestinationportbox,entertheportspecifiedinStep2. 12. ClickOK.

(XML) 1. 2. 3. 4. Explaintheconceptofdataisland? HowtouseXMLDOMmodelonclientsideusingJavaScript. WhatarethewaystocreateatreeviewcontrolusingXML,XSL&JavaScript? QuestionsonXPathNavigator,andtheotherclassesinSystem.XML Namespace? 5. WhatisUseofTemplateinXSL? 6. WhatisWellFormedXMLandValidXML 7. HowyouwilldoSubStringinXSL 8. CanwedosortinginXSL?howdoyoudealsortingcolumnsdynamicallyin XML. 9. WhatisAsyncpropertyofXMLMeans? 10. WhatisXPathQuery? 11. DifferenceBetweenElementandNode. 12. WhatisCDATASection. 13. DOM&SAXparsersexplanationanddifference 14. WhatisGetElementbynamemethodwilldo? 15. Whatisselectnodemethodwillgive? 16. Whatisvalidxmldocument?Whatawellformedxmldocument? 17. WhatistheDifferencebetweenXmlDocumentandXmlDataDocument? 18. ExplainwhataDiffGramis,andagooduseforone? ADiffGramisanXMLformatthatisusedtoidentifycurrentandoriginalversionsof dataelements.WhensendingandretrievingaDataSetfromanXMLWebservice,the DiffGramformatisimplicitlyused. TheDataSetusestheDiffGramformattoloadandpersistitscontents,andtoserialize itscontentsfortransportacrossanetworkconnection.WhenaDataSetiswrittenasa DiffGram,itpopulatestheDiffGramwithallthenecessaryinformationtoaccurately recreatethecontents,thoughnottheschema,oftheDataSet,includingcolumnvalues fromboththeOriginalandCurrentrowversions,rowerrorinformation,androw order.
001 fo 94 egaP

DiffGramFormat TheDiffGramformatisdividedintothreesections:thecurrentdata,theoriginal(or "before")data,andanerrorssection,asshowninthefollowingexample. <?xmlversion="1.0"?> <diffgr:diffgram xmlns:msdata="urn:schemasmicrosoftcom:xmlmsdata" xmlns:diffgr="urn:schemasmicrosoftcom:xmldiffgramv1" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <DataInstance> </DataInstance> <diffgr:before> </diffgr:before> <diffgr:errors> </diffgr:errors> </diffgr:diffgram> TheDiffGramformatconsistsofthefollowingblocksofdata: <DataInstance> Thenameofthiselement,DataInstance,isusedforexplanationpurposesinthis documentation.ADataInstanceelementrepresentsaDataSetorarowofa DataTable.InsteadofDataInstance,theelementwouldcontainthenameofthe DataSetorDataTable.ThisblockoftheDiffGramformatcontainsthecurrentdata, whetherithasbeenmodifiedornot.Anelement,orrow,thathasbeenmodifiedis identifiedwiththediffgr:hasChangesannotation. <diffgr:before> ThisblockoftheDiffGramformatcontainstheoriginalversionofarow.Elementsin thisblockarematchedtoelementsintheDataInstanceblockusingthediffgr:id annotation. <diffgr:errors> ThisblockoftheDiffGramformatcontainserrorinformationforaparticularrowinthe DataInstanceblock.Elementsinthisblockarematchedtoelementsinthe DataInstanceblockusingthediffgr:idannotation. 19. IfIreplacemySqlserverwithXMLfilesandhowabouthandlingthesame? 20. WritesyntaxtoserializeclassusingXMLSerializer? (IIS) 21. InwhichprocessdoesIISruns(wasaskingabouttheEXEfile) inetinfo.exeistheMicrosoftIISserverrunning,handlingASP.NETrequestsamong otherthings. WhenanASP.NETrequestisreceived(usuallyafilewith.aspx extension),theISAPIfilteraspnet_isapi.dlltakescareofitbypassingtherequestto theactualworkerprocessaspnet_wp.exe. 22. WherearetheIISlogfilesstored? C:\WINDOWS\system32\Logfiles\W3SVC1 OR c:\winnt\system32\LogFiles\W3SVC1 23. WhatarethedifferentIISauthenticationmodesinIIS5.0andExplain? Differencebetweenbasicanddigestauthenticationmodes? IISprovidesavarietyofauthenticationschemes: Anonymous(enabledbydefault) Basic Digest IntegratedWindowsauthentication(enabledbydefault) ClientCertificateMapping
001 fo 05 egaP

Anonymous AnonymousauthenticationgivesusersaccesstothepublicareasofyourWebsite withoutpromptingthemforausernameorpassword.Althoughlistedasan authenticationscheme,itisnottechnicallyperforminganyclientauthentication becausetheclientisnotrequiredtosupplyanycredentials.Instead,IISprovides storedcredentialstoWindowsusingaspecialuseraccount,IUSR_machinename.By default,IIScontrolsthepasswordforthisaccount.WhetherornotIIScontrolsthe passwordaffectsthepermissionstheanonymoususerhas.WhenIIScontrolsthe password,asubauthenticationDLL(iissuba.dll)authenticatestheuserusinganetwork logon.ThefunctionofthisDLListovalidatethepasswordsuppliedbyIISandto informWindowsthatthepasswordisvalid,therebyauthenticatingtheclient.However, itdoesnotactuallyprovideapasswordtoWindows.WhenIISdoesnotcontrolthe password,IIScallstheLogonUser()APIinWindowsandprovidestheaccountname, passwordanddomainnametologontheuserusingalocallogon.Afterthelogon,IIS cachesthesecuritytokenandimpersonatestheaccount.Alocallogonmakesit possiblefortheanonymoususertoaccessnetworkresources,whereasanetworklogon doesnot. BasicAuthentication IISBasicauthenticationasanimplementationofthebasicauthenticationschemefound insection11oftheHTTP1.0specification. Asthespecificationmakesclear,thismethodis,inandofitself,nonsecure.The reasonisthatBasicauthenticationassumesatrustedconnectionbetweenclientand server.Thus,theusernameandpasswordaretransmittedincleartext.More specifically,theyaretransmittedusingBase64encoding,whichistriviallyeasyto decode.ThismakesBasicauthenticationthewrongchoicetouseoverapublicnetwork onitsown. BasicAuthenticationisalongstandingstandardsupportedbynearlyallbrowsers.It alsoimposesnospecialrequirementsontheserversideuserscanauthenticate againstanyNTdomain,orevenagainstaccountsonthelocalmachine.WithSSLto shelterthesecuritycredentialswhiletheyareintransmission,youhavean authenticationsolutionthatisbothhighlysecureandquiteflexible. DigestAuthentication TheDigestauthenticationoptionwasaddedinWindows2000andIIS5.0.LikeBasic authentication,thisisanimplementationofatechniquesuggestedbyWebstandards, namelyRFC2069(supercededbyRFC2617). Digestauthenticationalsousesachallenge/responsemodel,butitismuchmoresecure thanBasicauthentication(whenusedwithoutSSL).Itachievesthisgreatersecurity notbyencryptingthesecret(thepassword)beforesendingit,butratherbyfollowinga differentdesignpatternonethatdoesnotrequiretheclienttotransmitthepassword overthewireatall. Insteadofsendingthepassworditself,theclienttransmitsaonewaymessagedigest (achecksum)oftheuser'spassword,using(bydefault)theMD5algorithm.Theserver thenfetchesthepasswordforthatuserfromaWindows2000DomainController, rerunsthechecksumalgorithmonit,andcomparesthetwodigests.Iftheymatch,the serverknowsthattheclientknowsthecorrectpassword,eventhoughthepassword itselfwasneversent.(IfyouhaveeverwonderedwhatthedefaultISAPIfilter"md5filt" thatisinstalledwithIIS5.0isusedfor,nowyouknow. IntegratedWindowsAuthentication IntegratedWindowsauthentication(formerlyknownasNTLMauthenticationand WindowsNTChallenge/Responseauthentication)canuseeitherNTLMorKerberosV5 authenticationandonlyworkswithInternetExplorer2.0andlater. WhenInternetExplorerattemptstoaccessaprotectedresource,IISsendstwoWWW Authenticateheaders,NegotiateandNTLM. IfInternetExplorerrecognizestheNegotiateheader,itwillchooseitbecauseit islistedfirst.WhenusingNegotiate,thebrowserwillreturninformationforboth NTLMandKerberos.Attheserver,IISwilluseKerberosifboththeclient (InternetExplorer5.0andlater)andserver(IIS5.0andlater)arerunning

001 fo 15 egaP

Windows2000andlater,andbotharemembersofthesamedomainortrusted domains.Otherwise,theserverwilldefaulttousingNTLM. IfInternetExplorerdoesnotunderstandNegotiate,itwilluseNTLM.

So,whichmechanismisuseddependsuponanegotiationbetweenInternetExplorer andIIS. WhenusedinconjunctionwithKerberosv5authentication,IIScandelegatesecurity credentialsamongcomputersrunningWindows2000andlaterthataretrustedand configuredfordelegation.Delegationenablesremoteaccessofresourcesonbehalfof thedelegateduser. IntegratedWindowsauthenticationisthebestauthenticationschemeinanintranet environmentwhereusershaveWindowsdomainaccounts,especiallywhenusing Kerberos.IntegratedWindowsauthentication,likedigestauthentication,doesnotpass theuser'spasswordacrossthenetwork.Instead,ahashedvalueisexchanged. ClientCertificateMapping Acertificateisadigitallysignedstatementthatcontainsinformationaboutanentity andtheentity'spublickey,thusbindingthesetwopiecesofinformationtogether.A trustedorganization(orentity)calledaCertificationAuthority(CA)issuesacertificate aftertheCAverifiesthattheentityiswhoitsaysitis.Certificatescancontaindifferent typesofdata.Forexample,anX.509certificateincludestheformatofthecertificate, theserialnumberofthecertificate,thealgorithmusedtosignthecertificate,thename oftheCAthatissuedthecertificate,thenameandpublickeyoftheentityrequesting thecertificate,andtheCA'ssignature.X.509clientcertificatessimplifyauthentication forlargeruserbasesbecausetheydonotrelyonacentralizedaccountdatabase.You canverifyacertificatesimplybyexaminingthecertificate. http://msdn.microsoft.com/library/default.asp?url=/library/en us/vsent7/html/vxconIISAuthentication.asp 1. HowtoconfigurethesitesinWebserver(IIS)? 2. AdvantagesinIIS6.0? http://www.microsoft.com/windowsserver2003/iis/evaluation/features/default.mspx http://www.microsoft.com/technet/treeview/default.asp?url=/technet/prodtechnol/win dowsserver2003/proddocs/datacenter/gs_whatschanged.asp 3. IISIsolationLevels? InternetInformationServerintroducedthenotion"IsolationLevel",whichisalso presentinIIS4underadifferentname.IIS5supportsthreeisolationlevels,thatyou cansetfromtheHomeDirectorytabofthesite'sPropertiesdialog: Low(IISProcess):ASPpagesruninINetInfo.Exe,themainIISprocess, thereforetheyareexecutedinprocess.Thisisthefastestsetting,andisthe defaultunderIIS4.TheproblemisthatifASPcrashes,IIScrashesaswelland mustberestarted(IIS5hasareliablerestartfeaturethatautomaticallyrestarts aserverwhenafatalerroroccurs). Medium(Pooled):InthiscaseASPrunsinadifferentprocess,whichmakes thissettingmorereliable:ifASPcrashesIISwon't.AlltheASPapplicationsat theMediumisolationlevelsharethesameprocess,soyoucanhaveawebsite runningwithjusttwoprocesses(IISandASPprocess).IIS5isthefirstInternet InformationServerversionthatsupportsthissetting,whichisalsothedefault settingwhenyoucreateanIIS5application.NotethatanASPapplicationthat runsatthislevelisrununderCOM+,soit'shostedinDLLHOST.EXE(andyou canseethisexecutableintheTaskManager). High(Isolated):EachASPapplicationrunsoutprocessinitsownprocess space,thereforeifanASPapplicationcrashes,neitherIISnoranyotherASP applicationwillbeaffected.Thedownsideisthatyouconsumemorememory andresourcesiftheserverhostsmanyASPapplications.BothIIS4andIIS5 supportsthissetting:underIIS4thisprocessrunsinsideMTS.EXE,whileunder IIS5itrunsinsideDLLHOST.EXE. WhenselectinganisolationlevelforyourASPapplication,keepinmindthatout processsettingsthatis,MediumandHigharelessefficientthaninprocess(Low).
001 fo 25 egaP

However,outprocesscommunicationhasbeenvastlyimprovedunderIIS5,andinfact IIS5'sMediumisolationleveloftendeliverbetterresultsthanIIS4'sLowisolation.In practice,youshouldn'tsettheLowisolationlevelforanIIS5applicationunlessyou reallyneedtoservehundredspagespersecond. Controls 4. HowwillyoudoRedoandUndoinaTextControl? 5. HowtoimplementDataGridin.NET?Howwouldumakeacomboboxappear inonecolumnofaDataGrid?Whatarethewaystoshowdatagridinsidea datagridforamasterdetailstypeoftables?IfwewriteanycodeforDataGrid methods,whatistheaccessspecifierusedforthatmethodsinthecode behindfileandwhy? 6. HowcanwecreateTreecontrolinasp.net? Programming 7. WriteaprograminC#forcheckingagivennumberisPRIMEornot. 8. Writeaprogramtofindtheanglebetweenthehoursandminutesinaclock 9. WriteaC#programtofindtheFactorialofn 10. HowdoIuploadafilefrommyASP.NETpage? A:InordertoperformfileuploadinyourASP.NETpage,youwillneedtousetwo classes:theSystem.Web.UI.HtmlControls.HtmlInputFileclassandthe System.Web.HttpPostedFileclass.TheHtmlInputFileclassrepresentsandHTMLinput controlthattheuserwilluseontheclientsidetoselectafiletoupload.The HttpPostedFileclassrepresentstheuploadedfileandisobtainedfromthePostedFile propertyoftheHtmlInputFileclass.InordertousetheHtmlInputFilecontrol,youneed toaddtheenctypeattributetoyourformtagasfollows: <formid="upload"method="post"runat="server"enctype="multipart/formdata"> Also,rememberthatthe/datadirectoryistheonlydirectorywithWritepermissions enabledfortheanonymoususer.Therefore,youwillneedtomakesurethattheyour codeuploadsthefiletothe/datadirectoryoroneofitssubdirectories. BelowisasimpleexampleofhowtouploadafileviaanASP.NETpageinC#and VB.NET. C# <%@ImportNamespace="System"%> <%@ImportNamespace="System.Web"%> <%@ImportNamespace="System.Web.UI.HtmlControls"%> <%@ImportNamespace="System.IO"%> <%@ImportNamespace="System.Drawing"%> <html> <head> <title>upload_cs</title> </head> <scriptlanguage="C#"runat="server"> publicvoidUploadFile(objectsender,EventArgse) { if(loFile.PostedFile!=null) { try { stringstrFileName,strFileNamePath,strFileFolder strFileFolder=Context.Server.MapPath(@"data\") strFileName=loFile.PostedFile.FileName strFileName=Path.GetFileName(strFileName) strFileNamePath=strFileFolder+strFileName loFile.PostedFile.SaveAs(strFileNamePath) lblFileName.Text=strFileName lblFileLength.Text=loFile.PostedFile.ContentLength.ToString() lblFileType.Text=loFile.PostedFile.ContentType
001 fo 35 egaP

pnStatus.Visible=true } catch(Exceptionx) { LabellblError=newLabel() lblError.ForeColor=Color.Red lblError.Text="Exceptionoccurred:"+x.Message lblError.Visible=true this.Controls.Add(lblError) } } } </script> <body> <formid="upload_cs"method="post"runat="server"enctype="multipart/formdata"> <P> <INPUTtype="file"id="loFile"runat="server"> </P> <P> <asp:Buttonid="btnUpload"runat="server"Text="Upload" OnClick="UploadFile"></asp:Button></P> <P> <asp:Panelid="pnStatus"runat="server"Visible="False"> <asp:Labelid="lblFileName"FontBold="True"Runat="server"></asp:Label> uploaded<BR> <asp:Labelid="lblFileLength"Runat="server"></asp:Label>bytes<BR> <asp:Labelid="lblFileType"Runat="server"></asp:Label> </asp:Panel></P> </form> </body> </html> 11. HowdoIsendanemailmessagefrommyASP.NETpage? A:YoucanusetheSystem.Web.Mail.MailMessageandtheSystem.Web.Mail.SmtpMail classtosendemailinyourASPXpages.Belowisasimpleexampleofusingthisclass tosendmailinC#andVB.NET.Inordertosendmailthroughourmailserver,you wouldwanttomakesuretosetthestaticSmtpServerpropertyoftheSmtpMailclassto mailfwd. C# <%@ImportNamespace="System"%> <%@ImportNamespace="System.Web"%> <%@ImportNamespace="System.Web.Mail"%> <HTML> <HEAD> <title>MailTest</title> </HEAD> <scriptlanguage="C#"runat="server"> privatevoidPage_Load(Objectsender,EventArgse) { try { MailMessagemailObj=newMailMessage() mailObj.From="sales@joeswidgets.com" mailObj.To="ringleader@forexampledomain.com" mailObj.Subject="YourWidgetOrder" mailObj.Body="Yourorderwasprocessed." mailObj.BodyFormat=MailFormat.Text SmtpMail.SmtpServer="mailfwd" SmtpMail.Send(mailObj) Response.Write("Mailsentsuccessfully")

001 fo 45 egaP

} catch(Exceptionx) { Response.Write("Yourmessagewasnotsent:"+x.Message) } } </script> <body> <formid="mail_test"method="post"runat="server"> </form> </body> </HTML> 12. Writeaprogramtocreateausercontrolwithnameandsurnameasdata membersandloginasmethodandalsothecodetocallit.(Hintuseevent delegates)PracticalExampleofPassinganEventstodelegates 13. Howcanyouread3rdlinefromatextfile?

Areasforstudy Assemblies,GAC(howtopostprivateassemblytogac) .netarchitecture,MSIL,CTS,CLR Events,delegates(thisisthebasicsof.net.uhavetounderstanditverywell) asp.net,webform,servercontrols,usercontrols ado.net,dataset,datareader,dataadapter remoting,webservice desktopapplicationdatagrid. Threading

snoitseuQ deksA yltneuqerF krowemarF TEN.


AndyMcMullan Lastupdate:5Aug2004 ThisFAQtriestoanswersomecommonlyaskedquestionsaboutthe fundamentalsofthe.NETFrameworktopicslikeassemblies,garbage collection,security,interopwithCOM,andremoting.Themostcommonlyused partsoftheclasslibraryarealsocovered.Otheraspectsofthe.NET FrameworksuchasASP.NET,ADO.NETandWinFormsarenotcovered. ThisFAQwasinspiredbydiscussionsontheDOTNETmailinglist.Thelisthas nowbeensplitintoseveralDOTNETXlistsfordetailssee http://discuss.develop.com/. ChristopheLauerhastranslatedtheFAQintoFrenchyoucanfinditat http://www.dotnetfr.org/documents/andy_faqdotnet_fr.html . Contents
001 fo 55 egaP

1.Introduction o 1.1Whatis.NET? o 1.2Does.NETonlyapplytopeoplebuildingwebsites? o 1.3Whenwas.NETannounced? o 1.4Whenwasthefirstversionof.NETreleased? o 1.5WhattoolscanIusetodevelop.NETapplications? o 1.6Whatplatformsdoesthe.NETFrameworkrunon? o 1.7Whatlanguagesdoesthe.NETFrameworksupport? o 1.8Willthe.NETFrameworkgothroughastandardisation process? 2.Basicterminology o 2.1WhatistheCLR? o 2.2WhatistheCTS? o 2.3WhatistheCLS? o 2.4WhatisIL? o 2.5WhatisC#? o 2.6Whatdoes'managed'meaninthe.NETcontext? o 2.7Whatisreflection? 3.Assemblies o 3.1Whatisanassembly? o 3.2HowcanIproduceanassembly? o 3.3Whatisthedifferencebetweenaprivateassemblyanda sharedassembly? o 3.4Howdoassembliesfindeachother? o 3.5Howdoesassemblyversioningwork? 4.ApplicationDomains o 4.1WhatisanApplicationDomain? o 4.2HowdoesanAppDomaingetcreated? o 4.3CanIwritemyown.NEThost? 5.GarbageCollection o 5.1Whatisgarbagecollection? o 5.2Isittruethatobjectsdon'talwaysgetdestroyedimmediately whenthelastreferencegoesaway? o 5.3Whydoesn'tthe.NETruntimeofferdeterministicdestruction? o 5.4Isthelackofdeterministicdestructionin.NETaproblem? o 5.5DoesnondeterministicdestructionaffecttheusageofCOM objectsfrommanagedcode? o 5.6I'veheardthatFinalizemethodsshouldbeavoided.ShouldI implementFinalizeonmyclass? o 5.7DoIhaveanycontroloverthegarbagecollectionalgorithm? o 5.8HowcanIfindoutwhatthegarbagecollectorisdoing? 6.Serialization o 6.1Whatisserialization?

001 fo 65 egaP

o o o o o o

6.2Doesthe.NETFrameworkhaveinbuiltsupportfor serialization? 6.3Iwanttoserializeinstancesofmyclass.ShouldIuse XmlSerializer,SoapFormatterorBinaryFormatter? 6.4CanIcustomisetheserializationprocess? 6.5WhyisXmlSerializersoslow? 6.6WhydoIgeterrorswhenItrytoserializeaHashtable? 6.7XmlSerializeristhrowingageneric"Therewasanerror reflectingMyClass"error.HowdoIfindoutwhattheproblemis?

7.Attributes o 7.1Whatareattributes? o 7.2CanIcreatemyownmetadataattributes? o 7.3CanIcreatemyowncontextattributes? 8.CodeAccessSecurity o 8.1WhatisCodeAccessSecurity(CAS)? o 8.2HowdoesCASwork? o 8.3WhodefinestheCAScodegroups? o 8.4HowdoIdefinemyowncodegroup? o 8.5HowdoIchangethepermissionsetforacodegroup? o 8.6CanIcreatemyownpermissionset? o 8.7I'mhavingsometroublewithCAS.HowcanIdiagnosemy problem? o 8.8Ican'tbebotheredwithallthisCASstuff.CanIturnitoff? 9.IntermediateLanguage(IL) o 9.1CanIlookattheILforanassembly? o 9.2CansourcecodebereverseengineeredfromIL? o 9.3HowcanIstopmycodebeingreverseengineeredfromIL? o 9.4CanIwriteILprogramsdirectly? o 9.5CanIdothingsinILthatIcan'tdoinC#? 10.ImplicationsforCOM o 10.1IsCOMdead? o 10.2IsDCOMdead? o 10.3IsMTS/COM+dead? o 10.4CanIuseCOMcomponentsfrom.NETprograms? o 10.5CanIuse.NETcomponentsfromCOMprograms? o 10.6IsATLredundantinthe.NETworld? 11.Miscellaneous o 11.1Howdoes.NETremotingwork? o 11.2HowcanIgetattheWin32APIfroma.NETprogram? 12.ClassLibrary o 12.1FileI/O 12.1.1HowdoIreadfromatextfile? 12.1.2HowdoIwritetoatextfile?
001 fo 75 egaP

o o

12.1.3HowdoIread/writebinaryfiles? 12.2TextProcessing 12.2.1Areregularexpressionssupported? 12.3Internet 12.3.1HowdoIdownloadawebpage? 12.3.2HowdoIuseaproxy? 12.4XML 12.4.1IsDOMsupported? 12.4.2IsSAXsupported? 12.4.3IsXPathsupported? 12.5Threading 12.5.1Ismultithreadingsupported? 12.5.2HowdoIspawnathread? 12.5.3HowdoIstopathread? 12.5.4HowdoIusethethreadpool? 12.5.5HowdoIknowwhenmythreadpoolworkitemhas completed? 12.5.6HowdoIpreventconcurrentaccesstomydata? 12.6Tracing 12.6.1Istherebuiltinsupportfortracing/logging? 12.6.2CanIredirecttracingtoafile? 12.6.3CanIcustomisethetraceoutput?

13.Resources o 13.1Recommendedbooks o 13.2InternetResources o 13.3Weblogs o 13.4Samplecode&utilities

1.Introduction
1.1Whatis.NET?
That'sdifficulttosumupinasentence.AccordingtoMicrosoft,.NETisa "revolutionarynewplatform,builtonopenInternetprotocolsandstandards, withtoolsandservicesthatmeldcomputingandcommunicationsinnew ways". Amorepracticaldefinitionwouldbethat.NETisanewenvironmentfor developingandrunningsoftwareapplications,featuringeaseofdevelopment ofwebbasedservices,richstandardruntimeservicesavailableto componentswritteninavarietyofprogramminglanguages,andinter languageandintermachineinteroperability. Notethatwhentheterm".NET"isusedinthisFAQitrefersonlytothenew .NETruntimeandassociatedtechnologies.Thisissometimescalledthe".NET Framework".ThisFAQdoesNOTcoveranyofthevariousotherexistingand newproducts/technologiesthatMicrosoftareattachingthe.NETnameto(e.g. SQLServer.NET).
001 fo 85 egaP

1.2Does.NETonlyapplytopeoplebuildingwebsites?
No.IfyouwriteanyWindowssoftware(usingATL/COM,MFC,VB,orevenraw Win32),.NETmayofferaviablealternative(oraddition)tothewayyoudo thingscurrently.Ofcourse,ifyoudodevelopwebsites,then.NEThaslotsto interestyounotleastASP.NET.

1.3Whenwas.NETannounced?
BillGatesdeliveredakeynoteatForum2000,heldJune22,2000,outlining the.NET'vision'.TheJuly2000PDChadanumberofsessionson.NET technology,anddelegatesweregivenCDscontainingaprereleaseversionof the.NETframework/SDKandVisualStudio.NET.

1.4Whenwasthefirstversionof.NETreleased?
Thefinalversionofthe1.0SDKandruntimewasmadepubliclyavailable around6pmPSTon15Jan2002.Atthesametime,thefinalversionofVisual Studio.NETwasmadeavailabletoMSDNsubscribers.

1.5WhattoolscanIusetodevelop.NETapplications?
Thereareanumberoftools,describedhereinascendingorderofcost:

.NETFrameworkSDK:TheSDKisfreeandincludescommandline compilersforC++,C#,andVB.NETandvariousotherutilitiestoaid development. ASP.NETWebMatrix:ThisisafreeASP.NETdevelopmentenvironment fromMicrosoft.AswellasaGUIdevelopmentenvironment,the downloadincludesasimplewebserverthatcanbeusedinsteadofIISto hostASP.NETapps.ThisopensupASP.NETdevelopmenttousersof WindowsXPHomeEdition,whichcannotrunIIS. MicrosoftVisualC#.NETStandard2003:Thisisacheap(around$100) versionofVisualStudiolimitedtoonelanguageandalsowithlimited wizardsupport.Forexample,there'snowizardsupportforclasslibraries orcustomUIcontrols.Usefulforbeginnerstolearnwith,orforsavvy developerswhocanworkaroundthedeficienciesinthesuppliedwizards. AswellasC#,thereareVB.NETandC++versions. MicrosoftVisualStudio.NETProfessional2003:Ifyouhavealicensefor VisualStudio6.0,youcangettheupgrade.Youcanalsoupgradefrom VS.NET2002foratoken$30.VisualStudio.NETincludessupportforall theMSlanguages(C#,C++,VB.NET)andhasextensivewizardsupport.

AtthetopendofthepricespectrumaretheVisualStudio.NET2003Enterprise andEnterpriseArchitecteditions.TheseofferextrafeaturessuchasVisual Sourcesafe(versioncontrol),andperformanceandanalysistools.Checkout theVisualStudio.NETFeatureComparisonat http://msdn.microsoft.com/vstudio/howtobuy/choosing.asp.

001 fo 95 egaP

1.6Whatplatformsdoesthe.NETFrameworkrunon?
TheruntimesupportsWindowsXP,Windows2000,NT4SP6aandWindows ME/98.Windows95isnotsupported.Somepartsoftheframeworkdonot workonallplatformsforexample,ASP.NETisonlysupportedonWindowsXP andWindows2000.Windows98/MEcannotbeusedfordevelopment. IISisnotsupportedonWindowsXPHomeEdition,andsocannotbeusedto hostASP.NET.However,theASP.NETWebMatrixwebserverdoesrunonXP Home. TheMonoprojectisattemptingtoimplementthe.NETframeworkonLinux.

1.7Whatlanguagesdoesthe.NETFrameworksupport?
MSprovidescompilersforC#,C++,VBandJScript.Othervendorshave announcedthattheyintendtodevelop.NETcompilersforlanguagessuchas COBOL,Eiffel,Perl,SmalltalkandPython.

1.8Willthe.NETFrameworkgothroughastandardisation process?
Fromhttp://msdn.microsoft.com/net/ecma/:"OnDecember13,2001,the ECMAGeneralAssemblyratifiedtheC#andcommonlanguageinfrastructure (CLI)specificationsintointernationalstandards.TheECMAstandardswillbe knownasECMA334(C#)andECMA335(theCLI)."

2.Basicterminology
2.1WhatistheCLR?
CLR=CommonLanguageRuntime.TheCLRisasetofstandardresources that(intheory)any.NETprogramcantakeadvantageof,regardlessof programminglanguage.RobertSchmidt(Microsoft)liststhefollowingCLR resourcesinhisMSDNPDC#article:

Objectorientedprogrammingmodel(inheritance,polymorphism, exceptionhandling,garbagecollection) Securitymodel Typesystem All.NETbaseclasses Many.NETframeworkclasses Development,debugging,andprofilingtools Executionandcodemanagement ILtonativetranslatorsandoptimizers

Whatthismeansisthatinthe.NETworld,differentprogramminglanguages willbemoreequalincapabilitythantheyhaveeverbeenbefore,although clearlynotalllanguageswillsupportallCLRservices.


001 fo 06 egaP

2.2WhatistheCTS?
CTS=CommonTypeSystem.Thisistherangeoftypesthatthe.NETruntime understands,andthereforethat.NETapplicationscanuse.Howevernotethat notall.NETlanguageswillsupportallthetypesintheCTS.TheCTSisa supersetoftheCLS.

2.3WhatistheCLS?
CLS=CommonLanguageSpecification.ThisisasubsetoftheCTSwhichall .NETlanguagesareexpectedtosupport.Theideaisthatanyprogramwhich usesCLScomplianttypescaninteroperatewithany.NETprogramwrittenin anylanguage. Intheorythisallowsverytightinteropbetweendifferent.NETlanguagesfor exampleallowingaC#classtoinheritfromaVBclass.

2.4WhatisIL?
IL=IntermediateLanguage.AlsoknownasMSIL(MicrosoftIntermediate Language)orCIL(CommonIntermediateLanguage).All.NETsourcecode(of anylanguage)iscompiledtoIL.TheIListhenconvertedtomachinecodeat thepointwherethesoftwareisinstalled,oratruntimebyaJustInTime (JIT)compiler.

2.5WhatisC#?
C#isanewlanguagedesignedbyMicrosofttoworkwiththe.NETframework. Intheir"IntroductiontoC#"whitepaper,MicrosoftdescribeC#asfollows: "C#isasimple,modern,objectoriented,andtypesafeprogramming languagederivedfromCandC++.C#(pronouncedCsharp)isfirmly plantedintheCandC++familytreeoflanguages,andwillimmediatelybe familiartoCandC++programmers.C#aimstocombinethehighproductivity ofVisualBasicandtherawpowerofC++." Substitute'Java'for'C#'inthequoteabove,andyou'llseethatthestatement stillworksprettywell:). IfyouareaC++programmer,youmightliketocheckoutmyC#FAQ.

2.6Whatdoes'managed'meaninthe.NETcontext?
Theterm'managed'isthecauseofmuchconfusion.Itisusedinvarious placeswithin.NET,meaningslightlydifferentthings. Managedcode:The.NETframeworkprovidesseveralcoreruntimeservicesto theprogramsthatrunwithinitforexampleexceptionhandlingandsecurity. Fortheseservicestowork,thecodemustprovideaminimumlevelof
001 fo 16 egaP

informationtotheruntime.Suchcodeiscalledmanagedcode.AllC#and VisualBasic.NETcodeismanagedbydefault.VS7C++codeisnotmanaged bydefault,butthecompilercanproducemanagedcodebyspecifyinga commandlineswitch(/com+). Manageddata:Thisisdatathatisallocatedanddeallocatedbythe.NET runtime'sgarbagecollector.C#andVB.NETdataisalwaysmanaged.VS7 C++dataisunmanagedbydefault,evenwhenusingthe/com+switch,butit canbemarkedasmanagedusingthe__gckeyword. Managedclasses:ThisisusuallyreferredtointhecontextofManaged Extensions(ME)forC++.WhenusingMEC++,aclasscanbemarkedwith the__gckeyword.Asthenamesuggests,thismeansthatthememoryfor instancesoftheclassismanagedbythegarbagecollector,butitalsomeans morethanthat.Theclassbecomesafullypaidupmemberofthe.NET communitywiththebenefitsandrestrictionsthatbrings.Anexampleofa benefitisproperinteropwithclasseswritteninotherlanguagesforexample, amanagedC++classcaninheritfromaVBclass.Anexampleofarestriction isthatamanagedclasscanonlyinheritfromonebaseclass.

2.7Whatisreflection?
All.NETcompilersproducemetadataaboutthetypesdefinedinthemodules theyproduce.Thismetadataispackagedalongwiththemodule(modulesin turnarepackagedtogetherinassemblies),andcanbeaccessedbya mechanismcalledreflection.TheSystem.Reflectionnamespacecontains classesthatcanbeusedtointerrogatethetypesforamodule/assembly. Usingreflectiontoaccess.NETmetadataisverysimilartousing ITypeLib/ITypeInfotoaccesstypelibrarydatainCOM,anditisusedfor similarpurposese.g.determiningdatatypesizesformarshalingdataacross context/process/machineboundaries. Reflectioncanalsobeusedtodynamicallyinvokemethods(see System.Type.InvokeMember),orevencreatetypesdynamicallyatruntime (seeSystem.Reflection.Emit.TypeBuilder).

3.Assemblies
3.1Whatisanassembly?
Anassemblyissometimesdescribedasalogical.EXEor.DLL,andcanbean application(withamainentrypoint)oralibrary.Anassemblyconsistsofone ormorefiles(dlls,exes,htmlfilesetc),andrepresentsagroupofresources, typedefinitions,andimplementationsofthosetypes.Anassemblymayalso containreferencestootherassemblies.Theseresources,typesandreferences aredescribedinablockofdatacalledamanifest.Themanifestispartofthe assembly,thusmakingtheassemblyselfdescribing.

001 fo 26 egaP

Animportantaspectofassembliesisthattheyarepartoftheidentityofa type.Theidentityofatypeistheassemblythathousesitcombinedwiththe typename.Thismeans,forexample,thatifassemblyAexportsatypecalled T,andassemblyBexportsatypecalledT,the.NETruntimeseestheseastwo completelydifferenttypes.Furthermore,don'tgetconfusedbetween assembliesandnamespacesnamespacesaremerelyahierarchicalwayof organisingtypenames.Totheruntime,typenamesaretypenames, regardlessofwhethernamespacesareusedtoorganisethenames.It'sthe assemblyplusthetypename(regardlessofwhetherthetypenamebelongsto anamespace)thatuniquelyindentifiesatypetotheruntime. Assembliesarealsoimportantin.NETwithrespecttosecuritymanyofthe securityrestrictionsareenforcedattheassemblyboundary. Finally,assembliesaretheunitofversioningin.NETmoreonthisbelow.

3.2HowcanIproduceanassembly?
Thesimplestwaytoproduceanassemblyisdirectlyfroma.NETcompiler.For example,thefollowingC#program:
publicclassCTest { publicCTest() { System.Console.WriteLine("HellofromCTest") } }

canbecompiledintoalibraryassembly(dll)likethis:
csc/t:libraryctest.cs

Youcanthenviewthecontentsoftheassemblybyrunningthe"IL Disassembler"toolthatcomeswiththe.NETSDK. Alternativelyyoucancompileyoursourceintomodules,andthencombine themodulesintoanassemblyusingtheassemblylinker(al.exe).FortheC# compiler,the/target:moduleswitchisusedtogenerateamoduleinsteadof anassembly.

3.3Whatisthedifferencebetweenaprivateassemblyanda sharedassembly?

Locationandvisibility:Aprivateassemblyisnormallyusedbya singleapplication,andisstoredintheapplication'sdirectory,orasub directorybeneath.Asharedassemblyisnormallystoredintheglobal assemblycache,whichisarepositoryofassembliesmaintainedbythe .NETruntime.Sharedassembliesareusuallylibrariesofcodewhich manyapplicationswillfinduseful,e.g.the.NETframeworkclasses.

001 fo 36 egaP

Versioning:Theruntimeenforcesversioningconstraintsonlyonshared assemblies,notonprivateassemblies.

3.4Howdoassembliesfindeachother?
Bysearchingdirectorypaths.Thereareseveralfactorswhichcanaffectthe path(suchastheAppDomainhost,andapplicationconfigurationfiles),butfor privateassembliesthesearchpathisnormallytheapplication'sdirectoryand itssubdirectories.Forsharedassemblies,thesearchpathisnormallysameas theprivateassemblypathplusthesharedassemblycache.

3.5Howdoesassemblyversioningwork?
Eachassemblyhasaversionnumbercalledthecompatibilityversion.Also eachreferencetoanassembly(fromanotherassembly)includesboththe nameandversionofthereferencedassembly. Theversionnumberhasfournumericparts(e.g.5.5.2.33).Assemblieswith eitherofthefirsttwopartsdifferentarenormallyviewedasincompatible.If thefirsttwopartsarethesame,butthethirdisdifferent,theassembliesare deemedas'maybecompatible'.Ifonlythefourthpartisdifferent,the assembliesaredeemedcompatible.However,thisisjustthedefaultguideline itistheversionpolicythatdecidestowhatextenttheserulesareenforced. Theversionpolicycanbespecifiedviatheapplicationconfigurationfile. Remember:versioningisonlyappliedtosharedassemblies,notprivate assemblies.

4.ApplicationDomains
4.1WhatisanApplicationDomain?
AnAppDomaincanbethoughtofasalightweightprocess.Multiple AppDomainscanexistinsideaWin32process.Theprimarypurposeofthe AppDomainistoisolateanapplicationfromotherapplications. Win32processesprovideisolationbyhavingdistinctmemoryaddressspaces. Thisiseffective,butitisexpensiveanddoesn'tscalewell.The.NETruntime enforcesAppDomainisolationbykeepingcontrolovertheuseofmemoryall memoryintheAppDomainismanagedbythe.NETruntime,sotheruntime canensurethatAppDomainsdonotaccesseachother'smemory.

4.2HowdoesanAppDomaingetcreated?
AppDomainsareusuallycreatedbyhosts.ExamplesofhostsaretheWindows Shell,ASP.NETandIE.Whenyouruna.NETapplicationfromthecommand line,thehostistheShell.TheShellcreatesanewAppDomainforevery application.

001 fo 46 egaP

AppDomainscanalsobeexplicitlycreatedby.NETapplications.HereisaC# samplewhichcreatesanAppDomain,createsaninstanceofanobjectinsideit, andthenexecutesoneoftheobject'smethods.Notethatyoumustnamethe executable'appdomaintest.exe'forthiscodetoworkasis.


usingSystem usingSystem.Runtime.Remoting publicclassCAppDomainInfo:MarshalByRefObject { publicstringGetAppDomainInfo() { return"AppDomain="+AppDomain.CurrentDomain.FriendlyName } } publicclassApp { publicstaticintMain() { AppDomainad=AppDomain.CreateDomain("Andy'snewdomain",null,null ) ObjectHandleoh=ad.CreateInstance("appdomaintest","CAppDomainInfo" ) CAppDomainInfoadInfo=(CAppDomainInfo)(oh.Unwrap()) stringinfo=adInfo.GetAppDomainInfo() Console.WriteLine("AppDomaininfo:"+info) return0 } }

4.3CanIwritemyown.NEThost?
Yes.Foranexampleofhowtodothis,takealookatthesourceforthedm.net monikerdevelopedbyJasonWhittingtonandDonBox (http://staff.develop.com/jasonw/clr/readme.htm).Thereisalsoacode sampleinthe.NETSDKcalledCorHost.

5.GarbageCollection
5.1Whatisgarbagecollection?
Garbagecollectionisasystemwherebyaruntimecomponenttakes responsibilityformanagingthelifetimeofobjectsandtheheapmemorythat theyoccupy.Thisconceptisnotnewto.NETJavaandmanyother languages/runtimeshaveusedgarbagecollectionforsometime.

5.2Isittruethatobjectsdon'talwaysgetdestroyed immediatelywhenthelastreferencegoesaway?

001 fo 56 egaP

Yes.Thegarbagecollectoroffersnoguaranteesaboutthetimewhenanobject willbedestroyedanditsmemoryreclaimed. Thereisaninterestingthreadinthearchives,startedbyChrisSells,aboutthe implicationsofnondeterministicdestructionofobjectsinC#: http://discuss.develop.com/archives/wa.exe?A2=ind0007&L=DOTNET&P=R24 819 InOctober2000,Microsoft'sBrianHarrypostedalengthyanalysisofthe problem: http://discuss.develop.com/archives/wa.exe?A2=ind0010A&L=DOTNET&P=R2 8572 ChrisSells'responsetoBrian'spostingishere: http://discuss.develop.com/archives/wa.exe?A2=ind0010C&L=DOTNET&P=R9 83

5.3Whydoesn'tthe.NETruntimeofferdeterministic destruction?
Becauseofthegarbagecollectionalgorithm.The.NETgarbagecollectorworks byperiodicallyrunningthroughalistofalltheobjectsthatarecurrentlybeing referencedbyanapplication.Alltheobjectsthatitdoesn'tfindduringthis searcharereadytobedestroyedandthememoryreclaimed.Theimplication ofthisalgorithmisthattheruntimedoesn'tgetnotifiedimmediatelywhenthe finalreferenceonanobjectgoesawayitonlyfindsoutduringthenext sweepoftheheap. Futhermore,thistypeofalgorithmworksbestbyperformingthegarbage collectionsweepasrarelyaspossible.Normallyheapexhaustionisthetrigger foracollectionsweep.

5.4Isthelackofdeterministicdestructionin.NETaproblem?
It'scertainlyanissuethataffectscomponentdesign.Ifyouhaveobjectsthat maintainexpensiveorscarceresources(e.g.databaselocks),youneedto providesomewayfortheclienttotelltheobjecttoreleasetheresourcewhen itisdone.MicrosoftrecommendthatyouprovideamethodcalledDispose() forthispurpose.However,thiscausesproblemsfordistributedobjectsina distributedsystemwhocallstheDispose()method?Someformofreference countingorownershipmanagementmechanismisneededtohandle distributedobjectsunfortunatelytheruntimeoffersnohelpwiththis.

5.5Doesnondeterministicdestructionaffecttheusageof COMobjectsfrommanagedcode?
Yes.WhenusingaCOMobjectfrommanagedcode,youareeffectivelyrelying onthegarbagecollectortocallthefinalreleaseonyourobject.IfyourCOM objectholdsontoanexpensiveresourcewhichisonlycleanedupafterthe
001 fo 66 egaP

finalrelease,youmayneedtoprovideanewinterfaceonyourobjectwhich supportsanexplicitDispose()method.

5.6I'veheardthatFinalizemethodsshouldbeavoided.Should IimplementFinalizeonmyclass?
AnobjectwithaFinalizemethodismoreworkforthegarbagecollectorthan anobjectwithoutone.Alsotherearenoguaranteesabouttheorderinwhich objectsareFinalized,sothereareissuessurroundingaccesstootherobjects fromtheFinalizemethod.Finally,thereisnoguaranteethataFinalizemethod willgetcalledonanobject,soitshouldneverbereliedupontodocleanupof anobject'sresources. Microsoftrecommendthefollowingpattern:
publicclassCTest:IDisposable { publicvoidDispose() { ...//Cleanupactivities GC.SuppressFinalize(this) } ~CTest()//C#syntaxhidingtheFinalize()method { Dispose() } }

InthenormalcasetheclientcallsDispose(),theobject'sresourcesarefreed, andthegarbagecollectorisrelievedofitsFinalizingdutiesbythecallto SuppressFinalize().Intheworstcase,i.e.theclientforgetstocallDispose(), thereisareasonablechancethattheobject'sresourceswilleventuallyget freedbythegarbagecollectorcallingFinalize().Giventhelimitationsofthe garbagecollectionalgorithmthisseemslikeaprettyreasonableapproach.

5.7DoIhaveanycontroloverthegarbagecollection algorithm?
Alittle.Forexample,theSystem.GCclassexposesaCollectmethodthis forcesthegarbagecollectortocollectallunreferencedobjectsimmediately.

5.8HowcanIfindoutwhatthegarbagecollectorisdoing?
Lotsofinterestingstatisticsareexportedfromthe.NETruntimeviathe'.NET CLRxxx'performancecounters.UsePerformanceMonitortoviewthem.

6.Serialization
6.1Whatisserialization?

001 fo 76 egaP

Serializationistheprocessofconvertinganobjectintoastreamofbytes. Deserializationistheoppositeprocessofcreatinganobjectfromastreamof bytes.Serialization/Deserializationismostlyusedtotransportobjects(e.g. duringremoting),ortopersistobjects(e.g.toafileordatabase).

6.2Doesthe.NETFrameworkhaveinbuiltsupportfor serialization?
Therearetwoseparatemechanismsprovidedbythe.NETclasslibrary XmlSerializerandSoapFormatter/BinaryFormatter.Microsoftuses XmlSerializerforWebServices,andusesSoapFormatter/BinaryFormatterfor remoting.Bothareavailableforuseinyourowncode.

6.3Iwanttoserializeinstancesofmyclass.ShouldIuse XmlSerializer,SoapFormatterorBinaryFormatter?
Itdepends.XmlSerializerhasseverelimitationssuchastherequirementthat thetargetclasshasaparameterlessconstructor,andonlypublicread/write propertiesandfieldscanbeserialized.However,ontheplusside, XmlSerializerhasgoodsupportforcustomisingtheXMLdocumentthatis producedorconsumed.XmlSerializer'sfeaturesmeanthatitismostsuitable forcrossplatformwork,orforconstructingobjectsfromexistingXML documents. SoapFormatterandBinaryFormatterhavefewerlimitationsthanXmlSerializer. Theycanserializeprivatefields,forexample.Howevertheybothrequirethat thetargetclassbemarkedwiththe[Serializable]attribute,solike XmlSerializertheclassneedstobewrittenwithserializationinmind.Also therearesomequirkstowatchoutforforexampleondeserializationthe constructorofthenewobjectisnotinvoked. ThechoicebetweenSoapFormatterandBinaryFormatterdependsonthe application.BinaryFormattermakessensewherebothserializationand deserializationwillbeperformedonthe.NETplatformandwhereperformance isimportant.SoapFormattergenerallymakesmoresenseinallothercases, foreaseofdebuggingifnothingelse.

6.4CanIcustomisetheserializationprocess?
Yes.XmlSerializersupportsarangeofattributesthatcanbeusedtoconfigure serializationforaparticularclass.Forexample,afieldorpropertycanbe markedwiththe[XmlIgnore]attributetoexcludeitfromserialization.Another exampleisthe[XmlElement]attribute,whichcanbeusedtospecifytheXML elementnametobeusedforaparticularpropertyorfield. SerializationviaSoapFormatter/BinaryFormattercanalsobecontrolledto someextentbyattributes.Forexample,the[NonSerialized]attributeisthe equivalentofXmlSerializer's[XmlIgnore]attribute.Ultimatecontrolofthe

001 fo 86 egaP

serializationprocesscanbeacheivedbyimplementingthetheISerializable interfaceontheclasswhoseinstancesaretobeserialized.

6.5WhyisXmlSerializersoslow?
ThereisaonceperprocesspertypeoverheadwithXmlSerializer.Sothefirst timeyouserializeordeserializeanobjectofagiventypeinanapplication, thereisasignificantdelay.Thisnormallydoesn'tmatter,butitmaymean,for example,thatXmlSerializerisapoorchoiceforloadingconfigurationsettings duringstartupofaGUIapplication.

6.6WhydoIgeterrorswhenItrytoserializeaHashtable?
XmlSerializerwillrefusetoserializeinstancesofanyclassthatimplements IDictionary,e.g.Hashtable.SoapFormatterandBinaryFormatterdonothave thisrestriction.

6.7XmlSerializeristhrowingageneric"Therewasanerror reflectingMyClass"error.HowdoIfindoutwhattheproblem is?


LookattheInnerExceptionpropertyoftheexceptionthatisthrowntogeta morespecificerrormessage.

7.Attributes
7.1Whatareattributes?
Thereareatleasttwotypesof.NETattribute.ThefirsttypeIwillrefertoasa metadataattributeitallowssomedatatobeattachedtoaclassormethod. Thisdatabecomespartofthemetadatafortheclass,and(likeotherclass metadata)canbeaccessedviareflection.Anexampleofametadataattribute is[serializable],whichcanbeattachedtoaclassandmeansthatinstancesof theclasscanbeserialized.
[serializable]publicclassCTest{}

Theothertypeofattributeisacontextattribute.Contextattributesusea similarsyntaxtometadataattributesbuttheyarefundamentallydifferent. Contextattributesprovideaninterceptionmechanismwherebyinstance activationandmethodcallscanbepreand/orpostprocessed.Ifyou'vecome acrossKeithBrown'suniversaldelegatoryou'llbefamiliarwiththisidea.

7.2CanIcreatemyownmetadataattributes?
Yes.SimplyderiveaclassfromSystem.Attributeandmarkitwiththe AttributeUsageattribute.Forexample:
[AttributeUsage(AttributeTargets.Class)]
001 fo 96 egaP

publicclassInspiredByAttribute:System.Attribute { publicstringInspiredBy publicInspiredByAttribute(stringinspiredBy) { InspiredBy=inspiredBy } }

[InspiredBy("AndyMc'sbrilliant.NETFAQ")] classCTest { }

classCApp { publicstaticvoidMain() { object[]atts=typeof(CTest).GetCustomAttributes(true) foreach(objectattinatts) if(attisInspiredByAttribute) Console.WriteLine("ClassCTestwasinspiredby{0}", ((InspiredByAttribute)att).InspiredBy) } }

7.3CanIcreatemyowncontextattributes?
Yes.TakealookatDonBox'ssample(calledCallThreshold)at http://www.develop.com/dbox/dotnet/threshold/,andalsoPeterDrayton's Tracehook.NETathttp://www.razorsoft.net/

8.CodeAccessSecurity
8.1WhatisCodeAccessSecurity(CAS)?
CASisthepartofthe.NETsecuritymodelthatdetermineswhetherornota pieceofcodeisallowedtorun,andwhatresourcesitcanusewhenitis running.Forexample,itisCASthatwillpreventa.NETwebappletfrom formattingyourharddisk.

8.2HowdoesCASwork?
TheCASsecuritypolicyrevolvesaroundtwokeyconceptscodegroupsand permissions.Each.NETassemblyisamemberofaparticularcodegroup, andeachcodegroupisgrantedthepermissionsspecifiedinanamed permissionset. Forexample,usingthedefaultsecuritypolicy,acontroldownloadedfroma websitebelongstothe'ZoneInternet'codegroup,whichadherestothe
001 fo 07 egaP

permissionsdefinedbythe'Internet'namedpermissionset.(Naturallythe 'Internet'namedpermissionsetrepresentsaveryrestrictiverangeof permissions.)

8.3WhodefinestheCAScodegroups?
Microsoftdefinessomedefaultones,butyoucanmodifytheseandeven createyourown.Toseethecodegroupsdefinedonyoursystem,run'caspol lg'fromthecommandline.Onmysystemitlookslikethis:
Level=Machine CodeGroups: 1.Allcode:Nothing 1.1.ZoneMyComputer:FullTrust 1.1.1.HonorSkipVerificationrequests:SkipVerification 1.2.ZoneIntranet:LocalIntranet 1.3. ZoneInternet:Internet 1.4.ZoneUntrusted:Nothing 1.5.ZoneTrusted:Internet 1.6.StrongName 0024000004800000940000000602000000240000525341310004000003 000000CFCB3291AA715FE99D40D49040336F9056D7886FED46775BC7BB5430BA4444FEF834 8EBD06 F962F39776AE4DC3B7B04A7FE6F49F25F740423EBF2C0B89698D8D08AC48D69CED0FC8F83B 465E08 07AC11EC1DCC7D054E807A43336DDE408A5393A48556123272CEEEE72F1660B71927D3856 1AABF5C AC1DF1734633C602F8F2D5:Everything

Notethehierarchyofcodegroupsthetopofthehierarchyisthemost general('Allcode'),whichisthensubdividedintoseveralgroups,eachof whichinturncanbesubdivided.Alsonotethat(somewhatcounter intuitively)asubgroupcanbeassociatedwithamorepermissivepermission setthanitsparent.

8.4HowdoIdefinemyowncodegroup?
Usecaspol.Forexample,supposeyoutrustcodefromwww.mydomain.com andyouwantithavefullaccesstoyoursystem,butyouwanttokeepthe defaultrestrictionsforallotherinternetsites.Toachievethis,youwouldadda newcodegroupasasubgroupofthe'ZoneInternet'group,likethis:
caspolag1.3sitewww.mydomain.comFullTrust

Nowifyouruncaspollgyouwillseethatthenewgrouphasbeenaddedas group1.3.1:
... 1.3.ZoneInternet:Internet 1.3.1.Sitewww.mydomain.com:FullTrust ...

001 fo 17 egaP

Notethatthenumericlabel(1.3.1)isjustacaspolinventiontomakethecode groupseasytomanipulatefromthecommandline.Theunderlyingruntime neverseesit.

8.5HowdoIchangethepermissionsetforacodegroup?
Usecaspol.Ifyouarethemachineadministrator,youcanoperateatthe 'machine'levelwhichmeansnotonlythatthechangesyoumakebecomethe defaultforthemachine,butalsothatuserscannotchangethepermissionsto bemorepermissive.Ifyouareanormal(nonadmin)useryoucanstillmodify thepermissions,butonlytomakethemmorerestrictive.Forexample,to allowintranetcodetodowhatitlikesyoumightdothis:
caspolcg1.2FullTrust

Notethatbecausethisismorepermissivethanthedefaultpolicy(ona standardsystem),youshouldonlydothisatthemachineleveldoingitat theuserlevelwillhavenoeffect.

8.6CanIcreatemyownpermissionset?
Yes.Usecaspolap,specifyinganXMLfilecontainingthepermissionsinthe permissionset.Tosaveyousometime,hereisasamplefilecorrespondingto the'Everything'permissionsetjustedittosuityourneeds.Whenyouhave editedthesample,addittotherangeofavailablepermissionsetslikethis:
caspolapsamplepermset.xml

Then,toapplythepermissionsettoacodegroup,dosomethinglikethis:
caspolcg1.3SamplePermSet

(Bydefault,1.3isthe'Internet'codegroup)

8.7I'mhavingsometroublewithCAS.HowcanIdiagnosemy problem?
Caspolhasacoupleofoptionsthatmighthelp.First,youcanaskcaspoltotell youwhatcodegroupanassemblybelongsto,usingcaspolrsg.Similarly,you canaskwhatpermissionsarebeingappliedtoaparticularassemblyusing caspolrsp.

8.8Ican'tbebotheredwithallthisCASstuff.CanIturnitoff?
Yes,aslongasyouareanadministrator.Justrun:
caspolsoff

9.IntermediateLanguage(IL)
001 fo 27 egaP

9.1CanIlookattheILforanassembly?
Yes.MSsupplyatoolcalledIldasmwhichcanbeusedtoviewthemetadata andILforanassembly.

9.2CansourcecodebereverseengineeredfromIL?
Yes,itisoftenrelativelystraightforwardtoregeneratehighlevelsource(e.g. C#)fromIL.

9.3HowcanIstopmycodebeingreverseengineeredfrom IL?
Thereiscurrentlynosimplewaytostopcodebeingreverseengineeredfrom IL.InfutureitislikelythatILobfuscationtoolswillbecomeavailable,either fromMSorfromthirdparties.Thesetoolsworkby'optimising'theILinsucha waythatreverseengineeringbecomesmuchmoredifficult. Ofcourseifyouarewritingwebservicesthenreverseengineeringisnota problemasclientsdonothaveaccesstoyourIL.

9.4CanIwriteILprogramsdirectly?
Yes.PeterDraytonpostedthissimpleexampletotheDOTNETmailinglist:
.assemblyMyAssembly{} .classMyApp{ .methodstaticvoidMain(){ .entrypoint ldstr"Hello,IL!" callvoidSystem.Console::WriteLine(classSystem.Object) ret } }

Justputthisintoafilecalledhello.il,andthenrunilasmhello.il.Anexe assemblywillbegenerated.

9.5CanIdothingsinILthatIcan'tdoinC#?
Yes.Acoupleofsimpleexamplesarethatyoucanthrowexceptionsthatare notderivedfromSystem.Exception,andyoucanhavenonzerobasedarrays.

10.ImplicationsforCOM
10.1IsCOMdead?
Thissubjectcausesalotofcontroversy,asyou'llseeifyoureadthemailing listarchives.Takealookatthefollowingtwothreads:

001 fo 37 egaP

http://discuss.develop.com/archives/wa.exe?A2=ind0007&L=DOTNET&D=0&P =68241 http://discuss.develop.com/archives/wa.exe?A2=ind0007&L=DOTNET&P=R60 761 FWIWmyviewisasfollows:COMismanythings,andit'sdifferentthingsto differentpeople.Buttome,COMisfundamentallyabouthowlittleblobsof codefindotherlittleblobsofcode,andhowtheycommunicatewitheachother whentheyfindeachother.COMspecifiespreciselyhowthislocationand communicationtakesplace.Ina'pure'.NETworld,consistingentirelyof.NET objects,littleblobsofcodestillfindeachotherandtalktoeachother,butthey don'tuseCOMtodoso.TheyuseamodelwhichissimilartoCOMinsome waysforexample,typeinformationisstoredinatabularformpackagedwith thecomponent,whichisquitesimilartopackagingatypelibrarywithaCOM component.Butit'snotCOM. So,doesthismatter?Well,Idon'treallycareaboutmostoftheCOMstuff goingawayIdon'tcarethatfindingcomponentsdoesn'tinvolveatriptothe registry,orthatIdon'tuseIDLtodefinemyinterfaces.Butthereisonething thatIwouldn'tliketogoawayIwouldn'tliketolosetheideaofinterface baseddevelopment.COM'sgreateststrength,inmyopinion,isitsinsistence onacastironseparationbetweeninterfaceandimplementation. Unfortunately,the.NETframeworkseemstomakenosuchinsistenceitlets youdointerfacebaseddevelopment,butitdoesn'tinsist.Somepeoplewould arguethathavingachoicecanneverbeabadthing,andmaybethey'reright, butIcan'thelpfeelingthatmaybeit'sabackwardstep.

10.2IsDCOMdead?
Prettymuch,for.NETdevelopers.The.NETFrameworkhasanewremoting modelwhichisnotbasedonDCOM.OfcourseDCOMwillstillbeusedin interopscenarios.

10.3IsMTS/COM+dead?
No.Theapproachforthefirst.NETreleaseistoprovideaccesstotheexisting COM+services(throughaninteroplayer)ratherthanreplacetheserviceswith native.NETones.Varioustoolsandattributesareprovidedtotrytomakethis aspainlessaspossible.ThePDCreleaseofthe.NETSDKincludesinterop supportforcoreservices(JITactivation,transactions)butnotsomeofthe higherlevelservices(e.g.COM+Events,Queuedcomponents). Overtimeitisexpectedthatinteropwillbecomemoreseamlessthismay meanthatsomeservicesbecomeacorepartoftheCLR,and/oritmaymean thatsomeserviceswillberewrittenasmanagedcodewhichrunsontopofthe CLR. Formoreonthistopic,searchforpostingsbyJoeLonginthearchivesJoeis theMSgroupmanagerforCOM+.Startwiththismessage:
001 fo 47 egaP

http://discuss.develop.com/archives/wa.exe?A2=ind0007&L=DOTNET&P=R68 370

10.4CanIuseCOMcomponentsfrom.NETprograms?
Yes.COMcomponentsareaccessedfromthe.NETruntimeviaaRuntime CallableWrapper(RCW).ThiswrapperturnstheCOMinterfacesexposedby theCOMcomponentinto.NETcompatibleinterfaces.Foroleautomation interfaces,theRCWcanbegeneratedautomaticallyfromatypelibrary.For nonoleautomationinterfaces,itmaybenecessarytodevelopacustomRCW whichmanuallymapsthetypesexposedbytheCOMinterfaceto.NET compatibletypes. Here'sasimpleexampleforthosefamiliarwithATL.First,createanATL componentwhichimplementsthefollowingIDL:
import"oaidl.idl" import"ocidl.idl" [ object, uuid(EA013F93487A440386ECFD9FEE5E6206), helpstring("ICppNameInterface"), pointer_default(unique), oleautomation ] interfaceICppName:IUnknown { [helpstring("methodSetName")]HRESULTSetName([in]BSTRname) [helpstring("methodGetName")]HRESULTGetName([out,retval]BSTR*pName) } [ uuid(F5E4C61DD93A4295A4B42453D4A4484D), version(1.0), helpstring("cppcomserver1.0TypeLibrary") ] libraryCPPCOMSERVERLib { importlib("stdole32.tlb") importlib("stdole2.tlb") [ uuid(600CE6D95ED74B4DBB49E8D5D5096F70), helpstring("CppNameClass") ] coclassCppName { [default]interfaceICppName } }

Whenyou'vebuiltthecomponent,youshouldgetatypelibrary.Runthe TLBIMPutilityonthetypelibary,likethis:

001 fo 57 egaP

tlbimpcppcomserver.tlb

Ifsuccessful,youwillgetamessagelikethis:
TypelibimportedsuccessfullytoCPPCOMSERVERLib.dll

Younowneeda.NETclientlet'suseC#.Createa.csfilecontainingthe followingcode:
usingSystem usingCPPCOMSERVERLib publicclassMainApp { staticpublicvoidMain() { CppNamecppname=newCppName() cppname.SetName("bob") Console.WriteLine("Nameis"+cppname.GetName()) } }

Notethatweareusingthetypelibrarynameasanamespace,andtheCOM classnameastheclass.Alternativelywecouldhaveused CPPCOMSERVERLib.CppNamefortheclassnameandgonewithouttheusing CPPCOMSERVERLibstatement. CompiletheC#codelikethis:


csc/r:cppcomserverlib.dllcsharpcomclient.cs

NotethatthecompilerisbeingtoldtoreferencetheDLLwepreviously generatedfromthetypelibraryusingTLBIMP. Youshouldnowbeabletoruncsharpcomclient.exe,andgetthefollowing outputontheconsole:


Nameisbob

10.5CanIuse.NETcomponentsfromCOMprograms?
Yes..NETcomponentsareaccessedfromCOMviaaCOMCallableWrapper (CCW).ThisissimilartoaRCW(seepreviousquestion),butworksinthe oppositedirection.Again,ifthewrappercannotbeautomaticallygeneratedby the.NETdevelopmenttools,oriftheautomaticbehaviourisnotdesirable,a customCCWcanbedeveloped.Also,forCOMto'see'the.NETcomponent, the.NETcomponentmustberegisteredintheregistry. Here'sasimpleexample.CreateaC#filecalledtestcomserver.csandputthe followinginit:
usingSystem
001 fo 67 egaP

usingSystem.Runtime.InteropServices namespaceAndyMc { [ClassInterface(ClassInterfaceType.AutoDual)] publicclassCSharpCOMServer { publicCSharpCOMServer(){} publicvoidSetName(stringname){m_name=name} publicstringGetName(){returnm_name} privatestringm_name } }

Thencompilethe.csfileasfollows:
csc/target:librarytestcomserver.cs

Youshouldgetadll,whichyouregisterlikethis:
regasmtestcomserver.dll/tlb:testcomserver.tlb/codebase

Nowyouneedtocreateaclienttotestyour.NETCOMcomponent.VBScript willdoputthefollowinginafilecalledcomclient.vbs:
DimdotNetObj SetdotNetObj=CreateObject("AndyMc.CSharpCOMServer") dotNetObj.SetName("bob") MsgBox"Nameis"&dotNetObj.GetName()

andrunthescriptlikethis:
wscriptcomclient.vbs

Andheyprestoyoushouldgetamessageboxdisplayedwiththetext"Name isbob". Analternativetotheapproachaboveittousethedm.netmonikerdeveloped byJasonWhittingtonandDonBox.Goto http://staff.develop.com/jasonw/clr/readme.htmtocheckitout.

10.6IsATLredundantinthe.NETworld?
Yes,ifyouarewritingapplicationsthatliveinsidethe.NETframework.Of coursemanydevelopersmaywishtocontinueusingATLtowriteC++COM componentsthatliveoutsidetheframework,butifyouareinsideyouwill almostcertainlywanttouseC#.RawC++(andthereforeATLwhichisbased onit)doesn'thavemuchofaplaceinthe.NETworldit'sjusttoonearthe metalandprovidestoomuchflexibilityfortheruntimetobeabletomanage it.

11.Miscellaneous
001 fo 77 egaP

11.1Howdoes.NETremotingwork?
.NETremotinginvolvessendingmessagesalongchannels.Twoofthestandard channelsareHTTPandTCP.TCPisintendedforLANsonlyHTTPcanbeused forLANsorWANs(internet). Supportisprovidedformultiplemessageserializarionformats.Examplesare SOAP(XMLbased)andbinary.Bydefault,theHTTPchannelusesSOAP(via the.NETruntimeSerializationSOAPFormatter),andtheTCPchanneluses binary(viathe.NETruntimeSerializationBinaryFormatter).Buteither channelcanuseeitherserializationformat. Thereareanumberofstylesofremoteaccess:

SingleCall.Eachincomingrequestfromaclientisservicedbyanew object.Theobjectisthrownawaywhentherequesthasfinished. Singleton.Allincomingrequestsfromclientsareprocessedbyasingle serverobject. Clientactivatedobject.Thisistheoldstateful(D)COMmodelwhereby theclientreceivesareferencetotheremoteobjectandholdsthat reference(thuskeepingtheremoteobjectalive)untilitisfinishedwith it.

Distributedgarbagecollectionofobjectsismanagedbyasystemcalled'leased basedlifetime'.Eachobjecthasaleasetime,andwhenthattimeexpiresthe objectisdisconnectedfromthe.NETruntimeremotinginfrastructure.Objects haveadefaultrenewtimetheleaseisrenewedwhenasuccessfulcallis madefromtheclienttotheobject.Theclientcanalsoexplicitlyrenewthe lease. Ifyou'reinterestedinusingXMLRPCasanalternativetoSOAP,takealookat CharlesCook'sXMLRPC.Netsiteat http://www.cookcomputing.com/xmlrpc/xmlrpc.shtml.

11.2HowcanIgetattheWin32APIfroma.NETprogram?
UseP/Invoke.ThisusessimilartechnologytoCOMInterop,butisusedto accessstaticDLLentrypointsinsteadofCOMobjects.Hereisanexampleof C#callingtheWin32MessageBoxfunction:
usingSystem usingSystem.Runtime.InteropServices classMainApp { [DllImport("user32.dll",EntryPoint="MessageBox",SetLastError=true, CharSet=CharSet.Auto)] publicstaticexternintMessageBox(inthWnd,StringstrMessage,StringstrCaption, uintuiType)
001 fo 87 egaP

publicstaticvoidMain() { MessageBox(0,"Hello,thisisPInvokeinoperation!",".NET",0) } }

12.ClassLibrary
12.1FileI/O
12.1.1HowdoIreadfromatextfile? First,useaSystem.IO.FileStreamobjecttoopenthefile:
FileStreamfs=newFileStream(@"c:\test.txt",FileMode.Open,FileAccess.Read)

FileStreaminheritsfromStream,soyoucanwraptheFileStreamobjectwitha StreamReaderobject.Thisprovidesaniceinterfaceforprocessingthestream linebyline:


StreamReadersr=newStreamReader(fs) stringcurLine while((curLine=sr.ReadLine())!=null) Console.WriteLine(curLine)

FinallyclosetheStreamReaderobject:
sr.Close()

NotethatthiswillautomaticallycallClose()ontheunderlyingStreamobject, soanexplicitfs.Close()isnotrequired. 12.1.2HowdoIwritetoatextfile? Similartothereadexample,exceptuseStreamWriterinsteadof StreamReader. 12.1.3HowdoIread/writebinaryfiles? Similartotextfiles,exceptwraptheFileStreamobjectwitha BinaryReader/WriterobjectinsteadofaStreamReader/Writerobject.

12.2TextProcessing
12.2.1Areregularexpressionssupported? Yes.UsetheSystem.Text.RegularExpressions.Regexclass.Forexample,the followingcodeupdatesthetitleinanHTMLfile:
FileStreamfs=newFileStream("test.htm",FileMode.Open,FileAccess.Read) StreamReadersr=newStreamReader(fs)
001 fo 97 egaP

Regexr=newRegex("<TITLE>(.*)</TITLE>") strings while((s=sr.ReadLine())!=null) { if(r.IsMatch(s)) s=r.Replace(s,"<TITLE>Newandimproved${1}</TITLE>") Console.WriteLine(s) }

12.3Internet
12.3.1HowdoIdownloadawebpage? FirstusetheSystem.Net.WebRequestFactoryclasstoacquireaWebRequest object:
WebRequestrequest=WebRequest.Create("http://localhost")

Thenaskfortheresponsefromtherequest:
WebResponseresponse=request.GetResponse()

TheGetResponsemethodblocksuntilthedownloadiscomplete.Thenyoucan accesstheresponsestreamlikethis:
Streams=response.GetResponseStream() //Outputthedownloadedstreamtotheconsole StreamReadersr=newStreamReader(s) stringline while((line=sr.ReadLine())!=null) Console.WriteLine(line)

NotethatWebRequestandWebReponseobjectscanbedowncastto HttpWebRequestandHttpWebReponseobjectsrespectively,toaccesshttp specificfunctionality. 12.3.2HowdoIuseaproxy? Twoapproachestoaffectallwebrequestsdothis:


System.Net.GlobalProxySelection.Select=newWebProxy("proxyname",80)

Alternatively,tosettheproxyforaspecificwebrequest,dothis:
HttpWebRequestrequest=(HttpWebRequest)WebRequest.Create("http://localhost") request.Proxy=newWebProxy("proxyname",80)

12.4XML
12.4.1IsDOMsupported?

001 fo 08 egaP

Yes.TakethisexampleXMLdocument:
<PEOPLE> <PERSON>Fred</PERSON> <PERSON>Bill</PERSON> </PEOPLE>

Thisdocumentcanbeparsedasfollows:
XmlDocumentdoc=newXmlDocument() doc.Load("test.xml") XmlNoderoot=doc.DocumentElement foreach(XmlNodepersonElementinroot.ChildNodes) Console.WriteLine(personElement.FirstChild.Value.ToString())

Theoutputis:
Fred Bill

12.4.2IsSAXsupported? No.Instead,anewXmlReader/XmlWriterAPIisoffered.LikeSAXitisstream basedbutitusesa'pull'modelratherthanSAX's'push'model.Here'san example:


XmlTextReaderreader=newXmlTextReader("test.xml") while(reader.Read()) { if(reader.NodeType==XmlNodeType.Element&&reader.Name=="PERSON") { reader.Read()//Skiptothechildtext Console.WriteLine(reader.Value) } }

12.4.3IsXPathsupported? Yes,viatheXPathXXXclasses:
XPathDocumentxpdoc=newXPathDocument("test.xml") XPathNavigatornav=xpdoc.CreateNavigator() XPathExpressionexpr=nav.Compile("descendant::PEOPLE/PERSON") XPathNodeIteratoriterator=nav.Select(expr) while(iterator.MoveNext()) Console.WriteLine(iterator.Current)

12.5Threading
12.5.1Ismultithreadingsupported?

001 fo 18 egaP

Yes,thereisextensivesupportformultithreading.Newthreadscanbe spawned,andthereisasystemprovidedthreadpoolwhichapplicationscan use. 12.5.2HowdoIspawnathread? CreateaninstanceofaSystem.Threading.Threadobject,passingitan instanceofaThreadStartdelegatethatwillbeexecutedonthenewthread. Forexample:


classMyThread { publicMyThread(stringinitData) { m_data=initData m_thread=newThread(newThreadStart(ThreadMain)) m_thread.Start() } //ThreadMain()isexecutedonthenewthread. privatevoidThreadMain() { Console.WriteLine(m_data) } publicvoidWaitUntilFinished() { m_thread.Join() } privateThreadm_thread privatestringm_data }

InthiscasecreatinganinstanceoftheMyThreadclassissufficienttospawn thethreadandexecutetheMyThread.ThreadMain()method:
MyThreadt=newMyThread("Hello,world.") t.WaitUntilFinished()

12.5.3HowdoIstopathread? Thereareseveraloptions.First,youcanuseyourowncommunication mechanismtotelltheThreadStartmethodtofinish.AlternativelytheThread classhasinbuiltsupportforinstructingthethreadtostop.Thetwoprinciple methodsareThread.Interrupt()andThread.Abort().Theformerwillcausea ThreadInterruptedExceptiontobethrownonthethreadwhenitnextgoesinto aWaitJoinSleepstate.Inotherwords,Thread.Interruptisapolitewayof askingthethreadtostopwhenitisnolongerdoinganyusefulwork.In contrast,Thread.Abort()throwsaThreadAbortExceptionregardlessofwhat thethreadisdoing.Furthermore,theThreadAbortExceptioncannotnormally becaught(thoughtheThreadStart'sfinallymethodwillbeexecuted). Thread.Abort()isaheavyhandedmechanismwhichshouldnotnormallybe required.
001 fo 28 egaP

12.5.4HowdoIusethethreadpool? BypassinganinstanceofaWaitCallbackdelegatetothe ThreadPool.QueueUserWorkItem()method:


classCApp { staticvoidMain() { strings="Hello,World" ThreadPool.QueueUserWorkItem(newWaitCallback(DoWork),s) Thread.Sleep(1000) } //DoWorkisexecutedonathreadfromthethreadpool. staticvoidDoWork(objectstate) { Console.WriteLine(state) } } //Givetimeforworkitemtobeexecuted

12.5.5HowdoIknowwhenmythreadpoolworkitemhascompleted? Thereisnowaytoquerythethreadpoolforthisinformation.Youmustput codeintotheWaitCallbackmethodtosignalthatithascompleted.Eventsare usefulforthis. 12.5.6HowdoIpreventconcurrentaccesstomydata? Eachobjecthasaconcurrencylock(criticalsection)associatedwithit.The System.Threading.Monitor.Enter/Exitmethodsareusedtoacquireandrelease thislock.Forexample,instancesofthefollowingclassonlyallowonethreadat atimetoentermethodf():


classC { publicvoidf() { try { Monitor.Enter(this) ... } finally { Monitor.Exit(this) } } }

C#hasa'lock'keywordwhichprovidesaconvenientshorthandforthecode above:
classC
001 fo 38 egaP

{ publicvoidf() { lock(this) { ... } } }

NotethatcallingMonitor.Enter(myObject)doesNOTmeanthatallaccessto myObjectisserialized.Itmeansthatthesynchronisationlockassociatedwith myObjecthasbeenacquired,andnootherthreadcanacquirethatlockuntil Monitor.Exit(o)iscalled.Inotherwords,thisclassisfunctionallyequivalentto theclassesabove:


classC { publicvoidf() { lock(m_object) { ... } } privatem_object=newobject() }

12.6Tracing
12.6.1Istherebuiltinsupportfortracing/logging? Yes,intheSystem.Diagnosticsnamespace.Therearetwomainclassesthat dealwithtracingDebugandTrace.Theybothworkinasimilarwaythe differenceisthattracingfromtheDebugclassonlyworksinbuildsthathave theDEBUGsymboldefined,whereastracingfromtheTraceclassonlyworksin buildsthathavetheTRACEsymboldefined.Typicallythismeansthatyou shoulduseSystem.Diagnostics.Trace.WriteLinefortracingthatyouwantto workindebugandreleasebuilds,andSystem.Diagnostics.Debug.WriteLinefor tracingthatyouwanttoworkonlyindebugbuilds. 12.6.2CanIredirecttracingtoafile? Yes.TheDebugandTraceclassesbothhaveaListenersproperty,whichisa collectionofsinksthatreceivethetracingthatyousendviaDebug.WriteLine andTrace.WriteLinerespectively.BydefaulttheListenerscollectioncontainsa singlesink,whichisaninstanceoftheDefaultTraceListenerclass.Thissends outputtotheWin32OutputDebugString()functionandalsothe System.Diagnostics.Debugger.Log()method.Thisisusefulwhendebugging, butifyou'retryingtotraceaproblematacustomersite,redirectingthe outputtoafileismoreappropriate.Fortunately,theTextWriterTraceListener classisprovidedforthispurpose.
001 fo 48 egaP

Here'showtousetheTextWriterTraceListenerclasstoredirectTraceoutputto afile:
Trace.Listeners.Clear() FileStreamfs=newFileStream(@"c:\log.txt",FileMode.Create,FileAccess.Write) Trace.Listeners.Add(newTextWriterTraceListener(fs)) Trace.WriteLine(@"Thiswillbewritentoc:\log.txt!") Trace.Flush()

NotetheuseofTrace.Listeners.Clear()toremovethedefaultlistener.Ifyou don'tdothis,theoutputwillgotothefileandOutputDebugString().Typically thisisnotwhatyouwant,becauseOutputDebugString()imposesabig performancehit. 12.6.3CanIcustomisethetraceoutput? Yes.YoucanwriteyourownTraceListenerderivedclass,anddirectalloutput throughit.Here'sasimpleexample,whichderivesfrom TextWriterTraceListener(andthereforehasinbuiltsupportforwritingtofiles, asshownabove)andaddstiminginformationandthethreadIDforeachtrace line:
classMyListener:TextWriterTraceListener { publicMyListener(Streams):base(s) { } publicoverridevoidWriteLine(strings) { Writer.WriteLine("{0:D8}[{1:D4}]{2}", Environment.TickCountm_startTickCount, AppDomain.GetCurrentThreadId(), s) } protectedintm_startTickCount=Environment.TickCount }

(NotethatthisimplementationisnotcompletetheTraceListener.Write methodisnotoverriddenforexample.) ThebeautyofthisapproachisthatwhenaninstanceofMyListenerisaddedto theTrace.Listenerscollection,allcallstoTrace.WriteLine()gothrough MyListener,includingcallsmadebyreferencedassembliesthatknownothing abouttheMyListenerclass.

13.Resources
13.1Recommendedbooks

001 fo 58 egaP

Irecommendthefollowingbooks,eitherbecauseIpersonallylikethem,or becauseIthinktheyarewellregardedbyother.NETdevelopers.(NotethatI getacommissionfromAmazonifyoubuyabookafterfollowingoneofthese links.)

AppliedMicrosoft.NETFrameworkProgrammingJeffreyRichter Muchanticipated,mainlyduetoRichter'ssuperbWin32books,andmost peoplethinkitdelivers.The'applied'isalittlemisleadingthisbookis mostlyabouthowthe.NETFrameworkworks'underthehood'. ExamplesareinC#,butthereisalsoaseparateVBeditionofthebook. Essential.NETVolume1,TheCommonLanguageRuntimeDonBox Asuperbbook,whichIrecommendtoanyonewhoalreadyhassome .NETdevelopmentexperience,andwantstogetadeeperunderstanding ofCLRfundamentals.It'sclearthatBoxhasdeeplyresearchedthe topicsandthencarefullyconstructedacoherentstoryaroundhis findings.It'sraretofindsuchcraftina.NETtext. C#andthe.NETPlatform,2ndEditionAndrewTroelsen RegardedbymanyasthebestallroundC#/.NETbook.Widecoverage includingWindowsForms,COMinterop,ADO.NET,ASP.NETetc.Troelsen alsohasarespectedVB.NETbookcalledVisualBasic.NETandthe.NET Platform:AnAdvancedGuide. ProgrammingWindowswithC#CharlesPetzold AnotherslightlymisleadingtitlethisbookissolelyaboutGUI programmingWindowsFormsandGDI+.Wellwritten,with comprehensivecoverage.Myonly(minor)criticismisthatthebook stickscloselytothefacts,withoutofferingagreatdealinthewayof 'tipsandtricks'forrealworldapps. WindowsFormsProgramminginC#ChrisSells Ihaven'treadthismyselfyet,butanythingSellswritesisusuallyworth reading. DevelopingApplicationswithVisualStudio.NETRichardGrimes Coverslotsofinterestingtopicsthatotherbooksdon't,includingATL7, ManagedC++,internationalization,remoting,aswellasthemorerun ofthemillCLRandC#stuff.AlsoalotofinfoontheVisualStudioIDE. ThisbookismostsuitableforreasonablyexperiencedC++ programmers. ProgrammingMicrosoftVisualBasic.NETFrancescoBalena BalenaisareknownedVBer,andthereviewsofhisVB.NETbookare glowing. .NETandCOMTheCompleteInteroperabilityGuideAdamNathan Don'tbeputoffbythesizethisbookisveryeasytodigestthanksto

001 fo 68 egaP

thesuperbwritingstyle.Thebibleof.NET/COMinterop.

Advanced.NETRemotingIngoRammer Widelyrecommended.

13.2InternetResources

TheMicrosoft.NEThomepageisathttp://www.microsoft.com/net/. MicrosoftalsohostGOTDOTNET. DevXhostthe.NETZone. http://www.cetuslinks.org/oo_dotnet.htmlisasuperbsetoflinksto .NETresources. ChrisSellshasagreatsetof.NETlinksat http://www.sellsbrothers.com/links/#manlinks. CSharp.org microsoft.public.dotnet.*newsgroups MyC#FAQforC++Programmers.

13.3Weblogs
ThefollowingWeblogs('blogs')haveregular.NETcontent:

The.NETGuy(BradWilson) CharlesCook:DeveloperofXMLRPC.NET. GwynCole:CoauthorofDevelopingWMIsolutions. ChrisBrumme BradAbrams DonBox JohnLam PeterDrayton:CoauthorofC#EssentialsandC#inaNutshell. IngoRammer:AuthorofAdvanced.NETremoting. DrewMarsh TomasRestrepo JustinRudd SimonFell:DeveloperofPocketSOAP. RichardCaetano ChrisSells

13.4Samplecode&utilities
LutzRoederhassomegreatutilitiesandlibrariesat http://www.aisto.com/roeder/dotnet/ PeterDrayton's.NETGoodiespageisathttp://www.razorsoft.net/ DonBox&JasonWhittington'sdm.netCOMmonikerat http://staff.develop.com/jasonw/clr/readme.htm

001 fo 78 egaP

MikeWoodringhassome.NETsamplesat http://staff.develop.com/woodring/dotnet/ CharlesCook'sXMLRPC.Netlibraryisavailableat http://www.cookcomputing.com/. MicrosoftSQLServer#InterviewQuestions(lastupdatedon


TransactSQLOptimizationTips IndexOptimizationtips TSQLQueries DataTypes Index Joins Lock StoredProcedure Trigger View Transaction Other XML Tools Permission Administration

TransactSQLOptimizationTips

Useviewsandstoredproceduresinsteadofheavydutyqueries. Thiscanreducenetworktraffic,becauseyourclientwillsendtoserver onlystoredprocedureorviewname(perhapswithsomeparameters) insteadoflargeheavydutyqueriestext.Thiscanbeusedtofacilitate permissionmanagementalso,becauseyoucanrestrictuseraccessto tablecolumnstheyshouldnotsee. Trytouseconstraintsinsteadoftriggers,wheneverpossible. Constraintsaremuchmoreefficientthantriggersandcanboost performance.So,youshoulduseconstraintsinsteadoftriggers, wheneverpossible. Usetablevariablesinsteadoftemporarytables. Tablevariablesrequirelesslockingandloggingresourcesthan temporarytables,sotablevariablesshouldbeusedwheneverpossible. ThetablevariablesareavailableinSQLServer2000only. TrytouseUNIONALLstatementinsteadofUNION,whenever possible. TheUNIONALLstatementismuchfasterthanUNION,becauseUNION ALLstatementdoesnotlookforduplicaterows,andUNIONstatement doeslookforduplicaterows,whetherornottheyexist. TrytoavoidusingtheDISTINCTclause,wheneverpossible. BecauseusingtheDISTINCTclausewillresultinsomeperformance degradation,youshouldusethisclauseonlywhenitisnecessary.
001 fo 88 egaP

TrytoavoidusingSQLServercursors,wheneverpossible. SQLServercursorscanresultinsomeperformancedegradationin comparisonwithselectstatements.Trytousecorrelatedsubqueryor derivedtables,ifyouneedtoperformrowbyrowoperations. TrytoavoidtheHAVINGclause,wheneverpossible. TheHAVINGclauseisusedtorestricttheresultsetreturnedbythe GROUPBYclause.WhenyouuseGROUPBYwiththeHAVINGclause,the GROUPBYclausedividestherowsintosetsofgroupedrowsand aggregatestheirvalues,andthentheHAVINGclauseeliminates undesiredaggregatedgroups.Inmanycases,youcanwriteyourselect statementso,thatitwillcontainonlyWHEREandGROUPBYclauses withoutHAVINGclause.Thiscanimprovetheperformanceofyour query. Ifyouneedtoreturnthetotaltable'srowcount,youcanuse alternativewayinsteadofSELECTCOUNT(*)statement. BecauseSELECTCOUNT(*)statementmakeafulltablescantoreturn thetotaltable'srowcount,itcantakeverymanytimeforthelarge table.Thereisanotherwaytodeterminethetotalrowcountinatable. Youcanusesysindexessystemtable,inthiscase.ThereisROWS columninthesysindexestable.Thiscolumncontainsthetotalrowcount foreachtableinyourdatabase.So,youcanusethefollowingselect statementinsteadofSELECTCOUNT(*):SELECTrowsFROMsysindexes WHEREid=OBJECT_ID('table_name')ANDindid<2So,youcan improvethespeedofsuchqueriesinseveraltimes. IncludeSETNOCOUNTONstatementintoyourstoredprocedures tostopthemessageindicatingthenumberofrowsaffectedbya TSQLstatement. Thiscanreducenetworktraffic,becauseyourclientwillnotreceivethe messageindicatingthenumberofrowsaffectedbyaTSQLstatement. TrytorestrictthequeriesresultsetbyusingtheWHEREclause. Thiscanresultsingoodperformancebenefits,becauseSQLServerwill returntoclientonlyparticularrows,notallrowsfromthetable(s).This canreducenetworktrafficandboosttheoverallperformanceofthe query. UsetheselectstatementswithTOPkeywordortheSET ROWCOUNTstatement,ifyouneedtoreturnonlythefirstn rows. Thiscanimproveperformanceofyourqueries,becausethesmaller resultsetwillbereturned.Thiscanalsoreducethetrafficbetweenthe serverandtheclients. Trytorestrictthequeriesresultsetbyreturningonlythe particularcolumnsfromthetable,notalltable'scolumns. Thiscanresultsingoodperformancebenefits,becauseSQLServerwill returntoclientonlyparticularcolumns,notalltable'scolumns.Thiscan reducenetworktrafficandboosttheoverallperformanceofthequery.

1.Indexes 2.avoidmorenumberoftriggersonthetable 3.unnecessarycomplicatedjoins


001 fo 98 egaP

4.correctuseofGroupbyclausewiththeselectlist 5.inworstcasesDenormalization IndexOptimizationtips

EveryindexincreasesthetimeintakestoperformINSERTS,UPDATES andDELETES,sothenumberofindexesshouldnotbeverymuch.Tryto usemaximum45indexesononetable,notmore.Ifyouhavereadonly table,thenthenumberofindexesmaybeincreased. Keepyourindexesasnarrowaspossible.Thisreducesthesizeofthe indexandreducesthenumberofreadsrequiredtoreadtheindex. Trytocreateindexesoncolumnsthathaveintegervaluesratherthan charactervalues. Ifyoucreateacomposite(multicolumn)index,theorderofthecolumns inthekeyareveryimportant.Trytoorderthecolumnsinthekeyasto enhanceselectivity,withthemostselectivecolumnstotheleftmostof thekey. Ifyouwanttojoinseveraltables,trytocreatesurrogateintegerkeys forthispurposeandcreateindexesontheircolumns. Createsurrogateintegerprimarykey(identityforexample)ifyourtable willnothavemanyinsertoperations. Clusteredindexesaremorepreferablethannonclustered,ifyouneedto selectbyarangeofvaluesoryouneedtosortresultssetwithGROUP BYorORDERBY. Ifyourapplicationwillbeperformingthesamequeryoverandoveron thesametable,considercreatingacoveringindexonthetable. YoucanusetheSQLServerProfilerCreateTraceWizardwith"Identify ScansofLargeTables"tracetodeterminewhichtablesinyourdatabase mayneedindexes.Thistracewillshowwhichtablesarebeingscanned byqueriesinsteadofusinganindex. Youcanusesp_MSforeachtableundocumentedstoredprocedureto rebuildallindexesinyourdatabase.Trytoscheduleittoexecuteduring CPUidletimeandslowproductionperiods. sp_MSforeachtable@command1="print'?'DBCCDBREINDEX('?')"

TSQLQueries
1. 2tables
EmployeePhone empid empname empid salary phnumber mgrid

2. Selectallemployeeswhodoesn'thavephone? SELECTempname FROMEmployee WHERE(empidNOTIN

001 fo 09 egaP

(SELECTDISTINCTempid FROMphone)) 3. Selecttheemployeenameswhoishavingmorethanonephone numbers. SELECTempname FROMemployee WHERE(empidIN (SELECTempid FROMphone GROUPBYempid HAVINGCOUNT(empid)>1)) 4. Selectthedetailsof3maxsalariedemployeesfromemployeetable. SELECTTOP3empid,salary FROMemployee ORDERBYsalaryDESC 5. Displayallmanagersfromthetable.(manageridissameasempid) SELECTempname FROMemployee WHERE(empidIN (SELECTDISTINCTmgrid FROMemployee)) 6. WriteaSelectstatementtolisttheEmployeeName,ManagerName underaparticularmanager? SELECTe1.empnameASEmpName,e2.empnameASManagerName FROMEmployeee1INNERJOIN Employeee2ONe1.mgrid=e2.empid ORDERBYe2.mgrid 7. 2tablesempandphone. empfieldsareempid,name Phfieldsareempid,ph(office,mobile,home).Selectallemployees whodoesn'thaveanyphnos. SELECT* FROMemployeeLEFTOUTERJOIN phoneONemployee.empid=phone.empid WHERE(phone.officeISNULLORphone.office='') AND(phone.mobileISNULLORphone.mobile='') AND(phone.homeISNULLORphone.home='') 8. Findemployeewhoislivinginmorethanonecity. TwoTables:
Emp Empid empName Salary City Empid City

9. SELECTempname,fname,lname FROMemployee WHERE(empidIN (SELECTempid FROMcity


001 fo 19 egaP

GROUPBYempid HAVINGCOUNT(empid)>1)) 10. Findallemployeeswhoislivinginthesamecity.(tableissameas above) SELECTfname FROMemployee WHERE(empidIN (SELECTempid FROMcitya WHEREcityIN (SELECTcity FROMcityb GROUPBYcity HAVINGCOUNT(city)>1))) 11. ThereisatablenamedMovieTablewiththreecolumns moviename,personandrole.Writeaquerywhichgetsthemoviedetails whereMr.AmitabhandMr.Vinodactedandtheirroleisactor. SELECTDISTINCTm1.moviename FROMMovieTablem1INNERJOIN MovieTablem2ONm1.moviename=m2.moviename WHERE(m1.person='amitabh'ANDm2.person='vinod'OR m2.person='amitabh'ANDm1.person='vinod')AND(m1.role= 'actor')AND(m2.role='actor') ORDERBYm1.moviename 12. Therearetwoemployeetablesnamedemp1andemp2.Both containssamestructure(salarydetails).ButEmp2salarydetailsare incorrectandemp1salarydetailsarecorrect.So,writeaquerywhich correctssalarydetailsofthetableemp2 updateaseta.sal=b.salfromemp1a,emp2bwherea.empid=b.empid 13. GivenaTablenamedStudentswhichcontainsstudentid, subjectidandmarks.Wherethereare10subjectsand50students. WriteaQuerytofindouttheMaximummarksobtainedineachsubject. 14. InthissametablesnowwriteaSQLQuerytogetthestudentid alsotocombinewithpreviousresults. 15. Threetablesstudent,course,markshowdogoatfinding nameofthestudentswhogotmaxmarksinthediffcourses. SELECTstudent.name,course.nameAScoursename,marks.sid, marks.mark FROMmarksINNERJOIN studentONmarks.sid=student.sidINNERJOIN courseONmarks.cid=course.cid WHERE(marks.mark= (SELECTMAX(Mark) FROMMarksMaxMark WHEREMaxMark.cID=Marks.cID)) 16. Thereisatableday_tempwhichhasthreecolumnsdayid,dayand temperature.HowdoIwriteaquerytogetthedifferenceof temperatureamongeachotherforsevendaysofaweek? SELECTa.dayid,a.dday,a.tempe,a.tempeb.tempeASDifference
001 fo 29 egaP

FROMday_tempaINNERJOIN day_tempbONa.dayid=b.dayid+1 OR Selecta.day,a.degreeb.degreefromtemperaturea,temperatureb wherea.id=b.id+1 17. Thereisatablewhichcontainsthenameslikethis.a1,a2,a3,a3, a4,a1,a1,a2andtheirsalaries.Writeaquerytogetgrandtotalsalary, andtotalsalariesofindividualemployeesinonequery. SELECTempid,SUM(salary)ASsalary FROMemployee GROUPBYempidWITHROLLUP ORDERBYempid 18. Howtoknowhowmanytablescontainsempnoasacolumn inadatabase? SELECTCOUNT(*)ASCounter FROMsyscolumns WHERE(name='empno') 19. Findduplicaterowsinatable?ORIhaveatablewithone columnwhichhasmanyrecordswhicharenotdistinct.Ineedto findthedistinctvaluesfromthatcolumnandnumberoftimesits repeated. SELECTsid,mark,COUNT(*)ASCounter FROMmarks GROUPBYsid,mark HAVING(COUNT(*)>1) 20. Howtodeletetherowswhichareduplicate(dontdelete bothduplicaterecords). SETROWCOUNT1 DELETEyourtable FROMyourtablea WHERE(SELECTCOUNT(*)FROMyourtablebWHEREb.name1= a.name1ANDb.age1=a.age1)>1 WHILE@@rowcount>0 DELETEyourtable FROMyourtablea WHERE(SELECTCOUNT(*)FROMyourtablebWHEREb.name1= a.name1ANDb.age1=a.age1)>1 SETROWCOUNT0 21. Howtofind6thhighestsalary SELECTTOP1salary FROM(SELECTDISTINCTTOP6salary FROMemployee ORDERBYsalaryDESC)a ORDERBYsalary 22. Findtopsalaryamongtwotables SELECTTOP1sal FROM(SELECTMAX(sal)ASsal FROMsal1 UNION
001 fo 39 egaP

SELECTMAX(sal)ASsal FROMsal2)a ORDERBYsalDESC 23. Writeaquerytoconvertallthelettersinawordtoupper case SELECTUPPER('test') 24. Writeaquerytoroundupthevaluesofanumber.For exampleeveniftheuserenters7.1itshouldberoundedupto8. SELECTCEILING(7.1) 25. WriteaSQLQuerytofindfirstdayofmonth? SELECTDATENAME(dw,DATEADD(dd,DATEPART(dd,GETDATE())+1, GETDATE()))ASFirstDay
Datepart year quarter month dayofyear day week weekday hour minute second millisecond Abbreviations yy,yyyy qq,q mm,m dy,y dd,d wk,ww dw hh mi,n ss,s ms

26. TableAcontainscolumn1whichisprimarykeyandhas2values (1,2)andTableBcontainscolumn1whichisprimarykeyandhas2 values(2,3).Writeaquerywhichreturnsthevaluesthatarenot commonforthetablesandthequeryshouldreturnonecolumnwith2 records. SELECTtbla.a FROMtbla,tblb WHEREtbla.a<> (SELECTtblb.a FROMtbla,tblb WHEREtbla.a=tblb.a) UNION SELECTtblb.a FROMtbla,tblb WHEREtblb.a<> (SELECTtbla.a FROMtbla,tblb WHEREtbla.a=tblb.a) OR(betterapproach) SELECTa
001 fo 49 egaP

FROMtbla WHEREaNOTIN (SELECTa FROMtblb) UNIONALL SELECTa FROMtblb WHEREaNOTIN (SELECTa FROMtbla) 27. Thereare3tablesTitles,AuthorsandTitleAuthors(checkPUBS db).Writethequerytogettheauthornameandthenumberofbooks writtenbythatauthor,theresultshouldstartfromtheauthorwhohas writtenthemaximumnumberofbooksandendwiththeauthorwhohas writtentheminimumnumberofbooks. SELECTauthors.au_lname,COUNT(*)ASBooksCount FROMauthorsINNERJOIN titleauthorONauthors.au_id=titleauthor.au_idINNERJOIN titlesONtitles.title_id=titleauthor.title_id GROUPBYauthors.au_lname ORDERBYBooksCountDESC 28. UPDATEemp_master SETemp_sal= CASE WHENemp_sal>0ANDemp_sal<=20000THEN(emp_sal*1.01) WHENemp_sal>20000THEN(emp_sal*1.02) END 29. Listallproductswithtotalquantityordered,ifquantityorderedis nullshowitas0. SELECTname,CASEWHENSUM(qty)ISNULLTHEN0WHENSUM(qty) >0THENSUM(qty)ENDAStot FROM[order]RIGHTOUTERJOIN productON[order].prodid=product.prodid GROUPBYname Result: coke60 mirinda0 pepsi10 30. ANY,SOME,orALL? ALLmeansgreaterthaneveryvalueinotherwords,greaterthanthe maximumvalue.Forexample,>ALL(1,2,3)meansgreaterthan3. ANYmeansgreaterthanatleastonevalue,thatis,greaterthanthe minimum.So>ANY(1,2,3)meansgreaterthan1.SOMEisanSQL92 standardequivalentforANY. 31. IN&=(differenceincorrelatedsubquery) INDEX

001 fo 59 egaP

32. WhatisIndex?Itspurpose? Indexesindatabasesaresimilartoindexesinbooks.Inadatabase,an indexallowsthedatabaseprogramtofinddatainatablewithout scanningtheentiretable.Anindexinadatabaseisalistofvaluesina tablewiththestoragelocationsofrowsinthetablethatcontaineach value.Indexescanbecreatedoneitherasinglecolumnora combinationofcolumnsinatableandareimplementedintheformofB trees.Anindexcontainsanentrywithoneormorecolumns(thesearch key)fromeachrowinatable.ABtreeissortedonthesearchkey,and canbesearchedefficientlyonanyleadingsubsetofthesearchkey.For example,anindexoncolumnsA,B,CcanbesearchedefficientlyonA, onA,B,andA,B,C. 33. ExplainaboutClusteredandnonclusteredindex?Howto choosebetweenaClusteredIndexandaNonClusteredIndex? Thereareclusteredandnonclusteredindexes.Aclusteredindexisa specialtypeofindexthatreordersthewayrecordsinthetableare physicallystored.Thereforetablecanhaveonlyoneclusteredindex.The leafnodesofaclusteredindexcontainthedatapages. Anonclusteredindexisaspecialtypeofindexinwhichthelogicalorder oftheindexdoesnotmatchthephysicalstoredorderoftherowson disk.Theleafnodesofanonclusteredindexdoesnotconsistofthedata pages.Instead,theleafnodescontainindexrows. Considerusingaclusteredindexfor: o Columnsthatcontainalargenumberofdistinctvalues. o Queriesthatreturnarangeofvaluesusingoperatorssuchas BETWEEN,>,>=,<,and<=. o Columnsthatareaccessedsequentially. o Queriesthatreturnlargeresultsets. NonclusteredindexeshavethesameBtreestructureasclustered indexes,withtwosignificantdifferences: o Thedatarowsarenotsortedandstoredinorderbasedontheir nonclusteredkeys. o Theleaflayerofanonclusteredindexdoesnotconsistofthedata pages.Instead,theleafnodescontainindexrows.Eachindexrow containsthenonclusteredkeyvalueandoneormorerowlocators thatpointtothedatarow(orrowsiftheindexisnotunique) havingthekeyvalue. o Pertableonly249nonclusteredindexes. 34. Disadvantageofindex? EveryindexincreasesthetimeintakestoperformINSERTS,UPDATES andDELETES,sothenumberofindexesshouldnotbeverymuch. 35. GivenascenariothatIhavea10ClusteredIndexinaTable toalltheir10Columns.Whataretheadvantagesand disadvantages? A:Only1clusteredindexispossible. 36. HowcanIenforcetouseparticularindex? Youcanuseindexhint(index=<index_name>)afterthetablename. SELECTau_lnameFROMauthors(index=aunmind)

001 fo 69 egaP

37. WhatisIndexTuning? Oneofthehardesttasksfacingdatabaseadministratorsistheselection ofappropriatecolumnsfornonclusteredindexes.Youshouldconsider creatingnonclusteredindexesonanycolumnsthatarefrequently referencedintheWHEREclausesofSQLstatements.Othergood candidatesarecolumnsreferencedbyJOINandGROUPBYoperations. Youmaywishtoalsoconsidercreatingnonclusteredindexesthatcover allofthecolumnsusedbycertainfrequentlyissuedqueries.These queriesarereferredtoascoveredqueriesandexperienceexcellent performancegains. IndexTuningistheprocessoffindingappropriatecolumnfornon clusteredindexes. SQLServerprovidesawonderfulfacilityknownastheIndexTuning Wizardwhichgreatlyenhancestheindexselectionprocess. 38. DifferencebetweenIndexdefragandIndexrebuild? Whenyoucreateanindexinthedatabase,theindexinformationused byqueriesisstoredinindexpages.Thesequentialindexpagesare chainedtogetherbypointersfromonepagetothenext.Whenchanges aremadetothedatathataffecttheindex,theinformationintheindex canbecomescatteredinthedatabase.Rebuildinganindexreorganizes thestorageoftheindexdata(andtabledatainthecaseofaclustered index)toremovefragmentation.Thiscanimprovediskperformanceby reducingthenumberofpagereadsrequiredtoobtaintherequested data DBCCINDEXDEFRAGDefragmentsclusteredandsecondaryindexesof thespecifiedtableorview. ** 39. Whatissortingandwhatisthedifferencebetweensorting &clusteredindexes? TheORDERBYclausesortsqueryresultsbyoneormorecolumnsupto 8,060bytes.Thiswillhappenbythetimewhenweretrievedatafrom database.Clusteredindexesphysicallysortingdata,while inserting/updatingthetable. 40. Whatarestatistics,underwhatcircumstancestheygoout ofdate,howdoyouupdatethem? Statisticsdeterminetheselectivityoftheindexes.Ifanindexedcolumn hasuniquevaluesthentheselectivityofthatindexismore,asopposed toanindexwithnonuniquevalues.Queryoptimizerusestheseindexes indeterminingwhethertochooseanindexornotwhileexecutinga query. Somesituationsunderwhichyoushouldupdatestatistics: 1)Ifthereissignificantchangeinthekeyvaluesintheindex 2)Ifalargeamountofdatainanindexedcolumnhasbeenadded, changed,orremoved(thatis,ifthedistributionofkeyvalueshas changed),orthetablehasbeentruncatedusingtheTRUNCATETABLE statementandthenrepopulated 3)Databaseisupgradedfromapreviousversion 41. Whatisfillfactor?Whatistheuseofit?Whathappens whenweignoreit?Whenyoushoulduselowfillfactor?
001 fo 79 egaP

Whenyoucreateaclusteredindex,thedatainthetableisstoredinthe datapagesofthedatabaseaccordingtotheorderofthevaluesinthe indexedcolumns.Whennewrowsofdataareinsertedintothetableor thevaluesintheindexedcolumnsarechanged,MicrosoftSQL Server2000mayhavetoreorganizethestorageofthedatainthe tabletomakeroomforthenewrowandmaintaintheorderedstorageof thedata.Thisalsoappliestononclusteredindexes.Whendataisadded orchanged,SQLServermayhavetoreorganizethestorageofthedata inthenonclusteredindexpages.Whenanewrowisaddedtoafullindex page,SQLServermovesapproximatelyhalftherowstoanewpageto makeroomforthenewrow.Thisreorganizationisknownasapage split.Pagesplittingcanimpairperformanceandfragmentthestorageof thedatainatable. Whencreatinganindex,youcanspecifyafillfactortoleaveextragaps andreserveapercentageoffreespaceoneachleaflevelpageofthe indextoaccommodatefutureexpansioninthestorageofthetable's dataandreducethepotentialforpagesplits.Thefillfactorvalueisa percentagefrom0to100thatspecifieshowmuchtofillthedatapages aftertheindexiscreated.Avalueof100meansthepageswillbefull andwilltaketheleastamountofstoragespace.Thissettingshouldbe usedonlywhentherewillbenochangestothedata,forexample,ona readonlytable.Alowervalueleavesmoreemptyspaceonthedata pages,whichreducestheneedtosplitdatapagesasindexesgrowbut requiresmorestoragespace.Thissettingismoreappropriatewhen therewillbechangestothedatainthetable. DATATYPES 42. WhatarethedatatypesinSQL
bigint datetime money smalldatetime tinyint Binary Decimal Nchar Smallint Varbinary bit float ntext smallmoney Varchar char image nvarchar text uniqueidentifier cursor int real timestamp

43. Differencebetweencharandnvarchar/charandvarchar datatype? char[(n)]FixedlengthnonUnicodecharacterdatawithlengthofn bytes.nmustbeavaluefrom1through8,000.Storagesizeisnbytes. TheSQL92synonymforcharischaracter. nvarchar(n)VariablelengthUnicodecharacterdataofncharacters.n mustbeavaluefrom1through4,000.Storagesize,inbytes,istwo timesthenumberofcharactersentered.Thedataenteredcanbe0 charactersinlength.TheSQL92synonymsfornvarchararenational charvaryingandnationalcharactervarying. varchar[(n)]VariablelengthnonUnicodecharacterdatawithlengthof nbytes.nmustbeavaluefrom1through8,000.Storagesizeisthe actuallengthinbytesofthedataentered,notnbytes.Thedataentered

001 fo 89 egaP

canbe0charactersinlength.TheSQL92synonymsforvarcharare charvaryingorcharactervarying. 44. GUIDdatasize? 128bit 45. HowGUIDbecominguniqueacrossmachines? Toensureuniquenessacrossmachines,theIDofthenetworkcardis used(amongothers)tocomputethenumber. 46. Whatisthedifferencebetweentextandimagedatatype? Textandimage.Usetextforcharacterdataifyouneedtostoremore than255charactersinSQLServer6.5,ormorethan8000inSQLServer 7.0.Useimageforbinarylargeobjects(BLOBs)suchasdigitalimages. Withtextandimagedatatypes,thedataisnotstoredintherow,sothe limitofthepagesizedoesnotapply.Allthatisstoredintherowisa pointertothedatabasepagesthatcontainthedata.Individualtext, ntext,andimagevaluescanbeamaximumof2GB,whichistoolongto storeinasingledatarow. JOINS 47. Whatarejoins? Sometimeswehavetoselectdatafromtwoormoretablestomakeour resultcomplete.Wehavetoperformajoin. 48. HowmanytypesofJoins? Joinscanbecategorizedas: Innerjoins(thetypicaljoinoperation,whichusessome comparisonoperatorlike=or<>).Theseincludeequijoinsand naturaljoins. Innerjoinsuseacomparisonoperatortomatchrowsfromtwo tablesbasedonthevaluesincommoncolumnsfromeachtable. Forexample,retrievingallrowswherethestudentidentification numberisthesameinboththestudentsandcoursestables. Outerjoins.Outerjoinscanbealeft,aright,orfullouterjoin. Outerjoinsarespecifiedwithoneofthefollowingsetsofkeywords whentheyarespecifiedintheFROMclause: LEFTJOINorLEFTOUTERJOINTheresultsetofaleftouter joinincludesalltherowsfromthelefttablespecifiedinthe LEFTOUTERclause,notjusttheonesinwhichthejoined columnsmatch.Whenarowinthelefttablehasno matchingrowsintherighttable,theassociatedresultset rowcontainsnullvaluesforallselectlistcolumnscoming fromtherighttable. RIGHTJOINorRIGHTOUTERJOINArightouterjoinisthe reverseofaleftouterjoin.Allrowsfromtherighttableare returned.Nullvaluesarereturnedforthelefttableanytime arighttablerowhasnomatchingrowinthelefttable. FULLJOINorFULLOUTERJOINAfullouterjoinreturnsall rowsinboththeleftandrighttables.Anytimearowhasno matchintheothertable,theselectlistcolumnsfromthe othertablecontainnullvalues.Whenthereisamatch

001 fo 99 egaP

betweenthetables,theentireresultsetrowcontainsdata valuesfromthebasetables. CrossjoinsCrossjoinsreturnallrowsfromthelefttable,each rowfromthelefttableiscombinedwithallrowsfromtheright table.CrossjoinsarealsocalledCartesianproducts.(A CartesianjoinwillgetyouaCartesianproduct.ACartesianjoinis whenyoujoineveryrowofonetabletoeveryrowofanother table.Youcanalsogetonebyjoiningeveryrowofatabletoevery rowofitself.) 49. Whatisselfjoin? Atablecanbejoinedtoitselfinaselfjoin. 50. WhatarethedifferencesbetweenUNIONandJOINS? Ajoinselectscolumnsfrom2ormoretables.Aunionselectsrows. 51. CanIimproveperformancebyusingtheANSIstylejoins insteadoftheoldstylejoins? CodeExample1: selecto.name,i.name fromsysobjectso,sysindexesi whereo.id=i.id CodeExample2: selecto.name,i.name fromsysobjectsoinnerjoinsysindexesi ono.id=i.id YouwillnotgetanyperformancegainbyswitchingtotheANSIstyle JOINsyntax. UsingtheANSIJOINsyntaxgivesyouanimportantadvantage:Because thejoinlogiciscleanlyseparatedfromthefilteringcriteria,youcan understandthequerylogicmorequickly. TheSQLServeroldstyleJOINexecutesthefilteringconditionsbefore executingthejoins,whereastheANSIstyleJOINreversesthis procedure(joinlogicprecedesfiltering). PerhapsthemostcompellingargumentforswitchingtotheANSIstyle JOINisthatMicrosofthasexplicitlystatedthatSQLServerwillnot supporttheoldstyleOUTERJOINsyntaxindefinitely.Anotherimportant considerationisthattheANSIstyleJOINsupportsqueryconstructions thattheoldstyleJOINsyntaxdoesnotsupport.
-resu a ro saila na y b ot derrefer esualc MORF eht ni stnemetats TCELES era selbat devireD eht y b des u elbat a smrof es ualc MORF eht ni TCELES eht fo tes tl user ehT .eman deificeps yna fi dnif ot elbat devired a sesu TCELES siht ,elpmaxe r oF .tnemetats TCELES ret uo tnuoc_eltit SA )di_eltit TCNITSID(TNUOC ,di_r ots TCELES( )seltit MORF )*(TNUOC TCELES( = tnuoc _eltit.AS DNA 001 f o 001 egaP :esabatad sbup eht ni seltit koob lla seirrac erots eman _rots .TS ,di _rots.TS TCELES di _rots.AS = di _rots.TS EREHW di_rots YB PUORG ,TS SA serots MORF selas MORF AS SA ) ?elbat devired si tahW .25

Das könnte Ihnen auch gefallen