Q. What is WCF ?
Answer: Windows Communication Foundation (Code named Indigo) is a programming platform and runtime system for building, configuring and deploying network-distributed services. It is the latest service oriented technology.WCF provides a common platform for all .NET communication.
Q.2. Diffrence Between Web Service & Wcf ?
Answer:
| Features | Web Service | WCF |
|---|---|---|
| Hosting | It can be hosted in IIS | It can be hosted in IIS, windows activation service, Self-hosting, Windows service |
| Programming | [WebService] attribute has to be added to the class | [ServiceContraact] attribute has to be added to the class |
| Model | [WebMethod] attribute represents the method exposed to client | [OperationContract] attribute represents the method exposed to client |
| Operation | One-way, Request- Response are the different operations supported in web service | One-Way, Request-Response, Duplex are different type of operations supported in WCF |
| XML | System.Xml.serialization name space is used for serialization | System.Runtime.Serialization namespace is used for serialization |
| Encoding | XML 1.0, MTOM(Message Transmission Optimization Mechanism), DIME, Custom | XML 1.0, MTOM, Binary, Custom |
| Transports | Can be accessed through HTTP, TCP, Custom | Can be accessed through HTTP, TCP, Named pipes, MSMQ,P2P, Custom |
| Protocols | Security | Security, Reliable messaging, Transactions |
Q.3.WCF Fundamental
- Endpoint
- Binding & Behavior
- Contracts & services host
- Message & channel
- Clint & Metadata
Endpoint
WCF Service is a program that exposes a collection of Endpoints. Each Endpoint is a portal for communicating with the world.End point consists of three components.
A - Address
B - Binding
C - Contract
Address :
Basically URL, specifies where this WCF service is hosted .Client will use this url to connect to the serviceFor Example http://localhost:8010/Service/IService.svcBinding : how client will communicate with service.There are different protocols available for the WCF to communicate to the Client.
- Transport -Defines the base protocol to be used like HTTP, Named Pipes, TCP, and MSMQ are some type of protocols.
- Encoding (Optional) - Three types of encoding are available-Text, Binary, or Message Transmission .
- Protocol(Optional) - Defines information to be used in the binding such as Security, transaction or reliable messaging capability
The following table gives some list of protocols supported by WCF binding.
| Binding | Description |
|---|---|
| BasicHttpBinding | Basic Web service communication. No security by default |
| WSHttpBinding | Web services with WS-* support. Supports transactions |
| WSDualHttpBinding | Web services with duplex contract and transaction support |
| WSFederationHttpBinding | Web services with federated security. Supports transactions |
| MsmqIntegrationBinding | Communication directly with MSMQ applications. Supports transactions |
| NetMsmqBinding | Communication between WCF applications by using queuing. Supports transactions |
| NetNamedPipeBinding | Communication between WCF applications on same computer. Supports duplex contracts and transactions |
| NetPeerTcpBinding | Communication between computers across peer-to-peer services. Supports duplex contracts |
| NetTcpBinding | Communication between WCF applications across computers. Supports duplex contracts and transactions |
Contract :
Collection of operation that specifies what the endpoint will communicate with outside world.

