Interview Questions


.NET Framework Frequently Asked Questions


Contents
  • 1. Introduction
    • 1.1 What is .NET?
    • 1.2 Does .NET only apply to people building web-sites?
    • 1.3 When was .NET announced?
    • 1.4 When was the first version of .NET released?
    • 1.5 What tools can I use to develop .NET applications?
    • 1.6 What platforms does the .NET Framework run on?
    • 1.7 What languages does the .NET Framework support?
    • 1.8 Will the .NET Framework go through a standardisation process?
       
  • 2. Basic terminology
    • 2.1 What is the CLR?
    • 2.2 What is the CTS?
    • 2.3 What is the CLS?
    • 2.4 What is IL?
    • 2.5 What is C#?
    • 2.6 What does 'managed' mean in the .NET context?
    • 2.7 What is reflection?
       
  • 3. Assemblies
    • 3.1 What is an assembly?
    • 3.2 How can I produce an assembly?
    • 3.3 What is the difference between a private assembly and a shared assembly?
    • 3.4 How do assemblies find each other?
    • 3.5 How does assembly versioning work?
       
  • 4. Application Domains
    • 4.1 What is an Application Domain?
    • 4.2 How does an AppDomain get created?
    • 4.3 Can I write my own .NET host?
       
  • 5. Garbage Collection
    • 5.1 What is garbage collection?
    • 5.2 Is it true that objects don't always get destroyed immediately when the last reference goes away?
    • 5.3 Why doesn't the .NET runtime offer deterministic destruction?
    • 5.4 Is the lack of deterministic destruction in .NET a problem?
    • 5.5 Does non-deterministic destruction affect the usage of COM objects from managed code?
    • 5.6 I've heard that Finalize methods should be avoided. Should I implement Finalize on my class?
    • 5.7 Do I have any control over the garbage collection algorithm?
    • 5.8 How can I find out what the garbage collector is doing?
       
  • 6. Serialization
    • 6.1 What is serialization?
    • 6.2 Does the .NET Framework have in-built support for serialization?
    • 6.3 I want to serialize instances of my class. Should I use XmlSerializer, SoapFormatter or BinaryFormatter?
    • 6.4 Can I customise the serialization process?
    • 6.5 Why is XmlSerializer so slow?
    • 6.6 Why do I get errors when I try to serialize a Hashtable?
    • 6.7 XmlSerializer is throwing a generic "There was an error reflecting MyClass" error. How do I find out what the problem is?
       
  • 7. Attributes
    • 7.1 What are attributes?
    • 7.2 Can I create my own metadata attributes?
    • 7.3 Can I create my own context attributes?
       
  • 8. Code Access Security
    • 8.1 What is Code Access Security (CAS)?
    • 8.2 How does CAS work?
    • 8.3 Who defines the CAS code groups?
    • 8.4 How do I define my own code group?
    • 8.5 How do I change the permission set for a code group?
    • 8.6 Can I create my own permission set?
    • 8.7 I'm having some trouble with CAS. How can I diagnose my problem?
    • 8.8 I can't be bothered with all this CAS stuff. Can I turn it off?
       
  • 9. Intermediate Language (IL)
    • 9.1 Can I look at the IL for an assembly?
    • 9.2 Can source code be reverse-engineered from IL?
    • 9.3 How can I stop my code being reverse-engineered from IL?
    • 9.4 Can I write IL programs directly?
    • 9.5 Can I do things in IL that I can't do in C#?
       
  • 10. Implications for COM
    • 10.1 Is COM dead?
    • 10.2 Is DCOM dead?
    • 10.3 Is MTS/COM+ dead?
    • 10.4 Can I use COM components from .NET programs?
    • 10.5 Can I use .NET components from COM programs?
    • 10.6 Is ATL redundant in the .NET world?
       
  • 11. Miscellaneous
    • 11.1 How does .NET remoting work?
    • 11.2 How can I get at the Win32 API from a .NET program?
       
  • 12. Class Library
    • 12.1 File I/O
      • 12.1.1 How do I read from a text file?
      • 12.1.2 How do I write to a text file?
      • 12.1.3 How do I read/write binary files?
    • 12.2 Text Processing
      • 12.2.1 Are regular expressions supported?
    • 12.3 Internet
      • 12.3.1 How do I download a web page?
      • 12.3.2 How do I use a proxy?
    • 12.4 XML
      • 12.4.1 Is DOM supported?
      • 12.4.2 Is SAX supported?
      • 12.4.3 Is XPath supported?
    • 12.5 Threading
      • 12.5.1 Is multi-threading supported?
      • 12.5.2 How do I spawn a thread?
      • 12.5.3 How do I stop a thread?
      • 12.5.4 How do I use the thread pool?
      • 12.5.5 How do I know when my thread pool work item has completed?
      • 12.5.6 How do I prevent concurrent access to my data?
    • 12.6 Tracing
      • 12.6.1 Is there built-in support for tracing/logging?
      • 12.6.2 Can I redirect tracing to a file?
      • 12.6.3 Can I customise the trace output?
         
  • 13. Resources
    • 13.1 Recommended books
    • 13.2 Internet Resources
    • 13.3 Weblogs
    • 13.4 Sample code & utilities

1. Introduction

1.1 What is .NET?

That's difficult to sum up in a sentence. According to Microsoft, .NET is a "revolutionary new platform, built on open Internet protocols and standards, with tools and services that meld computing and communications in new ways".
A more practical definition would be that .NET is a new environment for developing and running software applications, featuring ease of development of web-based services, rich standard run-time services available to components written in a variety of programming languages, and inter-language and inter-machine interoperability.
Note that when the term ".NET" is used in this FAQ it refers only to the new .NET runtime and associated technologies. This is sometimes called the ".NET Framework". This FAQ does NOT cover any of the various other existing and new products/technologies that Microsoft are attaching the .NET name to (e.g. SQL Server.NET).

1.2 Does .NET only apply to people building web-sites?

No. If you write any Windows software (using ATL/COM, MFC, VB, or even raw Win32), .NET may offer a viable alternative (or addition) to the way you do things currently. Of course, if you do develop web sites, then .NET has lots to interest you - not least ASP.NET.

1.3 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.

1.4 When was the first version of .NET released?

The final version of the 1.0 SDK and runtime was 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.

1.5 What tools can I use to develop .NET applications?

There are a number of tools, described here in ascending order of cost:
  • .NET Framework SDK: The SDK is free and includes command-line compilers for C++, C#, and VB.NET and various other utilities to aid development.
  • ASP.NET Web Matrix: This is a free ASP.NET development environment from Microsoft. As well as a GUI development environment, the download includes a simple web server that can be used instead of IIS to host ASP.NET apps. This opens up ASP.NET development to users of Windows XP Home Edition, which cannot run IIS.
  • Microsoft Visual C# .NET Standard 2003: This is a cheap (around $100) version of Visual Studio limited to one language and also with limited wizard support. For example, there's no wizard support for class libraries or custom UI controls. Useful for beginners to learn with, or for savvy developers who can work around the deficiencies in the supplied wizards. As well as C#, there are VB.NET and C++ versions.
  • Microsoft Visual Studio.NET Professional 2003: If you have a license for Visual Studio 6.0, you can get the upgrade. You can also upgrade from VS.NET 2002 for a token $30. Visual Studio.NET includes support for all the MS languages (C#, C++, VB.NET) and has extensive wizard support.
At the top end of the price spectrum are the Visual Studio.NET 2003 Enterprise and Enterprise Architect editions. These offer extra features such as Visual Sourcesafe (version control), and performance and analysis tools. Check out the Visual Studio.NET Feature Comparison at http://msdn.microsoft.com/vstudio/howtobuy/choosing.asp.

1.6 What platforms does the .NET Framework run on?

The runtime supports 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 Windows XP and Windows 2000. 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 Matrix web server does run on XP Home.
The Mono project is attempting to implement the .NET framework on Linux.

1.7 What languages does the .NET Framework support?

MS provides compilers for C#, C++, VB and JScript. Other vendors have announced that they intend to develop .NET compilers for languages such as COBOL, Eiffel, Perl, Smalltalk and Python.

1.8 Will the .NET Framework go through a standardisation process?

From http://msdn.microsoft.com/net/ecma/: "On December 13, 2001, the ECMA General Assembly ratified the C# and common language infrastructure (CLI) specifications into international standards. The ECMA standards will be known as ECMA-334 (C#) and ECMA-335 (the CLI)."


2. Basic terminology

2.1 What is the CLR?

CLR = Common Language Runtime. The CLR is a set of standard resources that (in theory) any .NET program can take advantage of, regardless of programming language. Robert Schmidt (Microsoft) lists the following CLR resources in his MSDN PDC# article:
  • Object-oriented programming model (inheritance, polymorphism, exception handling, garbage collection)
  • Security model
  • Type system
  • All .NET base classes
  • Many .NET framework classes
  • Development, debugging, and profiling tools
  • Execution and code management
  • IL-to-native translators and optimizers
What this means is that in the .NET world, different programming languages will be more equal in capability than they have ever been before, although clearly not all languages will support all CLR services.

2.2 What is the CTS?

CTS = Common Type System. This is the range of types that the .NET runtime understands, and therefore that .NET applications can use. However note that not all .NET languages will support all the types in the CTS. The CTS is a superset of the CLS.

2.3 What is the CLS?

CLS = Common Language Specification. This is a subset of the CTS which all .NET languages are expected to support. The idea is that any program which uses CLS-compliant types can interoperate with any .NET program written in any language.
In theory this allows very tight interop between different .NET languages - for example allowing a C# class to inherit from a VB class.

2.4 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. The IL is then converted to machine code at the point where the software is installed, or at run-time by a Just-In-Time (JIT) compiler.

2.5 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 :-).

2.6 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. All C# and Visual Basic.NET code is managed by default. VS7 C++ code is not managed by default, but the compiler can produce managed code by specifying a command-line switch (/com+).
Managed data: This is data that is allocated and de-allocated by the .NET runtime's garbage collector. C# and VB.NET data is always managed. VS7 C++ data is unmanaged by default, even when using the /com+ switch, but it can be marked as managed using the __gc keyword.
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.

2.7 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).


3. Assemblies

3.1 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 a library. 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.

3.2 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 /target:module switch is used to generate a module instead of an assembly.

3.3 What is the difference between a private assembly and a shared assembly?

  • Location and visibility: 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 normally stored in the global assembly cache, which is a repository of assemblies maintained by the .NET runtime. Shared assemblies are usually libraries of code which many applications will find useful, e.g. the .NET framework classes.
     
  • Versioning: The runtime enforces versioning constraints only on shared assemblies, not on private assemblies.

3.4 How do assemblies find each other?

By searching directory paths. There are several factors which can affect the path (such as the AppDomain host, and application configuration files), but for private assemblies the search path is normally the application's directory and its sub-directories. For shared assemblies, the search path is normally same as the private assembly path plus the shared assembly cache.

3.5 How does assembly versioning work?

Each assembly has a version number called the compatibility version. Also each reference to an assembly (from another assembly) includes both the name and version of the referenced assembly.
The version number has four numeric parts (e.g. 5.5.2.33). Assemblies with either of the first two parts different are normally viewed as incompatible. If the first two parts are the same, but the third is different, the assemblies are deemed as 'maybe compatible'. If only the fourth part is different, the assemblies are deemed compatible. However, this is just the default guideline - it is the version policy that decides to what extent these rules are enforced. The version policy can be specified via the application configuration file.
Remember: versioning is only applied to shared assemblies, not private assemblies.


4. Application Domains

4.1 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 an application from other applications.
Win32 processes provide isolation by having distinct memory address spaces. This is effective, but it is expensive and doesn't scale well. 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.

4.2 How does an AppDomain get created?

AppDomains are usually created by hosts. Examples of hosts are the Windows Shell, ASP.NET and IE. When you run a .NET application from the command-line, the host is the Shell. The Shell creates a new AppDomain for every application.
AppDomains can also be explicitly created by .NET applications. Here is a C# sample which creates an AppDomain, creates an instance of an object inside it, and then executes one of the object's methods. Note that you must name the executable 'appdomaintest.exe' for this code to work as-is.
using System;
using System.Runtime.Remoting;
 
public class CAppDomainInfo : MarshalByRefObject
{
     public string GetAppDomainInfo()
     {
            return "AppDomain = " + AppDomain.CurrentDomain.FriendlyName;
     }
 
}
 
public class App
{
    public static int Main()
    {
            AppDomain ad = AppDomain.CreateDomain( "Andy's new domain", null, null );
            ObjectHandle oh = ad.CreateInstance( "appdomaintest", "CAppDomainInfo" );
            CAppDomainInfo adInfo = (CAppDomainInfo)(oh.Unwrap());
            string info = adInfo.GetAppDomainInfo();
            
            Console.WriteLine( "AppDomain info: " + info );
            return 0;
    }
}

4.3 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.


5. Garbage Collection

5.1 What is garbage collection?

Garbage collection is a system whereby a run-time component takes responsibility for managing the lifetime of objects and the heap memory that they occupy. This concept is not new to .NET - Java and many other languages/runtimes have used garbage collection for some time.

5.2 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 is an interesting thread in the archives, started by Chris Sells, about the implications of non-deterministic destruction of objects in C# .

5.3 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.
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.

5.4 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 for the client 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.

5.5 Does non-deterministic destruction affect the usage of COM objects from managed code?

Yes. When using a COM object from managed code, you are effectively relying on the garbage collector to call the final release on your object. If your COM object holds onto an expensive resource which is only cleaned-up after the final release, you may need to provide a new interface on your object which supports an explicit Dispose() method.

5.6 I've heard that Finalize methods should be avoided. Should I implement Finalize on my class?

An object with a Finalize method is more work for the garbage collector than an object without one. Also there are no guarantees about the order in which objects are Finalized, so there are issues surrounding access to other objects from the Finalize method. Finally, there is no guarantee that a Finalize method will get called on an object, so it should never be relied upon to do clean-up of an object's resources.
Microsoft recommend the following pattern:
public class CTest : IDisposable
{ 
     public void Dispose()
     {
            ... // Cleanup activities
            GC.SuppressFinalize(this); 
     } 
 
