SOA via WCF - Part 2 -

This is the second part of my presentation in SilverKey Demo Day 2 (SKDD 2) last July, for the first part, Check Here, you will also find the presentation slides & samples attached in Part 1 or you can download from here
So let's start
Let's check our Agedna

In Part 1 we discussed what is SOA and the concepts behind it, also we had a walk through different approaches to apply SOA in our applications in terms of standards and patterns.
In Part 2 we are going to discuss WCF or (Windows Communication Foundation) which is Microsoft new framework to unify communication mechanisms and provide an infrastructure for our SOA applications.

As we've just mentioned WCF stands for Windows Communication Foundation and also it used to be called Indigo.
WCF was shipped with Windows Vista in November 2006 as part of .net framework 3.0, however it is also available for Windows 2000, XP and 2003.

WCF is all about providing an unified infrastructure that handles all communication scenarios and protocols, which includes different transport, messaging patterns, encoding .... etc.
WCF also playing a great role in making the life easier for .net developer, so the messages exchanged between different services are exposed as CLR types (classes), and also the services are represented as interfaces and classes, so it provides a good and very high level of abstraction.
So as one sentence you can say that WCF is the infrastructure for building Services.

As we said WCF unifies the communication techniques, but how ?
Before the WCF days, we used to have different technologies for different communication problem, so if you are doing TCP communication you will be using Sockets for example, and if you are providing online services over HTTP, you will be using Web Services, and if you are doing message queues you will be using MSMQ ... etc
So this was good, however it has some drawbacks.

  1. You have to learn different models for every communication technique.
  2. You can't change the communication technique you are using in a certain application to another without massive changes in your code.

So what WCF provides is a One Right Solution for all problems, which saves your time and effort, also it comes with a full fledged set of goodies such as Tracing, Logging which can be used regardless of the communication technique you are using.

One of WCF great benefits that it provides a very handy extensible model, that you can add support for new protocols easily, or even slight changes to current protocols like adding a new encoding or encryption algorithm.or a new tracing mechanism.
Another thing that WCF is supporting almost all the WS-* standards like WS-Addressing, WS-AtomicTransaction which makes the messages generated from WCF runtime interoperable with any current or future application built with same standard messaging.
and The most elegant feature of WCF, that all the configuration of the services and protocol specific properties can be configured using XML config files outside the application, which is a great feature that allows administrators to be part of the game, so they can change stuff like the impersonation options, and security settings, enabling and disabling trace listeners and logging, without the need to ask developers to do it, which is somehow similar to ASP.net configuration.
Also this config file can be edited using a UI tool..
For architects it is really easy to stay in the high level design and forget about implementation details and technology limitations.

So let's have a sample service
In this demo we will be discussing the basic elements in any WCF application.
The most basic three elements are

  1. Address
  2. Binding
  3. Contract

They are also called the ABC's of WCF, because every service has to define these three elements.
We will be discussing everyone of these elements in details,
let's now see how a Service is defined in WCF. in steps we will discuss how to build a simple News service.
1. Define the Contracts
In this step we will define the different contracts of the service the first type is

Service Contracts

 [ServiceContract(Namespace="com.silverkeytech.news")]
public interface INewsService
{
    [OperationContract(IsOneWay=false)]
    Article[] GetArticles();
}

As you see the Service Definition is just an interface (Contract) which is decorated with an attribute called ServiceContract.
This interface defines the different functions provided by the service in terms of inputs/outputs and exchange patterns.
Every service function is represented in a form of interface method, and the inputs of the service function are represented as inputs to the method and also the output is represented as return type of the method.
The exchange pattern is by default Request/Response which is represented using the Attribute OperationContract with the IsOneWay property set to false, if it was set to true this means that this service function is a fire & forget type of service, which the service clients will not expect any response for the messages sent to this functions.

Data Contracts
Also if you noticed in our method return type is a complex type Article this is not a primitive type in .net, it is a user defined type which has to be defined like this.

 [DataContract]
public class Article
{
    string title;
    string details;

    [DataMember]
    public string Title
    {
        get { return title; }
        set { title = value; }
    }
    [DataMember]
    public string Details
    {
        get { return details; }
        set { details = value; }
    }
}

As you can see it is a simple data class that is decorated with a DataContract attribute, so it tells the WCF runtime that this class will be converted to a message that will be sent or received by one or more service functions, also every field or property of interest has to be decorated with another attribute called DataMember.
2. Implement the Service

Now we need to provide the implementation of the Service Contract interface, which will do the actual job of the service, all what we need is to implement the interface in a class like this.

 public class NewsService : INewsService
{
    public Article[] GetArticles()
    {
        List<Article> articles = new List<Article>();
        for (int i = 0; i < 10; i++)
        {
            Article article = new Article();
            article.Title = "Title " + i.ToString();
            article.Details = "Details " + i.ToString();
            articles.Add(article);
        }
        return articles.ToArray();
    }
}

So the class NewsService implements the interface INewsService and provides an implementation of the service that does the actual job of how the service will handle the incoming requests.

