Ce diaporama a bien été signalé.
Le téléchargement de votre SlideShare est en cours. ×

Dotnet basics

Prochain SlideShare
.Net slid
.Net slid
Chargement dans…3

Consultez-les par la suite

1 sur 50
1 sur 50

Plus De Contenu Connexe

Dotnet basics

  1. 1. Dot Net - .Net Basic , Framework and Advanced 1 . What is .NET? .NET is a general-purpose software development platform, similar to Java. At its core is a virtual machine that turns intermediate language (IL) into machine code. High-level language 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 is included, featuring all the functionality one might expect from a contempory development platform - windows GUI development (Windows Forms), database access (ADO.NET), web development (ASP.NET), web services, XML etc See also Microsoft's definition 2 . When was .NET announced? Bill Gates delivered a keynote at Forum 2000, held June 22, 2000, outlining the .NET 'vision'. The July 2000 PDC had a number of sessions on .NET technology, and delegates were given CDs containing a pre-release version of the .NET framework/SDK and Visual Studio.NET. 3 . What versions of .NET are there? The final versions of the 1.0 SDK and runtime were made publicly available around &6pm PST on 15-Jan-2002. At the same time, the final version of Visual Studio.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 officially launched in early November. 4 . What operating systems does the .NET Framework run on? The runtime supports Windows Server 2003, Windows XP, Windows 2000, NT4 SP6a and Windows ME/98. Windows 95 is not supported. Some parts of the framework do not work on all platforms - for example, ASP.NET is only supported on XP and Windows 2000/2003. Windows 98/ME cannot be used for development IIS is not supported on Windows XP Home Edition, and so cannot be used to host ASP.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
  2. 2. 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 don't know what they were thinking. They certainly weren't thinking of people using search tools. It's 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 of the .NET framework - the Common Type System (CTS), metadata, the Virtual Execution Environment (VES) and its use of intermediate language (IL), and the support of multiple programming languages via the Common Language Specification (CLS). The CLI is documented through ECMA - seehttp://msdn.microsoft.com/net/ecma/ for more details. The CLR (Common Language Runtime) is Microsoft's primary implementation of the CLI. Microsoft also have a shared source implementation known as ROTOR, for educational purposes, as well as the .NET Compact Framework for mobile devices. Non-Microsoft CLI implementations 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) is compiled to IL during development. The IL is then converted to machine code at the point where 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. In their "Introduction to C#" whitepaper, Microsoft describe C# as follows: "C# is a simple, modern, object oriented, and type-safe programming language derived 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 you'll see that the statement still works 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 places within .NET, meaning slightly different things. Managed code: The .NET framework provides several core run-time services to the programs that run within it - for example exception handling and security. For these services 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 runtime's garbage
  3. 3. 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 the name suggests, this means that the memory for instances of the class is managed by the garbage collector, but it also means more than that. The class becomes a fully paid-up member of the .NET community with the benefits and restrictions that brings. An example of a benefit is proper interop with classes written in other languages - for example, a managed C++ class can inherit from a VB class. An example of a restriction is that a managed 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 be an application (with a main entry point) or alibrary. An assembly consists of one or more 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 other assemblies. These resources, types and references are described in a block of data called a 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. The identity of a type is the assembly that houses it combined with the type name. This means, for example, that if assembly A exports a type called T, and assembly B exports a type called T, the .NET runtime sees these as two completely different types. Furthermore, don't get confused between assemblies and namespaces - namespaces are merely a hierarchical way of organising type names. To the runtime, type names are type names, regardless of whether namespaces are used to organise the names. It's the assembly plus the typename (regardless of whether the type name belongs to a namespace) that uniquely indentifies a type to the runtime. Assemblies are also important in .NET with respect to security - many of the security restrictions 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. For example, 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 the modules into an assembly using the assembly linker (al.exe). For the C# compiler, the
  4. 4. /target:module switch is used to generate a module instead of an assembly. 13 . What is the difference between a private assembly and a shared assembly? The terms 'private' and 'shared' refer to how an assembly is deployed, not any intrinsic attributes of the assembly. A private assembly is normally used by a single application, and is stored in the application's directory, or a sub-directory beneath. A shared assembly is intended to be used 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 outside the GAC, in which case each application must be pointed to its location via a codebase entry in the application's configuration file.) The main advantage of deploying assemblies to 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 (such as the AppDomain host, and application configuration files), but for weakly named assemblies the search path is normally the application's directory and its sub-directories. For strongly named assemblies, the search path is the GAC followed by the private assembly path. 15 . How does assembly versioning work? An assembly has a version number consisting of four parts, e.g. 1.0.350.1. These are typically interpreted as Major.Minor.Build.Revision, but this is just a convention.& The CLR applies no version constraints on weakly named assemblies, so the assembly version has no real significance. For strongly named assemblies, the version of a referenced assembly is stored in the referring assembly, and by default only this exact version will be loaded at run-time. If the exact version is not available, the referring assembly will fail to load. It is possible to override this behaviour in the config file for the referring assembly - references to a single version or a range of versions of the referenced assembly can be redirected to a specific version. For example, versions to can be redirected to version However 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 version for assemblies deployed to the GAC - a publisher policy file allows the publisher of the assembly 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 problems when providing patches or 'hot fixes' for individual assemblies within an application. To avoid having to deploy config file changes or publisher policy files along with the hot fix, it makes sense to reuse the same assembly version for the hot fix. If desired, the assemblies can be distinguised by altering the assembly file version, which is not used at all by the CLR for applying version policy. For more discussion, see Suzanne Cook's When to Change
  5. 5. File/Assembly Versions blog entry. Note that the versioning of strongly named assemblies applies whether the assemblies are deployed privately or to the GAC. 16 . How can I develop an application that automatically updates itself from the 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 can exist inside a Win32 process. The primary purpose of the AppDomain is to isolate applications from each other, and so it is particularly useful in hosting scenarios such as ASP.NET. An AppDomain can be destroyed by the host without affecting other AppDomains in the process. Win32 processes provide isolation by having distinct memory address spaces. This is effective, but expensive. The .NET runtime enforces AppDomain isolation by keeping control over the use of memory - all memory in the AppDomain is managed by the .NET runtime, so the runtime can ensure that AppDomains do not access each other's memory. One non-obvious use of AppDomains is for unloading types. Currently the only way to unload a .NET type is to destroy the AppDomain it is loaded into. This is particularly useful if 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.net moniker developed by Jason Whittington and Don Box. There is also a code sample in the .NET SDK called CorHost. 19 . What is garbage collection? Garbage collection is a heap-management strategy where a run-time component takes responsibility for managing the lifetime of the memory used by objects. This concept is not new to .NET - Java and many other languages/runtimes have used garbage collection for some time. 20 . Is it true that objects don't always get destroyed immediately when the last reference goes away? Yes. The garbage collector offers no guarantees about the time when an object will be destroyed and its memory reclaimed.& There was an interesting thread on the DOTNET list, started by Chris Sells, about the implications of non-deterministic destruction of objects in C#. In October 2000, Microsoft's Brian Harry posted a lengthy analysis of the problem. Chris Sells'response to Brian's posting is here 21 . Why doesn't the .NET runtime offer deterministic destruction? Because of the garbage collection algorithm. The .NET garbage collector works by periodically running through a list of all the objects that are currently being referenced by an application. All the objects that it doesn't find during this search are ready to be destroyed and the memory reclaimed. The implication of this algorithm is that the runtime doesn't get notified immediately when the final reference on an object goes away - it only finds out during the next 'sweep' of the heap
  6. 6. Futhermore, this type of algorithm works best by performing the garbage collection sweep as rarely as possible. Normally heap exhaustion is the trigger for a collection sweep. 22 . Is the lack of deterministic destruction in .NET a problem? It's certainly an issue that affects component design. If you have objects that maintain expensive or scarce resources (e.g. database locks), you need to provide some way to tell the object to release the resource when it is done. Microsoft recommend that you provide a method called Dispose() for this purpose. However, this causes problems for distributed objects - in a distributed system who calls the Dispose() method? Some form of reference-counting or ownership-management mechanism is needed to handle distributed objects - unfortunately the runtime offers no help with this 23 . Should I implement Finalize on my class? Should I implement IDisposable? This issue is a little more complex than it first appears. There are really two categories of class that require deterministic destruction - the first category manipulate unmanaged types directly, whereas the second category manipulate managed types that require deterministic destruction. An example of the first category is a class with an IntPtr member representing an OS file handle. An example of the second category is a class with a System.IO.FileStream member For the first category, it makes sense to implement IDisposable and override Finalize. This allows the object user to 'do the right thing' by calling Dispose, but also provides a fallback of freeing the unmanaged resource in the Finalizer, should the calling code 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 managed member objects cannot be accessed in the Finalizer. This is because there is no guarantee about the ordering of Finalizer execution. So only the Dispose method should be implemented. (If you think about it, it doesn't really make sense to call Dispose on member objects from a Finalizer anyway, as the member object's Finalizer will do the required cleanup.) For classes that need to implement IDisposable and override Finalize, see Microsoft's 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 to implement Finalize but include a Debug.Assert at the start, thus signalling the problem in developer 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 the garbage collector to collect all unreferenced objects immediately Also there is a gcConcurrent setting that can be specified via the application configuration file. This specifies whether or not the garbage collector performs some of its collection activities on a separate thread. The setting only applies on multi-processor machines, 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 CLR xxx' performance counters. Use Performance Monitor to view them 26 . What is the lapsed listener problem?
  7. 7. The lapsed listener problem is one of the primary causes of leaks in .NET applications. It occurs when a subscriber (or 'listener') signs up for a publisher's event, but fails to unsubscribe. The failure to unsubscribe means that the publisher maintains a reference to the subscriber as long as the publisher is alive. For some publishers, this may be the duration of the application This situation causes two problems. The obvious problem is the leakage of the subscriber object. The other problem is the performance degredation due to the publisher sending redundant notifications to 'zombie' subscribers. There are at least a couple of solutions to the problem. The simplest is to make sure the subscriber is unsubscribed from the publisher, typically by adding an Unsubscribe() method to the subscriber. Another solution, documented here by Shawn Van Ness, is to change 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), or to 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 Web Services, and SoapFormatter/BinaryFormatter for remoting. Both are available for use in your own code 29 . 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 the target class has a parameterless constructor, and only public read/write properties and fields can be serialized. However, on the plus side, XmlSerializer has good support for customising the XML document that is produced or consumed. XmlSerializer's features mean that it is most suitable for cross-platform work, or for constructing objects from existing XML documents SoapFormatter and BinaryFormatter have fewer limitations than XmlSerializer. They can serialize private fields, for example. However they both require that the target class be marked with the [Serializable] attribute, so like XmlSerializer the class needs to be written with serialization in mind. Also there are some quirks to watch out for - for example 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 be performed on the .NET platform and where performance is important. SoapFormatter generally 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 configure serialization 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 used for a particular property or field.
  8. 8. Serialization via SoapFormatter/BinaryFormatter can also be controlled to some extent by attributes. For example, the [NonSerialized] attribute is the equivalent of XmlSerializer's [XmlIgnore] attribute. Ultimate control of the serialization process can be acheived by implementing the the ISerializable interface on the class whose instances are to be serialized. 31 . Why is XmlSerializer so slow? There is a once-per-process-per-type overhead with XmlSerializer. So the first time you serialize or deserialize an object of a given type in an application, there is a significant delay. This normally doesn't matter, but it may mean, for example, that XmlSerializer is a poor choice for loading configuration settings during startup of a GUI application 32 . Why do I get errors when I try to serialize a Hashtable? XmlSerializer will refuse to serialize instances of any class that implements IDictionary, e.g. Hashtable. SoapFormatter and BinaryFormatter do not have this restriction. 33 . XmlSerializer is throwing a generic "There was an error reflecting MyClass" error. How do I find out what the problem is? Look at the InnerException property of the exception that is thrown to get a more specific error message 34 . What are attributes? There are at least two types of .NET attribute. The first type I will refer to as a metadata attribute - it allows some data to be attached to a class or method. This data becomes part of the metadata for the class, and (like other class metadata) can be accessed via reflection. An example of a metadata attribute is [serializable], which can be attached 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 syntax to metadata attributes but they are fundamentally different. Context attributes provide an interception mechanism whereby instance activation and method calls can be pre- and/or post-processed. If you have encountered Keith Brown's universal delegator you'll be familiar 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 is allowed to run, and what resources it can use when it is running. For example, it is CAS that 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 and permissions. Each .NET assembly is a member of a particular code group, and each code group is granted the permissions specified in a named permission set. For example, using the default security policy, a control downloaded from a web site belongs to the 'Zone - Internet' code group, which adheres to the permissions defined by the 'Internet' named permission set. (Naturally the 'Internet' named permission set represents a very restrictive range of permissions.) 37 . I'm 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 you what code group an assembly belongs to, using caspol -rsg. Similarly, you can ask what permissions are being applied to a particular assembly using caspol -rsp
  9. 9. 38 . I can't be bothered with CAS. Can I turn it off? Yes, as long as you are an administrator. Just run: caspol -s off 39 . 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 for an assembly. 40 . Can source code be reverse-engineered from IL? Yes, it is often relatively straightforward to regenerate high-level source from IL. Lutz Roeder's 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 a way that reverse-engineering becomes much more difficult Of course if you are writing web services then reverse-engineering is not a problem as 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 will be generated. 43 . Can I do things in IL that I can't do in C#? Yes. A couple of simple examples are that you can throw exceptions that are not derived from System.Exception, and you can have non-zero-based arrays. 44 . Does .NET replace COM? This subject causes a lot of controversy, as you'll see if you read the mailing list archives. Take a look at the following two threads: http://discuss.develop.com/archives/wa.exe?A2=ind0007&L=DOTNET&D=0&P=68241 http://discuss.develop.com/archives/wa.exe?A2=ind0007&L=DOTNET&P=R60761 The bottom line is that .NET has its own mechanisms for type interaction, and they don't use COM. No IUnknown, no IDL, no typelibs, no registry-based activation. This is mostly good, as a lot of COM was ugly. Generally speaking, .NET allows you to package and use components in a similar way to COM, but makes the whole thing a bit easier. 45 . Is DCOM dead? Pretty much, for .NET developers. The .NET Framework has a new remoting model which is not based on DCOM. DCOM was pretty much dead anyway, once firewalls became widespread and Microsoft got SOAP fever. Of course DCOM will still
  10. 10. be used in interop scenarios. 46 . Is COM+ dead? Not immediately. The approach for .NET 1.0 was to provide access to the existing COM+ services (through an interop layer) rather than replace the services with native .NET ones. Various tools and attributes were provided to make this as painless 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 may mean that some services will be rewritten as managed code which runs on top of the CLR. For more on this topic, search for postings by Joe Long in the archives - Joe is the MS group manager for COM+. Start with this message: http://discuss.develop.com/archives/wa.exe?A2=ind0007&L=DOTNET&P=R68370 47 . Can I use COM components from .NET programs? Yes. COM components are accessed from the .NET runtime via a Runtime Callable Wrapper (RCW). This wrapper turns the COM interfaces exposed by the COM component into .NET-compatible interfaces. For oleautomation interfaces, the RCW can be generated automatically from a type library. For non-oleautomation interfaces, it may be necessary to develop a custom RCW which manually maps the types exposed 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 opposite direction. Again, if the wrapper cannot be automatically generated by the .NET development tools, or if the automatic behaviour is not desirable, a custom CCW can be developed. Also, for COM to 'see' the .NET component, the .NET component must be 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 instance of 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()
  11. 11. { 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 the thread 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 communication mechanism to tell the ThreadStart method to finish. Alternatively the Thread class has in-built support for instructing the thread to stop. The two principle methods are Thread.Interrupt() and Thread.Abort(). The former will cause a ThreadInterruptedException to be thrown on the thread when it next goes into a WaitJoinSleep state. In other words, Thread.Interrupt is a polite way of asking the thread 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 ThreadStart's finally method will be executed). Thread.Abort() is a heavy-handed mechanism which should not normally be required. 52 . How do I use the thread pool? By passing an instance of a WaitCallback delegate to the ThreadPool.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 code into the WaitCallback method to signal that it has completed. Events are useful for this. 54 . Should I use ReaderWriterLock instead of Monitor.Enter/Exit? Maybe, but be careful. ReaderWriterLock is used to allow multiple threads to read from a data source, while still granting exclusive access to a single writer thread.
  12. 12. This makes sense for data access that is mostly read-only, but there are some caveats. First, ReaderWriterLock is relatively poor performing compared to Monitor.Enter/Exit, which offsets some of the benefits. Second, you need to be very sure that the data structures you are accessing fully support multithreaded read access. Finally, there is apparently a bug in the v1.1 ReaderWriterLock that can cause starvation 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 deal with tracing - Debug and Trace. They both work in a similar way - the difference is that tracing from the Debug class only works in builds that have the DEBUG symbol defined, whereas tracing from the Trace class only works in builds that have the TRACE symbol defined. Typically this means that you should use System.Diagnostics.Trace.WriteLine for tracing that you want to work in debug and release builds, and System.Diagnostics.Debug.WriteLine for tracing that you want to work 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 a collection of sinks that receive the tracing that you send via Debug.WriteLine and Trace.WriteLine respectively. By default the Listeners collection contains a single sink, which is an instance of the DefaultTraceListener class. This sends output to the Win32 OutputDebugString() function and also the System.Diagnostics.Debugger.Log() method. This is useful when debugging, but if you're trying to trace a problem at a customer site, redirecting the output to a file is more appropriate. Fortunately, the TextWriterTraceListener class is provided for this purpose. Here's 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 don't do this, the output will go to the file and OutputDebugString(). Typically this is not what you 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 output through it. Here's a simple example, which derives from TextWriterTraceListener (and therefore has in-built support for writing to files, as shown above) and adds timing information 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}",
  13. 13. Environment.TickCount - m_startTickCount, AppDomain.GetCurrentThreadId(), s ); } protected int m_startTickCount = Environment.TickCount; } (Note that this implementation is not complete - the TraceListener.Write method is not overridden for example.) The beauty of this approach is that when an instance of MyListener is added to the Trace.Listeners collection, all calls to Trace.WriteLine() go through MyListener, including calls made by referenced assemblies that know nothing about the MyListener 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 standard channels are HTTP and TCP. TCP is intended for LANs only - HTTP can be used for LANs 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 .NET runtime Serialization SOAP Formatter), and the TCP channel uses binary (via the .NET runtime Serialization Binary Formatter). But either channel can use either serialization format. There are a number of styles of remote access: • SingleCall. Each incoming request from a client is serviced by a new object. The object is thrown away when the request has finished. • Singleton. All incoming requests from clients are processed by a single server object. • Client-activated object. This is the old stateful (D)COM model whereby the client receives a reference to the remote object and holds that reference (thus keeping the remote object alive) until it is finished with it. Distributed garbage collection of objects is managed by a system called 'leased based lifetime'. Each object has a lease time, and when that time expires the object is disconnected from the .NET runtime remoting infrastructure. Objects have a default renew time - the lease is renewed when a successful call is made from the client to the object. The client can also explicitly renew the lease. If you're interested in using XML-RPC as an alternative to SOAP, take a look at Charles Cook's 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 access static DLL entry points instead of COM objects. Here is an example of C# calling the Win32 MessageBox function: using System; using System.Runtime.InteropServices; class MainApp { [DllImport("user32.dll", EntryPoint="MessageBox", SetLastError=true,
  14. 14. CharSet=CharSet.Auto)] public static extern int MessageBox(int hWnd, String strMessage, String strCaption, 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 don't. 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 a class 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 object can send notifications to the subscribers. However, a public multicast delegate has the undesirable property that external objects can invoke the delegate, something we'd normally want to restrict to the publisher. Hence events - an event adds public methods to the containing class to add and remove receivers, but does not make the invocation 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 - a method 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 the type 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 a minimum 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, and corresponding 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 OS decides which to use based on the PE header of the executable. The flags in the PE header are controlled via the compiler /platform switch, which allows the target of the app to be specified as 'x86', 'x64' or 'any cpu'. Normally you specify 'any cpu', and your app will run as 32-bit on 32-bit Windows and 64-bit on 64-bit Windows. However if you have some 32-bit native code in your app (loaded via COM interop, for example), you will need to specify 'x86', which will force 64-bit Windows to load your app in a 32-bit process. You can also tweak the 32-bit flag in the PE header using the SDK corflags utility.
  15. 15. Some more explanation here: http://blogs.msdn.com/gauravseth/archive/2006/03/07/545104.aspx http://blogs.msdn.com/joshwil/archive/2005/04/08/406567.aspx http://msdn.microsoft.com/netframework/programming/64bit/gettingstarted/ 65 . What is reflection? All .NET compilers produce metadata about the types defined in the modules they produce. This metadata is packaged along with the module (modules in turn are packaged together in assemblies), and can be accessed by a mechanism called reflection. The System.Reflection namespace contains classes that can be used to interrogate the types for a module/assembly. Using reflection to access .NET metadata is very similar to using ITypeLib/ITypeInfo to 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/machine boundaries. Reflection can also be used to dynamically invoke methods (see System.Type.InvokeMember), or even create types dynamically at run-time (see System.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 more information about these features. 67 . What are the new 2.0 features useful for? Generics are useful for writing efficient type-independent code, particularly where the types might include value types. The obvious application is container classes, and the .NET 2.0 class library includes a suite of generic container classes in the System.Collections.Generic namespace. Here's a simple example of a generic container class being used: List<int> myList = new List<int>(); myList.Add( 10 ); Anonymous methods reduce the amount of code you have to write when using delegates, and are therefore especially useful for GUI programming. Here's an example AppDomain.CurrentDomain.ProcessExit += delegate { Console.WriteLine("Process ending ..."); }; 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 development tools such as Visual Studio. Iterators reduce the amount of code you need to write to implement IEnumerable/IEnumerator. Here's 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> {
  16. 16. 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 an implementation of IEnumerator, something we had to do manually in .NET 1.x. 68 . What's 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 type parameter 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 been constrained, and therefore only supports the methods of System.Object. Dispose is not a method on System.Object, so the compilation fails. To fix this code, we need to add a where clause, to reassure the compiler that our type T does indeed have a Dispose 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 use constraints to say that T implements a particular interface, but we can't dilute that to simply 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 at compile time) that if the code invokes the Dispose() method on a type, then the type will support the method. In fact, after writing generic code with interface constraints, we quickly see that we haven't 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-0050 Ian Griffiths: http://www.interact-sw.co.uk/iangblog/2004/03/14/generics Charles Cook: http://www.cookcomputing.com/blog/archives/000425.html 69 . What's 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.
  17. 17. • 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.Compression namespace. • The Semaphore class in the System.Threading namespace. • Wrappers for DPAPI in the form of the ProtectedData and ProtectedMemory classes in the System.Security.Cryptography namespace. • The IPC remoting channel in the System.Runtime.Remoting.Channels.Ipc namespace, 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
  18. 18. available? After the Init() and before the Page_Load(), or OnLoad() for a control. 5 . What namespace does the Web page belong in the .NET Framework class hierarchy? System.Web.UI.Page 6 . Where do you store the information about the user’s locale? System.Web.UI.Page.Culture 7 . What’s the difference between Codebehind="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 an event processing routine for each object (cell, button, row, etc.) is quite tedious. The controls can bubble up their eventhandlers, allowing the main DataGrid event handler to take care of its constituents. 9 . Suppose you want a certain ASP.NET function executed on MouseOver for a certain button. Where do you add an event handler? 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 code executes in the client's 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 executed on the server. However, during the code-behind's execution on the server, it can render client-side code such as JavaScript to be processed in the clients browser. But just to be clear, code-behind executes on the server, thus making it server-side code. 13 . Should user input data validation occur server-side or client-side? Why? All user input data validation should occur on the server at a minimum. Additionally, client-side validation can be performed where deemed appropriate and feasable to provide a richer, more responsive experience for the user. 14 . What is the difference between Server.Transfer and
  19. 19. Response.Redirect? Why would I choose one over the other? Server.Transfer transfers page processing from one page directly to the next page without making a round-trip back to the client's browser. This provides a faster response with a little less overhead on the server. Server.Transfer does not update the clients url history list or current url. Response.Redirect is used to redirect the user's browser to another page or site. This performas a trip back to the client where the client's browser is redirected to the new page. The user's browser history list is updated to reflect the new address. 15 . Can you explain the difference between an 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 connection to the original data source. — Data in a DataSet is bulk-loaded, rather than being loaded on demand. — There's no concept of cursor types in a DataSet. — DataSets have no current record pointer You can use For Each loops to move through the data. — You can store many edits in a DataSet, and write them to the original data source in a single operation. — Though the DataSet is universal, other objects in ADO.NET come in 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 to implement application and session level events. 17 . What are the Application_Start and Session_Start subroutines used for? This is where you can set the specific variables for the Application and Session objects. 18 . Can you explain what inheritance is and an example of when you might use it? When you want to inherit (use the functionality of) another class. Example: With a base class named Employee, a Manager class 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 MSDN 20 . Describe the difference between inline and code behind. Inline code written along side the html in a page. Code-behind is code written in a separate file and referenced by the .aspx page. 21 . Explain what a diffgram is, and a good use for one?
  20. 20. The DiffGram is one of the two XML formats that you can use to render DataSet object contents to XML. A good use is reading database data to an XML file to be sent to a Web Service. 22 . Whats MSIL, and why should my developers need an appreciation of it if at all? MSIL is the Microsoft Intermediate Language. All .NET compatible languages will get converted to MSIL. MSIL also allows the .NET Framework to JIT compile the assembly on the installed computer. 23 . Which method do you invoke on the DataAdapter control to 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 display data in a Repeater control? ItemTemplate. 26 . How can you provide an alternating color scheme in a Repeater control? Use the AlternatingItemTemplate. 27 . What property must you set, and what method must you call in your code, in order to bind the data from a data source to the Repeater control? You must set the DataSource property and call the DataBind method. 28 . What base class do all Web Forms inherit from? The Page class. 29 . Name two properties common in every validation control? ControlToValidate property and Text property. 30 . Which property on a Combo Box do you set with a column name, prior to setting the DataSource, to display data in the combo box? DataTextField property. 31 . Which control would you use if you needed to make sure the values in two different controls matched? CompareValidator control. 32 . How many classes can a single .NET DLL contain? It can contain many classes.
  21. 21. Web Service Questions 33 . What is the transport protocol you use to call a Web service? 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.org 36 . True or False: To test a Web service you must create a Windows application or Web application to consume this service? False, the web service comes with a test page and it provides HTTP-GET method to test. 37 . Can you give an example of when it would be appropriate to use a web service as opposed to a non-serviced .NET component Webservice is one of main component in Service Oriented Architecture. You could use webservices when your clients and servers are running on different networks and also different platforms. This provides a loosely coupled system. And also if the client is behind the firewall it would be easy to use webserivce since it runs on port 80 (by default) instead of having some thing else in SOA apps State Management Questions 38 . What is ViewState? ViewState allows the state of objects (serializable) to be stored in a hidden field on the page. ViewState is transported to the client and back to the server, and is not stored on the server or any other external 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? Why would I want it on or off? It allows the page to save the users input on a form across postbacks. It saves the server-side values for a given control into ViewState, which is stored as a hidden value on the page before sending the page to the clients browser. When the page is posted back to the server the server control is recreated with the state stored in viewstate.
  22. 22. 41 . What are the different types of Session state management options available with ASP.NET? ASP.NET provides In-Process and Out-of-Process state management. In-Process stores the session in memory on the web server. This requires the a "sticky-server" (or no load-balancing) so that the user is always reconnected to the same web server. Out-of- Process Session state management stores data in an external data source. The external data source may be either a SQL Server or a State Server service. Out-of-Process state management requires that all objects stored in session are serializable. 42 . Let's say I have an existing application written using Visual Studio 6 (VB 6, InterDev 6) and this application utilizes Windows 2000 COM+ transaction services. How would you approach migrating this application to .NET You have to use System.EnterpriseServices namespace and also COMInterop the existing application 43 . Can you give an example of what might be best suited to place in the Application_Start and Session_Start subroutines? In the Application_Start event you could store the data, which is used throughout the life time of an application for example application name, where as Session_Start could be used to store the information, which is required for that session of the application say for example user id or user name. 44 . If I'm developing an application that must accomodate multiple security levels though secure login and my ASP.NET web appplication is spanned across three web-servers (using round-robbin load balancing) what would be the best approach to maintain login-in state for the users? Use the state server or store the state in the database. This can be easily done through simple setting change in the web.config. <sessionState mode="InProc" stateConnectionString="tcpip=" sqlConnectionString="data source=;user id=sa;password=" cookieless="false" timeout="30" /> in the above one instead of mode="InProc", you specifiy stateserver or sqlserver. 45 . What are ASP.NET Web Forms? How is this technology different than what is available though ASP (1.0-3.0)? ASP.NET webforms are analogous to Windows Forms which are available to most VB developers. A webform is essentially a core container in a Page. An empty webform is nothing but a HTML Form tag(control) running at server and posting form to itself by default, but you could change it to post it to something else. This is a container, and you could place the web controls, user controls and HTML Controls in that one and interact with user on a postback
  23. 23. basis. 46 . How does VB.NET/C# achieve polymorphism? Polymorphism is achieved through virtual, overloaded, overridden methods in C# and VB.NET 47 . Describe session handling in a webform, how does it work and what are the its limits Sometimes it is necessary to carry a particular session data across pages. And HTTP is a stateless protocol. In order to maintain state between page calls, we could use cookies, hidden form fields etc. One of them is using sessions. each sessions are maintain a unique key on the server and serialize the data on it. Actually it is a hashtable and stores data on key/value pair of combination. You could set a session using Session Object and retrieve the same data/state by passing the key. //Set Session["abc"] = "Session Value"; // Get string abc = Session["abc"].ToString(); The downside of sessions is scalability. Say your application gets more and more hits and you though instead of one webserver handling it, have it in a webfarm (multiple web servers working under one domain). You cannot transfer the session so easily across multiple webservers. Reason is like I said, it physically serializes the state data to webserver hard disk. .NET proposes a new way to handle this using a stateserver (actually a trimmed down sql server) storing the web session data in a factory configured database schema or using Database with your own schema defined to handle the sessions. 48 . How would you get ASP.NET running in Apache web servers - 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 would allow more number of web site owners to take advantage of ASP.NET and its richness. 49 . Whats MSIL, and why should my developers need an appreciation of it if at all? MSIL is Microsoft Intermediate (Intermediary) Language. It is Microsoft's implementation of CIL (standard recognized
  24. 24. by ECMA and ISO) as part of CLI and C# Standardization. .NET supports more than 21 language (I think 24 now). They compile to IL first and then this IL would get JITted to Native code at runtime. Learning IL is advantageous in many terms. The important one is sometimes you need to optimize your code, so you could disassemble your compile assembly using ILDASM and tweak your code and re assemble it using ILASM. 50 . In what order do the events of an ASPX page execute. As a developer is it important to undertsand these events? This is the order of Page events i. Page_Init ii.Page_LoadViewState iii. Page_LoadPostData iv. Page_Load v. Page_RaisePostDataChanged vi. Page_RaisePostBackEvent vii. Page_PreRender viii. Page_SaveViewState ix. Page_Render x. Page_Dispose xii. Page_Error (this is caused whenever there is an exception at the page level). Out of all the Page_Load is the one where your code gets loaded and your magic should be written. page_init occurs only once, i.e. when the page is initially created. As a developer you need to know these, becuase your development activity is coding for these only. 51 . Which method do you invoke on the DataAdapter control to 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 s session? Session.Abandon 54 . 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 to write your own code to do this using Response.Cookies collection and HTTPCookie class and also 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:
  25. 25. 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:datagrid tags 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 be travelled across multiple requests, then you need to have permanent or persistant cookie. In order to do this, you have to set the your webserivce CookieContainer to a newly created CookieContainer, and the its cookie to a session value and then store the cookie(s) into the Service CookieCollection from that cookie container if something is there othere wise add cookie to the container. 58 . What tag do you use to add a hyperlink column to the DataGrid? HyperLinkColumn 59 . What is the standard you use to wrap up a call to a Web service SOAP. 60 . Which method do you use to redirect the user to another page without performing a round trip to the client? Server.Transfer Response.Redirect also does that but it requires round trip between client 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 which page to go to when using the Pager object? CurrentPageIndex. You need to set this one with the DataGridPageChangedEventArgs' NewPageIndex. 64 . Which control would you use if you needed to make sure the values in two different controls matched? Use CompareValidator 65 . True or False: To test a Web service you must create a windows application or Web application to consume this service?
  26. 26. False. The webservice comes with a test page and it provides HTTP-GET method to test. And if the web service turned off HTTP-GET for security purposes then you need to create a 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 more classes and an assembly can be contained in one dll or could spread across multiple dlls. too. Take System.dll, it is collections 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 position in a constant number of operations (changing some references) O(1). ? Easy to delete a node (as it only has to rearrange the links to the different nodes)., O(1). ? To find the nth node, will need to recurse through the list till it finds [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 node without 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 to be resized, an expensive operation that may not even be possible if memory is fragmented. Similarly, an array from which many elements are removed may become wastefully empty or need to be made smaller, O(n) ? easy to find the nth element in the array by directly referencing them 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 Job Home .Net J2EE PHP Testing Freshers HR Q/A Networking Others Freshers Jobs Experienced Jobs Post Ur Jobs
  27. 27. Dot Net - Asp.Net - Basic I 1 . What is ASP.NET? ASP.NET is a programming framework built on the common language runtime that can be 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 and uninstallation of multiple versions of ASP.NET on a single machine. You can find the file in C:WINNTMicrosoft.NETFrameworkv**aspnet_regiis.exe use 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 -enable This 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 and install 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.NET Response.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"%> .aspx VB.NET Response.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?
  28. 28. In classic ASP, when a form is submitted the form values are cleared. In some cases the form 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 all form values. This is because ASP .NET maintains your ViewState. ViewState is a state management technique built in ASP.NET. Its purpose is to keep the state of controls during subsequent postbacks by the same user. The ViewState indicates the status of the page when submitted to the server. The status is defined through a hidden field placed on each page with a <form runat="server"> control. <input type="hidden" name= "__VIEWSTATE"value="dDwyNTA3OTU0NDM7Oz7t5TntzkOUeB0QVV6FT2hvQwtpPw==" /> If you want to NOT maintain the ViewState, include the directive <%@ Page EnableViewState="false"%> at the top of an .aspx page If you do not want to maintain Viewstate for any control add the attribute EnableViewState="false" to any control. For more details refer The ASP.NET View State 7 . Where can I get the details on Migration of existing projects using various technologies to ASP.NET? Microsoft has designed Migration Assistants to help us convert existing pages and applications 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.Net 8 . What is the equivalent of date() and time() in ASP.NET? VB.NET System.DateTime.Now.ToShortDateString() System.DateTime.Now.ToShortTimeString() C# System.DateTime.Now.ToShortDateString(); System.DateTime.Now.ToShortTimeString(); 9 . How to prevent a button from validating it's form? Set the CauseValidation property of the button control to False 10 . How to get the IP address of the host accessing my site? VB.NET Response.Write (Request.UserHostAddress.ToString ())
  29. 29. 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 the parameter value associated with that key. VB.NET Request.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.NET 13 . 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 useful information? In the global.asax Application_error Event write the following code VB.NET Dim ex As Exception = Server.GetLastError().GetBaseException() If TypeOf ex Is System.IO.FileNotFoundException Then 'your code 'Response.Redirect("err404.aspx") Else 'your code End If C# Exception ex = Server.GetLastError().GetBaseException(); if (ex.GetType() == typeof(System.IO.FileNotFoundException)) { //your code Response.Redirect ("err404.aspx"); } else { //your code
  30. 30. } 15 . Is there a method similar to Response.Redirect that will send variables to the destination page other than using a query string or the post method? Server.Transfer preserves the current page context, so that in the target page you can extract values and such. However, it can have side effects; because Server.Transfer doesnt' go through the browser, the browser doesn't update its history and if the user clicks 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 the source page, where you can get the values you need, put them in Session, and then use Response.Redirect to transfer to the target page. (This does bounce off the browser.) In the 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 Controls 17 . How can I change the action of a form through code? You can't change it. The action attribute is owned by ASP.NET. Handle Events and Transfer. For work around refer to Paul Wilson's Multiple Forms and Non-PostBack Forms - Solution 18 . Is there any control that allows user to select a time from a clock - in other words is there a clock control? Peter Blum has developed some controls. Check out Peter's Date Package: TimeOfDayTextBox and DurationTextBox Controls 19 . How to Compare time? VB.NET Dim 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 Then Response.Write(t1.ToString() & " is < than " & t2.ToString()) Else Response.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 ) {
  31. 31. 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.NET Dim 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 Pope's article Basics of Cookies in ASP.NET 22 . Does ASP.Net still recognize the global.asa file? ASP.Net does not recognize the standard ASP global.asa file. Instead it uses a file named 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 it was in previous versions of ActiveServer Pages. Link to more information: <gcConcurrent> Element 24 . 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 ASP pages and applications 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. 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
  32. 32. Also refer: • Microsoft's ASP to ASP.NET Code Migration Assistant • John Peterson's article Microsoft's ASP to ASP.NET Migration Assistant • Paolo Cavone's article From ASP to ASP.NET... Painlessly! 25 . How do I publish my ASP.NET application to my ISP's web server? Your ISP must first create an IIS application and apply the Front Page Server Extensions to it. Then in Visual Studio .NET, select the "Project | Copy Project" menu. Then enter the URL and select the FrontPage web access method. The "Copy Project" feature copies all of the necessary files to your ISP's 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 to upload. For more details refer PRB: Remote ASP.NET Projects Require IIS on the Client Computer or FrontPage Server Extensions on the Server Computer 26 . Why do i get error message "Could not load type" whenever I browse to my ASP.NET web site? Your code-behind files for either your .aspx or the global.aspx page have not been complied. Use Visual Studio .NET's "Build | Build Solution" menu, or run the command line compiler. For more details refer PRB: "Could not load type" error message when you browse to .aspx page 27 . Will the WebMatrix SqlDataSourceControl work with a MySQL connection? SqlDataSourceControl lets you connect and work with MS SQL DB, while AccessDataSourceControl do the same thing but for MS Access DB. Therefore SqlDataSourceControl can't help you in your MySql connectivity . For Connectivity with MySql refer Accessing MySQL Database with ASP.NET 28 . Can I combine classic ASP and ASP.NET pages? No. ASP pages can run in the same site as ASP.NET pages, but you can't mix in a page. Also ASP and ASP.NET won't 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 don't have to manually worry about compiling and messing with dlls -- it just works. Of course, the source is now on the server, for anyone with access to the server -- but not just anyone on the web. CodeBehind attribute doesn't really "do" anything, its just a helper for VS.NET to associate the code file with the aspx file. This is necessary since VS.NET automates the pre-compiling that is harder by hand, and therefore the Src attribute is also gone. Now there is only a dll to deploy, no source, so it is certainly better protected, although its always 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 use ControlName.Value to get its value in CodeBehind file
  33. 33. 31 . I have created a .NET user control page (.ascx) but I cannot compile and run it. User control (ascx) can't 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 and strings inside XML tags. This is useful for localization. For more details refer Resources in .resx files 33 . Is it possible to use a style sheet class directly on a control instead of using inline or page-level formatting ? Every WebControl derived control has a CssClass property which allows you to set it's format to a style sheet. 34 . Can I recieve both HTML markup for page and code in the ASP.NET web page's 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 can't I put where at the top of an ASPX file and write my server-side scripts in C ? The parsers ASP.NET uses to extract code from ASPX files understand C#, Visual Basic.NET, and JScript.NET. You can write server-side scripts in any language supported by a .NET compiler. 36 . ASP pages that worked pefectly on Windows 2000 Server and IIS 5.0 do not work on Windows 2003 Server with IIS 6.0. ASP.NET pages work fine. Why? Start -> Settings -> Control Panel -> Administrative Tools -> and double clicking IIS Manager. Go to the Web Service Extensions tab, click Active Server Pages, then press the "Allow" button on the left 37 . Why do I get error message "Error creating assembly manifest: Error reading key 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 explicit path or a relative path. <Assembly: AssemblyKeyFileAttribute("Drive:key.snk")> 38 . How to get URL without querystring? VB.NET Dim stringUri As String = "http://www.syncfusion.com/?id=1&auid=16" Dim weburi As Uri = New Uri(stringUri) Dim query As String = weburi.Query Dim 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;
  34. 34. 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.NET Response.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.NET Response.Write ( Request.UrlReferrer.ToString()) C# Response.Write ( Request.UrlReferrer.ToString()); 42 . My ASP code gives an error "Compiler Error Message: BC30289: Statement cannot 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 of procedure or function wirtten properly. 43 . How can I save images ? You need a stream to read the response, WebResponse.GetResponseStream(), and a stream to write it to the hard drive. FileStream should do the trick. You'll have to write to the 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") to transfer to a different page? Server.Transfer only works with .aspx pages You can't use Transfer method with HTML pages 46 . How to detect the User's culture? VB.NET Dim sLang As String sLang = Request.UserLanguages(0) Response.Write(sLang)
  35. 35. C# string sLang ; sLang = Request.UserLanguages[0]; Response.Write (sLang); 47 . What is the difference between CurrentCulture property and the CurrentUICulture property? • CurrentCulture property : affects how the .NET Framework handles dates, currencies, sorting and formatting issues • CurrentUICulture property : determines which satellite assembly is used when loading resources 48 . 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 handler src is the object that fires the event e is an event argument object that contains more information about the event An event handler is used when one object wants to be notified when an event happens in another object 50 . 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..), Server's 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
  36. 36. Home .Net J2EE PHP Testing Freshers HR Q/A Networking Others Freshers Jobs Experienced Jobs Post Ur Jobs Dot Net - Asp.Net - Basic II 1 . What is the difference between URL and URI? A URL is the address of some resource on the Web, which means that normally you type the address into a browser and you get something back. There are other type of resources than Web pages, but that's the easiest conceptually. The browser goes out somewhere on the Internet and accesses something. A URI is just a unique string that uniquely identifies something, commonly a namespace. Sometimes they look like a URL that you could type into the address bar of your Web browser, but it doesn't have to point to any physical resource on the Web. It is just a unique set of characters, that, in fact, don't even have to be unique. URI is the more generic term, and a URL is a particular type of URI in that a URL has to uniquely identify some resource on the Web. 2 . How to convert milliseconds into time? VB.NET dim 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.Globalization VB.NET Dim myString As String = "syncFusion deVeloPer sUppOrt" ' Creates a TextInfo based on the "en-US" culture. Dim TI As TextInfo = New CultureInfo("en-US", False).TextInfo Response.Write(TI.ToTitleCase(myString))
  37. 37. 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 more than one user simultaneously? Use the HttpApplicationState's Lock and UnLock methods. For more details refer : MSDN: Application State 6 . Why do I get the error message "System.InvalidOperationException: It is invalid to show a modal dialog or form when the application is not running in UserInteractive mode. Specify the ServiceNotification or DefaultDesktopOnly style to display a ...."? You can't use MsgBox or MessageBox.Show in ASP.NET WebForm. You maybe use: VB.NET Response.Write("<script>alert('Hello');</script>") C# Response.Write("<script>alert('Hello');</script>") ; 7 . How to validate that a string is a valid date? VB.NET Dim blnValid As Boolean = False Try DateTime.Parse(MyString) blnValid = True Catch blnValid = False End Try C# bool blnValid=false; try { DateTime.Parse(MyString); blnValid=true; }
  38. 38. 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.NET Dim 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 property 11 . How to convert user input in dMy format to Mdy? VB.NET Dim 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.ParseExact 12 . 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 to retrieve the filename and directory path specified by the user on the File Download dialog box? Clients do not report information back about where the user selects to save the content, so there isn't an easy way to do this. Instead, you would need to ask the user before using the content-disposition for a file path, and then you could specify the filename parameter for the content-disposition header. Still, the user is free to change that path when actually downloading. 13 . How to hide or show Controls in server side code? In any appropriate event write VB.NET TextBox1.Visible =not TextBox1.Visible
  39. 39. 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 indicate whether 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, but you 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 it's 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 desirable 17 . 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 ip address. Note that name of the machine could be different than host, since your site could be using host headers 18 . What is the meaning of validateRequest=true in .net framework1.1? The value of validateRequest is set to 'true' by default, which means that the framework 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 of an expression. The expression inside <%# %> will be executed only when you call the page's or control's DataBind method. The expression inside <%= %> will be executed and displayed as and when it appears in the page. 20 . What permissions do ASP.NET applications posses by default?
  40. 40. By default ASP.NET Web applications run as ASP.NET user. This user has limited permissions equivalent to the User Group. 21 . How can I specify the relative path for a file? Suppose you have following file hierarchy: default.aspx Admin/login.aspx Misc/testpage.aspx And you are on the login.aspx and want your user to navigate to the default.aspx (or testpage.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 only so that the user can click on the browse button and pick a file but they cannot type 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.NET 'Declare Protected WithEvents Title1 As System.Web.UI.HtmlControls.HtmlGenericControl 'In Page_Load Title1.InnerText ="Page 1" C# //Declare protected System.Web.UI.HtmlControls.HtmlGenericControl Title1 ; //In Page_Load Title1.InnerText ="Page 1" ; 24 . Why do I get the error message "Object must implement IConvertible". How can I resolve it? The common cause for this error is specifying a control as a SqlParameter's Value instead of the control's text value. For example, if you write code as below you'll get the above error: VB.NET Dim nameParameter As SqlParameter = command.Parameters.Add("@name",
  41. 41. SqlDbType.NVarChar, 50) nameParameter.Value = txtName C# SqlParameter nameParameter = command.Parameters.Add("@name", SqlDbType.NVarChar, 50); nameParameter.Value = txtName ; To resolve it, specify the control's Text property instead of the control itself. VB.NET nameParameter.Value = txtName.Text C# nameParameter.Value =txtName.Text; 25 . Why is default.aspx page not opened if i specify http://localhost. I am able to 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 the number 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 applying the 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 version 27 . Is it possible to migrate Visual InterDev Design-Time Controls to ASP.NET? Refer INFO: Migrating Visual InterDev Design-Time Controls to ASP.NET 28 . How to automatically get the latest version of all the asp.net solution items from Source Safe when opening the solution? In VS.NET you can go to Tools > Options > Source Control > General and check the checkbox 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 the GridLayout? For VB.NET, go to path C:Program FilesMicrosoft Visual Studio .NETVb7VBWizardsWebFormTemplates1033 Change the following line in the existing WebForm1.aspx <body MS_POSITIONING="[!output DEFAULT_HTML_LAYOUT]"> to
  42. 42. For C#, go to path C:Program FilesMicrosoft Visual Studio .NET 2003VC#VC#WizardsCSharpWebAppWizTemplates1033 Change the following line in the existing WebForm1.aspx <body MS_POSITIONING="[!output DEFAULT_HTML_LAYOUT]"> to Note:Before changing any templates it's a good idea to make backup copies of them Or rather than above approach you can change the behavior for new files on a per project basis 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 a database. 31 . How to format a Telphone number in the xxx-xxx-xxxx format? VB.NET Dim 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 temporary files containing derived Page classes, and a given parser understands only one language 33 . Can I use custom .NET data types in a Web form? Yes. Place the DLL containing the type in the application root's bin directory and ASP.NET will automatically load the DLL when the type is referenced. This is also what happens 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 which displays its own error page. This can be done by setting the ErroPage attribute of Page Directive or ErrorPage
  43. 43. 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.
  44. 44. 8 . What’s the advantage of using System.Text.StringBuilder over System.String? StringBuilder is more efficient in cases where there is a large amount of string manipulation. Strings are immutable, so each time 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 the System.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. The CopyTo() method copies the elements into another existing array. Both perform a shallow copy. A shallow copy means the contents (each array element) contains references to the same object as the elements in the original array. A deep copy (which neither of these methods performs) would create a new instance of each element's object, resulting in a different, yet identacle object. 11 . How can you sort the elements of the array in descending order? By calling Sort() and then Reverse() methods. 12 . What’s the .NET collection class that allows an element to be accessed using a unique key? HashTable. 13 . Will the finally block get executed if an exception has not occurred? Yes. 14 . What’s the C# syntax to catch any possible exception? A catch block that catches the exception of type System.Exception. You can also omit the parameter data type in this case and just write catch {}. 15 . Can multiple catch blocks be executed for a single try statement? No. Once the proper catch block processed, control is transferred to the finally block (if there are any). 16 . Explain the three services model commonly know as a three-tier application. Presentation (UI), Business (logic and underlying code) and Data (from storage or other sources). Class Questions 17 . What is the syntax to inherit from a class in C#?