Click here to Skip to main content
15,867,568 members
Articles / WCF

WCF - A Quick Review

Rate me:
Please Sign up or sign in to vote.
4.95/5 (22 votes)
3 Sep 2013CPOL6 min read 40.9K   41   9
This article is for those who want to revise WCF in a single go.

Introduction

I have read many articles on WCF but I am always looking for an article which gives me a quick look at every topic of WCF. This article is for those who want to revise WCF in a single go. Let’s start with Service Oriented Architecture and after that, we will take a look at WCF.

What is SOA?

SOA is an architectural style for building business applications using loosely coupled services which are orchestrated to achieve a specific functionality by linking together. It’s not a technology or tool. SOA shifts our thinking from classes and objects to Services and Communication mechanisms to Messages instead of HTTP.

Points to Remember about SOA

  1. SOA separates application into services:
    • It allows connectivity of dissimilar technologies
    • It should be durable and secure
  2. Services and Messages are building blocks of SOA:
    • Service-Self-contained business functionality
    • Services should communicate using messages
    • Service should define themselves
    • Messages formats should be standard, e.g., XML
    • Messages should be able to communicate asynchronously and should be reliable
    • Messages should be able to describe and discover a service in a standard manner

Benefits of SOA

  • Location independence
  • Interoperable across platforms
  • API-like development paradigm
  • Better organisation than object distribution
  • Loose coupling
  • Security

Principles of Service Orientation

  1. Boundaries are explicit
    • A service communicates by sending messages across their boundary
    • All communication occurs through messages
  2. Services are autonomous
    • We can build, manage, and version services independently
    • We can change a service without affecting clients as long as clients can continue sending and receiving the same message
  3. Services share contracts and schema
    • Contract describes the messages a service can send and receive
    • Schemas define how the client and service construct the messages they exchange

What is the difference between a Service and a Component?

A Service is used to communicate in a heterogeneous environment. It enables us to go cross platform. Components and classes bind us to communicate inside a programming boundary. It ties us to a specific language.

Windows Communication Foundation

WCF was introduced in Microsoft .NET framework 3.0. Formerly known as Indigo, it’s a unified model that brings together web services, Remoting, Sockets, MSMQ and Enterprise services. It enforces the SOA approach and provides Transaction support, security, durability, etc.

All the classes related to WCF come under the System.ServiceModel namespace.

Image 1

Benefits of WCF

  • Reliability
  • Durability
  • Transaction
  • Instance Management
  • Throttling
  • Interoperability
  • Fault Isolation
  • Logging
  • Tracing
  • Synchronization
  • Error Masking
  • Buffering
  • Versioning

EndPoints

All communication with a Windows Communication Foundation (WCF) service occurs through the endpoints of the service. Endpoints provide clients access to the functionality offered by a WCF service – MSDN.

The host application makes the service available by providing one or more endpoints to the clients. Each endpoint consists of three elements: Address, Binding, and Contract.

Image 2

Address: In WCF, every service is associated with a unique address. The address consists of two important elements:

  1. Service location – The portion of the address indicates the name of the target machine
  2. Transport protocol - Example: HTTP/HTTPS, TCP, IPC, MSMQ, etc.

[base address] / [optional URI]

Example: http:// localhost:8001