     ~CTest()       // C# syntax hiding the Finalize() method
     {
            Dispose(); 
     }
}
In the normal case the client calls Dispose(), the object's resources are freed, and the garbage collector is relieved of its Finalizing duties by the call to SuppressFinalize(). In the worst case, i.e. the client forgets to call Dispose(), there is a reasonable chance that the object's resources will eventually get freed by the garbage collector calling Finalize(). Given the limitations of the garbage collection algorithm this seems like a pretty reasonable approach.

5.7 Do I have any control over the garbage collection algorithm?

A little. For example, the System.GC class exposes a Collect method - this forces the garbage collector to collect all unreferenced objects immediately.

5.8 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.


6. Serialization

6.1 What is serialization?

Serialization is the process of converting an object into a stream of bytes. Deserialization is the opposite process of 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).

6.2 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 uses SoapFormatter/BinaryFormatter for remoting. Both are available for use in your own code.

6.3 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.

6.4 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.
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.

6.5 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.

6.6 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.

6.7 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.


7. Attributes

7.1 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've come across Keith Brown's universal delegator you'll be familiar with this idea.

7.2 Can I create my own metadata attributes?

Yes. Simply derive a class from System.Attribute and mark it with the AttributeUsage attribute. For example:
[AttributeUsage(AttributeTargets.Class)]
public class InspiredByAttribute : System.Attribute 
{ 
     public string InspiredBy;
     
     public InspiredByAttribute( string inspiredBy )
     {
            InspiredBy = inspiredBy;
     }
}
 
 
[InspiredBy("Andy Mc's brilliant .NET FAQ")]
class CTest
{
}
 
 
class CApp
{
     public static void Main()
     {              
            object[] atts = typeof(CTest).GetCustomAttributes(true);
 
            foreach( object att in atts )
                    if( att is InspiredByAttribute )
                            Console.WriteLine( "Class CTest was inspired by {0}", ((InspiredByAttribute)att).InspiredBy  );
     }
}

7.3 Can I create my own context attributes?

Yes. Take a look at Don Box's sample (called CallThreshold) at http://www.develop.com/dbox/dotnet/threshold/


8. Code Access Security

8.1 What is Code Access Security (CAS)?

CAS is the part of the .NET security model that determines whether or not a piece of 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.

8.2 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.)

8.3 Who defines the CAS code groups?

Microsoft defines some default ones, but you can modify these and even create your own. To see the code groups defined on your system, run 'caspol -lg' from the command-line. On my system it looks like this:
Level = Machine
 
Code Groups:
 
1.  All code: Nothing
   1.1.  Zone - MyComputer: FullTrust
      1.1.1.  Honor SkipVerification requests: SkipVerification
   1.2.  Zone - Intranet: LocalIntranet
   1.3.  Zone - Internet: Internet
   1.4.  Zone - Untrusted: Nothing
   1.5.  Zone - Trusted: Internet
   1.6.  StrongName - 0024000004800000940000000602000000240000525341310004000003
000000CFCB3291AA715FE99D40D49040336F9056D7886FED46775BC7BB5430BA4444FEF8348EBD06
F962F39776AE4DC3B7B04A7FE6F49F25F740423EBF2C0B89698D8D08AC48D69CED0FC8F83B465E08
07AC11EC1DCC7D054E807A43336DDE408A5393A48556123272CEEEE72F1660B71927D38561AABF5C
AC1DF1734633C602F8F2D5: Everything
Note the hierarchy of code groups - the top of the hierarchy is the most general ('All code'), which is then sub-divided into several groups, each of which in turn can be sub-divided. Also note that (somewhat counter-intuitively) a sub-group can be associated with a more permissive permission set than its parent.

8.4 How do I define my own code group?

Use caspol. For example, suppose you trust code from www.mydomain.com and you want it have full access to your system, but you want to keep the default restrictions for all other internet sites. To achieve this, you would add a new code group as a sub-group of the 'Zone - Internet' group, like this:
caspol -ag 1.3 -site www.mydomain.com FullTrust 
Now if you run caspol -lg you will see that the new group has been added as group 1.3.1:
...
   1.3.  Zone - Internet: Internet
      1.3.1.  Site - www.mydomain.com: FullTrust
...
Note that the numeric label (1.3.1) is just a caspol invention to make the code groups easy to manipulate from the command-line. The underlying runtime never sees it.

8.5 How do I change the permission set for a code group?

Use caspol. If you are the machine administrator, you can operate at the 'machine' level - which means not only that the changes you make become the default for the machine, but also that users cannot change the permissions to be more permissive. If you are a normal (non-admin) user you can still modify the permissions, but only to make them more restrictive. For example, to allow intranet code to do what it likes you might do this:
caspol -cg 1.2 FullTrust
Note that because this is more permissive than the default policy (on a standard system), you should only do this at the machine level - doing it at the user level will have no effect.

8.6 Can I create my own permission set?

Yes. Use caspol -ap, specifying an XML file containing the permissions in the permission set. To save you some time, here is a sample file corresponding to the 'Everything' permission set - just edit to suit your needs. When you have edited the sample, add it to the range of available permission sets like this:
caspol -ap samplepermset.xml
Then, to apply the permission set to a code group, do something like this:
caspol -cg 1.3 SamplePermSet
(By default, 1.3 is the 'Internet' code group)

8.7 I'm having some trouble with CAS. How can I diagnose my 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.

8.8 I can't be bothered with all this CAS stuff. Can I turn it off?

Yes, as long as you are an administrator. Just run:
caspol -s off


9. Intermediate Language (IL)

9.1 Can I look at the IL for an assembly?

Yes. MS supply a tool called Ildasm which can be used to view the metadata and IL for an assembly.

9.2 Can source code be reverse-engineered from IL?

Yes, it is often relatively straightforward to regenerate high-level source (e.g. C#) from IL.

9.3 How can I stop my code being reverse-engineered from IL?

There is currently no simple way to stop code being reverse-engineered from IL. In future it is likely that IL obfuscation tools will become available, either from MS or from third parties. 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.

9.4 Can I write IL programs directly?

 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.

9.5 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.


10. Implications for COM

10.1 Is COM dead?

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:

FWIW my view is as follows: COM is many things, and it's different things to different people. But to me, COM is fundamentally about how little blobs of code find other little blobs of code, and how they communicate with each other when they find each other. COM specifies precisely how this location and communication takes place. In a 'pure' .NET world, consisting entirely of .NET objects, little blobs of code still find each other and talk to each other, but they don't use COM to do so. They use a model which is similar to COM in some ways - for example, type information is stored in a tabular form packaged with the component, which is quite similar to packaging a type library with a COM component. But it's not COM.
So, does this matter? Well, I don't really care about most of the COM stuff going away - I don't care that finding components doesn't involve a trip to the registry, or that I don't use IDL to define my interfaces. But there is one thing that I wouldn't like to go away - I wouldn't like to lose the idea of interface-based development. COM's greatest strength, in my opinion, is its insistence on a cast-iron separation between interface and implementation. Unfortunately, the .NET framework seems to make no such insistence - it lets you do interface-based development, but it doesn't insist. Some people would argue that having a choice can never be a bad thing, and maybe they're right, but I can't help feeling that maybe it's a backward step.

10.2 Is DCOM dead?

Pretty much, for .NET developers. The .NET Framework has a new remoting model which is not based on DCOM. Of course DCOM will still be used in interop scenarios.

10.3 Is MTS/COM+ dead?

No. The approach for the first .NET release is 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 are provided to try to make this as painless as possible. The PDC release of the .NET SDK includes interop support for core services (JIT activation, transactions) but not some of the higher level services (e.g. COM+ Events, Queued components).
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.

10.4 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.
Here's a simple example for those familiar with ATL. First, create an ATL component which implements the following IDL:
import "oaidl.idl"; 
import "ocidl.idl";
 
[
     object,
     uuid(EA013F93-487A-4403-86EC-FD9FEE5E6206),
     helpstring("ICppName Interface"), 
     pointer_default(unique), 
     oleautomation
] 
 
interface ICppName : IUnknown
{ 
     [helpstring("method SetName")] HRESULT SetName([in] BSTR name); 
     [helpstring("method GetName")] HRESULT GetName([out,retval] BSTR *pName ); 
}; 
 
[ 
     uuid(F5E4C61D-D93A-4295-A4B4-2453D4A4484D), 
     version(1.0),
     helpstring("cppcomserver 1.0 Type Library")
] 
library CPPCOMSERVERLib 
{
     importlib("stdole32.tlb");
     importlib("stdole2.tlb"); 
     [
            uuid(600CE6D9-5ED7-4B4D-BB49-E8D5D5096F70),  
            helpstring("CppName Class") 
     ]
     coclass CppName
     { 
            [default] interface ICppName; 
     };
};
When you've built the component, you should get a typelibrary. Run the TLBIMP utility on the typelibary, like this:
tlbimp cppcomserver.tlb
If successful, you will get a message like this:
Typelib imported successfully to CPPCOMSERVERLib.dll
You now need a .NET client - let's use C#. Create a .cs file containing the following code:
using System;
using CPPCOMSERVERLib; 
 
public class MainApp 
{ 
     static public void Main() 
     { 
            CppName cppname = new CppName();
            cppname.SetName( "bob" ); 
            Console.WriteLine( "Name is " + cppname.GetName() ); 
     }
}
Note that we are using the type library name as a namespace, and the COM class name as the class. Alternatively we could have used CPPCOMSERVERLib.CppName for the class name and gone without the using CPPCOMSERVERLib statement.
Compile the C# code like this:
csc /r:cppcomserverlib.dll csharpcomclient.cs
Note that the compiler is being told to reference the DLL we previously generated from the typelibrary using TLBIMP.
You should now be able to run csharpcomclient.exe, and get the following output on the console:
Name is bob

10.5 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.
Here's a simple example. Create a C# file called testcomserver.cs and put the following in it:
          
using System; 
 
namespace AndyMc 
{ 
     [ClassInterface(ClassInterfaceType.AutoDual)]
     public class CSharpCOMServer
     { 
            public CSharpCOMServer() {} 
            public void SetName( string name ) { m_name = name; } 
            public string GetName() { return m_name; }  
            private string m_name; 
     }          
}
Then compile the .cs file as follows:
csc /target:library testcomserver.cs
You should get a dll, which you register like this:
regasm testcomserver.dll /tlb:testcomserver.tlb /codebase
Now you need to create a client to test your .NET COM component. VBScript will do - put the following in a file called comclient.vbs:
Dim dotNetObj 
Set dotNetObj = CreateObject("AndyMc.CSharpCOMServer") 
dotNetObj.SetName ("bob") 
MsgBox "Name is " & dotNetObj.GetName()
and run the script like this:
wscript comclient.vbs
And hey presto you should get a message box displayed with the text "Name is bob".

10.6 Is ATL redundant in the .NET world?

Yes, if you are writing applications that live inside the .NET framework. Of course many developers may wish to continue using ATL to write C++ COM components that live outside the framework, but if you are inside you will almost certainly want to use C#. Raw C++ (and therefore ATL which is based on it) doesn't have much of a place in the .NET world - it's just too near the metal and provides too much flexibility for the runtime to be able to manage it.


11. Miscellaneous

11.1 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 site at http://www.cookcomputing.com/xmlrpc/xmlrpc.shtml.

11.2 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, 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 ); 
     }
}        


12. Class Library

12.1 File I/O

12.1.1 How do I read from a text file?

First, use a System.IO.FileStream object to open the file:
FileStream fs = new FileStream( @"c:\test.txt", FileMode.Open, FileAccess.Read );
FileStream inherits from Stream, so you can wrap the FileStream object with a StreamReader object. This provides a nice interface for processing the stream line by line:
StreamReader sr = new StreamReader( fs );
string curLine;
while( (curLine = sr.ReadLine()) != null )
     Console.WriteLine( curLine );
Finally close the StreamReader object:
sr.Close();
Note that this will automatically call Close() on the underlying Stream object, so an explicit fs.Close() is not required.

12.1.2 How do I write to a text file?

Similar to the read example, except use StreamWriter instead of StreamReader.

12.1.3 How do I read/write binary files?

Similar to text files, except wrap the FileStream object with a BinaryReader/Writer object instead of a StreamReader/Writer object.

12.2 Text Processing

12.2.1 Are regular expressions supported?

Yes. Use the System.Text.RegularExpressions.Regex class. For example, the following code updates the title in an HTML file:
FileStream fs = new FileStream( "test.htm", FileMode.Open, FileAccess.Read );
StreamReader sr = new StreamReader( fs ); 
            
Regex r = new Regex( "<TITLE>(.*)</TITLE>" ); 
string s; 
while( (s = sr.ReadLine()) != null ) 
{
     if( r.IsMatch( s ) )  
            s = r.Replace( s, "<TITLE>New and improved ${1}</TITLE>" );
     Console.WriteLine( s ); 
}

12.3 Internet

12.3.1 How do I download a web page?

First use the System.Net.WebRequestFactory class to acquire a WebRequest object:
WebRequest request = WebRequest.Create( "http://localhost" );
Then ask for the response from the request:
WebResponse response = request.GetResponse();
The GetResponse method blocks until the download is complete. Then you can access the response stream like this:
Stream s = response.GetResponseStream();
 
// Output the downloaded stream to the console
StreamReader sr = new StreamReader( s );
string line;
while( (line = sr.ReadLine()) != null )
     Console.WriteLine( line );
Note that WebRequest and WebReponse objects can be downcast to HttpWebRequest and HttpWebReponse objects respectively, to access http-specific functionality.

12.3.2 How do I use a proxy?

Two approaches - to affect all web requests do this:
System.Net.GlobalProxySelection.Select = new WebProxy( "proxyname", 80 );
Alternatively, to set the proxy for a specific web request, do this:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create( "http://localhost" );
request.Proxy = new WebProxy( "proxyname", 80 );


12.4 XML

12.4.1 Is DOM supported?

Yes. Take this example XML document:
<PEOPLE>
     <PERSON>Fred</PERSON>
     <PERSON>Bill</PERSON>  
</PEOPLE>   
This document can be parsed as follows:
XmlDocument doc = new XmlDocument();
doc.Load( "test.xml" );
 
XmlNode root = doc.DocumentElement;
 
foreach( XmlNode personElement in root.ChildNodes )
     Console.WriteLine( personElement.FirstChild.Value.ToString() );
The output is:
Fred
Bill

12.4.2 Is SAX supported?

