Saturday, March 30, 2013

.Net Interview Question and answers

JSON and AJAX:


What is JSON?


Once you've successfully fired an AJAX request, what sort of response should the server give? An XML document? An HTML snippet? A JSON string which is converted to a JavaScript object?

JSON stands for JavaScript Object Notation and is a lightweight data-interchange format. Because it is text-based it is easy for humans to read and write, and it has a regular syntax that's easy to parse programmatically. JSON is basically a subset of JavaScript and, as you'll see, is even easier to parse than XML.

Differences between JSON and XML:

Even though AJAX initially used XML as the format for transferring data, any format will work, including HTML, plain text and—why not—JSON.JSON is less verbose than XML, which translates directly to improved performance—less data means fewer bytes to transfer and parse, in other words JSON requires less bandwidth and fewer memory and CPU resources. JavaScript developers know that JSON is a subset of JavaScript. Indeed, the JSON code you just saw is a literal representation of arrays and objects in JavaScript!

AJAX and JavaScript:

  • With AJAX, your JavaScript can communicate directly with the server, using the JavaScript XMLHttpRequest object. With this object, your JavaScript can trade data with a web server, without reloading the page.
  • AJAX uses asynchronous data transfer (HTTP requests) between the browser and the web server, allowing web pages to request small bits of information from the server instead of whole pages.
  • The AJAX technique makes Internet applications smaller, faster and more user-friendly.
  • Microsoft first implemented the XMLHTTPRequest object in Internet Explorer 5 for Windows as an ActiveX object.

ASP.NET Page life cycle:
  • OnpreInit - called just before page initialization
  • OnInit -all controls initialized to their default state. themes and master page properties are set.
  • OnInitcomplete- page initialization is complete. all the controls are initialized. But view state is not populated.
  • OnPreLoad - viewstate and postback data are restored to the controls.
  • OnLoad - page specific actions to be performed.
  • OnLoadComplete - page loading is complete
  • RaisePostbackEvent - when postback occurs in
  • OnPreRender - any prerendering steps to be taken care of
  • Onprerendercomplete - page is ready for rendering
  • SaveControlstate: saves any control state associated with custom controls.
  • SaveViewState - saves any server control viewstate changes that have occured since the time the page was posted back to server.
  • Render: Initializes HTMLTextwriter object and calls on the child controls to render. Render is responsible for creating markup which is sent to browser.
  • OnUnload: any uncleanup tasks.
DLL Import Attribute:

DLLImport attribute provides information needed to access unmanaged API methods or unmanaged DLL. when this attribute is used method should be marked as public static extern as being a static entry.

Const & Readonly Properties:

A const must be initialized at the time of its creation. A readonly field can be assigned to once in the class constructor allowing you to pass in the value at run-time. Declaring fields as const protects both you and other programmers from accidentally changing the value of the field. Also note that with const fields, the compiler performs some optimization by not declaring any stack space for the field. The readonly keyword is similar to const, with two exceptions. First, the storage of a readonly field is the same as a regular read-write field, and thus there is no performance benefit. Secondly, readonly fields can be initialized in the constructor of the containing class.

.Net Trace and Debug classes:

Trace provides set of methods that help you trace the execution of your code. Trace can be enabled in Release builds where as Debug is disabled in Release builds. Trace can be used to instrument the application running in real world settings which helps to isolate problems and fix them without disturbing running sys.
if the condition fails, Trace.assert will display dialog box. we can customize the trace output and target by configuring trace listeners with out recompilng app.

What is Multicast Delegate? 
  • It is a Delegate which holds the reference of more than one methods.
  • Multicast delegates must contain only methods that return void, else there is a run-time exception.
  • Delegates are used to call a method asynchronously.
  • Delegates can invoke static methods and instance methods with the same syntax.

.Net Garbage Collection summary:

Is there a way to force garbage collection?

call System.GC.Collect().

If you need to have some objects destructed, and System.GC.Collect() doesn't seem to be doing it for you, you can force finalizers to be run by setting all the references to the object to null and then calling System.GC.RunFinalizers(). but it's recommended to use IDisposable interface, call dispose method. Dont forget to call GC.SupressFinilazer.

When the garbage collector performs a collection, it checks for objects in the managed heap that are no longer being used by the application and performs the necessary operations to reclaim their memory.

