Friday, 4 November 2011

WCF vs webservices

A. Difference between Webservices and WCF

1)WCF comes with .Net frame work 3.0/3.5. To use in 2.0 frame work we need to install MS add in component.

2)Web service can be hosted on IIS only where as WCF can be hosted on IIS, Self hosting, Windows service and Windows activation service. Since WCF can be hosted in different applications it is flexible.

3)WebService and WebMethod are used in web services where as in WCF - Service contracts, Operation contacts, Message contacts, Data contacts and Fault contacts are used in the service.

4)WebService can be accessed over HTTP, TCP, Custom where as WCF can be accessed over HTTP, TCP, Named pipes, MSMQ , Custom and P2P.

5)In Webservice unhandled exceptions are returned to clients where as in WCF a configuration settins is provided for these faults.

6)Webservice use System.Xml.serialization to translate data where as WCF uses System.Runtime.Serialization name-space.

Monday, 17 October 2011

Two Interfaces having same method and same parameters


Code Snippet
    public interface I1
    {
        void Method();   
    }
    public interface I2
    {
        void Method();
    }
    public class Implementor : I1, I2
    {
        public void Method()
        {
            Trace.WriteLine("Method");
        }
    }
            I1 i1 = new Implementor();
            I2 i2 = new Implementor();
            i1.Method();
            i2.Method();



If you want separate methods per interface, implement them explicitly:
Code Snippet
    public interface I1
    {
        void Method();   
    }
    public interface I2
    {
        void Method();
    }
    public class Implementor : I1, I2
    {
        #region I1 Members

        void I1.Method()
        {
            throw new NotImplementedException();
        }

        #endregion

        #region I2 Members

        void I2.Method()
        {
            throw new NotImplementedException();
        }

        #endregion
    }

Collections

Types of Collections in .NET

There are many types of collections in the .Net Framework 2.0. The most general types of them are under the "System.Collections" namespace. All of them have the following basic methods and properties to manipulate the stored data. "Add" to add a new element, "Remove" to remove an existing element, and "Count" to get the total number of elements stored in a collection.

Non-Generic Collections

Found under the "System.Collections" namespace.
ArrayList: an array of contiguous indexed elements whose size can be increased dynamically at run time as required. You can use this data structure to store any types of data like integers, strings, structures, objects, .....
BitArray: an array of contiguous bit values (zeros and ones). Its size must be determined at design time.
SortedList: represents a list of key/value pair elements, sorted by keys and can be accessed by key and by index.
Stack: represents the data structure of last-in-first-out (LIFO).
Queue: represents the data structure of first-in-first-out (FIFO).
HashTable: represents a collection of key/value pair elements stored based on the hash code of the key.

Generic Collections


Found under the "System.Collections.Generic" namespace.
LinkedList: represents a doubly linked list data structure of a specified data type.
Dictionary: represents a collection of keys and values.
List: the generic counterpart of the ArrayList collection.
Queue: the generic counterpart of the non-generic Queue collection.
Stack: the generic counterpart of the non-generic Stack collection

Saturday, 15 October 2011

Different Types of Serialization

The Microsoft .NET Framework provides an almost bewildering variety of ways to serialize an object.

XML Serialization

XML serialization allows the public properties and fields of an object to be reduced to an XML document that describes the publicly visible state of the object. This method serializes only public properties and fields—private data will not be persisted, so XML serialization does not provide full fidelity with the original object in all cases. However, because the persistence format is XML, the data being saved can be read and manipulated in a variety of ways and on multiple platforms.
The benefits of XML serialization include the following:
  • Allows for complete and flexible control over the format and schema of the XML produced by serialization.
  • Serialized format is both human-readable and machine-readable.
  • Easy to implement. Does not require any custom serialization-related code in the object to be serialized.
  • The XML Schema Definition tool (xsd.exe) can generate an XSD Schema from a set of serializable classes, and generate a set of serializable classes from an XSD Schema, making it easy to programmatically consume and manipulate nearly any XML data in an object-oriented (rather than XML-oriented) fashion.
  • Objects to be serialized do not need to be explicitly configured for serialization, either by the SerializableAttribute or by implementing the ISerializable interface.
The restrictions of XML serialization include the following:
  • The class to be serialized must have a default (parameterless) public constructor.
  • Read-only properties are not persisted.
  • Only public properties and fields can be serialized.

SOAP Serialization

SOAP serialization is similar to XML serialization in that the objects being serialized are persisted as XML. The similarity, however, ends there. The classes used for SOAP serialization reside in the System.Runtime.Serialization namespace rather than the System.Xml.Serialization namespace used by XML serialization. The run-time serialization classes (which include both the SoapFormatter and the BinaryFormatter classes) use a completely different mechanism for serialization than the XmlSerializer class.
The benefits of SOAP serialization include the following:
  • Produces a fully SOAP-compliant envelope that can be processed by any system or service that understands SOAP.
  • Supports either objects that implement the ISerializable interface to control their own serialization, or objects that are marked with the SerializableAttribute attribute.
  • Can deserialize a SOAP envelope into a compatible set of objects.
  • Can serialize and restore non-public and public members of an object.
The restrictions of SOAP serialization include the following:
  • The class to be serialized must either be marked with the SerializableAttribute attribute, or must implement the ISerializable interface and control its own serialization and deserialization.
  • Only understands SOAP. It cannot work with arbitrary XML schemas.

Binary Serialization

