You are on page 1of 45

(Framework) 1. Whatis.NETFramework? The.NETFrameworkhastwomaincomponents:thecommonlanguageruntimeand the.NETFrameworkclasslibrary. Youcanthinkoftheruntimeasanagentthatmanagescodeatexecutiontime, providingcoreservicessuchasmemorymanagement,threadmanagement,and remoting,whilealsoenforcingstricttypesafetyandotherformsofcodeaccuracythat ensuresecurityandrobustness. Theclasslibrary,isacomprehensive,objectorientedcollectionofreusabletypesthat youcanusetodevelopapplicationsrangingfromtraditionalcommandlineor graphicaluserinterface(GUI)applicationstoapplicationsbasedonthelatest innovationsprovidedbyASP.NET,suchasWebFormsandXMLWebservices. 2. WhatisCLR?

TheCLSissimplyaspecificationthatdefinestherulestosupportlanguageintegration insuchawaythatprogramswritteninanylanguage,yetcaninteroperatewithone another,takingfulladvantageofinheritance,polymorphism,exceptions,andother features.TheserulesandthespecificationaredocumentedintheECMAproposed standarddocument,"PartitionIArchitecture",availablehere. 3. Is.NETaruntimeserviceoradevelopmentplatform? Ans:It'sbothandactuallyalotmore.Microsoft.NETincludesanewwayofdelivering softwareandservicestobusinessesandconsumers.ApartofMicrosoft.NETisthe .NETFrameworks.The.NETframeworksSDKconsistsoftwoparts:the.NETcommon languageruntimeandthe.NETclasslibrary.Inaddition,theSDKalsoincludes commandlinecompilersforC#,C++,JScript,andVB.Youusethesecompilersto buildapplicationsandcomponents.Thesecomponentsrequiretheruntimetoexecute sothisisadevelopmentplatform. 4. WhatarethenewfeaturesofFramework1.1? 1. NativeSupportforDevelopingMobileWebApplications 2. EnableExecutionofWindowsFormsAssembliesOriginatingfromtheInternet AssembliesoriginatingfromtheInternetzoneforexample,Microsoft WindowsFormscontrolsembeddedinanInternetbasedWebpageor WindowsFormsassemblieshostedonanInternetWebserverandloaded eitherthroughtheWebbrowserorprogrammaticallyusingthe System.Reflection.Assembly.LoadFrom()methodnowreceivesufficient permissiontoexecuteinasemitrustedmanner.Defaultsecuritypolicyhas beenchangedsothatassembliesassignedbythecommonlanguageruntime (CLR)totheInternetzonecodegroupnowreceivetheconstrained permissionsassociatedwiththeInternetpermissionset.Inthe.NET Framework1.0ServicePack1andServicePack2,suchapplicationsreceived thepermissionsassociatedwiththeNothingpermissionsetandcouldnot execute. 3. EnableCodeAccessSecurityforASP.NETApplications Systemsadministratorscannowusecodeaccesssecuritytofurtherlockdown thepermissionsgrantedtoASP.NETWebapplicationsandWebservices. Althoughtheoperatingsystemaccountunderwhichanapplicationruns imposessecurityrestrictionsontheapplication,thecodeaccesssecurity systemoftheCLRcanenforceadditionalrestrictionsonselectedapplication resourcesbasedonpoliciesspecifiedbysystemsadministrators.Youcanuse thisfeatureinasharedserverenvironment(suchasanInternetservice provider(ISP)hostingmultipleWebapplicationsononeserver)toisolate separateapplicationsfromoneanother,aswellaswithstandaloneservers whereyouwantapplicationstorunwiththeminimumnecessaryprivileges. 4. NativeSupportforCommunicatingwithODBCandOracleDatabases 5. UnifiedProgrammingModelforSmartClientApplicationDevelopment TheMicrosoft.NETCompactFrameworkbringstheCLR,WindowsForms controls,andother.NETFrameworkfeaturestosmalldevices.The.NET

CompactFrameworksupportsalargesubsetofthe.NETFrameworkclass libraryoptimizedforsmalldevices. 6. SupportforIPv6 The.NETFramework1.1supportstheemergingupdatetotheInternet Protocol,commonlyreferredtoasIPversion6,orsimplyIPv6.Thisprotocolis designedtosignificantlyincreasetheaddressspaceusedtoidentify communicationendpointsintheInternettoaccommodateitsongoinggrowth. http://msdn.microsoft.com/netframework/technologyinfo/Overview/whatsnew.aspx 5. WhatisCodeAccessSecurity(CAS)? CASisthepartofthe.NETsecuritymodelthatdetermineswhetherornotapieceof codeisallowedtorun,andwhatresourcesitcanusewhenitisrunning.Forexample, itisCASthatwillpreventa.NETwebappletfromformattingyourharddisk. HowdoesCASwork? TheCASsecuritypolicyrevolvesaroundtwokeyconceptscodegroupsand permissions.Each.NETassemblyisamemberofaparticularcodegroup,andeach codegroupisgrantedthepermissionsspecifiedinanamedpermissionset. Forexample,usingthedefaultsecuritypolicy,acontroldownloadedfromawebsite belongstothe'ZoneInternet'codegroup,whichadherestothepermissionsdefined bythe'Internet'namedpermissionset.(Naturallythe'Internet'namedpermissionset representsaveryrestrictiverangeofpermissions.) WhodefinestheCAScodegroups? Microsoftdefinessomedefaultones,butyoucanmodifytheseandevencreateyour own.Toseethecodegroupsdefinedonyoursystem,run'caspollg'fromthe commandline.Onmyssystemitlookslikethis: 6. Level=Machine 7. CodeGroups: 8. 9. 1.Allcode:Nothing 10. 1.1.ZoneMyComputer:FullTrust 11. 1.1.1.HonorSkipVerificationrequests:SkipVerification 12. 1.2.ZoneIntranet:LocalIntranet 13. 1.3.ZoneInternet:Internet 14. 1.4.ZoneUntrusted:Nothing 15. 1.5.ZoneTrusted:Internet 16. 1.6.StrongName 0024000004800000940000000602000000240000525341310004000003 17. 000000CFCB3291AA715FE99D40D49040336F9056D7886FED46775BC7BB5430BA44 44FEF8348EBD06 18. F962F39776AE4DC3B7B04A7FE6F49F25F740423EBF2C0B89698D8D08AC48D69CED 0FC8F83B465E08 19. 07AC11EC1DCC7D054E807A43336DDE408A5393A48556123272CEEEE72F1660B71 927D38561AABF5C AC1DF1734633C602F8F2D5:Everything Notethehierarchyofcodegroupsthetopofthehierarchyisthemostgeneral('All code'),whichisthensubdividedintoseveralgroups,eachofwhichinturncanbe subdivided.Alsonotethat(somewhatcounterintuitively)asubgroupcanbe associatedwithamorepermissivepermissionsetthanitsparent. HowdoIdefinemyowncodegroup? Usecaspol.Forexample,supposeyoutrustcodefromwww.mydomain.comandyou

wantithavefullaccesstoyoursystem,butyouwanttokeepthedefaultrestrictions forallotherinternetsites.Toachievethis,youwouldaddanewcodegroupasasub groupofthe'ZoneInternet'group,likethis: caspolag1.3sitewww.mydomain.comFullTrust Nowifyouruncaspollgyouwillseethatthenewgrouphasbeenaddedasgroup 1.3.1: ... 1.3. ZoneInternet:Internet 1.3.1. Sitewww.mydomain.com:FullTrust ... Notethatthenumericlabel(1.3.1)isjustacaspolinventiontomakethecodegroups easytomanipulatefromthecommandline.Theunderlyingruntimeneverseesit. HowdoIchangethepermissionsetforacodegroup? Usecaspol.Ifyouarethemachineadministrator,youcanoperateatthe'machine' levelwhichmeansnotonlythatthechangesyoumakebecomethedefaultforthe machine,butalsothatuserscannotchangethepermissionstobemorepermissive.If youareanormal(nonadmin)useryoucanstillmodifythepermissions,butonlyto makethemmorerestrictive.Forexample,toallowintranetcodetodowhatitlikes youmightdothis: caspolcg1.2FullTrust Notethatbecausethisismorepermissivethanthedefaultpolicy(onastandard system),youshouldonlydothisatthemachineleveldoingitattheuserlevelwill havenoeffect. CanIcreatemyownpermissionset? Yes.Usecaspolap,specifyinganXMLfilecontainingthepermissionsinthe permissionset.Tosaveyousometime,hereisasamplefilecorrespondingtothe 'Everything'permissionsetjustedittosuityourneeds.Whenyouhaveeditedthe sample,addittotherangeofavailablepermissionsetslikethis: caspolapsamplepermset.xml Then,toapplythepermissionsettoacodegroup,dosomethinglikethis: caspolcg1.3SamplePermSet(Bydefault,1.3isthe'Internet'codegroup) I'mhavingsometroublewithCAS.HowcanIdiagnosemyproblem? Caspolhasacoupleofoptionsthatmighthelp.First,youcanaskcaspoltotellyou whatcodegroupanassemblybelongsto,usingcaspolrsg.Similarly,youcanask whatpermissionsarebeingappliedtoaparticularassemblyusingcaspolrsp. Ican'tbebotheredwithallthisCASstuff.CanIturnitoff? Yes,aslongasyouareanadministrator.Justrun: caspolsoff 20.WhatisMSIL,IL? Whencompilingtomanagedcode,thecompilertranslatesyoursourcecodeinto Microsoftintermediatelanguage(MSIL),whichisaCPUindependentsetof instructionsthatcanbeefficientlyconvertedtonativecode.MSILincludesinstructions forloading,storing,initializing,andcallingmethodsonobjects,aswellasinstructions forarithmeticandlogicaloperations,controlflow,directmemoryaccess,exception handling,andotheroperations.Microsoftintermediatelanguage(MSIL)isalanguage usedastheoutputofanumberofcompilersandastheinputtoajustintime(JIT) compiler.ThecommonlanguageruntimeincludesaJITcompilerforconvertingMSIL tonativecode. 21.CanIwriteILprogramsdirectly? Yes.PeterDraytonpostedthissimpleexampletotheDOTNETmailinglist: .assemblyMyAssembly{} .classMyApp{ .methodstaticvoidMain(){ .entrypoint ldstr "Hello,IL!" call voidSystem.Console::WriteLine(classSystem.Object)

ret } } Justputthisintoafilecalledhello.il,andthenrunilasmhello.il.Anexeassemblywill begenerated. CanIdothingsinILthatIcan'tdoinC#? Yes.Acoupleofsimpleexamplesarethatyoucanthrowexceptionsthatarenot derivedfromSystem.Exception,andyoucanhavenonzerobasedarrays. 22.WhatisCTS? Thecommontypesystemdefineshowtypesaredeclared,used,andmanagedinthe runtime,andisalsoanimportantpartoftheruntime'ssupportforcrosslanguage integration. Thecommontypesystemsupportstwogeneralcategoriesoftypes,eachofwhichis furtherdividedintosubcategories: Valuetypes Valuetypesdirectlycontaintheirdata,andinstancesofvaluetypesareeither allocatedonthestackorallocatedinlineinastructure.Valuetypescanbe builtin(implementedbytheruntime),userdefined,orenumerations. Referencetypes Referencetypesstoreareferencetothevalue'smemoryaddress,andare allocatedontheheap.Referencetypescanbeselfdescribingtypes,pointer types,orinterfacetypes.Thetypeofareferencetypecanbedeterminedfrom valuesofselfdescribingtypes.Selfdescribingtypesarefurthersplitinto arraysandclasstypes.Theclasstypesareuserdefinedclasses,boxedvalue types,anddelegates. 23.WhatisJIT(justintime)?howitworks? BeforeMicrosoftintermediatelanguage(MSIL)canbeexecuted,itmustbeconverted bya.NETFrameworkjustintime(JIT)compilertonativecode,whichisCPUspecific codethatrunsonthesamecomputerarchitectureastheJITcompiler. RatherthanusingtimeandmemorytoconvertalltheMSILinaportableexecutable (PE)filetonativecode,itconvertstheMSILasitisneededduringexecutionand storestheresultingnativecodesothatitisaccessibleforsubsequentcalls. Theruntimesuppliesanothermodeofcompilationcalledinstalltimecodegeneration. TheinstalltimecodegenerationmodeconvertsMSILtonativecodejustasthe regularJITcompilerdoes,butitconvertslargerunitsofcodeatatime,storingthe resultingnativecodeforusewhentheassemblyissubsequentlyloadedandexecuted. AspartofcompilingMSILtonativecode,codemustpassaverificationprocessunless anadministratorhasestablishedasecuritypolicythatallowscodetobypass verification.VerificationexaminesMSILandmetadatatofindoutwhetherthecode canbedeterminedtobetypesafe,whichmeansthatitisknowntoaccessonlythe memorylocationsitisauthorizedtoaccess. 24.Whatisstrongname? Anamethatconsistsofanassembly'sidentityitssimpletextname,versionnumber, andcultureinformation(ifprovided)strengthenedbyapublickeyandadigital signaturegeneratedovertheassembly. 25.Whatisportableexecutable(PE)? Thefileformatdefiningthestructurethatallexecutablefiles(EXE)andDynamicLink Libraries(DLL)mustusetoallowthemtobeloadedandexecutedbyWindows.PEis derivedfromtheMicrosoftCommonObjectFileFormat(COFF).TheEXEandDLLfiles createdusingthe.NETFrameworkobeythePE/COFFformatsandalsoaddadditional headeranddatasectionstothefilesthatareonlyusedbytheCLR.Thespecification forthePE/COFFfileformatsisavailableat http://www.microsoft.com/whdc/hwdev/hardware/pecoffdown.mspx 26.Whichnamespaceisthebaseclassfor.netClasslibrary? Ans:system.object 27.WhatisEventDelegate?clearsyntaxforwritingaeventdelegate Theeventkeywordletsyouspecifyadelegatethatwillbecalledupontheoccurrence ofsome"event"inyourcode.Thedelegatecanhaveoneormoreassociatedmethods thatwillbecalledwhenyourcodeindicatesthattheeventhasoccurred.Aneventin

oneprogramcanbemadeavailabletootherprogramsthattargetthe.NETFramework CommonLanguageRuntime. //keyword_delegate.cs //delegatedeclaration delegatevoidMyDelegate(inti) 28. classProgram 29. { 30. publicstaticvoidMain() 31. { 32. TakesADelegate(newMyDelegate(DelegateFunction)) 33. } 34. publicstaticvoidTakesADelegate(MyDelegateSomeFunction) 35. { 36. SomeFunction(21) 37. } 38. publicstaticvoidDelegateFunction(inti) 39. { 40. System.Console.WriteLine("Calledbydelegatewithnumber:{0}.",i) 41. } } 42.Whatareobjectpoolingandconnectionpoolinganddifference?Wheredowe settheMinandMaxPoolsizeforconnectionpooling? ObjectpoolingisaCOM+servicethatenablesyoutoreducetheoverheadofcreating eachobjectfromscratch.Whenanobjectisactivated,itispulledfromthepool.When theobjectisdeactivated,itisplacedbackintothepooltoawaitthenextrequest.You canconfigureobjectpoolingbyapplyingtheObjectPoolingAttributeattributetoaclass thatderivesfromtheSystem.EnterpriseServices.ServicedComponentclass. Objectpoolingletsyoucontrolthenumberofconnectionsyouuse,asopposedto connectionpooling,whereyoucontrolthemaximumnumberreached. Followingareimportantdifferencesbetweenobjectpoolingandconnectionpooling: Creation.Whenusingconnectionpooling,creationisonthesamethread,so ifthereisnothinginthepool,aconnectioniscreatedonyourbehalf.With objectpooling,thepoolmightdecidetocreateanewobject.However,ifyou havealreadyreachedyourmaximum,itinsteadgivesyouthenextavailable object.Thisiscrucialbehaviorwhenittakesalongtimetocreateanobject, butyoudonotuseitforverylong. Enforcementofminimumsandmaximums.Thisisnotdoneinconnection pooling.Themaximumvalueinobjectpoolingisveryimportantwhentryingto scaleyourapplication.Youmightneedtomultiplexthousandsofrequeststo justafewobjects.(TPC/Cbenchmarksrelyonthis.) COM+objectpoolingisidenticaltowhatisusedin.NETFrameworkmanagedSQL Clientconnectionpooling.Forexample,creationisonadifferentthreadand minimumsandmaximumsareenforced. 43.WhatisApplicationDomain? TheprimarypurposeoftheAppDomainistoisolateanapplicationfromother applications.Win32processesprovideisolationbyhavingdistinctmemoryaddress spaces.Thisiseffective,butitisexpensiveanddoesn'tscalewell.The.NETruntime enforcesAppDomainisolationbykeepingcontrolovertheuseofmemoryallmemory intheAppDomainismanagedbythe.NETruntime,sotheruntimecanensurethat AppDomainsdonotaccesseachother'smemory. Objectsindifferentapplicationdomainscommunicateeitherbytransportingcopiesof objectsacrossapplicationdomainboundaries,orbyusingaproxytoexchange messages. MarshalByRefObjectisthebaseclassforobjectsthatcommunicateacross applicationdomainboundariesbyexchangingmessagesusingaproxy.Objectsthatdo