GC automatically performs cleanup of managed resources. To cleanup unmanaged resources there are two ways of doing it thru two methods

Finalize - Non Deterministic and execution is not guaranteed. Performance overhead in the form of finalization queues. All instances that implement finalize are placed in this queue. By Default, Object.finalize does nothing. you cannot implement Finalize in C#. Destructors are treated as finalize methods in C#.The thread on which the finalizer is run is unspecified

Destructors:

Destructors are the C# mechanism for performing cleanup operations. Destructors provide appropriate safeguards, such as automatically calling the base type's destructor. In C# code, Object..::.Finalize cannot be called or overridden.

A type must implement Finalize when it uses unmanaged resources such as file handles or database connections that must be released when the managed object that uses them is reclaimed. See the IDisposable interface for a complementary and more controllable means of disposing resources.

Finalization is the process by which GC allows objects to clean up any unmanaged resources they're holding before actual instance is destroyed. Implementation of finalize is called finalizer. Finalize is protected and, therefore, is accessible only through this object class or a derived class.

This method is automatically called after an object becomes inaccessible, unless the object has been exempted from finalization by a call to SuppressFinalize.

Generations:

The GC maintains lists of managed objects arranged in "generations." A generation is a measure of the relative lifetime of the objects in memory. Recently created objects are stored in lower generations compared to those created earlier in the application's life cycle. Longer-lived objects get promoted to higher generations.

Indexers:


  1. Indexers allow instances of a class or struct to be indexed just like arrays. Indexers resemble properties except that their accessors take parameters.
  2. Indexers enable objects to be indexed in a similar manner to arrays.
  3. A get accessor returns a value. A set accessor assigns a value.
  4. The this keyword is used to define the indexers.
  5. The value keyword is used to define the value being assigned by the set indexer.
  6. Indexers do not have to be indexed by an integer value; it is up to you how to define the specific look-up mechanism.
  7. Indexers can be overloaded. only instance members are allowed.
  8. Indexers can have more than one formal parameter, for example, when accessing a two-dimensional array.
  9. properties enable field-like access, indexers enable array-like access.Static indexers are not allowed in C#. 
MultiThreading & System.Threading:

The System.Threading namespace provides classes and interfaces that enable multithreaded programming. In addition to classes for synchronizing thread activities and access to data ( Mutex, Monitor, Interlocked, AutoResetEvent, and so on), this namespace includes a ThreadPool class that allows you to use a pool of system-supplied threads, and a Timer class that executes callback methods on thread pool threads.

Thread.CurrentPrincipal returns the user associated with the thread and CurrentThread returns the currently executing thread.Thread.Join blocks the calling thread and waits until the current thread terminates or completes.

Thread.resume and Thread.suspend are retired instead we should use thread Synchronization methods like InterLocked method which solves threading issues as well as shields from hyper threading as well as multi processors mode. 

The synchronization locks like monitor work by blocking other threads from access to the code(Critical Section) while thread is inside the lock. but these locks can introduce deadlocks.

Other thread synchronization methods like ReaderWriterLock, Mutex, Semaphore. Mutex is heavy weight object compared to Monitor since it's a kernel object(specific to OS). But Mutex class can lock data across AppDomain and process boundaries,

To retrieve results of Asynchronous operation use IAsyncResult Interface. To Perform asynchronous operations without overhead of threads use ThreadPool.