No. Instead, a new XmlReader/XmlWriter API is offered. Like SAX it is stream-based but it uses a 'pull' model rather than SAX's 'push' model. Here's an example:
XmlTextReader reader = new XmlTextReader( "test.xml" );
 
while( reader.Read() )
{
     if( reader.NodeType == XmlNodeType.Element && reader.Name == "PERSON" )
     {
            reader.Read(); // Skip to the child text
            Console.WriteLine( reader.Value );
     }
}

12.4.3 Is XPath supported?

Yes, via the XPathXXX classes:
XPathDocument xpdoc = new XPathDocument("test.xml");
XPathNavigator nav = xpdoc.CreateNavigator();
XPathExpression expr = nav.Compile("descendant::PEOPLE/PERSON");
 
XPathNodeIterator iterator = nav.Select(expr);
while (iterator.MoveNext())
     Console.WriteLine(iterator.Current);


12.5 Threading

12.5.1 Is multi-threading supported?

Yes, there is extensive support for multi-threading. New threads can be spawned, and there is a system-provided threadpool which applications can use.

12.5.2 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()
     {
            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();

12.5.3 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.

12.5.4 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 );
     }
}

12.5.5 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.

12.5.6 How do I prevent concurrent access to my data?

Each object has a concurrency lock (critical section) associated with it. The System.Threading.Monitor.Enter/Exit methods are used to acquire and release this lock. For example, instances of the following class only allow one thread at a time to enter method f():
class C
{
     public void f()
     {
            try
            {
                    Monitor.Enter(this);
                    ...
            }
            finally
            {
                    Monitor.Exit(this);
            }
     }
}
C# has a 'lock' keyword which provides a convenient shorthand for the code above:
class C
{
     public void f()
     {
            lock(this)
            {
                    ...
            }
     }
}
Note that calling Monitor.Enter(myObject) does NOT mean that all access to myObject is serialized. It means that the synchronisation lock associated with myObject has been acquired, and no other thread can acquire that lock until Monitor.Exit(o) is called. In other words, this class is functionally equivalent to the classes above:
class C
{
     public void f()
     {
            lock( m_object )
            {
                    ...
            }
     }
     
     private m_object = new object();
}


12.6 Tracing

12.6.1 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.

12.6.2 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.

12.6.3 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}", 
                    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.


13. Resources

13.1 Recommended books

I recommend the following books, either because I personally like them, or because I think they are well regarded by other .NET developers. (Note that I get a commission from Amazon if you buy a book after following one of these links.)
  • Applied Microsoft .NET Framework Programming - Jeffrey Richter
    Much anticipated, mainly due to Richter's superb Win32 books, and most people think it delivers. The 'applied' is a little misleading - this book is mostly about how the .NET Framework works 'under the hood'. Examples are in C#, but there is also a separate VB edition of the book.
     
  • Essential .NET Volume 1, The Common Language Runtime - Don Box
    Don's books don't always demonstrate the same dazzling ability to communicate that he exhibits in person, but they are always chock full of technical detail you just don't get other places. Essential .NET is likely to become a must-read for all .NET developers.
     
  • Programming Windows with C# - Charles Petzold
    Another slightly misleading title - this book is solely about GUI programming - Windows Forms and GDI+. Well written, with comprehensive coverage. My only (minor) criticism is that the book sticks closely to the facts, without offering a great deal in the way of 'tips and tricks' for real-world apps.
     
  • Developing Applications with Visual Studio.NET - Richard Grimes
    Covers lots of interesting topics that other books don't, including ATL7, Managed C++, internationalization, remoting, as well as the more run-of-the-mill CLR and C# stuff. Also a lot of info on the Visual Studio IDE. This book is most suitable for reasonably experienced C++ programmers.
     
  • C# and the .NET Platform - Andrew Troelsen
    Regarded by many as the best all round C#/.NET book. Wide coverage including Windows Forms, COM interop, ADO.NET, ASP.NET etc. Troelsen also has a respected VB.NET book called Visual Basic .NET and the .NET Platform: An Advanced Guide.
     
  • Programming Microsoft Visual Basic .NET - Francesco Balena
    Balena is a reknowned VB-er, and the reviews of his VB.NET book are glowing.
     
  • .NET and COM - The Complete Interoperability Guide - Adam Nathan
    Widely regarded as the bible of .NET/COM interop.
     
  • Advanced .NET Remoting - Ingo Rammer
    Widely recommended.
     

13.2 Internet Resources


*********************************************************************************


ASP.NET Questions

Q. Explain the differences between Server-side and Client-side code?
A. Server-side code executes on the server. Client-side code executes in the context of the clients' browser.hudihudi.com
Q. What are some ways to manage state in an ASP.Net application?
A. Session objects, Application objects, ViewState, cookies, hidden form fields.

Q. What does the "EnableViewState" property do? Why would I want it on or off?
A. It allows page objects to save their state in a Base64 encoded string in the page HTML. One should only have it enabled when needed because it adds to the page size and can get fairly large for complex pages with many controls. (It takes longer to download the page).
Q. What is the difference between Server.Transfer and Response.Redirect? Why would I choose one over the other?
A. Server.Transfer transfers excution directly to another page. Response.Redirect sends a response to the client and directs the client (the browser) to load the new page (it causes a roundtrip). If you don't need to execute code on the client, Transfer is more efficient.
Q. How can I maintain Session state in a Web Farm or Web Garden?
A. Use a State Server or SQL Server to store the session state.
Q. What base class do all Web Forms inherit from?
A. The Page class.
Q. What does WSDL stand for? What does it do?
A.(Web Services Description Language). It describes the interfaces and other information of a web service.
Q. Which WebForm Validator control would you use if you needed to make sure the values in two different WebForm controls matched?
A. CompareValidator Control

Q. What property must you set, and what method must you call in your code, in order to bind the data from some data source to the Repeater control?
A. You must set the DataSource property and call the DataBind method.hudihudi.com
What is the main difference between an ASP.NET Web application and a traditional Windows application.
ASP.NET Web applications runs under common language runtime using managed code where as Unmanaged Windows application runs under Windows using unmanaged code.


What are the two main parts of the .NET Framework?
The two main parts of the .NET Framework are
The common language runtime (CLR).
The .NET Framework class library.
When can’t you use ASP.NET to create a Web application?
When you are developing for non–Microsoft Windows Web servers, such as Linux/Apache.
List the four major differences between Web and Windows applications.
·         Web forms cannot use the standard Windows controls. Instead, they use server controls, HTML controls, user controls, or custom controls created specially for Web forms.
·         Web applications are displayed in a browser. Windows applications display their own windows and have more control over how those windows are displayed.
·         Web forms are instantiated on the server, sent to the browser, and destroyed immediately. Windows forms are instantiated, exist for as long as needed, and are destroyed.
·         Web applications run on a server and are displayed remotely on clients. Windows applications run on the same machine they are displayed on.

Describe the life cycle of a Web application: When are Web forms instantiated and how long do they exist?
A Web application starts with the first request for a resource within the application’s boundaries. Web forms are instantiated when they are requested. They are processed by the server and are abandoned immediately after the server sends its response to the client. A Web application ends after all client sessions end.
How do you preserve persistent data, such as simple variables, in a Web application?
You can preserve data in state variables, such as ApplicationState, SessionState, or ViewState.
How does the .NET Framework organize its classes?
The .NET Framework uses namespaces to organize its classes.
In Visual Basic .NET, what is the difference between a class module and a code module?
Class modules are instantiated at run time to create objects that provide separate storage for variables and properties in each instance. Code modules do not have instances, so any module-level variables they use are shared among calls to the module’s procedures.
In Visual C#, how do you declare a method to make it available without having to first instantiate an object from the class?
To create a method that can be called without instantiating an object, declare that method as static.
How do you call a member of a base class from within a derived class?
To refer to a member of a base class in Visual Basic .NET, use the MyBase keyword. To refer to a member of a base class in Visual C#, use the base keyword.
Where would you save the following data items so that they persist between requests to a Web form?
·         A control created at run time
·         An object that provides services to all users
·         User preferences
·         Save controls created at run time in the Page object’s ViewState.
·         Save objects that provide services to all users in the Application state.
·         Save user preferences in SessionState.
What is the main difference between the Button server control and the Button HTML control?
When clicked, the Button server control triggers an ASP.NET Click event procedure on the server. The Button HTML control triggers the event procedure indicated in the button’s onclick attribute, which runs on the client.
How do you get several RadioButton controls to interoperate on a Web form so that only one of the RadioButton controls can have a value of True/true at any given time?
Set the GroupName property of each RadioButton to the same name.
Why does ASP.NET perform validation on both the client and the server?
Client-side validation helps avoid round-trips to the server. Validating on the client ensures that the data is valid before it is submitted, in most cases. However, because validation might be turned off (or maliciously hacked) on the client, data must be revalidated on the server side. This provides full assurance that the data is valid while avoiding as many round-trips as possible.
What types of validation would you use to verify that a user entered a valid ­customer number?
You would use a RequiredFieldValidator and a RegularExpressionValidator. If you have access to a list of expected customer numbers, you could replace the RegularExpressionValidator with a CustomValidator that checked the list.
What is wrong with the following line of code?
Server.Transfer("Default.htm");
You can’t use the Transfer method with HTML pages. It works only with .aspx pages.
Why can’t you open a new browser window from within server code?
Server code executes on the server, whereas the new window is created on the client. You need to use client-side code to do things that affect the client, such as upload files, display new windows, or navigate back in history.
What steps would you follow and what objects would you use to quickly find the number of records in a database table?
There are two ways to accomplish this task:
·         Use a database connection and a command object to execute a SQL command that re-turns the number of rows in the table.
·         Use a database connection and data adapter object to create a data set for the table, and then get the number rows in the data set.
How do typed data sets differ from untyped data sets, and what are the advantages of typed data sets?
Typed data sets use explicit names and data types for their members, whereas untyped data sets use collections to refer to their members. The following examples show a typed reference vs. an untyped reference to a data item:
// Typed reference to the Contacts table's HomePhone column.
DataSet1.Contacts.HomePhoneColumn.Caption = "@Home";
// Untyped reference to the Contacts table's HomePhone column.
DataSet1.Tables["Contacts"].Columns["HomePhone"].Caption = "@Home";
Typed data sets do error checking at design time. This error checking helps catch typos and type mismatch errors, which would be detected only at run time with untyped data sets.
How do you call a stored procedure?
Create a command object, set the object’s CommandText property to the name of the stored procedure, and set the CommandType property to StoredProcedure. To execute the stored procedure, use the command object’s ExecuteNonQuery, ExcecuteScalar, ExecuteReader, or ExecutelXmlReader method. For example, the following code calls the Ten Most Expensive Products stored procedure on the Northwind Traders database:
// Create a connection for NorthWind Trader's database.
SqlConnection connNWind = new SqlConnection("integrated security=SSPI;" +
"data source=(local);initial catalog=Northwind");
// Create a command object to execute.
SqlCommand cmdTopTen = new SqlCommand(connNWind);
cmdTopTen.CommandText = "Ten Most Expensive Products";
// Set the command properties.
cmdTopTen.CommandType = CommandType.StoredProcedure;
// Create a data reader object to get the results.
SqlDataReader drdTopTen;
// Open the connection.
connNWind.Open();
// Excecute the stored procedure.
drdTopTen = cmdTopTen.ExecuteReader();
Explain the difference between handling transactions at the data set level and at the database level.
Data sets provide implicit transactions, because changes to the data set aren’t made permanent in the database until you call the Update method. To handle transactions in a data set, process the Update method and check for errors. If errors occur during an update, none of the changes from the data set is made in the database. You can try to correct the error and resubmit the update, or you can roll back the changes to the data set using the RejectChanges method.

Databases provide explicit transactions through the Transaction object. You create a Transaction object from a database connection and then assign that Transaction object to the commands you want to include in the transaction through the command object’s Transaction property. As you perform the commands on the database, you check for errors. If errors occur, you can either try to correct them and resubmit the command, or you can restore the state of the database using the Transaction object’s RollBack method. If no errors occur, you can make the changes permanent by calling the transaction object’s Commit method. 
Explain why exception handling is important to a completed application.
When an unhandled exception occurs in an application, the application stops—the user can’t proceed, and any work he or she did immediately prior to the exception is lost. Exception handling provides a way to intercept and correct unusual occurrences that would otherwise cause these problems.
List two different exception-handling approaches in ASP.NET Web applications.
Exceptions can be handled in exception-handling blocks using the Try, Catch, and Finally keywords in Visual Basic .NET or the try, catch, and finally keywords in Visual C#. They can also be handled using Error event procedures at the Global, Application, or Page levels using the Server object’s GetLastError and ClearError methods.
Describe the purpose of error pages and why they are needed.
Because Web applications run over the Internet, some exceptions occur outside the scope of the application. This means that your application can’t respond directly to these exceptions. These types of exceptions are identified by HTTP response codes, which IIS can respond to by displaying custom error pages listed in your application’s Web.config file.
Explain why tracing helps with exception handling.
Tracing allows you to record unusual events while your application is running, without users being aware of it. If an unanticipated exception occurs, your application can write a message to the trace log, which helps you diagnose problems during testing and after deployment. 
1.What is Code Access Security (CAS)? How does CAS work? 
CAS is the part of the .NET security model that determines whether or not a piece of 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.
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.)
2. What are object pooling and connection pooling and difference? Where do we set the Min and Max Pool size for connection pooling? 
Object pooling is a COM+ service that enables you to reduce the overhead of creating each object from scratch. When an object is activated, it is pulled from the pool. When the object is deactivated, it is placed back into the pool to await the next request. You can configure object pooling by applying the ObjectPoolingAttribute attribute to a class that derives from the System.EnterpriseServices.ServicedComponent class. Object pooling lets you control the number of connections you use, as opposed to connection pooling, where you control the maximum number reached.
Following are important differences between object pooling and connection pooling:
1. Creation. When using connection pooling, creation is on the same thread, so if there is nothing in the pool, a connection is created on your behalf. With object pooling, the pool might decide to create a new object. However, if you have already reached your maximum, it instead gives you the next available object. This is crucial behavior when it takes a long time to create an object, but you do not use it for very long.
2. Enforcement of minimums and maximums. This is not done in connection pooling. The maximum value in object pooling is very important when trying to scale your application. You might need to multiplex thousands of requests to just a few objects. (TPC/C benchmarks rely on this.)