notinheritfromMarshalByRefObjectareimplicitlymarshalbyvalue.Whenaremote applicationreferencesamarshalbyvalueobject,acopyoftheobjectispassedacross applicationdomainboundaries. HowdoesanAppDomaingetcreated? AppDomainsareusuallycreatedbyhosts.ExamplesofhostsaretheWindowsShell, ASP.NETandIE.Whenyouruna.NETapplicationfromthecommandline,thehostis theShell.TheShellcreatesanewAppDomainforeveryapplication. AppDomainscanalsobeexplicitlycreatedby.NETapplications.HereisaC#sample whichcreatesanAppDomain,createsaninstanceofanobjectinsideit,andthen executesoneoftheobject'smethods.Notethatyoumustnametheexecutable 'appdomaintest.exe'forthiscodetoworkasis. usingSystem usingSystem.Runtime.Remoting publicclassCAppDomainInfo:MarshalByRefObject { publicstringGetAppDomainInfo() { return"AppDomain="+AppDomain.CurrentDomain.FriendlyName } } publicclassApp { publicstaticintMain() { AppDomainad=AppDomain.CreateDomain("Andy'snewdomain",null, null) ObjectHandleoh=ad.CreateInstance("appdomaintest", "CAppDomainInfo") CAppDomainInfoadInfo=(CAppDomainInfo)(oh.Unwrap()) stringinfo=adInfo.GetAppDomainInfo() Console.WriteLine("AppDomaininfo:"+info) return0 } } 44.Whatisserializationin.NET?Whatarethewaystocontrolserialization? Serializationistheprocessofconvertinganobjectintoastreamofbytes. Deserializationistheoppositeprocessofcreatinganobjectfromastreamofbytes. Serialization/Deserializationismostlyusedtotransportobjects(e.g.duringremoting), ortopersistobjects(e.g.toafileordatabase).Serializationcanbedefinedasthe processofstoringthestateofanobjecttoastoragemedium.Duringthisprocess,the publicandprivatefieldsoftheobjectandthenameoftheclass,includingthe assemblycontainingtheclass,areconvertedtoastreamofbytes,whichisthen writtentoadatastream.Whentheobjectissubsequentlydeserialized,anexactclone oftheoriginalobjectiscreated.

Binaryserializationpreservestypefidelity,whichisusefulforpreservingthe stateofanobjectbetweendifferentinvocationsofanapplication.For example,youcanshareanobjectbetweendifferentapplicationsbyserializing ittotheclipboard.Youcanserializeanobjecttoastream,disk,memory,over thenetwork,andsoforth.Remotingusesserializationtopassobjects"by value"fromonecomputerorapplicationdomaintoanother. XMLserializationserializesonlypublicpropertiesandfieldsanddoesnot preservetypefidelity.Thisisusefulwhenyouwanttoprovideorconsume datawithoutrestrictingtheapplicationthatusesthedata.BecauseXMLisan

openstandard,itisanattractivechoiceforsharingdataacrosstheWeb.SOAP isanopenstandard,whichmakesitanattractivechoice. Therearetwoseparatemechanismsprovidedbythe.NETclasslibraryXmlSerializer andSoapFormatter/BinaryFormatter.MicrosoftusesXmlSerializerforWebServices, andusesSoapFormatter/BinaryFormatterforremoting.Bothareavailableforusein yourowncode.

WhydoIgeterrorswhenItrytoserializeaHashtable? XmlSerializerwillrefusetoserializeinstancesofanyclassthatimplements IDictionary,e.g.Hashtable.SoapFormatterandBinaryFormatterdonothavethis restriction. 45.Whatistheuseoftraceutility? ** 46.Whatareservercontrols? ASP.NETservercontrolsarecomponentsthatrunontheserverandencapsulateuser interfaceandotherrelatedfunctionality.TheyareusedinASP.NETpagesandin ASP.NETcodebehindclasses. 47.WhatisthedifferencebetweenWebUserControlandWebCustomControl? CustomControls Webcustomcontrolsarecompiledcomponentsthatrunontheserverandthat encapsulateuserinterfaceandotherrelatedfunctionalityintoreusablepackages. TheycanincludeallthedesigntimefeaturesofstandardASP.NETservercontrols, includingfullsupportforVisualStudiodesignfeaturessuchasthePropertieswindow, thevisualdesigner,andtheToolbox. ThereareseveralwaysthatyoucancreateWebcustomcontrols: Youcancompileacontrolthatcombinesthefunctionalityoftwoormore existingcontrols.Forexample,ifyouneedacontrolthatencapsulatesa buttonandatextbox,youcancreateitbycompilingtheexistingcontrols together. Ifanexistingservercontrolalmostmeetsyourrequirementsbutlackssome requiredfeatures,youcancustomizethecontrolbyderivingfromitand overridingitsproperties,methods,andevents. IfnoneoftheexistingWebservercontrols(ortheircombinations)meetyour requirements,youcancreateacustomcontrolbyderivingfromoneofthe basecontrolclasses.TheseclassesprovideallthebasicfunctionalityofWeb servercontrols,soyoucanfocusonprogrammingthefeaturesyouneed. IfnoneoftheexistingASP.NETservercontrolsmeetthespecificrequirementsofyour applications,youcancreateeitheraWebusercontroloraWebcustomcontrolthat encapsulatesthefunctionalityyouneed.Themaindifferencebetweenthetwocontrols liesineaseofcreationvs.easeofuseatdesigntime. Webusercontrolsareeasytomake,buttheycanbelessconvenienttousein advancedscenarios.YoudevelopWebusercontrolsalmostexactlythesamewaythat youdevelopWebFormspages.LikeWebForms,usercontrolscanbecreatedinthe visualdesigner,theycanbewrittenwithcodeseparatedfromtheHTML,andtheycan handleexecutionevents.However,becauseWebusercontrolsarecompiled dynamicallyatruntimetheycannotbeaddedtotheToolbox,andtheyare representedbyasimpleplaceholderglyphwhenaddedtoapage.ThismakesWeb usercontrolshardertouseifyouareaccustomedtofullVisualStudio.NETdesign timesupport,includingthePropertieswindowandDesignviewpreviews.Also,the onlywaytosharetheusercontrolbetweenapplicationsistoputaseparatecopyin eachapplication,whichtakesmoremaintenanceifyoumakechangestothecontrol. Webcustomcontrolsarecompiledcode,whichmakesthemeasiertousebutmore

difficulttocreateWebcustomcontrolsmustbeauthoredincode.Onceyouhave createdthecontrol,however,youcanaddittotheToolboxanddisplayitinavisual designerwithfullPropertieswindowsupportandalltheotherdesigntimefeaturesof ASP.NETservercontrols.Inaddition,youcaninstallasinglecopyoftheWebcustom controlintheglobalassemblycacheandshareitbetweenapplications,whichmakes maintenanceeasier. Webusercontrols Webcustomcontrols Easiertocreate Hardertocreate LimitedsupportforconsumerswhouseaFullvisualdesigntoolsupportforconsumers visualdesigntool AseparatecopyofthecontrolisrequiredOnlyasinglecopyofthecontrolisrequired, ineachapplication intheglobalassemblycache CannotbeaddedtotheToolboxinVisual CanbeaddedtotheToolboxinVisualStudio Studio Goodforstaticlayout Goodfordynamiclayout 48.Whatisexceptionhandling? Whenanexceptionoccurs,thesystemsearchesforthenearestcatchclausethatcan handletheexception,asdeterminedbytheruntimetypeoftheexception.First,the currentmethodissearchedforalexicallyenclosingtrystatement,andtheassociated catchclausesofthetrystatementareconsideredinorder.Ifthatfails,themethod thatcalledthecurrentmethodissearchedforalexicallyenclosingtrystatementthat enclosesthepointofthecalltothecurrentmethod.Thissearchcontinuesuntila catchclauseisfoundthatcanhandlethecurrentexception,bynaminganexception classthatisofthesameclass,orabaseclass,oftheruntimetypeoftheexception beingthrown.Acatchclausethatdoesn'tnameanexceptionclasscanhandleany exception. Onceamatchingcatchclauseisfound,thesystempreparestotransfercontroltothe firststatementofthecatchclause.Beforeexecutionofthecatchclausebegins,the systemfirstexecutes,inorder,anyfinallyclausesthatwereassociatedwithtry statementsmorenestedthatthantheonethatcaughttheexception. Exceptionsthatoccurduringdestructorexecutionareworthspecialmention.Ifan exceptionoccursduringdestructorexecution,andthatexceptionisnotcaught,then theexecutionofthatdestructoristerminatedandthedestructorofthebaseclass(if any)iscalled.Ifthereisnobaseclass(asinthecaseoftheobjecttype)orifthereis nobaseclassdestructor,thentheexceptionisdiscarded. 49.WhatisAssembly? Assembliesarethebuildingblocksof.NETFrameworkapplicationstheyformthe fundamentalunitofdeployment,versioncontrol,reuse,activationscoping,and securitypermissions.Anassemblyisacollectionoftypesandresourcesthatarebuilt toworktogetherandformalogicalunitoffunctionality.Anassemblyprovidesthe commonlanguageruntimewiththeinformationitneedstobeawareoftype implementations.Totheruntime,atypedoesnotexistoutsidethecontextofan assembly. Assembliesareafundamentalpartofprogrammingwiththe.NETFramework.An assemblyperformsthefollowingfunctions: Itcontainscodethatthecommonlanguageruntimeexecutes.Microsoft intermediatelanguage(MSIL)codeinaportableexecutable(PE)filewillnot beexecutedifitdoesnothaveanassociatedassemblymanifest.Notethat eachassemblycanhaveonlyoneentrypoint(thatis,DllMain,WinMain,or Main). Itformsasecurityboundary.Anassemblyistheunitatwhichpermissionsare requestedandgranted. Itformsatypeboundary.Everytype'sidentityincludesthenameofthe assemblyinwhichitresides.AtypecalledMyTypeloadedinthescopeofone

assemblyisnotthesameasatypecalledMyTypeloadedinthescopeof anotherassembly. Itformsareferencescopeboundary.Theassembly'smanifestcontains assemblymetadatathatisusedforresolvingtypesandsatisfyingresource requests.Itspecifiesthetypesandresourcesthatareexposedoutsidethe assembly.Themanifestalsoenumeratesotherassembliesonwhichit depends. Itformsaversionboundary.Theassemblyisthesmallestversionableunitin thecommonlanguageruntimealltypesandresourcesinthesameassembly areversionedasaunit.Theassembly'smanifestdescribestheversion dependenciesyouspecifyforanydependentassemblies. Itformsadeploymentunit.Whenanapplicationstarts,onlytheassemblies thattheapplicationinitiallycallsmustbepresent.Otherassemblies,suchas localizationresourcesorassembliescontainingutilityclasses,canberetrieved ondemand.Thisallowsapplicationstobekeptsimpleandthinwhenfirst downloaded. Itistheunitatwhichsidebysideexecutionissupported.

Assembliescanbestaticordynamic.Staticassembliescaninclude.NETFramework types(interfacesandclasses),aswellasresourcesfortheassembly(bitmaps,JPEG files,resourcefiles,andsoon).StaticassembliesarestoredondiskinPEfiles.You canalsousethe.NETFrameworktocreatedynamicassemblies,whicharerundirectly frommemoryandarenotsavedtodiskbeforeexecution.Youcansavedynamic assembliestodiskaftertheyhaveexecuted. Thereareseveralwaystocreateassemblies.Youcanusedevelopmenttools,suchas VisualStudio.NET,thatyouhaveusedinthepasttocreate.dllor.exefiles.Youcan usetoolsprovidedinthe.NETFrameworkSDKtocreateassemblieswithmodules createdinotherdevelopmentenvironments.Youcanalsousecommonlanguage runtimeAPIs,suchasReflection.Emit,tocreatedynamicassemblies. 50.Whatarethecontentsofassembly? Ingeneral,astaticassemblycanconsistoffourelements: Theassemblymanifest,whichcontainsassemblymetadata. Typemetadata. Microsoftintermediatelanguage(MSIL)codethatimplementsthetypes. Asetofresources. 51.Whatarethedifferenttypesofassemblies? Private,Public/Shared,Satellite 52.Whatisthedifferencebetweenaprivateassemblyandasharedassembly? 0. Locationandvisibility:Aprivateassemblyisnormallyusedbyasingle application,andisstoredintheapplication'sdirectory,orasubdirectory beneath.Asharedassemblyisnormallystoredintheglobalassemblycache, whichisarepositoryofassembliesmaintainedbythe.NETruntime.Shared assembliesareusuallylibrariesofcodewhichmanyapplicationswillfind useful,e.g.the.NETframeworkclasses. 1. Versioning:Theruntimeenforcesversioningconstraintsonlyonshared assemblies,notonprivateassemblies. 53.WhatareSatelliteAssemblies?Howyouwillcreatethis?Howwillyougetthe differentlanguagestrings? Satelliteassembliesareoftenusedtodeploylanguagespecificresourcesforan application.Theselanguagespecificassembliesworkinsidebysideexecution becausetheapplicationhasaseparateproductIDforeachlanguageandinstalls satelliteassembliesinalanguagespecificsubdirectoryforeachlanguage.When uninstalling,theapplicationremovesonlythesatelliteassembliesassociatedwitha givenlanguageand.NETFrameworkversion.Nocore.NETFrameworkfilesare removedunlessthelastlanguageforthat.NETFrameworkversionisbeingremoved. (Forexample,EnglishandJapaneseeditionsofthe.NETFrameworkversion1.1share