Contracts: The Contract is a platform-neutral and standard way of describing what the service does. WCF defines four types of Contracts:

  1. Service Contracts
    • It is an interface that defines a service operation which works with a single type or data contracts.
    • Describes which operations the client can perform on the service.
    • [ServiceContract] attribute marks an interface as a service contract.
    • [OperationContact] attribute exposes methods of the interface.
    C#
    // Employee ServiceContract
    [ServiceContract]
    public interface IEmployeeService
    {
          // Define the GetEmpName OperationContact here….
        [OperationContract]
        String GetEmployeeName (int empId);
    
          // Define the GetempInfo OperationContact here….
        [OperationContract]
        StudentInformation GetEmployeeInfo (int empId);
    }
  2. Data Contracts
    • Defines which data types are passed to and from the service.
    • Describes how CLR types are mapped to XSD schema definitions.
    • WCF defines implicit contracts for built-in-types such as int and string, but you can easily define explicit opt-in-data contract for custom types.
    • Enables complex types to be serialized and deserialized so it can be passed.
    • It must be decorated with [Data Contracts].
    • Every member of a Data Contract should be decorated with [DataMember].
    C#
    [DataContract]
    public class EmployeeInfo
    {
        [DataMember]
        Public string EmpName;
    
        // Define the other Datamembers here….
    }
  3. Fault Contracts
    • Define which errors are raised by the service and how the service handles and propagates errors to its clients.
    • We use the FaultContact attribute on service’s operation.
    • Use the FaultException<T> class to return a strongly typed SOAP fault.
  4. Message Contracts
    • It allows the service to interact directly with messages.
    • It can be typed or untyped.
    • Message contracts are useful in interoperability cases.

Channels

  • Clients and services communicate by passing messages
  • The mechanism that they use to communicate is a channel stack, which is made up of channels.

Image 3

Bindings

  • Bindings specify how clients and WCF services communicate:
    • Specifies how a client endpoint communicates with a service endpoint.
    • Specifies the transport protocol, message-encoding, security, transaction, and reliability the client and service will use.
  • A binding represents the channel stack.
  • Bindings inherit from the Binding class.
  • Consists of binding elements describing some aspects of the communication.
    • Transport (HTTP, TCP, etc.)
    • Protocol (security, reliability, transaction, etc.)
    • Message encoding (text, binary, etc.)
  • A binding is comprised of several binding elements.
  • Each binding element corresponds to a channel in the channel stack.
  • Binding element inherits from the BindingElement class.
  • Can be created declaratively or programmatically.

The frequently used bindings in WCF are:

  1. BasicHttpBinding – It is designed to expose a WCF service as a legacy ASMX web service.
  2. WSHttpBinding- It uses HTTP or HTTPS for transport and offers a variety of features over internet, all using the WS-* standards. Visual Studio uses this by default.
  3. WSDualHttpBinding – Support WS-* plus two way communication.
  4. NetTcpBinding – TCP binding uses TCP for cross-machine communication on the intranet. It supports a variety of features including reliability, transactions, and security. It is optimized for WCF – to – WCF communication.
  5. NetNamedPipeBinding – This binding is used for inter Process Communication (IPC). It uses named pipes as a transport for same machine communication. It is the most secure binding.
  6. NetMsmqBinding- This binding uses MSMQ for transport and offers support for disconnected queued calls.

Hosting

  1. It exposes service on wire so client can use it.
  2. A WCF service can be hosted in the following ways:
    1. IIS hosting
    2. Self hosting
      1. Console application
      2. Window Service
      3. Windows Forms or a WPF application
    3. WAS hosting

    Image 4

  3. Role of the host application
    • Start and stop the service
    • Listen for request from clients
    • Direct those requests to the service
    • Send responses back to the clients
  4. ServiceHost object is associated with a WCF service at runtime.

Binding Configuration

  1. Binding configuration allows tweaking of communication characteristics between the client and the service.
  2. Sets the characteristics of the transport.
  3. Usually set on both the client and the service.
  4. Set on the endpoint itself.
  5. Potential settings:
    1. Session reliability
    2. Message size
    3. Timeouts
    4. Security

a) Reliability

  • Can be used with NetTCPBinding or WSHttpBinding
  • Enables communication retries
  • Also enforces message ordering
XML
<reliableSession enabled="true" order="true"/>

b) Message size

  • Can be used with any binding
  • Increase or decrease total message size, default 64K
  • Useful when returning lists or a stream
XML
<binding name="binding1" maxReceivedMessageSize="100000">
</binding>