Other Miscellaneous points to remember:


  1. You must use the Missing class and pass Missing.Value (in System.Reflection) for any values that have optional parameters. 
  2. In a garbage collected environment, it's impossible to get true determinism. However, a design pattern ts implementing IDisposable on any class that contains a critical resource. Whenever this class is consumed, it may be placed in a using statement
  3. Convert.ToInt32 also converts a string (or some other valid types) into a variable of type int. It basically behaves the same way as Int32.Parse() except that it won't throw an exception System.NullArgumentException if a null string is passed to the method, instead it will return 0.
  4. Int32.Parse converts a string variable (or some other valid types) into a variable of type int. However if you pass a non-recognized value (text string, empty string or null string), it will throw an exception (System.NullArgumentException if null else System.FormatException)
  5. you may prefer to use the new Int32.TryParse method, which accepts a string, an ouput int and returns true or false if the conversion succeeds. If the conversion succeeds, the output int is set to the result.
  6. Custom attributes for the assemblies can be set in AssemblyInfo.cs file.
  7. Use the regasm.exe utility to generate a type library (if needed) and the necessary entries in the Windows Registry to make a class available to classic COM clients. Once a class is registered in the Windows Registry with regasm.exe, a COM client can use the class as though it were a COM class. 
  8. For value types: use “==” For reference types: use Equals method.
  9. You can create an alias within a single file with the "using" directive
  10. Structs differ from classes in several important ways; however, structs are value types rather than reference types, and inheritance is not supported for structs. Struct values are stored on the stack 
  11. With regard to versioning, interfaces are less flexible than classes. 
  12. With a class, you can ship version 1 and then, in version 2, decide to add another method. As long as the method is not abstract (i.e., as long as you provide a default implementation of the method), any existing derived classes continue to function with no changes. Because interfaces do not support implementation inheritance, this same pattern does not hold for interfaces. Adding a method to an interface is like adding an abstract method to a base class--any class that implements the interface will break, because the class doesn't implement the new interface method.
  13. There is no way to restrict to a namespace. Namespaces are never units of protection. But if you're using assemblies, you can use the 'internal' access modifier to restrict access to only within the assembly. 
  14. if u want to keyword as an identifier use @ with it.e.g int @checked=9;
  15. How do you mark a method obsolete?
  16. [Obsolete("This is a message describing why this method is obsolete")]
  17. Can you declare the override method static while the original method is non-static? 
  18. No, you cannot, the signature of the virtual method must remain the same, only the keyword virtual is changed to keyword override. 
  19. If a base class has a bunch of overloaded constructors, and an inherited class has another bunch of overloaded constructors, can you enforce a call from an inherited constructor to an arbitrary base constructor? 
  20. Yes, just place a colon, and then keyword base (parameter list to invoke the appropriate constructor) in the overloaded constructor definition inside the inherited class. 
  21. What is the difference between the System.Array.CopyTo() and System.Array.Clone()? 
  22. The first one performs a deep copy of the array, the second one is shallow. 
  23. What are the ways to deploy an assembly? 
  24. An MSI installer, a CAB archive, and XCOPY command. 
  25. What namespaces are necessary to create a localized application? 
  26. System.Globalization, System.Resources. 
  27. What is the difference between // comments, /* */ comments and /// comments? 
  28. Single-line, multi-line and XML documentation comments. 
  29. What does the This window show in the debugger? 
  30. It points to the object that is pointed to by this reference. Object’s instance data is shown. 
  31. Why are there five tracing levels in System.Diagnostics.TraceSwitcher? 
  32. The tracing dumps can be quite verbose and for some applications that are constantly running you run the risk of overloading the machine and the hard drive there. Five levels range from None to Verbose, allowing to fine-tune the tracing activities. 
  33. How do you debug an ASP.NET Web application? 
  34. Attach the aspnet_wp.exe process to the DbgClr debugger. 
  35. What are three test cases you should go through in unit testing? 
  36. Positive test cases (correct data, correct output), negative test cases (broken or missing data, proper handling), exception test cases (exceptions are thrown and caught properly). 
  37. Visual Studio Windows (Immediate/Command):
    The Immediate window is used at design time to debug and evaluate expressions, execute statements, print variable values, and so forth. It allows you to enter expressions to be evaluated or executed by the development language during debugging. To display the Immediate window, open a project for editing, then choose Windows from the Debug menu and select Immediate.
    IMMEDIATE WINDOW:Preface the expression with a question mark (?).
    Temporarily enter Command mode while in Immediate mode (to execute a single command).
     Enter the command, prefacing it with a greater than sign (>).
     >alias
    Switch to the Command window.
     Enter cmd into the window, prefacing it with a greater than sign (>).
     >cmd
    Switch back to the Immediate window.
     Enter immed into the window without the greater than sign (>).
    Differences between IComparable and IComparer:
    Any class that implements IComparable is *comparable*. That is, you can
    compare an instance of that class with another instance in a manner that
    you define.
    class that implements IComparer is a comparer i.e a class that imposes ordering on a
    set of objects.
    When you want to sort an unsorted array of objects of the same class,
    you can either make the class implement IComparable, or you can
    implement IComparer in a separate class, and pass that to Array.Sort().
    Of course if the comparison is done based on a *private* member of the
    class, IComparable is more appropriate, since having your IComparator
    implementation be able to access its private members may not be
    possible/appropriate.
    Any class that implements IComparable is *comparable*. That is, you can
    compare an instance of that class with another instance in a manner that
    you define.
    OTOH, a class that implements IComparer is a... well, a comparer (Java
    people call this a Comparator), i.e.: a class that imposes ordering on a
    set of objects.
    When you want to sort an unsorted array of objects of the same class,
    you can either make the class implement IComparable, or you can
    implement IComparer in a separate class, and pass that to Array.Sort().
    Of course if the comparison is done based on a *private* member of the
    class, IComparable is more appropriate, since having your IComparator
    implementation be able to access its private members may not be
    possible/appropriate.
    .Net Security : Code Access security (CAS):
    CAS is only useful for partial trust assemblies. Run time completely ignores CAS for full trust assemblies.
    Using CAS Assembly declarations prevent the applications from running without sufficient permissions and restrict the permissions granted to the assemblies.
    There are three types of CAS assembly declarations like RequestMinimum, RequestOptional and RequestRefuse.
    there are six methods to control permissions in an assembly: Assert, LinkDemand, Demand, Deny, InheritanceDemand, PermitOnly
    LinkDemand and demand should be used when accessing custom resources or unmanaged code. You should use PermitOnly and Deny within an assembly being misused by an attacker.
    To protect methods declaratively and imperatively we can use demand and linkdemand.
    Interface based Programming:


Interfaced-based design provides loose coupling, true component-based programming, easier maintainability and it makes code reuse much more accessible because implementation is separated from the interface.Separation of interface from implementation is a core principle of component-oriented programming.  the client is coded against an abstraction of a service (the interface), not a particular implementation of it (the object). As a result, changing an implementation detail on the server side (or even switching to a different service provider altogether) doesn’t affect the client.

When different service providers share a common base class, they all become polymorphic with that service abstraction,

There are a few important differences between an abstract class and an interface: 
  • An abstract class can still have implementation: it can have member variables or non-abstract methods or properties. An interface can’t have implementation or member variables. 
  • A .NET class can derive from only one base class, even if that base class is abstract. However, a .NET class can implement as many interfaces as required. 
  • An abstract class can derive from any other class or from one or more interfaces. An interface can derive only from other interfaces. 
  • An abstract class can have nonpublic (protected or private) methods and properties, even if they are all abstract. In an interface, by definition, all members are public. 
  • An abstract class can have static methods and static members and can define constants. An interface can have none of those. 
  • An abstract class can have constructors. An interface can’t. 
These differences are deliberately in place, not to restrict interfaces, but rather to provide for a formal public contract between a service provider (the classes implementing the interface) and the service consumer (the client of the classes). Disallowing any kind of implementation details in interfaces (such as method implementations, constants, static members, and constructors) enables .NET to promote loose coupling between the service providers and the client. Because there is nothing in the contract that even hints at implementation, by definition the implementation is well encapsulated behind the interface, and service providers are free to change their implementations without affecting the client. You can even say that the interface acts like a binary shield, isolating each party from the other.

Interfaces features:

Because interfaces can’t be instantiated, .NET forces clients to choose a particular implementation to instantiate. Having only public members in an interface complements the contract semantics nicely: you would not want a contract with hidden clauses or "fine print." Everything the contract implies should be public and well defined. The more explicit and well defined a contract is, the less likely it is that there will be conflicts down the road regarding exactly what the class providing the service is required to do. The class implementing the interface must implement all the interface members without exception, because it has committed to providing this exact service definition. An interface can extend only other interfaces, not classes. By deriving a new interface from an existing interface, you define a new and specialized contract, and any class that implements that interface must implement all members of the base interface(s). A class can choose to implement multiple interfaces, just as a person can choose to commit to multiple contracts.

To interact with an object using an interface, all a client has to do is instantiate a concrete class that supports the interface and assign that object to an interface variable, similar to using any other base type. Using the same definitions as in Example 3-1, the client code might be:

IMyInterface obj;
obj = new MyClass( );
obj.Method1( );

Interfaces promote loose coupling between clients and objects.