thesamecorefiles.TheJapanese.NETFrameworkversion1.1addssatellite assemblieswithlocalizedresourcesina\jasubdirectory.Anapplicationthatsupports the.NETFrameworkversion1.1,regardlessofitslanguage,alwaysusesthesame coreruntimefiles.) http://www.ondotnet.com/lpt/a/2637 ** 54.Howwilluloaddynamicassembly?Howwillcreateassembliesatruntime? ** 55.WhatisAssemblymanifest?whatalldetailstheassemblymanifestwill contain? Everyassembly,whetherstaticordynamic,containsacollectionofdatathatdescribes howtheelementsintheassemblyrelatetoeachother.Theassemblymanifest containsthisassemblymetadata.Anassemblymanifestcontainsallthemetadata neededtospecifytheassembly'sversionrequirementsandsecurityidentity,andall metadataneededtodefinethescopeoftheassemblyandresolvereferencesto resourcesandclasses.TheassemblymanifestcanbestoredineitheraPEfile(an.exe or.dll)withMicrosoftintermediatelanguage(MSIL)codeorinastandalonePEfile thatcontainsonlyassemblymanifestinformation. ItcontainsAssemblyname,Versionnumber,Culture,Strongnameinformation,Listof allfilesintheassembly,Typereferenceinformation,Informationonreferenced assemblies. 56.Differencebetweenassemblymanifest&metadata? assemblymanifestAnintegralpartofeveryassemblythatrenderstheassembly selfdescribing.Theassemblymanifestcontainstheassembly'smetadata.The manifestestablishestheassemblyidentity,specifiesthefilesthatmakeupthe assemblyimplementation,specifiesthetypesandresourcesthatmakeupthe assembly,itemizesthecompiletimedependenciesonotherassemblies,andspecifies thesetofpermissionsrequiredfortheassemblytorunproperly.Thisinformationis usedatruntimetoresolvereferences,enforceversionbindingpolicy,andvalidatethe integrityofloadedassemblies.Theselfdescribingnatureofassembliesalsohelps makeszeroimpactinstallandXCOPYdeploymentfeasible. metadataInformationthatdescribeseveryelementmanagedbythecommon languageruntime:anassembly,loadablefile,type,method,andsoon.Thiscan includeinformationrequiredfordebuggingandgarbagecollection,aswellassecurity attributes,marshalingdata,extendedclassandmemberdefinitions,versionbinding, andotherinformationrequiredbytheruntime. 57.WhatisGlobalAssemblyCache(GAC)andwhatisthepurposeofit?(Howto makeanassemblytopublic?Steps)Howmorethanoneversionofan assemblycankeepinsameplace? Eachcomputerwherethecommonlanguageruntimeisinstalledhasamachinewide codecachecalledtheglobalassemblycache.Theglobalassemblycachestores assembliesspecificallydesignatedtobesharedbyseveralapplicationsonthe computer. Youshouldshareassembliesbyinstallingthemintotheglobalassembly cacheonlywhenyouneedto. Steps Createastrongnameusingsn.exetool eg:snkkeyPair.snk withinAssemblyInfo.csaddthegeneratedfilename eg:[assembly:AssemblyKeyFile("abc.snk")] recompileproject,theninstallittoGACbyeither drag&dropittoassemblyfolder(C:\WINDOWS\assemblyORC:\WINNT\assembly) (shfusion.dlltool) or gacutiliabc.dll 58.IfIhavemorethanoneversionofoneassemblies,thenhow'llIuseold version(how/wheretospecifyversionnumber?)inmyapplication? ** 59.Howtofindmethodsofaassemblyfile(notusingILDASM) Reflection

60.WhatisGarbageCollectionin.Net?Garbagecollectionprocess? Theprocessoftransitivelytracingthroughallpointerstoactivelyusedobjectsinorder tolocateallobjectsthatcanbereferenced,andthenarrangingtoreuseanyheap memorythatwasnotfoundduringthistrace.Thecommonlanguageruntimegarbage collectoralsocompactsthememorythatisinusetoreducetheworkingspaceneeded fortheheap. 61.Readonlyvs.const? Aconstfieldcanonlybeinitializedatthedeclarationofthefield.Areadonlyfieldcan beinitializedeitheratthedeclarationorinaconstructor.Therefore,readonlyfields canhavedifferentvaluesdependingontheconstructorused.Also,whileaconstfield isacompiletimeconstant,thereadonlyfieldcanbeusedforruntimeconstants,as inthefollowingexample: publicstaticreadonlyuintl1=(uint)DateTime.Now.Ticks 62.WhatisReflectionin.NET?Namespace? Howwillyouloadanassembly whichisnotreferencedbycurrentassembly? All.NETcompilersproducemetadataaboutthetypesdefinedinthemodulesthey produce.Thismetadataispackagedalongwiththemodule(modulesinturnare packagedtogetherinassemblies),andcanbeaccessedbyamechanismcalled reflection.TheSystem.Reflectionnamespacecontainsclassesthatcanbeusedto interrogatethetypesforamodule/assembly. Usingreflectiontoaccess.NETmetadataisverysimilartousingITypeLib/ITypeInfoto accesstypelibrarydatainCOM,anditisusedforsimilarpurposese.g.determining datatypesizesformarshalingdataacrosscontext/process/machineboundaries. Reflectioncanalsobeusedtodynamicallyinvokemethods(see System.Type.InvokeMember),orevencreatetypesdynamicallyatruntime(see System.Reflection.Emit.TypeBuilder). 63.WhatisCustomattribute?Howtocreate?IfI'mhavingcustomattributein anassembly,howtosaythatnameinthecode? A:Theprimarystepstoproperlydesigncustomattributeclassesareasfollows: . ApplyingtheAttributeUsageAttribute([AttributeUsage(AttributeTargets.All, Inherited=false,AllowMultiple=true)]) a. Declaringtheattribute.(classpublicclassMyAttribute:System.Attribute{//. ..}) b. Declaringconstructors(publicMyAttribute(boolmyvalue){this.myvalue= myvalue}) c. Declaringproperties d. publicboolMyProperty e. { f. get{returnthis.myvalue} g. set{this.myvalue=value} h. } 64. Thefollowingexampledemonstratesthebasicwayofusingreflectiontogetaccess tocustomattributes. 65. classMainClass 66. { 67. publicstaticvoidMain() 68. { 69. System.Reflection.MemberInfoinfo=typeof(MyClass) 70. object[]attributes=info.GetCustomAttributes() 71. for(inti=0i<attributes.Lengthi++) 72. { 73. System.Console.WriteLine(attributes[i]) 74. } 75. } } 76.Whatisthemanagedandunmanagedcodein.net? The.NETFrameworkprovidesaruntimeenvironmentcalledtheCommonLanguage

Runtime,whichmanagestheexecutionofcodeandprovidesservicesthatmakethe developmentprocesseasier.Compilersandtoolsexposetheruntime'sfunctionality andenableyoutowritecodethatbenefitsfromthismanagedexecutionenvironment. Codethatyoudevelopwithalanguagecompilerthattargetstheruntimeiscalled managedcodeitbenefitsfromfeaturessuchascrosslanguageintegration,cross languageexceptionhandling,enhancedsecurity,versioninganddeploymentsupport, asimplifiedmodelforcomponentinteraction,anddebuggingandprofilingservices. 77.Howdoyoucreatethreadingin.NET?Whatisthenamespaceforthat? ** System.Threading.Thread 78.SerializeandMarshalByRef? 79.usingdirectivevsusingstatement YoucreateaninstanceinausingstatementtoensurethatDisposeiscalledonthe objectwhentheusingstatementisexited.Ausingstatementcanbeexitedeither whentheendoftheusingstatementisreachedorif,forexample,anexceptionis thrownandcontrolleavesthestatementblockbeforetheendofthestatement. Theusingdirectivehastwouses: Createanaliasforanamespace(ausingalias). Permittheuseoftypesinanamespace,suchthat,youdonothavetoqualify theuseofatypeinthatnamespace(ausingdirective). 80.DescribetheManagedExecutionProcess? Themanagedexecutionprocessincludesthefollowingsteps: 0. Choosingacompiler. Toobtainthebenefitsprovidedbythecommonlanguageruntime,youmust useoneormorelanguagecompilersthattargettheruntime. 1. CompilingyourcodetoMicrosoftintermediatelanguage(MSIL). CompilingtranslatesyoursourcecodeintoMSILandgeneratestherequired metadata. 2. CompilingMSILtonativecode. Atexecutiontime,ajustintime(JIT)compilertranslatestheMSILintonative code.Duringthiscompilation,codemustpassaverificationprocessthat examinestheMSILandmetadatatofindoutwhetherthecodecanbe determinedtobetypesafe. 3. Executingyourcode. Thecommonlanguageruntimeprovidestheinfrastructurethatenables executiontotakeplaceaswellasavarietyofservicesthatcanbeusedduring execution. 81.WhatisActiveDirectory?WhatisthenamespaceusedtoaccesstheMicrosoft ActiveDirectories?WhatareADSIDirectories? ActiveDirectoryServiceInterfaces(ADSI)isaprogrammaticinterfaceforMicrosoft WindowsActiveDirectory.Itenablesyourapplicationstointeractwithdiverse directoriesonanetwork,usingasingleinterface.VisualStudio.NETandthe.NET FrameworkmakeiteasytoaddADSIfunctionalitywiththeDirectoryEntryand DirectorySearchercomponents. UsingADSI,youcancreateapplicationsthatperformcommonadministrativetasks, suchasbackingupdatabases,accessingprinters,andadministeringuseraccounts. ADSImakesitpossibleforyouto: Logononcetoworkwithdiversedirectories.TheDirectoryEntrycomponent classprovidesusernameandpasswordpropertiesthatcanbeenteredat runtimeandcommunicatedtotheActiveDirectoryobjectyouarebindingto. Useasingleapplicationprogramminginterface(API)toperformtaskson multipledirectorysystemsbyofferingtheuseravarietyofprotocolstouse. TheDirectoryServicesnamespaceprovidestheclassestoperformmost administrativefunctions. Perform"richquerying"ondirectorysystems.ADSItechnologyallowsfor searchingforanobjectbyspecifyingtwoquerydialects:SQLandLDAP.

Accessanduseasingle,hierarchicalstructureforadministeringand maintainingdiverseandcomplicatednetworkconfigurationsbyaccessingan ActiveDirectorytree. IntegratedirectoryinformationwithdatabasessuchasSQLServer.The DirectoryEntrypathmaybeusedasanADO.NETconnectionstringprovided thatitisusingtheLDAPprovider.

usingSystem.DirectoryServices 82.HowGarbageCollector(GC)Works? Themethodsinthisclassinfluencewhenanobjectisgarbagecollectedandwhen resourcesallocatedbyanobjectarereleased.Propertiesinthisclassprovide informationaboutthetotalamountofmemoryavailableinthesystemandtheage category,orgeneration,ofmemoryallocatedtoanobject.Periodically,thegarbage collectorperformsgarbagecollectiontoreclaimmemoryallocatedtoobjectsforwhich therearenovalidreferences.Garbagecollectionhappensautomaticallywhena requestformemorycannotbesatisfiedusingavailablefreememory.Alternatively,an applicationcanforcegarbagecollectionusingtheCollectmethod. Garbagecollectionconsistsofthefollowingsteps: 0. Thegarbagecollectorsearchesformanagedobjectsthatarereferencedin managedcode. 1. Thegarbagecollectorattemptstofinalizeobjectsthatarenotreferenced. 2. Thegarbagecollectorfreesobjectsthatarenotreferencedandreclaimstheir memory. 83.WhydoweneedtocallCG.SupressFinalize? Requeststhatthesystemnotcallthefinalizermethodforthespecifiedobject. publicstaticvoidSuppressFinalize( objectobj )Themethodremovesobjfromthesetofobjectsthatrequirefinalization.Theobj parameterisrequiredtobethecallerofthismethod. ObjectsthatimplementtheIDisposableinterfacecancallthismethodfromthe IDisposable.Disposemethodtopreventthegarbagecollectorfromcalling Object.Finalizeonanobjectthatdoesnotrequireit. 84.Whatisnmaketool? TheNmaketool(Nmake.exe)isa32bittoolthatyouusetobuildprojectsbasedon commandscontainedina.makfile. usage:nmakeaall 85.WhatareNamespaces? Thenamespacekeywordisusedtodeclareascope.Thisnamespacescopeletsyou organizecodeandgivesyouawaytocreategloballyuniquetypes.Evenifyoudonot explicitlydeclareone,adefaultnamespaceiscreated.Thisunnamednamespace, sometimescalledtheglobalnamespace,ispresentineveryfile.Anyidentifierinthe globalnamespaceisavailableforuseinanamednamespace.Namespacesimplicitly havepublicaccessandthisisnotmodifiable. 86.C++&C#differences ** 87.Ifyouwanttowriteyourowndotnetlanguage,whatstepsyouwillutake care? 88.Whatiscustomevents?Howtocreateit? 89.howdotnetcompiledcodewillbecomeplatformindependent? 90.withoutmodifyingsourcecodeifwecompileagain,willitbegeneratedMSIL again? 91.Describethedifferencebetweeninlineandcodebehindwhichisbestina looselycoupledsolution? 92.WhatisthedifferencebetweenCONSTandREADONLY? 93.Whatisthedifferencebetweenref&outparameters? WhatisthedifferencebetweenarraysandArraylist? 94.Whatareindexers?

95.Howtocreateeventsforacontrol? 96.ExplainaboutSOAP 97.PracticalExampleofPassinganEventstodelegates 98.Howcanyouread3rdlinefromatextfile? 99.WhatisAsynchronouscallandhowitcanbeimplementedusingdelegates? 100. WhatisthedifferencebetweenArrayandLinkedList? 101. WhatisJaggedArrays? Ajaggedarrayisanarraywhoseelementsarearrays.Theelementsofajaggedarray canbeofdifferentdimensionsandsizes.Ajaggedarrayissometimescalledan "arrayofarrays." (COM) 102. InteropServices? Thecommonlanguageruntimeprovidestwomechanismsforinteroperatingwith unmanagedcode: Platforminvoke,whichenablesmanagedcodetocallfunctionsexportedfrom anunmanagedlibrary. COMinterop,whichenablesmanagedcodetointeractwithCOMobjects throughinterfaces. BothplatforminvokeandCOMinteropuseinteropmarshalingtoaccuratelymove methodargumentsbetweencallerandcalleeandback,ifrequired. 103. HowdoesuhandlethisCOMcomponentsdevelopedinother programminglanguagesin.NET? 104. WhatisRCW(RuntimeCallableWrappers)? ThecommonlanguageruntimeexposesCOMobjectsthroughaproxycalledthe runtimecallablewrapper(RCW).AlthoughtheRCWappearstobeanordinaryobject to.NETclients,itsprimaryfunctionistomarshalcallsbetweena.NETclientanda COMobject. 105. WhatisCCW(COMCallableWrapper) AproxyobjectgeneratedbythecommonlanguageruntimesothatexistingCOM applicationscanusemanagedclasses,including.NETFrameworkclasses, transparently. 106. HowCCWandRCWisworking? ** 107. Howwillyouregistercom+services? The.NETFrameworkSDKprovidesthe.NETFrameworkServicesInstallationTool (Regsvcs.exeacommandlinetool)tomanuallyregisteranassemblycontaining servicedcomponents.Youcanalsoaccesstheseregistrationfeatures programmaticallywiththeSystem.EnterpriseServicesRegistrationHelperclassby creatinganinstanceofclassRegistrationHelperandusingthemethodInstallAssembly 108. WhatisuseofContextUtilclass? ContextUtilisthepreferredclasstouseforobtainingCOM+contextinformation. 109. WhatisthenewthreefeaturesofCOM+services,whicharenotthere inCOM(MTS)? ** 110. IstheCOMarchitecturesameas.Netarchitecture? Whatisthe differencebetweenthem? ** 111. CanwecopyaCOMdlltoGACfolder? ** 112. WhatisPinvoke? Platforminvokeisaservicethatenablesmanagedcodetocallunmanagedfunctions implementedindynamiclinklibraries(DLLs),suchasthoseintheWin32API.It

