Friday, April 22, 2016

WCF - Getting Started

In this post we are going to learn the basic concepts of WCF and how to create a basic WCF Service.


What is WCF?

WCF or Windows Communication Foundations is a Microsoft platform for creating, building and deploying network-distributed services.


The ABC of Windows Communication Foundation

The "ABC" is the basic concept and also the key to understand the WCF endpoint.
  • "A" stands for Address: Where is the service?
  • "B" stands for Binding: How do I talk to the service?
  • "C" stands for Contract: What can the service do for me?


"ABC" means that creating a WCF service is a three-step process:
  • You define a contract and implement it on a service
  • You choose or define a service binding that selects a transport along with quality of service, security and other options
  • You deploy an endpoint for the contract by binding it (using the binding definition, hence the name) to a network address.


Create a WCF project

Before we start with the three-step process to create a WCF we need to create a WCF project.

When you create the project it will already have a Contract and a Service, but we will create new ones.
Delete the files IService1.cs and Service1.svc.
Now we are ready to through the three-step process.


Step #1 - Defining and Implementing Service Contracts

The Service Contract will define what operations the service supports. An operation is an action that can be executed by the service, if we compare it to the ASMX web services the operation is like the Web Service Method.
To define a Service Contract we need to create an interface and mark it with the ServiceContractAttribute attribute and the methods with the OperationContractAttribute attribute.
First let`s add a WCF Service to the project.


When you add a new WCF Service the visual studio will create a Service and also the Contract. First let`s change the contract. This is shown in the following code.


    [ServiceContract]
    public interface IOnlineDinnerService
    {
        [OperationContract]
        String OrderDinner(int comboNumber);
    }

Above, the interface is marked with the ServiceContractAttribute attribute and the method with the OperationContractAttribute attribute, as explained before it is a requirement to create a WCF Service.
Now let`s implement the interface in the Service. This is shown in the following code.


    public class OnlineDinnerService : IOnlineDinnerService
    {
 
        public String OrderDinner(int comboNumber)
        {
            return $"You have ordered the combo number {comboNumber}. Your Order Number is {new Random().Next(1, 100)}";
        }
    }

Above, we implemented the contract, now we already have our Contract and our Service created, but as you can notice our service operations just accept simple types. What if we want to use a complex type? For that we need to create the Data Contracts.


What are Data Contracts?

The Data Contract describes the data that will be exchanged between a service and a client.
The WCF uses an engine called Data Contract Serializer to serialize and deserialize data.
By default the primitive types and certain types as String and DateTime can be serialize with no proper preparation, but new complex types need to be prepared as a Data Contract. The following code show how to do it.

    [DataContract]
    public class DinnerCombo
    {
        [DataMember]
        public int ComboNumber { get; set; }
        [DataMember]
        public Decimal Price { get; set; }
        [DataMember]
        public String Name { get; set; }
    }
Now that we already have defined a DataContract we are ready to create an operation using it. To do it, first let`s add an operation to the Service Contract (IOnlineDinnerService). This is shown in the following code.

        [OperationContract]
        List<DinnerCombo> GetDinnerCombos();
Now let`s implement the new service operation in the Service. To do it, edit the OnlineDinnerService service as in the following code.

        public List<DinnerCombo> GetDinnerCombos()
        {
            return new List<DinnerCombo>()
            {
                new DinnerCombo {ComboNumber =1, Name="X-Burguer Combo", Price=6.99M },
                new DinnerCombo {ComboNumber =2, Name="Fried Chicken Combo", Price=7.99M },
                new DinnerCombo {ComboNumber =3, Name="Rosted Beef and Desert", Price=8.99M }
            };
        }

Step #2 - Configuring the binding

Bindings are used to specify the transport, encoding, and protocol details required for clients and services to communicate with each other. WCF uses bindings to generate the underlying wire representation of the endpoint, so most of the binding details must be agreed upon by the parties that are communicating.
The WCF by default offers a lot of different bindings, each binding has different types of security, transport or protocols. You can check all system-provided bindings on https://msdn.microsoft.com/en-us/library/ms730879(v=vs.110).aspx.
There are two ways to configure a binding, imperatively in code and declaratively using configuration.
In this example we will do it declaratively in the application`s web config file using the BasicHttpBinding.

  <system.serviceModel>
    <services>
      <service name="WCF.GettingStarted.OnlineDinnerService">
        <endpoint address="" binding="basicHttpBinding" contract="WCF.GettingStarted.IOnlineDinnerService"></endpoint>
        <endpoint address="/mex" binding="mexHttpBinding" contract="IMetadataExchange"></endpoint>
      </service>
    </services>
     ...
  </system.serviceModel>
Above, we the service for our OnlineDinnerService and then we created 2 endpoints, the first one uses the basicHttpBinding to communicate with the service. The second one uses mexHttpBinding, this binding will enable the service to publish it`s metadata. Check the link https://msdn.microsoft.com/en-us/library/aa751951(v=vs.110).aspx for more details about publishing metadata.


Step #3 - Deploying and endpoint for the contract

In the Step #2 we defined the binding for the endpoint, in that same endpoint you can see the tag "contract", there we defined the contract for that endpoint.
Now our service has the OnlineDinnerService implementation and this service has an endpoint using the contract IOnlineDinnerService with the basicHttpBinding.


You can download the full from the github (https://github.com/rbercocano/WCF-Getting-Started).
Enjoy!

No comments:

Post a Comment

Microservices – Creating Resilient Services

Dealing with unexpected failures is one of the hardest problems to solve, especially in a distributed system . A microservice needs to...