COM+ object pooling is identical to what is used in .NET Framework managed SQL Client connection pooling. For example, creation is on a different thread and minimums and maximums are enforced.     

3. What is a WebService and what is the underlying protocol used in it? Namespace?
Web Services are applications delivered as a service on the Web. Web services allow for programmatic access of business logic over the Web. Web services typically rely on XML-based protocols, messages, and interface descriptions for communication and access. Web services are designed to be used by other programs or applications rather than directly by end user. Programs invoking a Web service are called clients. SOAP over HTTP is the most commonly used protocol for invoking Web services.

4. What is serialization in .NET? What are the ways to control serialization?
Serialization is the process of converting an object into a stream of bytes. Deserialization is the opposite process of 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).Serialization can be defined as the process of storing the state of an object to a storage medium. During this process, the public and private fields of the object and the name of the class, including the assembly containing the class, are converted to a stream of bytes, which is then written to a data stream. When the object is subsequently deserialized, an exact clone of the original object is created.
1. Binary serialization preserves type fidelity, which is useful for preserving the state of an object between different invocations of an application. For example, you can share an object between different applications by serializing it to the clipboard. You can serialize an object to a stream, disk, memory, over the network, and so forth. Remoting uses serialization to pass objects "by value" from one computer or application domain to another.
2. XML serialization serializes only public properties and fields and does not preserve type fidelity. This is useful when you want to provide or consume data without restricting the application that uses the data. Because XML is an open standard, it is an attractive choice for sharing data across the Web. SOAP is an open standard, which makes it an attractive choice.

