• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Dotnet basics

Dotnet basics






Total Views
Views on SlideShare
Embed Views



1 Embed 1

http://localhost 1



Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
Post Comment
Edit your comment

    Dotnet basics Dotnet basics Document Transcript

    • Dot Net - .Net Basic , Framework and Advanced1 . What is .NET? .NET is a general-purpose software development platform, similar to Java. At its coreis a virtual machine that turns intermediate language (IL) into machine code. High-levellanguage compilers for C#, VB.NET and C++ are provided to turn source code into IL. C#is a new programming language, very similar to Java. An extensive class library isincluded, featuring all the functionality one might expect from a contempory developmentplatform - windows GUI development (Windows Forms), database access (ADO.NET), webdevelopment (ASP.NET), web services, XML etcSee also Microsofts definition2 . When was .NET announced? Bill Gates delivered a keynote at Forum 2000, held June 22, 2000, outlining the .NETvision. The July 2000 PDC had a number of sessions on .NET technology, and delegateswere given CDs containing a pre-release version of the .NET framework/SDK and VisualStudio.NET.3 . What versions of .NET are there? The final versions of the 1.0 SDK and runtime were made publicly availablearound &6pm PST on 15-Jan-2002. At the same time, the final version of VisualStudio.NET was made available to MSDN subscribers. .NET 1.1 was released in April 2003, and was mostly bug fixes for 1.0. .NET 2.0 was released to MSDN subscribers in late October 2005, and was officiallylaunched in early November.4 . What operating systems does the .NET Framework run on? The runtime supports Windows Server 2003, Windows XP, Windows 2000, NT4 SP6aand Windows ME/98. Windows 95 is not supported. Some parts of the framework do notwork on all platforms - for example, ASP.NET is only supported on XP and Windows2000/2003. Windows 98/ME cannot be used for developmentIIS is not supported on Windows XP Home Edition, and so cannot be used to hostASP.NET. However, the ASP.NET Web Matrixweb server does run on XP Home The .NET Compact Framework is a version of the .NET Framework for mobile devices,running Windows CE or Windows Mobile. The Mono project has a version of the .NET Framework that runs on Linux.5 . What tools can I use to develop .NET applications? There are a number of tools, described here in ascending order of cost:• The .NET Framework SDK is free and includes command-line compilers for C++, C#, and VB.NET and various other utilities to aid development.• SharpDevelop is a free IDE for C# and VB.NET.• Microsoft Visual Studio Express editions are cut-down versions of Visual Studio, for hobbyist or novice developers.There are different versions for C#, VB, web development etc. Originally the plan was to charge $49, but MS has decided to offer
    • them as free downloads instead, at least until November 2006.• Microsoft Visual Studio Standard 2005 is around $300, or $200 for the upgrade.• Microsoft VIsual Studio Professional 2005 is around $800, or $550 for the upgrade• At the top end of the price range are the Microsoft Visual Studio Team Edition for Software Developers 2005 with MSDN Premium and Team Suite editions. You can see the differences between the various Visual Studio versions here.6 . Why did they call it .NET? I dont know what they were thinking. They certainly werent thinking of people usingsearch tools. Its meaningless marketing nonsense.7 . What is the CLI? Is it the same as the CLR? The CLI (Common Language Infrastructure) is the definiton of the fundamentals ofthe .NET framework - the Common Type System (CTS), metadata, the Virtual ExecutionEnvironment (VES) and its use of intermediate language (IL), and the support of multipleprogramming languages via the Common Language Specification (CLS). The CLI isdocumented through ECMA - seehttp://msdn.microsoft.com/net/ecma/ for more details. The CLR (Common Language Runtime) is Microsofts primary implementation of theCLI. Microsoft also have a shared source implementation known as ROTOR, for educationalpurposes, as well as the .NET Compact Framework for mobile devices. Non-Microsoft CLIimplementations include Mono and DotGNU Portable.NET.8 . What is IL? IL = Intermediate Language. Also known as MSIL (Microsoft Intermediate Language)or CIL (Common Intermediate Language). All .NET source code (of any language) iscompiled to IL during development. The IL is then converted to machine code at the pointwhere the software is installed, or (more commonly) at run-time by a Just-In-Time (JIT)compiler.9 . What is C#? C# is a new language designed by Microsoft to work with the .NET framework. Intheir "Introduction to C#" whitepaper, Microsoft describe C# as follows: "C# is a simple, modern, object oriented, and type-safe programming languagederived from C and C++. C# (pronounced “C sharp”) is firmly planted in the C and C++family tree of languages, and will immediately be familiar to C and C++ programmers. C#aims to combine the high productivity of Visual Basic and the raw power of C++." Substitute Java for C# in the quote above, and youll see that the statement stillworks pretty well :-).10 . What does managed mean in the .NET context? The term managed is the cause of much confusion. It is used in various placeswithin .NET, meaning slightly different things. Managed code: The .NET framework provides several core run-time services to theprograms that run within it - for example exception handling and security. For theseservices to work, the code must provide a minimum level of information to the runtime.Such code is called managed code. Managed data: This is data that is allocated and freed by the .NET runtimes garbage
    • collector. Managed classes: This is usually referred to in the context of Managed Extensions(ME) for C++. When using ME C++, a class can be marked with the __gc keyword. As thename suggests, this means that the memory for instances of the class is managed by thegarbage collector, but it also means more than that. The class becomes a fully paid-upmember of the .NET community with the benefits and restrictions that brings. An exampleof a benefit is proper interop with classes written in other languages - for example, amanaged C++ class can inherit from a VB class. An example of a restriction is that amanaged class can only inherit from one base class.11 . What is an assembly? An assembly is sometimes described as a logical .EXE or .DLL, and can bean application (with a main entry point) or alibrary. An assembly consists of one ormore files (dlls, exes, html files etc), and represents a group of resources, type definitions,and implementations of those types. An assembly may also contain references to otherassemblies. These resources, types and references are described in a block of data calleda manifest. The manifest is part of the assembly, thus making the assembly self-describing. An important aspect of assemblies is that they are part of the identity of a type. Theidentity of a type is the assembly that houses it combined with the type name. Thismeans, for example, that if assembly A exports a type called T, and assembly B exports atype called T, the .NET runtime sees these as two completely different types. Furthermore,dont get confused between assemblies and namespaces - namespaces are merely ahierarchical way of organising type names. To the runtime, type names are type names,regardless of whether namespaces are used to organise the names. Its the assembly plusthe typename (regardless of whether the type name belongs to a namespace) thatuniquely indentifies a type to the runtime. Assemblies are also important in .NET with respect to security - many of the securityrestrictions are enforced at the assembly boundary. Finally, assemblies are the unit of versioning in .NET - more on this below.12 . How can I produce an assembly? The simplest way to produce an assembly is directly from a .NET compiler. Forexample, the following C# program:public class CTest { public CTest() { System.Console.WriteLine( "Hello from CTest" ); } } can be compiled into a library assembly (dll) like this:csc /t:library ctest.cs You can then view the contents of the assembly by running the "IL Disassembler"tool that comes with the .NET SDK. Alternatively you can compile your source into modules, and then combine themodules into an assembly using the assembly linker (al.exe). For the C# compiler, the
    • /target:module switch is used to generate a module instead of an assembly.13 . What is the difference between a private assembly and a sharedassembly? The terms private and shared refer to how an assembly is deployed, not anyintrinsic attributes of the assembly. A private assembly is normally used by a single application, and is stored in theapplications directory, or a sub-directory beneath. A shared assembly is intended to beused by multiple applications, and is normally stored in the global assembly cache (GAC),which is a central repository for assemblies. (A shared assembly can also be stored outsidethe GAC, in which case each application must be pointed to its location via a codebaseentry in the applications configuration file.) The main advantage of deploying assembliesto the GAC is that the GAC can support multiple versions of the same assembly side-by-side. Assemblies deployed to the GAC must be strong-named. Outside the GAC, strong-naming is optional.14 . How do assemblies find each other? By searching directory paths. There are several factors that can affect the path (suchas the AppDomain host, and application configuration files), but for weakly namedassemblies the search path is normally the applications directory and its sub-directories.For strongly named assemblies, the search path is the GAC followed by the privateassembly path.15 . How does assembly versioning work? An assembly has a version number consisting of four parts, e.g. 1.0.350.1. These aretypically interpreted as Major.Minor.Build.Revision, but this is just a convention.& The CLR applies no version constraints on weakly named assemblies, so theassembly version has no real significance. For strongly named assemblies, the version of a referenced assembly is stored in thereferring assembly, and by default only this exact version will be loaded at run-time. If theexact version is not available, the referring assembly will fail to load. It is possible tooverride this behaviour in the config file for the referring assembly - references to a singleversion or a range of versions of the referenced assembly can be redirected to a specificversion. For example, versions to can be redirected to version note that there is no way to specify a range of versions to be redirected to.Publisher policy files offer an alternative mechanism for redirecting to a different versionfor assemblies deployed to the GAC - a publisher policy file allows the publisher of theassembly to redirect all applications to a new version of an assembly in one operation,rather than having to modify all of the application configuration files. The restrictions on version policy for strongly named assemblies can cause problemswhen providing patches or hot fixes for individual assemblies within an application. Toavoid having to deploy config file changes or publisher policy files along with the hot fix, itmakes sense to reuse the same assembly version for the hot fix. If desired, the assembliescan be distinguised by altering the assembly file version, which is not used at all by theCLR for applying version policy. For more discussion, see Suzanne Cooks When to Change
    • File/Assembly Versions blog entry. Note that the versioning of strongly named assemblies applies whether theassemblies are deployed privately or to the GAC.16 . How can I develop an application that automatically updates itself fromthe web? For .NET 1.x, use the Updater Application Block. For .NET 2.x, use ClickOnce.17 . What is an application domain? An AppDomain can be thought of as a lightweight process. Multiple AppDomains canexist inside a Win32 process. The primary purpose of the AppDomain is to isolateapplications from each other, and so it is particularly useful in hosting scenarios such asASP.NET. An AppDomain can be destroyed by the host without affecting otherAppDomains in the process. Win32 processes provide isolation by having distinct memory address spaces. This iseffective, but expensive. The .NET runtime enforces AppDomain isolation by keepingcontrol over the use of memory - all memory in the AppDomain is managed by the .NETruntime, so the runtime can ensure that AppDomains do not access each others memory. One non-obvious use of AppDomains is for unloading types. Currently the only way tounload a .NET type is to destroy the AppDomain it is loaded into. This is particularly usefulif you create and destroy types on-the-fly via reflection.18 . Can I write my own .NET host?Yes. For an example of how to do this, take a look at the source for the dm.netmoniker developed by Jason Whittington and Don Box. There is also a code sample inthe .NET SDK called CorHost.19 . What is garbage collection? Garbage collection is a heap-management strategy where a run-time componenttakes responsibility for managing the lifetime of the memory used by objects. This conceptis not new to .NET - Java and many other languages/runtimes have used garbagecollection for some time.20 . Is it true that objects dont always get destroyed immediately when thelast reference goes away? Yes. The garbage collector offers no guarantees about the time when an object willbe destroyed and its memory reclaimed.& There was an interesting thread on the DOTNET list, started by Chris Sells, about theimplications of non-deterministic destruction of objects in C#. In October 2000, MicrosoftsBrian Harry posted a lengthy analysis of the problem. Chris Sellsresponse to Briansposting is here21 . Why doesnt the .NET runtime offer deterministic destruction? Because of the garbage collection algorithm. The .NET garbage collector works byperiodically running through a list of all the objects that are currently being referenced byan application. All the objects that it doesnt find during this search are ready to bedestroyed and the memory reclaimed. The implication of this algorithm is that the runtimedoesnt get notified immediately when the final reference on an object goes away - it onlyfinds out during the next sweep of the heap
    • Futhermore, this type of algorithm works best by performing the garbage collectionsweep as rarely as possible. Normally heap exhaustion is the trigger for a collectionsweep.22 . Is the lack of deterministic destruction in .NET a problem? Its certainly an issue that affects component design. If you have objects thatmaintain expensive or scarce resources (e.g. database locks), you need to provide someway to tell the object to release the resource when it is done. Microsoft recommend thatyou provide a method called Dispose() for this purpose. However, this causes problems fordistributed objects - in a distributed system who calls the Dispose() method? Some formof reference-counting or ownership-management mechanism is needed to handledistributed objects - unfortunately the runtime offers no help with this23 . Should I implement Finalize on my class? Should I implementIDisposable? This issue is a little more complex than it first appears. There are really twocategories of class that require deterministic destruction - the first category manipulateunmanaged types directly, whereas the second category manipulate managed types thatrequire deterministic destruction. An example of the first category is a class with an IntPtrmember representing an OS file handle. An example of the second category is a class witha System.IO.FileStream member For the first category, it makes sense to implement IDisposable and overrideFinalize. This allows the object user to do the right thing by calling Dispose, but alsoprovides a fallback of freeing the unmanaged resource in the Finalizer, should the callingcode fail in its duty. However this logic does not apply to the second category of class,with only managed resources. In this case implementing Finalize is pointless, as managedmember objects cannot be accessed in the Finalizer. This is because there is no guaranteeabout the ordering of Finalizer execution. So only the Dispose method should beimplemented. (If you think about it, it doesnt really make sense to call Dispose onmember objects from a Finalizer anyway, as the member objects Finalizer will do therequired cleanup.) For classes that need to implement IDisposable and override Finalize, seeMicrosofts documented pattern. Note that some developers argue that implementing a Finalizer is always a bad idea,as it hides a bug in your code (i.e. the lack of a Dispose call). A less radical approach is toimplement Finalize but include a Debug.Assert at the start, thus signalling the problem indeveloper builds but allowing the cleanup to occur in release builds.24 . Do I have any control over the garbage collection algorithm? A little. For example the System.GC class exposes a Collect method, which forces thegarbage collector to collect all unreferenced objects immediately Also there is a gcConcurrent setting that can be specified via the applicationconfiguration file. This specifies whether or not the garbage collector performs some of itscollection activities on a separate thread. The setting only applies on multi-processormachines, and defaults to true.25 . How can I find out what the garbage collector is doing? Lots of interesting statistics are exported from the .NET runtime via the .NET CLRxxx performance counters. Use Performance Monitor to view them26 . What is the lapsed listener problem?
    • The lapsed listener problem is one of the primary causes of leaks in .NETapplications. It occurs when a subscriber (or listener) signs up for a publishers event, butfails to unsubscribe. The failure to unsubscribe means that the publisher maintains areference to the subscriber as long as the publisher is alive. For some publishers, this maybe the duration of the application This situation causes two problems. The obvious problem is the leakage of thesubscriber object. The other problem is the performance degredation due to the publishersending redundant notifications to zombie subscribers. There are at least a couple of solutions to the problem. The simplest is to make surethe subscriber is unsubscribed from the publisher, typically by adding an Unsubscribe()method to the subscriber. Another solution, documented here by Shawn Van Ness, is tochange the publisher to use weak references in its subscriber list.27 . What is serialization? Serialization is the process of converting an object into a stream of bytes.Deserialization is the opposite process, i.e. creating an object from a stream of bytes.Serialization/Deserialization is mostly used to transport objects (e.g. during remoting), orto persist objects (e.g. to a file or database).28 . Does the .NET Framework have in-built support for serialization? There are two separate mechanisms provided by the .NET class library -XmlSerializer and SoapFormatter/BinaryFormatter. Microsoft uses XmlSerializer for WebServices, and SoapFormatter/BinaryFormatter for remoting. Both are available for use inyour own code29 . I want to serialize instances of my class. Should I use XmlSerializer,SoapFormatter or BinaryFormatter? It depends. XmlSerializer has severe limitations such as the requirement that thetarget class has a parameterless constructor, and only public read/write properties andfields can be serialized. However, on the plus side, XmlSerializer has good support forcustomising the XML document that is produced or consumed. XmlSerializers featuresmean that it is most suitable for cross-platform work, or for constructing objects fromexisting XML documents SoapFormatter and BinaryFormatter have fewer limitations than XmlSerializer. Theycan serialize private fields, for example. However they both require that the target classbe marked with the [Serializable] attribute, so like XmlSerializer the class needs to bewritten with serialization in mind. Also there are some quirks to watch out for - forexample on deserialization the constructor of the new object is not invoked. The choice between SoapFormatter and BinaryFormatter depends on the application.BinaryFormatter makes sense where both serialization and deserialization will beperformed on the .NET platform and where performance is important. SoapFormattergenerally makes more sense in all other cases, for ease of debugging if nothing else.30 . Can I customise the serialization process? Yes. XmlSerializer supports a range of attributes that can be used to configureserialization for a particular class. For example, a field or property can be marked with the[XmlIgnore] attribute to exclude it from serialization. Another example is the[XmlElement] attribute, which can be used to specify the XML element name to be usedfor a particular property or field.
    • Serialization via SoapFormatter/BinaryFormatter can also be controlled to someextent by attributes. For example, the [NonSerialized] attribute is the equivalent ofXmlSerializers [XmlIgnore] attribute. Ultimate control of the serialization process can beacheived by implementing the the ISerializable interface on the class whose instances areto be serialized.31 . Why is XmlSerializer so slow? There is a once-per-process-per-type overhead with XmlSerializer. So the first timeyou serialize or deserialize an object of a given type in an application, there is a significantdelay. This normally doesnt matter, but it may mean, for example, that XmlSerializer is apoor choice for loading configuration settings during startup of a GUI application32 . Why do I get errors when I try to serialize a Hashtable? XmlSerializer will refuse to serialize instances of any class that implementsIDictionary, e.g. Hashtable. SoapFormatter and BinaryFormatter do not have thisrestriction.33 . XmlSerializer is throwing a generic "There was an error reflectingMyClass" error. How do I find out what the problem is? Look at the InnerException property of the exception that is thrown to get a morespecific error message34 . What are attributes? There are at least two types of .NET attribute. The first type I will refer to asa metadata attribute - it allows some data to be attached to a class or method. This databecomes part of the metadata for the class, and (like other class metadata) can beaccessed via reflection. An example of a metadata attribute is [serializable], which can beattached to a class and means that instances of the class can be serialized.[serializable] public class CTest {}The other type of attribute is a context attribute. Context attributes use a similar syntaxto metadata attributes but they are fundamentally different. Context attributes provide aninterception mechanism whereby instance activation and method calls can be pre- and/orpost-processed. If you have encountered Keith Browns universal delegator youll befamiliar with this idea.35 . What is Code Access Security (CAS)? CAS is the part of the .NET security model that determines whether or not code isallowed to run, and what resources it can use when it is running. For example, it is CASthat will prevent a .NET web applet from formatting your hard disk.36 . How does CAS work? The CAS security policy revolves around two key concepts - code groups andpermissions. Each .NET assembly is a member of a particular code group, and each codegroup is granted the permissions specified in a named permission set. For example, using the default security policy, a control downloaded from a web sitebelongs to the Zone - Internet code group, which adheres to the permissions defined bythe Internet named permission set. (Naturally the Internet named permission setrepresents a very restrictive range of permissions.)37 . Im having some trouble with CAS. How can I troubleshoot the problem? Caspol has a couple of options that might help. First, you can ask caspol to tell youwhat code group an assembly belongs to, using caspol -rsg. Similarly, you can ask whatpermissions are being applied to a particular assembly using caspol -rsp
    • 38 . I cant be bothered with CAS. Can I turn it off? Yes, as long as you are an administrator. Just run: caspol -s off39 . Can I look at the IL for an assembly? Yes. MS supply a tool called Ildasm that can be used to view the metadata and IL foran assembly.40 . Can source code be reverse-engineered from IL? Yes, it is often relatively straightforward to regenerate high-level source from IL. LutzRoeders Reflector does a very good job of turning IL into C# or VB.NET.41 . How can I stop my code being reverse-engineered from IL? You can buy an IL obfuscation tool. These tools work by optimising the IL in such away that reverse-engineering becomes much more difficult Of course if you are writing web services then reverse-engineering is not a problemas clients do not have access to your IL.42 . Can I write IL programs directly? Yes. Peter Drayton posted this simple example to the DOTNET mailing list: .assembly MyAssembly {} .class MyApp { .method static void Main() { .entrypoint ldstr "Hello, IL!" call void System.Console::WriteLine(class System.Object) ret } }Just put this into a file called hello.il, and then run ilasm hello.il. An exe assembly willbe generated.43 . Can I do things in IL that I cant do in C#? Yes. A couple of simple examples are that you can throw exceptions that are notderived from System.Exception, and you can have non-zero-based arrays.44 . Does .NET replace COM? This subject causes a lot of controversy, as youll see if you read the mailing listarchives. Take a look at the following two threads:http://discuss.develop.com/archives/wa.exe?A2=ind0007&L=DOTNET&D=0&P=68241http://discuss.develop.com/archives/wa.exe?A2=ind0007&L=DOTNET&P=R60761The bottom line is that .NET has its own mechanisms for type interaction, and theydont use COM. No IUnknown, no IDL, no typelibs, no registry-based activation. Thisis mostly good, as a lot of COM was ugly. Generally speaking, .NET allows you topackage and use components in a similar way to COM, but makes the whole thing abit easier.45 . Is DCOM dead? Pretty much, for .NET developers. The .NET Framework has a new remotingmodel which is not based on DCOM. DCOM was pretty much dead anyway, oncefirewalls became widespread and Microsoft got SOAP fever. Of course DCOM will still
    • be used in interop scenarios.46 . Is COM+ dead? Not immediately. The approach for .NET 1.0 was to provide access to theexisting COM+ services (through an interop layer) rather than replace the serviceswith native .NET ones. Various tools and attributes were provided to make this aspainless as possible. Over time it is expected that interop will become more seamless- this may mean that some services become a core part of the CLR, and/or it maymean that some services will be rewritten as managed code which runs on top of theCLR.For more on this topic, search for postings by Joe Long in the archives - Joe is the MSgroup manager for COM+. Start with this message:http://discuss.develop.com/archives/wa.exe?A2=ind0007&L=DOTNET&P=R6837047 . Can I use COM components from .NET programs? Yes. COM components are accessed from the .NET runtime via a RuntimeCallable Wrapper (RCW). This wrapper turns the COM interfaces exposed by the COMcomponent into .NET-compatible interfaces. For oleautomation interfaces, the RCWcan be generated automatically from a type library. For non-oleautomation interfaces,it may be necessary to develop a custom RCW which manually maps the typesexposed by the COM interface to .NET-compatible types.48 . Can I use .NET components from COM programs? Yes. .NET components are accessed from COM via a COM Callable Wrapper(CCW). This is similar to a RCW (see previous question), but works in the oppositedirection. Again, if the wrapper cannot be automatically generated by the .NETdevelopment tools, or if the automatic behaviour is not desirable, a custom CCW canbe developed. Also, for COM to see the .NET component, the .NET component mustbe registered in the registry.49 . Is ATL redundant in the .NET world? Yes. ATL will continue to be valuable for writing COM components for some time,but it has no place in the .NET world.50 . How do I spawn a thread? Create an instance of a System.Threading.Thread object, passing it an instanceof a ThreadStart delegate that will be executed on the new thread. For example: class MyThread { public MyThread( string initData ) { m_data = initData; m_thread = new Thread( new ThreadStart(ThreadMain) ); m_thread.Start(); } // ThreadMain() is executed on the new thread. private void ThreadMain() { Console.WriteLine( m_data ); } public void WaitUntilFinished()
    • { m_thread.Join(); } private Thread m_thread; private string m_data; }In this case creating an instance of the MyThread class is sufficient to spawn thethread and execute the MyThread.ThreadMain() method: MyThread t = new MyThread( "Hello, world." ); t.WaitUntilFinished();51 . How do I stop a thread? There are several options. First, you can use your own communicationmechanism to tell the ThreadStart method to finish. Alternatively the Thread class hasin-built support for instructing the thread to stop. The two principle methods areThread.Interrupt() and Thread.Abort(). The former will cause aThreadInterruptedException to be thrown on the thread when it next goes into aWaitJoinSleep state. In other words, Thread.Interrupt is a polite way of asking thethread to stop when it is no longer doing any useful work. In contrast, Thread.Abort()throws a ThreadAbortException regardless of what the thread is doing. Furthermore,the ThreadAbortException cannot normally be caught (though the ThreadStarts finallymethod will be executed). Thread.Abort() is a heavy-handed mechanism which shouldnot normally be required.52 . How do I use the thread pool? By passing an instance of a WaitCallback delegate to theThreadPool.QueueUserWorkItem() method class CApp { static void Main() { string s = "Hello, World"; ThreadPool.QueueUserWorkItem( new WaitCallback( DoWork ), s ); Thread.Sleep( 1000 ); // Give time for work item to be executed } // DoWork is executed on a thread from the thread pool. static void DoWork( object state ) { Console.WriteLine( state ); } }53 . How do I know when my thread pool work item has completed? There is no way to query the thread pool for this information. You must put codeinto the WaitCallback method to signal that it has completed. Events are useful forthis.54 . Should I use ReaderWriterLock instead of Monitor.Enter/Exit? Maybe, but be careful. ReaderWriterLock is used to allow multiple threads toread from a data source, while still granting exclusive access to a single writer thread.
    • This makes sense for data access that is mostly read-only, but there are somecaveats. First, ReaderWriterLock is relatively poor performing compared toMonitor.Enter/Exit, which offsets some of the benefits. Second, you need to be verysure that the data structures you are accessing fully support multithreaded readaccess. Finally, there is apparently a bug in the v1.1 ReaderWriterLock that can causestarvation for writers when there are a large number of readers.Ian Griffiths has some interesting discussion on ReaderWriterLock here and here.55 . Tracing . Is there built-in support for tracing/logging? Yes, in the System.Diagnostics namespace. There are two main classes that dealwith tracing - Debug and Trace. They both work in a similar way - the difference isthat tracing from the Debug class only works in builds that have the DEBUG symboldefined, whereas tracing from the Trace class only works in builds that have theTRACE symbol defined. Typically this means that you should useSystem.Diagnostics.Trace.WriteLine for tracing that you want to work in debug andrelease builds, and System.Diagnostics.Debug.WriteLine for tracing that you want towork only in debug builds.56 . Can I redirect tracing to a file? Yes. The Debug and Trace classes both have a Listeners property, which is acollection of sinks that receive the tracing that you send via Debug.WriteLine andTrace.WriteLine respectively. By default the Listeners collection contains a single sink,which is an instance of the DefaultTraceListener class. This sends output to the Win32OutputDebugString() function and also the System.Diagnostics.Debugger.Log()method. This is useful when debugging, but if youre trying to trace a problem at acustomer site, redirecting the output to a file is more appropriate. Fortunately, theTextWriterTraceListener class is provided for this purpose.Heres how to use the TextWriterTraceListener class to redirect Trace output to a file: Trace.Listeners.Clear(); FileStream fs = new FileStream( @"c:log.txt", FileMode.Create, FileAccess.Write ); Trace.Listeners.Add( new TextWriterTraceListener( fs ) ); Trace.WriteLine( @"This will be writen to c:log.txt!" ); Trace.Flush();Note the use of Trace.Listeners.Clear() to remove the default listener. If you dont dothis, the output will go to the file and OutputDebugString(). Typically this is not whatyou want, because OutputDebugString() imposes a big performance hit.57 . Can I customise the trace output? Yes. You can write your own TraceListener-derived class, and direct all outputthrough it. Heres a simple example, which derives from TextWriterTraceListener (andtherefore has in-built support for writing to files, as shown above) and adds timinginformation and the thread ID for each trace line: class MyListener : TextWriterTraceListener { public MyListener( Stream s ) : base(s) { } public override void WriteLine( string s ) { Writer.WriteLine( "{0:D8} [{1:D4}] {2}",
    • Environment.TickCount - m_startTickCount, AppDomain.GetCurrentThreadId(), s ); } protected int m_startTickCount = Environment.TickCount; }(Note that this implementation is not complete - the TraceListener.Write method isnot overridden for example.)The beauty of this approach is that when an instance of MyListener is added to theTrace.Listeners collection, all calls to Trace.WriteLine() go through MyListener,including calls made by referenced assemblies that know nothing about theMyListener class.58 . Are there any third party logging components available? Log4net is a port of the established log4j Java logging component.59 . Miscellaneous . How does .NET remoting work? .NET remoting involves sending messages along channels. Two of the standardchannels are HTTP and TCP. TCP is intended for LANs only - HTTP can be used forLANs or WANs (internet).Support is provided for multiple message serializarion formats. Examples are SOAP(XML-based) and binary. By default, the HTTP channel uses SOAP (via the .NETruntime Serialization SOAP Formatter), and the TCP channel uses binary (via the .NETruntime Serialization Binary Formatter). But either channel can use either serializationformat.There are a number of styles of remote access:• SingleCall. Each incoming request from a client is serviced by a new object. Theobject is thrown away when the request has finished.• Singleton. All incoming requests from clients are processed by a single serverobject.• Client-activated object. This is the old stateful (D)COM model whereby the clientreceives a reference to the remote object and holds that reference (thus keeping theremote object alive) until it is finished with it.Distributed garbage collection of objects is managed by a system called leased basedlifetime. Each object has a lease time, and when that time expires the object isdisconnected from the .NET runtime remoting infrastructure. Objects have a defaultrenew time - the lease is renewed when a successful call is made from the client tothe object. The client can also explicitly renew the lease.If youre interested in using XML-RPC as an alternative to SOAP, take a look atCharles Cooks XML-RPC.Net.60 . How can I get at the Win32 API from a .NET program? Use P/Invoke. This uses similar technology to COM Interop, but is used to accessstatic DLL entry points instead of COM objects. Here is an example of C# calling theWin32 MessageBox function: using System; using System.Runtime.InteropServices; class MainApp { [DllImport("user32.dll", EntryPoint="MessageBox", SetLastError=true,
    • CharSet=CharSet.Auto)] public static extern int MessageBox(int hWnd, String strMessage, StringstrCaption, uint uiType); public static void Main() { MessageBox( 0, "Hello, this is PInvoke in operation!", ".NET", 0 ); } }Pinvoke.net is a great resource for off-the-shelf P/Invoke signatures.61 . How do I write to the application configuration file at runtime? You dont. See http://www.interact-sw.co.uk/iangblog/2004/11/25/savingconfig.62 . What is the difference between an event and a delegate? An event is just a wrapper for a multicast delegate. Adding a public event to aclass is almost the same as adding a public multicast delegate field. In both cases,subscriber objects can register for notifications, and in both cases the publisher objectcan send notifications to the subscribers. However, a public multicast delegate has theundesirable property that external objects can invoke the delegate, something wednormally want to restrict to the publisher. Hence events - an event adds publicmethods to the containing class to add and remove receivers, but does not make theinvocation mechanism public.See this post by Julien Couvreur for more discussion.63 . What size is a .NET object? Each instance of a reference type has two fields maintained by the runtime - amethod table pointer and a sync block. These are 4 bytes each on a 32-bit system,making a total of 8 bytes per object overhead. Obviously the instance data for thetype must be added to this to get the overall size of the object. So, for example,instances of the following class are 12 bytes each: class MyInt { ... private int x; }However, note that with the current implementation of the CLR there seems to be aminimum object size of 12 bytes, even for classes with no data (e.g. System.Object).Values types have no equivalent overhead.64 . Will my .NET app run on 64-bit Windows? 64-bit (x64) versions of Windows support both 32-bit and 64-bit processes, andcorresponding 32-bit and 64-bit versions of .NET 2.0. (.NET 1.1 is 32-bit only)..NET 1.x apps automatically run as 32-bit processes on 64-bit Windows..NET 2.0 apps can either run as 32-bit processes or as 64-bit processes. The OSdecides which to use based on the PE header of the executable. The flags in the PEheader are controlled via the compiler /platform switch, which allows the target of theapp to be specified as x86, x64 or any cpu. Normally you specify any cpu, andyour app will run as 32-bit on 32-bit Windows and 64-bit on 64-bit Windows. Howeverif you have some 32-bit native code in your app (loaded via COM interop, forexample), you will need to specify x86, which will force 64-bit Windows to load yourapp in a 32-bit process. You can also tweak the 32-bit flag in the PE header using theSDK corflags utility.
    • Some more explanation here:http://blogs.msdn.com/gauravseth/archive/2006/03/07/545104.aspxhttp://blogs.msdn.com/joshwil/archive/2005/04/08/406567.aspxhttp://msdn.microsoft.com/netframework/programming/64bit/gettingstarted/65 . What is reflection? All .NET compilers produce metadata about the types defined in the modulesthey produce. This metadata is packaged along with the module (modules in turn arepackaged together in assemblies), and can be accessed by a mechanism calledreflection. The System.Reflection namespace contains classes that can be used tointerrogate the types for a module/assembly.Using reflection to access .NET metadata is very similar to using ITypeLib/ITypeInfoto access type library data in COM, and it is used for similar purposes - e.g.determining data type sizes for marshaling data across context/process/machineboundaries.Reflection can also be used to dynamically invoke methods (seeSystem.Type.InvokeMember), or even create types dynamically at run-time (seeSystem.Reflection.Emit.TypeBuilder).66 . .NET 2.0 What are the new features of .NET 2.0? Generics, anonymous methods, partial classes, iterators, property visibility(separate visibility for get and set) and static classes.See http://msdn.microsoft.com/msdnmag/issues/04/05/C20/default.aspx for moreinformation about these features.67 . What are the new 2.0 features useful for? Generics are useful for writing efficient type-independent code, particularlywhere the types might include value types. The obvious application is containerclasses, and the .NET 2.0 class library includes a suite of generic container classes inthe System.Collections.Generic namespace. Heres a simple example of a genericcontainer class being used: List<int> myList = new List<int>(); myList.Add( 10 );Anonymous methods reduce the amount of code you have to write when usingdelegates, and are therefore especially useful for GUI programming. Heres anexample AppDomain.CurrentDomain.ProcessExit += delegate { Console.WriteLine("Processending ..."); };Partial classes is a useful feature for separating machine-generated code from hand-written code in the same class, and will therefore be heavily used by developmenttools such as Visual Studio.Iterators reduce the amount of code you need to write to implementIEnumerable/IEnumerator. Heres some sample code: static void Main() { RandomEnumerator re = new RandomEnumerator( 5 ); foreach( double r in re ) Console.WriteLine( r ); Console.Read(); } class RandomEnumerator : IEnumerable<double> {
    • public RandomEnumerator(int size) { m_size = size; } public IEnumerator<double> GetEnumerator() { Random rand = new Random(); for( int i=0; i < m_size; i++ ) yield return rand.NextDouble(); } int m_size = 0; }The use of yield return is rather strange at first sight. It effectively synthethises animplementation of IEnumerator, something we had to do manually in .NET 1.x.68 . Whats the problem with .NET generics? .NET generics work great for container classes. But what about other uses? Well,it turns out that .NET generics have a major limitation - they require the typeparameter to be constrained. For example, you cannot do this: static class Disposer<T> { public static void Dispose(T obj) { obj.Dispose(); } }The C# compiler will refuse to compile this code, as the type T has not beenconstrained, and therefore only supports the methods of System.Object. Dispose isnot a method on System.Object, so the compilation fails. To fix this code, we need toadd a where clause, to reassure the compiler that our type T does indeed have aDispose method static class Disposer<T> where T : IDisposable { public static void Dispose(T obj) { obj.Dispose(); } }The problem is that the requirement for explicit contraints is very limiting. We can useconstraints to say that T implements a particular interface, but we cant dilute that tosimply say that T implements a particular method. Contrast this with C++ templates(for example), where no constraint at all is required - it is assumed (and verified atcompile time) that if the code invokes the Dispose() method on a type, then the typewill support the method.In fact, after writing generic code with interface constraints, we quickly see that wehavent gained much over non-generic interface-based programming. For example,we can easily rewrite the Disposer class without generics: static class Disposer { public static void Dispose( IDisposable obj ) { obj.Dispose(); } }For more on this topic, start by reading the following articles:Bruce Eckel: http://www.mindview.net/WebLog/log-0050Ian Griffiths: http://www.interact-sw.co.uk/iangblog/2004/03/14/genericsCharles Cook: http://www.cookcomputing.com/blog/archives/000425.html69 . Whats new in the .NET 2.0 class library? Here is a selection of new features in the .NET 2.0 class library:• Generic collections in the System.Collections.Generic namespace.
    • • The System.Nullable<T> type. (Note that C# has special syntax for this type, e.g.int? is equivalent to Nullable<int>)• The GZipStream and DeflateStream classes in the System.IO.Compressionnamespace.• The Semaphore class in the System.Threading namespace.• Wrappers for DPAPI in the form of the ProtectedData and ProtectedMemory classesin the System.Security.Cryptography namespace.• The IPC remoting channel in the System.Runtime.Remoting.Channels.Ipcnamespace, for optimised intra-machine communication.and many, many more. See http://msdn2.microsoft.com/en-us/library/t357fb32(en-US,VS.80).aspx for a comprehensive list of changes. Click here to Register in Naukri.com or Monster.com or TimesJobs.com etc.,Prepare For Job Home .Net J2EE PHP Testing Freshers HR Q/A Networking Others Freshers Jobs Experienced Jobs Post Ur Jobs Dot Net - Asp.Net 1 . Describe the role of inetinfo.exe, aspnet_isapi.dll andaspnet_wp.exe in the page loading process. inetinfo.exe is theMicrosoft IIS server running, handling ASP.NET requests among other things.When an ASP.NET request is received (usually a file with .aspx extension), the ISAPI filter aspnet_isapi.dll takes care of it by passing the request tothe actual worker process aspnet_wp.exe. 2 . What’s the difference between Response.Write() andResponse.Output.Write()? Response.Output.Write() allows you to write formatted output. 3 . What methods are fired during the page load? Init() - when the page is instantiated Load() - when the page is loaded into server memory PreRender() - the brief moment before the page is displayed to the user as HTML Unload() - when page finishes loading. 4 . When during the page processing cycle is ViewState
    • available? After the Init() and before the Page_Load(), or OnLoad() for acontrol.5 . What namespace does the Web page belong in the .NETFramework class hierarchy? System.Web.UI.Page6 . Where do you store the information about the user’slocale? System.Web.UI.Page.Culture7 . What’s the difference betweenCodebehind="MyCode.aspx.cs" andSrc="MyCode.aspx.cs"? CodeBehind is relevant to Visual Studio.NET only.8 . What’s a bubbled event? When you have a complex control, like DataGrid, writing anevent processing routine for each object (cell, button, row, etc.) isquite tedious. The controls can bubble up their eventhandlers,allowing the main DataGrid event handler to take care of itsconstituents.9 . Suppose you want a certain ASP.NET function executed onMouseOver for a certain button. Where do you add an eventhandler? Add an OnMouseOver attribute to the button. Example:btnSubmit.Attributes.Add("onmouseover","someClientCodeHere();");10 . What data types do the RangeValidator control support? Integer, String, and Date.11 . Explain the differences between Server-side and Client-side code? Server-side code executes on the server. Client-side codeexecutes in the clients browser.12 . What type of code (server or client) is found in a Code-Behind class? The answer is server-side code since code-behind is executedon the server. However, during the code-behinds execution on theserver, it can render client-side code such as JavaScript to beprocessed in the clients browser. But just to be clear, code-behindexecutes on the server, thus making it server-side code.13 . Should user input data validation occur server-side orclient-side? Why? All user input data validation should occur on the server at aminimum. Additionally, client-side validation can be performedwhere deemed appropriate and feasable to provide a richer, moreresponsive experience for the user.14 . What is the difference between Server.Transfer and
    • Response.Redirect? Why would I choose one over the other? Server.Transfer transfers page processing from one pagedirectly to the next page without making a round-trip back to theclients browser. This provides a faster response with a little lessoverhead on the server. Server.Transfer does not update the clientsurl history list or current url. Response.Redirect is used to redirectthe users browser to another page or site. This performas a tripback to the client where the clients browser is redirected to the newpage. The users browser history list is updated to reflect the newaddress.15 . Can you explain the difference betweenan ADO.NET Dataset and an ADO Recordset? Valid answers are:— A DataSet can represent an entire relational database in memory,complete with tables, relations, and views.— A DataSet is designed to work without any continuing connectionto the original data source.— Data in a DataSet is bulk-loaded, rather than being loaded ondemand.— Theres no concept of cursor types in a DataSet.— DataSets have no current record pointer You can use For Eachloops to move through the data.— You can store many edits in a DataSet, and write them to theoriginal data source in a single operation.— Though the DataSet is universal, other objects in ADO.NET comein different versions for different data sources.16 . What is the Global.asax used for? The Global.asax (including the Global.asax.cs file) is used toimplement application and session level events.17 . What are the Application_Start and Session_Startsubroutines used for? This is where you can set the specific variables for theApplication and Session objects.18 . Can you explain what inheritance is and an example ofwhen you might use it? When you want to inherit (use the functionality of) anotherclass. Example: With a base class named Employee, a Managerclass could be derived from the Employee base class.19 . Whats an assembly? Assemblies are the building blocks of the .NET framework.Overview of assemblies from MSDN20 . Describe the difference between inline and code behind. Inline code written along side the html in a page. Code-behindis code written in a separate file and referenced by the .aspx page.21 . Explain what a diffgram is, and a good use for one?
    • The DiffGram is one of the two XML formats that you can use torender DataSet object contents to XML. A good use is readingdatabase data to an XML file to be sent to a Web Service.22 . Whats MSIL, and why should my developers need anappreciation of it if at all? MSIL is the Microsoft Intermediate Language. All .NETcompatible languages will get converted to MSIL. MSIL also allowsthe .NET Framework to JIT compile the assembly on theinstalled computer.23 . Which method do you invoke on the DataAdapter controlto load your generated dataset with data? The Fill() method.24 . Can you edit data in the Repeater control? No, it just reads the information from its data source.25 . Which template must you provide, in order to displaydata in a Repeater control? ItemTemplate.26 . How can you provide an alternating color scheme in aRepeater control? Use the AlternatingItemTemplate.27 . What property must you set, and what method must youcall in your code, in order to bind the data from a data sourceto the Repeater control? You must set the DataSource property and call the DataBindmethod.28 . What base class do all Web Forms inherit from? The Page class.29 . Name two properties common in every validationcontrol? ControlToValidate property and Text property.30 . Which property on a Combo Box do you set with a columnname, prior to setting the DataSource, to display data in thecombo box? DataTextField property.31 . Which control would you use if you needed to make surethe values in two different controls matched? CompareValidator control.32 . How many classes can a single .NET DLL contain? It can contain many classes.
    • Web Service Questions33 . What is the transport protocol you use to call a Webservice? SOAP (Simple Object Access Protocol) is the preferred protocol.34 . What does WSDL stand for? Web Services Description Language.35 . Where on the Internet would you look for Web services? http://www.uddi.org36 . True or False: To test a Web service you must create aWindows application or Web application to consume thisservice? False, the web service comes with a test page and it providesHTTP-GET method to test.37 . Can you give an example of when it would be appropriateto use a web service as opposed to a non-serviced .NETcomponent Webservice is one of main component in Service OrientedArchitecture. You could use webservices when your clients andservers are running on different networks and also differentplatforms. This provides a loosely coupled system. And also if theclient is behind the firewall it would be easy to use webserivce sinceit runs on port 80 (by default) instead of having some thing else inSOA appsState Management Questions38 . What is ViewState? ViewState allows the state of objects (serializable) to be storedin a hidden field on the page. ViewState is transported to the clientand back to the server, and is not stored on the server or any otherexternal source. ViewState is used the retain the state of server-side objects between postabacks.39 . What is the lifespan for items stored in ViewState? Item stored in ViewState exist for the life of the current page.This includes postbacks (to the same page).40 . What does the "EnableViewState" property do? Whywould I want it on or off? It allows the page to save the users input on a form acrosspostbacks. It saves the server-side values for a given control intoViewState, which is stored as a hidden value on the page beforesending the page to the clients browser. When the page is postedback to the server the server control is recreated with the statestored in viewstate.
    • 41 . What are the different types of Session statemanagement options available with ASP.NET? ASP.NET provides In-Process and Out-of-Process statemanagement. In-Process stores the session in memory on the webserver. This requires the a "sticky-server" (or no load-balancing) sothat the user is always reconnected to the same web server. Out-of-Process Session state management stores data in an external datasource. The external data source may be either a SQL Server or aState Server service. Out-of-Process state management requiresthat all objects stored in session are serializable.42 . Lets say I have an existing application written usingVisual Studio 6 (VB 6, InterDev 6) and this application utilizesWindows 2000 COM+ transaction services. How would youapproach migrating this application to .NET You have to use System.EnterpriseServices namespace and alsoCOMInterop the existing application43 . Can you give an example of what might be best suited toplace in the Application_Start and Session_Start subroutines? In the Application_Start event you could store the data, whichis used throughout the life time of an application for exampleapplication name, where as Session_Start could be used to store theinformation, which is required for that session of the application sayfor example user id or user name.44 . If Im developing an application that must accomodatemultiple security levels though secure login and my ASP.NETweb appplication is spanned across three web-servers (usinground-robbin load balancing) what would be the bestapproach to maintain login-in state for the users? Use the state server or store the state in the database. This canbe easily done through simple setting change in the web.config.<sessionStatemode="InProc"stateConnectionString="tcpip="sqlConnectionString="data source=;userid=sa;password="cookieless="false"timeout="30"/>in the above one instead of mode="InProc", you specifiy stateserveror sqlserver.45 . What are ASP.NET Web Forms? How is this technologydifferent than what is available though ASP (1.0-3.0)? ASP.NET webforms are analogous to Windows Forms which areavailable to most VB developers. A webform is essentially a corecontainer in a Page. An empty webform is nothing but a HTML Formtag(control) running at server and posting form to itself by default,but you could change it to post it to something else. This is acontainer, and you could place the web controls, user controls andHTML Controls in that one and interact with user on a postback
    • basis.46 . How does VB.NET/C# achieve polymorphism? Polymorphism is achieved through virtual, overloaded,overridden methods in C# and VB.NET47 . Describe session handling in a webform, how does itwork and what are the its limitsSometimes it is necessary to carry a particular session data acrosspages.And HTTP is a stateless protocol. In order to maintain state betweenpage calls, we could use cookies, hidden form fields etc. One of themisusing sessions. each sessions are maintain a unique key on theserver andserialize the data on it. Actually it is a hashtable and stores data onkey/valuepair of combination. You could set a session using Session Objectand retrieve the same data/stateby passing the key.//SetSession["abc"] = "Session Value";// Getstring abc = Session["abc"].ToString();The downside of sessions is scalability. Say your application getsmore and more hitsand you though instead of one webserver handling it, have it in awebfarm (multiple webservers working under one domain). You cannot transfer the sessionso easily across multiplewebservers. Reason is like I said, it physically serializes the statedata to webserver hard disk..NET proposes a new way to handle this using a stateserver (actuallya trimmed down sql server)storing the web session data in a factory configured databaseschema or using Database with your ownschema defined to handle the sessions.48 . How would you get ASP.NET running in Apache webservers - why would you even do this? You need to create a CLRHost, which hosts the CLR (ASP.NET)on top of Apache.Since Apache is #1 webserver used by many companies, this wouldallow more number of web site ownersto take advantage of ASP.NET and its richness.49 . Whats MSIL, and why should my developers need anappreciation of it if at all?MSIL is Microsoft Intermediate (Intermediary) Language. It isMicrosofts implementation of CIL (standard recognized
    • by ECMA and ISO) as part of CLI and C# Standardization..NET supports more than 21 language (I think 24 now). Theycompile to IL first and then this IL would get JITted to Nativecode at runtime. Learning IL is advantageous in many terms. Theimportant one is sometimes you need to optimize yourcode, so you could disassemble your compile assembly usingILDASM and tweak your code and re assemble it using ILASM.50 . In what order do the events of an ASPX page execute. Asa developer is it important to undertsand these events? This is the order of Page eventsi. Page_Initii.Page_LoadViewStateiii. Page_LoadPostDataiv. Page_Loadv. Page_RaisePostDataChangedvi. Page_RaisePostBackEventvii. Page_PreRenderviii. Page_SaveViewStateix. Page_Renderx. Page_Disposexii. Page_Error (this is caused whenever there is an exception at thepage level).Out of all the Page_Load is the one where your code gets loaded andyour magic should be written. page_initoccurs only once, i.e. when the page is initially created.As a developer you need to know these, becuase your developmentactivity is coding for these only.51 . Which method do you invoke on the DataAdapter controlto load your generated dataset with data? Fill()52 . Can you edit data in the Repeater control? No. Only DataList and DataGrid provide you editing capabilities.53 . What method do you use to explicitly kill a user ssession? Session.Abandon54 . How do you turn off cookies for one page in your site? Actually I never did this. But there should be a way to do this.May be need towrite your own code to do this using Response.Cookies collectionand HTTPCookie class andalso SessionStateMode. Or there may be some simple way to do it.Need to do further research on this.55 . Which two properties are on every validation control? The common properties are:
    • i. IsValid (bool)ii. ControlToValidate (string)iii. ErrorMessage (string)iv. ValidationDisplay (Display)v. Text (string)The common method is:Validate()56 . What tags do you need to add within the asp:datagridtags to bind columns manually? You need to set AutoGenerateColumns Property to false.57 . How do you create a permanent cookie? If you are developing web services and the cookies need to betravelled across multiple requests, thenyou need to have permanent or persistant cookie.In order to do this, you have to set the your webserivceCookieContainer to a newly created CookieContainer, and theits cookie to a session value and then store the cookie(s) into theService CookieCollection from that cookie containerif something is there othere wise add cookie to the container.58 . What tag do you use to add a hyperlink column to theDataGrid? HyperLinkColumn59 . What is the standard you use to wrap up a call to a Webservice SOAP.60 . Which method do you use to redirect the user to anotherpage without performing a round trip to the client? Server.TransferResponse.Redirect also does that but it requires round trip betweenclient and server.61 . What does WSDL stand for? Web Services Description Language.62 . True or False: A Web service can only be written in .NET False.63 . What property do you have to set to tell the grid whichpage to go to when using the Pager object? CurrentPageIndex. You need to set this one with theDataGridPageChangedEventArgs NewPageIndex.64 . Which control would you use if you needed to make surethe values in two different controls matched? Use CompareValidator65 . True or False: To test a Web service you must create awindows application or Web application to consume thisservice?
    • False. The webservice comes with a test page and it providesHTTP-GET method to test.And if the web service turned off HTTP-GET for security purposesthen you need to createa web application or windows app as a client to this to test.66 . How many classes can a single .NET DLL contain? many is correct. Yes an assembly can contain one or moreclasses and an assembly canbe contained in one dll or could spread across multiple dlls. too. TakeSystem.dll, it iscollections of so many classes.67 . Why would you use an array vs linked-list ? Linked List:? They allow a new element to be inserted or deleted at any positionin a constant number of operations (changing some references)O(1).? Easy to delete a node (as it only has to rearrange the links to thedifferent nodes)., O(1).? To find the nth node, will need to recurse through the list till itfinds [linked lists allow only sequential access to elements. ], O(n)Array? Insertion or deletion of element at any position require a linear(O(n)) number of operations.? Poor at deleting nodes (or elements) as it cannot remove one nodewithout individually shifting all the elements up the list by one.,O(n)? Poor at inserting as an array will eventually either fill up or need tobe resized, an expensive operation that may not even be possible ifmemory is fragmented. Similarly, an array from which manyelements are removed may become wastefully empty or need to bemade smaller, O(n)? easy to find the nth element in the array by directly referencingthem by their position in the array.[ arrays allow random access ] ,O(1) Click here to Register in Naukri.com or Monster.com or TimesJobs.com etc.,Prepare For JobHome .Net J2EE PHP Testing Freshers HRQ/A Networking Others Freshers Jobs Experienced Jobs Post Ur Jobs
    • Dot Net - Asp.Net - Basic I1 . What is ASP.NET? ASP.NET is a programming framework built on the common language runtime that canbe used on a server to build powerful Web applications.2 . Why does my ASP.NET file have multiple tag with runat=server? This means that ASP.Net is not properly registered with IIS..Net framework provides an Administration utility that manages the installation anduninstallation of multiple versions of ASP.NET on a single machine. You can find the file inC:WINNTMicrosoft.NETFrameworkv**aspnet_regiis.exeuse the command: aspnet_regiis.exe -u ---> to uninstall current asp.net version.use the command: aspnet_regiis.exe -i ---> to install current asp.net version. For Windows Server 2003, you must use aspnet_regiis -i -enableThis is because of the "Web Service Extensions" feature in IIS 6 (if you install VS.NET or the framework without IIS installed, and then go back in andinstall IIS afterwards, you have to re-register so that ASP.NET hooks into IIS properly."3 . How to find out what version of ASP.NET I am using on my machine? VB.NETResponse.Write(System.Environment.Version.ToString() ) C#Response.Write(System.Environment.Version.ToString() );4 . Is it possible to pass a querystring from an .asp page to aspx page? Yes you can pass querystring from .asp to ASP.NET page .asp<%response.redirect "webform1.aspx?id=11"%> .aspxVB.NETResponse.Write (Request("id").ToString ()) C#Response.Write (Request["id"].ToString ());5 . How to comment out ASP.NET Tags? <%--<asp:Label id="Label1" style="Z-INDEX: 101; LEFT: 8px; POSITION: absolute;TOP: 48px" runat="server">Label</asp:Label>--%>6 . What is a ViewState?
    • In classic ASP, when a form is submitted the form values are cleared. In some cases theform is submitted with huge information. In such cases if the server comes back with error,one has to re-enter correct information in the form. But submitting clears up all form values.This happens as the site does not maintain any state (ViewState). In ASP .NET, when the form is submitted the form reappears in the browser with allform values. This is because ASP .NET maintains your ViewState. ViewState is a statemanagement technique built in ASP.NET. Its purpose is to keep the state of controls duringsubsequent postbacks by the same user. The ViewState indicates the status of the pagewhen submitted to the server. The status is defined through a hidden field placed on eachpage with a <form runat="server"> control.<input type="hidden" name="__VIEWSTATE"value="dDwyNTA3OTU0NDM7Oz7t5TntzkOUeB0QVV6FT2hvQwtpPw==" /> If you want to NOT maintain the ViewState, include the directive <%@ PageEnableViewState="false"%> at the top of an .aspx page If you do not want to maintainViewstate for any control add the attribute EnableViewState="false" to any control. For moredetails refer The ASP.NET View State7 . Where can I get the details on Migration of existing projects using varioustechnologies to ASP.NET? Microsoft has designed Migration Assistants to help us convert existing pages andapplications to ASP.NET. It does not make the conversion process completely automatic,but it will speed up project by automating some of the steps required for migration.Below are the Code Migration Assistants• ASP to ASP.NET Migration Assistant• PHP to ASP.NET Migration Assistant• JSP to ASP.NET Migration Assistant Refer Migrating to ASP.Net8 . What is the equivalent of date() and time() in ASP.NET? VB.NETSystem.DateTime.Now.ToShortDateString()System.DateTime.Now.ToShortTimeString() C#System.DateTime.Now.ToShortDateString();System.DateTime.Now.ToShortTimeString();9 . How to prevent a button from validating its form? Set the CauseValidation property of the button control to False10 . How to get the IP address of the host accessing my site? VB.NETResponse.Write (Request.UserHostAddress.ToString ())
    • C#Response.Write (Request.UserHostAddress.ToString ());11 . How to access the Parameters passed in via the URL? Call the Request.QueryStringmethod passing in the key. The method will return theparameter value associated with that key. VB.NETRequest.QueryString("id") C#Request.QueryString["id"];12 . How to display a Wait page while a query is running? Refer Asynchronous Wait State Pattern in ASP.NET13 . How to implement Form based Authentication in ASP.NET application? For• VB.NET• C#14 . How to catch the 404 error in my web application and provide more usefulinformation? In the global.asax Application_error Event write the following code VB.NETDim ex As Exception = Server.GetLastError().GetBaseException()If TypeOf ex Is System.IO.FileNotFoundException Thenyour codeResponse.Redirect("err404.aspx")Elseyour codeEnd If C#Exception ex = Server.GetLastError().GetBaseException();if (ex.GetType() == typeof(System.IO.FileNotFoundException)){//your codeResponse.Redirect ("err404.aspx");}else{//your code
    • }15 . Is there a method similar to Response.Redirect that will send variables to thedestination page other than using a query string or the post method? Server.Transfer preserves the current page context, so that in the target page youcan extract values and such. However, it can have side effects; because Server.Transferdoesnt go through the browser, the browser doesnt update its history and if the userclicks Back, they go to the page previous to the source page. Another way to pass values is to use something like a LinkButton. It posts back to thesource page, where you can get the values you need, put them in Session, and then useResponse.Redirect to transfer to the target page. (This does bounce off the browser.) Inthe target page you can read the Session values as required. Refer to Passing Values Between Web Forms Pages for more information.16 . What are the differences between HTML versus Server Control? Refer• ASP.NET Server Controls Recommendations• Introduction to ASP.NET Server Controls17 . How can I change the action of a form through code? You cant change it. The action attribute is owned by ASP.NET. Handle Events andTransfer. For work around refer to Paul Wilsons Multiple Forms and Non-PostBack Forms -Solution18 . Is there any control that allows user to select a time from a clock - in otherwords is there a clock control? Peter Blum has developed some controls. Check out Peters Date Package:TimeOfDayTextBox and DurationTextBox Controls19 . How to Compare time? VB.NETDim t1 As String = DateTime.Parse("3:30 PM").ToString("t")Dim t2 As String = DateTime.Now.ToString("t")If DateTime.Compare(DateTime.Parse(t1), DateTime.Parse(t2)) < 0 ThenResponse.Write(t1.ToString() & " is < than " & t2.ToString())ElseResponse.Write(t1.ToString() & " is > than " & t2.ToString())End If C#string t1 = DateTime.Parse("3:30 PM").ToString("t");string t2 = DateTime.Now.ToString("t");if (DateTime.Compare(DateTime.Parse (t1), DateTime.Parse (t2)) < 0 ){
    • Response.Write(t1.ToString() + " is < than " + t2.ToString());}else{Response.Write(t1.ToString() + " is > than " + t2.ToString());}20 . How To work with TimeSpan Class? VB.NETDim adate As DateTime = DateTime.Parse("06/24/2003")Dim bdate As DateTime = DateTime.Parse("06/28/2003")Dim ts As New TimeSpan(bdate.Ticks - adate.Ticks)Response.Write(ts.TotalDays & "<br>")Response.Write(ts.TotalHours & ":" & ts.TotalMinutes & ":" & ts.TotalSeconds & ":" &ts.TotalMilliseconds) C#DateTime adate = DateTime.Parse("06/24/2003");DateTime bdate = DateTime.Parse("06/28/2003");TimeSpan ts = new TimeSpan (bdate.Ticks - adate.Ticks);Response.Write(ts.TotalDays.ToString () + "<br>");Response.Write(ts.TotalHours.ToString() + ":" + ts.TotalMinutes.ToString() + ":" +ts.TotalSeconds.ToString() + ":" + ts.TotalMilliseconds.ToString() );21 . Where can I get information on Cookies in ASP.NET? Refer Mike Popes article Basics of Cookies in ASP.NET22 . Does ASP.Net still recognize the global.asa file? ASP.Net does not recognize the standard ASP global.asa file. Instead it uses a filenamed global.asax with the same - plus additional - functionality.23 . How should I destroy my objects in ASP.Net? ASP.Net actually has very solid internal garbage collection. So this is not an issue as itwas in previous versions of ActiveServer Pages.Link to more information: <gcConcurrent> Element24 . Are there resources online with tips on ASP to ASP.Net conversions? Microsoft has deisnged The ASP to ASP.NET Migration Assistant help us convert ASPpages and applications to ASP.NET. It does not make the conversion process completelyautomatic, but it will speed up project by automating some of the steps required formigration. The following Code Migration Assistants are discussed in the link below.• ASP to ASP.NET Migration Assistant• PHP to ASP.NET Migration Assistant• JSP to ASP.NET Migration Assistant Refer Migrating to ASP.Net
    • Also refer:• Microsofts ASP to ASP.NET Code Migration Assistant• John Petersons article Microsofts ASP to ASP.NET Migration Assistant• Paolo Cavones article From ASP to ASP.NET... Painlessly!25 . How do I publish my ASP.NET application to my ISPs web server? Your ISP must first create an IIS application and apply the Front Page ServerExtensions to it. Then in Visual Studio .NET, select the "Project | Copy Project" menu. Thenenter the URL and select the FrontPage web access method. The "Copy Project" featurecopies all of the necessary files to your ISPs machine for your ASP.NET application to run. You can also FTP your files to your ISP web server. But you must know which files toupload. For more details refer PRB: Remote ASP.NET Projects Require IIS on the ClientComputer or FrontPage Server Extensions on the Server Computer26 . Why do i get error message "Could not load type" whenever I browse to myASP.NET web site? Your code-behind files for either your .aspx or the global.aspx page have not beencomplied. Use Visual Studio .NETs "Build | Build Solution" menu, or run the command linecompiler. For more details refer PRB: "Could not load type" error message when you browse to.aspx page27 . Will the WebMatrix SqlDataSourceControl work with a MySQL connection? SqlDataSourceControl lets you connect and work with MS SQL DB, whileAccessDataSourceControl do the same thing but for MS Access DB. ThereforeSqlDataSourceControl cant help you in your MySql connectivity .For Connectivity with MySql refer Accessing MySQL Database with ASP.NET28 . Can I combine classic ASP and ASP.NET pages? No.ASP pages can run in the same site as ASP.NET pages, but you cant mix in a page. AlsoASP and ASP.NET wont share their session.29 . What is the difference between src and Code-Behind? Src attribute means you deploy the source code files and everything is compiled JIT(just-in-time) as needed. Many people prefer this since they dont have to manually worryabout compiling and messing with dlls -- it just works. Of course, the source is now on theserver, for anyone with access to the server -- but not just anyone on the web. CodeBehind attribute doesnt really "do" anything, its just a helper for VS.NET toassociate the code file with the aspx file. This is necessary since VS.NET automates thepre-compiling that is harder by hand, and therefore the Src attribute is also gone. Nowthere is only a dll to deploy, no source, so it is certainly better protected, although itsalways decompilable even then.30 . How can I get the value of input box with type hidden in code-behind? You can set the runat= server for the hidden control and you can useControlName.Value to get its value in CodeBehind file
    • 31 . I have created a .NET user control page (.ascx) but I cannot compile and runit. User control (ascx) cant be run on it own, but you can drag it onto any web page(aspx) and then run it.32 . What is a .resx file? The .resx resource file format consists of XML entries, which specify objects andstrings inside XML tags. This is useful for localization. For more details refer Resources in.resx files33 . Is it possible to use a style sheet class directly on a control instead of usinginline or page-level formatting ? Every WebControl derived control has a CssClass property which allows you to set itsformat to a style sheet.34 . Can I recieve both HTML markup for page and code in the ASP.NET webpages source code portion in the Web browser? No. The Web browser recieves only HTML markup.No source code or web control syntax is passed back to the web browser.35 . Why cant I put where at the top of an ASPX file and write my server-sidescripts in C ? The parsers ASP.NET uses to extract code from ASPX files understand C#, VisualBasic.NET, and JScript.NET. You can write server-side scripts in any language supported bya .NET compiler.36 . ASP pages that worked pefectly on Windows 2000 Server and IIS 5.0 do notwork on Windows 2003 Server with IIS 6.0. ASP.NET pages work fine. Why? Start -> Settings -> Control Panel -> Administrative Tools -> and double clicking IISManager.Go to the Web Service Extensions tab, click Active Server Pages, then press the "Allow"button on the left37 . Why do I get error message "Error creating assembly manifest: Error readingkey file key.snk -- The system cannot find the file specified"? Check the location of the key.snk file relative to the assembly file. Provide an explicitpath or a relative path.<Assembly: AssemblyKeyFileAttribute("Drive:key.snk")>38 . How to get URL without querystring? VB.NETDim stringUri As String = "http://www.syncfusion.com/?id=1&auid=16"Dim weburi As Uri = New Uri(stringUri)Dim query As String = weburi.QueryDim weburl As String = stringUri.Substring(0, stringUri.Length - query.Length)Response.Write(weburl) C#string stringUri = "http://www.syncfusion.com/?id=1&auid=16";Uri weburi = new Uri(stringUri);string query = weburi.Query;
    • string weburl = stringUri.Substring(0, stringUri.Length - query.Length);Response.Write (weburl);39 . What is the best way to output only time and not Date? Use DateTime as follows VB.NETResponse.Write(DateTime.Now.ToString("hh:mm:ss")) C#Response.Write(DateTime.Now.ToString("hh:mm:ss"));40 . Do I have to compile code if I am changing the content of my aspx.cs file? Yes if you have used Codebehind="my.aspx.cs".Not if you used src="my.aspx.cs" in your page declaration.41 . How to grab the referring URL? VB.NETResponse.Write ( Request.UrlReferrer.ToString()) C#Response.Write ( Request.UrlReferrer.ToString());42 . My ASP code gives an error "Compiler Error Message: BC30289: Statementcannot appear within a method body. End of method assumed" when changed to.aspx? Use a <script runat=server> block instead of the <% %> syntax to define Subs.Make sure you have proper events associated with the code and have start and end ofprocedure or function wirtten properly.43 . How can I save images ? You need a stream to read the response, WebResponse.GetResponseStream(), and astream to write it to the hard drive. FileStream should do the trick. Youll have to write tothe filestream what you read from the response stream.44 . How can I logout when using FormsAuthentication?FormsAuthentication.SignOut()45 . Why do I get a blank page when I use Server.Transfer("page1.htm") totransfer to a different page? Server.Transfer only works with .aspx pagesYou cant use Transfer method with HTML pages46 . How to detect the Users culture? VB.NETDim sLang As StringsLang = Request.UserLanguages(0)Response.Write(sLang)
    • C#string sLang ;sLang = Request.UserLanguages[0];Response.Write (sLang);47 . What is the difference between CurrentCulture property and theCurrentUICulture property?• CurrentCulture property : affects how the .NET Framework handles dates, currencies,sorting and formatting issues• CurrentUICulture property : determines which satellite assembly is used when loadingresources48 . Can I read the hard disk serial # of the client computer using ASP.NET? No. Such information is not passed to the server with a http request.49 . What is xxx(src As Object, e As EventArgs)? xxx is an event handlersrc is the object that fires the evente is an event argument object that contains more information about the eventAn event handler is used when one object wants to be notified when an event happens inanother object50 . What is the difference between Absolute vs Relative URLs? Absolute /Fully Qualified URLs:• Contain all information necessary for the browser(or other client program) to locate the resource named in the URL o This includes protocol moniker used( i.e http://, ftp://..etc..), Servers Domain name or IP address and the file path o Absolute URL looks as http://localhost/megasolutions/page1.aspx Relative URLs:• Only provide information necessary to locate a resource relative to the current document(document relative) or current server or domain(root relative) o Document relative URL - page1.aspx o Root Relative URL - /megasolutions/Admin/pagelog.aspx Click here to Register in Naukri.com or Monster.com or TimesJobs.com etc.,Prepare For Job
    • Home .Net J2EE PHP Testing Freshers HR Q/A Networking Others Freshers Jobs Experienced Jobs Post Ur Jobs Dot Net - Asp.Net - Basic II1 . What is the difference between URL and URI? A URL is the address of some resource on the Web, which means that normally youtype the address into a browser and you get something back. There are other type ofresources than Web pages, but thats the easiest conceptually. The browser goes outsomewhere on the Internet and accesses something. A URI is just a unique string that uniquely identifies something, commonly anamespace. Sometimes they look like a URL that you could type into the address bar ofyour Web browser, but it doesnt have to point to any physical resource on the Web. It isjust a unique set of characters, that, in fact, dont even have to be unique. URI is the more generic term, and a URL is a particular type of URI in that a URL hasto uniquely identify some resource on the Web.2 . How to convert milliseconds into time? VB.NETdim ts as TimeSpan = TimeSpan.FromMilliseconds(10000)Response.Write (ts.ToString () ) C#TimeSpan ts = TimeSpan.FromMilliseconds(10000);Response.Write (ts.ToString () );3 . How to include multiple vb/cs files in the source? You can do this using assembly directives.<%@ assembly src="test1.vb" %><%@ assembly src="test2.vb" %>or<%@ assembly src="test1.cs" %><%@ assembly src="test2.cs" %> However, note that each source file will be compiled individually into its own assembly,so they cannot have dependencies on each other.4 . How to convert a string to Proper Case? Use the namespace System.GlobalizationVB.NETDim myString As String = "syncFusion deVeloPer sUppOrt" Creates a TextInfo based on the "en-US" culture.Dim TI As TextInfo = New CultureInfo("en-US", False).TextInfoResponse.Write(TI.ToTitleCase(myString))
    • C#string myString = "syncFusion deVeloPer sUppOrt";// Creates a TextInfo based on the "en-US" culture.TextInfo TI = new CultureInfo("en-US",false).TextInfo;Response.Write (TI.ToTitleCase( myString )); For more details refer TextInfo.ToTitleCase()5 . How can I ensure that application-level variables are not updated by morethan one user simultaneously? Use the HttpApplicationStates Lock and UnLock methods. For more details refer : MSDN: Application State6 . Why do I get the error message "System.InvalidOperationException: It isinvalid to show a modal dialog or form when the application is not running inUserInteractive mode. Specify the ServiceNotification or DefaultDesktopOnlystyle to display a ...."? You cant use MsgBox or MessageBox.Show in ASP.NET WebForm. You maybe use:VB.NETResponse.Write("<script>alert(Hello);</script>") C#Response.Write("<script>alert(Hello);</script>") ;7 . How to validate that a string is a valid date? VB.NETDim blnValid As Boolean = FalseTryDateTime.Parse(MyString)blnValid = TrueCatchblnValid = FalseEnd Try C#bool blnValid=false;try{DateTime.Parse(MyString);blnValid=true;}
    • catch{blnValid=false;}8 . Are namespaces and Class names Case Sensitive? Namespaces and Class names are case Sensitive. Namespaces imported using the @Import Directive will cause an error if the correct case is not used.9 . How to convert string to a DateTime and compare it with another DateTime? VB.NETDim blntimeIsOk As Boolean = DateTime.Parse("15:00") < DateTime.Parse("08:00")Response.Write(blntimeIsOk) C#bool blntimeIsOk = (DateTime.Parse("15:00") < DateTime.Parse("08:00"));Response.Write (blntimeIsOk);10 . How to get the url of page dynamically? Use Request.Url property11 . How to convert user input in dMy format to Mdy? VB.NETDim dt As DateTime = DateTime.ParseExact("0299", New String() {"My", "M/y"}, Nothing,System.Globalization.DateTimeStyles.None) C#DateTime dt = DateTime.ParseExact("0299", new string[] {"My","M/y"},null,System.Globalization.DateTimeStyles.None); For more details refer DateTime.ParseExact12 . When the User is prompted a File Download dialogbox, if the user selects"Save" then the "Save as" dialog box is displayed. Is there any way for me toretrieve the filename and directory path specified by the user on the FileDownload dialog box? Clients do not report information back about where the user selects to save thecontent, so there isnt an easy way to do this. Instead, you would need to ask the userbefore using the content-disposition for a file path, and then you could specify the filenameparameter for the content-disposition header. Still, the user is free to change that pathwhen actually downloading.13 . How to hide or show Controls in server side code? In any appropriate event writeVB.NETTextBox1.Visible =not TextBox1.Visible
    • C#TextBox1.Visible =!TextBox1.Visible ;14 . How to check if the user is using a secure or non secure connection? The Request Object defines a Property called IsSecureConnection, that will indicatewhether http:// or https:// has been used.15 . Is it possible to write code in many languages in one ASP.NET project? You cannot write the code-behind files in different languages in the same project, butyou can write the aspx pages and ascx controls in different languages.16 . What is the difference between Response.Redirect() and Server.Transfer(). Response.Redirect• Tranfers the page control to the other page, in other words it sends the request to the other page.• Causes the client to navigate to the page you are redirecting to. In http terms it sends a 302 response to the client, and the client goes where its told. Server.Transfer• Only transfers the execution to another page and during this you will see the URL of the old page since only execution is transfered to new page and not control.• Occurs entirely on the server, no action is needed by the client Sometimes for performance reasons, the server method is more desirable17 . How to get the hostname or IP address of the server? You can use either of these:• HttpContext.Current.Server.MachineName• HttpContext.Current.Request.ServerVariables["LOCAL_ADDR"] The first one should return the name of the machine, the second returns the local ipaddress.Note that name of the machine could be different than host, since your site could be usinghost headers18 . What is the meaning of validateRequest=true in .net framework1.1? The value of validateRequest is set to true by default, which means that theframework will automatically deny submission of the < and > characters.19 . What is the different between and ? The <%# %> is used for databinding where as <%= %> is used to output the result ofan expression. The expression inside <%# %> will be executed only when you call thepages or controls DataBind method. The expression inside <%= %> will be executed anddisplayed as and when it appears in the page.20 . What permissions do ASP.NET applications posses by default?
    • By default ASP.NET Web applications run as ASP.NET user. This user has limitedpermissions equivalent to the User Group.21 . How can I specify the relative path for a file? Suppose you have following file hierarchy:default.aspxAdmin/login.aspxMisc/testpage.aspxAnd you are on the login.aspx and want your user to navigate to the default.aspx (ortestpage.aspx) file. Then you can use• Response.Redirect ("../default.aspx")• Response.Redirect ("../Misc/testpage.aspx")22 . How can I specify the "upload a file" input textbox in a form to be read onlyso that the user can click on the browse button and pick a file but they cannottype anything into the textbox next to the browse button. <input id="File1" type="file" contenteditable=false />23 . How to change the Page Title dynamically?<TITLE id="Title1" runat =server ></TITLE> VB.NETDeclareProtected WithEvents Title1 As System.Web.UI.HtmlControls.HtmlGenericControlIn Page_LoadTitle1.InnerText ="Page 1" C#//Declareprotected System.Web.UI.HtmlControls.HtmlGenericControl Title1 ;//In Page_LoadTitle1.InnerText ="Page 1" ;24 . Why do I get the error message "Object must implement IConvertible". Howcan I resolve it? The common cause for this error is specifying a control as a SqlParameters Valueinstead of the controls text value.For example, if you write code as below youll get the above error: VB.NETDim nameParameter As SqlParameter = command.Parameters.Add("@name",
    • SqlDbType.NVarChar, 50)nameParameter.Value = txtName C#SqlParameter nameParameter = command.Parameters.Add("@name", SqlDbType.NVarChar,50);nameParameter.Value = txtName ; To resolve it, specify the controls Text property instead of the control itself. VB.NETnameParameter.Value = txtName.Text C#nameParameter.Value =txtName.Text;25 . Why is default.aspx page not opened if i specify http://localhost. I am ableto view this page if i hardcode it as http://localhost/default.aspx? If some other default page comes higher in the list, adjust the default.aspx to be thenumber one entry inside the IIS configuration. If you have multiple websites inside IIS,make sure the configuration is applied on the right website (or on all websites by applyingthe configuration on the server-level using the properties dialog, configure WWW service).26 . Can ASP.NET work on an NT server? No. For more details refer ASP 1.1 version27 . Is it possible to migrate Visual InterDev Design-Time Controls to ASP.NET? Refer INFO: Migrating Visual InterDev Design-Time Controls to ASP.NET28 . How to automatically get the latest version of all the asp.net solution itemsfrom Source Safe when opening the solution? In VS.NET you can go to Tools > Options > Source Control > General and check thecheckbox for Get everything when a solution opens.This retrieves the latest version of all solution items when you open the solution.29 . How to make VS.Net use FlowLayout as the default layout rather than theGridLayout? For VB.NET, go to path C:Program FilesMicrosoft Visual Studio.NETVb7VBWizardsWebFormTemplates1033Change the following line in the existing WebForm1.aspx<body MS_POSITIONING="[!output DEFAULT_HTML_LAYOUT]"> to
    • For C#, go to path C:Program FilesMicrosoft Visual Studio .NET2003VC#VC#WizardsCSharpWebAppWizTemplates1033Change the following line in the existing WebForm1.aspx<body MS_POSITIONING="[!output DEFAULT_HTML_LAYOUT]"> to Note:Before changing any templates its a good idea to make backup copies of themOr rather than above approach you can change the behavior for new files on a per projectbasis in Visual Studio by:1. Right clicking on the project name (Ex: "WebApplication1)" in Solution Explorer, and select "Properties".2. From project properties window, under Common Properties>Designer Defaults>Page Layout change "Grid" to "Flow".30 . Can I use a DataReader to update/insert/delete a record? No. DataReader provides a means of reading a forward-only stream of rows from adatabase.31 . How to format a Telphone number in the xxx-xxx-xxxx format? VB.NETDim Telno As Double = Double.Parse(ds.Tables(0).Rows(0)("TelNo").ToString())Response.Write(Telno.ToString("###-###-####")) C#double Telno= double.Parse(ds.Tables[0].Rows[0]["TelNo"].ToString());Response.Write(Telno.ToString("###-###-####"));32 . Can two different programming languages be mixed in a single ASPX file? No. ASP.NET uses parsers to strip the code from ASPX files and copy it to temporaryfiles containing derived Page classes, and a given parser understands only one language33 . Can I use custom .NET data types in a Web form? Yes. Place the DLL containing the type in the application roots bin directory andASP.NET will automatically load the DLL when the type is referenced. This is also whathappens when you add a custom control from the toolbox to your web form.34 . How can I have a particular Web page in an ASP.NET application whichdisplays its own error page. This can be done by setting the ErroPage attribute of Page Directive or ErrorPage
    • property of Page Class to the desired Custom Error Page<%@Page Language="C#" ErrorPage="specificerropage.htm"%> In web.config<customErrors mode="On" /> Click here to Register in Naukri.com or Monster.com or TimesJobs.com etc.,Prepare For Job Home .Net J2EE PHP Testing Freshers HR Q/A Networking Others Freshers Jobs Experienced Jobs Post Ur Jobs Dot Net - C#.Net 1 . Does C# support multiple-inheritance? No. 2 . Who is a protected class-level variable available to? It is available to any sub-class (a class inheriting this class). 3 . Are private class-level variables inherited? Yes, but they are not accessible. Although they are not visible or accessible via the class interface, they are inherited. 4 . Describe the accessibility modifier “protected internal”. It is available to classes that are within the same assembly and derived from the specified base class. 5 . What’s the top .NET class that everything is derived from? System.Object. 6 . What does the term immutable mean? The data value may not be changed. Note: The variable value may be changed, but the original immutable data value was discarded and a new data value was created in memory. 7 . What’s the difference between System.String and System.Text.StringBuilder classes? System.String is immutable. System.StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed.
    • 8 . What’s the advantage of usingSystem.Text.StringBuilder over System.String? StringBuilder is more efficient in cases where there is a largeamount of string manipulation. Strings are immutable, so eachtime a string is changed, a new instance in memory is created.9 . Can you store multiple data types in System.Array? No.10 . What’s the difference between theSystem.Array.CopyTo() and System.Array.Clone()? The Clone() method returns a new array (a shallow copy)object containing all the elements in the original array. TheCopyTo() method copies the elements into another existingarray. Both perform a shallow copy. A shallow copy means thecontents (each array element) contains references to the sameobject as the elements in the original array. A deep copy (whichneither of these methods performs) would create a new instanceof each elements object, resulting in a different, yet identacleobject.11 . How can you sort the elements of the array indescending order? By calling Sort() and then Reverse() methods.12 . What’s the .NET collection class that allows anelement to be accessed using a unique key? HashTable.13 . Will the finally block get executed if an exception hasnot occurred? Yes.14 . What’s the C# syntax to catch any possible exception? A catch block that catches the exception of typeSystem.Exception. You can also omit the parameter data type inthis case and just write catch {}.15 . Can multiple catch blocks be executed for a single trystatement? No. Once the proper catch block processed, control istransferred to the finally block (if there are any).16 . Explain the three services model commonly know as athree-tier application. Presentation (UI), Business (logic and underlying code) andData (from storage or other sources).Class Questions17 . What is the syntax to inherit from a class in C#?
    • Place a colon and then the name of the base class.Example: class MyNewClass : MyBaseClass18 . Can you prevent your class from being inherited byanother class? Yes. The keyword “sealed” will prevent the class from beinginherited.19 . Can you allow a class to be inherited, but prevent themethod from being over-ridden? Yes. Just leave the class public and make the methodsealed.20 . What’s an abstract class? A class that cannot be instantiated. An abstract class is aclass that must be inherited and have the methods overridden.An abstract class is essentially a blueprint for a class without anyimplementation.21 . When do you absolutely have to declare a class asabstract? 1. When the class itself is inherited from an abstract class,but not all base abstract methods have been overridden. 2. When at least one of the methods in the class isabstract.22 . What is an interface class? Interfaces, like classes, define a set of properties, methods,and events. But unlike classes, interfaces do not provideimplementation. They are implemented by classes, and definedas separate entities from classes.23 . Why can’t you specify the accessibility modifier formethods inside the interface? They all must be public, and are therefore public by default.24 . Can you inherit multiple interfaces? Yes. .NET does support multiple interfaces.25 . What happens if you inherit multiple interfaces andthey have conflicting method names? It’s up to you to implement the method inside your ownclass, so implementation is left entirely up to you. This mightcause a problem on a higher-level scale if similarly namedmethods from different interfaces expect different data, but asfar as compiler cares you’re okay.To Do: Investigate26 . What’s the difference between an interface andabstract class? In an interface class, all methods are abstract - there is noimplementation. In an abstract class some methods can beconcrete. In an interface class, no accessibility modifiers are
    • allowed. An abstract class may have accessibility modifiers.27 . What is the difference between a Struct and a Class? Structs are value-type variables and are thus saved on thestack, additional overhead but faster retrieval. Anotherdifference is that structs cannot inherit.Method and Property Questions28 . What’s the implicit name of the parameter that getspassed into the set method/property of a class? Value. The data type of the value parameter is defined bywhatever data type the property is declared as.29 . What does the keyword “virtual” declare for a methodor property? The method or property can be overridden.30 . How is method overriding different from methodoverloading? When overriding a method, you change the behavior of themethod for the derived class. Overloading a method simplyinvolves having another method with the same name within theclass.31 . Can you declare an override method to be static if theoriginal method is not static? No. The signature of the virtual method must remain thesame. (Note: Only the keyword virtual is changed to keywordoverride)32 . What are the different ways a method can beoverloaded? Different parameter data types, different number ofparameters, different order of parameters.33 . If a base class has a number of overloadedconstructors, and an inheriting class has a number ofoverloaded constructors; can you enforce a call from aninherited constructor to a specific base constructor? Yes, just place a colon, and then keyword base (parameterlist to invoke the appropriate constructor) in the overloadedconstructor definition inside the inherited class.Events and Delegates34 . What’s a delegate? A delegate object encapsulates a reference to a method.35 . What’s a multicast delegate? A delegate that has multiple handlers assigned to it. Each
    • assigned handler (method) is called.36 . Is XML case-sensitive? Yes.37 . What’s the difference between // comments, /* */comments and /// comments? Single-line comments, multi-line comments, and XMLdocumentation comments.38 . How do you generate documentation from the C# filecommented properly with a command-line compiler? Compile it with the /doc switch.Debugging and Testing Questions39 . What debugging tools come with the .NET SDK? 1. CorDBG – command-line debugger. To use CorDbg, youmust compile the original C# file using the /debug switch. 2. DbgCLR – graphic debugger. Visual Studio .NETuses the DbgCLR.40 . What does assert() method do? In debug compilation, assert takes in a Boolean condition asa parameter, and shows the error dialog if the condition is false.The program proceeds without any interruption if the condition istrue.41 . What’s the difference between the Debug class andTrace class? Documentation looks the same. Use Debug class for debugbuilds, use Trace class for both debug and release builds.42 . Why are there five tracing levels inSystem.Diagnostics.TraceSwitcher? The tracing dumps can be quite verbose. For applicationsthat are constantly running you run the risk of overloading themachine and the hard drive. Five levels range from None toVerbose, allowing you to fine-tune the tracing activities.43 . Where is the output of TextWriterTraceListenerredirected? To the Console or a text file depending on the parameterpassed to the constructor.44 . How do you debug an ASP.NET Web application? Attach the aspnet_wp.exe process to the DbgClr debugger.45 . What are three test cases you should go through inunit testing?1. Positive test cases (correct data, correct output).2. Negative test cases (broken or missing data, proper
    • handling).3. Exception test cases (exceptions are thrown and caughtproperly).46 . Can you change the value of a variable whiledebugging a C# application? Yes. If you are debugging via Visual Studio.NET, just go toImmediate window.ADO.NET and Database Questions47 . What is the role of the DataReader class in ADO.NETconnections? It returns a read-only, forward-only rowset from the datasource. A DataReader provides fast access when a forward-onlysequential read is needed.48 . What are advantages and disadvantages of Microsoft-provided data provider classes in ADO.NET? SQLServer.NET data provider is high-speed and robust, butrequires SQL Server license purchased from Microsoft. OLE-DB.NET is universal for accessing other sources, like Oracle, DB2,Microsoft Access and Informix. OLE-DB.NET is a .NET layer ontop of the OLE layer, so it’s not as fastest and efficient asSqlServer.NET.49 . What is the wildcard character in SQL? Let’s say you want to query database with LIKE for allemployees whose name starts with La. The wildcard character is%, the proper query with LIKE would involve ‘La%’.50 . Explain ACID rule of thumb for transactions. A transaction must be:1. Atomic - it is one unit of work and does not dependent onprevious and following transactions.2. Consistent - data is either committed or roll back, no “in-between” case where something has been updated andsomething hasn’t.3. Isolated - no transaction sees the intermediate results ofthe current transaction).4. Durable - the values persist if the data had beencommitted even if the system crashes right after.51 . What connections does Microsoft SQL Server support? Windows Authentication (via Active Directory) and SQLServer authentication (via Microsoft SQL Server username andpassword).52 . Between Windows Authentication and SQL ServerAuthentication, which one is trusted and which one isuntrusted? Windows Authentication is trusted because the username
    • and password are checked with the Active Directory, the SQLServer authentication is untrusted, since SQL Server is the onlyverifier participating in the transaction.53 . What does the Initial Catalog parameter define in theconnection string? The database name to connect to.54 . What is a pre-requisite for connection pooling? Multiple processes must agree that they will share the sameconnection, where every parameter is the same, including thesecurity settings. The connection string must be identical.Assembly Questions55 . How is the DLL Hell problem solved in .NET? Assembly versioning allows the application to specify notonly the library it needs to run (which was available underWin32), but also the version of the assembly.56 . What are the ways to deploy an assembly? An MSI installer, a CAB archive, and XCOPY command.57 . What is a satellite assembly? When you write a multilingual or multi-cultural application in.NET, and want to distribute the core application separately fromthe localized modules, the localized assemblies that modify thecore application are called satellite assemblies.58 . What namespaces are necessary to create a localizedapplication? System.Globalization and System.Resources.59 . What is the smallest unit of execution in .NET? An Assembly.60 . When should you call the garbage collector in .NET? As a good rule, you should not call the garbage collector.However, you could call the garbage collector when you are doneusing a large object (or set of objects) to force the garbagecollector to dispose of those very large objects from memory.However, this is usually not a good practice.61 . How do you convert a value-type to a reference-type? Use Boxing.62 . What happens in memory when you Box and Unbox avalue-type? Boxing converts a value-type to a reference-type, thusstoring the object on the heap. Unboxing converts a reference-type to a value-type, thus storing the value on the stack.