Click here to Skip to main content
15,881,882 members
Articles / Programming Languages / C#
Technical Blog

WCF Part 2: Fundamentals.

Rate me:
Please Sign up or sign in to vote.
4.67/5 (3 votes)
17 Dec 2012CPOL9 min read 13.4K   10  
The fundamentals of WCF.

We have seen the evolution of WCF in our previous article: WCF Part 1: Why WCF?. Next, we will go through the fundamentals of WCF. I will try to make it more worthy than an interview question puff.

What is WCF?

Windows Communication Foundation. Easy. Although, I was not able to find as why it is called a foundation but I was able to relate it to the fact that WCF was the first attempt to bring all the communication protocols and messaging formats under one roof. Refer to the last article for details. With WCF in hand, no developer has to go anywhere or learn a new technology to create a distributed system.

Definition: As per Wikipedia, “Windows Communication Foundation is a runtime and a set of APIs (application programming interface) in the .NET Framework for building connected, service-oriented applications”.

MSDN, “Windows Communication Foundation (WCF) is Microsoft’s unified programming model for building service-oriented applications. It enables developers to build secure, reliable, transacted solutions that integrate across platforms and inter-operate with existing investments.”

Our definition, “ WCF provides a flexible way of developing service oriented applications. Flexibility in terms of communication protocols, message formats, security options, transactions and it covers almost all the existing platforms and also supports older versions to a certain extent”. It means WCF is a one stop solution for a service oriented paradigm.

What is the fundamental knowledge required?

Communication between server and client happens by exchanging messages over a network which must be following a transport protocol.

  • What are these messages?

  • “A self-contained unit of data that can consist of several parts, including a body and headers.” If you have a xml file or json or any other format which fits into this criteria can be termed as message. These messages are first encoded before being sent. we have following encoding options available.

      • Text encoding: “ Text is translated into numeric values and numeric values are rendered as visible characters. This can happen by using an encoding standard like UTF-8, UTF-16.”
      • Message Transmission Optimization Mechanism (MTOM) encoding: “MTOM is a mechanism for transmitting large binary attachments with SOAP messages as raw bytes, allowing for smaller messages.”
      • Binary encoding: “Binary encoding relies on bits, the smallest unit of encoding.”
  • What is this transport protocol?

    1. HTTP: Hyper text transfer Protocol, a request/response protocol for internet. Browsers can understand HTTP. Easy!
    2. TCP: Transmission Control Protocol requires dedicated connection between client and the server.
    3. Named Pipes: An object in Windows O/S kernel which facilitates communication between processes on a single machine.
    4. Message Queues: Not exactly a transport protocol, MSMQ is essentially a messaging protocol that allows applications running on separate servers/processes to communicate. There is no condition for the machines to stay connected following this protocol.
    5. Peer Networking mesh: In peer-to-peer (P2P) application  each participant (node) acts as both a client and a server to the other participants in the network and there is no relying on a smaller number of more powerful server computers on the network.

We hear a term SOAP, it is time to define this term. Simple Object Access Protocol. Although it contains ‘protocol’ but it’s not exactly a transport protocol, it is defined as a XML message sent over HTTP. Simple! A SOAP message is an XML document that has two main sections: the header and the body. What we have mentioned above in messages, encodings and transport protocol sections, all are required to read the body of this SOAP message, but what about the headers?

These headers can be read or write by Protocol channels, For ex: WS-Security and WS-Reliability. First, we will define channels,

Channels:

A channel is a component that operates on messages and message headers. There are two types of channels: transport channels and protocol channels.

  • If we combine one of the above defined encodings with one of the transport protocol then this combination will be called transport protocol. They operate only on the message body.
  • For reading and writing Headers of the message, we have to use one of the protocol channels. WS-Security is an implementation of the WS-Security specification enabling security at the message layer. The WS-Reliable Messaging channel enables the guarantee of message delivery.

Now we know about the message and their transmissions, we will move to the components of WCF required to implement all this.

Flow:

Major components of WCF are ABC. We will concentrate on the flow between client and server machine to identify the components of WCF.

A-Address

Client sends a request to server. How client knows for which program/component of the server, I am sending this request? For this, Address  of component is required. This is the unique location where service will be deployed and can be accessed by the client. How this address looks like?

http:\\localhost:8085\CalculatorService

A WCF Address is normally specified as a URL. This WCF service example uses HTTP as its transport protocol, and it is located on the local server with location path as root. Service Name is CalculatorService.

B-Binding

Now client knows where the service is located, then for transmission of this service from server to client; transport, encoding, and protocol details are required. These details should be agreed upon between server and client before starting the transmission. A combination of these elements will form our binding.

  • basicHttpBinding: This binding supports backward compatibility with ASMX [old web services] based clients. Basic http binding sends SOAP messages and is used when there is a requirement for the WCF services to communicate with non WCF based systems.
  • wsHttpBinding: This binding sends SOAP messages and implements WS* specifications [specifications associated with Web Services] to support enterprise requirements of security, reliability, ordered delivery and transaction management.
  • netTcpBinding: This binding sends SOAP messages, provides binary encoding and optimized communication between WCF services and WCF clients on Windows network.
  • netNamedPipeBinding: This binding is used to provide secure and reliable Named Pipe based communication between WCF services and WCF client on the same machine. It is the ideal choice for communication between processes on the same machine.
  • netPeerTcpBinding: This type of binding exists to cater peer-to-peer computing using WCF services.
  • netMsmqBinding: Microsoft Message Queuing, This type of binding supports MSMQ for transport and asynchronous queued calls.