5 Explain SOAP, WSDL, UDDI in brief.Namespace? 
SOAP:-SOAP is an XML-based messaging framework specifically designed for exchanging formatted data across the Internet, for example using request and reply messages or sending entire documents. SOAP is simple, easy to use, and completely neutral with respect to operating system, programming language, or distributed computing platform.After SOAP became available as a mechanism for exchanging XML messages among enterprises (or among disparate applications within the same enterprise), a better way was needed to describe the messages and how they are exchanged.
WSDL :-The Web Services Description Language (WSDL) is a particular form of an XML Schema, developed by Microsoft and IBM for the purpose of defining the XML message, operation, and protocol mapping of a web service accessed using SOAP or other XML protocol. WSDL defines web services in terms of "endpoints" that operate on XML messages. The WSDL syntax allows both the messages and the operations on the messages to be defined abstractly, so they can be mapped to multiple physical implementations. The current WSDL spec describes how to map messages and operations to SOAP 1.1, HTTP GET/POST, and MIME. WSDL creates web service definitions by mapping a group of endpoints into a logical sequence of operations on XML messages. The same XML message can be mapped to multiple operations (or services) and bound to one or more communications protocols (using "ports").
UDDI :-The Universal Description, Discovery, and Integration (UDDI) framework defines a data model (in XML) and SOAP APIs for registration and searches on business information, including the web services a business exposes to the Internet. UDDI is an independent consortium of vendors, founded by Microsoft, IBM, and Ariba, for the purpose of developing an Internet standard for web service description registration and discovery. Microsoft, IBM, and Ariba also are hosting the initial deployment of a UDDI service, which is conceptually patterned after DNS (the Internet service that translates URLs into TCP addresses). UDDI uses a private agreement profile of SOAP (i.e. UDDI doesn't use the SOAP serialization format because it's not well suited to passing complete XML documents (it's aimed at RPC style interactions). The main idea is that businesses use the SOAP APIs to register themselves with UDDI, and other businesses search UDDI when they want to discover a trading partner, for example someone from whom they wish to procure sheet metal, bolts, or transistors. The information in UDDI is categorized according to industry type and geographical location, allowing UDDI consumers to search through lists of potentially matching businesses to find the specific one they want to contact. Once a specific business is chosen, another call to UDDI is made to obtain the specific contact information for that business. The contact information includes a pointer to the target business's WSDL or other XML schema file describing the web service that the target business publishes. .

6. What is Method Overriding? How to override a function in C#? 
An override method provides a new implementation of a member inherited from a base class. The method overridden by an override declaration is known as the overridden base method. The overridden base method must have the same signature as the override method.
Use the override modifier to modify a method, a property, an indexer, or an event. You cannot override a non-virtual or static method. The overridden base method must be virtual, abstract, or override

7. How can we check if all validation and controls are valid or proper?How can we force to run all validation control to run? 
By using Page.IsValid() property we can check if all validation and controls are valid or proper by using Page.Validate we can force to run all validation control to run

8. What is the difference between Server.Transfer and Response.Redirect? Why would I choose one over the other? 
Server.Transfer transfers page processing from one 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.

9.What is JIT (just in time)? how it works? 
Before Microsoft intermediate language (MSIL) can be executed, it must be converted by a .NET Framework just-in-time (JIT) compiler to native code, which is CPU-specific code that runs on the same computer architecture as the JIT compiler. Rather than using time and memory to convert all the MSIL in a portable executable (PE) file to native code, it converts the MSIL as it is needed during execution and stores the resulting native code so that it is accessible for subsequent calls. The runtime supplies another mode of compilation called install-time code generation. The install-time code generation mode converts MSIL to native code just as the regular JIT compiler does, but it converts larger units of code at a time, storing the resulting native code for use when the assembly is subsequently loaded and executed. As part of compiling MSIL to native code, code must pass a verification process unless an administrator has established a security policy that allows code to bypass verification. Verification examines MSIL and metadata to find out whether the code can be determined to be type safe, which means that it is known to access only the memory locations it is authorized to access.

10 .Difference between DataReader and DataAdapter / DataSet and DataAdapter? 
You can use the ADO.NET DataReader to retrieve a read-only, forward-only stream of data from a database. Using the DataReader can increase application performance and reduce system overhead because only one row at a time is ever in memory. After creating an instance of the Command object, you create a DataReader by calling Command.ExecuteReader to retrieve rows from a data source, as shown in the following example. SqlDataReader myReader = myCommand.ExecuteReader(); You use the Read method of the DataReader object to obtain a row from the results of the query. while (myReader.Read()) Console.WriteLine("\t{0}\t{1}", myReader.GetInt32(0), myReader.GetString(1)); myReader.Close(); The DataSet is a memory-resident representation of data that provides a consistent relational programming model regardless of the data source. It can be used with multiple and differing data sources, used with XML data, or used to manage data local to the application. The DataSet represents a complete set of data including related tables, constraints, and relationships among the tables. The methods and objects in a DataSet are consistent with those in the relational database model. The DataSet can also persist and reload its contents as XML and its schema as XML Schema definition language (XSD) schema. The DataAdapter serves as a bridge between a DataSet and a data source for retrieving and saving data. The DataAdapter provides this bridge by mapping Fill, which changes the data in the DataSet to match the data in the data source, and Update, which changes the data in the data source to match the data in the DataSet. If you are connecting to a Microsoft SQL Server database, you can increase overall performance by using the SqlDataAdapter along with its associated SqlCommand and SqlConnection. For other OLE DB-supported databases, use the DataAdapter with its associated OleDbCommand and OleDbConnection objects.

11. Differences between dataset.clone and dataset.copy? 
Clone - Copies the structure of the DataSet, including all DataTable schemas, relations, and constraints. Does not copy any data.
Copy - Copies both the structure and data for this DataSet.

12. What is State Management in .Net and how many ways are there to maintain a state in .Net? What is view state? 
Web pages are recreated each time the page is posted to the server. In traditional Web programming, this would ordinarily mean that all information associated with the page and the controls on the page would be lost with each round trip. To overcome this inherent limitation of traditional Web programming, the ASP.NET page framework includes various options to help you preserve changes — that is, for managing state. The page framework includes a facility called view state that automatically preserves property values of the page and all the controls on it between round trips. However, you will probably also have application-specific values that you want to preserve. To do so, you can use one of the state management options.
Client-Based State Management Options:
View State
Hidden Form Fields
Cookies
Query Strings
Server-Based State Management Options
Application State
Session State
Database Support

13. Difference between web services & remoting? Namespace? 
ASP.NET Web Services .NET Remoting Protocol Can be accessed only over HTTP Can be accessed over any protocol (including TCP, HTTP, SMTP and so on) State Management Web services work in a stateless environment Provide support for both stateful and stateless environments through Singleton and SingleCall objects Type System Web services support only the datatypes defined in the XSD type system, limiting the number of objects that can be serialized. Using binary communication, .NET Remoting can provide support for rich type system Interoperability Web services support interoperability across platforms, and are ideal for heterogeneous environments. .NET remoting requires the client be built using .NET, enforcing homogenous environment. Reliability Highly reliable due to the fact that Web services are always hosted in IIS Can also take advantage of IIS for fault isolation. If IIS is not used, application needs to provide plumbing for ensuring the reliability of the application. Extensibility Provides extensibility by allowing us to intercept the SOAP messages during the serialization and deserialization stages. Very extensible by allowing us to customize the different components of the .NET remoting framework. Ease-of-Programming Easy-to-create and deploy. Complex to program.

14 .What is MSIL, IL?
When compiling to managed code, the compiler translates your source code into Microsoft intermediate language (MSIL), which is a CPU-independent set of instructions that can be efficiently converted to native code. MSIL includes instructions for loading, storing, initializing, and calling methods on objects, as well as instructions for arithmetic and logical operations, control flow, direct memory access, exception handling, and other operations. Microsoft intermediate language (MSIL) is a language used as the output of a number of compilers and as the input to a just-in-time (JIT) compiler. The common language runtime includes a JIT compiler for converting MSIL to native code.

15. What is strong name?
A name that consists of an assembly's identity—its simple text name, version number, and culture information (if provided)—strengthened by a public key and a digital signature generated over the assembly.

16. What is exception handling? 
When an exception occurs, the system searches for the nearest catch clause that can handle the exception, as determined by the run-time type of the exception. First, the current method is searched for a lexically enclosing try statement, and the associated catch clauses of the try statement are considered in order. If that fails, the method that called the current method is searched for a lexically enclosing try statement that encloses the point of the call to the current method. This search continues until a catch clause is found that can handle the current exception, by naming an exception class that is of the same class, or a base class, of the run-time type of the exception being thrown. A catch clause that doesn't name an exception class can handle any exception. Once a matching catch clause is found, the system prepares to transfer control to the first statement of the catch clause. Before execution of the catch clause begins, the system first executes, in order, any finally clauses that were associated with try statements more nested that than the one that caught the exception.
Exceptions that occur during destructor execution are worth special mention. If an exception occurs during destructor execution, and that exception is not caught, then the execution of that destructor is terminated and the destructor of the base class (if any) is called. If there is no base class (as in the case of the object type) or if there is no base class destructor, then the exception is discarded.

17 .What is the managed and unmanaged code in .net?
The .NET Framework provides a run-time environment called the Common Language Runtime, which manages the execution of code and provides services that make the development process easier. Compilers and tools expose the runtime's functionality and enable you to write code that benefits from this managed execution environment. Code that you develop with a language compiler that targets the runtime is called managed code; it benefits from features such as cross-language integration, cross-language exception handling, enhanced security, versioning and deployment support, a simplified model for component interaction, and debugging and profiling services.

18 .What is the namespace threading in .net? 
System.Threading.Thread How to encode string string ss="pervej"; string encode=Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(ss)); Response.Write(encode); 

********************************************************************************


.Net Object Oriented Programming Concepts

Class: 
Class is concrete representation of an entity. It represents a group of objects, which posses similar attributes and behavior.
 
Provides Abstraction and Encapsulations. A category name that can be given to group of objects of similar kind.
 

Object:
 
Object represents/resembles a Physical/real entity. An object is simply something you can give a name.
 

Object Oriented Programming:
 
It is a Style of programming that represents a program as a system of objects and enables code-reuse.
 

Encapsulation:
 
Binding of attributes and behaviors. Hiding the implementation and exposing the functionality.
 

Abstraction:
 
Hiding the complexity. Defining communication inter
face for the functionality and hiding rest of the things. 
In
 .Net destructor can not be abstract. Can define Either Finalize / Destructor. For Destructor access specifiers can not be assigned. It is Private. 

Overloading:
 
Adding a new method with the same name in same/derived class but with different number/types of parameters. Implements Polymorphism.
 

Overriding:
 
When we need to provide different implementation than the provide by base class, We define the same method with same signatures in the derived class. Method must be Protected/Protected-Friend/Public for this purpose. (Base class routine can be
 called by Mybase.Method, base.Method). 

Shadowing:
 
When the method is defined as Final/sealed in base class and not overridable and we need to provide different implementation for the same. We define method with Shadows/new.
 

Inheritance:
 
Gives you ability to provide is-a relationship. Acquires attributes and behaviors from another. When a class acquires attributes and behaviors from another class.
 (must not be Final or sealed class in .Net) 

Abstract Class:
 
Instance can not be created. Optionally can have one or more abstract methods but not necessary. Can provide body to Classes.
 

Inter
face: 
What a Class must do, But not how-to.
 
Bridge for the communication when the
 caller does not know to whom he is calling. 
Describes externally visible behavior of element.
 
Only Public members which defines the means of the communication with the outer world. Can-be-Used-As Relationship.
 
Can not contain data but can declare property. There can be no implementation. Inter
face can be derived from another interface. 

Polymorphism:
 
Mean by more than one form. Ability to provide different implementation based on different no./type of parameters. A method behaves differently based on the different input parameters. Does not depend on the Return-Type.
 

Pure-Polymorphism:
 
Make an method abstract/virtual in base class. Override it in Derived Class. Declare a variable of type base class and assign an object of derived class to it. Now
 call the virtual/abstract method. The actual method to be called is decided at runtime. 

Early-Binding:
 
Calling an non-virtual method decides the method to call at compile time is known as Early-Binding. 

Late-Binding:
 
Same as pure-polymorphism.
 

Identifiers/Access Specifies and scope:
 
VB
.NET: Private, Protected, Friend, Protected Friend, Public. 
C#: private, protected, internal, protected internal, public.
 

What is a Delegate?
 
A strongly typed function pointer. A delegate object encapsulates a reference to a method. When actual function needs to be
 called will be decided at run-time. 

Static Variable and Its Life-Time:
 
VB
.NET: Public Shared VAR As Type. 
C#: public static Type VAR;
 
Life time is till the class is in memory.
 

Constructor:
 
Special Method Always
 called whenever an instance of the class is created. 

Destructor/Finalize:
 
Called by GC just before object is being reclaimed by GC.

ASP.NET

Different Types of Caching? 
Output Caching: stores the responses from an asp
.net page. 
Fragment Caching: Only caches/stores the portion of page (User Control)
 
Data Caching: is Programmatic way to Cache objects for performance.
 

Authentication and Authorization:
 
Authentication is identifying/validating the user against the credentials (username and password) and Authorization performs after authentication. Authorization allowing access of specific resource to user.
 

Different Types of Directives:
 
Page, Register, Control, OutputCache, Import, Implements, Assembly, Reference
 

Difference between Server-Side and Client-Side:
 
Server-Side code is executed on web-server and does not transmitted to client, while client-side code executed on client(browser) and is rendered to client along with the content.
 

Difference Server.Transfer and Response.Redirect:
 
Both ends the processing for the current request immediately. Server.Transfer start executing the another resource specified as parameter without acknowledgement to client(browser) while Response.Redirect intimate client that your requested resource is available at this location and then client request for that resource.
 

Different Types of Validators and Validation Controls:
 
RequiredFieldValidator, RangeValidator, RegularExpressionValidator, CompareValidator, CustomValidator, ValidationSummary
 

How to Manage State in ASP
.Net? 
Client based: ViewState, QueryString and Cookies Server based: Session, Application.
 

Difference between User Control and Custom Control:
 
CUSTOM Controls are compiled code (Dlls), easier to use, difficult to create, and can be placed in toolbox. Drag and Drop controls. Attributes can be set visually at design time. Can be used by Multiple Applications (If Shared Dlls), Even if Private can copy to bin directory of webApp add reference and use. Normally designed to provide common functionality independent of consuming Application.
 

3 Types of Session State Modes?
 
InProc(cookieless, timeout),
 
StateServer (Server, Port stateConnectionString="tcpip=server:port"),
 
SQLServer (sqlconnectionstring) and Off.
 

What is ViewState and How it is managed, Its Advantages/Benefits?
 
ViewState is a special object that ASP
.NET uses to maintain the state of page and all webcontrols/ServerControls within it. It is in this object preserves the states of various FORM elements during post-backs. It is rendered to client(browser) as a Hidden variable __VIEWSTATE under <form>tag. We can also add custom values to it. 

What is web.config and machine.config:
 
machine.config is default configuration for all applications running under this version, located in %WinDir%\Microsfot
.Net\Framework\Version. Settings can be overridden by Web.Config for an specific application Web.Config resides in application’s root/virtual root and exists in sub-sequent folders. 

Role of Global.asax:
 
Optional file contains the code to handle Application level events raised by ASP
.Net or By HttpModule. This file resides in application root directory. Application_Start, _End, _AuthenticateRequest, _Error, Session_Start, _End, BeginRequest, EndRequest. This file is parsed and compiled into dynamically generated class derived from HttpApplication. 

Page Life Cycle:
 
Init, LoadViewState, LoadPostBackData, Load, RaisePostBackDataChangedEvent, RaisePostBackEvents, Pre-Render, SaveViewState, Render, Unload, (IpostBackDataChangedEventHandler and IpostBackEventHandler) Error, CommitTransaction, AbortTransaction, Abort
 
inetinfo.exe, aspnet_isapi.dll aspnet_wp.exe, HttpModules (OutputCache, Session, Authentication, Authorization, Custom Modules Specified) and Then HttpHandlers PageHandlerFactory for *.aspx
 

Can the action attribute of a server-side <form>tag be set to a value and if not how can you possibly pass data from a form to a subsequent Page?
 
No assigning value will not work because will be overwritten at the time of rendering. We can assign value to it by register a startup script which will set the action value of form on client-side. Rest are Server.Transfer and Response.Redirect.
 

ASP
.Net List Controls and differentiate between them? 
RadioButtonList, CheckBoxList, DropDownList, Repeater, DataGrid, DataList
 

Type Of Code in Code-Behind class:
 
Server-Side Code.
 

What might be best suited to place in the Application_Start and Session_Start:
 
Application level variables and settings initialization in App_Start
 
User specific variables and settings in Session_Start
 

Difference between inline and code-behind. Which is best?
 
Inline is mixed with html and code-behind is separated. Use code-behind, Because Inline pages are loaded, parsed, compiled and processed at each first request to page and remains in compiled code remains in cache until it expires, If expires it again load, parse and compile While code-behind allows to be pre-compiled and provide better performance.
 

Which Template must provide to display data in Repeater?
 
ItemTemplate.
 

How to Provide Alternating Color Scheme in Repeater?
 
AlternatingItemTemplate
 

What base class all Web Forms inherit from?
 
System.Web.UI.Page
 

What method do you use to explicitly kill a user’s Session?
 
HttpContext.Current.Session.Abandon()
 

How do you turn off cookies in one page of your asp
.net application? 
We will not use it. But can not turn off cookies from server. To allow or not is a client side functionality.
 

Which two properties are on every validation control?
 
ControlToValidate and Text, ErrorMessage
 

How do you create a permanent cookie?
 
Set expires property to Date.MaxValue (HttpCookie.Expires = Date.MaxValue)
 

What is the standard you use to wrap up a
 call to a Web Service? 
SOAP
 

Which method do you use to redirect to user to another page without performing a round trip to Client?
 
Server.Transfer(“AnotherPage.aspx”)
 

What is transport protocol you use to
 call a Web-Service SOAP? 
HTTP-POST
 

A Web Service can only be written in
 .NET? 
FALSE
 

Where on internet would you look for Web services?
 
www.uddi.org
 

How many classes can a single
 .NET DLL contain? 
Unlimited
 

How many namespaces are in
 .NET version 1.1? 
124
 

What is a bubbled event?
 
When you have a complex control like DataGrid. Writing an event processing routine for each object (cell, button, row etc.). DataGrid handles the events of its constituents and will raise its own defined custom events.
 

Difference between ASP Session State and ASP
.Net Session State? 
ASP: relies on cookies, Serialize all requests from a client, Does not survive process shutdown, Can not maintained across machines in a Web farm/garden.
 

Layouts of ASP
.NET Pages: 
GridLayout and FlowLayout
 

Web User Control:
 
Combines existing Server and HTML controls by using VS
.Net. to create functional units that encapsulate some aspects of UI. Resides in Content Files, which must be included in project in which the controls are used. 

Composite Custom Control:
 
combination of existing HTML and Server Controls.
 

Rendered custom control:
 
create entirely new control by rendering HTML directly rather than using composition.
 

Where do you store the information about user’s Locale?
 
Page.Culture
 

should Validation occur on Client/Server Side for Date Input?
 
Both. Client-side reduces extra round-trip. Server-Side ensures prevention against hacking and failure against automated requests.
 

HTTP GET and HTTP POST:
 
As their names imply, both HTTP GET and HTTP POST use HTTP as their underlying protocol. Both of these methods encode request parameters as name/value pairs in the HTTP request. The GET method creates a query string and appends it to the script's URL on the server that handles the request. For the POST method, the name/value pairs are passed in the body of the HTTP request message.
 

Web Services Discovery:
 
Even though advertising of a web service is important, it is optional. Web services can be private as well as public. Depending on the business model, some business-to -business (B2B) services would not normally be advertised publicly. Instead, the web service owners would provide specific instructions on accessing and using their service only to the business partner. To advertise web services publicly, authors post discovery files on the Internet. Potential web services clients can browse to these files for information about how to use the web services—the WSDL (Web Service Description Language). Think of it as the yellow pages for the web service. All it does is point you to where the actual web services reside and to the description of those web services. The process of looking up a service and checking out the service description is
 called Web Service discovery. There are two ways of advertising the service: static and dynamic. In both of these, XML conveys the locations of web services. 

Static discovery is easier to understand because it is explicit in nature. If you want to advertise your web service, you must explicitly create the .disco discovery file and point it to the WSDL.
 

As opposed to explicitly specifying the URL for all web services your site supports, you can enable dynamic discovery, which enables all web services underneath a specific URL on your web site to be listed automati
cally. For your web site, you might want to group related web services under many different directories and then provide a single dynamic discovery file in each of the directory. 

Web Services and Security:
 
We incorporate security into web service in two ways: system security and application security. System -level security allows for restricting access to the web services from unauthorized clients. It is done in a declarative fashion, whereas application - level security is more flexible. With system-level security, you will most likely have the list of authorized clients' IP addresses that you will let access your web service through the use of some configuration - management tools. With application-level security, you will incorporate the authentication into your web service, thus providing a more flexible configuration.
 

In system – level security client send a user name and password to web server. This pair can be in plain text format or in some encrypted format. Once server authenticates the user it can access the services available to server.
 

In application – level security mode your web services involves taking security into your own hands. You can program your web services so that all of their methods require an access token, which can be obtained from the web service after sending in the client's username and password. The client credentials can be sent to the server through SSL (Secure Sockets Layer), which eliminates the risk of sending clear-text passwords across the wire. Through this SSL channel, the server returns an access token to the
 caller, who can use it to invoke all other web service methods. 

Web Form Events
 
The first event that happens in the life of a Web Form is the Init event. This is raised so that we can have initialization code for the page. The controls on the page are not yet created at this point. This event is raised once for each user of the page.
 

The Load event follows the Init event. Subsequently, it is raised each time the page is requested. When this event is raised, all child controls of the Web Form are loaded and accessible. You should be able to retrieve data and populate the controls so that they can render themselves on the page when sent back to the client.
 

The PreRender event happens just before the page is rendered and sent back to the client. We don't often handle this event; however, it depends on the situation.
 

The last event in the life of a Web Form is the Unload event. This happens when the page is unloaded from memory. Final cleanup should be done here.
 

Lifecycle Of A Web Form:
 
In ASP
 .NET, the web page starts its life when a client requests a particular page. IIS parses and runs the scripts on the ASP page to render HTML content. As soon as the page rendering is complete, the page's life ceases; only the view states of the page persist between requests to the page. These view states allow the controls on the server to appear as if they are still present to handle server events. 

Using Web Services:
 
In Visual Studio
.NET IDE, you can choose Project >> Add Web Reference and then type in the URL where the web service resides. For example, we'll point to the web service we created on local server, than is PubsWS (suppose). The URL to this web service on our server is http://localhost/PubsWS/PubsWS.asmx. After adding the web reference, you can access the proxy object to the web service you are calling via the type servername.proxyObjectName. For your case, it is localhost.PubsWS. 

The following code excerpt demonstrates how to use the web service through the proxy. We create an instance of the proxy object and then ask it to relay the message to the real web service to get the list of authors. The result will be streamed back in XML format, which is reconstructed into a DataSet object.
 

[C#]
 
localhost.PubsWS ws = new localhost.PubsWS( ); DataSet ds = ws.GetAuthors( );
 

ASP
.NET Session-State Management: 
ASP
.NET improves upon ASP session-state management by moving to an out-of-process model. By having all web servers in the farm pointing to a common server that hosts the out-of-process state manager, the web client can be redirected around the farm without losing the session states. By using an out-of-process model, we no longer have the problem of losing session states when the IIS process is cycled. This means that if the web server application crashed for whatever reason and restarted within the session time-out duration, the web clients could still have all their session states intact. Of course, if the out-of-process state manager crashed, that is a whole different issue. This leads to the next improvement of ASP.NET—the ability to persist session state to a database. 

There are two levels of configuration: machine and application. Machine-level configuration associates with the machine.config file stored in WinNT\Microsoft
.NET\ Framework\\CONFIG\machine.config, while the application-level configuration uses the web.config file in the application root directory. The application-level configuration overrides the machine -level configuration.
Acronyms

CCW
COM Callable Wrapper
CLI
Common Language Infrastructure. This is a subset of the CLR and base class libraries that Microsoft has submitted to ECMA so that a third-party vendor can build a .NET runtime on another platform.
CLR
Common Language Runtime
CLS
Common Language Specification
COFF
Common Object File Format
COM
Component Object Model
CTS
Common Type System
DISCO
Discovery of Web Services. A Web Service has one or more. DISCO files that contain information on how to access its WSDL.
DNA
Distributed interNet Applications Architecture.
DOM
Document Object Model
GDI
Graphical Device Interface
GAC
Global Assembly Cache
GUID
Globally Unique Identifier
HTTP
Hyper Text Transfer Protocol
IDL
Interface Definition Language
IL
Intermediate Language
MSIL
Microsoft Intermediate Language
MS-DTC
Microsoft Distributed Transaction Coordinator
N-Tier
Multi-Tier
OLTP
Online Transaction Processing
OLAP
Online Analytical Processing
PE
Portable Executable
RAD
Rapid Application Development
RCW
Runtime Callable Wrapper
SMTP
Simple Mail Transfer Protocol
SOAP
Simple Object Access Protocol
TCP
Transport Control Protocol
TLB
Type Library
UDF
Uniform Data Format
UI
User Interface
URL
Uniform Resource Locator
UDDI
Universal Description, Discovery and Integration
WAP
Wireless Access Protocol
WSDL
Web Services Definition Language
WML
Wireless Markup Language
XML
Extensible Markup Language

******************************************************************************

JQuery Interview Question Answer

1- What is jQuery ?
It's very simple but most valuable Question on jQuery means jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, animating, event handling, and Ajax interactions for rapid web development. jQuery is designed to change the way that you write JavaScript. Jquery is build library for javascript no need to write your own functions or script jquery all ready done for you

2- How you will use Jquery means requirement needed for using jquery?
Nothing more need to do just olny download jquery library(.js file) from any of the jquery site Download jquery and just linked with your html pages like all other javascript file

like below :
Code:
< script src="jquery.js" language="javascript" type="text/javascript">

3- what the use of $ symbol in Jquery?
$ Symbol is just replacement of jquery means at the place of $ you may use jquery hence $ symbol is used for indication that this line used for jquery

4- How do you select an item using css class or ID and get the value by use of jquery?
If an element of html like < div> , < p> or any tag have ID MyId and class used MyClass then we select the element by below jquery code
Code:
$('#MyId') for ID and for classs $('.MyClass')
and for value
Code:
var myValue = $('#MyId').val();
// get the value in var Myvalue by id
Or for set the value in selected item
Code:
$('#MyId').val("print me");
// set the value of a form input

5- How to get the server response from an AJAX request using Jquery?
When invoking functions that have asynchronous behavior We must provide a callback function to capture the desired result. This is especially important with AJAX in the browser because when a remote request is made, it is indeterminate when the response will be received.
Below an example of making an AJAX call and alerting the response (or error):
Code:
$.ajax({
     url: 'pcdsEmpRecords.php',
     success: function(response) {
        alert(response);
     },
     error: function(xhr) {
        alert('Error!  Status = ' + xhr.status);
     }
});

6- How do you update ajax response with id " resilts"?
By using below code we can update div content where id 'results' with ajax response
Code:
function updateStatus() {
     $.ajax({
            url: 'pcdsEmpRecords.php',
            success: function(response) {
             // update div id Results
             $('#results').html(response);
         }
     });
}

7- How do You disable or enable a form element?
There are two ways to disable or enable form elements.
Set the 'disabled' attribute to true or false:
Code:
// Disable #pcds
$('#pcds').attr('disabled', true);
// Enable #pcds
$('#pcds').attr('disabled', false);
Add or remove the 'disabled' attribute:
// Disable #pcds
$("#pcds").attr('disabled', 'disabled');
// Enable #x
$("#pcds").removeAttr('disabled');

8- How do you check or uncheck a checkbox input or radio button?
There are two ways to check or uncheck a checkbox or radio button.
Set the 'checked' attribute to true or false.
Code:
// Check #pcds
$('#pcds').attr('checked', true);
// Uncheck #pcds
$('#pcds').attr('checked', false);
Add or remove the 'checked' attribute:
// Check #pcds
$("#pcds").attr('checked', 'checked');
// Uncheck #pcds
$("#pcds").removeAttr('checked');

9- How do you get the text value of a selected option?
Select elements typically have two values that you want to access. First there's the value to be sent to the server, which is easy:
Code:
$("#pcdsselect").val();
// => 1
The second is the text value of the select. For example, using the following select box:
Code:
<select id="pcdsselect">
   <option value="1">Mr</option>
   <option value="2">Mrs</option>
   <option value="3">Ms</option>
   <option value="4">Dr</option>
   <option value="5">Prof</option>
</select>
If you wanted to get the string "Mr" if the first option was selected (instead of just "1"), you would do that in the following way:
Code:
$("#mpcdsselect option:selected").text();
// => "Mr"




*******************************************************************************

JavaScript Questions:

1.JavaScript vs. Jscript

JavaScript is a scripting language developed by Netscape Communications.
The Netscape Navigator interprets JavaScript embedded into Web pages.
JavaScript is used for developing web applications.
It is not dependent on Sun Microsystem's Java language.

JScript
Microsoft JScript is an open implementation of Netscape's JavaScript.
JScript is a scripting language designed to create active online content. ActiveX controls, Java programs, etc can be linked and automated in the web pages using JScript.
2.What is the difference between Client side JavaScript and Server side JavaScript.

Client side java script comprises the basic language and predefined objects which are relevant to running java script in a browser. The client side java script is embedded directly by in the HTML pages. This script is interpreted by the browser at run time.

Server side java script also resembles like client side java script. It has relevant java script which is to run in a server. The server side java scripts are deployed only after compilation.
What is the difference between Client side JavaScript and Server side tJavaScript?

Client-Side JavaScript (CSJS)
It is JavaScript that enables the enables web pages on browsers to run active online content.

Server-Side JavaScript (SSJS)
It is JavaScript that enables back-end access to databases, file systems, and servers
3.Where are cookies actually stored on the hard disk?

The storage of cookies on the hard disk depends on OS and the browser. The Netscape navigator on Windows, the file cookies.txt contains all the cookies. The path is :

c:\Program Files\Netscape\Users\username\cookies.txt

The Internet Explorer stores the cookies on a file by name username@website.txt is

c:\Windows\Cookies\username@Website.txt

Where are cookies actually stored on the hard disk?

This depends on the user's browser and OS.

In the case of Netscape on Windows OS, its stored in cookies.txt

In IE, each cookie is stored in a file and has is named as username@website.txt.
what is the differene between java and java script...?

Java Script is object based language it is used for front end validations
java is object oriented language object oriented language supports OOP's Object based not suppoted inheritence.
What are JavaScript types?

Number, String, Boolean, Function, Object, Null, Undefined.
How do you convert numbers between different bases in JavaScript?

Use the parseInt() function, that takes a string as the first parameter, and the base as a second parameter. So to convert hexadecimal 3F to decimal, use parseInt ("3F", 16);
What does isNaN function do ?

Return true if the argument is not a number.
What is negative infinity?

It’s a number in JavaScript, derived by dividing negative number by zero.
What boolean operators does JavaScript support?

&&, || and !
What does "1"+2+4 evaluate to?

Since 1 is a string, everything is a string, so the result is 124.
What looping structures are there in JavaScript?

for, while, do-while loops, but no foreach.
How do you create a new object in JavaScript?

var obj = new Object(); or var obj = {};
How do you assign object properties?

obj["age"] = 17 or obj.age = 17
What’s a way to append a value to an array?

arr[arr.length] = value;
What is this keyword?

It refers to the current object.
What is the main difference between Client side JavaScript and and Server side Java Script. How actually they run on both side with Example?

Clientside Javascript encompasses the core language plus extras such as the predefined objects, only relevant to running Javasript in a browser.The clientside javascript is embedded directly in the HTML pages and is interpreted by the browser completly at the run time. Serverside javascript also encompasses the core language plus extas as the predefined objects and functions only relevant to running Javasript in a server.The serverside javascripts are compiled before they are deployed.


*********************************************************************************




LINQ Interview Questions and Answers: 


What is a Lambda expression?

A Lambda expression is nothing but an Anonymous Function, can contain expressions and statements. Lambda expressions can be used mostly to create delegates or expression tree types. Lambda expression uses lambda operator => and read as 'goes to' operator.

Left side of this operator specifies the input parameters and contains the expression or statement block at the right side.

Example: myExp = myExp/10;

Now, let see how we can assign the above to a delegate and create an expression tree:
delegate int myDel(int intMyNum);

static void Main(string[] args)
{
//assign lambda expression to a delegate:
myDel myDelegate = myExp => myExp / 10;
int intRes = myDelegate(110);
Console.WriteLine("Output {0}", intRes);
Console.ReadLine();
//Create an expression tree type
//This needs System.Linq.Expressions
Expression<myDel> myExpDel = myExp => myExp /10;
}

No te:
The => operator has the same precedence as assignment (=) and is right-associative.
Lambdas are used in method-based LINQ queries as arguments to standard query operator methods such as Where.

What is LINQ?

It stands for Language Integrated Query. LINQ is collection of standard query operators that provides the query facilities into .NET framework language like C# , VB.NET.


How LINQ is beneficial than Stored Procedures?

There are couple of advantage of LINQ over stored procedures.

1. Debugging - It is really very hard to debug the Stored procedure but as LINQ is part of .NET, you can use visual studio's debugger to debug the queries.

2. Deployment - With stored procedures, we need to provide an additional script for stored procedures but with LINQ everything gets complied into single DLL hence deployment becomes easy.

3. Type Safety - LINQ is type safe, so queries errors are type checked at compile time. It is really good to encounter an error when compiling rather than runtime exception!


Why Select clause comes after from clause in LINQ?
The reason is, LINQ is used with C# or other programming languages, which requires all the variables to be declared first. From clause of LINQ query just defines the range or conditions to select records. So that’s why from clause must appear before Select in LINQ.


What is the extension of the file, when LINQ to SQL is used?
The extension of the file is .dbml

What is the LINQ file extension that interacts with Code Behind's objects.
its .dbml

Why can't datareader by returned from a Web Service's Method
Cos, it's not serializable

What is the use of System.XML.XLinq.dll?
System.XML.XLinq.dll contains classes to provide functionality to use LINQ with XML.


What is the use of System.Data.DLinq.dll?
System.Data.DLinq.dll provides functionality to work with LINQ to SQL.

Which assembly represents the core LINQ API?
System.Query.dll assembly represents the core LINQ API.


What is the benefit of using LINQ on Dataset?
The main aim of using LINQ to Dataset is to run strongly typed queries on Dataset.

Suppose we want to combine the results from two Datasets, or we want to take a distinct value from the Dataset, then it is advisable to use LINQ.

Normally you can use the SQL queries to run on the database to populate the Dataset, but you are not able to use SQL query on a Dataset to retrieve a particular values. To get this you need to use ADO.NET functionalities. But, in case of LINQ, it provides more dignified way of querying the Dataset and provides some new features as compared to ADO.NET.


What are the advantages of LINQ over Stored Procedures?

Below is the three advantages of LINQ over stored procedures.

Debugging - As debug point concern, as LINQ is part of .NET, we can use the visual studio's debugger to debug the queries but it is tough to debug the Stored procedure as it will not support the visual studio debugger.

Deployment - In case of deployment, we need to provide an additional script for stored procedures to execute but in case of LINQ, it will complie into single DLL hence deployment becomes easier.

Type Safety - As LINQ is type safe, the queries errors are type checked at compile time. Better suggest to use LINQ because it helps to encounter an error at the compile time rather than at runtime exception.




What is the disadvantage of LINQ over stored procedures?

The disadvantage with LINQ is, it is not a precompiled statement where as stored procedures are precompiled. In case of LINQ the queries need to be compile before the execution. So according to this, I can say stored procedures are faster in performance as compared to LINQ.




What are Quantifiers?

They are LINQ Extension methods which return a Boolean value

1)All
2)Any
3)Contains
4)SequenceEqual