c) Transmission Timeouts

  • Can be used with any Binding
  • Sets the maximum time WCF will wait for a message to be transmitted
  • Throws exception when exceeded
  • Default is 45
XML
<binding name="binding1" sendTimeOut="00:01:00"
</binding>

Best Practices

  • Always set reliability to true
    • Benefits from retries
    • Ordering may only be important for one way calls
  • Default timeouts are usually fine

Service Behaviour

  • Attribute controls Runtime aspects of the service
  • Characteristics specify to the service only
  • Does not affect binding (Transport)
  • Typically unknown to client
  • It can be configured in a number of ways
  • Two types of settings (not always both)
    • Configuration
    • Attribute decoration (at Service class level)
  • Service behaviour defined at Service level not at the endpoint level like Binding configuration.

Configuration

XML
<service name="MyService" behaviourConfiguration="behaviour1">
<endpoint> </endpoint>
</service>
 
<behaviours>
   <serviceBehaviors>
        <behaviour name="behaviour1">
            <..  ...>
        </behavior>
   </serviceBehaviors>
</behaviours>

Attribute Decoration

C#
[ServiceBehavior(InstanceContextMode=InstanceContextMode.PerCall)]
Public class MyService : IMyService
{
   ... implementation code here....
}

Service Debugging

  • By default, service does not pass error details to client.
  • We can set attribute in config file or on service to get more clear error information.
  • In config file:
    XML
    <behaviours>
       <serviceBehaviors>
            <behaviour name="behaviour1">
                <serviceDebug includeExceptionDetailsInFault="true"/>
            </behavior>
       </serviceBehaviors>
    </behaviours>
  • In Service class:
    C#
    [ServiceBehavior(includeExceptionDetailsInFault=true)]
    Public class MyService : IMyService
    {
    ... implementation code here....
    }  

    Thanks for reading. if you like the article, please vote up. Happy coding!!!

License

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


Written By
Software Developer Morpho E-Documents
India India
I Started my Programming career in 2010.I develop Web applications using C# to create Information Systems, e-commerce Portals and Data driven websites.

I am MCP and MCTS (Web Application Development with Microsoft .Net Framework 4 (70-515), Programming in HTML5 with Javascript and CSS Specialist(70-480)and Microsoft Sharepoint Application Development (70-573)).

My interests involves Programming, Website development and Learning subjects related to Computer Science/Information Systems.C# is the best programming language and I love working with C# and other Microsoft Technologies.

Comments and Discussions

 
GeneralMy vote of 3 Pin
sandipraj2125-Nov-13 19:56
sandipraj2125-Nov-13 19:56 
QuestionVery Usefull articles on WCF Pin
sandipraj2125-Nov-13 19:55
sandipraj2125-Nov-13 19:55 
GeneralMy vote of 5 Pin
Pratik Bhuva23-Oct-13 21:44
professionalPratik Bhuva23-Oct-13 21:44 
QuestionGood Article. As i am new to WCF, i want suggestions plz help me... Pin
Pratik Bhuva23-Oct-13 21:42
professionalPratik Bhuva23-Oct-13 21:42 
GeneralMy vote of 4 Pin
Mohammed Hameed4-Sep-13 19:01
professionalMohammed Hameed4-Sep-13 19:01 
Main concepts of WCF highlighted. Thanks.
GeneralMy vote of 5 Pin
Antariksh Verma22-Aug-13 3:02
professionalAntariksh Verma22-Aug-13 3:02 
GeneralMy vote of 5 Pin
SagarRS22-Aug-13 1:41
professionalSagarRS22-Aug-13 1:41 
GeneralVery Good.... Some Typos Pin
sund7wells19-Aug-13 23:57
sund7wells19-Aug-13 23:57 
GeneralRe: Very Good.... Some Typos Pin
Bhupendra Chauhan20-Aug-13 0:28
professionalBhupendra Chauhan20-Aug-13 0:28 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.