.NET Technical bits: May 2011

Wednesday, May 11, 2011

Difference between WCF and ASP.NET Web Services

Data translation:
ASP.NET web service depends on defining data and relies on the XmlSerializer to transform data to or from a service.

There are few issues with XmlSerializer to XML from serialize .NET types.

• The translated XML will have only the public fields or properties of .NET types

• The implemented class from IDictionary (ex: hash table) cannot be translated

• This will have the classes which implement IEnumerable interface

The WCF uses the attributes DataContract attribute and DataMemeber attribute to translate .NET types in to XML.

[DataContract]
public class Member
{
       [DataMember]
       public int memberID;
       [DataMember]
       public string memberName;
       [DataMember]
       public decimal salary;
}

The DataContractAttribute can be used for class or a struct. DataMemberAttribute can be used for private/public field or property.

DataContractSerializer and XMLSerializer:

• Performance wise DataContractSerializer better than XMLserialization

• DataContratSerializer Explicitly shows the which fields or properties are serialized into XML but XMLSerializer is not

• Hash Table can be translated in DataContractSerializer

Creating WCF and Web Services:

When we create a web service the WebService attribute need to be added to the web service class and WebMethod Attribute need to be added for any web service class methods.
For Example:

[WebService]
public class MyService : System.Web.Services.WebService
{
      [WebMethod]
      public string InvokeMe(string message)
     {
            return message;
     }
}

To create a WCF service we will write this code:
[ServiceContract]
public interface IMyService
{
        [OperationContract]
        string InvokeMe(string message);
}

public class MyService : IMyService
{
        public string InvokeMe (string message)
       {
              return message;
       }
}

The interface defines a WCF service contract using the ServiceContract attribute and the OperationContract tells which of the methods of the interface defines the operations of the service contract. The service type in WCF will be referred to as a class that implements the service.

Hosting the Services:
ASP.NET web services are created and compiled and will be hosted in IIS. This hosted will have the service file with extension .asmx and will have assembly with the compiled class. The hosted .asmx url can be added as a web reference to a .NET project so that the class and methods from service will be accessible in the project.
WCF Service can be hosted within IIS or WindowsActivationService using the steps below.

• Compile the service type into a class library.

• Copy the service file with an extension .SVC into a virtual directory and assembly into bin sub directory of the virtual directory.

• Copy the web.config file into the virtual directory.