example:
int[] arr={10,20,30};
var b=arr.All(a=>a>20);
-------------------------------------------
Output:
b will return False since all elements are not > 20.




Difference between XElement and XDocument
Both are the classes defined by System.Xml.Linq namespace

XElement class
represents an XML fragment
XDocument class represents an entire XML document with all associated meta-data.

example:

XDocument d = new XDocument(
new XComment("hello"),
new XElement("book",
new XElement("bookname", "ASP.NET"),
new XElement("authorname", "techmedia"),

)
);




Briefly can you explain the purpose of LINQ providers ?
They are a set of classes that takes a LINQ query and dynamically generates on the fly query which is executed against a specific data source(sql database, oracle, xml file, array...etc)


What is the difference between N-layer and N-tier architecture?
N-layers of application may reside on the same physical computor(same tier) and the components in each layer communicates with the components of other layer by well defined interfaces.Layered architecture focuses on the grouping of related functionality within an application into distinct layers that are stacked vertically on top of each other.Communication between layers is explicit and loosely coupled.With strict layering, components in one layer can interact only with componentsin the same layer or with components from the layer directly below it.


The main benefits of the layered architectural style are:
Abstraction,Isolation, Manageability, Performance, Reusability, Testability.


N-tiers architectue usually have atleast three separate logical parts,each located on separate physical server.Each tier is responsible with specific functionality.Each tier is completely independent from all other tier, except for those immediately above and below it.Communication between tiers is typically asynchronous in order to support better scalability.


The main benifit of tier achitecture styles are
1.Maintainability. Because each tier is independent of the other tiers, updates or changes can be carried out without affecting the application as a whole.
2.Scalability. Because tiers are based on the deployment of layers, scaling out an application is reasonably straightforward.
3.Flexibility. Because each tier can be managed or scaled independently, flexibility is increased.
4.Availability. Applications can exploit the modular architecture of enabling systems using easily scalable components, which increases availability.




Tell me the exact difference between IQueryable and IEnumerable interface ?

IEnumerable<T> is applicable for in-memory data querying, and in contrast IQueryable<T> allows remote execution, like web service or database querying.


What is the difference between Count() and LongCount() extension methods in LINQ ?

public static long display()
{
var tempval = (from h in objDB.tbl_mvc_login
select h).Count ();
return tempval;
}

public static long display()
{
var tempval = (from h in objDB.tbl_mvc_login;
select h).LongCount ();
return tempval;
}


Look carefully to the above methods declared. They both does the same thing but LongCount() has a greater range than Count(). According to MSDN, it has the range from

long.MinValue = -9223372036854775808
long.MaxValue = 9223372036854775807

which is quite big. Its DotNet Framework type is System.Int64. While count() DotNet Framework type is System.Int32 which has a range from

long.MinValue = -2,147,483,648
long.MaxValue = 2,147,483,647

So, next time if you want to count something which is quite big then use LongCount() extension method otherwise use Count().


Can you explain in brief about Aggregate() extension method in LINQ ?
public static int display()
{
int[] numbersArray = { 1, 2, 3, 4, 5 };
return numbersArray.Aggregate((x1, x2) => x1 * x2);
}

output : 120

In the above code, "numbersArray" is an integer array. Here, the first one being the first number or the previous result, and the second one is the second or next number to participate the calculation.

The calculation goes like :-

1 * 1 = 1 (stored in x1)
x1 * 2 = 2 (stored in x1)
x1 * 3 = 6 (stored in x1)
x1 * 4 = 24 (stored in x1)
x1 * 5 = 120 (stored and returned back)


What is the difference between FirstOrDefault() and SingleOrDefault() extension method in LINQ ?
FirstOrDefault() = gets the first item that matches a given criteria.

SingleOrDefault() = if you specify this extension method that means you are specifically saying that there can be only one value that matches the criteria. If there are more then 1 value that matches the criteria, throw an exception.

What is the difference between First() and Single() extension methods in LINQ ?
• First() - There is at least one result, an exception is thrown if no result is returned.

• Single() - There is exactly 1 result, no more, no less, an exception is thrown if no result is returned.

How to get the Value of attribute from XML using XDocument class?

Let us look at the below situation
<?xml version='1.0' encoding='UTF-8'?>
<Countries>
<State Name = 'Karnataka'>
<City Name='Bangalore' />
<City Name= 'Guledgudda' />
<City Name= 'Hubli' />
<City Name= 'Tumkur' />
</State>
</Countries>

The challenge is to get the City Names using XDocument class. The below code will help us to do so