Table- Combination of encoding and transport protocol for each binding

Table - Combination of encoding and transport protocol for each binding

Additional Bindings: WSDualHttpBinding, WSFederationHttpBinding, WSFederationHttpBinding, MsmqIntegrationBinding.

Developers can use built-in bindings plus they can tweak and configure as per the requirements or can try and write their own custom bindings. WCF gives full freedom to developers in terms of customization.

C-Contract

So far, we have discussed, where our service is located and what all communication criteria are available to begin the transmission. Client places a request to server and ask to begin some process or program , we have earlier told that client will never know the exact implementation of the program but an abstract of it through interface. Here, Interface is the contract which client invokes at the server side. There are several types of WCF contracts, such as Service Contract, Operation Contract, Data Contract, Message Contract, and Fault Contract. In simple terms, Contracts are Interfaces.

  • Service Contract specifies the actual signatures of the service, and is distributed as an interface. This service contract contains several operation contract which declares individual method signatures. Client can call methods of server by invoking service contract interface.
  • Operation Contract is a definition of an operation which defines the parameters and return type of an operation. It has to be implemented before being consumed.
  • We have an interface file in our service solution, where we need to define the service contract and operation contract.

    C#
    [ServiceContract()]
    public interface IEmployeeService
    {
    [OperationContract()]
    string GetData(string name);
    }

    There is a class file associated with each interface file of our solution, where we implement this interface

    C#
    public class EmployeeService: IEmployeeService
    {
    
    public string GetData(string name)
    {
    return "Hi"+ name ;
    }
    }
  • We already have .NET types like string, int which do not require fine-grained control while sending the message between client and server. These types are easily understood by client and server. But when we create a custom type like Employee, it is observed that without decorating it with additional details, it won’t be understood by client. Here, it has be declared as a data contract, it will provide additional message parameters which describes a message that a service can create or consume.
  • C#
    [DataContract]
    public class Employee
    {
    private int m_id;
    private int m_Salary;
    
    [DataMember]
    public int ID
    {
    get { return m_id; }
    set { m_id = value; }
    }
    
    [DataMember]
    public int Salary
    {
    get { return m_Salary; }
    set { m_Salary= value; }
    }
    
    }

    How this custom type used?

    C#
    //At service side
    public Employee GetEmployee(int empId)
    {
    
    Employee empDetail =from emp in employeeList where emp.ID=empId select emp;
    return empDetail;
    }
  • When data contract requires more control over message security. Then message contract is required which defines specific message parts using SOAP protocols, and allows finer-grained control over parts of the message like header.
  • C#
    [MessageContract]
    public class Employee
    {
        [MessageHeader]
        public int EmpID;
        [MessageBodyMember]
        public string Name;
        MessageBodyMember]
        public int Salary;
    }
  • Fault Contract is similar to our message but it restricts itself to error messages. Client should be warned of any error or fault which happened at the server while executing the program. At this point, fault contract needs to be defined and consumed.
  • Fault contract is similar to data contract but only the declaration changes like:

    C#
    [ServiceContract()]
    public interface IEmployeeService
    {
    [OperationContract()]
    [FaultContract(typeof(<em>some data contract named ‘fault’</em>))]
    string GetData(string name);
    }

    In the implementation class:

    C#
    public class EmployeeService: IEmployeeService
    {
    
    public string GetData(string name)
    {
    try
    {
    //execute something
    }
    catch(Exception ex)
    {
    Fault fault= new Fault (); //Data contract named Fault.
    fault.ExceptionMessage = "Error occured.";
    fault.InnerException = ex.InnerException;
    fault.StackTrace = ex.StackTrace
    throw new FaultException(fault, "Fault exception thrown";
    }
    }
    }

There are many custom attributes available to customize the contracts like Name, Serializable which can be used as per the requirements.

EndPoints

We started with basic fundamentals of WCF service and continued our journey by defining all the major items and now is the time to tell that, all these fundamentals explained above can be packed in one term, Endpoints.

We require A B C to configure our service and client, so that transmission can begin between them. It can also be termed as, we require to configure endpoints at server and client to begin transmission. Endpoint is just a term here which encapsulated ABC. The important point is, we have seen above that there are many options available for Addresses , Bindings and Contracts so we can also say that there can be multiple endpoints exposed by server to cater different clients as per their needs.

Endpoints

Endpoints

Metadata

Now we have checked all the configuration part of WCF service but to know all this, what client will have to do? client will use Metadata. The metadata of a service describes the characteristics of the service that client needs to know in order to communicate with the service. Client should have high level understanding what this service does. The metadata includes the information about data contract of the service, methods of the service , types available, security requirements. WCF defines endpoints with the extension of ‘mex’ to expose the metadata to the client.

What we have tried here is to get the users acquainted with some WCF terminologies while trying to avoid most of the complex terms. We have tried to raise the WCF knowledge from the ground up. There are many fundamentals pending but that would be more clear and useful while we develop a WCF application. Next article, we will develop one WCF service and go through the other fundamentals.

Related posts:

  1. WCF Part 1: Why WCF?
  2. know your URL
  3. Concepts: S O L I D
This article was originally posted at http://codespread.com/wcf-part-2-fundamentals.html

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer CodeSpread.com
India India
I am a regular developer working on c#,asp.net,sql,cms,digital marketing related sites. Through my blog, I am showing the non-technical part of our daily technical terms and processes which can be used to describe it to a layman.Sometimes I write basic technical posts also.

Comments and Discussions

 
-- There are no messages in this forum --