Treating interfaces as binary contracts, which shields clients from changes made to the service providers, is exactly the idea behind COM interfaces, and logically, .NET interfaces have the same semantics as COM interfaces. If you are an experienced COM developer or architect, working with interfaces is probably second nature to you, and you will feel right at home with .NET interfaces.

Interfaces are abstract types and, as such, can’t be used directly. To use an interface, you need to cast into an interface reference an object that supports it. There are two types of casting—implicit and explicit—and which type you use has an impact on type safety.

Assigning a class instance to an interface variable directly is called an implicit cast, because the compiler is required to figure out which type to cast the class to:

Abstract Software Factory Design pattern:



The Abstract Factory provides an interface for creating families of related or dependent objects without specifying their concrete classes. 

public abstract class FactoryBase
{
    public abstract Product FactoryMethod(int type);
}

public class ConcreteFactory : FactoryBase
{
    public override Product FactoryMethod(int type)
    {
        switch (type)
        {
            case 1:
                return new ConcreteProduct1();

            case 2:
                return new ConcreteProduct2();

            default:
                throw new ArgumentException("Invalid type.", "type");
        }
    }
}


public abstract class ProductBase { }

public class ConcreteProduct1 : ProductBase { }

public class ConcreteProduct2 : ProductBase { }


Singleton pattern:

The singleton pattern is a Gang of Four design pattern. This is a creational pattern as it is to control class instantiation. The pattern ensures that only one object of a particular class is ever created. All further references to objects of the singleton class refer to the same underlying instance.


WCF supported protocols:

WCF allows you to publish and consume services using a variety of different protocols and switch between them relatively painlessly.Using WCF you can communicate over standard HTTP, TCP/IP, named pipes, Message Queues, and use a variety of different protocols like standard SOAP 1.x, WS-* Web services protocols, or use highly-optimized binary representations of the WS-* protocols.

So, for example, it’s almost trivial to publish a WCF service that publishes its service contract via HTTP as well as using TCP/IP. It’s nearly as easy to allow a WCF client to consume that same service either over HTTP or TCP/IP. Although the protocol and session semantics of HTTP and TCP/IP communication are vastly different, WCF can provide a common model to access either one of these services.

WCF as a whole is based solidly on W3C standards or recommendations-all WCF messages are based on SOAP and the SOAP 1.x, WSDL 1.x./2.0 and WS-* protocols,

Both WCF services and the client can easily switch between different bindings and access services through different protocols with the same codebase.

Contract Based Programming:

WCF encourages contract-based programming, which means that it tries to push you into defining your service contract interface explicitly with a .NET interface that you then implement explicitly on an implementation class. The contract interface is marked up with a ServiceContract attribute with each exposed service method marked with an OperationContract attribute.

Data Contracts:

In addition, you can also define data contracts to explicitly specify how to expose return values and parameters (message types) to the service. You define a data contract on a class with the class marked with a DataContract attribute and each member that is to be published on the class marked with an explicit DataMember attribute. You can then use these types as part of your service method parameters and return values and be guaranteed that your messages published in the WSDL (and correspondingly by any WCF proxies) match the signature of the data contract.

Unfortunately you cannot define data contracts on interfaces so you must define them on implementation classes or structs so there’s a bit more tight coupling in this mechanism than with a service contract.

Special Metadata Endpoint:

WCF uses a special metadata exchange (MEX) endpoint to provide the service definition to clients. The MEX endpoint can be accessed by clients over any of the protocols the service supports. One unobvious gotcha is that MEX functionality is not enabled by default

MSMQ - Poison Message:

A poison message is a message that has exceeded the maximum number of delivery attempts to the application. This situation can arise when a queue-based application cannot process a message because of errors. To meet reliability demands, a queued application receives messages under a transaction. Aborting the transaction in which a queued message was received leaves the message in the queue so that the message is retried under a new transaction. If the problem that caused the transaction to abort is not corrected, the receiving application can get stuck in a loop receiving and aborting the same message until the maximum number of delivery attempts has been exceeded and a poison message results.

A message can become a poison message for many reasons. The most common reasons are application specific. For example, if an application reads a message from a queue and performs some database processing, the application may fail to get a lock on the database, causing it to abort the transaction. Because the database transaction was aborted, the message remains in the queue, which causes the application to reread the message a second time and make another attempt to acquire a lock on the database. Messages can also become poison if they contain invalid information