locatesandinvokesanexportedfunctionandmarshalsitsarguments(integers, strings,arrays,structures,andsoon)acrosstheinteroperationboundaryasneeded. 113. IsittruethatCOMobjectsnolongerneedtoberegisteredonthe server? Answer:YesandNo.LegacyCOMobjectsstillneedtoberegisteredontheserver beforetheycanbeused.COMdevelopedusingthenew.NETFrameworkwillnotneed toberegistered.Developerswillbeabletoautoregistertheseobjectsjustbyplacing theminthe'bin'folderoftheapplication. 114. Can.NETFrameworkcomponentsusethefeaturesofComponent Services? Answer:Yes,youcanusethefeaturesandfunctionsofComponentServicesfroma .NETFrameworkcomponent. http://msdn.microsoft.com/library/techart/Pahlcompserv.htm (OOPS) 115. WhataretheOOPSconcepts? 1)Encapsulation:Itisthemechanismthatbindstogethercodeanddatain manipulates,andkeepsbothsafefromoutsideinterferenceandmisuse.Inshortit isolatesaparticularcodeanddatafromallothercodesanddata.Awelldefined interfacecontrolstheaccesstothatparticularcodeanddata. 2)Inheritance:Itistheprocessbywhichoneobjectacquiresthepropertiesof anotherobject.Thissupportsthehierarchicalclassification.Withouttheuseof hierarchies,eachobjectwouldneedtodefineallitscharacteristicsexplicitly.However, byuseofinheritance,anobjectneedonlydefinethosequalitiesthatmakeitunique withinitsclass.Itcaninherititsgeneralattributesfromitsparent.Anewsubclass inheritsalloftheattributesofallofitsancestors. 3)Polymorphism:Itisafeaturethatallowsoneinterfacetobeusedforgeneralclass ofactions.Thespecificactionisdeterminedbytheexactnatureofthesituation.In generalpolymorphismmeans"oneinterface,multiplemethods",Thismeansthatitis possibletodesignagenericinterfacetoagroupofrelatedactivities.Thishelpsreduce complexitybyallowingthesameinterfacetobeusedtospecifyageneralclassof action.Itisthecompiler'sjobtoselectthespecificaction(thatis,method)asit appliestoeachsituation. 116. WhatisthedifferencebetweenaStructandaClass? ThestructtypeissuitableforrepresentinglightweightobjectssuchasPoint, Rectangle,andColor.Althoughitispossibletorepresentapointasaclass,a structismoreefficientinsomescenarios.Forexample,ifyoudeclareanarray of1000Pointobjects,youwillallocateadditionalmemoryforreferencingeach object.Inthiscase,thestructislessexpensive. Whenyoucreateastructobjectusingthenewoperator,itgetscreatedand theappropriateconstructoriscalled.Unlikeclasses,structscanbe instantiatedwithoutusingthenewoperator.Ifyoudonotusenew,thefields willremainunassignedandtheobjectcannotbeuseduntilallofthefieldsare initialized. Itisanerrortodeclareadefault(parameterless)constructorforastruct.A defaultconstructorisalwaysprovidedtoinitializethestructmemberstotheir defaultvalues. Itisanerrortoinitializeaninstancefieldinastruct. Thereisnoinheritanceforstructsasthereisforclasses.Astructcannot inheritfromanotherstructorclass,anditcannotbethebaseofaclass. Structs,however,inheritfromthebaseclassObject.Astructcanimplement interfaces,anditdoesthatexactlyasclassesdo. Astructisavaluetype,whileaclassisareferencetype. 117. Valuetype&referencetypesdifference?Examplefrom.NET.Integer &structarevaluetypesorreferencetypesin.NET? Mostprogramminglanguagesprovidebuiltindatatypes,suchasintegersand floatingpointnumbers,thatarecopiedwhentheyarepassedasarguments(thatis,

theyarepassedbyvalue).Inthe.NETFramework,thesearecalledvaluetypes.The runtimesupportstwokindsofvaluetypes: Builtinvaluetypes The.NETFrameworkdefinesbuiltinvaluetypes,suchasSystem.Int32and System.Boolean,whichcorrespondandareidenticaltoprimitivedatatypes usedbyprogramminglanguages. Userdefinedvaluetypes Yourlanguagewillprovidewaystodefineyourownvaluetypes,whichderive fromSystem.ValueType.Ifyouwanttodefineatyperepresentingavaluethat issmall,suchasacomplexnumber(usingtwofloatingpointnumbers),you mightchoosetodefineitasavaluetypebecauseyoucanpassthevaluetype efficientlybyvalue.Ifthetypeyouaredefiningwouldbemoreefficiently passedbyreference,youshoulddefineitasaclassinstead. Variablesofreferencetypes,referredtoasobjects,storereferencestotheactual data.Thisfollowingarethereferencetypes:

class interface delegate

Thisfollowingarethebuiltinreferencetypes: object string 118. WhatisInheritance,MultipleInheritance,SharedandRepeatable Inheritance? ** 119. WhatisMethodoverloading? Methodoverloadingoccurswhenaclasscontainstwomethodswiththesamename, butdifferentsignatures. 120. WhatisMethodOverriding?HowtooverrideafunctioninC#? Usetheoverridemodifiertomodifyamethod,aproperty,anindexer,oranevent.An overridemethodprovidesanewimplementationofamemberinheritedfromabase class.Themethodoverriddenbyanoverridedeclarationisknownastheoverridden basemethod.Theoverriddenbasemethodmusthavethesamesignatureasthe overridemethod. Youcannotoverrideanonvirtualorstaticmethod.Theoverriddenbasemethodmust bevirtual,abstract,oroverride. 121. Canwecallabaseclassmethodwithoutcreatinginstance? ItspossibleIfitsastaticmethod. Itspossiblebyinheritingfromthatclassalso. Itspossiblefromderivedclassesusingbasekeyword. 122. Youhaveonebaseclassvirtualfunctionhowwillcallthatfunction fromderivedclass? Ans: 123. classa 124. { 125. publicvirtualintm() 126. { 127. return1 128. } 129. } 130. classb:a 131. { 132. publicintj() 133. {

134. 135. }

returnm() }

136. Inwhichcasesyouuseoverrideandnewbase? Usethenewmodifiertoexplicitlyhideamemberinheritedfromabaseclass.Tohide aninheritedmember,declareitinthederivedclassusingthesamename,andmodify itwiththenewmodifier. C#Languagefeatures 137. WhatareSealedClassesinC#? Thesealedmodifierisusedtopreventderivationfromaclass.Acompiletimeerror occursifasealedclassisspecifiedasthebaseclassofanotherclass.(Asealedclass cannotalsobeanabstractclass) 138. WhatisPolymorphism?HowdoesVB.NET/C#achievepolymorphism? ** 139. classToken 140. { 141. publicstringDisplay() 142. { 143. //Implementationgoeshere 144. return"base" 145. } 146. } 147. classIdentifierToken:Token 148. { 149. publicnewstringDisplay()//Whatistheuseofnewkeyword 150. { 151. //Implementationgoeshere 152. return"derive" 153. } 154. } 155. staticvoidMethod(Tokent) 156. { 157. Console.Write(t.Display()) 158. } 159. publicstaticvoidMain() 160. { 161. IdentifierTokenVariable=newIdentifierToken() 162. Method(Variable)//WhichClassMethodiscalledhere 163. Console.ReadLine() 164. } 165. FortheabovecodeWhatisthe"new"keywordandWhichClassMethodis 166. calledhere A:itwillcallbaseclassDisplaymethod 167. classToken 168. { 169. publicvirtualstringDisplay() 170. { 171. //Implementationgoeshere 172. return"base" 173. } 174. } 175. classIdentifierToken:Token