Binary serialization allows the serialization of an object into a binary stream, and restoration from a binary stream into an object. This method can be faster than XML serialization, and the binary representation is usually much more compact than an XML representation. However, this performance comes at the cost of cross-platform compatibility and human readability.
The benefits of binary serialization include the following:
  • It's the fastest serialization method because it does not have the overhead of generating an XML document during the serialization process.
  • The resulting binary data is more compact than an XML string, so it takes up less storage space and can be transmitted quickly.
  • Supports either objects that implement the ISerializable interface to control its own serialization, or objects that are marked with the SerializableAttribute attribute.
  • Can serialize and restore non-public and public members of an object.
The restrictions of binary serialization include the following:
  • The class to be serialized must either be marked with the SerializableAttribute attribute, or must implement the ISerializable interface and control its own serialization and deserialization.
  • The binary format produced is specific to the .NET Framework and it cannot be easily used from other systems or platforms.
  • The binary format is not human-readable, which makes it more difficult to work with if the original program that produced the data is not available.

Difference between "throw" and "throw ex" in .NET

Exception handling seems to be a common problem for .NET developers, particularly younger developers. We pretty much all know that you should wrap operations that have the potential for failing in a try/catch block if you are interested in being able to do something about the error that occurred. I'm not going to talk about the rules and guidelines for using exception handling. Instead I'm going to focus on a particular aspect of exception handling, which I tend to call exception bubbling.
Exception bubbling means that even though you are catching the exception and doing something with it, you want that exception to "bubble" up from your code to the calling code so it has a chance to do something with that exception. This is a fairly common scenario, but it has the potential to cause some major problems when you are debugging.
I'm sure most of the exception bubbling code you've seen looks similar to this
   1: try
   2: {
   3:     // do some operation that can fail
   4: }
   5: catch (Exception ex)
   6: {
   7:     // do some local cleanup
   8:     throw ex;
   9: }
This code looks perfectly reasonable and does the job. It properly catches the exception, does some local cleanup and then bubbles the exception up the chain. (A side note here is that you really shouldn't catch a general exception like this. I'm doing this for simplicity in the examples, but you should be catching specific exceptions and only those that you can do something about.)
However, how  many of you have seen code that looks like this
   1: try
   2: {
   3:     // do some operation that can fail
   4: }
   5: catch (Exception ex)
   6: {
   7:     // do some local cleanup
   8:     throw;
   9: }
There is a subtle difference between these two calls that won't be apparent until you are trying to debug the problem. That difference is in the stack trace information that gets sent with the exception.
In the first case, the stack trace is truncated below the method that failed. What this means is that when you look at the stack trace, it will look as if the exception originated in your code. This isn't always the case, particularly if you are bubbling up a CLR generated exception (like a SqlException). This is a problem known as "breaking the stack", because you no longer have the full stack trace information. This happens because you are in essence creating a new exception to throw.
By using "throw" by itself, you preserve the stack trace information. You can confirm this by looking at the IL generated for these two code blocks. This makes the difference very obvious since in the first example the IL instruction called is "throw" while in the second the instruction is called "rethrow".
Before you run and change all of your code, there are still places where "throw ex" is appropriate. There are times when you want to add information to the exception that was caught or change it into a more meaningful exception. In these instances you actually want a new exception to be thrown. Again, there are two ways you can do this. The most common way that I have seen is
   1: try
   2: {
   3:     // do some operation that can fail
   4: }
   5: catch (Exception ex)
   6: {
   7:     // do some local cleanup
   8:     throw new ApplicationException("operation failed!");
   9: }
However, this still suffers the problem of breaking the stack. Here you are generating a completely new exception and loosing any of the stack trace information from the original exception. What you really want to do is
   1: try
   2: {
   3:     // do some operation that can fail
   4: }
   5: catch (Exception ex)
   6: {
   7:     // do some local cleanup
   8:     throw new ApplicationException("operation failed!", ex);
   9: }
By passing the original exception to the ApplicationException you are preserving the original exception, and it's stack trace information, as the inner exception to your ApplicationException.
To wrap everything up
    1. Only catch exceptions if they are important to you and you need to do some sort of cleanup as a result.
    2. If you need to bubble an exception up the chain, use "throw" by itself.
    3. If you need to add information to the exception or repackage it, always pass the original exception as the inner exception

How to declare a pure virtual function in C# ?

Firstly, the class must always be declared abstract.
Secondly, the method must be declared abstract.
The following is a simple example of an abstract method:
abstract class AbstractClass
{
   public abstract void AbstractMethod();
}

Friday, 14 October 2011

How does the server identify a browser ?

The first time when a browser request a page, server establishes a session and creates a session Id. Server returns this ID to the browser as part of the 'Response'. This ID is not displayed to the user. Browser will keep this internally.

There are cases where this Session ID can be visible to the users. Visit HomeDepot.com and hit any link from the home page. Then check the URL in the browser. You can see a string like BV_SessionID=@@@@0941891585.1123945660@@@@. This number represents the session id. This particular site sends the session id as a query string in the URL. If you delete this session id from the url, server will treat it as a new session and will create a new session.

But ideally, in a ASP.NET web site, there is no need to make the session id publicly visible. Server can keep it internally and send to server without annoying you.

After the browser gets a session ID, it will send the session ID to the server along with each additional page requests it makes. The webserver can identify the sessions using this Id. For some reason, if the session times out, then this ID will be no longer valid. In such cases, server will create a new session and will treat this request as a new request.