string inputXml = @"<?xml version='1.0' encoding='UTF-8'?>
<Countries>
<State Name = 'Karnataka'>
<City Name='Bangalore' />
<City Name= 'Guledgudda' />
<City Name= 'Hubli' />
<City Name= 'Tumkur' />
</State>
</Countries>";
XDocument countrySource = XDocument.Parse(inputXml);
//The query
countrySource
.Descendants("State")
.SelectMany(i => i.Elements())
.ToList()
.ForEach(i=>Console.WriteLine((string)i.Attribute("Name")));

//Output
Bangalore
Guledgudda
Hubli
Tumkur

Explain with an example how to perform group by in LINQ/LAMBDA?

string input = new string[] { "Apple", "Banana", "Mango", "Apple", "Orange", "Mango", "Strawberry", "Apple" };
The problem is to write a query using LINQ and LAMBDA that will count the nunber of fruits.
Solution
var input = new string[] { "Apple", "Banana", "Mango", "Apple", "Orange", "Mango", "Strawberry", "Apple" };

//Using LINQ

(from a in input
group a by a into g
select new
{
Key = g.Key
,Count = g.Count()
})

.ToList()

.ForEach(i => Console.WriteLine("Number of {0} is {1}", i.Key, i.Count));

//Using Lambda
input
.GroupBy(g => g)
.Select(i => new { Key = i.Key, Count = i.Count() })
.ToList()
.ForEach(i => Console.WriteLine("Number of {0} is {1}", i.Key, i.Count));


Output

Number of Apple is 3
Number of Banana is 1
Number of Mango is 2
Number of Orange is 1
Number of Strawberry is 1

How to assign a computed value to the same array back?

var input = new string[] { "Apple", "Banana", "Mango", "Apple", "Orange", "Mango", "Strawberry", "Apple"};

The problem is to write a query using LINQ that will count the number of fruits and will assign back the value to the same array i.e. we should not create another array for storing the computed values.

Solution

var input = new string[] { "Apple", "Banana", "Mango", "Apple", "Orange", "Mango", "Strawberry", "Apple" };

input = (from a in input
group a by a into g
where g.Count() >= 2
select g.Key + " ( " + g.Count() + " )").ToArray();

Output
Apple ( 3 )
Mango ( 2 )

How will you obtain the length of the longest string in a Data table assuming that every column in of type string using Lambda?

DataTable dt = new DataTable();

var maxLength = dt.AsEnumerable()

.SelectMany(r => r.ItemArray.OfType<string>())

.Max(i => i.Length);

First cast the Datatable to System.Collections.Generic.IEnumerable<T> object by using the AsEnumerable() extension method,then using the SelectMany extension method
to find out the items in the ItemArray whose type is string and finally figuring out the max length of the records.


How will you obtain the length of the longest string in every column of a Datatable assuming that every column in of type string using Lambda?

DataTable dt = new DataTable();
var maximumColumnsLengths =
Enumerable.Range(0, dt.Columns.Count)
.Select(col => dt.AsEnumerable()
.Select(row => row[col]).OfType<string>()
.Max(val => val.Length)).ToList();


Write a code snippet for Left outer join using LINQ?

I failed to answer this question in my interview session. So I searched the answer for the question and found in MSDN. After my understanding I just wrote a simple program to understand the left outer join in LINQ.

namespace LeftOuterJoin
{
 namespace LeftOuterJoin
{


class Employee
{
public string EmpName { get; set; }
public int EmpAge { get; set; }
public string EmpDeptID { get; set; }
}

class Department
{
public string DeptID { get; set; }
public string DeptName { get; set; }
}
class Program
{
public static void Main(string[] args)
{
Employee objEmp1 = new Employee { EmpName = "Naga", EmpAge = 29, EmpDeptID = "1" };
Employee objEmp2 = new Employee {EmpName = "Sundar", EmpAge = 30, EmpDeptID = "2"};
Employee objEmp3 = new Employee { EmpName = "Siva", EmpAge = 28, EmpDeptID = "3" };
Employee objEmp4 = new Employee{EmpName = "Shankar", EmpAge = 31, EmpDeptID = "4"};
Department objDept1 = new Department { DeptID = "1", DeptName = "IT" };
Department objDept2 = new Department { DeptID = "2", DeptName = "Admin" };
Department objDept3 = new Department { DeptID = "3", DeptName = "Testing" };
Department objDept4 = new Department { DeptID = "4", DeptName = "HR" };
Department objDept5 = new Department { DeptID = "5", DeptName = "Sales" };
//Creating List of Objects

List<Employee> employees = new List<Employee> {objEmp1, objEmp2, objEmp3, objEmp4};
List<Department> depts = new List<Department> { objDept1, objDept2, objDept3, objDept4, objDept5 };

//Left Side Department Right side Employee
var DeptEmpCollection = from dept in depts
join emp in employees on dept.DeptID equals emp.EmpDeptID into de
from Employees in de.DefaultIfEmpty()
select new { dept.DeptName, EmployeesName = (Employees == null ? "--No Employee--" : Employees.EmpName) };
foreach (var EmpDept in DeptEmpCollection)
{
Console.WriteLine("Dept {0}, EmpName {1}", EmpDept.DeptName, EmpDept.EmployeesName);
}
Console.Read();
}
}
}
}


Write a query to get the single employee name when there are many employees whose name is "test" in the database ?

var employee = (from h in contextobject.Employee
where h.EmployeeName == "test"
select h).FirstOrDefault<Employee>();

Write a query to get the list of all employees whose name is "test" ?

var employeeList = (from h in context.Employee
where h.EmployeeName == "test"
select h).ToList<Employee>();



********************************************************************************


WCF INTERVIEW QUESTION & ANSWERS

 

1.
What is WCF?

WCF (Indigo was the code name for WCF) is a unification of .Net framework communication technologies.
2.
What is Windows card space?

Windows card space is a central part of Microsoft's effort to create an Identify met system, or a unified, secure and interoperable identify layer for the internet.
3.
What are the main components of WCF?


There are three main components of WCF:
§  Service class
§  Hosting environment
§  End point

4.
What are the advantages of hosting WCF Services in IIS as compared to self hosting?

There are two main advantages of using IIS over self hosting.
§  Automatic activation
§  Process recycling
 5.
What is .NET 3.0?

In one simple equation .NET 3.0 = .NET 2.0 + Windows Communication Foundation + Windows Presentation Foundation + Windows Workflow Foundation + Windows Card Space.
6.
What is the difference between WCF and Web Services?

Web services can only be invoked by HTTP. While Services or a WCF component can be invoked by any protocol and any transport type. Second web services are not flexible. However Services are flexible. If you make a new version of the service then you need to just expose a new end. Therefore services are agile and which is a very practical approach looking at the current business trends.
7.
What are the different bindings supported by WCF?

WCF includes predefined bindings.
§  Basic Http binding
§  WsHttp binding
§  NetTcp Binding
§  Netnamed pipes binding
§  Net MSMQ binding
8.
Can we have two way communications in MSMQ?

Yes
9.
What are dead letter queues?

The main use of queue is that you do not need the client and the server running at one time. Therefore it is possible that a message will lie in queue for long time until the server or client picks it up. But there are scenarios where a message is no use after a certain time.
10.
what are the various ways of hosting a WCF service?

There are three major ways to host a WCF service :
Self-hosting the service in his own application domain. This we have already covered in the first section. The service comes in to existence when you create the object of Service Host class and the service closes when you call the Close of the Service Host class.
Host in application domain or process provided by IIS Server.
Host in Application domain and process provided by WAS (Windows Activation Service) Server
11.
What are the core security features that WCF addresses?

§  Confidentiality
§  Integrity
§  Authentication
§  Authorization
12.
What is SOA?

SOA is a collection of well defined services, where each individual service can be modified independently of other services to help respond to the ever evolving market conditions of a business.
13.
What is the difference between transport level and message level security?

Transport level security happens at the channel level. Transport level security is the easiest to implement as it happens at the communication level. WCF uses transport protocols like TCP, HTTP, MSMQ etc and every of these protocols have their own security mechanisms.
Message level security is implemented with message data itself.
14.
What is service and client in perspective of data communication?

A service is a unit of functionality exposed to the world.
The client of a service is merely the party consuming the service.
15.
What is bindings?

A binding defines how an endpoint communicates to the world. A binding defines the transport (such as HTTP or TCP) and the encoding being used (such as text or binary). A binding can contain binding elements that specify details like the security mechanisms used to secure messages, or the message pattern used by an endpoint.
16.
What are the types of contracts in Wcf?

§  Service contract
§  Data contract
§  Message contract
17.
What are the advantages of WCF?

WCF is interoperable with other services when compared to .Net Remoting,where the client and service have to be .Net.
WCF services provide better reliability and security in compared to ASMX web services.
In WCF, there is no need to make much change in code for implementing the security model and changing the binding.
WCF has integrated logging mechanism, changing the configuration file settings will provide this functionality.
18.
Define service contracts?

Service contracts define the operations that a service will perform when executed. They tell the outside world a lot about the service such as message data types, operation locations, the protocols the client will need in order to communicate with the service, and the operations the service provides.
19.
Define message contracts?

Message contracts allow the control of SOAP messages that are produced and consumed by WCF. Basically it boils down to being able to customize the format of contract parameters and the placing of elements within a SOAP message, or in other words, having control of the structure as well as the contents of a SOAP message.
20.
Define data contracts?

Data contracts specifically define the data that is being exchanged between a client and service. The data contract is an agreement, meaning that the client and the service must agree on the data contract in order for the exchange of data to take place.
21.
Define transaction?

A transaction is a collection or group of one or more units of operation executed as a whole. Another way to say it is that transactions provide a way to logically group single pieces of work and execute them as a single unit, or transaction.
22.
What is address in WCF?

Address is a way of letting client know that where a service is located. In WCF, every service is associated with a unique address.
23.
What are the types of bindings in WCF?

§  Basic binding
§  TCP binding
§  Peer network binding
§  IPC binding
§  Web Service (WS) binding
§  Federated WS binding
§  Duplex WS binding
§  MSMQ binding
§  MSMQ integration binding
 24.
What are different elements of WCF Srevices Client configuration file?

WCF Services client configuration file contains endpoint, address, binding and contract.
25.
What is three major points in WCF?

§  Address
§  Binding
§  Contract
26.
What are Endpoints?

An endpoint is the entity that a client connects to using a specific protocol and data format when consuming a service.
27.
What are the features of WCF?

Transactions : A transaction is a unit of work. A transaction ensures that everything within that transaction either succeeds as a whole or fails as whole.
Hosting : WCF hosting allows services to be hosted in a handful of different environments, such as Windows NT Services, Windows Forms, and console applications, and well as IIS (Internet Information Services) and Windows Activation Services (WAS).
Security : WCF also enables you to integrate your application into an existing security infrastructure, including those that extend beyond the standard Windows-only environments by using secure SOAP messages.
Queuing : WCF enables queuing by providing support for the MSMQ transport.
28.
Explain WCF contracts?

Contracts in Windows Communication Foundation provide the interoperability they need to communicate with the client. It is through contracts that clients and services agree as to the types of operations and structures they will use during the period that they are communicating back and forth. Without contracts, no work would be accomplished because no agreement would happen.
Three basic contracts are used to define a Windows Communication Foundation service :
Service Contract : Defines the methods of a service, that is, what operations are available on the endpoint to the client.
Data Contract : Defines the data types used by the available service methods.
Message Contract : Provides the ability to control the message headers during the creation of a message.
29.
What is the use of SessionMode?

The SessionMode attribute specifies the type of support for reliable sessions that a contract requires or supports. The value of this parameter comes from the Session Mode enumeration.
30.
What are the types of performance counters?

There are three types of performance counters :
§  Service
§  Endpoint
§  Operation
31.
What are the main components of WCF?

The main components of WCF are :
§  Service class
§  Hosting environment
§  End point
32.
What are the types of messaging programs?

In WCF, different types of applications can send and receive messages.
§  Clients
§  Services
§  Intermediaries
33.
What is transfer security?

Transfer Security is responsible for providing message integrity, confidentiality, and authentication Each of these were defined previously. Windows Communication Foundation builds on this security to include quite a few modes of transfer security.
34.
What are the types of messaging patterns?

Messaging patterns basically describe how programs exchange messages. When a program sends a message, it must conform to one of several patterns in order for it to successfully communicate with the destination program.
There are three basic messaging patterns that programs can use to exchange messages.
§  Simplex
§  Duplex
§  Request Reply


****************************************************************************


WPF INTERVIEW QUESTION & ANSWERS

1.
What is WPF?


WPF is an abbreviation for Windows Presentation Foundation.
It’s a set of .NET assemblies and supporting tools.
It’s intended to provide a unified API for creating rich, sophisticated user interfaces on Windows XP and Windows Vista.

2.
What are the types sibling libraries in WPF?


There are three types of sibling libraries of WPF are :
§  WCF
§  WF
§  CardSpace

3.
What is the difference between WCF and WF?


Windows Communication Foundation is focused on messaging. This API greatly simplifies all sorts of networking and communication tasks. It covers everything from web services to remoting to P2P and more.
A powerful library for building workflow enabled applications. It utilizes a markup language for declaring workflows in an application,and thus prevents workflow from becoming hard-coded. It also makes it very easy for developers to create custom workflow tasks.

4.
What is the use of cardspace?


CardSpace provides a common identification system that can be used by desktop applications,web sites, and more.

5.
What operating systems does WPF currently support?


WPF is currently available on Windows XP and Windows Vista.

6.
What is XAML?


XAML (pronounced as Zammel) is a declarative XML-based language by which you can define object and properties in XML. XAML document is loaded by a XAML parser. XAML parser instantiates objects and set there properties. XAML describes objects, properties and there relation in between them. Using XAML, you can create any kind of objects that means graphical or non-graphical.

7.
What is the benefit of using a markup language for designing a user interface?


Using a markup language such as XAML, or even HTML, is beneficial because it provides a common medium for both designers and developers. Additionally, the markup language allows for a declarative approach for building applications, which is often easier to construct and maintain.

8.
What are the types of binding modes?


There are three different binding modes :
§  one–way
§  two–way
§  one–way–to–source

9.
What is the difference between a XAML file and a code-behind file?


