Windows Forms & C# Interview Questions
Windows Forms & C# Interview Questions
2. [Link]("Hello,WindowsForms")
3. Canyouwriteaclasswithoutspecifyingnamespace?Which namespacedoesitbelongtobydefault?? Yes,youcan,thentheclassbelongstoglobalnamespacewhichhasno [Link],naturally,youwouldntwantglobal namespace. 4. YouaredesigningaGUIapplicationwithawindowandseveral [Link] lotofgreyspace,[Link] problem?[Link] defaultpropertyofawidgetonaformistopleft,soitstaysatthesame locationwhenresized. 5. HowcanyousavethedesiredpropertiesofWindowsForms application?.[Link] [Link] XMLfiles,sortoflikewhat.inifileswerebeforeforWin32apps. 6. [Link] [Link]?Initializeaninstanceof [Link] AppSettingsReaderclass,passinginthenameofthepropertyandthe [Link]. 7. Canyouautomatethisprocess?InVisualStudioyes,useDynamic [Link],storageandretrieval. 8. Myprogressbarfreezesupanddialogwindowshowsblank, [Link],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.
12. WhatsthedifferencebetweenMoveandLocationChanged? ResizeandSizeChanged?Bothmethodsdothesame,Moveand ResizearethenamesadoptedfromVBtoeasemigrationtoC#. 13. Howwouldyoucreateanonrectangularwindow,letssay anellipse?Createarectangularform,settheTransparencyKey propertytothesamevalueasBackColor,whichwilleffectivelymakethe [Link] [Link],whichwillremovethecontourandcontentsof theform. 14. HowdoyoucreateaseparatorintheMenuDesigner?A [Link],anampersand&\wouldunderlinethenext letter. 15. Howsanchoringdifferentfromdocking?Anchoringtreatsthe componentashavingtheabsolutesizeandadjustsitslocationrelative [Link] [Link] thebottomnomatterwhat,[Link] topright,butchangeitspositionwiththeformbeingresized,use anchoring.
InterviewQuestions C#
1. Whatstheimplicitnameoftheparameterthatgetspassedinto theclasssetmethod?Value,anditsdatatypedependsonwhatever variablewerechanging. 2. HowdoyouinheritfromaclassinC#?Placeacolonandthenthe [Link]++. 3. DoesC#supportmultipleinheritance?No,useinterfacesinstead. 4. Whenyouinheritaprotectedclasslevelvariable,whoisit availableto?Classesinthesamenamespace. 5. Areprivateclasslevelvariablesinherited?Yes,buttheyarenot accessible,solookingatityoucanhonestlysaythattheyarenot [Link]. 6. [Link] toderivedclassesandclasseswithinthesameAssembly(andnaturally fromthebaseclassitsdeclaredin). 7. C#[Link] thattakesastringasaparameter,butwanttokeeptheno [Link]?[Link] youwriteatleastoneconstructor,C#cancelsthefreebieconstructor, andnowyouhavetowriteoneyourself,eveniftheresno implementationinit. 8. [Link]? [Link]. 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 [Link] derivefromyourclasswillgetamessage:cannotinheritfromSealed [Link] Java. 14. Canyouallowclasstobeinherited,butpreventthemethod frombeingoverridden?Yes,justleavetheclasspublicandmakethe methodsealed. 15. Whatsanabstractclass?Aclassthatcannotbeinstantiated.A conceptinC++[Link] [Link],itsablueprint foraclasswithoutanyimplementation. 16. Whendoyouabsolutelyhavetodeclareaclassasabstract (asopposedtofreewillededucatedchoiceordecisionbasedon UMLdiagram)?Whenatleastoneofthemethodsintheclassis [Link],butnot allbaseabstractmethodshavebeenoverridden. 17. Whatsaninterfaceclass?Itsanabstractclasswithpublic abstractmethodsallofwhichmustbeimplementedintheinherited classes. 18. Whycantyouspecifytheaccessibilitymodifierformethods insidetheinterface?[Link],toprevent youfromgettingthefalseimpressionthatyouhaveanyfreedomof choice,youarenotallowedtospecifyanyaccessibility,itspublicby default. 19. Canyouinheritmultipleinterfaces? Yes,whynot. 20. Andiftheyhaveconflictingmethodnames?Itsuptoyouto implementthemethodinsideyourownclass,soimplementationisleft [Link] similarlynamedmethodsfromdifferentinterfacesexpectdifferentdata, butasfarascompilercaresyoureokay. 21. Whatsthedifferencebetweenaninterfaceandabstract class?Intheinterfaceallmethodsmustbeabstractintheabstract [Link] 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. [Link] [Link]?[Link] [Link] mutablestringwhereavarietyofoperationscanbeperformed. 25. [Link] [Link]?StringBuilderismoreefficientinthecases,where [Link],soeach timeitsbeingoperatedon,anewinstanceiscreated. 26. [Link]?No. 27. [Link]() [Link]()?Thefirstoneperformsadeepcopyofthe array,thesecondoneisshallow. 28. Howcanyousorttheelementsofthearrayindescending order?BycallingSort()andthenReverse()methods. 29. [Link] byauniquekey?HashTable. 30. WhatsclassSortedListunderneath?AsortedHashTable. 31. Willfinallyblockgetexecutediftheexceptionhadnot occurred?Yes. 32. WhatstheC#equivalentofC++catch(),whichwasa catchallstatementforanypossibleexception?Acatchblockthat [Link] parameterdatatypeinthiscaseandjustwritecatch{}. 33. Canmultiplecatchblocksbeexecuted?No,oncetheproper catchcodefiresoff,thecontrolistransferredtothefinallyblock(ifthere areany),andthenwhateverfollowsthefinallyblock. 34. Whyisitabadideatothrowyourownexceptions?Well,ifat thatpointyouknowthatanerrorhasoccurred,thenwhynotwritethe propercodetohandlethaterrorinsteadofpassinganewException objecttothecatchblock?Throwingyourownexceptionssignifiessome designflawsintheproject. 35. Whatsadelegate?Adelegateobjectencapsulatesareference [Link]++theywerereferredtoasfunctionpointers. 36. Whatsamulticastdelegate?Itsadelegatethatpointstoand eventuallyfiresoffseveralmethods. 37. [Link]?Assembly versioningallowstheapplicationtospecifynotonlythelibraryitneeds torun(whichwasavailableunderWin32),butalsotheversionofthe assembly. 38. Whatarethewaystodeployanassembly?AnMSIinstaller,a CABarchive,andXCOPYcommand.
001 fo 4 egaP
39. Whatsasatelliteassembly?Whenyouwriteamultilingualor [Link],andwanttodistributethecore applicationseparatelyfromthelocalizedmodules,thelocalized assembliesthatmodifythecoreapplicationarecalledsatellite assemblies. 40. Whatnamespacesarenecessarytocreatealocalized application?[Link],[Link]. 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. [Link]?CorDBG commandlinedebugger,[Link] .[Link],youmustcompiletheoriginalC# fileusingthe/debugswitch. 46. WhatdoestheThiswindowshowinthedebugger?Itpoints [Link] shown. 47. Whatdoesassert()do?Indebugcompilation,asserttakesina Booleanconditionasaparameter,andshowstheerrordialogifthe [Link] conditionistrue. 48. WhatsthedifferencebetweentheDebugclassandTrace class?[Link] builds,useTraceclassforbothdebugandreleasebuilds. 49. Whyaretherefivetracinglevelsin [Link]?Thetracingdumpscanbequite verboseandforsomeapplicationsthatareconstantlyrunningyourun [Link] rangefromNonetoVerbose,allowingtofinetunethetracingactivities. 50. WhereistheoutputofTextWriterTraceListenerredirected? TotheConsoleoratextfiledependingontheparameterpassedtothe constructor. 51. [Link]?Attachthe aspnet_wp.exeprocesstotheDbgClrdebugger. 52. Whatarethreetestcasesyoushouldgothroughinunit testing?Positivetestcases(correctdata,correctoutput),negativetest cases(brokenormissingdata,properhandling),exceptiontestcases (exceptionsarethrownandcaughtproperly). 53. Canyouchangethevalueofavariablewhiledebugginga C#application?Yes,[Link],just gotoImmediatewindow.
001 fo 5 egaP
54. Explainthethreeservicesmodel(threetierapplication). Presentation(UI),business(logicandunderlyingcode)anddata(from storageorothersources). 55. WhatareadvantagesanddisadvantagesofMicrosoft [Link]?[Link] providerishighspeedandrobust,butrequiresSQLServerlicense [Link] sources,likeOracle,DB2,MicrosoftAccessandInformix,[Link] layerontopofOLElayer,sonotthefastestthingintheworld. [Link] ODBCengines. 56. [Link] connections?Itreturnsareadonlydatasetfromthedatasourcewhen thecommandisexecuted. 57. WhatisthewildcardcharacterinSQL?Letssayyouwant toquerydatabasewithLIKEforallemployeeswhosenamestarts [Link]%,theproperquerywithLIKEwould involveLa%. 58. [Link] 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?[Link]. 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,[Link] processcrashes,itdiesalonewithouttakingtheentireOSorabunchof otherapplicationsdown. 3. Whydoyoucallitaprocess?Whatsdifferentbetweenprocess [Link],notcommoncomputerusage, terminology?[Link] [Link] numerousprocesseslaunchedofthesameapplication(5copiesofWord running),but1processcanrunjust1application. 4. [Link]? DistributedComputingEnvironment/RemoteProcedureCalls(DEC/RPC), MicrosoftDistributedComponentObjectModel(DCOM),CommonObject RequestBrokerArchitecture(CORBA),andJavaRemoteMethod Invocation(RMI). 5. Whatarepossibleimplementationsofdistributedapplicationsin .NET?.[Link] FrameworkClassLibrary,noteworthyclassesarein [Link]. 6. [Link]?Use remotingformoreefficientexchangeofinformationwhenyoucontrol [Link] informationexchangewhenyouarejustaclientoraserverwiththe otherendbelongingtosomeoneelse. 7. [Link]?Itsafake copyoftheserverobjectthatresidesontheclientsideandbehavesasif [Link] [Link]. 8. [Link]?Remotableobjects aretheobjectsthatcanbemarshaledacrosstheapplicationdomains. Youcanmarshalbyvalue,whereadeepcopyoftheobjectiscreated [Link], wherejustareferencetoanexistingobjectispassed. 9. [Link]?Channelsrepresentthe objectsthattransfertheotherserializedobjectsfromoneapplication domaintoanotherandfromonecomputertoanother,aswellasone [Link] objectcanbetransferred. 10. [Link] [Link]?[Link] [Link] 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 [Link] thisobjectisdeterminedbylifetimelease. 15. Howdoyoudefinetheleaseoftheobject?Byimplementing ILeaseinterfacewhenwritingtheclasscode. 16. [Link]?Yes, [Link]([Link] [Link]).ApplicationlevelXMLsettingstakeprecedenceover [Link]. 17. Howcanyouautomaticallygenerateinterfaceforthe [Link]?UsetheSoapsuds tool.
InterviewQuestions [Link]
1. [Link],aspnet_isapi.dll andaspnet_wp.[Link] theMicrosoftIISserverrunning,[Link] [Link](usuallyafilewith .aspxextension),theISAPIfilteraspnet_isapi.dlltakescareofitby passingtherequesttotheactualworkerprocessaspnet_wp.exe. 2. [Link]() [Link]()?Thelatteroneallowsyoutowrite formattedoutput. 3. Whatmethodsarefiredduringthepageload?Init()whenthe pageisinstantiated,Load()whenthepageisloadedintoserver memory,PreRender()thebriefmomentbeforethepageisdisplayed totheuserasHTML,Unload()whenpagefinishesloading. 4. [Link] hierarchy?[Link] 5. Wheredoyoustoretheinformationabouttheuserslocale? [Link] 6. WhatsthedifferencebetweenCodebehind="[Link]" andSrc="[Link]"?CodeBehindisrelevanttoVisual [Link].
001 fo 8 egaP
7. Whatsabubbledevent?Whenyouhaveacomplexcontrol,like DataGrid,writinganeventprocessingroutineforeachobject(cell, button,row,etc.)[Link] eventhandlers,allowingthemainDataGrideventhandlertotakecare ofitsconstituents. 8. [Link] [Link] handler? ItstheAttributesproperty,theAddfunctioninsidethatproperty. [Link]("onMouseOver","someClientCode()") 9. WhatdatatypedoestheRangeValidatorcontrolsupport? Integer,StringandDate. 10. ExplainthedifferencesbetweenServersideandClientside code? [Link] clientsbrowser. 11. Whattypeofcode(serverorclient)isfoundinaCode Behindclass? Serversidecode. 12. Shouldvalidation(didtheuserenterarealdate)occur serversideorclientside?Why?[Link] additionalrequesttotheservertovalidatetheusersinput. 13. Whatdoesthe"EnableViewState"propertydo?Whywould Iwantitonoroff? [Link] theusersinputonaform. 14. [Link] [Link]?WhywouldIchooseoneovertheother? [Link]. [Link]. 15. [Link] DatasetandanADORecordset?
ADataSetcanrepresentanentirerelationaldatabaseinmemory,complete withtables,relations,andviews. ADataSetisdesignedtoworkwithoutanycontinuingconnectiontothe originaldatasource. DatainaDataSetisbulkloaded,ratherthanbeingloadedondemand. There'snoconceptofcursortypesinaDataSet. DataSetshavenocurrentrecordpointerYoucanuseForEachloopstomove throughthedata. YoucanstoremanyeditsinaDataSet,andwritethemtotheoriginaldata sourceinasingleoperation. ThoughtheDataSetisuniversal,[Link] versionsfordifferentdatasources.
001 fo 9 egaP
17. IfImdevelopinganapplicationthatmustaccommodate [Link] webapplicationisspannedacrossthreewebservers(using roundrobinloadbalancing)whatwouldbethebestapproach tomaintainlogininstatefortheusers?Maintaintheloginstate securitythroughadatabase. 18. Canyouexplainwhatinheritanceisandanexampleof whenyoumightuseit?Whenyouwanttoinherit(usethe functionalityof)[Link] couldbederivedfromtheEmployeebaseclass. 19. Whatsanassembly? Assembliesarethebuildingblocksofthe .[Link] 20. Describethedifferencebetweeninlineandcodebehind. [Link] [Link]. 21. Explainwhatadiffgramis,andagooduseforone?The DiffGramisoneofthetwoXMLformatsthatyoucanusetorender [Link] filetobesenttoaWebService. 22. WhatsMSIL,andwhyshouldmydevelopersneedan appreciationofitifatall?MSIListheMicrosoftIntermediate [Link]. 23. WhichmethoddoyouinvokeontheDataAdaptercontrolto loadyourgenerateddatasetwithdata?[Link]()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:[Link]? False 34. WhatdoesWSDLstandfor?(WebServicesDescription Language)
001 fo 01 egaP
35. WhereontheInternetwouldyoulookforWebservices? ([Link] 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 [Link] [Link] WebService&Remoting COM XML IIS Controls Programming
1. [Link]? [Link]:thecommonlanguageruntimeand [Link]. Youcanthinkoftheruntimeasanagentthatmanagescodeatexecutiontime, providingcoreservicessuchasmemorymanagement,threadmanagement,and remoting,whilealsoenforcingstricttypesafetyandotherformsofcodeaccuracythat ensuresecurityandrobustness. Theclasslibrary,isacomprehensive,objectorientedcollectionofreusabletypesthat youcanusetodevelopapplicationsrangingfromtraditionalcommandlineorgraphical userinterface(GUI)applicationstoapplicationsbasedonthelatestinnovations [Link],suchasWebFormsandXMLWebservices. 2. WhatisCLR,CTS,CLS? [Link] RuntimeorCLR(similartotheJavaVirtualMachineorJVMinJava),whichhandlesthe executionofcodeandprovidesusefulservicesfortheimplementationoftheprogram. CLRtakescareofcodemanagementatprogramexecutionandprovidesvarious beneficialservicessuchasmemorymanagement,threadmanagement,security management,codeverification,compilation,[Link] 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 [Link] standarddocument,"PartitionIArchitecture",[Link] 3. WhatarethenewfeaturesofFramework1.1? 1. NativeSupportforDevelopingMobileWebApplications 2. EnableExecutionofWindowsFormsAssembliesOriginatingfromtheInternet AssembliesoriginatingfromtheInternetzoneforexample,Microsoft WindowsFormscontrolsembeddedinanInternetbasedWebpageor WindowsFormsassemblieshostedonanInternetWebserverandloadedeither throughtheWebbrowserorprogrammaticallyusingthe [Link]()methodnowreceivesufficient [Link] beenchangedsothatassembliesassignedbythecommonlanguageruntime (CLR)totheInternetzonecodegroupnowreceivetheconstrainedpermissions [Link].NETFramework1.0Service Pack1andServicePack2,suchapplicationsreceivedthepermissions associatedwiththeNothingpermissionsetandcouldnotexecute. 3. [Link] Systemsadministratorscannowusecodeaccesssecuritytofurtherlockdown [Link]. Althoughtheoperatingsystemaccountunderwhichanapplicationrunsimposes securityrestrictionsontheapplication,thecodeaccesssecuritysystemofthe CLRcanenforceadditionalrestrictionsonselectedapplicationresourcesbased [Link] sharedserverenvironment(suchasanInternetserviceprovider(ISP)hosting multipleWebapplicationsononeserver)toisolateseparateapplicationsfrom oneanother,aswellaswithstandaloneserverswhereyouwantapplicationsto runwiththeminimumnecessaryprivileges. 4. NativeSupportforCommunicatingwithODBCandOracleDatabases 5. UnifiedProgrammingModelforSmartClientApplicationDevelopment [Link],WindowsForms controls,[Link] [Link] libraryoptimizedforsmalldevices. 6. SupportforIPv6 The.NETFramework1.1supportstheemergingupdatetotheInternetProtocol, commonlyreferredtoasIPversion6,[Link] tosignificantlyincreasetheaddressspaceusedtoidentifycommunication endpointsintheInternettoaccommodateitsongoinggrowth. [Link] 4. [Link]? Ans:It'[Link] [Link] [Link]:[Link] [Link],theSDKalsoincludes commandlinecompilersforC#,C++,JScript,[Link] [Link] sothisisadevelopmentplatform. 5. WhatisMSIL,IL? Whencompilingtomanagedcode,thecompilertranslatesyoursourcecodeinto Microsoftintermediatelanguage(MSIL),whichisaCPUindependentsetofinstructions [Link], storing,initializing,andcallingmethodsonobjects,aswellasinstructionsfor arithmeticandlogicaloperations,controlflow,directmemoryaccess,exception handling,[Link](MSIL)isalanguage
001 fo 21 egaP
6.
7.
8.
9.
usedastheoutputofanumberofcompilersandastheinputtoajustintime(JIT) [Link] nativecode. CanIwriteILprogramsdirectly? [Link]: .assemblyMyAssembly{} .classMyApp{ .methodstaticvoidMain(){ .entrypoint ldstr "Hello,IL!" call [Link]::WriteLine([Link]) ret } } [Link],[Link] begenerated. CanIdothingsinILthatIcan'tdoinC#? [Link] [Link],andyoucanhavenonzerobasedarrays. WhatisJIT(justintime)?howitworks? BeforeMicrosoftintermediatelanguage(MSIL)canbeexecuted,itmustbeconverted [Link](JIT)compilertonativecode,whichisCPUspecific codethatrunsonthesamecomputerarchitectureastheJITcompiler. RatherthanusingtimeandmemorytoconvertalltheMSILinaportableexecutable (PE)filetonativecode,itconvertstheMSILasitisneededduringexecutionandstores theresultingnativecodesothatitisaccessibleforsubsequentcalls. Theruntimesuppliesanothermodeofcompilationcalledinstalltimecodegeneration. TheinstalltimecodegenerationmodeconvertsMSILtonativecodejustastheregular JITcompilerdoes,butitconvertslargerunitsofcodeatatime,storingtheresulting nativecodeforusewhentheassemblyissubsequentlyloadedandexecuted. AspartofcompilingMSILtonativecode,codemustpassaverificationprocessunless anadministratorhasestablishedasecuritypolicythatallowscodetobypass [Link] bedeterminedtobetypesafe,whichmeansthatitisknowntoaccessonlythe memorylocationsitisauthorizedtoaccess. Whatisstrongname? Anamethatconsistsofanassembly'sidentityitssimpletextname,versionnumber, andcultureinformation(ifprovided)strengthenedbyapublickeyandadigital signaturegeneratedovertheassembly. Whatisportableexecutable(PE)? Thefileformatdefiningthestructurethatallexecutablefiles(EXE)andDynamicLink Libraries(DLL)[Link] derivedfromtheMicrosoftCommonObjectFileFormat(COFF).TheEXEandDLLfiles [Link]/COFFformatsandalsoaddadditional [Link] forthePE/COFFfileformatsisavailableat [Link]
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. }
25. WhatisCodeAccessSecurity(CAS)? [Link] codeisallowedtorun,[Link], [Link]. HowdoesCASwork? TheCASsecuritypolicyrevolvesaroundtwokeyconceptscodegroupsand [Link],andeach codegroupisgrantedthepermissionsspecifiedinanamedpermissionset. Forexample,usingthedefaultsecuritypolicy,acontroldownloadedfromawebsite belongstothe'ZoneInternet'codegroup,whichadherestothepermissionsdefined bythe'Internet'namedpermissionset.(Naturallythe'Internet'namedpermissionset representsaveryrestrictiverangeofpermissions.) WhodefinestheCAScodegroups? Microsoftdefinessomedefaultones,butyoucanmodifytheseandevencreateyour [Link],run'caspollg'fromthe [Link]: 26. Level=Machine 27. CodeGroups: 28. 29. [Link]:Nothing 30. [Link]:FullTrust 31. [Link]:SkipVerification 32. [Link]:LocalIntranet 33. [Link]:Internet 34. [Link]:Nothing 35. [Link]:Internet [Link] Notethehierarchyofcodegroupsthetopofthehierarchyisthemostgeneral('All code'),whichisthensubdividedintoseveralgroups,eachofwhichinturncanbesub [Link](somewhatcounterintuitively)asubgroupcanbeassociated withamorepermissivepermissionsetthanitsparent. HowdoIdefinemyowncodegroup? [Link],[Link] wantithavefullaccesstoyoursystem,butyouwanttokeepthedefaultrestrictions [Link],youwouldaddanewcodegroupasasub groupofthe'ZoneInternet'group,likethis: [Link] Nowifyouruncaspollgyouwillseethatthenewgrouphasbeenaddedasgroup 1.3.1: 1.3. ZoneInternet:Internet 1.3.1. [Link]:FullTrust ... Notethatthenumericlabel(1.3.1)isjustacaspolinventiontomakethecodegroups [Link].
001 fo 41 egaP
HowdoIchangethepermissionsetforacodegroup? [Link],youcanoperateatthe'machine' levelwhichmeansnotonlythatthechangesyoumakebecomethedefaultforthe machine,[Link] youareanormal(nonadmin)useryoucanstillmodifythepermissions,butonlyto [Link],toallowintranetcodetodowhatitlikesyou mightdothis: caspolcg1.2FullTrust Notethatbecausethisismorepermissivethanthedefaultpolicy(onastandard system),youshouldonlydothisatthemachineleveldoingitattheuserlevelwill havenoeffect.
CanIcreatemyownpermissionset? [Link],specifyinganXMLfilecontainingthepermissionsinthepermission [Link],hereisasamplefilecorrespondingtothe'Everything' [Link],addit totherangeofavailablepermissionsetslikethis: [Link] Then,toapplythepermissionsettoacodegroup,dosomethinglikethis: caspolcg1.3SamplePermSet(Bydefault,1.3isthe'Internet'codegroup) I'[Link]? [Link],youcanaskcaspoltotellyou whatcodegroupanassemblybelongsto,[Link],youcanask whatpermissionsarebeingappliedtoaparticularassemblyusingcaspolrsp. Ican'[Link]? Yes,[Link]: caspolsoff [Link] 36. [Link]? Ans:[Link] 37. Whatareobjectpoolingandconnectionpoolinganddifference?Wheredowe settheMinandMaxPoolsizeforconnectionpooling? ObjectpoolingisaCOM+servicethatenablesyoutoreducetheoverheadofcreating [Link],[Link] theobjectisdeactivated,[Link] canconfigureobjectpoolingbyapplyingtheObjectPoolingAttributeattributetoaclass [Link]. Objectpoolingletsyoucontrolthenumberofconnectionsyouuse,asopposedto connectionpooling,whereyoucontrolthemaximumnumberreached. Followingareimportantdifferencesbetweenobjectpoolingandconnectionpooling: [Link],creationisonthesamethread,soif thereisnothinginthepool,[Link] pooling,[Link],ifyouhave alreadyreachedyourmaximum,itinsteadgivesyouthenextavailableobject. Thisiscrucialbehaviorwhenittakesalongtimetocreateanobject,butyoudo notuseitforverylong. [Link] [Link] [Link] justafewobjects.(TPC/Cbenchmarksrelyonthis.) COM+[Link] [Link],creationisonadifferentthreadandminimums andmaximumsareenforced.
001 fo 51 egaP
1. WhatisApplicationDomain? TheprimarypurposeoftheAppDomainistoisolateanapplicationfromother applications.Win32processesprovideisolationbyhavingdistinctmemoryaddress [Link],butitisexpensiveanddoesn'[Link] enforcesAppDomainisolationbykeepingcontrolovertheuseofmemoryallmemory [Link],sotheruntimecanensurethat AppDomainsdonotaccesseachother'smemory. Objectsindifferentapplicationdomainscommunicateeitherbytransportingcopiesof objectsacrossapplicationdomainboundaries,orbyusingaproxytoexchange messages. MarshalByRefObjectisthebaseclassforobjectsthatcommunicateacross [Link] [Link] applicationreferencesamarshalbyvalueobject,acopyoftheobjectispassedacross applicationdomainboundaries. HowdoesanAppDomaingetcreated? [Link], [Link],thehostis [Link]. [Link]#sample whichcreatesanAppDomain,createsaninstanceofanobjectinsideit,andthen executesoneoftheobject'[Link] '[Link]'forthiscodetoworkasis. usingSystem [Link] publicclassCAppDomainInfo:MarshalByRefObject { publicstringGetAppDomainInfo() { return"AppDomain="+[Link] } } publicclassApp { publicstaticintMain() { AppDomainad=[Link]("Andy'snewdomain",null,null ) ObjectHandleoh=[Link]("appdomaintest","CAppDomainInfo" ) CAppDomainInfoadInfo=(CAppDomainInfo)([Link]()) stringinfo=[Link]() [Link]("AppDomaininfo:"+info) return0 } } 2. [Link]?Whatarethewaystocontrolserialization? Serializationistheprocessofconvertinganobjectintoastreamofbytes. Deserializationistheoppositeprocessofcreatinganobjectfromastreamofbytes. Serialization/Deserializationismostlyusedtotransportobjects([Link]), ortopersistobjects([Link]).Serializationcanbedefinedasthe [Link],the publicandprivatefieldsoftheobjectandthenameoftheclass,includingtheassembly containingtheclass,areconvertedtoastreamofbytes,whichisthenwrittentoadata [Link],anexactcloneoftheoriginal objectiscreated.
001 fo 61 egaP
Binaryserializationpreservestypefidelity,whichisusefulforpreservingthe [Link], youcanshareanobjectbetweendifferentapplicationsbyserializingittothe [Link],disk,memory,overthe network,[Link]"byvalue" fromonecomputerorapplicationdomaintoanother. XMLserializationserializesonlypublicpropertiesandfieldsanddoesnot [Link] [Link] standard,[Link] openstandard,whichmakesitanattractivechoice.
[Link] andSoapFormatter/[Link], andusesSoapFormatter/[Link] yourowncode. WhydoIgeterrorswhenItrytoserializeaHashtable? XmlSerializerwillrefusetoserializeinstancesofanyclassthatimplementsIDictionary, [Link]. 3. Whatisexceptionhandling? Whenanexceptionoccurs,thesystemsearchesforthenearestcatchclausethatcan handletheexception,[Link],the currentmethodissearchedforalexicallyenclosingtrystatement,andtheassociated [Link],themethodthat calledthecurrentmethodissearchedforalexicallyenclosingtrystatementthat [Link] clauseisfoundthatcanhandlethecurrentexception,bynaminganexceptionclass thatisofthesameclass,orabaseclass,oftheruntimetypeoftheexceptionbeing [Link]'tnameanexceptionclasscanhandleanyexception. Onceamatchingcatchclauseisfound,thesystempreparestotransfercontroltothe [Link],the systemfirstexecutes,inorder,anyfinallyclausesthatwereassociatedwithtry statementsmorenestedthatthantheonethatcaughttheexception. [Link] exceptionoccursduringdestructorexecution,andthatexceptionisnotcaught,then theexecutionofthatdestructoristerminatedandthedestructorofthebaseclass(if any)[Link](asinthecaseoftheobjecttype)orifthereis nobaseclassdestructor,thentheexceptionisdiscarded. 4. WhatisAssembly? [Link] fundamentalunitofdeployment,versioncontrol,reuse,activationscoping,and [Link] [Link] commonlanguageruntimewiththeinformationitneedstobeawareoftype [Link],atypedoesnotexistoutsidethecontextofan assembly. [Link] assemblyperformsthefollowingfunctions: [Link] intermediatelanguage(MSIL)codeinaportableexecutable(PE)filewillnotbe [Link] assemblycanhaveonlyoneentrypoint(thatis,DllMain,WinMain,orMain). [Link] requestedandgranted. [Link]'sidentityincludesthenameofthe [Link] assemblyisnotthesameasatypecalledMyTypeloadedinthescopeof anotherassembly.
001 fo 71 egaP
[Link]'smanifestcontains assemblymetadatathatisusedforresolvingtypesandsatisfyingresource [Link] [Link]. [Link] thecommonlanguageruntimealltypesandresourcesinthesameassembly [Link]'smanifestdescribestheversion dependenciesyouspecifyforanydependentassemblies. [Link],onlytheassembliesthat [Link],suchas localizationresourcesorassembliescontainingutilityclasses,canberetrieved [Link] downloaded. Itistheunitatwhichsidebysideexecutionissupported.
[Link] types(interfacesandclasses),aswellasresourcesfortheassembly(bitmaps,JPEG files,resourcefiles,andsoon).[Link] [Link],whicharerundirectlyfrom [Link] todiskaftertheyhaveexecuted. [Link],suchas [Link],[Link] [Link] [Link] runtimeAPIs,[Link],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 [Link], [Link] assembliesareusuallylibrariesofcodewhichmanyapplicationswillfinduseful, [Link]. 2. Versioning:Theruntimeenforcesversioningconstraintsonlyonshared assemblies,notonprivateassemblies. 1. WhatareSatelliteAssemblies?Howyouwillcreatethis?Howwillyougetthe differentlanguagestrings? Satelliteassembliesareoftenusedtodeploylanguagespecificresourcesforan [Link] theapplicationhasaseparateproductIDforeachlanguageandinstallssatellite [Link], theapplicationremovesonlythesatelliteassembliesassociatedwithagivenlanguage [Link] [Link]. (Forexample,EnglishandJapaneseeditionsofthe.NETFrameworkversion1.1share [Link].NETFrameworkversion1.1addssatellite assemblieswithlocalizedresourcesina\[Link] the.NETFrameworkversion1.1,regardlessofitslanguage,alwaysusesthesamecore runtimefiles.)
001 fo 81 egaP
2. 3.
4.
5.
6.
7. 8.
[Link] ** Howwilluloaddynamicassembly?Howwillcreateassembliesatruntime? ** WhatisAssemblymanifest?whatalldetailstheassemblymanifestwill contain? Everyassembly,whetherstaticordynamic,containsacollectionofdatathatdescribes [Link] [Link] specifytheassembly'sversionrequirementsandsecurityidentity,andallmetadata neededtodefinethescopeoftheassemblyandresolvereferencestoresourcesand [Link]([Link])with Microsoftintermediatelanguage(MSIL)codeorinastandalonePEfilethatcontains onlyassemblymanifestinformation. ItcontainsAssemblyname,Versionnumber,Culture,Strongnameinformation,Listof allfilesintheassembly,Typereferenceinformation,Informationonreferenced assemblies. Differencebetweenassemblymanifest&metadata? assemblymanifestAnintegralpartofeveryassemblythatrenderstheassembly [Link]'[Link] establishestheassemblyidentity,specifiesthefilesthatmakeuptheassembly implementation,specifiesthetypesandresourcesthatmakeuptheassembly,itemizes thecompiletimedependenciesonotherassemblies,andspecifiesthesetof [Link] timetoresolvereferences,enforceversionbindingpolicy,andvalidatetheintegrityof [Link] impactinstallandXCOPYdeploymentfeasible. metadataInformationthatdescribeseveryelementmanagedbythecommon languageruntime:anassembly,loadablefile,type,method,[Link] includeinformationrequiredfordebuggingandgarbagecollection,aswellassecurity attributes,marshalingdata,extendedclassandmemberdefinitions,versionbinding, andotherinformationrequiredbytheruntime. WhatisGlobalAssemblyCache(GAC)andwhatisthepurposeofit?(Howto makeanassemblytopublic?Steps)Howmorethanoneversionofan assemblycankeepinsameplace? Eachcomputerwherethecommonlanguageruntimeisinstalledhasamachinewide [Link] assembliesspecificallydesignatedtobesharedbyseveralapplicationsonthe computer. Youshouldshareassembliesbyinstallingthemintotheglobalassembly cacheonlywhenyouneedto. Steps [Link] eg:[Link] [Link] eg:[assembly:AssemblyKeyFile("[Link]")] recompileproject,theninstallittoGACbyeither drag&dropittoassemblyfolder(C:\WINDOWS\assemblyORC:\WINNT\assembly) ([Link]) or [Link] IfIhavemorethanoneversionofoneassemblies,thenhow'llIuseold version(how/wheretospecifyversionnumber?)inmyapplication? ** Howtofindmethodsofaassemblyfile(notusingILDASM) Reflection [Link]?Garbagecollectionprocess? Theprocessoftransitivelytracingthroughallpointerstoactivelyusedobjectsinorder tolocateallobjectsthatcanbereferenced,andthenarrangingtoreuseanyheap [Link]
001 fo 91 egaP
collectoralsocompactsthememorythatisinusetoreducetheworkingspaceneeded fortheheap. 9. [Link]?Namespace? Howwillyouloadanassemblywhich isnotreferencedbycurrentassembly? [Link] [Link](modulesinturnare packagedtogetherinassemblies),andcanbeaccessedbyamechanismcalled [Link] interrogatethetypesforamodule/assembly. [Link]/ITypeInfoto accesstypelibrarydatainCOM,[Link] datatypesizesformarshalingdataacrosscontext/process/machineboundaries. Reflectioncanalsobeusedtodynamicallyinvokemethods(see [Link]),orevencreatetypesdynamicallyatruntime(see [Link]). 10. WhatisCustomattribute?Howtocreate?IfI'mhavingcustomattributeinan assembly,howtosaythatnameinthecode? A:Theprimarystepstoproperlydesigncustomattributeclassesareasfollows: a. ApplyingtheAttributeUsageAttribute([AttributeUsage([Link], Inherited=false,AllowMultiple=true)]) b. Declaringtheattribute.(classpublicclassMyAttribute:[Link]{//.. .}) c. Declaringconstructors(publicMyAttribute(boolmyvalue){[Link]= myvalue}) d. Declaringproperties publicboolMyProperty { get{[Link]} set{[Link]=value} } Thefollowingexampledemonstratesthebasicwayofusingreflectiontogetaccessto customattributes. classMainClass { publicstaticvoidMain() { [Link]=typeof(MyClass) object[]attributes=[Link]() for(inti=0i<[Link]++) { [Link](attributes[i]) } } } 1. [Link]? [Link] Runtime,whichmanagestheexecutionofcodeandprovidesservicesthatmakethe [Link]'sfunctionalityand [Link] thatyoudevelopwithalanguagecompilerthattargetstheruntimeiscalledmanaged codeitbenefitsfromfeaturessuchascrosslanguageintegration,crosslanguage exceptionhandling,enhancedsecurity,versioninganddeploymentsupport,asimplified modelforcomponentinteraction,anddebuggingandprofilingservices. 2. [Link]?Whatisthenamespaceforthat? ** [Link] 3. SerializeandMarshalByRef?
001 fo 02 egaP
4. usingdirectivevsusingstatement YoucreateaninstanceinausingstatementtoensurethatDisposeiscalledonthe [Link] 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 [Link],codemustpassaverificationprocessthat examinestheMSILandmetadatatofindoutwhetherthecodecanbe determinedtobetypesafe. 4. Executingyourcode. Thecommonlanguageruntimeprovidestheinfrastructurethatenables executiontotakeplaceaswellasavarietyofservicesthatcanbeusedduring execution. 1. WhatisActiveDirectory?WhatisthenamespaceusedtoaccesstheMicrosoft ActiveDirectories?WhatareADSIDirectories? ActiveDirectoryServiceInterfaces(ADSI)isaprogrammaticinterfaceforMicrosoft [Link] directoriesonanetwork,[Link] FrameworkmakeiteasytoaddADSIfunctionalitywiththeDirectoryEntryand DirectorySearchercomponents. UsingADSI,youcancreateapplicationsthatperformcommonadministrativetasks, suchasbackingupdatabases,accessingprinters,andadministeringuseraccounts. ADSImakesitpossibleforyouto: [Link] classprovidesusernameandpasswordpropertiesthatcanbeenteredat runtimeandcommunicatedtotheActiveDirectoryobjectyouarebindingto. Useasingleapplicationprogramminginterface(API)toperformtaskson [Link] DirectoryServicesnamespaceprovidestheclassestoperformmost administrativefunctions. Perform"richquerying"[Link] searchingforanobjectbyspecifyingtwoquerydialects:SQLandLDAP. Accessanduseasingle,hierarchicalstructureforadministeringandmaintaining diverseandcomplicatednetworkconfigurationsbyaccessinganActiveDirectory tree. [Link] [Link] thatitisusingtheLDAPprovider. [Link] 1. HowGarbageCollector(GC)Works? Themethodsinthisclassinfluencewhenanobjectisgarbagecollectedandwhen [Link]
001 fo 12 egaP
informationaboutthetotalamountofmemoryavailableinthesystemandtheage category,orgeneration,[Link],thegarbage collectorperformsgarbagecollectiontoreclaimmemoryallocatedtoobjectsforwhich [Link] [Link],an applicationcanforcegarbagecollectionusingtheCollectmethod. Garbagecollectionconsistsofthefollowingsteps: 1. Thegarbagecollectorsearchesformanagedobjectsthatarereferencedin managedcode. 2. Thegarbagecollectorattemptstofinalizeobjectsthatarenotreferenced. 3. Thegarbagecollectorfreesobjectsthatarenotreferencedandreclaimstheir memory. 1. [Link]? Requeststhatthesystemnotcallthefinalizermethodforthespecifiedobject. publicstaticvoidSuppressFinalize( objectobj )[Link] parameterisrequiredtobethecallerofthismethod. ObjectsthatimplementtheIDisposableinterfacecancallthismethodfromthe [Link] [Link]. 2. Whatisnmaketool? TheNmaketool([Link])isa32bittoolthatyouusetobuildprojectsbasedon [Link]. usage:nmakeaall 3. WhatareNamespaces? [Link] [Link] explicitlydeclareone,[Link], sometimescalledtheglobalnamespace,[Link] [Link] havepublicaccessandthisisnotmodifiable. 4. WhatisthedifferencebetweenCONSTandREADONLY? [Link] [Link] [Link],readonlyfieldscanhavedifferentvaluesdependingonthe constructorused. readonlyintb publicX() { b=1 } publicX(strings) { b=5 } publicX(strings,inti) { b=i } Also,whileaconstfieldisacompiletimeconstant,thereadonlyfieldcanbeusedfor runtimeconstants,asinthefollowingexample: publicstaticreadonlyuintl1=(uint)[Link](thiscan'tbepossiblewith const) 5. Whatisthedifferencebetweenref&outparameters? [Link] parameter,whoseargumentdoesnothavetobeexplicitlyinitializedbeforebeing passedtoanoutparameter.
001 fo 22 egaP
6. WhatisthedifferencebetweenArrayandLinkedList? 7. WhatisthedifferencebetweenArrayandArraylist? AselementsareaddedtoanArrayList,thecapacityisautomaticallyincreasedas [Link] bysettingtheCapacitypropertyexplicitly. 8. WhatisJaggedArrays? [Link] [Link]"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 [Link]? 2. WhatisRCW(RuntimeCallableWrappers)? ThecommonlanguageruntimeexposesCOMobjectsthroughaproxycalledthe runtimecallablewrapper(RCW).AlthoughtheRCWappearstobeanordinaryobjectto .NETclients,[Link] object. 3. WhatisCCW(COMCallableWrapper) AproxyobjectgeneratedbythecommonlanguageruntimesothatexistingCOM applicationscanusemanagedclasses,[Link], transparently. 4. HowCCWandRCWisworking? ** 5. Howwillyouregistercom+services? [Link] ([Link])tomanuallyregisteranassemblycontaining [Link] [Link] classRegistrationHelperandusingthemethodInstallAssembly 6. WhatisuseofContextUtilclass? ContextUtilisthepreferredclasstouseforobtainingCOM+contextinformation.
001 fo 32 egaP
7. WhatisthenewthreefeaturesofCOM+services,whicharenotthereinCOM (MTS)? ** 8. [Link]? Whatisthedifference betweenthem? ** 9. CanwecopyaCOMdlltoGACfolder? ** 10. WhatisPinvoke? Platforminvokeisaservicethatenablesmanagedcodetocallunmanagedfunctions implementedindynamiclinklibraries(DLLs),[Link] locatesandinvokesanexportedfunctionandmarshalsitsarguments(integers,strings, arrays,structures,andsoon)acrosstheinteroperationboundaryasneeded. 11. IsittruethatCOMobjectsnolongerneedtoberegisteredontheserver? Answer:[Link] [Link] [Link] theminthe'bin'folderoftheapplication. 12. [Link]? Answer:Yes,youcanusethefeaturesandfunctionsofComponentServicesfroma .NETFrameworkcomponent. [Link] (OOPS) 13. WhataretheOOPSconcepts? 1)Encapsulation:Itisthemechanismthatbindstogethercodeanddatain manipulates,[Link] [Link] interfacecontrolstheaccesstothatparticularcodeanddata. 2)Inheritance:Itistheprocessbywhichoneobjectacquiresthepropertiesofanother [Link],each [Link],byuseof inheritance,anobjectneedonlydefinethosequalitiesthatmakeituniquewithinits [Link] theattributesofallofitsancestors. 3)Polymorphism:Itisafeaturethatallowsoneinterfacetobeusedforgeneralclass [Link] generalpolymorphismmeans"oneinterface,multiplemethods",Thismeansthatitis [Link] complexitybyallowingthesameinterfacetobeusedtospecifyageneralclassof [Link]'sjobtoselectthespecificaction(thatis,method)asitapplies toeachsituation. 14. WhatisthedifferencebetweenaStructandaClass? ThestructtypeissuitableforrepresentinglightweightobjectssuchasPoint, Rectangle,[Link],a [Link],ifyoudeclareanarray of1000Pointobjects,youwillallocateadditionalmemoryforreferencingeach [Link],thestructislessexpensive. Whenyoucreateastructobjectusingthenewoperator,itgetscreatedandthe [Link],structscanbeinstantiated [Link],thefieldswillremain unassignedandtheobjectcannotbeuseduntilallofthefieldsareinitialized. Itisanerrortodeclareadefault(parameterless)constructorforastruct.A defaultconstructorisalwaysprovidedtoinitializethestructmemberstotheir defaultvalues. Itisanerrortoinitializeaninstancefieldinastruct. [Link] fromanotherstructorclass,[Link],
001 fo 42 egaP
however,[Link], anditdoesthatexactlyasclassesdo. Astructisavaluetype,whileaclassisareferencetype. 15. Valuetype&referencetypesdifference?[Link]&struct [Link]? Mostprogramminglanguagesprovidebuiltindatatypes,suchasintegersandfloating pointnumbers,thatarecopiedwhentheyarepassedasarguments(thatis,theyare passedbyvalue).[Link],[Link] supportstwokindsofvaluetypes: Builtinvaluetypes [Link],suchasSystem.Int32and [Link],whichcorrespondandareidenticaltoprimitivedatatypes usedbyprogramminglanguages. Userdefinedvaluetypes Yourlanguagewillprovidewaystodefineyourownvaluetypes,whichderive [Link] issmall,suchasacomplexnumber(usingtwofloatingpointnumbers),you mightchoosetodefineitasavaluetypebecauseyoucanpassthevaluetype [Link] 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,[Link] overridemethodprovidesanewimplementationofamemberinheritedfromabase [Link] [Link] overridemethod. [Link] 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
34. Inwhichcasesyouuseoverrideandnewbase? [Link] aninheritedmember,declareitinthederivedclassusingthesamename,andmodify itwiththenewmodifier. C#Languagefeatures 35. WhatareSealedClassesinC#? [Link] occursifasealedclassisspecifiedasthebaseclassofanotherclass.(Asealedclass cannotalsobeanabstractclass) 36. WhatisPolymorphism?[Link]/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. [Link]([Link]()) 56. } 57. publicstaticvoidMain() 58. { 59. IdentifierTokenVariable=newIdentifierToken() 60. Method(Variable)//WhichClassMethodiscalledhere 61. [Link]() 62. } 63. FortheabovecodeWhatisthe"new"keywordandWhichClassMethodis 64. calledhere A:itwillcallbaseclassDisplaymethod 65. classToken 66. { 67. 68. 69. 70.
71. } 72. } 73. classIdentifierToken:Token 74. { 75. publicoverridestringDisplay()//Whatistheuseofnewkeyword 76. { 77. //Implementationgoeshere 78. return"derive" 79. } 80. } 81. staticvoidMethod(Tokent) 82. { 83. [Link]([Link]()) 84. } 85. publicstaticvoidMain() 86. { 87. IdentifierTokenVariable=newIdentifierToken() 88. Method(Variable)//WhichClassMethodiscalledhere 89. [Link]() 90. } 91. A:Derive 92. InwhichScenarioyouwillgoforInterfaceorAbstractClass? Interfaces,likeclasses,defineasetofproperties,methods,[Link] classes,[Link], [Link] yourclassestoinheritimplementationfromabaseclass,italsoforcesyoutomake mostofyourdesigndecisionswhentheclassisfirstpublished. Abstractclassesareusefulwhencreatingcomponentsbecausetheyallowyouspecify aninvariantleveloffunctionalityinsomemethods,butleavetheimplementationof [Link] well,becauseifadditionalfunctionalityisneededinderivedclasses,itcanbeaddedto thebaseclasswithoutbreakingcode. [Link] 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 [Link] Constants unqualifiednamespollute staticandinstanceintialiser [Link] 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 [Link] Youcanwriteanew hasimposedstructureonyou. replacementmoduleforan Dependingontheclevernessof interfacethatcontainsnot theauthoroftheabstractclass, onestickofcodein thismaybegoodorbad. commonwiththeexisting Anotherissuethat'simportantis [Link] whatIcall"heterogeneousvs. youimplementthe homogeneous."If interface,youstartfrom implementors/subclassesare scratchwithoutany Plugin homogeneous,tendtowardsan defaultimplementation. [Link] Youhavetoobtainyour heterogeneous,useaninterface. toolsfromotherclasses (NowallIhavetodoiscomeup nothingcomeswiththe withagooddefinitionof interfaceotherthanafew hetero/homogeneousinthis [Link] context.)Ifthevariousobjects freedomtoimplementa areallofakind,andsharea radicallydifferentinternal commonstateandbehavior, design. thentendtowardsacommon [Link] 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 [Link] Fast JVMsarediscoveringways toreducethisspeed penalty. Theconstantdeclarations Youcanputsharedcodeintoan inaninterfaceareall abstractclass,whereyoucannot presumedpublicstatic [Link] final,soyoumayleave wanttosharecode,youwill Terseness [Link]'t havetowriteotherbubblegum callanymethodsto [Link] computetheinitialvalues methodstocomputetheinitial [Link] valuesofyourconstantsand neednotdeclareindividualvariables,bothinstanceand
001 fo 82 egaP
methodsofaninterface [Link] presumedso. Ifyouaddanewmethod toaninterface,youmust trackdownall Adding implementationsofthat functionality interfaceintheuniverse andprovidethemwitha concreteimplementation ofthatmethod.
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. [Link]("A") 115. } 116. } 117. publicclassB:A 118. { 119. } 120. publicclassC:B,IWeather 121. { 122. publicvoiddisplay() 123. { 124. [Link]("C") 125. } 126. }
001 fo 92 egaP
127. [Link](),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. [Link](1) //Error 154. [Link]=1 //Error 155. ((IList)x).Count=1 //Ok,[Link] 156. ((ICounter)x).Count(1) //Ok,[Link] 157. } 158. } 159. Writeonecodeexampleforcompiletimebindingandoneforruntime binding?Whatisearly/latebinding? Anobjectisearlyboundwhenitisassignedtoavariabledeclaredtobeofaspecific [Link] otheroptimizationsbeforeanapplicationexecutes. 'Createavariabletoholdanewobject. DimFSAsFileStream 'Assignanewobjecttothevariable. FS=NewFileStream("C:\[Link]",[Link]) Bycontrast,anobjectislateboundwhenitisassignedtoavariabledeclaredtobeof [Link],butlackmanyof theadvantagesofearlyboundobjects. DimxlAppAsObject xlApp=CreateObject("[Link]") 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 [Link],anditcannotusethe vararg(variableargument)callingconvention. [Link] classbeforethefirstinstanceiscreatedoranystaticmembersarereferenced. 165. WhatisPrivateConstructor?anditsuse?Canyoucreateinstanceofa classwhichhasPrivateConstructor? A:Whenaclassdeclaresonlyprivateinstanceconstructors,itisnotpossiblefor classesoutsidetheprogramtoderivefromtheclassortodirectlycreateinstancesof it.(ExceptNestedclasses) Makeaconstructorprivateif: [Link],youmighthavea specialconstructorusedonlyintheimplementationofyourclass'Clonemethod. [Link],youmay haveaclasscontainingnothingbutSharedutilityfunctions,andnoinstancedata. Creatinginstancesoftheclasswouldwastememory. 166. [Link] instanceoftheclassdoIneedtomakeallconstructorstoprivate? (yes) 167. Overloadedconstructorwillcalldefaultconstructorinternally? (no) 168. Whatarevirtualdestructors? 169. Destructorandfinalize GenerallyinC++[Link] explicitlycallthedestructorsinC++.Andalsotheobjectsaredestroyedinreverse [Link]++youhavecontroloverthedestructors. InC#youcannevercallthem,[Link] thecontroloverthedestructor(inC#)?it'[Link] (GC).[Link] [Link]()method. Pointstoremember: [Link],andcannotbeinvokedexplicitly. [Link],aclasscanhave,atmost,onedestructor. [Link],aclasshasnodestructorsotherthantheone, whichmaybedeclaredinit. [Link]. [Link]
001 fo 13 egaP
codetousetheinstance. [Link] becomeseligiblefordestruction. [Link],thedestructorsinitsinheritancechainarecalled,in order,frommostderivedtoleastderived. [Link] us/cpguide/html/[Link] 170. WhatisthedifferencebetweenFinalizeandDispose(Garbage collection) Classinstancesoftenencapsulatecontroloverresourcesthatarenotmanagedbythe runtime,suchaswindowhandles(HWND),databaseconnections,andsoon. Therefore,youshouldprovidebothanexplicitandanimplicitwaytofreethose [Link] object(destructorsyntaxinC#andtheManagedExtensionsforC++).Thegarbage collectorcallsthismethodatsomepointaftertherearenolongeranyvalidreferences totheobject. Insomecases,youmightwanttoprovideprogrammersusinganobjectwiththeability toexplicitlyreleasetheseexternalresourcesbeforethegarbagecollectorfreesthe [Link],betterperformancecanbe achievediftheprogrammerexplicitlyreleasesresourceswhentheyarenolongerbeing [Link],implementtheDisposemethodprovidedbythe [Link] [Link] alive. NotethatevenwhenyouprovideexplicitcontrolbywayofDispose,youshould [Link] preventresourcesfrompermanentlyleakingiftheprogrammerfailstocallDispose. 171. Whatisclosemethod?HowitsdifferentfromFinalize&Dispose? ** 172. Whatisboxing&unboxing? 173. Whatischeck/uncheck? 174. Whatistheuseofbasekeyword?Tellmeapracticalexampleforbase keywordsusage? 175. [Link]? 176. try { ... } catch { ...//[Link]'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:[Link] [Link] exits. 214. IsgotostatementsupportedinC#?HowaboutJava? GotosaresupportedinC#[Link] providesabsolutelynofunctionality. 215. WhatsdifferentaboutswitchstatementsinC#? [Link]++switchstatement,C#doesnotsupportan [Link],youcanusegotoa switchcase,orgotodefault. case1: cost+=25 break case2: cost+=25 gotocase1 ([Link]) 216. [Link]? [Link] DatabaseInteractionsArePerformedUsingDataCommands DataCanBeCachedinDatasets DatasetsAreIndependentofDataSources DataIsPersistedasXML SchemasDefineDataStructures 217. [Link]? SqlConnectionnwindConn=newSqlConnection("DataSource=localhostIntegrated Security=SSPI"+ "InitialCatalog=northwind") [Link]() 218. Whatarerelationobjectsindatasetandhow&wheretousethem? InaDataSetthatcontainsmultipleDataTableobjects,youcanuseDataRelation
001 fo 33 egaP
objectstorelateonetabletoanother,tonavigatethroughthetables,andtoreturn childorparentrowsfromarelatedtable. AddingaDataRelationtoaDataSetadds, bydefault,aUniqueConstrainttotheparenttableandaForeignKeyConstraintto thechildtable. ThefollowingcodeexamplecreatesaDataRelationusingtwoDataTableobjectsina [Link],whichservesasalink [Link] [Link] [Link] DataColumnandthethirdargumentsetsthechildDataColumn. [Link]("CustOrders", [Link]["Customers"].Columns["CustID"], [Link]["Orders"].Columns["CustID"]) OR privatevoidCreateRelation() { //GettheDataColumnobjectsfromtwoDataTableobjectsinaDataSet. DataColumnparentCol DataColumnchildCol //CodetogettheDataSetnotshownhere. parentCol=[Link]["Customers"].Columns["CustID"] childCol=[Link]["Orders"].Columns["CustID"] //CreateDataRelation. DataRelationrelCustOrder relCustOrder=newDataRelation("CustomersOrders",parentCol,childCol) //AddtherelationtotheDataSet. [Link](relCustOrder) } 219. DifferencebetweenOLEDBProviderandSqlClient? Ans:[Link]/sqlservercombination [Link]'sfasterthanthe Oracleprovider,[Link]'sfaster becauseitaccessesthenativelibrary(whichautomaticallygivesyoubetter performance),anditwaswrittenwithlotsofhelpfromtheSQLServerteam. 220. Whatarethedifferentnamespacesusedintheprojecttoconnectthe database?[Link]? [Link] [Link] OLEDBdatasource,executecommandsagainstthesource,andreadthe results. [Link] ProviderforSQLServer,whichallowsyoutoconnecttoSQLServer7.0,execute commands,[Link] [Link],butisoptimizedforaccesstoSQL Server7.0andlater. [Link] [Link] space. [Link] [Link] themanagedspace. 221. DifferencebetweenDataReaderandDataAdapter/DataSetand DataAdapter? [Link],forwardonlystreamof [Link] reducesystemoverheadbecauseonlyonerowatatimeiseverinmemory. AftercreatinganinstanceoftheCommandobject,youcreateaDataReaderby
001 fo 43 egaP
[Link],asshownin thefollowingexample. SqlDataReadermyReader=[Link]() YouusetheReadmethodoftheDataReaderobjecttoobtainarowfromtheresults ofthequery. while([Link]()) [Link]("\t{0}\t{1}",myReader.GetInt32(0),[Link](1)) [Link]() TheDataSetisamemoryresidentrepresentationofdatathatprovidesaconsistent [Link] multipleanddifferingdatasources,usedwithXMLdata,orusedtomanagedatalocal [Link] tables,constraints,[Link] [Link] alsopersistandreloaditscontentsasXMLanditsschemaasXMLSchemadefinition language(XSD)schema. TheDataAdapterservesasabridgebetweenaDataSetandadatasourceforretrieving [Link],whichchanges thedataintheDataSettomatchthedatainthedatasource,andUpdate,which [Link] connectingtoaMicrosoftSQLServerdatabase,youcanincreaseoverallperformance byusingtheSqlDataAdapteralongwithitsassociatedSqlCommandandSqlConnection. ForotherOLEDBsupporteddatabases,usetheDataAdapterwithitsassociated OleDbCommandandOleDbConnectionobjects. 222. WhichmethoddoyouinvokeontheDataAdaptercontroltoloadyour generateddatasetwithdata? Fill() 223. ExplaindifferentmethodsandPropertiesofDataReaderwhichyouhave usedinyourproject? Read GetString GetInt32 while([Link]()) [Link]("\t{0}\t{1}",myReader.GetInt32(0),[Link](1)) [Link]() 224. [Link]? ReadsXMLschemaanddataintotheDataSet. 225. Inhowmanywayswecanretrievetablerecordscount?Howtofindthe countofrecordsinadataset? foreach([Link]){ //Foreachrow,printthevaluesofeachcolumn. foreach([Link]){ 226. Howtocheckifadatareaderisclosedoropened? IsClosed() 227. [Link] recordisalreadydeletedinSQLSERVERasbackend? ORWhatisconcurrency?Howwillyouavoidconcurrencywhendealingwith dataset?(Oneuserdeletedonerowafterthatanotheruserthroughhis [Link]?Howwillyouavoid theproblem?) ** 228. Howdoyoumerge2datasetsintothethirddatasetinasimplemanner? ORIfyouareexecutingthesestatementsincommandObject."Select*from Table1Select*fromTable2howyouwilldealresultset? ** 229. Howdoyousortadataset? **
001 fo 53 egaP
230. Ifadatasetcontains100rows,howtofetchrowsbetween5and15 only? ** 231. [Link]? CloneCopiesthestructureoftheDataSet,includingallDataTableschemas,relations, [Link]. CopyCopiesboththestructureanddataforthisDataSet. 232. Whatistheuseofparameterobject? ** 233. HowtogenerateXMLfromadatasetandviceversa? ** 234. WhatismethodtogetXMLandschemafromDataset? ans:getXML()andgetSchema() 235. Howdouimplementlockingconceptfordataset? ** ([Link]) 236. [Link]? 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 .[Link] builtontopofthewindow&IIS,it thesameobjectsthattraditional wasalwaysaseparateentity&its applicationswoulduse,[Link] functionalitywaslimited. [Link]'s consumption. GarbageCollection Declarevariablewithdatatype Inbuiltgraphicssupport Cultures
Loadview state
automaticallypopulatedas describedinMaintainingStateina [Link] defaultimplementationofthe LoadViewStatemethodto customizestaterestoration. Process Processincomingformdataand postbackdata updatepropertiesaccordingly. Load LoadPostDatamethod(if IPostBackDataHandleris implemented)
Sendpostback Raisechangeeventsinresponseto RaisePostDataChangedEvent change statechangesbetweenthecurrent method(if notifications andpreviouspostbacks. IPostBackDataHandleris implemented) Handle postback events Prerender Handletheclientsideeventthat causedthepostbackandraise appropriateeventsontheserver. RaisePostBackEventmethod(if IPostBackEventHandleris implemented)
Performanyupdatesbeforethe PreRenderevent [Link] (OnPreRendermethod) madetothestateofthecontrolin theprerenderphasecanbesaved, whilechangesmadeinthe renderingphasearelost. TheViewStatepropertyofa SaveViewStatemethod controlisautomaticallypersistedto [Link] stringobjectissenttotheclient [Link] improvingefficiency,acontrolcan overridetheSaveViewState methodtomodifytheViewState property. Generateoutputtoberenderedto Rendermethod theclient. Performanyfinalcleanupbefore Disposemethod thecontrolistorndown. Referencestoexpensiveresources suchasdatabaseconnectionsmust bereleasedinthisphase. Performanyfinalcleanupbefore UnLoadevent(OnUnLoad [Link] method) authorsgenerallyperformcleanup inDisposeanddonothandlethis event.
Savestate
Render Dispose
Unload
[Link] [Link]. 241. WhatisthedifferencebetweenWebUserControlandWebCustom Control? CustomControls Webcustomcontrolsarecompiledcomponentsthatrunontheserverandthat [Link] [Link],including fullsupportforVisualStudiodesignfeaturessuchasthePropertieswindow,thevisual designer,andtheToolbox. ThereareseveralwaysthatyoucancreateWebcustomcontrols: Youcancompileacontrolthatcombinesthefunctionalityoftwoormore [Link],ifyouneedacontrolthatencapsulatesabutton andatextbox,youcancreateitbycompilingtheexistingcontrolstogether. Ifanexistingservercontrolalmostmeetsyourrequirementsbutlackssome requiredfeatures,youcancustomizethecontrolbyderivingfromitand overridingitsproperties,methods,andevents. IfnoneoftheexistingWebservercontrols(ortheircombinations)meetyour requirements,youcancreateacustomcontrolbyderivingfromoneofthebase [Link] controls,soyoucanfocusonprogrammingthefeaturesyouneed. [Link] applications,youcancreateeitheraWebusercontroloraWebcustomcontrolthat [Link] [Link]. Webusercontrolsareeasytomake,buttheycanbelessconvenienttousein [Link] [Link],usercontrolscanbecreatedinthe visualdesigner,theycanbewrittenwithcodeseparatedfromtheHTML,andtheycan [Link],becauseWebusercontrolsarecompiled dynamicallyatruntimetheycannotbeaddedtotheToolbox,andtheyarerepresented [Link] [Link], [Link],theonlywaytoshare theusercontrolbetweenapplicationsistoputaseparatecopyineachapplication, whichtakesmoremaintenanceifyoumakechangestothecontrol. Webcustomcontrolsarecompiledcode,whichmakesthemeasiertousebutmore [Link] createdthecontrol,however,youcanaddittotheToolboxanddisplayitinavisual designerwithfullPropertieswindowsupportandalltheotherdesigntimefeaturesof [Link],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 [Link] raisedwhenyourapplicationstartsorstopsorwhenanindividualuser'ssessionstarts orstops: [Link], Application_BeginRequestisraisedwhenanyWebFormspageorXMLWeb [Link] [Link] event,Application_EndRequest,providesyouwithanopportunitytocloseor otherwisedisposeofresourcesusedfortherequest. Sessioneventsaresimilartoapplicationevents(thereisaSession_OnStart andaSession_OnEndevent),butareraisedwitheachuniquesessionwithin [Link] fromyourapplicationandendseitherwhenyourapplicationexplicitlyclosesthe sessionorwhenthesessiontimesout. [Link]. 243. [Link]? [Link]&itcanspanacrossmultipleservers. 244. Whatiscookielesssession?Howitworks? Bydefault,[Link] request,[Link],asessioncanbetrackedby [Link]: <sessionStatecookieless="true"/> [Link] 245. Howyouwillhandlesessionwhendeployingapplicationinmorethana server?Describesessionhandlinginawebfarm,howdoesitworkandwhat arethelimits? Bydefault,[Link] request,[Link],[Link] process,[Link]: [Link],eitherusingtheServicessnapinorby executing"netstartaspnet_state"[Link] [Link],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([Link])? Session publicproperties 248. [Link] [Link]?Whatisviewstate? [Link]
001 fo 93 egaP
programming,thiswouldordinarilymeanthatallinformationassociatedwiththepage andthecontrolsonthepagewouldbelostwitheachroundtrip. ToovercomethisinherentlimitationoftraditionalWebprogramming,[Link] pageframeworkincludesvariousoptionstohelpyoupreservechangesthatis,for [Link] automaticallypreservespropertyvaluesofthepageandallthecontrolsonitbetween roundtrips. However,youwillprobablyalsohaveapplicationspecificvaluesthatyouwantto [Link],youcanuseoneofthestatemanagementoptions. ClientBasedStateManagementOptions: ViewState HiddenFormFields Cookies QueryStrings ServerBasedStateManagementOptions ApplicationState SessionState DatabaseSupport 249. Whatarethedisadvantagesofviewstate/whatarethebenefits? Automaticviewstatemanagementisafeatureofservercontrolsthatenablesthemto repopulatetheirpropertyvaluesonaroundtrip(withoutyouhavingtowriteany code).Thisfeaturedoesimpactperformance,however,sinceaservercontrol'sview [Link] whenviewstatehelpsyouandwhenithindersyourpage'sperformance. 250. WhenmaintainingsessionthroughSqlserver,whatistheimpactof ReadandWriteoperationonSessionobjects?willperformancedegrade? Maintainingstateusingdatabasetechnologyisacommonpracticewhenstoringuser [Link] particularlyusefulformaintaininglongtermstateorstatethatmustbepreservedeven iftheservermustberestarted. ** 251. Whatarethecontentsofcookie? ** 252. Howdoyoucreateapermanentcookie? ** 253. WhatisViewState?Whatdoesthe"EnableViewState"propertydo?Why wouldIwantitonoroff? ** 254. ExplainthedifferencesbetweenServersideandClientsidecode? Serversidecodewillprocessatserverside&[Link] code(javascript)willexecuteonlyatclientside. 255. Canyougiveanexampleofwhatmightbebestsuitedtoplaceinthe Application_StartandSession_Startsubroutines? **
256. [Link] [Link]? A: [Link] thesite,applicationorsubdirectorylevelonthesharedhosting platform. Certainoptionscanaffectthesecurity,performanceand stabilityoftheserverand,thereforecannotbechanged. Thefollowing [Link] file(s): browserCaps clientTarget pages customErrors globalization
001 fo 04 egaP
Passport SpecifiesMicrosoftPassportauthenticationasthedefault
001 fo 14 egaP
283. HowdoyouspecifywhetheryourdatashouldbepassedasQuerystring andForms(MainlyaboutPOSTandGET) Throughattributetagofformtag. 284. Whatistheothermethod,otherthanGETandPOST,[Link]? 285. Whatarevalidator?[Link]?Howdou disablethem?[Link]?How [Link]?Howtodisablevalidatorcontrolby clientsideJavaScript? [Link] [Link] [Link],the validationcontrolscanalsoperformvalidation("EnableClientScript"propertysetto true/false)usingclientscript. [Link]: RequiredFieldValidatorControl,CompareValidatorControl,RangeValidatorControl, RegularExpressionValidatorControl,CustomValidatorControl,ValidationSummary Control. 286. Whichtwopropertiesarethereoneveryvalidationcontrol? ControlToValidate,ErrorMessage 287. [Link]? Withinthe<HEAD>sectionofanHTMLdocumentthatwillusethesestyles,addalink tothisexternalCSSstylesheetthat followsthisform: <LINKREL="STYLESHEET"TYPE="text/css"HREF="[Link]"> [Link]. 288. Howdoyouimplementpostbackwithatextbox?Whatispostbackand usestate? MakeAutoPostBackpropertytotrue 289. HowcanyoudebuganASPpage,withouttouchingthecode? 290. WhatisSQLinjection? AnSQLinjectionattack"injects"ormanipulatesSQLcodebyaddingunexpectedSQL toaquery. Manywebpagestakeparametersfromwebuser,andmakeSQLquerytothe [Link],webpagethatusernameandpassword andmakeSQLquerytothedatabasetocheckifauserhasvalidnameandpassword. Username:'or1=1 Password:[Empty] Thiswouldexecutethefollowingqueryagainsttheuserstable: selectcount(*)fromuserswhereuserName=''or1=1'anduserPass='' 291. [Link]? 292. [Link]? 293. [Link]? A:[Link]() [C#] ExceptionLastError StringErrMessage LastError=[Link]() if(LastError!=null) ErrMessage=[Link] else ErrMessage="NoErrors" [Link]("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 [Link] usingN1usingN2 [Link]? Ans:usingalias Eg:usingMyAlias=[Link] 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. [Link]?[Link] [Link]? [Link] [Link] [Link] directoryitislocatedinandtoall [Link] ormodifysettingsspecifiedin [Link] WinNT\[Link]\Framework\<version>\config\[Link] [Link]
001 fo 34 egaP
[Link] filestoensurethattheirvaluescannotbecomepublic(attemptstoaccessthemwill causeASP.NETtoreturn403:Access Forbidden). [Link] auniquecollectionofsettingsfor eachincomingURLtargetrequest(thesesettingsarecalculatedonlyonceandthen [Link] automaticallywatchesforfilechangesandwillinvalidatethecacheifanyofthe configurationfileschange). [Link] 308. [Link]? Configuringsessionstate:Sessionstatefeaturescanbeconfiguredviathe <sessionState>[Link].Todoublethedefaulttimeoutof20 minutes,[Link]: <sessionState timeout="40" /> 309. [Link] file? Off Inproc StateServer SQLServer Indicatesthatsessionstateisnotenabled. Indicatesthatsessionstateisstoredlocally. Indicatesthatsessionstateisstoredonaremoteserver. IndicatesthatsessionstateisstoredontheSQLServer.
310. Whatissmartnavigation? WhenapageisrequestedbyanInternetExplorer5browser,orlater,smartnavigation enhancestheuser'sexperienceofthepagebyperformingthefollowing: eliminatingtheflashcausedbynavigation. persistingthescrollpositionwhenmovingfrompagetopage. persistingelementfocusbetweennavigations. retainingonlythelastpagestateinthebrowser'shistory. [Link] [Link] whendecidingwhethertosetthispropertytotrue. SettheSmartNavigationattributetotrueinthe@[Link]. Whenthepageisrequested,thedynamicallygeneratedclasssetsthisproperty. 311. [Link] itimportanttoundertsandtheseevents? 312. [Link] wouldyouevendothis? 313. Whattagsdoyouneedtoaddwithintheasp:datagridtagstobind columnsmanually 314. WhatbaseclassdoallWebFormsinheritfrom? [Link] 315. [Link]? 316. Isitpossibleformetochangemyaspxfileextensiontosomeother name? Yes. OpenIIS>DefaultWebsite>Properties SelectHomeDirectorytab Clickonconfigurationbutton Clickonadd.Enteraspnet_isapidetails (C:\WINDOWS\[Link]\Framework\v1.0.3705\aspnet_isapi.dll | GET,HEAD,POST,DEBUG)
001 fo 44 egaP
[Link](C:\WINDOWS\[Link]\Framework\v1.0.3705\CONFIG)& addnewextensionunder<httpHandlers>tag <addverb="*"path="*.santhosh"type="[Link]"/> 317. WhatisAutoEventWireupattributefor? (WEBSERVICE&REMOTING) 318. WhatisaWebServiceandwhatistheunderlyingprotocolusedin it?WhyWebServices? [Link] [Link] XMLbasedprotocols,messages,andinterfacedescriptionsforcommunicationand [Link] [Link] overHTTPisthemostcommonlyusedprotocolforinvokingWebservices. TherearethreemainusesofWebservices. 1. ApplicationintegrationWebserviceswithinanintranetarecommonlyusedto [Link],a .NETclientrunningonWindows2000caneasilyinvokeaJavaWebservice runningonamainframeorUnixmachinetoretrievedatafromalegacy application. 2. BusinessintegrationWebservicesallowtradingpartnerstoengageine [Link] [Link] businesswithWebservicesmeansalowbarriertoentrybecauseWebservices canbeaddedtoexistingapplicationsrunningonanyplatformwithoutchanging legacycode. 3. CommercialWebservicesfocusonsellingcontentandbusinessservicesto [Link], commercialWebservicestargetapplicationsnothumansastheirdirectusers. ContinentalAirlinesexposesflightschedulesandstatusWebservicesfortravel [Link],commercial [Link] wouldbeverydifficulttogetcustomerstopayyouforusingaWebservicethat createsbusinesschartswiththecustomers?[Link] achartingcomponent([Link])andinstallitonthesame [Link],itmakessensetosellrealtime [Link] addvaluetoyourservicesandexplorenewmarkets,butultimatelycustomers payforcontentsand/orbusinessservices,notfortechnology 1. AreWebServicesareplacementforotherdistributedcomputingplatforms? [Link]. 2. InaWebservice,[Link] DataSetisbestchoice? A:WebServicewillsupportonlyDataSet. 3. HowtogenerateWebServiceproxy?WhatisSOAP,WSDL,UDDIandthe conceptbehindWebServices?WhatarevariouscomponentsofWSDL?What [Link]? SOAPisanXMLbasedmessagingframeworkspecificallydesignedforexchanging formatteddataacrosstheInternet,forexampleusingrequestandreplymessagesor [Link],easytouse,andcompletelyneutralwith respecttooperatingsystem,programminglanguage,ordistributedcomputing platform. AfterSOAPbecameavailableasamechanismforexchangingXMLmessagesamong enterprises(oramongdisparateapplicationswithinthesameenterprise),abetterway [Link] DescriptionLanguage(WSDL)isaparticularformofanXMLSchema,developedby MicrosoftandIBMforthepurposeofdefiningtheXMLmessage,operation,and
001 fo 54 egaP
[Link] defineswebservicesintermsof"endpoints"[Link] syntaxallowsboththemessagesandtheoperationsonthemessagestobedefined abstractly,[Link] WSDLspecdescribeshowtomapmessagesandoperationstoSOAP1.1,HTTP GET/POST,[Link] [Link] messagecanbemappedtomultipleoperations(orservices)andboundtooneormore communicationsprotocols(using"ports"). TheUniversalDescription,Discovery,andIntegration(UDDI)frameworkdefinesadata model(inXML)andSOAPAPIsforregistrationandsearchesonbusinessinformation, [Link] consortiumofvendors,foundedbyMicrosoft,IBM,andAriba,forthepurposeof developinganInternetstandardforwebservicedescriptionregistrationanddiscovery. Microsoft,IBM,andAribaalsoarehostingtheinitialdeploymentofaUDDIservice, whichisconceptuallypatternedafterDNS(theInternetservicethattranslatesURLs intoTCPaddresses).UDDIusesaprivateagreementprofileofSOAP([Link]'t usetheSOAPserializationformatbecauseit'snotwellsuitedtopassingcompleteXML documents(it'saimedatRPCstyleinteractions).Themainideaisthatbusinessesuse theSOAPAPIstoregisterthemselveswithUDDI,andotherbusinessessearchUDDI whentheywanttodiscoveratradingpartner,forexamplesomeonefromwhomthey wishtoprocuresheetmetal,bolts,[Link] categorizedaccordingtoindustrytypeandgeographicallocation,allowingUDDI consumerstosearchthroughlistsofpotentiallymatchingbusinessestofindthespecific [Link],anothercalltoUDDIis [Link] informationincludesapointertothetargetbusiness'sWSDLorotherXMLschemafile describingthewebservicethatthetargetbusinesspublishes. 4. [Link]? ToaccessanXMLWebservicefromaclientapplication,youfirstaddaWebreference, [Link],Visual StudiocreatesanXMLWebserviceproxyclassautomaticallyandaddsittoyour [Link] marshallingofappropriateargumentsbackandforthbetweentheXMLWebserviceand [Link](WSDL)to createtheproxy. TogenerateanXMLWebserviceproxyclass: Fromacommandprompt,[Link],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 [Link],youuseSecureSocketsLayer(SSL) [Link],useHTTPBasic orDigestauthenticationwithMicrosoftWindowsintegrationtofigureoutwhothe
001 fo 64 egaP
calleris. theseitemscannot: ParseaSOAPrequestforvalidvalues AuthenticateaccessattheWebMethodlevel(theycanauthenticateattheWeb Servicelevel) Stopreadingarequestassoonasitisrecognizedasinvalid [Link] us/cpguide/html/[Link] 8. Howwillyouexpose/publishawebservice? 9. Whatisdiscofile? 10. Whatstheattributeforwebservicemethod?Whatisthenamespacefor creatingwebservice? [WebMethod] [Link] [Link] 11. WhatisRemoting? Theprocessofcommunicationbetweendifferentoperatingsystemprocesses, [Link] architecturedesignedtosimplifycommunicationbetweenobjectslivingindifferent applicationdomains,whetheronthesamecomputerornot,andbetweendifferent contexts,whetherinthesameapplicationdomainornot. 12. Differencebetweenwebservices&remoting? [Link] 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 [Link],enforcing homogenousenvironment. CanalsotakeadvantageofIISfor [Link], applicationneedstoprovide plumbingforensuringthereliability oftheapplication.
TypeSystem
Reliability
Extensibility
Providesextensibilityby allowingustointerceptthe Veryextensiblebyallowingusto SOAPmessagesduringthe customizethedifferentcomponents serializationanddeserialization [Link]. stages. Easytocreateanddeploy. Complextoprogram.
Easeof Programming
001 fo 74 egaP
13. [Link] crossprocesscommunication,eachisdesignedtobenefitadifferenttargetaudience. [Link]..NET Remotingprovidesamorecomplexprogrammingmodelandhasamuchnarrower reach. Asexplainedbefore,theclearperformanceadvantageprovidedbyTCPChannel remotingshouldmakeyouthinkaboutusingthischannelwheneveryoucanaffordto [Link] [Link],[Link] goingtogocrossplatformoryouhavetherequirementofsupportingSOAPviaHTTP, [Link]. [Link] [Link] understandhowbothtechnologiesworkandthenchoosetheonethatisrightforyour [Link] networks,[Link] [Link], .[Link],useWebserviceswhenyouneedtosend andreceivedatafromdifferentcomputingplatforms,[Link] [Link],you [Link] takeadvantageofthebestofbothworlds. [Link] serializedataintomessagesandtheformattheychooseformetadata. [Link] [Link]. .NET [Link] [Link] assembliesformetadata. 14. CanyoupassSOAPmessagesthroughremoting? 15. CAOandSAO. ClientActivatedobjectsarethoseremoteobjectswhoseLifetimeisdirectlyControlled [Link],nottheclienthas completecontroloverthelifetimeoftheobjects. Clientactivatedobjectsareinstantiatedontheserverassoonastheclientrequestthe [Link] firstmethodiscalledontheobject.(InSAOtheobjectisinstantiatedwhentheclient callsthemethodontheobject) 16. singletonandsinglecall. [Link] exists,allclientrequestsareservicedbythatinstance. [Link] invocationwillbeservicedbyadifferentserverinstance,evenifthepreviousinstance hasnotyetbeenrecycledbythesystem. 17. WhatisAsynchronousWebServices? 18. WebClientclassanditsmethods? 19. Flowofremoting? 20. Whatistheuseoftraceutility? UsingtheSOAPTraceUtility TheMicrosoftSimpleObjectAccessProtocol(SOAP)Toolkit2.0includesaTCP/IP traceutility,[Link] byHTTPbetweenaSOAPclientandaserviceontheserver. UsingtheTraceUtilityontheServer Toseeallofaservice'smessagesreceivedfromandsenttoallclients,performthe followingstepsontheserver. 1. Ontheserver,opentheWebServicesDescriptionLanguage(WSDL)file. 2. IntheWSDLfile,locatethe<soap:address>elementthatcorrespondstothe [Link]
001 fo 84 egaP
example,ifthelocationattributespecifies <[Link] <[Link] 3. [Link]. 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 [Link],iftheWSDLcontains <[Link] <[Link] 8. Ontheclient,[Link]. 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,[Link] 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 [Link],the DiffGramformatisimplicitlyused. TheDataSetusestheDiffGramformattoloadandpersistitscontents,andtoserialize [Link] 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="[Link] <DataInstance> </DataInstance> <diffgr:before> </diffgr:before> <diffgr:errors> </diffgr:errors> </diffgr:diffgram> TheDiffGramformatconsistsofthefollowingblocksofdata: <DataInstance> Thenameofthiselement,DataInstance,isusedforexplanationpurposesinthis [Link] [Link],theelementwouldcontainthenameofthe [Link], [Link],orrow,thathasbeenmodifiedis identifiedwiththediffgr:hasChangesannotation. <diffgr:before> [Link] thisblockarematchedtoelementsintheDataInstanceblockusingthediffgr:id annotation. <diffgr:errors> ThisblockoftheDiffGramformatcontainserrorinformationforaparticularrowinthe [Link] DataInstanceblockusingthediffgr:idannotation. 19. IfIreplacemySqlserverwithXMLfilesandhowabouthandlingthesame? 20. WritesyntaxtoserializeclassusingXMLSerializer? (IIS) 21. InwhichprocessdoesIISruns(wasaskingabouttheEXEfile) [Link],[Link] otherthings. [Link]([Link] 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 [Link] authenticationscheme,itisnottechnicallyperforminganyclientauthentication [Link],IISprovides storedcredentialstoWindowsusingaspecialuseraccount,IUSR_machinename.By default,[Link] [Link] password,asubauthenticationDLL([Link])authenticatestheuserusinganetwork [Link] informWindowsthatthepasswordisvalid,[Link], [Link] password,IIScallstheLogonUser()APIinWindowsandprovidestheaccountname, [Link],IIS [Link] possiblefortheanonymoususertoaccessnetworkresources,whereasanetworklogon doesnot. BasicAuthentication IISBasicauthenticationasanimplementationofthebasicauthenticationschemefound insection11oftheHTTP1.0specification. Asthespecificationmakesclear,thismethodis,inandofitself,[Link] reasonisthatBasicauthenticationassumesatrustedconnectionbetweenclientand [Link],[Link] specifically,theyaretransmittedusingBase64encoding,whichistriviallyeasyto [Link] onitsown. [Link] alsoimposesnospecialrequirementsontheserversideuserscanauthenticate againstanyNTdomain,[Link] shelterthesecuritycredentialswhiletheyareintransmission,youhavean authenticationsolutionthatisbothhighlysecureandquiteflexible. DigestAuthentication [Link] authentication,thisisanimplementationofatechniquesuggestedbyWebstandards, namelyRFC2069(supercededbyRFC2617). Digestauthenticationalsousesachallenge/responsemodel,butitismuchmoresecure thanBasicauthentication(whenusedwithoutSSL).Itachievesthisgreatersecurity notbyencryptingthesecret(thepassword)beforesendingit,butratherbyfollowinga differentdesignpatternonethatdoesnotrequiretheclienttotransmitthepassword overthewireatall. Insteadofsendingthepassworditself,theclienttransmitsaonewaymessagedigest (achecksum)oftheuser'spassword,using(bydefault)[Link] thenfetchesthepasswordforthatuserfromaWindows2000DomainController, rerunsthechecksumalgorithmonit,[Link],the serverknowsthattheclientknowsthecorrectpassword,eventhoughthepassword itselfwasneversent.(IfyouhaveeverwonderedwhatthedefaultISAPIfilter"md5filt" thatisinstalledwithIIS5.0isusedfor,nowyouknow. IntegratedWindowsAuthentication IntegratedWindowsauthentication(formerlyknownasNTLMauthenticationand WindowsNTChallenge/Responseauthentication)canuseeitherNTLMorKerberosV5 authenticationandonlyworkswithInternetExplorer2.0andlater. WhenInternetExplorerattemptstoaccessaprotectedresource,IISsendstwoWWW Authenticateheaders,NegotiateandNTLM. IfInternetExplorerrecognizestheNegotiateheader,itwillchooseitbecauseit [Link],thebrowserwillreturninformationforboth [Link],IISwilluseKerberosifboththeclient (InternetExplorer5.0andlater)andserver(IIS5.0andlater)arerunning
001 fo 15 egaP
So,whichmechanismisuseddependsuponanegotiationbetweenInternetExplorer andIIS. WhenusedinconjunctionwithKerberosv5authentication,IIScandelegatesecurity credentialsamongcomputersrunningWindows2000andlaterthataretrustedand [Link] thedelegateduser. IntegratedWindowsauthenticationisthebestauthenticationschemeinanintranet environmentwhereusershaveWindowsdomainaccounts,especiallywhenusing [Link],likedigestauthentication,doesnotpass theuser'[Link],ahashedvalueisexchanged. ClientCertificateMapping Acertificateisadigitallysignedstatementthatcontainsinformationaboutanentity andtheentity'spublickey,thusbindingthesetwopiecesofinformationtogether.A trustedorganization(orentity)calledaCertificationAuthority(CA)issuesacertificate [Link] [Link],anX.509certificateincludestheformatofthecertificate, theserialnumberofthecertificate,thealgorithmusedtosignthecertificate,thename oftheCAthatissuedthecertificate,thenameandpublickeyoftheentityrequesting thecertificate,andtheCA'ssignature.X.509clientcertificatessimplifyauthentication [Link] canverifyacertificatesimplybyexaminingthecertificate. [Link] us/vsent7/html/[Link] 1. HowtoconfigurethesitesinWebserver(IIS)? 2. AdvantagesinIIS6.0? [Link] [Link] dowsserver2003/proddocs/datacenter/gs_whatschanged.asp 3. IISIsolationLevels? InternetInformationServerintroducedthenotion"IsolationLevel",whichisalso presentinIIS4underadifferentname.IIS5supportsthreeisolationlevels,thatyou cansetfromtheHomeDirectorytabofthesite'sPropertiesdialog: Low(IISProcess):[Link],themainIISprocess, [Link],andisthe [Link],IIScrashesaswelland mustberestarted(IIS5hasareliablerestartfeaturethatautomaticallyrestarts aserverwhenafatalerroroccurs). Medium(Pooled):InthiscaseASPrunsinadifferentprocess,whichmakes thissettingmorereliable:ifASPcrashesIISwon'[Link] theMediumisolationlevelsharethesameprocess,soyoucanhaveawebsite runningwithjusttwoprocesses(IISandASPprocess).IIS5isthefirstInternet InformationServerversionthatsupportsthissetting,whichisalsothedefault [Link] runsatthislevelisrununderCOM+,soit'[Link](andyou canseethisexecutableintheTaskManager). High(Isolated):EachASPapplicationrunsoutprocessinitsownprocess space,thereforeifanASPapplicationcrashes,neitherIISnoranyotherASP [Link] andresourcesiftheserverhostsmanyASPapplications.BothIIS4andIIS5 supportsthissetting:[Link],whileunder [Link]. WhenselectinganisolationlevelforyourASPapplication,keepinmindthatout processsettingsthatis,MediumandHigharelessefficientthaninprocess(Low).
001 fo 25 egaP
However,outprocesscommunicationhasbeenvastlyimprovedunderIIS5,andinfact IIS5'sMediumisolationleveloftendeliverbetterresultsthanIIS4'[Link] practice,youshouldn'tsettheLowisolationlevelforanIIS5applicationunlessyou reallyneedtoservehundredspagespersecond. Controls 4. HowwillyoudoRedoandUndoinaTextControl? 5. [Link]?Howwouldumakeacomboboxappear inonecolumnofaDataGrid?Whatarethewaystoshowdatagridinsidea datagridforamasterdetailstypeoftables?IfwewriteanycodeforDataGrid methods,whatistheaccessspecifierusedforthatmethodsinthecode behindfileandwhy? 6. [Link]? Programming 7. WriteaprograminC#forcheckingagivennumberisPRIMEornot. 8. Writeaprogramtofindtheanglebetweenthehoursandminutesinaclock 9. WriteaC#programtofindtheFactorialofn 10. [Link]? A:[Link],youwillneedtousetwo classes:[Link] [Link] [Link] HttpPostedFileclassrepresentstheuploadedfileandisobtainedfromthePostedFile [Link],youneed toaddtheenctypeattributetoyourformtagasfollows: <formid="upload"method="post"runat="server"enctype="multipart/formdata"> Also,rememberthatthe/datadirectoryistheonlydirectorywithWritepermissions [Link],youwillneedtomakesurethattheyour codeuploadsthefiletothe/datadirectoryoroneofitssubdirectories. [Link]#and [Link]. C# <%@ImportNamespace="System"%> <%@ImportNamespace="[Link]"%> <%@ImportNamespace="[Link]"%> <%@ImportNamespace="[Link]"%> <%@ImportNamespace="[Link]"%> <html> <head> <title>upload_cs</title> </head> <scriptlanguage="C#"runat="server"> publicvoidUploadFile(objectsender,EventArgse) { if([Link]!=null) { try { stringstrFileName,strFileNamePath,strFileFolder strFileFolder=[Link](@"data\") strFileName=[Link] strFileName=[Link](strFileName) strFileNamePath=strFileFolder+strFileName [Link](strFileNamePath) [Link]=strFileName [Link]=[Link]() [Link]=[Link]
001 fo 35 egaP
[Link]=true } catch(Exceptionx) { LabellblError=newLabel() [Link]=[Link] [Link]="Exceptionoccurred:"+[Link] [Link]=true [Link](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. [Link]? A:[Link] [Link] tosendmailinC#[Link],you wouldwanttomakesuretosetthestaticSmtpServerpropertyoftheSmtpMailclassto mailfwd. C# <%@ImportNamespace="System"%> <%@ImportNamespace="[Link]"%> <%@ImportNamespace="[Link]"%> <HTML> <HEAD> <title>MailTest</title> </HEAD> <scriptlanguage="C#"runat="server"> privatevoidPage_Load(Objectsender,EventArgse) { try { MailMessagemailObj=newMailMessage() [Link]="sales@[Link]" [Link]="ringleader@[Link]" [Link]="YourWidgetOrder" [Link]="Yourorderwasprocessed." [Link]=[Link] [Link]="mailfwd" [Link](mailObj) [Link]("Mailsentsuccessfully")
001 fo 45 egaP
} catch(Exceptionx) { [Link]("Yourmessagewasnotsent:"+[Link]) } } </script> <body> <formid="mail_test"method="post"runat="server"> </form> </body> </HTML> 12. Writeaprogramtocreateausercontrolwithnameandsurnameasdata membersandloginasmethodandalsothecodetocallit.(Hintuseevent delegates)PracticalExampleofPassinganEventstodelegates 13. Howcanyouread3rdlinefromatextfile?
[Link] o [Link]? o [Link]? o [Link]? o [Link]? o [Link]? o [Link]? o [Link]? o [Link] process? [Link] o 2.1WhatistheCLR? o 2.2WhatistheCTS? o 2.3WhatistheCLS? o 2.4WhatisIL? o 2.5WhatisC#? o 2.6Whatdoes'managed'[Link]? o 2.7Whatisreflection? [Link] o 3.1Whatisanassembly? o 3.2HowcanIproduceanassembly? o 3.3Whatisthedifferencebetweenaprivateassemblyanda sharedassembly? o 3.4Howdoassembliesfindeachother? o 3.5Howdoesassemblyversioningwork? [Link] o 4.1WhatisanApplicationDomain? o 4.2HowdoesanAppDomaingetcreated? o [Link]? [Link] o 5.1Whatisgarbagecollection? o 5.2Isittruethatobjectsdon'talwaysgetdestroyedimmediately whenthelastreferencegoesaway? o 5.3Whydoesn'[Link]? o [Link]? o 5.5DoesnondeterministicdestructionaffecttheusageofCOM objectsfrommanagedcode? o 5.6I'[Link] implementFinalizeonmyclass? o 5.7DoIhaveanycontroloverthegarbagecollectionalgorithm? o 5.8HowcanIfindoutwhatthegarbagecollectorisdoing? [Link] o 6.1Whatisserialization?
001 fo 65 egaP
o o o o o o
[Link] o 7.1Whatareattributes? o 7.2CanIcreatemyownmetadataattributes? o 7.3CanIcreatemyowncontextattributes? [Link] o 8.1WhatisCodeAccessSecurity(CAS)? o 8.2HowdoesCASwork? o 8.3WhodefinestheCAScodegroups? o 8.4HowdoIdefinemyowncodegroup? o 8.5HowdoIchangethepermissionsetforacodegroup? o 8.6CanIcreatemyownpermissionset? o 8.7I'[Link] problem? o 8.8Ican'[Link]? [Link](IL) o 9.1CanIlookattheILforanassembly? o 9.2CansourcecodebereverseengineeredfromIL? o 9.3HowcanIstopmycodebeingreverseengineeredfromIL? o 9.4CanIwriteILprogramsdirectly? o 9.5CanIdothingsinILthatIcan'tdoinC#? [Link] o 10.1IsCOMdead? o 10.2IsDCOMdead? o 10.3IsMTS/COM+dead? o [Link]? o [Link]? o [Link]? [Link] o [Link]? o [Link]? [Link] 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?
[Link]
[Link]?
That'[Link],.NETisa "revolutionarynewplatform,builtonopenInternetprotocolsandstandards, withtoolsandservicesthatmeldcomputingandcommunicationsinnew ways". [Link] developingandrunningsoftwareapplications,featuringeaseofdevelopment ofwebbasedservices,richstandardruntimeservicesavailableto componentswritteninavarietyofprogramminglanguages,andinter languageandintermachineinteroperability. Notethatwhentheterm".NET"isusedinthisFAQitrefersonlytothenew .[Link]".NET Framework".ThisFAQdoesNOTcoveranyofthevariousotherexistingand newproducts/[Link](e.g. [Link]).
001 fo 85 egaP
[Link]?
[Link](usingATL/COM,MFC,VB,orevenraw Win32),.NETmayofferaviablealternative(oraddition)tothewayyoudo [Link],ifyoudodevelopwebsites,[Link] [Link].
[Link]?
BillGatesdeliveredakeynoteatForum2000,heldJune22,2000,outlining [Link]'vision'.[Link] technology,anddelegatesweregivenCDscontainingaprereleaseversionof [Link]/[Link].
[Link]?
Thefinalversionofthe1.0SDKandruntimewasmadepubliclyavailable [Link],thefinalversionofVisual [Link].
[Link]?
Thereareanumberoftools,describedhereinascendingorderofcost:
.NETFrameworkSDK:TheSDKisfreeandincludescommandline compilersforC++,C#,[Link] development. [Link]:[Link] [Link],the downloadincludesasimplewebserverthatcanbeusedinsteadofIISto [Link] WindowsXPHomeEdition,whichcannotrunIIS. MicrosoftVisualC#.NETStandard2003:Thisisacheap(around$100) versionofVisualStudiolimitedtoonelanguageandalsowithlimited [Link],there'snowizardsupportforclasslibraries [Link],orforsavvy developerswhocanworkaroundthedeficienciesinthesuppliedwizards. AswellasC#,[Link]++versions. MicrosoftVisualStudio.NETProfessional2003:Ifyouhavealicensefor VisualStudio6.0,[Link] VS.NET2002foratoken$[Link] theMSlanguages(C#,C++,[Link])andhasextensivewizardsupport.
001 fo 95 egaP
[Link]?
TheruntimesupportsWindowsXP,Windows2000,NT4SP6aandWindows ME/[Link] workonallplatformsforexample,[Link] andWindows2000.Windows98/MEcannotbeusedfordevelopment. IISisnotsupportedonWindowsXPHomeEdition,andsocannotbeusedto [Link],[Link] Home. [Link].
[Link]?
MSprovidescompilersforC#,C++,[Link] [Link] COBOL,Eiffel,Perl,SmalltalkandPython.
[Link] process?
From[Link] ECMAGeneralAssemblyratifiedtheC#andcommonlanguageinfrastructure (CLI)[Link] knownasECMA334(C#)andECMA335(theCLI)."
[Link]
2.1WhatistheCLR?
CLR=[Link] that(intheory)[Link],regardlessof [Link](Microsoft)liststhefollowingCLR resourcesinhisMSDNPDC#article:
2.2WhatistheCTS?
CTS=[Link] understands,[Link] [Link] supersetoftheCLS.
2.3WhatistheCLS?
CLS=[Link] .[Link] [Link] anylanguage. [Link] exampleallowingaC#classtoinheritfromaVBclass.
2.4WhatisIL?
IL=[Link](MicrosoftIntermediate Language)orCIL(CommonIntermediateLanguage).[Link](of anylanguage)[Link] thepointwherethesoftwareisinstalled,oratruntimebyaJustInTime (JIT)compiler.
2.5WhatisC#?
C#[Link]. 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'[Link]?
Theterm'managed'[Link] [Link],meaningslightlydifferentthings. Managedcode:[Link] theprogramsthatrunwithinitforexampleexceptionhandlingandsecurity. Fortheseservicestowork,thecodemustprovideaminimumlevelof
001 fo 16 egaP
[Link]#and [Link].VS7C++codeisnotmanaged bydefault,butthecompilercanproducemanagedcodebyspecifyinga commandlineswitch(/com+). Manageddata:[Link] runtime'sgarbagecollector.C#[Link].VS7 C++dataisunmanagedbydefault,evenwhenusingthe/com+switch,butit canbemarkedasmanagedusingthe__gckeyword. Managedclasses:ThisisusuallyreferredtointhecontextofManaged Extensions(ME)forC++.WhenusingMEC++,aclasscanbemarkedwith the__gckeyword.Asthenamesuggests,thismeansthatthememoryfor instancesoftheclassismanagedbythegarbagecollector,butitalsomeans [Link] [Link] benefitisproperinteropwithclasseswritteninotherlanguagesforexample, amanagedC++[Link] isthatamanagedclasscanonlyinheritfromonebaseclass.
2.7Whatisreflection?
[Link] [Link](modulesin turnarepackagedtogetherinassemblies),andcanbeaccessedbya [Link] classesthatcanbeusedtointerrogatethetypesforamodule/assembly. [Link] ITypeLib/ITypeInfotoaccesstypelibrarydatainCOM,anditisusedfor [Link] context/process/machineboundaries. Reflectioncanalsobeusedtodynamicallyinvokemethods(see [Link]),orevencreatetypesdynamicallyatruntime ([Link]).
[Link]
3.1Whatisanassembly?
[Link],andcanbean application(withamainentrypoint)[Link] ormorefiles(dlls,exes,htmlfilesetc),andrepresentsagroupofresources, typedefinitions,[Link] [Link],typesandreferences [Link] assembly,thusmakingtheassemblyselfdescribing.
001 fo 26 egaP
Animportantaspectofassembliesisthattheyarepartoftheidentityofa [Link] [Link],forexample,thatifassemblyAexportsatypecalled T,andassemblyBexportsatypecalledT,[Link] [Link],don'tgetconfusedbetween assembliesandnamespacesnamespacesaremerelyahierarchicalwayof [Link],typenamesaretypenames, [Link]'sthe assemblyplusthetypename(regardlessofwhetherthetypenamebelongsto anamespace)thatuniquelyindentifiesatypetotheruntime. [Link] securityrestrictionsareenforcedattheassemblyboundary. Finally,[Link].
3.2HowcanIproduceanassembly?
[Link] example,thefollowingC#program:
publicclassCTest { publicCTest() { [Link]("HellofromCTest") } }
canbecompiledintoalibraryassembly(dll)likethis:
csc/t:[Link]
3.3Whatisthedifferencebetweenaprivateassemblyanda sharedassembly?
001 fo 36 egaP
Versioning:Theruntimeenforcesversioningconstraintsonlyonshared assemblies,notonprivateassemblies.
3.4Howdoassembliesfindeachother?
[Link] path(suchastheAppDomainhost,andapplicationconfigurationfiles),butfor privateassembliesthesearchpathisnormallytheapplication'sdirectoryand [Link],thesearchpathisnormallysameas theprivateassemblypathplusthesharedassemblycache.
3.5Howdoesassemblyversioningwork?
[Link] eachreferencetoanassembly(fromanotherassembly)includesboththe nameandversionofthereferencedassembly. Theversionnumberhasfournumericparts(e.g.[Link]).Assemblieswith [Link] thefirsttwopartsarethesame,butthethirdisdifferent,theassembliesare deemedas'maybecompatible'.Ifonlythefourthpartisdifferent,the [Link],thisisjustthedefaultguideline itistheversionpolicythatdecidestowhatextenttheserulesareenforced. Theversionpolicycanbespecifiedviatheapplicationconfigurationfile. Remember:versioningisonlyappliedtosharedassemblies,notprivate assemblies.
[Link]
4.1WhatisanApplicationDomain?
[Link] [Link] AppDomainistoisolateanapplicationfromotherapplications. Win32processesprovideisolationbyhavingdistinctmemoryaddressspaces. Thisiseffective,butitisexpensiveanddoesn'[Link] enforcesAppDomainisolationbykeepingcontrolovertheuseofmemoryall [Link],sotheruntime canensurethatAppDomainsdonotaccesseachother'smemory.
4.2HowdoesanAppDomaingetcreated?
[Link] Shell,[Link] line,[Link] application.
001 fo 46 egaP
[Link]?
[Link],[Link] monikerdevelopedbyJasonWhittingtonandDonBox ([Link] [Link].
[Link]
5.1Whatisgarbagecollection?
Garbagecollectionisasystemwherebyaruntimecomponenttakes responsibilityformanagingthelifetimeofobjectsandtheheapmemorythat [Link] languages/runtimeshaveusedgarbagecollectionforsometime.
5.2Isittruethatobjectsdon'talwaysgetdestroyed immediatelywhenthelastreferencegoesaway?
001 fo 56 egaP
[Link] willbedestroyedanditsmemoryreclaimed. Thereisaninterestingthreadinthearchives,startedbyChrisSells,aboutthe implicationsofnondeterministicdestructionofobjectsinC#: [Link] 819 InOctober2000,Microsoft'sBrianHarrypostedalengthyanalysisofthe problem: [Link] 8572 ChrisSells'responsetoBrian'spostingishere: [Link] 83
5.3Whydoesn'[Link] destruction?
[Link] byperiodicallyrunningthroughalistofalltheobjectsthatarecurrentlybeing [Link]'tfindduringthis [Link] ofthisalgorithmisthattheruntimedoesn'tgetnotifiedimmediatelywhenthe finalreferenceonanobjectgoesawayitonlyfindsoutduringthenext sweepoftheheap. Futhermore,thistypeofalgorithmworksbestbyperformingthegarbage [Link] foracollectionsweep.
[Link]?
It'[Link] maintainexpensiveorscarceresources([Link]),youneedto providesomewayfortheclienttotelltheobjecttoreleasetheresourcewhen [Link]() [Link],thiscausesproblemsfordistributedobjectsina distributedsystemwhocallstheDispose()method?Someformofreference countingorownershipmanagementmechanismisneededtohandle distributedobjectsunfortunatelytheruntimeoffersnohelpwiththis.
5.5Doesnondeterministicdestructionaffecttheusageof COMobjectsfrommanagedcode?
[Link],youareeffectivelyrelying [Link] objectholdsontoanexpensiveresourcewhichisonlycleanedupafterthe
001 fo 66 egaP
finalrelease,youmayneedtoprovideanewinterfaceonyourobjectwhich supportsanexplicitDispose()method.
5.6I'[Link] IimplementFinalizeonmyclass?
AnobjectwithaFinalizemethodismoreworkforthegarbagecollectorthan [Link] objectsareFinalized,sothereareissuessurroundingaccesstootherobjects [Link],thereisnoguaranteethataFinalizemethod willgetcalledonanobject,soitshouldneverbereliedupontodocleanupof anobject'sresources. Microsoftrecommendthefollowingpattern:
publicclassCTest:IDisposable { publicvoidDispose() { ...//Cleanupactivities [Link](this) } ~CTest()//C#syntaxhidingtheFinalize()method { Dispose() } }
5.7DoIhaveanycontroloverthegarbagecollection algorithm?
[Link],[Link] forcesthegarbagecollectortocollectallunreferencedobjectsimmediately.
5.8HowcanIfindoutwhatthegarbagecollectorisdoing?
[Link]'.NET CLRxxx'[Link].
[Link]
6.1Whatisserialization?
001 fo 76 egaP
[Link] serialization?
[Link] XmlSerializerandSoapFormatter/[Link] XmlSerializerforWebServices,andusesSoapFormatter/BinaryFormatterfor [Link].
[Link] XmlSerializer,SoapFormatterorBinaryFormatter?
[Link] thetargetclasshasaparameterlessconstructor,andonlypublicread/write [Link],ontheplusside, XmlSerializerhasgoodsupportforcustomisingtheXMLdocumentthatis [Link]'sfeaturesmeanthatitismostsuitable forcrossplatformwork,orforconstructingobjectsfromexistingXML documents. SoapFormatterandBinaryFormatterhavefewerlimitationsthanXmlSerializer. Theycanserializeprivatefields,[Link] thetargetclassbemarkedwiththe[Serializable]attribute,solike [Link] therearesomequirkstowatchoutforforexampleondeserializationthe constructorofthenewobjectisnotinvoked. ThechoicebetweenSoapFormatterandBinaryFormatterdependsonthe [Link] [Link] [Link], foreaseofdebuggingifnothingelse.
6.4CanIcustomisetheserializationprocess?
[Link] [Link],afieldorpropertycanbe markedwiththe[XmlIgnore][Link] exampleisthe[XmlElement]attribute,whichcanbeusedtospecifytheXML elementnametobeusedforaparticularpropertyorfield. SerializationviaSoapFormatter/BinaryFormattercanalsobecontrolledto [Link],the[NonSerialized]attributeisthe equivalentofXmlSerializer's[XmlIgnore][Link]
001 fo 86 egaP
serializationprocesscanbeacheivedbyimplementingthetheISerializable interfaceontheclasswhoseinstancesaretobeserialized.
6.5WhyisXmlSerializersoslow?
[Link] timeyouserializeordeserializeanobjectofagiventypeinanapplication, [Link]'tmatter,butitmaymean,for example,thatXmlSerializerisapoorchoiceforloadingconfigurationsettings duringstartupofaGUIapplication.
6.6WhydoIgeterrorswhenItrytoserializeaHashtable?
XmlSerializerwillrefusetoserializeinstancesofanyclassthatimplements IDictionary,[Link] thisrestriction.
[Link]
7.1Whatareattributes?
[Link] metadataattributeitallowssomedatatobeattachedtoaclassormethod. Thisdatabecomespartofthemetadatafortheclass,and(likeotherclass metadata)[Link] is[serializable],whichcanbeattachedtoaclassandmeansthatinstancesof theclasscanbeserialized.
[serializable]publicclassCTest{}
7.2CanIcreatemyownmetadataattributes?
[Link] [Link]:
[AttributeUsage([Link])]
001 fo 96 egaP
[InspiredBy("AndyMc'[Link]")] classCTest { }
7.3CanIcreatemyowncontextattributes?
[Link]'ssample(calledCallThreshold)at [Link] [Link]://[Link]/
[Link]
8.1WhatisCodeAccessSecurity(CAS)?
[Link] pieceofcodeisallowedtorun,andwhatresourcesitcanusewhenitis [Link],[Link] formattingyourharddisk.
8.2HowdoesCASwork?
TheCASsecuritypolicyrevolvesaroundtwokeyconceptscodegroupsand [Link], andeachcodegroupisgrantedthepermissionsspecifiedinanamed permissionset. Forexample,usingthedefaultsecuritypolicy,acontroldownloadedfroma websitebelongstothe'ZoneInternet'codegroup,whichadherestothe
001 fo 07 egaP
8.3WhodefinestheCAScodegroups?
Microsoftdefinessomedefaultones,butyoucanmodifytheseandeven [Link],run'caspol lg'[Link]:
Level=Machine CodeGroups: [Link]:Nothing [Link]:FullTrust [Link]:SkipVerification [Link]:LocalIntranet 1.3. ZoneInternet:Internet [Link]:Nothing [Link]:Internet [Link] 0024000004800000940000000602000000240000525341310004000003 000000CFCB3291AA715FE99D40D49040336F9056D7886FED46775BC7BB5430BA4444FEF834 8EBD06 F962F39776AE4DC3B7B04A7FE6F49F25F740423EBF2C0B89698D8D08AC48D69CED0FC8F83B 465E08 07AC11EC1DCC7D054E807A43336DDE408A5393A48556123272CEEEE72F1660B71927D3856 1AABF5C AC1DF1734633C602F8F2D5:Everything
8.4HowdoIdefinemyowncodegroup?
[Link],[Link] andyouwantithavefullaccesstoyoursystem,butyouwanttokeepthe [Link],youwouldadda newcodegroupasasubgroupofthe'ZoneInternet'group,likethis:
[Link]
Nowifyouruncaspollgyouwillseethatthenewgrouphasbeenaddedas group1.3.1:
... [Link]:Internet [Link]:FullTrust ...
001 fo 17 egaP
8.5HowdoIchangethepermissionsetforacodegroup?
[Link],youcanoperateatthe 'machine'levelwhichmeansnotonlythatthechangesyoumakebecomethe defaultforthemachine,butalsothatuserscannotchangethepermissionsto [Link](nonadmin)useryoucanstillmodify thepermissions,[Link],to allowintranetcodetodowhatitlikesyoumightdothis:
caspolcg1.2FullTrust
8.6CanIcreatemyownpermissionset?
[Link],specifyinganXMLfilecontainingthepermissionsinthe [Link],hereisasamplefilecorrespondingto the'Everything'[Link] editedthesample,addittotherangeofavailablepermissionsetslikethis:
[Link]
Then,toapplythepermissionsettoacodegroup,dosomethinglikethis:
caspolcg1.3SamplePermSet
(Bydefault,1.3isthe'Internet'codegroup)
8.7I'[Link] problem?
[Link],youcanaskcaspoltotell youwhatcodegroupanassemblybelongsto,[Link],you canaskwhatpermissionsarebeingappliedtoaparticularassemblyusing caspolrsp.
8.8Ican'[Link]?
Yes,[Link]:
caspolsoff
[Link](IL)
001 fo 27 egaP
9.1CanIlookattheILforanassembly?
[Link] andILforanassembly.
9.2CansourcecodebereverseengineeredfromIL?
Yes,itisoftenrelativelystraightforwardtoregeneratehighlevelsource(e.g. C#)fromIL.
9.3HowcanIstopmycodebeingreverseengineeredfrom IL?
Thereiscurrentlynosimplewaytostopcodebeingreverseengineeredfrom [Link],either [Link]'optimising'theILinsucha waythatreverseengineeringbecomesmuchmoredifficult. Ofcourseifyouarewritingwebservicesthenreverseengineeringisnota problemasclientsdonothaveaccesstoyourIL.
9.4CanIwriteILprogramsdirectly?
[Link]:
.assemblyMyAssembly{} .classMyApp{ .methodstaticvoidMain(){ .entrypoint ldstr"Hello,IL!" [Link]::WriteLine([Link]) ret } }
[Link],[Link] assemblywillbegenerated.
9.5CanIdothingsinILthatIcan'tdoinC#?
[Link] [Link],andyoucanhavenonzerobasedarrays.
[Link]
10.1IsCOMdead?
Thissubjectcausesalotofcontroversy,asyou'llseeifyoureadthemailing [Link]:
001 fo 37 egaP
[Link] =68241 [Link] 761 FWIWmyviewisasfollows:COMismanythings,andit'sdifferentthingsto [Link],COMisfundamentallyabouthowlittleblobsof codefindotherlittleblobsofcode,andhowtheycommunicatewitheachother [Link] [Link]'pure'.NETworld,[Link] objects,littleblobsofcodestillfindeachotherandtalktoeachother,butthey don'[Link] waysforexample,typeinformationisstoredinatabularformpackagedwith thecomponent,whichisquitesimilartopackagingatypelibrarywithaCOM [Link]'snotCOM. So,doesthismatter?Well,Idon'treallycareaboutmostoftheCOMstuff goingawayIdon'tcarethatfindingcomponentsdoesn'tinvolveatriptothe registry,orthatIdon'[Link] thatIwouldn'tliketogoawayIwouldn'tliketolosetheideaofinterface [Link]'sgreateststrength,inmyopinion,isitsinsistence onacastironseparationbetweeninterfaceandimplementation. Unfortunately,[Link] youdointerfacebaseddevelopment,butitdoesn'[Link] arguethathavingachoicecanneverbeabadthing,andmaybethey'reright, butIcan'thelpfeelingthatmaybeit'sabackwardstep.
10.2IsDCOMdead?
Prettymuch,[Link] [Link] interopscenarios.
10.3IsMTS/COM+dead?
[Link] COM+services(throughaninteroplayer)ratherthanreplacetheserviceswith [Link] [Link] supportforcoreservices(JITactivation,transactions)butnotsomeofthe higherlevelservices([Link]+Events,Queuedcomponents). Overtimeitisexpectedthatinteropwillbecomemoreseamlessthismay meanthatsomeservicesbecomeacorepartoftheCLR,and/oritmaymean thatsomeserviceswillberewrittenasmanagedcodewhichrunsontopofthe CLR. Formoreonthistopic,searchforpostingsbyJoeLonginthearchivesJoeis theMSgroupmanagerforCOM+.Startwiththismessage:
001 fo 47 egaP
[Link] 370
[Link]?
[Link] CallableWrapper(RCW).ThiswrapperturnstheCOMinterfacesexposedby [Link] interfaces,[Link] nonoleautomationinterfaces,itmaybenecessarytodevelopacustomRCW [Link] compatibletypes. Here'[Link],createanATL componentwhichimplementsthefollowingIDL:
import"[Link]" import"[Link]" [ 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("[Link]") importlib("[Link]") [ uuid(600CE6D95ED74B4DBB49E8D5D5096F70), helpstring("CppNameClass") ] coclassCppName { [default]interfaceICppName } }
Whenyou'vebuiltthecomponent,[Link] TLBIMPutilityonthetypelibary,likethis:
001 fo 57 egaP
[Link]
Ifsuccessful,youwillgetamessagelikethis:
[Link]
[Link]'suseC#.[Link] followingcode:
usingSystem usingCPPCOMSERVERLib publicclassMainApp { staticpublicvoidMain() { CppNamecppname=newCppName() [Link]("bob") [Link]("Nameis"+[Link]()) } }
[Link]?
Yes..NETcomponentsareaccessedfromCOMviaaCOMCallableWrapper (CCW).ThisissimilartoaRCW(seepreviousquestion),butworksinthe [Link],ifthewrappercannotbeautomaticallygeneratedby [Link],oriftheautomaticbehaviourisnotdesirable,a [Link],forCOMto'see'[Link], [Link]. Here'[Link]#[Link] followinginit:
usingSystem
001 fo 67 egaP
[Link]:
csc/target:[Link]
Youshouldgetadll,whichyouregisterlikethis:
[Link]/tlb:[Link]/codebase
[Link] [Link]:
DimdotNetObj SetdotNetObj=CreateObject("[Link]") [Link]("bob") MsgBox"Nameis"&[Link]()
andrunthescriptlikethis:
[Link]
[Link]?
Yes,[Link] coursemanydevelopersmaywishtocontinueusingATLtowriteC++COM componentsthatliveoutsidetheframework,butifyouareinsideyouwill almostcertainlywanttouseC#.RawC++(andthereforeATLwhichisbased onit)doesn'[Link]'sjusttoonearthe metalandprovidestoomuchflexibilityfortheruntimetobeabletomanage it.
[Link]
001 fo 77 egaP
[Link]?
.[Link] [Link] forLANsorWANs(internet). [Link] SOAP(XMLbased)[Link],theHTTPchannelusesSOAP(via [Link]),andtheTCPchanneluses binary([Link]).Buteither channelcanuseeitherserializationformat. Thereareanumberofstylesofremoteaccess:
[Link]?
UseP/[Link],butisusedto [Link] C#callingtheWin32MessageBoxfunction:
usingSystem [Link] classMainApp { [DllImport("[Link]",EntryPoint="MessageBox",SetLastError=true, CharSet=[Link])] publicstaticexternintMessageBox(inthWnd,StringstrMessage,StringstrCaption, uintuiType)
001 fo 87 egaP
publicstaticvoidMain() { MessageBox(0,"Hello,thisisPInvokeinoperation!",".NET",0) } }
[Link]
12.1FileI/O
12.1.1HowdoIreadfromatextfile? First,[Link]:
FileStreamfs=newFileStream(@"c:\[Link]",[Link],[Link])
FinallyclosetheStreamReaderobject:
[Link]()
12.2TextProcessing
12.2.1Areregularexpressionssupported? [Link],the followingcodeupdatesthetitleinanHTMLfile:
FileStreamfs=newFileStream("[Link]",[Link],[Link]) StreamReadersr=newStreamReader(fs)
001 fo 97 egaP
12.3Internet
12.3.1HowdoIdownloadawebpage? [Link] object:
WebRequestrequest=[Link]("[Link]
Thenaskfortheresponsefromtherequest:
WebResponseresponse=[Link]()
[Link] accesstheresponsestreamlikethis:
Streams=[Link]() //Outputthedownloadedstreamtotheconsole StreamReadersr=newStreamReader(s) stringline while((line=[Link]())!=null) [Link](line)
Alternatively,tosettheproxyforaspecificwebrequest,dothis:
HttpWebRequestrequest=(HttpWebRequest)[Link]("[Link] [Link]=newWebProxy("proxyname",80)
12.4XML
12.4.1IsDOMsupported?
001 fo 08 egaP
[Link]:
<PEOPLE> <PERSON>Fred</PERSON> <PERSON>Bill</PERSON> </PEOPLE>
Thisdocumentcanbeparsedasfollows:
XmlDocumentdoc=newXmlDocument() [Link]("[Link]") XmlNoderoot=[Link] foreach([Link]) [Link]([Link]())
Theoutputis:
Fred Bill
12.4.3IsXPathsupported? Yes,viatheXPathXXXclasses:
XPathDocumentxpdoc=newXPathDocument("[Link]") XPathNavigatornav=[Link]() XPathExpressionexpr=[Link]("descendant::PEOPLE/PERSON") XPathNodeIteratoriterator=[Link](expr) while([Link]()) [Link]([Link])
12.5Threading
12.5.1Ismultithreadingsupported?
001 fo 18 egaP
InthiscasecreatinganinstanceoftheMyThreadclassissufficienttospawn [Link]()method:
MyThreadt=newMyThread("Hello,world.") [Link]()
12.5.3HowdoIstopathread? [Link],youcanuseyourowncommunication [Link] [Link] [Link]()[Link]().Theformerwillcausea ThreadInterruptedExceptiontobethrownonthethreadwhenitnextgoesinto [Link],[Link] [Link] contrast,[Link]()throwsaThreadAbortExceptionregardlessofwhat [Link],theThreadAbortExceptioncannotnormally becaught(thoughtheThreadStart'sfinallymethodwillbeexecuted). [Link]()isaheavyhandedmechanismwhichshouldnotnormallybe required.
001 fo 28 egaP
C#hasa'lock'keywordwhichprovidesaconvenientshorthandforthecode above:
classC
001 fo 38 egaP
12.6Tracing
12.6.1Istherebuiltinsupportfortracing/logging? Yes,[Link] [Link] differenceisthattracingfromtheDebugclassonlyworksinbuildsthathave theDEBUGsymboldefined,whereastracingfromtheTraceclassonlyworksin [Link] [Link] workindebugandreleasebuilds,[Link] tracingthatyouwanttoworkonlyindebugbuilds. 12.6.2CanIredirecttracingtoafile? [Link],whichisa [Link] [Link] singlesink,[Link] outputtotheWin32OutputDebugString()functionandalsothe [Link]()[Link], butifyou'retryingtotraceaproblematacustomersite,redirectingthe [Link],theTextWriterTraceListener classisprovidedforthispurpose.
001 fo 48 egaP
Here'showtousetheTextWriterTraceListenerclasstoredirectTraceoutputto afile:
[Link]() FileStreamfs=newFileStream(@"c:\[Link]",[Link],[Link]) [Link](newTextWriterTraceListener(fs)) [Link](@"Thiswillbewritentoc:\[Link]!") [Link]()
[Link]()[Link] don'tdothis,theoutputwillgotothefileandOutputDebugString().Typically thisisnotwhatyouwant,becauseOutputDebugString()imposesabig performancehit. 12.6.3CanIcustomisethetraceoutput? [Link],anddirectalloutput [Link]'sasimpleexample,whichderivesfrom TextWriterTraceListener(andthereforehasinbuiltsupportforwritingtofiles, asshownabove)andaddstiminginformationandthethreadIDforeachtrace line:
classMyListener:TextWriterTraceListener { publicMyListener(Streams):base(s) { } publicoverridevoidWriteLine(strings) { [Link]("{0:D8}[{1:D4}]{2}", Environment.TickCountm_startTickCount, [Link](), s) } protectedintm_startTickCount=[Link] }
[Link]
13.1Recommendedbooks
001 fo 58 egaP
[Link] Muchanticipated,mainlyduetoRichter'ssuperbWin32books,andmost [Link]'applied'isalittlemisleadingthisbookis [Link]'underthehood'. ExamplesareinC#,butthereisalsoaseparateVBeditionofthebook. Essential.NETVolume1,TheCommonLanguageRuntimeDonBox Asuperbbook,whichIrecommendtoanyonewhoalreadyhassome .NETdevelopmentexperience,andwantstogetadeeperunderstanding [Link]'sclearthatBoxhasdeeplyresearchedthe topicsandthencarefullyconstructedacoherentstoryaroundhis [Link]'[Link]. C#[Link],2ndEditionAndrewTroelsen RegardedbymanyasthebestallroundC#/.[Link] includingWindowsForms,COMinterop,[Link],[Link] [Link] Platform:AnAdvancedGuide. ProgrammingWindowswithC#CharlesPetzold AnotherslightlymisleadingtitlethisbookissolelyaboutGUI programmingWindowsFormsandGDI+.Wellwritten,with [Link](minor)criticismisthatthebook stickscloselytothefacts,withoutofferingagreatdealinthewayof 'tipsandtricks'forrealworldapps. WindowsFormsProgramminginC#ChrisSells Ihaven'treadthismyselfyet,butanythingSellswritesisusuallyworth reading. [Link] Coverslotsofinterestingtopicsthatotherbooksdon't,includingATL7, ManagedC++,internationalization,remoting,aswellasthemorerun ofthemillCLRandC#[Link]. ThisbookismostsuitableforreasonablyexperiencedC++ programmers. [Link] BalenaisareknownedVBer,[Link] glowing. .NETandCOMTheCompleteInteroperabilityGuideAdamNathan Don'tbeputoffbythesizethisbookisveryeasytodigestthanksto
001 fo 68 egaP
[Link]/COMinterop.
[Link] Widelyrecommended.
13.2InternetResources
[Link]://[Link]/net/. MicrosoftalsohostGOTDOTNET. [Link]. [Link] .NETresources. [Link] [Link] [Link] [Link].*newsgroups MyC#FAQforC++Programmers.
13.3Weblogs
ThefollowingWeblogs('blogs')[Link]:
[Link](BradWilson) CharlesCook:[Link]. GwynCole:CoauthorofDevelopingWMIsolutions. ChrisBrumme BradAbrams DonBox JohnLam PeterDrayton:CoauthorofC#EssentialsandC#inaNutshell. IngoRammer:[Link]. DrewMarsh TomasRestrepo JustinRudd SimonFell:DeveloperofPocketSOAP. RichardCaetano ChrisSells
13.4Samplecode&utilities
LutzRoederhassomegreatutilitiesandlibrariesat [Link] PeterDrayton'[Link]://[Link]/ DonBox&JasonWhittington'[Link] [Link]
001 fo 78 egaP
TransactSQLOptimizationTips IndexOptimizationtips TSQLQueries DataTypes Index Joins Lock StoredProcedure Trigger View Transaction Other XML Tools Permission Administration
TransactSQLOptimizationTips
Useviewsandstoredproceduresinsteadofheavydutyqueries. Thiscanreducenetworktraffic,becauseyourclientwillsendtoserver onlystoredprocedureorviewname(perhapswithsomeparameters) [Link] permissionmanagementalso,becauseyoucanrestrictuseraccessto tablecolumnstheyshouldnotsee. Trytouseconstraintsinsteadoftriggers,wheneverpossible. Constraintsaremuchmoreefficientthantriggersandcanboost [Link],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 [Link] derivedtables,ifyouneedtoperformrowbyrowoperations. TrytoavoidtheHAVINGclause,wheneverpossible. TheHAVINGclauseisusedtorestricttheresultsetreturnedbythe [Link],the GROUPBYclausedividestherowsintosetsofgroupedrowsand aggregatestheirvalues,andthentheHAVINGclauseeliminates [Link],youcanwriteyourselect statementso,thatitwillcontainonlyWHEREandGROUPBYclauses [Link] query. Ifyouneedtoreturnthetotaltable'srowcount,youcanuse alternativewayinsteadofSELECTCOUNT(*)statement. BecauseSELECTCOUNT(*)statementmakeafulltablescantoreturn thetotaltable'srowcount,itcantakeverymanytimeforthelarge [Link]. Youcanusesysindexessystemtable,[Link] [Link] [Link],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 [Link] serverandtheclients. Trytorestrictthequeriesresultsetbyreturningonlythe particularcolumnsfromthetable,notalltable'scolumns. Thiscanresultsingoodperformancebenefits,becauseSQLServerwill returntoclientonlyparticularcolumns,notalltable'[Link] reducenetworktrafficandboosttheoverallperformanceofthequery.
EveryindexincreasesthetimeintakestoperformINSERTS,UPDATES andDELETES,[Link] usemaximum45indexesononetable,[Link] table,thenthenumberofindexesmaybeincreased. [Link] indexandreducesthenumberofreadsrequiredtoreadtheindex. Trytocreateindexesoncolumnsthathaveintegervaluesratherthan charactervalues. Ifyoucreateacomposite(multicolumn)index,theorderofthecolumns [Link] enhanceselectivity,withthemostselectivecolumnstotheleftmostof thekey. Ifyouwanttojoinseveraltables,trytocreatesurrogateintegerkeys forthispurposeandcreateindexesontheircolumns. Createsurrogateintegerprimarykey(identityforexample)ifyourtable willnothavemanyinsertoperations. Clusteredindexesaremorepreferablethannonclustered,ifyouneedto selectbyarangeofvaluesoryouneedtosortresultssetwithGROUP BYorORDERBY. Ifyourapplicationwillbeperformingthesamequeryoverandoveron thesametable,considercreatingacoveringindexonthetable. YoucanusetheSQLServerProfilerCreateTraceWizardwith"Identify ScansofLargeTables"tracetodeterminewhichtablesinyourdatabase [Link] byqueriesinsteadofusinganindex. Youcanusesp_MSforeachtableundocumentedstoredprocedureto [Link] CPUidletimeandslowproductionperiods. sp_MSforeachtable@command1="print'?'DBCCDBREINDEX('?')"
TSQLQueries
1. 2tables
EmployeePhone empid empname empid salary phnumber mgrid
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? [Link],[Link] FROMEmployeee1INNERJOIN [Link]=[Link] [Link] 7. 2tablesempandphone. empfieldsareempid,name Phfieldsareempid,ph(office,mobile,home).Selectallemployees whodoesn'thaveanyphnos. SELECT* FROMemployeeLEFTOUTERJOIN [Link]=[Link] WHERE([Link]='') AND([Link]='') AND([Link]='') 8. Findemployeewhoislivinginmorethanonecity. TwoTables:
Emp Empid empName Salary City Empid City
GROUPBYempid HAVINGCOUNT(empid)>1)) 10. Findallemployeeswhoislivinginthesamecity.(tableissameas above) SELECTfname FROMemployee WHERE(empidIN (SELECTempid FROMcitya WHEREcityIN (SELECTcity FROMcityb GROUPBYcity HAVINGCOUNT(city)>1))) 11. ThereisatablenamedMovieTablewiththreecolumns moviename,[Link] [Link]. [Link] FROMMovieTablem1INNERJOIN [Link]=[Link] WHERE([Link]='amitabh'[Link]='vinod'OR [Link]='amitabh'[Link]='vinod')AND([Link]= 'actor')AND([Link]='actor') [Link] 12. [Link] containssamestructure(salarydetails).ButEmp2salarydetailsare [Link],writeaquerywhich correctssalarydetailsofthetableemp2 [Link]=b.salfromemp1a,[Link]=[Link] 13. GivenaTablenamedStudentswhichcontainsstudentid, subjectidandmarks.Wherethereare10subjectsand50students. WriteaQuerytofindouttheMaximummarksobtainedineachsubject. 14. InthissametablesnowwriteaSQLQuerytogetthestudentid alsotocombinewithpreviousresults. 15. Threetablesstudent,course,markshowdogoatfinding nameofthestudentswhogotmaxmarksinthediffcourses. [Link],[Link],[Link], [Link] FROMmarksINNERJOIN [Link]=[Link] [Link]=[Link] WHERE([Link]= (SELECTMAX(Mark) FROMMarksMaxMark [Link]=[Link])) 16. Thereisatableday_tempwhichhasthreecolumnsdayid,dayand [Link] temperatureamongeachotherforsevendaysofaweek? [Link],[Link],[Link],[Link]
001 fo 29 egaP
FROMday_tempaINNERJOIN day_tempbONa.dayid=[Link]+1 OR [Link],[Link],temperatureb [Link]=[Link]+1 17. Thereisatablewhichcontainsthenameslikethis.a1,a2,a3,a3, a4,a1,a1,[Link], andtotalsalariesofindividualemployeesinonequery. SELECTempid,SUM(salary)ASsalary FROMemployee GROUPBYempidWITHROLLUP ORDERBYempid 18. Howtoknowhowmanytablescontainsempnoasacolumn inadatabase? SELECTCOUNT(*)ASCounter FROMsyscolumns WHERE(name='empno') 19. Findduplicaterowsinatable?ORIhaveatablewithone [Link] 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. [Link] 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=[Link] GROUPBYname Result: coke60 mirinda0 pepsi10 30. ANY,SOME,orALL? ALLmeansgreaterthaneveryvalueinotherwords,greaterthanthe [Link],>ALL(1,2,3)meansgreaterthan3. ANYmeansgreaterthanatleastonevalue,thatis,greaterthanthe [Link]>ANY(1,2,3)meansgreaterthan1.SOMEisanSQL92 standardequivalentforANY. 31. IN&=(differenceincorrelatedsubquery) INDEX
001 fo 59 egaP
32. WhatisIndex?Itspurpose? [Link],an indexallowsthedatabaseprogramtofinddatainatablewithout [Link] tablewiththestoragelocationsofrowsinthetablethatcontaineach [Link] combinationofcolumnsinatableandareimplementedintheformofB [Link](thesearch key)[Link],and [Link] example,anindexoncolumnsA,B,CcanbesearchedefficientlyonA, onA,B,andA,B,C. 33. ExplainaboutClusteredandnonclusteredindex?Howto choosebetweenaClusteredIndexandaNonClusteredIndex? [Link] specialtypeofindexthatreordersthewayrecordsinthetableare [Link] leafnodesofaclusteredindexcontainthedatapages. Anonclusteredindexisaspecialtypeofindexinwhichthelogicalorder oftheindexdoesnotmatchthephysicalstoredorderoftherowson [Link] [Link],theleafnodescontainindexrows. Considerusingaclusteredindexfor: o Columnsthatcontainalargenumberofdistinctvalues. o Queriesthatreturnarangeofvaluesusingoperatorssuchas BETWEEN,>,>=,<,and<=. o Columnsthatareaccessedsequentially. o Queriesthatreturnlargeresultsets. NonclusteredindexeshavethesameBtreestructureasclustered indexes,withtwosignificantdifferences: o Thedatarowsarenotsortedandstoredinorderbasedontheir nonclusteredkeys. o Theleaflayerofanonclusteredindexdoesnotconsistofthedata [Link],[Link] containsthenonclusteredkeyvalueandoneormorerowlocators thatpointtothedatarow(orrowsiftheindexisnotunique) havingthekeyvalue. o Pertableonly249nonclusteredindexes. 34. Disadvantageofindex? EveryindexincreasesthetimeintakestoperformINSERTS,UPDATES andDELETES,sothenumberofindexesshouldnotbeverymuch. 35. GivenascenariothatIhavea10ClusteredIndexinaTable [Link] disadvantages? A:Only1clusteredindexispossible. 36. HowcanIenforcetouseparticularindex? Youcanuseindexhint(index=<index_name>)afterthetablename. SELECTau_lnameFROMauthors(index=aunmind)
001 fo 69 egaP
37. WhatisIndexTuning? Oneofthehardesttasksfacingdatabaseadministratorsistheselection [Link] creatingnonclusteredindexesonanycolumnsthatarefrequently [Link] candidatesarecolumnsreferencedbyJOINandGROUPBYoperations. Youmaywishtoalsoconsidercreatingnonclusteredindexesthatcover [Link] queriesarereferredtoascoveredqueriesandexperienceexcellent performancegains. IndexTuningistheprocessoffindingappropriatecolumnfornon clusteredindexes. SQLServerprovidesawonderfulfacilityknownastheIndexTuning Wizardwhichgreatlyenhancestheindexselectionprocess. 38. DifferencebetweenIndexdefragandIndexrebuild? Whenyoucreateanindexinthedatabase,theindexinformationused [Link] [Link] aremadetothedatathataffecttheindex,theinformationintheindex [Link] thestorageoftheindexdata(andtabledatainthecaseofaclustered index)[Link] reducingthenumberofpagereadsrequiredtoobtaintherequested data DBCCINDEXDEFRAGDefragmentsclusteredandsecondaryindexesof thespecifiedtableorview. ** 39. Whatissortingandwhatisthedifferencebetweensorting &clusteredindexes? TheORDERBYclausesortsqueryresultsbyoneormorecolumnsupto 8,[Link] [Link],while inserting/updatingthetable. 40. Whatarestatistics,underwhatcircumstancestheygoout ofdate,howdoyouupdatethem? [Link] hasuniquevaluesthentheselectivityofthatindexismore,asopposed [Link] 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 [Link] thevaluesintheindexedcolumnsarechanged,MicrosoftSQL Server2000mayhavetoreorganizethestorageofthedatainthe tabletomakeroomforthenewrowandmaintaintheorderedstorageof [Link] orchanged,SQLServermayhavetoreorganizethestorageofthedata [Link] page,SQLServermovesapproximatelyhalftherowstoanewpageto [Link] [Link] thedatainatable. Whencreatinganindex,youcanspecifyafillfactortoleaveextragaps andreserveapercentageoffreespaceoneachleaflevelpageofthe indextoaccommodatefutureexpansioninthestorageofthetable's [Link] percentagefrom0to100thatspecifieshowmuchtofillthedatapages aftertheindexiscreated.Avalueof100meansthepageswillbefull [Link] usedonlywhentherewillbenochangestothedata,forexample,ona [Link] pages,whichreducestheneedtosplitdatapagesasindexesgrowbut [Link] 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,[Link]. TheSQL92synonymforcharischaracter. nvarchar(n)VariablelengthUnicodecharacterdataofncharacters.n mustbeavaluefrom1through4,[Link],inbytes,istwo timesthenumberofcharactersentered.Thedataenteredcanbe0 charactersinlength.TheSQL92synonymsfornvarchararenational charvaryingandnationalcharactervarying. varchar[(n)]VariablelengthnonUnicodecharacterdatawithlengthof nbytes.nmustbeavaluefrom1through8,[Link] actuallengthinbytesofthedataentered,[Link]
001 fo 89 egaP
canbe0charactersinlength.TheSQL92synonymsforvarcharare charvaryingorcharactervarying. 44. GUIDdatasize? 128bit 45. HowGUIDbecominguniqueacrossmachines? Toensureuniquenessacrossmachines,theIDofthenetworkcardis used(amongothers)tocomputethenumber. 46. Whatisthedifferencebetweentextandimagedatatype? [Link] than255charactersinSQLServer6.5,ormorethan8000inSQLServer [Link](BLOBs)suchasdigitalimages. Withtextandimagedatatypes,thedataisnotstoredintherow,sothe [Link] [Link], ntext,andimagevaluescanbeamaximumof2GB,whichistoolongto storeinasingledatarow. JOINS 47. Whatarejoins? Sometimeswehavetoselectdatafromtwoormoretablestomakeour [Link]. 48. HowmanytypesofJoins? Joinscanbecategorizedas: Innerjoins(thetypicaljoinoperation,whichusessome comparisonoperatorlike=or<>).Theseincludeequijoinsand naturaljoins. Innerjoinsuseacomparisonoperatortomatchrowsfromtwo tablesbasedonthevaluesincommoncolumnsfromeachtable. Forexample,retrievingallrowswherethestudentidentification numberisthesameinboththestudentsandcoursestables. [Link],aright,orfullouterjoin. Outerjoinsarespecifiedwithoneofthefollowingsetsofkeywords whentheyarespecifiedintheFROMclause: LEFTJOINorLEFTOUTERJOINTheresultsetofaleftouter joinincludesalltherowsfromthelefttablespecifiedinthe LEFTOUTERclause,notjusttheonesinwhichthejoined [Link] matchingrowsintherighttable,theassociatedresultset rowcontainsnullvaluesforallselectlistcolumnscoming fromtherighttable. RIGHTJOINorRIGHTOUTERJOINArightouterjoinisthe [Link] [Link] arighttablerowhasnomatchingrowinthelefttable. FULLJOINorFULLOUTERJOINAfullouterjoinreturnsall [Link] matchintheothertable,theselectlistcolumnsfromthe [Link]
001 fo 99 egaP
betweenthetables,theentireresultsetrowcontainsdata valuesfromthebasetables. CrossjoinsCrossjoinsreturnallrowsfromthelefttable,each rowfromthelefttableiscombinedwithallrowsfromtheright [Link].(A [Link] whenyoujoineveryrowofonetabletoeveryrowofanother [Link] rowofitself.) 49. Whatisselfjoin? Atablecanbejoinedtoitselfinaselfjoin. 50. WhatarethedifferencesbetweenUNIONandJOINS? [Link]. 51. CanIimproveperformancebyusingtheANSIstylejoins insteadoftheoldstylejoins? CodeExample1: [Link],[Link] fromsysobjectso,sysindexesi [Link]=[Link] CodeExample2: [Link],[Link] fromsysobjectsoinnerjoinsysindexesi [Link]=[Link] YouwillnotgetanyperformancegainbyswitchingtotheANSIstyle JOINsyntax. UsingtheANSIJOINsyntaxgivesyouanimportantadvantage:Because thejoinlogiciscleanlyseparatedfromthefilteringcriteria,youcan understandthequerylogicmorequickly. TheSQLServeroldstyleJOINexecutesthefilteringconditionsbefore executingthejoins,whereastheANSIstyleJOINreversesthis procedure(joinlogicprecedesfiltering). PerhapsthemostcompellingargumentforswitchingtotheANSIstyle JOINisthatMicrosofthasexplicitlystatedthatSQLServerwillnot [Link] 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