3. Hosting the Service
Now after we implemented the service, we have to host it on an application, there are different choices depending on your need, you can host the service on Windows Applications (Console, Windows Forms, Windows Services) or Web Applications (IIS), for simplicity I will host my service on a console application.

 namespace Host
{
    class Program
    {
        static void Main(string[] args)
        {
            using (ServiceHost host = new ServiceHost(typeof(NewsService)))
            {
                host.Open();
                Console.ReadKey();
            }
        }
    }
}

As you see, the host is very simple, all the hard work is done in the ServiceHost class which its constructor requires the type of the class that implements my service, in our case NewsService class.
Then we call the Open method to allow the service to accept any incoming requests and process them, the last Console.ReadKey is just for not allowing the application to exit unless somebody presses any key.

4. Configuring the Service
After we hosted the service we need to configure this service, we need to write how the service is going to interact with its clients, this will be done using the App.Config file of the host

 <?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <system.serviceModel>
        <services>
            <service name="BeebcNews.NewsService">
                <endpoint address="EndPoint1" binding="basicHttpBinding"
                    bindingConfiguration="" name="HttpEndpoint" contract="BeebcNews.INewsService" />
                <host>
                    <baseAddresses>
                        <add baseAddress="https://localhost:9000/beeBC" />
                    </baseAddresses>
                </host>
            </service>
        </services>
    </system.serviceModel>
</configuration>

This is sample configuration file that is used to configure the NewsService we've just implemented

5. Consuming The Service
After we host and deploy our service, we need to consume it, which mean we need to write client applications that sends and receives requests and responses from the service.

Generating Proxy Class
So for the client application to be able to use the service we need to use a proxy class, the proxy class is generated using a tool called svcutil.exe this tool can be applied either on the Service dll or on the WSDL file url of the service.
so let's assume our NewsService dll is called MyLibrary.dll
We will write this command in the command prompt.

svcutil.exe MyLibrary.dll

This command will generate the XSD files & WSDL file for the types and services inside the library, there are more switches can be used for more specific options.
Then after we generate the XSD, WSDL of the wcf service we apply this command on the generated files.

svcutil.exe *.xsd *.wsdl /language:C#

This command will use the XSD, WSDL file we generated with the first command to generate a proxy class in C# and an XML config file.

Then we can use the new files to write our client applications.
Another way of generating the Proxy classes is to switch on the MetaData publishing for the service, so the service will have a http url that contains the WSDL file, then we can use this command

svcutil.exe https://[the service url]

and this will generate the C# proxy and the config file

Implementing the Client Application

 namespace Client
{
    class Program
    {
        static void Main(string[] args)
        {
            NewsServiceClient client = new NewsServiceClient("HttpEndpoint");
            Article[] myArticles = client.GetArticles();
            foreach(Article a in myArticles)
                Console.WriteLine(a.Title);
            Console.ReadKey();
        }
    }
}

The previous code is a simple example of a client application that uses the generated proxy class we've just generated that generated the NewsServiceClient class, which has the same functions provided by the INewsService interface so we can call them and the WCF will handle the communication between the client and server.

Now let's have an overview of the architecture of WCF, or let's call it the journey of the incoming message to the service and how it is going to be handled.
The architecture of WCF is basically a pipeline, the message arrives on the transport layer which is going to pass it to the next layer to be decoded and then it passes through different protocol specific layers till it reaches the dispatcher, which is going to decide this message belongs to which method in the running instance of the service, and then deliver it to the method to be processed then the return value (if any) takes a similar path down the pipeline back to the original sender.
This pipeline is configured using the Configuration and the Contract, the configuration defines the layers in the WCF pipeline and the Contract helps the Dispatcher to find the destination of the message.

If you take a look on the XML Configuration in the previous example, you will find that under the Service element there is something called EndPoint
The EndPoint is the container that has the three basic elements of the service we mentioned before (Address, Binding & Contract).
So in our previous example the Address was EndPoint1, which is going to be concatenated with the baseAddress of the Service in our case "https://localhost:9000/beeBC" so the result address will behttps://localhost:9000/beeBC/EndPoint1, then the Binding which was "basicHttpBinding" which is the simply SOAP messages over HTTP using text encoding.
and the Contract which has the full name of the INewsService interface which defines our service contract.
Now let's see each Endpoint element in details

The Address
Defines Where the endpoint resides

The Binding
Defines How the service is communicating with the outside world.

The Contract
Defines What the service will offer to its clients.

Before we end this presentation, I would like to highlight that WCF 2 is on the way, it will be shipped with next version of Visual Studio 2008 and .net framework 3.5
The new version of WCF will have better support for Webby style services such as REST style services and also supports different encodings like RSS, ATOM and JSON.
Also the huge change will be that WCF and WF are merged together in what is called Silver project, which will enable developers to develop WCF service with Workflow as an implementation.

These are some resources for more information about WCF and SOA also some books for further information.

I hope you read this line, which means that you kept reading the whole presentation, I hope it was useful for you, if you have any questions write them as a comment to this blog post and I will be answering them immediately.

kick it on DotNetKicks.com