176. { 177. publicoverridestringDisplay()//Whatistheuseofnewkeyword 178. { 179. //Implementationgoeshere 180. return"derive" 181. } 182. } 183. staticvoidMethod(Tokent) 184. { 185. Console.Write(t.Display()) 186. } 187. publicstaticvoidMain() 188. { 189. IdentifierTokenVariable=newIdentifierToken() 190. Method(Variable)//WhichClassMethodiscalledhere 191. Console.ReadLine() 192. } 193. A:Derive 194. InwhichScenarioyouwillgoforInterfaceorAbstractClass? Interfaces,likeclasses,defineasetofproperties,methods,andevents.Butunlike classes,interfacesdonotprovideimplementation.Theyareimplementedbyclasses, anddefinedasseparateentitiesfromclasses.Eventhoughclassinheritanceallows yourclassestoinheritimplementationfromabaseclass,italsoforcesyoutomake mostofyourdesigndecisionswhentheclassisfirstpublished. Abstractclassesareusefulwhencreatingcomponentsbecausetheyallowyouspecify aninvariantleveloffunctionalityinsomemethods,butleavetheimplementationof othermethodsuntilaspecificimplementationofthatclassisneeded.Theyalso versionwell,becauseifadditionalfunctionalityisneededinderivedclasses,itcanbe addedtothebaseclasswithoutbreakingcode. Interfacesvs.AbstractClasses Feature Interface Abstractclass Multiple Aclassmayimplement Aclassmayextendonlyone inheritance severalinterfaces. abstractclass. Anabstractclasscanprovide Aninterfacecannot Default completecode,defaultcode, provideanycodeatall, implementation and/orjuststubsthathaveto muchlessdefaultcode. beoverridden. Staticfinalconstantsonly, canusethemwithout qualificationinclasses thatimplementthe Bothinstanceandstatic interface.Ontheother constantsarepossible.Both paw,theseunqualified Constants staticandinstanceintialiser namespollutethe codearealsopossibleto namespace.Youcanuse computetheconstants. themanditisnotobvious wheretheyarecoming fromsincethe qualificationisoptional. Aninterface Athirdpartyclassmustbe Thirdparty implementationmaybe rewrittentoextendonlyfrom convenience addedtoanyexisting theabstractclass. thirdpartyclass. Interfacesareoftenused Anabstractclassdefinesthe isavsableortodescribetheperipheral coreidentityofitsdescendants. cando abilitiesofaclass,notits IfyoudefinedaDogabstract centralidentity,e.g.an classthenDamamation

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

neednotdeclare individualmethodsofan interfaceabstract.They areallpresumedso. Ifyouaddanewmethod toaninterface,youmust trackdownall Adding implementationsofthat functionality interfaceintheuniverse andprovidethemwitha concreteimplementation ofthatmethod.

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

195. seethecode 196. interfaceICommon 197. { 198. intgetCommon() 199. } 200. interfaceICommonImplements1:ICommon 201. { 202. } 203. interfaceICommonImplements2:ICommon 204. { 205. } 206. publicclassa:ICommonImplements1,ICommonImplements2 207. { } HowtoimplementgetCommonmethodinclassa?Areyouseeinganyprobleminthe implementation? Ans:

publicclassa:ICommonImplements1,ICommonImplements2 { publicintgetCommon() { return1 } } 208. interfaceIWeather 209. { 210. voiddisplay() 211. } 212. publicclassA:IWeather 213. { 214. publicvoiddisplay() 215. { 216. MessageBox.Show("A") 217. } 218. } 219. publicclassB:A 220. { 221. } 222. publicclassC:B,IWeather 223. {

224. publicvoiddisplay() 225. { 226. MessageBox.Show("C") 227. } 228. } 229. WhenIinstantiateC.display(),willitwork? 230. interfaceIPrint 231. { 232. stringDisplay() 233. } 234. interfaceIWrite 235. { 236. stringDisplay() 237. } 238. classPrintDoc:IPrint,IWrite 239. { 240. //Hereisimplementation 241. } howtoimplementtheDisplayintheclassprintDoc(Howtoresolvethenaming Conflict)A:nonamingconflicts

classPrintDoc:IPrint,IWrite { publicstringDisplay() { return"s" } } 242. interfaceIList 243. { 244. intCount{getset} 245. } 246. interfaceICounter 247. { 248. voidCount(inti) 249. } 250. interfaceIListCounter:IList,ICounter{} 251. classC 252. { 253. voidTest(IListCounterx) 254. { 255. x.Count(1) //Error 256. x.Count=1 //Error 257. ((IList)x).Count=1 //Ok,invokesIList.Count.set 258. ((ICounter)x).Count(1) //Ok,invokesICounter.Count 259. } 260. } 261. Writeonecodeexampleforcompiletimebindingandoneforruntime binding?Whatisearly/latebinding? Anobjectisearlyboundwhenitisassignedtoavariabledeclaredtobeofaspecific objecttype.Earlyboundobjectsallowthecompilertoallocatememoryandperform otheroptimizationsbeforeanapplicationexecutes. 'Createavariabletoholdanewobject. DimFSAsFileStream 'Assignanewobjecttothevariable. FS=NewFileStream("C:\tmp.txt",FileMode.Open)

Bycontrast,anobjectislateboundwhenitisassignedtoavariabledeclaredtobeof typeObject.Objectsofthistypecanholdreferencestoanyobject,butlackmanyof theadvantagesofearlyboundobjects. DimxlAppAsObject xlApp=CreateObject("Excel.Application") 262. Canyouexplainwhatinheritanceisandanexampleofwhenyou mightuseit? 263. Howcanyouwriteaclasstorestrictthatonlyoneobjectofthisclass canbecreated(Singletonclass)? (Accessspecifiers) 264. Whataretheaccessspecifiersavailableinc#? Private,Protected,Public,Internal,ProtectedInternal. 265. ExplainaboutProtectedandprotectedinternal,internalaccess specifier? protectedAccessislimitedtothecontainingclassortypesderivedfromthe containingclass. internalAccessislimitedtothecurrentassembly. protectedinternalAccessislimitedtothecurrentassemblyortypesderivedfromthe containingclass. (Constructor/Destructor) 266. Differencebetweentypeconstructorandinstanceconstructor?What isstaticconstructor,whenitwillbefired?Andwhatisitsuse? (Classconstructormethodisalsoknownastypeconstructorortypeinitializer) Instanceconstructorisexecutedwhenanewinstanceoftypeiscreatedandtheclass constructorisexecutedafterthetypeisloadedandbeforeanyoneofthetype membersisaccessed.(Itwillgetexecutedonly1sttime,whenwecallanystatic methods/fieldsinthesameclass.)Classconstructorsareusedforstaticfield initialization.Onlyoneclassconstructorpertypeispermitted,anditcannotusethe vararg(variableargument)callingconvention. Astaticconstructorisusedtoinitializeaclass.Itiscalledautomaticallytoinitialize theclassbeforethefirstinstanceiscreatedoranystaticmembersarereferenced. 267. WhatisPrivateConstructor?anditsuse?Canyoucreateinstanceofa classwhichhasPrivateConstructor? A:Whenaclassdeclaresonlyprivateinstanceconstructors,itisnotpossiblefor classesoutsidetheprogramtoderivefromtheclassortodirectlycreateinstancesof it.(ExceptNestedclasses) Makeaconstructorprivateif: Youwantittobeavailableonlytotheclassitself.Forexample,youmighthavea specialconstructorusedonlyintheimplementationofyourclass'Clonemethod. Youdonotwantinstancesofyourcomponenttobecreated.Forexample,youmay haveaclasscontainingnothingbutSharedutilityfunctions,andnoinstancedata. Creatinginstancesoftheclasswouldwastememory. 268. Ihave3overloadedconstructorsinmyclass.Inordertoavoidmaking instanceoftheclassdoIneedtomakeallconstructorstoprivate? (yes) 269. Overloadedconstructorwillcalldefaultconstructorinternally? (no) 270. Whatarevirtualdestructors? 271. Destructorandfinalize GenerallyinC++thedestructoriscalledwhenobjectsgetsdestroyed.Andonecan explicitlycallthedestructorsinC++.Andalsotheobjectsaredestroyedinreverse orderthattheyarecreatedin.SoinC++youhavecontroloverthedestructors. InC#youcannevercallthem,thereasonisonecannotdestroyanobject.Sowho hasthecontroloverthedestructor(inC#)?it'sthe.NetframeworksGarbage Collector(GC).GCdestroystheobjectsonlywhennecessary.Somesituationsof

necessityarememoryisexhaustedoruserexplicitlycallsSystem.GC.Collect() method. Pointstoremember: 1.Destructorsareinvokedautomatically,andcannotbeinvokedexplicitly. 2.Destructorscannotbeoverloaded.Thus,aclasscanhave,atmost,onedestructor. 3.Destructorsarenotinherited.Thus,aclasshasnodestructorsotherthantheone, whichmaybedeclaredinit. 4.Destructorscannotbeusedwithstructs.Theyareonlyusedwithclasses. 5.Aninstancebecomeseligiblefordestructionwhenitisnolongerpossibleforany codetousetheinstance. 6.Executionofthedestructorfortheinstancemayoccuratanytimeafterthe instancebecomeseligiblefordestruction. 7.Whenaninstanceisdestructed,thedestructorsinitsinheritancechainarecalled, inorder,frommostderivedtoleastderived. http://msdn.microsoft.com/library/default.asp?url=/library/en us/cpguide/html/cpconfinalizemethodscdestructors.asp 272. WhatisthedifferencebetweenFinalizeandDispose(Garbage collection) Classinstancesoftenencapsulatecontroloverresourcesthatarenotmanagedbythe runtime,suchaswindowhandles(HWND),databaseconnections,andsoon. Therefore,youshouldprovidebothanexplicitandanimplicitwaytofreethose resources.ProvideimplicitcontrolbyimplementingtheprotectedFinalizeMethodon anobject(destructorsyntaxinC#andtheManagedExtensionsforC++).The garbagecollectorcallsthismethodatsomepointaftertherearenolongeranyvalid referencestotheobject. Insomecases,youmightwanttoprovideprogrammersusinganobjectwiththe abilitytoexplicitlyreleasetheseexternalresourcesbeforethegarbagecollectorfrees theobject.Ifanexternalresourceisscarceorexpensive,betterperformancecanbe achievediftheprogrammerexplicitlyreleasesresourceswhentheyarenolonger beingused.Toprovideexplicitcontrol,implementtheDisposemethodprovidedbythe IDisposableInterface.Theconsumeroftheobjectshouldcallthismethodwhenitis doneusingtheobject.Disposecanbecalledevenifotherreferencestotheobject arealive. NotethatevenwhenyouprovideexplicitcontrolbywayofDispose,youshould provideimplicitcleanupusingtheFinalizemethod.Finalizeprovidesabackupto preventresourcesfrompermanentlyleakingiftheprogrammerfailstocallDispose. 273. Whatisclosemethod?HowitsdifferentfromFinalize&Dispose? ** 274. Whatisboxing&unboxing? 275. Whatischeck/uncheck? 276. Whatistheuseofbasekeyword?Tellmeapracticalexampleforbase keywordsusage? 277. Whatarethedifferent.nettoolswhichuusedinprojects? 278. try { ... } catch { ...//exceptionoccurredhere.What'llhappen? } finally { .. } Ans:Itwillthrowexception. 279. Whatwilldotoavoidpriorcase? Ans: 280. try

281. { 282. try 283. { 284. ... 285. } 286. catch 287. { 288. ... 289. //exceptionoccurredhere. 290. } 291. finally 292. { 293. ... 294. } 295. } 296. catch 297. { 298. ... 299. } 300. finally 301. { 302. ... } 303. try 304. { 305. ... 306. } 307. catch 308. { 309. ... 310. } 311. finally 312. { 313. .. 314. } 315. Willitgotofinallyblockifthereisnoexceptionhappened? Ans:Yes.Thefinallyblockisusefulforcleaningupanyresourcesallocatedinthetry block.Controlisalwayspassedtothefinallyblockregardlessofhowthetryblock exits. 316. IsgotostatementsupportedinC#?HowaboutJava? GotosaresupportedinC#tothefullest.InJavagotoisareservedkeywordthat providesabsolutelynofunctionality. 317. WhatsdifferentaboutswitchstatementsinC#? Nofallthroughsallowed.UnliketheC++switchstatement,C#doesnotsupportan explicitfallthroughfromonecaselabeltoanother.Ifyouwant,youcanusegotoa switchcase,orgotodefault. case1: cost+=25 break case2: cost+=25 gotocase1 (ADO.NET) 318. AdvantageofADO.Net? ADO.NETDoesNotDependOnContinuouslyLiveConnections DatabaseInteractionsArePerformedUsingDataCommands DataCanBeCachedinDatasets

DatasetsAreIndependentofDataSources DataIsPersistedasXML SchemasDefineDataStructures 319. Howwoulduconnecttodatabaseusing.NET? SqlConnectionnwindConn=newSqlConnection("DataSource=localhostIntegrated Security=SSPI"+ "InitialCatalog=northwind") nwindConn.Open() 320. Whatarerelationobjectsindatasetandhow&wheretousethem? InaDataSetthatcontainsmultipleDataTableobjects,youcanuseDataRelation objectstorelateonetabletoanother,tonavigatethroughthetables,andtoreturn childorparentrowsfromarelatedtable. AddingaDataRelationtoaDataSetadds, bydefault,aUniqueConstrainttotheparenttableandaForeignKeyConstraintto thechildtable. ThefollowingcodeexamplecreatesaDataRelationusingtwoDataTableobjectsina DataSet.EachDataTablecontainsacolumnnamedCustID,whichservesasalink betweenthetwoDataTableobjects.TheexampleaddsasingleDataRelationtothe RelationscollectionoftheDataSet.Thefirstargumentintheexamplespecifiesthe nameoftheDataRelationbeingcreated.Thesecondargumentsetstheparent DataColumnandthethirdargumentsetsthechildDataColumn. custDS.Relations.Add("CustOrders", custDS.Tables["Customers"].Columns["CustID"], custDS.Tables["Orders"].Columns["CustID"]) OR privatevoidCreateRelation() { //GettheDataColumnobjectsfromtwoDataTableobjectsinaDataSet. DataColumnparentCol DataColumnchildCol //CodetogettheDataSetnotshownhere. parentCol=DataSet1.Tables["Customers"].Columns["CustID"] childCol=DataSet1.Tables["Orders"].Columns["CustID"] //CreateDataRelation. DataRelationrelCustOrder relCustOrder=newDataRelation("CustomersOrders",parentCol,childCol) //AddtherelationtotheDataSet. DataSet1.Relations.Add(relCustOrder) } 321. DifferencebetweenOLEDBProviderandSqlClient? Ans:SQLClient.NETclassesarehighlyoptimizedforthe.net/sqlservercombination andachieveoptimalresults.TheSqlClientdataproviderisfast.It'sfasterthanthe Oracleprovider,andfasterthanaccessingdatabaseviatheOleDblayer.It'sfaster becauseitaccessesthenativelibrary(whichautomaticallygivesyoubetter performance),anditwaswrittenwithlotsofhelpfromtheSQLServerteam. 322. Whatarethedifferentnamespacesusedintheprojecttoconnectthe database?Whatdataprovidersavailablein.nettoconnecttodatabase? System.Data.OleDbclassesthatmakeupthe.NETFrameworkDataProvider forOLEDBcompatibledatasources.Theseclassesallowyoutoconnecttoan OLEDBdatasource,executecommandsagainstthesource,andreadthe results. System.Data.SqlClientclassesthatmakeupthe.NETFrameworkData ProviderforSQLServer,whichallowsyoutoconnecttoSQLServer7.0, executecommands,andreadresults.TheSystem.Data.SqlClient namespaceissimilartotheSystem.Data.OleDbnamespace,butisoptimized foraccesstoSQLServer7.0andlater.

System.Data.Odbcclassesthatmakeupthe.NETFrameworkDataProvider forODBC.TheseclassesallowyoutoaccessODBCdatasourceinthe managedspace. System.Data.OracleClientclassesthatmakeupthe.NETFrameworkData ProviderforOracle.TheseclassesallowyoutoaccessanOracledatasourcein themanagedspace. 323. DifferencebetweenDataReaderandDataAdapter/DataSetand DataAdapter? YoucanusetheADO.NETDataReadertoretrieveareadonly,forwardonlystreamof datafromadatabase.UsingtheDataReadercanincreaseapplicationperformanceand reducesystemoverheadbecauseonlyonerowatatimeiseverinmemory. AftercreatinganinstanceoftheCommandobject,youcreateaDataReaderby callingCommand.ExecuteReadertoretrieverowsfromadatasource,asshownin thefollowingexample. SqlDataReadermyReader=myCommand.ExecuteReader() YouusetheReadmethodoftheDataReaderobjecttoobtainarowfromtheresults ofthequery. while(myReader.Read()) Console.WriteLine("\t{0}\t{1}",myReader.GetInt32(0),myReader.GetString(1)) myReader.Close() TheDataSetisamemoryresidentrepresentationofdatathatprovidesaconsistent relationalprogrammingmodelregardlessofthedatasource.Itcanbeusedwith multipleanddifferingdatasources,usedwithXMLdata,orusedtomanagedatalocal totheapplication.TheDataSetrepresentsacompletesetofdataincludingrelated tables,constraints,andrelationshipsamongthetables.Themethodsandobjectsina DataSetareconsistentwiththoseintherelationaldatabasemodel.TheDataSetcan alsopersistandreloaditscontentsasXMLanditsschemaasXMLSchemadefinition language(XSD)schema. TheDataAdapterservesasabridgebetweenaDataSetandadatasourcefor retrievingandsavingdata.TheDataAdapterprovidesthisbridgebymappingFill, whichchangesthedataintheDataSettomatchthedatainthedatasource,and Update,whichchangesthedatainthedatasourcetomatchthedataintheDataSet. IfyouareconnectingtoaMicrosoftSQLServerdatabase,youcanincreaseoverall performancebyusingtheSqlDataAdapteralongwithitsassociatedSqlCommandand SqlConnection.ForotherOLEDBsupporteddatabases,usetheDataAdapterwithits associatedOleDbCommandandOleDbConnectionobjects. 324. WhichmethoddoyouinvokeontheDataAdaptercontroltoloadyour generateddatasetwithdata? Fill() 325. ExplaindifferentmethodsandPropertiesofDataReaderwhichyou haveusedinyourproject? Read GetString GetInt32 while(myReader.Read()) Console.WriteLine("\t{0}\t{1}",myReader.GetInt32(0),myReader.GetString(1)) myReader.Close() 326. WhathappenswhenweissueDataset.ReadXmlcommand? ReadsXMLschemaanddataintotheDataSet. 327. Inhowmanywayswecanretrievetablerecordscount?Howtofind thecountofrecordsinadataset? foreach(DataTablethisTableinmyDataSet.Tables){ //Foreachrow,printthevaluesofeachcolumn. foreach(DataRowmyRowinthisTable.Rows){ 328. Howtocheckifadatareaderisclosedoropened? IsClosed() 329. Whathappenswhenutrytoupdatedatainadatasetin.NETwhilethe recordisalreadydeletedinSQLSERVERasbackend? ORWhatisconcurrency?Howwillyouavoidconcurrencywhendealingwith

dataset?(Oneuserdeletedonerowafterthatanotheruserthroughhis datasetwastryingtoupdatesamerow.Whatwillhappen?Howwillyou avoidtheproblem?) ** 330. Howdoyoumerge2datasetsintothethirddatasetinasimple manner?ORIfyouareexecutingthesestatementsincommandObject. "Select*fromTable1Select*fromTable2howyouwilldealresultset? ** 331. Howdoyousortadataset? ** 332. Ifadatasetcontains100rows,howtofetchrowsbetween5and15 only? ** 333. Differencesbetweendataset.cloneanddataset.copy? CloneCopiesthestructureoftheDataSet,includingallDataTableschemas, relations,andconstraints.Doesnotcopyanydata. CopyCopiesboththestructureanddataforthisDataSet. 334. Whatistheuseofparameterobject? ** 335. HowtogenerateXMLfromadatasetandviceversa? ** 336. WhatismethodtogetXMLandschemafromDataset? ans:getXML()andgetSchema() 337. Howdouimplementlockingconceptfordataset? ** (ASP.NET) 338. Asp.netandaspdifferences? CodeRenderBlock CodeDeclarationBlock Compiled Request/Response EventDriven ObjectOriented Constructors/Destructors, Inheritance,overloading.. ExceptionHandlingTry,Catch, Finally DownlevelSupport Cultures UserControls Inbuiltclientsidevalidation Itcanspanacrossservers,Itcan Sessionweren'ttransferableacross surviveservercrashes,canworkwith servers browsersthatdon'tsupportcookies itsanintegralpartofOSunderthe .netframework.Itsharesmanyof builtontopofthewindow&IIS,it thesameobjectsthattraditional wasalwaysaseparateentity&its applicationswoulduse,andall.net functionalitywaslimited. objectsareavailableforasp.net's consumption. GarbageCollection Declarevariablewithdatatype Inbuiltgraphicssupport Cultures

339. HowASPandASP.NETpageworks?Explainaboutasp.netpagelife cycle? ** 340. Orderofeventsinanasp.netpage?ControlExecutionLifecycle? Phase Initialize Whatacontrolneedstodo Initializesettingsneededduring thelifetimeoftheincomingWeb request. Methodoreventtooverride Initevent(OnInitmethod)

Loadview state

Attheendofthisphase,the LoadViewStatemethod ViewStatepropertyofacontrol isautomaticallypopulatedas describedinMaintainingStateina Control.Acontrolcanoverridethe defaultimplementationofthe LoadViewStatemethodto customizestaterestoration. LoadPostDatamethod(if IPostBackDataHandleris implemented)

Process Processincomingformdataand postbackdata updatepropertiesaccordingly. Load

Performactionscommontoall Loadevent requests,suchassettingupa databasequery.Atthispoint, (OnLoadmethod) servercontrolsinthetreeare createdandinitialized,thestateis restored,andformcontrolsreflect clientsidedata. RaisePostDataChangedEvent method(if IPostBackDataHandleris implemented)

Sendpostback Raisechangeeventsinresponse change tostatechangesbetweenthe notifications currentandpreviouspostbacks. Handle postback events Prerender

Handletheclientsideeventthat RaisePostBackEventmethod(if causedthepostbackandraise IPostBackEventHandleris appropriateeventsontheserver. implemented) Performanyupdatesbeforethe PreRenderevent outputisrendered.Anychanges (OnPreRendermethod) madetothestateofthecontrolin theprerenderphasecanbe saved,whilechangesmadeinthe renderingphasearelost. TheViewStatepropertyofa SaveViewStatemethod controlisautomaticallypersisted toastringobjectafterthisstage. Thisstringobjectissenttothe clientandbackasahidden variable.Forimprovingefficiency, acontrolcanoverridethe SaveViewStatemethodto modifytheViewStateproperty. Generateoutputtoberenderedto Rendermethod theclient. Performanyfinalcleanupbefore Disposemethod thecontrolistorndown. Referencestoexpensiveresources suchasdatabaseconnections

Savestate

Render Dispose

mustbereleasedinthisphase. Unload Performanyfinalcleanupbefore UnLoadevent(OnUnLoad thecontrolistorndown.Control method) authorsgenerallyperformcleanup inDisposeanddonothandlethis event.

341. Note TooverrideanEventNameevent,overridetheOnEventNamemethod (andcallbase.OnEventName). (Session/State) 342. ApplicationandSessionEvents TheASP.NETpageframeworkprovideswaysforyoutoworkwitheventsthatcanbe raisedwhenyourapplicationstartsorstopsorwhenanindividualuser'ssessionstarts orstops: Applicationeventsareraisedforallrequeststoanapplication.Forexample, Application_BeginRequestisraisedwhenanyWebFormspageorXMLWeb serviceinyourapplicationisrequested.Thiseventallowsyoutoinitialize resourcesthatwillbeusedforeachrequesttotheapplication.A correspondingevent,Application_EndRequest,providesyouwithan opportunitytocloseorotherwisedisposeofresourcesusedfortherequest. Sessioneventsaresimilartoapplicationevents(thereisaSession_OnStart andaSession_OnEndevent),butareraisedwitheachuniquesessionwithin theapplication.Asessionbeginswhenauserrequestsapageforthefirsttime fromyourapplicationandendseitherwhenyourapplicationexplicitlycloses thesessionorwhenthesessiontimesout. YoucancreatehandlersforthesetypesofeventsintheGlobal.asaxfile. 343. DifferencebetweenASPSessionandASP.NETSession? asp.netsessionsupportscookielesssession&itcanspanacrossmultipleservers. 344. Whatiscookielesssession?Howitworks? Bydefault,ASP.NETwillstorethesessionstateinthesameprocessthatprocessesthe request,justasASPdoes.Ifcookiesarenotavailable,asessioncanbetrackedby addingasessionidentifiertotheURL.Thiscanbeenabledbysettingthefollowing: <sessionStatecookieless="true"/> http://samples.gotdotnet.com/quickstart/aspplus/doc/stateoverview.aspx 345. Howyouwillhandlesessionwhendeployingapplicationinmorethan aserver?Describesessionhandlinginawebfarm,howdoesitworkandwhat arethelimits? Bydefault,ASP.NETwillstorethesessionstateinthesameprocessthatprocessesthe request,justasASPdoes.Additionally,ASP.NETcanstoresessiondatainanexternal process,whichcanevenresideonanothermachine.Toenablethisfeature: StarttheASP.NETstateservice,eitherusingtheServicessnapinorby executing"netstartaspnet_state"onthecommandline.Thestateservicewill bydefaultlistenonport42424.Tochangetheport,modifytheregistrykey fortheservice: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\aspnet_state\Par ameters\Port Setthemodeattributeofthe<sessionState>sectionto"StateServer". ConfigurethestateConnectionStringattributewiththevaluesofthe machineonwhichyoustartedaspnet_state. Thefollowingsampleassumesthatthestateserviceisrunningonthesamemachine astheWebserver("localhost")andusesthedefaultport(42424):

<sessionState mode="StateServer" stateConnectionString="tcpip=localhost:42424" /> Notethatifyoutrythesampleabovewiththissetting,youcanresettheWebserver (enteriisresetonthecommandline)andthesessionstatevaluewillpersist.**

346. Whatmethoddoyouusetoexplicitlykillauserssession? Abandon() 347. Whatarethedifferentwaysyouwouldconsidersendingdataacross pagesinASP(i.ebetween1.aspto2.asp)? Session publicproperties 348. WhatisStateManagementin.Netandhowmanywaysarethereto maintainastatein.Net?Whatisviewstate? Webpagesarerecreatedeachtimethepageispostedtotheserver.Intraditional Webprogramming,thiswouldordinarilymeanthatallinformationassociatedwiththe pageandthecontrolsonthepagewouldbelostwitheachroundtrip. ToovercomethisinherentlimitationoftraditionalWebprogramming,theASP.NET pageframeworkincludesvariousoptionstohelpyoupreservechangesthatis,for managingstate.Thepageframeworkincludesafacilitycalledviewstatethat automaticallypreservespropertyvaluesofthepageandallthecontrolsonitbetween roundtrips. However,youwillprobablyalsohaveapplicationspecificvaluesthatyouwantto preserve.Todoso,youcanuseoneofthestatemanagementoptions. ClientBasedStateManagementOptions: ViewState HiddenFormFields Cookies QueryStrings ServerBasedStateManagementOptions ApplicationState SessionState DatabaseSupport 349. Whatarethedisadvantagesofviewstate/whatarethebenefits? Automaticviewstatemanagementisafeatureofservercontrolsthatenablesthemto repopulatetheirpropertyvaluesonaroundtrip(withoutyouhavingtowriteany code).Thisfeaturedoesimpactperformance,however,sinceaservercontrol'sview stateispassedtoandfromtheserverinahiddenformfield.Youshouldbeawareof whenviewstatehelpsyouandwhenithindersyourpage'sperformance. 350. WhenmaintainingsessionthroughSqlserver,whatistheimpactof ReadandWriteoperationonSessionobjects?willperformancedegrade? Maintainingstateusingdatabasetechnologyisacommonpracticewhenstoringuser specificinformationwheretheinformationstoreislarge.Databasestorageis particularlyusefulformaintaininglongtermstateorstatethatmustbepreserved eveniftheservermustberestarted. ** 351. Whatarethecontentsofcookie? ** 352. Howdoyoucreateapermanentcookie? ** 353. WhatisViewState?Whatdoesthe"EnableViewState"propertydo? WhywouldIwantitonoroff? **

354. ExplainthedifferencesbetweenServersideandClientsidecode? Serversidecodewillprocessatserverside&itwillsendtheresulttoclient.Client sidecode(javascript)willexecuteonlyatclientside. 355. Canyougiveanexampleofwhatmightbebestsuitedtoplaceinthe Application_StartandSession_Startsubroutines? ** 356. WhichASP.NETconfigurationoptionsaresupportedintheASP.NET implementationonthesharedwebhostingplatform? A: ManyoftheASP.NETconfigurationoptionsarenotconfigurableatthesite, applicationorsubdirectorylevelonthesharedhostingplatform. Certainoptionscan affectthesecurity,performanceandstabilityoftheserverand,thereforecannotbe changed. Thefollowingsettingsaretheonlyonesthatcanbechangedinyoursites web.configfile(s): browserCaps clientTarget pages customErrors globalization authorization authentication webControls webServices http://msdn.microsoft.com/library/default.asp?url=/library/en us/cpguide/html/cpconaspnetconfiguration.asp 357. Brieflydescribetheroleofglobal.asax? 358. Howcanudebugyour.netapplication? 359. Howdoudeployyourasp.netapplication? 360. Wheredowestoreourconnectionstringinasp.netapplication? 361. Variousstepstakentooptimizeawebbasedapplication(caching, storedprocedureetc.) 362. HowdoesASP.NETframeworkmapsclientsideeventstoServerside events. (Security) 363. SecuritytypesinASP/ASP.NET?DifferentAuthenticationmodes? 364. How.Nethasimplementedsecurityforwebapplications? 365. HowtodoFormsauthenticationinasp.net? 366. Explainauthenticationlevelsin.net? 367. Explainautherizationlevelsin.net? 368. WhatisRoleBasedsecurity? Aroleisanamedsetofprincipalsthathavethesameprivilegeswithrespectto security(suchasatelleroramanager).Aprincipalcanbeamemberofoneormore roles.Therefore,applicationscanuserolemembershiptodeterminewhethera principalisauthorizedtoperformarequestedaction. ** 369. Howwillyoudowindowsauthenticationandwhatisthenamespace? Ifauserisloggedunderintegratedwindowsauthenticationmode,butheis stillnotabletologon,whatmightbethepossiblecauseforthis?InASP.Net applicationhowdoyoufindthenameoftheloggedinpersonunderwindows authentication? 370. Whatarethedifferentauthenticationmodesinthe.NETenvironment? 371. <authenticationmode="Windows|Forms|Passport|None"> 372. <formsname="name" 373. loginUrl="url" 374. protection="All|None|Encryption|Validation" 375. timeout="30"path="/"> 376. requireSSL="true|false" 377. slidingExpiration="true|false"> 378. <credentialspasswordFormat="Clear|SHA1|MD5">

379. <username="username"password="password"/> 380. </credentials> 381. </forms> 382. <passportredirectUrl="internal"/> </authentication> Attribute Option Description mode Controlsthedefaultauthenticationmodeforanapplication. WindowsSpecifiesWindowsauthenticationasthedefaultauthentication mode.UsethismodewhenusinganyformofMicrosoftInternet InformationServices(IIS)authentication:Basic,Digest, IntegratedWindowsauthentication(NTLM/Kerberos),or certificates. Forms SpecifiesASP.NETformsbasedauthenticationasthedefault authenticationmode.

Passport SpecifiesMicrosoftPassportauthenticationasthedefault authenticationmode. None Specifiesnoauthentication.Onlyanonymoususersareexpected orapplicationscanhandleeventstoprovidetheirown authentication.

383. HowdoyouspecifywhetheryourdatashouldbepassedasQuery stringandForms(MainlyaboutPOSTandGET) Throughattributetagofformtag. 384. Whatistheothermethod,otherthanGETandPOST,inASP.NET? 385. Whatarevalidator?NametheValidationcontrolsinasp.net?Howdou disablethem?Willtheasp.netvalidatorsruninserversideorclientside? HowdoyoudoClientsidevalidationin.Net?Howtodisablevalidatorcontrol byclientsideJavaScript? AsetofservercontrolsincludedwithASP.NETthattestuserinputinHTMLandWeb servercontrolsforprogrammerdefinedrequirements.Validationcontrolsperform inputcheckinginservercode.Iftheuserisworkingwithabrowserthatsupports DHTML,thevalidationcontrolscanalsoperformvalidation("EnableClientScript" propertysettotrue/false)usingclientscript. Thefollowingvalidationcontrolsareavailableinasp.net: RequiredFieldValidatorControl,CompareValidatorControl,RangeValidatorControl, RegularExpressionValidatorControl,CustomValidatorControl,ValidationSummary Control. 386. Whichtwopropertiesarethereoneveryvalidationcontrol? ControlToValidate,ErrorMessage 387. Howdoyouusecssinasp.net? Withinthe<HEAD>sectionofanHTMLdocumentthatwillusethesestyles,addalink tothisexternalCSSstylesheetthat followsthisform: <LINKREL="STYLESHEET"TYPE="text/css"HREF="MyStyles.css"> MyStyles.cssisthenameofyourexternalCSSstylesheet. 388. Howdoyouimplementpostbackwithatextbox?Whatispostback andusestate? MakeAutoPostBackpropertytotrue 389. HowcanyoudebuganASPpage,withouttouchingthecode? 390. WhatisSQLinjection? AnSQLinjectionattack"injects"ormanipulatesSQLcodebyaddingunexpectedSQL toaquery. Manywebpagestakeparametersfromwebuser,andmakeSQLquerytothe database.Takeforinstancewhenauserlogin,webpagethatusernameand passwordandmakeSQLquerytothedatabasetocheckifauserhasvalidnameand password.

Username:'or1=1 Password:[Empty] Thiswouldexecutethefollowingqueryagainsttheuserstable: selectcount(*)fromuserswhereuserName=''or1=1'anduserPass='' 391. HowcanuhandleExceptionsinAsp.Net? 392. HowcanuhandleUnManagedCodeExceptionsinASP.Net? 393. Asp.netHowtofindlasterrorwhichoccurred? A:Server.GetLastError() [C#] ExceptionLastError StringErrMessage LastError=Server.GetLastError() if(LastError!=null) ErrMessage=LastError.Message else ErrMessage="NoErrors" Response.Write("LastError="+ErrMessage) 394. HowtodoCachinginASP? A:<%@OutputCacheDuration="60"VaryByParam="None"%> VaryByParam Description value none Oneversionofpagecached(onlyrawGET) nversionsofpagecachedbasedonquerystringand/or * POSTbody nversionsofpagecachedbasedonvalueofv1variable v1 inquerystringorPOSTbody nversionsofpagecachedbasedonvalueofv1andv2 v1v2 variablesinquerystringorPOSTbody 395. <%@OutputCacheDuration="60"VaryByParam="none"%> <%@OutputCacheDuration="60"VaryByParam="*"%> <%@OutputCacheDuration="60"VaryByParam="nameage"%> TheOutputCachedirectivesupportsseveralothercachevaryingoptions VaryByHeadermaintainseparatecacheentryforheaderstringchanges (UserAgent,UserLanguage,etc.) VaryByControlforusercontrols,maintainseparatecacheentryfor propertiesofausercontrol VaryByCustomcanspecifyseparatecacheentriesforbrowsertypesand versionorprovideacustomGetVaryByCustomStringmethodin HttpApplicationderivedclass 396. WhatistheGlobalASA(X)File? 397. AnyalternativetoavoidnamecollisionsotherthenNamespaces. AscenariothattwonamespacesnamedN1andN2aretherebothhavingthesame classsayA.nowinanotherclassivewritten usingN1usingN2 andiaminstantiatingclassAinthisclass.Thenhowwilluavoidnamecollisions? Ans:usingalias Eg:usingMyAlias=MyCompany.Proj.Nested 398. WhichisthenamespaceusedtowriteerrormessageineventLog File? 399. Whatarethepageleveltransactionandclassleveltransaction? 400. Whataredifferenttransactionoptions? 401. Whatisthenamespaceforencryption? 402. Whatisthedifferencebetweenapplicationandcachevariables? 403. Whatisthedifferencebetweencontrolandcomponent?

404. Youvedefinedonepage_loadeventinaspxpageandsamepage_load eventincodebehindhowwillprogrun? 405. WherewouldyouuseanIHttpModule,andwhatarethelimitationsof anyapproachyoumighttakeinimplementingone? 406. CanyoueditdataintheRepeatercontrol?Whichtemplatemustyouprovide, inordertodisplaydatainaRepeatercontrol?Howcanyouprovideanalternating colorschemeinaRepeatercontrol?Whatpropertymustyouset,andwhatmethod mustyoucallinyourcode,inordertobindthedatafromsomedatasourcetothe Repeatercontrol? 407. Whatistheuseofweb.config?Differencebetweenmachine.configand Web.config? ASP.NETconfigurationfilesareXMLbasedtextfileseachnamedweb.configthatcan appearinanydirectoryonanASP.NET Webapplicationserver.Eachweb.configfileappliesconfigurationsettingstothe directoryitislocatedinandtoall virtualchilddirectoriesbeneathit.Settingsinchilddirectoriescanoptionallyoverride ormodifysettingsspecifiedin parentdirectories.Therootconfigurationfile WinNT\Microsoft.NET\Framework\<version>\config\machine.configprovides defaultconfigurationsettingsfortheentiremachine.ASP.NETconfiguresIISto preventdirectbrowseraccesstoweb.config filestoensurethattheirvaluescannotbecomepublic(attemptstoaccessthemwill causeASP.NETtoreturn403:Access Forbidden). AtruntimeASP.NETusestheseweb.configconfigurationfilestohierarchically computeauniquecollectionofsettingsfor eachincomingURLtargetrequest(thesesettingsarecalculatedonlyonceandthen cachedacrosssubsequentrequestsASP.NET automaticallywatchesforfilechangesandwillinvalidatethecacheifanyofthe configurationfileschange). http://samples.gotdotnet.com/quickstart/aspplus/doc/configformat.aspx 408. Whatistheuseofsessionstatetagintheweb.configfile? Configuringsessionstate:Sessionstatefeaturescanbeconfiguredviathe <sessionState>sectioninaweb.configfile.Todoublethedefaulttimeoutof20 minutes,youcanaddthefollowingtotheweb.configfileofanapplication: <sessionState timeout="40" /> 409. Whatarethedifferentmodesforthesessionstatesintheweb.config file? Off Inproc StateServer SQLServer Indicatesthatsessionstateisnotenabled. Indicatesthatsessionstateisstoredlocally. Indicatesthatsessionstateisstoredonaremoteserver. IndicatesthatsessionstateisstoredontheSQLServer.

410. Whatissmartnavigation? WhenapageisrequestedbyanInternetExplorer5browser,orlater,smart navigationenhancestheuser'sexperienceofthepagebyperformingthefollowing: eliminatingtheflashcausedbynavigation. persistingthescrollpositionwhenmovingfrompagetopage. persistingelementfocusbetweennavigations. retainingonlythelastpagestateinthebrowser'shistory. SmartnavigationisbestusedwithASP.NETpagesthatrequirefrequentpostbacksbut withvisualcontentthatdoesnotchangedramaticallyonreturn.Considerthiscarefully whendecidingwhethertosetthispropertytotrue.

SettheSmartNavigationattributetotrueinthe@Pagedirectiveinthe.aspxfile. Whenthepageisrequested,thedynamicallygeneratedclasssetsthisproperty. 411. InwhatorderdotheeventsofanASPXpageexecute.Asadeveloper isitimportanttoundertsandtheseevents? 412. HowwouldyougetASP.NETrunninginApachewebserverswhy wouldyouevendothis? 413. Whattagsdoyouneedtoaddwithintheasp:datagridtagstobind columnsmanually 414. WhatbaseclassdoallWebFormsinheritfrom? System.Web.UI.Page 415. Howcanwecreatepiechartinasp.net? 416. Isitpossibleformetochangemyaspxfileextensiontosomeother name? Yes. OpenIIS>DefaultWebsite>Properties SelectHomeDirectorytab Clickonconfigurationbutton Clickonadd.Enteraspnet_isapidetails (C:\WINDOWS\Microsoft.NET\Framework\v1.0.3705\aspnet_isapi.dll | GET,HEAD,POST,DEBUG) Openmachine.config(C:\WINDOWS\Microsoft.NET\Framework\v1.0.3705\CONFIG)& addnewextensionunder<httpHandlers>tag <addverb="*"path="*.santhosh"type="System.Web.UI.PageHandlerFactory"/> 417. WhatisAutoEventWireupattributefor? (WEBSERVICE&REMOTING) 418. WhatisaWebServiceandwhatistheunderlyingprotocolusedinit? Namespace? WebServicesareapplicationsdeliveredasaserviceontheWeb.Webservicesallow forprogrammaticaccessofbusinesslogicovertheWeb.Webservicestypicallyrelyon XMLbasedprotocols,messages,andinterfacedescriptionsforcommunicationand access.Webservicesaredesignedtobeusedbyotherprogramsorapplicationsrather thandirectlybyenduser.ProgramsinvokingaWebservicearecalledclients.SOAP overHTTPisthemostcommonlyusedprotocolforinvokingWebservices. 419. WhyWebServices? Byexposingdataandfunctionalityusingstandardprotocols,Webservicesmakeit easytobuildsophisticatedapplicationsthatintegratemanyfeaturesandcontent. TherearethreemainusesofWebservices.ApplicationintegrationWebserviceswithin anintranetarecommonlyusedtointegratebusinessapplicationsrunningondisparate platforms.Forexample,a.NETclientrunningonWindows2000caneasilyinvokea JavaWebservicerunningonamainframeorUnixmachinetoretrievedatafroma legacyapplication.BusinessintegrationWebservicesallowtradingpartnerstoengage inebusinessleveragingtheexistingInternetinfrastructure.Organizationscansend electronicpurchaseorderstosuppliersandreceiveelectronicinvoices.Doinge businesswithWebservicesmeansalowbarriertoentrybecauseWebservicescanbe addedtoexistingapplicationsrunningonanyplatformwithoutchanginglegacycode. CommercialWebservicesfocusonsellingcontentandbusinessservicestoclientsover theInternetsimilartofamiliarWebpages.UnlikeWebpages,commercialWeb servicestargetapplicationsnothumansastheirdirectusers.ContinentalAirlines exposesflightschedulesandstatusWebservicesfortravelWebsitesandagenciesto useintheirapplications.LikeWebpages,commercialWebservicesarevaluableonlyif theyexposeavaluableserviceorcontent.Itwouldbeverydifficulttogetcustomers topayyouforusingaWebservicethatcreatesbusinesschartswiththecustomers? data.Customerswouldratherbuyachartingcomponent(e.g.COMor.NET component)andinstallitonthesamemachineastheirapplication.Ontheother hand,itmakessensetosellrealtimeweatherinformationorstockquotesasaWeb

service.Technologycanhelpyouaddvaluetoyourservicesandexplorenewmarkets, butultimatelycustomerspayforcontentsand/orbusinessservices,notfortechnology 420. InaWebservice,needtodisplay10rowsfromatable.SoDataReader orDataSetisbestchoice? A:WebServicewillsupportonlyDataSet. 421. AreWebServicesareplacementforotherdistributedcomputing platforms? No.WebServicesisjustanewwayoflookingatexistingimplementationplatforms. 422. WhatisSOAP,WSDL,UDDIandtheconceptbehindWebServices? WhatarevariouscomponentsofWSDL?WhatistheuseofWSDL.exeutility? SOAPisanXMLbasedmessagingframeworkspecificallydesignedforexchanging formatteddataacrosstheInternet,forexampleusingrequestandreplymessagesor sendingentiredocuments.SOAPissimple,easytouse,andcompletelyneutralwith respecttooperatingsystem,programminglanguage,ordistributedcomputing platform. AfterSOAPbecameavailableasamechanismforexchangingXMLmessagesamong enterprises(oramongdisparateapplicationswithinthesameenterprise),abetterway wasneededtodescribethemessagesandhowtheyareexchanged.TheWebServices DescriptionLanguage(WSDL)isaparticularformofanXMLSchema,developedby MicrosoftandIBMforthepurposeofdefiningtheXMLmessage,operation,and protocolmappingofawebserviceaccessedusingSOAPorotherXMLprotocol.WSDL defineswebservicesintermsof"endpoints"thatoperateonXMLmessages.The WSDLsyntaxallowsboththemessagesandtheoperationsonthemessagestobe definedabstractly,sotheycanbemappedtomultiplephysicalimplementations.The currentWSDLspecdescribeshowtomapmessagesandoperationstoSOAP1.1,HTTP GET/POST,andMIME.WSDLcreateswebservicedefinitionsbymappingagroupof endpointsintoalogicalsequenceofoperationsonXMLmessages.ThesameXML messagecanbemappedtomultipleoperations(orservices)andboundtooneor morecommunicationsprotocols(using"ports"). TheUniversalDescription,Discovery,andIntegration(UDDI)frameworkdefinesa datamodel(inXML)andSOAPAPIsforregistrationandsearchesonbusiness information,includingthewebservicesabusinessexposestotheInternet.UDDIisan independentconsortiumofvendors,foundedbyMicrosoft,IBM,andAriba,forthe purposeofdevelopinganInternetstandardforwebservicedescriptionregistration anddiscovery.Microsoft,IBM,andAribaalsoarehostingtheinitialdeploymentofa UDDIservice,whichisconceptuallypatternedafterDNS(theInternetservicethat translatesURLsintoTCPaddresses).UDDIusesaprivateagreementprofileofSOAP (i.e.UDDIdoesn'tusetheSOAPserializationformatbecauseit'snotwellsuitedto passingcompleteXMLdocuments(it'saimedatRPCstyleinteractions).Themainidea isthatbusinessesusetheSOAPAPIstoregisterthemselveswithUDDI,andother businessessearchUDDIwhentheywanttodiscoveratradingpartner,forexample someonefromwhomtheywishtoprocuresheetmetal,bolts,ortransistors.The informationinUDDIiscategorizedaccordingtoindustrytypeandgeographical location,allowingUDDIconsumerstosearchthroughlistsofpotentiallymatching businessestofindthespecificonetheywanttocontact.Onceaspecificbusinessis chosen,anothercalltoUDDIismadetoobtainthespecificcontactinformationforthat business.Thecontactinformationincludesapointertothetargetbusiness'sWSDLor otherXMLschemafiledescribingthewebservicethatthetargetbusinesspublishes. 423. Howtogenerateproxyclassotherthan.netappandwsdltool? ToaccessanXMLWebservicefromaclientapplication,youfirstaddaWebreference, whichisareferencetoanXMLWebservice.WhenyoucreateaWebreference,Visual StudiocreatesanXMLWebserviceproxyclassautomaticallyandaddsittoyour project.ThisproxyclassexposesthemethodsoftheXMLWebserviceandhandlesthe marshallingofappropriateargumentsbackandforthbetweentheXMLWebservice andyourapplication.VisualStudiousestheWebServicesDescriptionLanguage (WSDL)tocreatetheproxy. TogenerateanXMLWebserviceproxyclass: Fromacommandprompt,useWsdl.exetocreateaproxyclass,specifying(at aminimum)theURLtoanXMLWebserviceoraservicedescription,orthe

pathtoasavedservicedescription. Wsdl/language:language /protocol:protocol/namespace:myNameSpace /out:filename /username:username/password:password/domain:domain<urlorpath> 424. asynchronouswebservicemeans? 425. Whataretheeventsfiredwhenwebservicecalled? 426. HowdoesSOAPtransporthappenandwhatistheroleofHTTPinit? Howyoucanaccessawebserviceusingsoap? 427. HowwilldotransactioninWebServices? 428. Whatarethedifferentformatterscanbeusedinboth?Why?.. binary/soap 429. Whatisaproxyinwebservice?HowdoIuseaproxyserverwhen invokingaWebservice? IfyouareusingtheSOAPToolkit,youneedtosetsomeconnectorpropertiestousea proxyserver:DimsoapAsSoapClientSetsoap=NewSoapClient soap.ConnectorProperty("ProxyServer")=?proxyservername? soap.ConnectorProperty("ProxyPort")=?8080?soap.ConnectorProperty("UseProxy") =TrueWhilewith.NET,youjustneedtocreateaSystem.Net.WebProxyobjectand useittosettheProxypropertyDimwebsAslocalhost.MyService()webs.Proxy=New System.Net.WebProxy(?http://proxyserver:8080?) 430. Howyouwillprotect/secureawebservice? Forthemostpart,thingsthatyoudotosecureaWebsitecanbeusedtosecurea WebService.Ifyouneedtoencryptthedataexchange,youuseSecureSocketsLayer (SSL)oraVirtualPrivateNetworktokeepthebitssecure.Forauthentication,use HTTPBasicorDigestauthenticationwithMicrosoftWindowsintegrationtofigure outwhothecalleris. theseitemscannot: ParseaSOAPrequestforvalidvalues AuthenticateaccessattheWebMethodlevel(theycanauthenticateatthe WebServicelevel) Stopreadingarequestassoonasitisrecognizedasinvalid http://msdn.microsoft.com/library/default.asp?url=/library/en us/cpguide/html/cpcontransactionsupportinaspnetwebservices.asp 431. Howwillyouexpose/publishawebservice? 432. Whatstheattributeforwebservicemethod?Whatisthenamespace forcreatingwebservice? 433. Whatisdiscofile? 434. WhatisRemoting? Theprocessofcommunicationbetweendifferentoperatingsystemprocesses, regardlessofwhethertheyareonthesamecomputer.The.NETremotingsystemis anarchitecturedesignedtosimplifycommunicationbetweenobjectslivingindifferent applicationdomains,whetheronthesamecomputerornot,andbetweendifferent contexts,whetherinthesameapplicationdomainornot. 435. Differencebetweenwebservices&remoting? ASP.NETWebServices Protocol State Management TypeSystem .NETRemoting

Canbeaccessedoveranyprotocol CanbeaccessedonlyoverHTTP (includingTCP,HTTP,SMTPandso on) Providesupportforbothstatefuland Webservicesworkinastateless statelessenvironmentsthrough environment SingletonandSingleCallobjects Webservicessupportonlythe datatypesdefinedintheXSD Usingbinarycommunication,.NET Remotingcanprovidesupportfor

typesystem,limitingthe numberofobjectsthatcanbe serialized. Webservicessupport interoperabilityacross Interoperability platforms,andareidealfor heterogeneousenvironments. Highlyreliableduetothefact thatWebservicesarealways hostedinIIS

richtypesystem

.NETremotingrequirestheclientbe builtusing.NET,enforcing homogenousenvironment. CanalsotakeadvantageofIISfor faultisolation.IfIISisnotused, applicationneedstoprovide plumbingforensuringthereliability oftheapplication.

Reliability

Extensibility

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

Easeof Programming

436. Thoughboththe.NETRemotinginfrastructureandASP.NETWebservicescan enablecrossprocesscommunication,eachisdesignedtobenefitadifferenttarget audience.ASP.NETWebservicesprovideasimpleprogrammingmodelandawide reach..NETRemotingprovidesamorecomplexprogrammingmodelandhasamuch narrowerreach. Asexplainedbefore,theclearperformanceadvantageprovidedbyTCPChannel remotingshouldmakeyouthinkaboutusingthischannelwheneveryoucanaffordto doso.IfyoucancreatedirectTCPconnectionsfromyourclientstoyourserverandif youneedtosupportonlythe.NETplatform,youshouldgoforthischannel.Ifyouare goingtogocrossplatformoryouhavetherequirementofsupportingSOAPviaHTTP, youshoulddefinitelygoforASP.NETWebservices. Boththe.NETremotingandASP.NETWebservicesarepowerfultechnologiesthat provideasuitableframeworkfordevelopingdistributedapplications.Itisimportantto understandhowbothtechnologiesworkandthenchoosetheonethatisrightforyour application.Forapplicationsthatrequireinteroperabilityandmustfunctionoverpublic networks,Webservicesareprobablythebestbet.Forthosethatrequire communicationswithother.NETcomponentsandwhereperformanceisakeypriority, .NETRemotingisthebestchoice.Inshort,useWebserviceswhenyouneedtosend andreceivedatafromdifferentcomputingplatforms,use.NETRemotingwhen sendingandreceivingdatabetween.NETapplications.Insomearchitectural scenarios,youmightalsobeabletouse.NETRemotinginconjunctionwithASP.NET Webservicesandtakeadvantageofthebestofbothworlds. TheKeydifferencebetweenASP.NETwebservicesand.NETRemotingishowthey serializedataintomessagesandtheformattheychooseformetadata. ASP.NETuses XMLserializerforserializingorMarshalling.AndXSDisusedforMetadata. .NET RemotingreliesonSystem.Runtime.Serialization.Formatter.Binaryand System.Runtime.Serialization.SOAPFormatterandrelieson.NETCLRRuntime assembliesformetadata. 437. CanyoupassSOAPmessagesthroughremoting? 438. CAOandSAO. ClientActivatedobjectsarethoseremoteobjectswhoseLifetimeisdirectlyControlled bytheclient.ThisisindirectcontrasttoSAO.Wheretheserver,nottheclienthas completecontroloverthelifetimeoftheobjects. Clientactivatedobjectsareinstantiatedontheserverassoonastheclientrequestthe objecttobecreated.UnlikeasSAOaCAOdoesntdelaytheobjectcreationuntilthe firstmethodiscalledontheobject.(InSAOtheobjectisinstantiatedwhentheclient callsthemethodontheobject)

439. singletonandsinglecall. Singletontypesneverhavemorethanoneinstanceatanyonetime.Ifaninstance exists,allclientrequestsareservicedbythatinstance. SingleCalltypesalwayshaveoneinstanceperclientrequest.Thenextmethod invocationwillbeservicedbyadifferentserverinstance,evenifthepreviousinstance hasnotyetbeenrecycledbythesystem. 440. WhatisAsynchronousWebServices? 441. HowtogenerateWebServiceproxy? 442. WebClientclassanditsmethods? 443. Flowofremoting? (XML) 444. Explaintheconceptofdataisland? 445. HowtouseXMLDOMmodelonclientsideusingJavaScript. 446. WhatarethewaystocreateatreeviewcontrolusingXML,XSL& JavaScript? 447. QuestionsonXPathNavigator,andtheotherclassesinSystem.XML Namespace? 448. WhatisUseofTemplateinXSL? 449. WhatisWellFormedXMLandValidXML 450. HowyouwilldoSubStringinXSL 451. CanwedosortinginXSL?howdoyoudealsortingcolumns dynamicallyinXML. 452. WhatisAsyncpropertyofXMLMeans? 453. WhatisXPathQuery? 454. DifferenceBetweenElementandNode. 455. WhatisCDATASection. 456. DOM&SAXparsersexplanationanddifference 457. WhatisGetElementbynamemethodwilldo? 458. Whatisselectnodemethodwillgive? 459. Whatisvalidxmldocument?Whatawellformedxmldocument? 460. WhatistheDifferencebetweenXmlDocumentandXmlDataDocument? 461. ExplainwhataDiffGramis,andagooduseforone? ADiffGramisanXMLformatthatisusedtoidentifycurrentandoriginalversionsof dataelements.WhensendingandretrievingaDataSetfromanXMLWebservice,the DiffGramformatisimplicitlyused. TheDataSetusestheDiffGramformattoloadandpersistitscontents,andto serializeitscontentsfortransportacrossanetworkconnection.WhenaDataSetis writtenasaDiffGram,itpopulatestheDiffGramwithallthenecessaryinformationto accuratelyrecreatethecontents,thoughnottheschema,oftheDataSet,including columnvaluesfromboththeOriginalandCurrentrowversions,rowerror information,androworder. DiffGramFormat TheDiffGramformatisdividedintothreesections:thecurrentdata,theoriginal(or "before")data,andanerrorssection,asshowninthefollowingexample. 462. <?xmlversion="1.0"?> 463. <diffgr:diffgram 464. xmlns:msdata="urn:schemasmicrosoftcom:xmlmsdata" 465. xmlns:diffgr="urn:schemasmicrosoftcom:xmldiffgram v1" 466. xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 467. 468. <DataInstance> 469. </DataInstance> 470. 471. <diffgr:before> 472. </diffgr:before> 473. 474. <diffgr:errors>

475.

</diffgr:errors> </diffgr:diffgram>

TheDiffGramformatconsistsofthefollowingblocksofdata: <DataInstance> Thenameofthiselement,DataInstance,isusedforexplanationpurposesinthis documentation.ADataInstanceelementrepresentsaDataSetorarowofa DataTable.InsteadofDataInstance,theelementwouldcontainthenameofthe DataSetorDataTable.ThisblockoftheDiffGramformatcontainsthecurrentdata, whetherithasbeenmodifiedornot.Anelement,orrow,thathasbeenmodifiedis identifiedwiththediffgr:hasChangesannotation. <diffgr:before> ThisblockoftheDiffGramformatcontainstheoriginalversionofarow.Elementsin thisblockarematchedtoelementsintheDataInstanceblockusingthediffgr:id annotation. <diffgr:errors> ThisblockoftheDiffGramformatcontainserrorinformationforaparticularrowinthe DataInstanceblock.Elementsinthisblockarematchedtoelementsinthe DataInstanceblockusingthediffgr:idannotation. 476. IfIreplacemySqlserverwithXMLfilesandhowabouthandlingthe same? 477. WritesyntaxtoserializeclassusingXMLSerializer? (IIS) 478. InwhichprocessdoesIISruns(wasaskingabouttheEXEfile) inetinfo.exeistheMicrosoftIISserverrunning,handlingASP.NETrequestsamong otherthings. WhenanASP.NETrequestisreceived(usuallyafilewith.aspx extension),theISAPIfilteraspnet_isapi.dlltakescareofitbypassingtherequestto theactualworkerprocessaspnet_wp.exe. 479. WherearetheIISlogfilesstored? C:\WINDOWS\system32\Logfiles\W3SVC1 OR c:\winnt\system32\LogFiles\W3SVC1 480. WhatarethedifferentIISauthenticationmodesinIIS5.0and Explain?Differencebetweenbasicanddigestauthenticationmodes? IISprovidesavarietyofauthenticationschemes: Anonymous(enabledbydefault) Basic Digest IntegratedWindowsauthentication(enabledbydefault) ClientCertificateMapping Anonymous AnonymousauthenticationgivesusersaccesstothepublicareasofyourWebsite withoutpromptingthemforausernameorpassword.Althoughlistedasan authenticationscheme,itisnottechnicallyperforminganyclientauthentication becausetheclientisnotrequiredtosupplyanycredentials.Instead,IISprovides storedcredentialstoWindowsusingaspecialuseraccount,IUSR_machinename.By default,IIScontrolsthepasswordforthisaccount.WhetherornotIIScontrolsthe passwordaffectsthepermissionstheanonymoususerhas.WhenIIScontrolsthe password,asubauthenticationDLL(iissuba.dll)authenticatestheuserusinga networklogon.ThefunctionofthisDLListovalidatethepasswordsuppliedbyIISand toinformWindowsthatthepasswordisvalid,therebyauthenticatingtheclient. However,itdoesnotactuallyprovideapasswordtoWindows.WhenIISdoesnot

controlthepassword,IIScallstheLogonUser()APIinWindowsandprovidesthe accountname,passwordanddomainnametologontheuserusingalocallogon. Afterthelogon,IIScachesthesecuritytokenandimpersonatestheaccount.Alocal logonmakesitpossiblefortheanonymoususertoaccessnetworkresources,whereas anetworklogondoesnot. BasicAuthentication IISBasicauthenticationasanimplementationofthebasicauthenticationscheme foundinsection11oftheHTTP1.0specification. Asthespecificationmakesclear,thismethodis,inandofitself,nonsecure.The reasonisthatBasicauthenticationassumesatrustedconnectionbetweenclientand server.Thus,theusernameandpasswordaretransmittedincleartext.More specifically,theyaretransmittedusingBase64encoding,whichistriviallyeasyto decode.ThismakesBasicauthenticationthewrongchoicetouseoverapublic networkonitsown. BasicAuthenticationisalongstandingstandardsupportedbynearlyallbrowsers.It alsoimposesnospecialrequirementsontheserversideuserscanauthenticate againstanyNTdomain,orevenagainstaccountsonthelocalmachine.WithSSLto shelterthesecuritycredentialswhiletheyareintransmission,youhavean authenticationsolutionthatisbothhighlysecureandquiteflexible. DigestAuthentication TheDigestauthenticationoptionwasaddedinWindows2000andIIS5.0.LikeBasic authentication,thisisanimplementationofatechniquesuggestedbyWebstandards, namelyRFC2069(supercededbyRFC2617). Digestauthenticationalsousesachallenge/responsemodel,butitismuchmore securethanBasicauthentication(whenusedwithoutSSL).Itachievesthisgreater securitynotbyencryptingthesecret(thepassword)beforesendingit,butratherby followingadifferentdesignpatternonethatdoesnotrequiretheclienttotransmit thepasswordoverthewireatall. Insteadofsendingthepassworditself,theclienttransmitsaonewaymessagedigest (achecksum)oftheuser'spassword,using(bydefault)theMD5algorithm.The serverthenfetchesthepasswordforthatuserfromaWindows2000Domain Controller,rerunsthechecksumalgorithmonit,andcomparesthetwodigests.Ifthey match,theserverknowsthattheclientknowsthecorrectpassword,eventhoughthe passworditselfwasneversent.(IfyouhaveeverwonderedwhatthedefaultISAPI filter"md5filt"thatisinstalledwithIIS5.0isusedfor,nowyouknow. IntegratedWindowsAuthentication IntegratedWindowsauthentication(formerlyknownasNTLMauthenticationand WindowsNTChallenge/Responseauthentication)canuseeitherNTLMorKerberosV5 authenticationandonlyworkswithInternetExplorer2.0andlater. WhenInternetExplorerattemptstoaccessaprotectedresource,IISsendstwoWWW Authenticateheaders,NegotiateandNTLM.

IfInternetExplorerrecognizestheNegotiateheader,itwillchooseitbecause itislistedfirst.WhenusingNegotiate,thebrowserwillreturninformationfor bothNTLMandKerberos.Attheserver,IISwilluseKerberosifboththeclient (InternetExplorer5.0andlater)andserver(IIS5.0andlater)arerunning Windows2000andlater,andbotharemembersofthesamedomainor trusteddomains.Otherwise,theserverwilldefaulttousingNTLM. IfInternetExplorerdoesnotunderstandNegotiate,itwilluseNTLM.

So,whichmechanismisuseddependsuponanegotiationbetweenInternetExplorer andIIS. WhenusedinconjunctionwithKerberosv5authentication,IIScandelegatesecurity credentialsamongcomputersrunningWindows2000andlaterthataretrustedand configuredfordelegation.Delegationenablesremoteaccessofresourcesonbehalfof thedelegateduser. IntegratedWindowsauthenticationisthebestauthenticationschemeinanintranet environmentwhereusershaveWindowsdomainaccounts,especiallywhenusing

Kerberos.IntegratedWindowsauthentication,likedigestauthentication,doesnotpass theuser'spasswordacrossthenetwork.Instead,ahashedvalueisexchanged. ClientCertificateMapping Acertificateisadigitallysignedstatementthatcontainsinformationaboutanentity andtheentity'spublickey,thusbindingthesetwopiecesofinformationtogether.A trustedorganization(orentity)calledaCertificationAuthority(CA)issuesacertificate aftertheCAverifiesthattheentityiswhoitsaysitis.Certificatescancontain differenttypesofdata.Forexample,anX.509certificateincludestheformatofthe certificate,theserialnumberofthecertificate,thealgorithmusedtosignthe certificate,thenameoftheCAthatissuedthecertificate,thenameandpublickeyof theentityrequestingthecertificate,andtheCA'ssignature.X.509clientcertificates simplifyauthenticationforlargeruserbasesbecausetheydonotrelyonacentralized accountdatabase.Youcanverifyacertificatesimplybyexaminingthecertificate. http://msdn.microsoft.com/library/default.asp?url=/library/en us/vsent7/html/vxconIISAuthentication.asp 481. HowtoconfigurethesitesinWebserver(IIS)? 482. AdvantagesinIIS6.0? http://www.microsoft.com/windowsserver2003/iis/evaluation/features/default.mspx http://www.microsoft.com/technet/treeview/default.asp?url=/technet/prodtechnol/win dowsserver2003/proddocs/datacenter/gs_whatschanged.asp 483. IISIsolationLevels? InternetInformationServerintroducedthenotion"IsolationLevel",whichisalso presentinIIS4underadifferentname.IIS5supportsthreeisolationlevels,thatyou cansetfromtheHomeDirectorytabofthesite'sPropertiesdialog: Low(IISProcess):ASPpagesruninINetInfo.Exe,themainIISprocess, thereforetheyareexecutedinprocess.Thisisthefastestsetting,andisthe defaultunderIIS4.TheproblemisthatifASPcrashes,IIScrashesaswelland mustberestarted(IIS5hasareliablerestartfeaturethatautomatically restartsaserverwhenafatalerroroccurs). Medium(Pooled):InthiscaseASPrunsinadifferentprocess,whichmakes thissettingmorereliable:ifASPcrashesIISwon't.AlltheASPapplicationsat theMediumisolationlevelsharethesameprocess,soyoucanhaveawebsite runningwithjusttwoprocesses(IISandASPprocess).IIS5isthefirst InternetInformationServerversionthatsupportsthissetting,whichisalso thedefaultsettingwhenyoucreateanIIS5application.NotethatanASP applicationthatrunsatthislevelisrununderCOM+,soit'shostedin DLLHOST.EXE(andyoucanseethisexecutableintheTaskManager). High(Isolated):EachASPapplicationrunsoutprocessinitsownprocess space,thereforeifanASPapplicationcrashes,neitherIISnoranyotherASP applicationwillbeaffected.Thedownsideisthatyouconsumemorememory andresourcesiftheserverhostsmanyASPapplications.BothIIS4andIIS5 supportsthissetting:underIIS4thisprocessrunsinsideMTS.EXE,while underIIS5itrunsinsideDLLHOST.EXE. WhenselectinganisolationlevelforyourASPapplication,keepinmindthatout processsettingsthatis,MediumandHigharelessefficientthaninprocess(Low). However,outprocesscommunicationhasbeenvastlyimprovedunderIIS5,andin factIIS5'sMediumisolationleveloftendeliverbetterresultsthanIIS4'sLowisolation. Inpractice,youshouldn'tsettheLowisolationlevelforanIIS5applicationunlessyou reallyneedtoservehundredspagespersecond. Controls 484. HowwillyoudoRedoandUndoinaTextControl? 485. HowtoimplementDataGridin.NET?Howwouldumakeacombobox appearinonecolumnofaDataGrid?Whatarethewaystoshowdatagrid

insideadatagridforamasterdetailstypeoftables?Ifwewriteanycodefor DataGridmethods,whatistheaccessspecifierusedforthatmethodsinthe codebehindfileandwhy? 486. HowcanwecreateTreecontrolinasp.net? Programming 487. WriteaprograminC#forcheckingagivennumberisPRIMEornot. 488. Writeaprogramtofindtheanglebetweenthehoursandminutesina clock 489. WriteaC#programtofindtheFactorialofn 490. HowdoIuploadafilefrommyASP.NETpage? A:InordertoperformfileuploadinyourASP.NETpage,youwillneedtousetwo classes:theSystem.Web.UI.HtmlControls.HtmlInputFileclassandthe System.Web.HttpPostedFileclass.TheHtmlInputFileclassrepresentsandHTMLinput controlthattheuserwilluseontheclientsidetoselectafiletoupload.The HttpPostedFileclassrepresentstheuploadedfileandisobtainedfromthePostedFile propertyoftheHtmlInputFileclass.InordertousetheHtmlInputFilecontrol,you needtoaddtheenctypeattributetoyourformtagasfollows: <formid="upload"method="post"runat="server"enctype="multipart/formdata"> Also,rememberthatthe/datadirectoryistheonlydirectorywithWritepermissions enabledfortheanonymoususer.Therefore,youwillneedtomakesurethattheyour codeuploadsthefiletothe/datadirectoryoroneofitssubdirectories. BelowisasimpleexampleofhowtouploadafileviaanASP.NETpageinC#and VB.NET. C# <%@ImportNamespace="System"%> <%@ImportNamespace="System.Web"%> <%@ImportNamespace="System.Web.UI.HtmlControls"%> <%@ImportNamespace="System.IO"%> <%@ImportNamespace="System.Drawing"%> <html> <head> <title>upload_cs</title> </head> <scriptlanguage="C#"runat="server"> publicvoidUploadFile(objectsender,EventArgse) { if(loFile.PostedFile!=null) { try { stringstrFileName,strFileNamePath,strFileFolder strFileFolder=Context.Server.MapPath(@"data\") strFileName=loFile.PostedFile.FileName strFileName=Path.GetFileName(strFileName) strFileNamePath=strFileFolder+strFileName loFile.PostedFile.SaveAs(strFileNamePath) lblFileName.Text=strFileName lblFileLength.Text=loFile.PostedFile.ContentLength.ToString() lblFileType.Text=loFile.PostedFile.ContentType pnStatus.Visible=true } catch(Exceptionx) { LabellblError=newLabel() lblError.ForeColor=Color.Red lblError.Text="Exceptionoccurred:"+x.Message lblError.Visible=true this.Controls.Add(lblError)

} } } </script> <body> <formid="upload_cs"method="post"runat="server"enctype="multipart/form data"> <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> 491. HowdoIsendanemailmessagefrommyASP.NETpage? A:YoucanusetheSystem.Web.Mail.MailMessageandtheSystem.Web.Mail.SmtpMail classtosendemailinyourASPXpages.Belowisasimpleexampleofusingthisclass tosendmailinC#andVB.NET.Inordertosendmailthroughourmailserver,you wouldwanttomakesuretosetthestaticSmtpServerpropertyoftheSmtpMailclass tomailfwd. C# <%@ImportNamespace="System"%> <%@ImportNamespace="System.Web"%> <%@ImportNamespace="System.Web.Mail"%> <HTML> <HEAD> <title>MailTest</title> </HEAD> <scriptlanguage="C#"runat="server"> privatevoidPage_Load(Objectsender,EventArgse) { try { MailMessagemailObj=newMailMessage() mailObj.From="sales@joeswidgets.com" mailObj.To="ringleader@forexampledomain.com" mailObj.Subject="YourWidgetOrder" mailObj.Body="Yourorderwasprocessed." mailObj.BodyFormat=MailFormat.Text SmtpMail.SmtpServer="mailfwd" SmtpMail.Send(mailObj) Response.Write("Mailsentsuccessfully") } catch(Exceptionx) { Response.Write("Yourmessagewasnotsent:"+x.Message) } } </script> <body>

<formid="mail_test"method="post"runat="server"> </form> </body> </HTML> 492. Writeaprogramtocreateausercontrolwithnameandsurnameas datamembersandloginasmethodandalsothecodetocallit.(Hintuse eventdelegates)

You might also like