One Community, One World
The first step in WCF way
by Ahmed Rafie  on Jul 11 2007 12:00AM
  PageViews 6636   |    Add to Fav   |     Send to Friend   |    no downloads available
In this article I will discuss the concepts of  Windows Communication Foundation, and explorer how the service communicates with its clients through endpoints. finally I will show you how to create your first WCF Service.  

Resources Used
Microsoft .NET Framework 3.0 Redistributable Package
Visual Studio 2005 extensions for .NET Framework 3.0

Before we go through this article, I’d like to introduce Windows Communication Foundation to you in only few lines. WCF unifies the existing .Net distributed technologies into a single programming model. And it provides you with new levels of scalability and interoperability. WCF is a programming model that enables developers to build service solutions that are reliable and secure, and even transacted.

WCF Features
This section discusses a few of those features:  

Transaction is a unit of work, a transaction rather succeed as a whole or fails as whole. For example if you have a transaction contains more than one items of work to perform and during the execution of that transaction one of those items fails, then all of them fail. WCF provides a rich set of features that enable you to create distributed transactions in your web service application.  

Windows Communication Foundation (WCF) is a SOAP message-based distributed programming platform, and securing messages between clients and services is essential to protect the data. WCF provides a versatile and interoperable platform for exchanging secure messages based upon both existing security infrastructure as well as security standards for SOAP messages that have been published from standards organizations.  

WCF hosting allows services to be hosted in different environments such as windows service application, windows application, consol application, and IIS. there are two primary hosting enviroments, Self-Hosting which means that you will build the host enviroment yourself and the Hosted enviroment which mean that you will use a built-in hosting enviroment such as IIS.  

WCF supports message queuing, allowing message to be safely stored, and providing a constant state of communication. Queuing collects and stores sent messages from a sending application and forward them on to the receiving application. This provides a safe and reliable message delivery mechanism.

Windows Communication Foundation Concepts
If you have two components, and you want to transfer data between these components. So you have to make a connection between component A and component B. But we have small problem here, how does component A find component B. So component B must have an address in order to component A can find it and identify where it is.

Figure 1: A Connection between two components.

If component A is a client application and component B is a service. So the client application must know the address of the service in order to establish a connection with it through channel. A channel is the medium through which messages are exchanged. This channel is created by the client specifying the address of the service and the type of channel to create.

Figure 2: illustrates the steps of connection between a client and a service.

The client first establishes a connection to the service through service’s address and then the service accepts the client’s request to open a channel.

In WCF you can access the service through Endpoint which is the component of the service that communicate with the client and provides the service operations. Think of a service as a collection of one or more Endpoints. Each Endpoint has a unique address that distinguishes it from the other Endpoints on the same service.

Figure 3: A Service with multiple Endpoints.

Each endpoint consists of an address specifies where to send messages. The binding describes how to send messages. And the contract describes what the message contain.

As mentioned, each Endpoint consists of three component the address, binding and contract. You can think that address is the most important component of them, because without address you wouldn’t be able to find the endpoint to begin with. For example, an address might look like the following:


The Endpoint Address also contains more than one part, The first one is the transport protocol such as http, name of the machine running the service such as localhost, and finally the specific service path.  

The second component of Endpoint is binding, binding specify how the Endpoint will communicate with the client. When you defining a binding, the information you specify will typically fall into one of several categories:  

  • The Protocol:
This defines information to be used such as security, transaction capability.
  • The Encoding: This defines the encoding to be used by messages during communication.
  • The Transport: This defines the base protocol to be used in communication.  
  • Contracts
    In WCF contracts provide the interoperability they need to communicate with the client. It is through contracts that clients and services agree what types of operations and structures they will use during the period of communication.

    Three basic contacts are used to define a WCF service:  

    • Service Contract: Defines the methods of a service.
    • Data Contact: Defines the data types used by the available service methods.
    • Message Contract: Provides the ability to control the message headers.   

    Now you have a good idea of what is Windows Communication Foundation, Next we will create a simple Windows Communication Foundation service and test it.

    Create your first WCF Service
    These steps assume that you have a computer with visual studio 2005 installed, .net framework 3.0, IIS, and visual studio 2005 extensions for .Net Framework 3.  

    Open an instance of visual studio and from the File menu select New then select Web Site. This will open the New Web Site dialog, from the location combo box choose HTTP this will host your WCF Service in IIS in local machine or you can choose another machine that you have access to, Then specifies the path for your service. After that you have to choose WCF service from the installed templates, this template will add the necessary references to WCF class Library. Finally click ok to start writing your code.

    Figure 4:  Create New WCF Service using visual studio template.  

    After creating the service your solution explorer should look like this  

    Figure 5: solution explorer

    If you looked at this picture you will notice that your service is hosted in the local machine and using the default port for http protocol, and the service path is /WCFService. Just like ASP.Net web service you can see the App_Code folder which contains the Service.cs file that contains the service implementation. 

    public interface IMyService 
        string MyOperation1(string myValue1);     
        string MyOperation2(DataContract1 dataContractValue);

    This is an interface written using C# but with some modification, first the ServiceContaract attribute which tell the CLR that you have WCF Contract. And each method in this interface signed with OperationContract attribute which indicate that these methods will be available to the client to invoke. 

    public class MyService : IMyService 
            public string MyOperation1(string myValue1)     
                    return "Hello: " + myValue1;     
            public string MyOperation2(DataContract1 dataContractValue)     
                    return "Hello: " + dataContractValue.FirstName;     

    The MySerivce class implements the interface and all its methods just like the code snippet. But we have new data type here as a parameter in MyOperation2 method named DataContract1.
    If you looked to the code you will find the definition of the DataContract just like this 

    [DataContract] public class DataContract1 
            string firstName;     
            string lastName;       
            public string FirstName     
                    get { return firstName;}         
                    set { firstName = value;}     
            public string LastName     
                    get { return lastName;}         
                    set { lastName = value;}     

    Simply a data contract describes the data that is to be exchanged. We have here a class with a DataContract Attribute and each of its properties signed with a DataMember attribute.

    Back to solution explorer there is a new file named Service.svc .it is used much like .asmx file in ASP.Net web service. This file contains the ServiceHost directive which define the programming language the service used and the code behind file. It is possible to put your code in this file but it is not recommended. This file should look like this code snippet. 

    <% @ServiceHost Language=C# Debug="true" Service="MyService" CodeBehind="~/App_Code/Service.cs" %> 

    And you have Web.config file that contains all the configuration of your service. The file should look like this code snippet. 

    <?xml version="1.0"?>   
    <configuration xmlns="">   
                <service name="MyService" behaviorConfiguration="returnFaults">         
                    <endpoint contract="IMyService" binding="wsHttpBinding"/>       
                    <behavior name="returnFaults" >           
                        <serviceDebug includeExceptionDetailInFaults="true" />         
            <compilation debug="true"/>   

    You can see the system.serviceModel element contains the entire WCF configuration, the service element define a service and add set of attributes such as name, behaviorConfiguration.

    And sure the Endpoint element which defines the contract and binding, this service using wsHttpBinding which offers a lot more functionality in the area of interoperability. It uses the HTTP and HTTPS transport for communication as well.Before running the service, you have to enable windows authentication for your service from IIS property window of the service virtual directory.

    You can do so by opening IIS and select WCFService and from the context menu select properties, in the properties windows select directory security tab, in the authentication and access control click edit. And finally check the integrated windows authentication.

    Figure 6: Enable Windows authentication for WCF Service

    Finally, in order to have your service accessed, you have to modify the web.config and modify the behavior section as the following: 

    <behavior name="returnFaults" >           
        <serviceDebug includeExceptionDetailInFaults="true" />           
        <serviceMetadata httpGetEnabled="true" /> 

    The new line here is the serviceMetadata; this element enables the client to get the service metadata in order to start communication with it. Just like the WSDL.

    Now you can run the service, your IE should look like the next picture.

    Figure 7: the Service is running.

    Now the time to create the client in order to test the service, right click your solution and from the context menu select add then select New Project. I will choose to test it with a windows application, so I will choose windows application template and set the name to MyWCFClient and click ok.

    Just like you add a web reference you will add the service, right click the client project and select Add Service Reference, this will open the Add Service Reference dialog, write the URI of the Service and the reference name. And click ok.  

    Figure 8: Add Service Reference.

    You will notice that the visual studio add the necessary references to the system.serviceModel.

    From the tool box add button and a textbox controls, and double click the button and add the following code snippet. 

    private void button1_Click(object sender, EventArgs e)         
                localhost.MyServiceClient Client = new MyWCFClient.localhost.MyServiceClient();             
                textBox1.Text = Client.MyOperation1("Rafie");         

    Make the windows application your first startup project and go and run the client application. Click on the button.

    Figure 9: Application running Congratulation!

    Now have created your first WCF Service and now you have a good idea of how the WCF service communicate with the clients through Endpoint.

    Each of these components you worked with like the address or the binding is very important and has many considerations to take care of. In this article you have a complete vision about how the WCF Service working and communicating with the client. WCF actually has many other important features to learn like the transactions, hosting and security.