In the previous article, I have introduced Windows Communication Foundation and how it helps in implementing Service Oriented Architecture. In this article, we will look into some more of the fundamentals and try to develop a simple service. Before coming into development, let us discuss the concepts like message, channels, bindings, contracts, and end-points. After that we can enter the world of services.

Introduction:

In the previous article, I have introduced Windows Communication Foundation and how it helps in implementing Service Oriented Architecture. In this article, we will look into some more of the fundamentals and try to develop a simple service. Before coming into development, let us discuss the concepts like message, channels, bindings, contracts, and end-points. After that we can enter the world of services.

Some Important Concepts:

In the previous article, I have already mentioned that, to under workings of WCF service, the following concepts are important:
Services
Message — message structures and patterns.
Channel
Binding
Contracts
• End Points

Let us understand these concepts first.

Services:

Service is a .Net class which have some methods exposed through the WCF. Each service has one or more endpoints through which the clients of these services communicate. These endpoints in turn are made up of three parts:

1. Address:  which states where the service is hosted
2. Binding : which defines how the service can communicate with other services and clients and,
3. Contract: which defines the overall structure of the communication

So basically you have to define the service, one or more endpoints and the host environment. The host environment is nothing but an application domain and a process of any form like console, windows forms, WPF, windows services, IIS. To create a service, you must create a service contract class which will have the methods to be exposed by the service and data contract class which will specify the structure your interface will expose. For using this service you need to create the client and the WSDL (Web Services Description Language) document.

Service descriptions show some information about the service like, what it does and how it could be accessed. The following standards are used to describe a service:

WSDL
WS-Policy
WS-Metadata Exchange
XSD

Message:

Message is the main key in WCF, because the services and client will communicate with each other via messages. Messages in WCF are XML documents consisting of two parts: one or more headers and a body. Headers contain information about the message and the body contains data. Messages have one of the following three patterns:

Simplex: This is a one way asynchronous messaging pattern. The message is sent from client to the service.
Request-Reply: This is a two way asynchronous messaging pattern. The client sends a request to the service and waits for the reply. This pattern is followed in internet.
Duplex: This is a two way synchronous pattern. In this pattern, both the client and service communicate with each other without waiting for reply.

Channel:

A Channel is actually a link between a client and a service.  The clients and services pass messages through channels.  There are four main types of channels:

• Simplex Input
• Simplex Output
• Request-Reply
• Duplex

Each channel has some features like security, session, message pattern etc. You need to declare the properties of the channel before creating the channel. You also need to choose a transport. Most common transports in WCF are HTTP, TCP and MSMQ. With each of these transport protocol come its own security characteristics. You can also use SOAP message security or other security mechanisms in your application. You can also encode messages in a WCF application. We will discuss more on channels and channel interoperability in our next article.

Binding:

Bindings define the way that a service can communicate with other services and clients. System-provided bindings are used to specify the transport protocols, encoding, and security details required for clients and services to communicate with each other. Each channel has its own characteristics and each binding uses a combination of various available properties for a channel.  There are some pre-defined bindings in Windows Communication Foundation, but you can also write a custom binding. The system defined bindings are presented here:

BasicHttpBinding: This is suitable for communication with WS-Basic Profile conformant Web Services like ASMX-based services. This binding uses HTTP as the transport and Text/XML as the message encoding.

WSHttpBinding: A secure and interoperable binding that is suitable for non-duplex service contracts.

WSDualHttpBinding: A secure and interoperable binding that is suitable for duplex service contracts or communication through SOAP intermediaries.

WSFederationHttpBinding: A secure and interoperable binding that supports the WS-Federation protocol, enabling organizations that are in a federation to efficiently authenticate and authorize users.

NetTcpBinding: A secure and optimized binding suitable for cross-machine communication between WCF applications.

NetNamedPipeBinding: A secure, reliable, optimized binding that is suitable for on-machine communication between WCF applications.

NetMsmqBinding: A queued binding that is suitable for cross-machine communication between WCF applications.

NetPeerTcpBinding: A binding that enables secure, multi-machine communication.

MsmqIntegrationBinding: A binding that is suitable for cross-machine communication between a WCF application and existing MSMQ applications.

Contract:

Contracts define the structure of communication.  There are three types of contracts:

Service Contract:  A service contract is basically the interface which defines what the service can do for you.  A service can have more than one service contracts.  You implement an interface for your service logic.  For example, a service that converts the temperature from Celsius to Fahrenheit operates as a converter may have an IConverter contract with the method for conversion.

Data Contract: Data contracts let you to pass custom objects to service operations.  In our previous example we can send the temperature value to the data contracts.

Message Contract: This is used to change the structure of your messages to use them in your application.  For example, you can change the body of a message.

Endpoint:

Endpoints are the access points of a service.  An endpoint associates a service contract and binding with an address so the clients can find and use it.  Each service can have at least one or more endpoints. An endpoint has three elements: Address, Binding, and Service Contract.

A Sample WCF Application:

Let us discuss a sample example provided in the MSDN library to understand the concepts discussed so far. To create a WCF application, you will have to go through six steps, which are:

1. Define a WCF Service Contract – this means creating a user-defined interface to describe the functionalities offered. For example, the service provided will be that of a calculator. The following code snippet shows the contract implementing the ICalculator interface.

// Define a service contract.
[ServiceContract(Namespace="
http://Microsoft.ServiceModel.Samples")]
public interface ICalculator
{
    [OperationContract]
    double Add(double n1, double n2);
    [OperationContract]
    double Subtract(double n1, double n2);
    [OperationContract]
    double Multiply(double n1, double n2);
    [OperationContract]
    double Divide(double n1, double n2);
}


2. Implement the WCF Service Contract – this is writing the service class, which will inherit the service contract and define the functionalities.

// Service class that implements the service contract.
public class CalculatorService : ICalculator
{
    public double Add(double n1, double n2)
    {
        return n1 + n2;
    }
    public double Subtract(double n1, double n2)
    {
        return n1 - n2;
    }
    public double Multiply(double n1, double n2)
    {
        return n1 * n2;
    }
    public double Divide(double n1, double n2)
    {
        return n1 / n2;
    }
}

3. Host and run the service – this involves configuring endpoints to expose the service functionalities. The endpoints are defined in the web.config file.

<services>
    <service
        name="Microsoft.ServiceModel.Samples.CalculatorService"
        behaviorConfiguration="CalculatorServiceBehavior">
        <!-- ICalculator is exposed at the base address provided by         host:
http://localhost/servicemodelsamples/service.svc.  -->
       <endpoint address=""
              binding="wsHttpBinding"
              contract="Microsoft.ServiceModel.Samples.ICalculator" />
       ...
    </service>
</services>


4. Create a WCF Client – this involves creating a WCF client. The process uses the ServiceModel Metadata Utility Tool (Svcutil.exe) provided by WCF

svcutil.exe /n:"http://Microsoft.ServiceModel.Samples,Microsoft.ServiceModel.Samples" http://localhost/servicemodelsamples/service.svc/mex /out:generatedClient.cs


5. Configure the WCF Client – this involves creating the client.

// Create a client.
CalculatorClient client = new CalculatorClient();

// Call the Add service operation.
double value1 = 100.00D;
double value2 = 15.99D;
double result = client.Add(value1, value2);
Console.WriteLine("Add({0},{1}) = {2}", value1, value2, result);

// Call the Subtract service operation.
value1 = 145.00D;
value2 = 76.54D;
result = client.Subtract(value1, value2);
Console.WriteLine("Subtract({0},{1}) = {2}", value1, value2, result);

// Call the Multiply service operation.
value1 = 9.00D;
value2 = 81.25D;
result = client.Multiply(value1, value2);
Console.WriteLine("Multiply({0},{1}) = {2}", value1, value2, result);

// Call the Divide service operation.
value1 = 22.00D;
value2 = 7.00D;
result = client.Divide(value1, value2);
Console.WriteLine("Divide({0},{1}) = {2}", value1, value2, result);

//Closing the client releases all communication resources.
client.Close();

6. Use the WCF Client -- When you run the sample, the operation requests and responses are displayed in the client console window. Press ENTER in the client window to shut down the client.

Add(100,15.99) = 115.99
Subtract(145,76.54) = 68.46
Multiply(9,81.25) = 731.25
Divide(22,7) = 3.14285714285714

To view the complete code and more samples, please visit this link.

Conclusion:

We have discussed the Basic concepts and fundamentals of WCF. In our next article, we will look into the differences between traditional web services, also called ASP.Net web services (.asmx) and the WCF services.