Example:
Endpoints will be mentioned in the web.config file on the created service.
contract="Iservice"
Binding="wshttpBinding"/>
Binding & BehaviorBinding describes how the client will communicate with service.<system.serviceModel><services><service name="MathService"
behaviorConfiguration="MathServiceBehavior"><endpoint address="" contract="IMathService"
binding="wsHttpBinding"/></service></services><behaviors><serviceBehaviors><behavior name="MathServiceBehavior"><serviceMetadata httpGetEnabled="True"/><serviceDebug includeExceptionDetailInFaults="true" /></behavior></serviceBehaviors></behaviors></system.serviceModel>
Example:
Endpoints will be mentioned in the web.config file on the created service.
contract="Iservice"Binding="wshttpBinding"/>Binding & BehaviorBinding describes how the client will communicate with service.<system.serviceModel><services><service name="MathService"behaviorConfiguration="MathServiceBehavior"><endpoint address="" contract="IMathService"binding="wsHttpBinding"/></service></services><behaviors><serviceBehaviors><behavior name="MathServiceBehavior"><serviceMetadata httpGetEnabled="True"/><serviceDebug includeExceptionDetailInFaults="true" /></behavior></serviceBehaviors></behaviors></system.serviceModel>
Contracts & Service host
Contracts : there are four types of contracts available in WCF.
- Service contracts
- Data contract
- Message Contract
- Fault Contract
Service Contracts :
Service contract describes the operation that service provide. A Service can have more than one service contract but it should have at least one Service contract.
Service Contract can be define using [ServiceContract] and [OperationContract] attribute. [ServiceContract] attribute is similar to the [WebServcie] attribute in the WebService and [OpeartionContract] is similar to the [WebMethod] in WebService.
[ServiceContract()]
public interface ISimpleCalculator
{
[OperationContract()]
int Add(int num1, int num2);
}
Once we define Service contract in the interface, we can create implement class for this interface.
public class SimpleCalculator : ISimpleCalculator
{
public int Add(int num1, int num2)
{
return num1 + num2;
}
}
DataContract : A data contract is a formal agreement between a service and a client that abstractly describes the data to be exchanged.Data contract can be explicit or implicit. Simple type such as int, string etc has an implicit data contract. User defined object are explicit or Complex type. a Data contract using [DataContract] and [DataMember] attribute.
[ServiceContract]
public interface IEmployeeService
{
[OperationContract]
Employee GetEmployeeDetails(int EmpId);
}
[DataContract]
public class Employee
{
private string m_Name;
private int m_Age;
private int m_Salary;
private string m_Designation;
private string m_Manager;
[DataMember]
public string Name
{
get { return m_Name; }
set { m_Name = value; }
}
[DataMember]
public int Age
{
get { return m_Age; }
set { m_Age = value; }
}
[DataMember]
public int Salary
{
get { return m_Salary; }
set { m_Salary = value; }
}
[DataMember]
public string Designation
{
get { return m_Designation; }
set { m_Designation = value; }
}
[DataMember]
public string Manager
{
get { return m_Manager; }
set { m_Manager = value; }
}
}
Client side
On client side we can create the proxy for the service and make use of it. The client side code is shown below.
protected void btnGetDetails_Click(object sender, EventArgs e)
{
EmployeeServiceClient objEmployeeClient = new EmployeeServiceClient();
Employee empDetails;
empDetails = objEmployeeClient.GetEmployeeDetails(empId);
//Do something on employee details
}
Message Contract : Message is the packet of data which contains important information. WCF uses these messages to transfer information from Source to destination.
Message Pattern
It describes how the programs will exchange message each other. There are three way of communication between source and destination
- Simplex - It is one way communication. Source will send message to target, but target will not respond to the message.
- Request/Replay - It is two way communications, when source send message to the target, it will resend response message to the source. But at a time only one can send a message
- Duplex - It is two way communication, both source and target can send and receive message simultaniouly.
[MessageContract]
public class EmployeeDetails
{
[MessageHeader]
public string EmpID;
[MessageBodyMember]
public string Name;
[MessageBodyMember]
public string Designation;
[MessageBodyMember]
public int Salary;
[MessageBodyMember]
public string Location;
}
Fault Contract : when we develop managed application or service, we will handle the exception using try- catch block. But these exceptions handlings are technology specific.
By default when we throw any exception from service, it will not reach the client side. WCF provides the option to handle and convey the error message to client from service using SOAP Fault contract.
Step 1: I have created simple calculator service with Add operation which will throw general exception as shown below
//Service interface
[ServiceContract()]
public interface ISimpleCalculator
{
[OperationContract()]
int Add(int num1, int num2);
}
//Service implementation
public class SimpleCalculator : ISimpleCalculator
{
public int Add(int num1, int num2)
{
//Do something
throw new Exception("Error while adding number");
}
}
Step 2: On client side code. Exceptions are handled using try-Catch block. Even though I have capture the exception when I run the application. I got the message that exceptions are not handled properly.
try
{
MyCalculatorServiceProxy.MyCalculatorServiceProxy proxy
= new MyCalculatorServiceProxy.MyCalculatorServiceProxy();
Console.WriteLine("Client is running at " + DateTime.Now.ToString());
Console.WriteLine("Sum of two numbers... 5+5 =" + proxy.Add(5, 5));
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
}

Step 3: Now if you want to send exception information form service to client, you have to use FaultException as shown below.
public int Add(int num1, int num2)
{
//Do something
throw new FaultException("Error while adding number");
}
Step 4: Output window on the client side is show below.

Step 5: You can also create your own Custom type and send the error information to the client using FaultContract. These are the steps to be followed to create the fault contract.
- Define a type using the data contract and specify the fields you want to return.
- Decorate the service operation with the FaultContract attribute and specify the type name.
- Raise the exception from the service by creating an instance and assigning properties of the custom exception.
Step 6: Defining the type using Data Contract
[DataContract()]
public class CustomException
{
[DataMember()]
public string Title;
[DataMember()]
public string ExceptionMessage;
[DataMember()]
public string InnerException;
[DataMember()]
public string StackTrace;
}
Step 7: Decorate the service operation with the FaultContract [ServiceContract()]
public interface ISimpleCalculator
{
[OperationContract()]
[FaultContract(typeof(CustomException))]
int Add(int num1, int num2);
}
Step 8: Raise the exception from the service
public int Add(int num1, int num2)
{
//Do something
CustomException ex = new CustomException();
ex.Title = "Error Funtion:Add()";
ex.ExceptionMessage = "Error occur while doing add function.";
ex.InnerException = "Inner exception message from serice";
ex.StackTrace = "Stack Trace message from service.";
throw new FaultException(ex,"Reason: Testing the Fault contract") ;
}
} Step 9: On client side, you can capture the service exception and process the information, as shown below.
try
{
MyCalculatorServiceProxy.MyCalculatorServiceProxy proxy
= new MyCalculatorServiceProxy.MyCalculatorServiceProxy();
Console.WriteLine("Client is running at " + DateTime.Now.ToString());
Console.WriteLine("Sum of two numbers... 5+5 =" + proxy.Add(5, 5));
Console.ReadLine();
}
catch (FaultException ex)
{
//Process the Exception
}
{
//Process the Exception
}
No comments:
New comments are not allowed.