The XAML file contains the XAML markup, whereas the code-behind file is associated with a XAML file and contains code (such as C# or VB).

10.
Which files are automatically added to a new WPF Application project?


App.xaml and Window1.xaml, along with their associated code-behind files. The former represents the application as a whole, whereas the latter represents the primary window of the application.

11.
What is the purpose of the x:Name attribute in XAML?


The x:Name attribute allows you to uniquely identify an instance of an object defined in XAML. The value of the x:Name attribute can be referenced in the associated C# or VB code.

12.
What is a feature of XAML that is available when it is compiled rather than interpreted?


When your XAML is compiled, you can embed procedural code such as C# or VB. For more information about this, look up the markup extension x:Code.

13.
What is an attached property?


An attached property is a property that is declared by one control and attached to another. It allows the inclusion of additional information with a control for later use by an external source.

14.
What kind of documents are supported in WPF?


There are two kind of major document supported in
§  WPF Fixed format documents
§  Flow format document.

15.
What is the difference between fixed format documents and flow format documents?


Fixed format documents look like PDF format. They display content regardless of screen size and resolution.
But Flow format document adjust depending on screen size and resolution.

16.
What is the difference between a Panel and a Decorator?


Panel has a collection of Children that it arranges according to various rules, based on the type of panel.
Decorator, on the other hand, has only one Child to which it applies some additional set of behavior.

17.
What is the feature of silverlight 4?

Silverlight 4 is the current version at the time of writing and it introduced a number of new features, including :
§  Support for Google’s Chrome web browser
§  Access to the user’s web cam and microphone
§  Mousewheel input
§  Enhancements to existing controls, such as the DataGrid
§  New controls, such as the RichTextBox
§  Enhanced data binding support
§  Managed Extensibility Framework support
§  WCF RIA services
18.
What is the purpose of AccessText?


AccessText enables you to specify displayed text with an embedded keyboard shortcut used to access the corresponding control. Simply precede the desired letter of the text with an underscore.

19.
What are the types of Inlines that can be used in a TextBlock?


§  Span
§  Bold
§  Italic
§  Underline
§  Hyperlink
§  Run
§  LineBreak
§  InlineUIContainer
§  Figure
§  Floater

20.
What is the most common format for declaring a data binding in markup?


Markup extensions are the most common means of declaring a data binding. They are identified by the use of curly brackets ({}).The less common format is XAML.

21.
Is x:Static the same as a data binding?


x:Static is another markup extension that is different from the data binding markup extension. It is used to retrieve data from static value members on classes.

22.
How many ways are there to deploy WPF applications, and what are they?


There are three ways to deploy WPF applications :
§  as a simple XAML file
§  an XBAP
§  or a standard executable.

23.
How do navigation applications differ from standard WPF applications?


Navigation applications are based on a web browser metaphor. They use pages instead of windows, and they include a forward and back button by default.

24.
What type of elements can be hosted in a ToolBar?


A ToolBar can host any type of .NET class.

25.
What is the simplest and most common way to componentize a complex UI?


The easiest way to break up a complex UI is to create separate UserControls for related parts and reference them from the original UI.

26.
What class is used to save and load the content of a RichTextBox?


To save or load the content of a RichTextBox, use the TextRange class.

27.
What are the types of binding in WPF?


There are two types of binding in WPF :
§  Key Binding
§  Mouse Binding

28.
What is the difference between key binding and mouse binding?


KeyBinding allows you to define gestures for commands that consist of a keystroke possibly combined with one or more modifiers, whereas MouseBinding allows you to define gestures for the mouse that can also be optionally combined with modifiers on the keyboard.

29.
What type is used to render WPF output to a bitmap?


Use RenderTargetBitmap to render WPF visuals to a bitmap.

30.
What is the base class for all renderable types in WPF?

All elements that are renderable must inherit from Visual.
31.
What is a repository?

A repository is a type of class that hides the actual data storage mechanism from the rest of the application.
32.
What are the types of common file dialogs that WPF supports?


The common file dialogs that WPF supports include SaveFileDialog, OpenFileDialog, and PrintDialog. WPF does not presently have a common dialog for folder selection, font selection, or print preview.

33.
What is the name of the FrameworkElement most commonly used to work with media in WPF?


MediaElement is used to play back a variety of audio and video formats.

34.
What are two common properties on all the Shape classes?


There are more than a dozen properties on the base class System.Windows.Shapes.Shape.
§  Fill
§  Stroke
§  StrokeDashArray
§  StrokeDashCap
§  StrokeEndLineCap
§  StrokeLineJoin
§  StrokeMiterLimit
§  StrokeStartLineCap
§  StrokeThickness

35.
What are the different types of brushes that WPF offers?


There are six different types of brushes
§  SolidColorBrush
§  LinearGradientBrush
§  RadialGradientBrush
§  DrawingBrush
§  VisualBrush
§  ImageBrush

36.
What are the four channels of a WPF Color object?


There are four channels of a WPF color objects are :
§  Alpha
§  Red
§  Green
§  Blue

37.
What are the types of bitmap effects?


The built-in bitmap effects are :
§  DropShadowBitmapEffect
§  OuterGlowBitmapEffect
§  BlurBitmapEffect
§  EmbossBitmapEffect
§  BevelBitmapEffect

38.
What are the two types of transforms present on FrameworkElement?


The two transforms that are present on FrameworkElement are RenderTransform and LayoutTransform.

39.
What is Windows Workflow Foundation?


WWF is a programming model for building workflow-enabled applications on windows. System.Workflow namespace has all the necessary modules to develop any type of workflow.


40.
What is a Workflow?


A Workflow is a set of activities, which is stored as model and they depict a process.Workflow is run by the Workflow runtime engine.

*******************************************************************************



      COMMON INTERVIEW QUESTIONS AND ANSWERS

Review these typical interview questions and think about how you would answer them. Read
the questions listed; you will also find some strategy suggestions with it.

1. Tell me about yourself:
The most often asked question in interviews. You need to have a short statement prepared
in your mind. Be careful that it does not sound rehearsed. Limit it to work-related items
unless instructed otherwise. Talk about things you have done and jobs you have held that
relate to the position you are interviewing for. Start with the item farthest back and work up
to the present.
2. Why did you leave your last job?
Stay positive regardless of the circumstances. Never refer to a major problem with
management and never speak ill of supervisors, co-workers or the organization. If you do,
you will be the one looking bad. Keep smiling and talk about leaving for a positive reason
such as an opportunity, a chance to do something special or other forward-looking reasons.
3. What experience do you have in this field?
Speak about specifics that relate to the position you are applying for. If you do not have
specific experience, get as close as you can.
4. Do you consider yourself successful?
You should always answer yes and briefly explain why. A good explanation is that you have
set goals, and you have met some and are on track to achieve the others.
5. What do co-workers say about you?
Be prepared with a quote or two from co-workers. Either a specific statement or a
paraphrase will work. Jill Clark, a co-worker at Smith Company, always said I was the
hardest workers she had ever known. It is as powerful as Jill having said it at the interview
herself.
6. What do you know about this organization?
This question is one reason to do some research on the organization before the interview.
Find out where they have been and where they are going. What are the current issues and
who are the major players?
7. What have you done to improve your knowledge in the last year?
Try to include improvement activities that relate to the job. A wide variety of activities can
be mentioned as positive self-improvement. Have some good ones handy to mention.
8. Are you applying for other jobs?
Be honest but do not spend a lot of time in this area. Keep the focus on this job and what
you can do for this organization. Anything else is a distraction.
9. Why do you want to work for this organization?
This may take some thought and certainly, should be based on the research you have done
on the organization. Sincerity is extremely important here and will easily be sensed. Relate
it to your long-term career goals.
10. Do you know anyone who works for us?
Be aware of the policy on relatives working for the organization. This can affect your answer
even though they asked about friends not relatives. Be careful to mention a friend only if
they are well thought of.
11. What kind of salary do you need?
A loaded question. A nasty little game that you will probably lose if you answer first. So, do
not answer it. Instead, say something like, That's a tough question. Can you tell me the
range for this position? In most cases, the interviewer, taken off guard, will tell you. If not,
say that it can depend on the details of the job. Then give a wide range.
12. Are you a team player?
You are, of course, a team player. Be sure to have examples ready. Specifics that show you
often perform for the good of the team rather than for yourself are good evidence of your
team attitude. Do not brag, just say it in a matter-of-fact tone. This is a key point.
13. How long would you expect to work for us if hired?
Specifics here are not good. Something like this should work: I'd like it to be a long time. Or
As long as we both feel I'm doing a good job.
14. Have you ever had to fire anyone? How did you feel about that?
This is serious. Do not make light of it or in any way seem like you like to fire people. At the
same time, you will do it when it is the right thing to do. When it comes to the organization
versus the individual who has created a harmful situation, you will protect the organization.
Remember firing is not the same as layoff or reduction in force.
15. What is your philosophy towards work?
The interviewer is not looking for a long or flowery dissertation here. Do you have strong
feelings that the job gets done? Yes. That's the type of answer that works best here. Short
and positive, showing a benefit to the organization.
16. If you had enough money to retire right now, would you?
Answer yes if you would. But since you need to work, this is the type of work you prefer. Do
not say yes if you do not mean it.
17. Have you ever been asked to leave a position?
If you have not, say no. If you have, be honest, brief and avoid saying negative things
about the people or organization involved.
18. Explain how you would be an asset to this organization
You should be anxious for this question. It gives you a chance to highlight your best points
as they relate to the position being discussed. Give a little advance thought to this
relationship.
19. Why should we hire you?
Point out how your assets meet what the organization needs. Do not mention any other
candidates to make a comparison.

20. Tell me about a suggestion you have made
Have a good one ready. Be sure and use a suggestion that was accepted and was then
considered successful. One related to the type of work applied for is a real plus.
21. What irritates you about co-workers?
This is a trap question. Think real hard but fail to come up with anything that irritates you.
A short statement that you seem to get along with folks is great.
22. What is your greatest strength?
Numerous answers are good, just stay positive. A few good examples:
Your ability to prioritize, Your problem-solving skills, Your ability to work under pressure,
Your ability to focus on projects, Your professional expertise, Your leadership skills, Your
positive attitude .
23. Tell me about your dream job.
Stay away from a specific job. You cannot win. If you say the job you are contending for is
it, you strain credibility. If you say another job is it, you plant the suspicion that you will be
dissatisfied with this position if hired. The best is to stay genetic and say something like: A
job where I love the work, like the people, can contribute and can't wait to get to work.
24. Why do you think you would do well at this job?
Give several reasons and include skills, experience and interest.
25. What are you looking for in a job?
See answer # 23
26. What kind of person would you refuse to work with?
Do not be trivial. It would take disloyalty to the organization, violence or lawbreaking to get
you to object. Minor objections will label you as a whiner.
27. What is more important to you: the money or the work?
Money is always important, but the work is the most important. There is no better answer.
28. What would your previous supervisor say your strongest point is?
There are numerous good possibilities:
Loyalty, Energy, Positive attitude, Leadership, Team player, Expertise, Initiative, Patience,
Hard work, Creativity, Problem solver
29. Tell me about a problem you had with a supervisor
Biggest trap of all. This is a test to see if you will speak ill of your boss. If you fall for it and
tell about a problem with a former boss, you may well below the interview right there. Stay
positive and develop a poor memory about any trouble with a supervisor.
30. What has disappointed you about a job?
Don't get trivial or negative. Safe areas are few but can include:
Not enough of a challenge. You were laid off in a reduction Company did not win a contract,
which would have given you more responsibility.
31. Tell me about your ability to work under pressure.
You may say that you thrive under certain types of pressure. Give an example that relates
to the type of position applied for.
32. Do your skills match this job or another job more closely?
Probably this one. Do not give fuel to the suspicion that you may want another job more
than this one.
33. What motivates you to do your best on the job?
This is a personal trait that only you can say, but good examples are:
Challenge, Achievement, Recognition
34. Are you willing to work overtime? Nights? Weekends?
This is up to you. Be totally honest.
35. How would you know you were successful on this job?
Several ways are good measures:
You set high standards for yourself and meet them. Your outcomes are a success.Your boss
tell you that you are successful
36. Would you be willing to relocate if required?
You should be clear on this with your family prior to the interview if you think there is a
chance it may come up. Do not say yes just to get the job if the real answer is no. This can
create a lot of problems later on in your career. Be honest at this point and save yourself
future grief.
37. Are you willing to put the interests of the organization ahead of your own?
This is a straight loyalty and dedication question. Do not worry about the deep ethical and
philosophical implications. Just say yes.
38. Describe your management style.
Try to avoid labels. Some of the more common labels, like progressive, salesman or
consensus, can have several meanings or descriptions depending on which management
expert you listen to. The situational style is safe, because it says you will manage according
to the situation, instead of one size fits all.
39. What have you learned from mistakes on the job?
Here you have to come up with something or you strain credibility. Make it small, well
intentioned mistake with a positive lesson learned. An example would be working too far
ahead of colleagues on a project and thus throwing coordination off.
40. Do you have any blind spots?
Trick question. If you know about blind spots, they are no longer blind spots. Do not reveal
any personal areas of concern here. Let them do their own discovery on your bad points. Do
not hand it to them.
41. If you were hiring a person for this job, what would you look for?
Be careful to mention traits that are needed and that you have.
42. Do you think you are overqualified for this position?
Regardless of your qualifications, state that you are very well qualified for the position.

43. How do you propose to compensate for your lack of experience?
First, if you have experience that the interviewer does not know about, bring that up: Then,
point out (if true) that you are a hard working quick learner.
44. What qualities do you look for in a boss?
Be generic and positive. Safe qualities are knowledgeable, a sense of humor, fair, loyal to
subordinates and holder of high standards. All bosses think they have these traits.
45. Tell me about a time when you helped resolve a dispute between others.
Pick a specific incident. Concentrate on your problem solving technique and not the dispute
you settled.
46. What position do you prefer on a team working on a project?
Be honest. If you are comfortable in different roles, point that out.
47. Describe your work ethic.
Emphasize benefits to the organization. Things like, determination to get the job done and
work hard but enjoy your work are good.
48. What has been your biggest professional disappointment?
Be sure that you refer to something that was beyond your control. Show acceptance and no
negative feelings.
49. Tell me about the most fun you have had on the job.
Talk about having fun by accomplishing something for the organization.
50. Do you have any questions for me?
Always have some questions prepared. Questions prepared where you will be an asset to
the organization are good. How soon will I be able to be productive? and What type of
projects will I be able to assist on? are examples.

No comments:

Post a Comment