Latest

random

About WCF - An Introduction with Example

Introduction to Windows Communication Foundation (WCF)


What is WCF?

A replacement for ASMX based web services, it is basically used for making your applications interoperable with other application built with non .net based technologies or Linux based systems etc.

It is a part of the .NET Framework that provides a unified programming model for rapidly building service-oriented applications that communicate across the web and the enterprise.

Web Services
.Net Remoting
WCF
It can be accesses only over HTTP.
It can be accessed over any protocol
WCF support of almost all protocols like TCP, MSMQ, NamedPipe , Peer2Peer and HTTP.
It works in stateless environment.
Provide support for both stateful and stateless environments through Singleton and SingleCall objects
WCF Service works asynchronously.
It supports only the data types defined in the XSD type system, limiting the number of objects that can be serialized.
Using binary communication, .NET Remoting can provide support for rich type system.
WCF service can be hosted on self hosting application, IIS and WAS (windows application service).
It support interoperability across platforms, and are ideal for heterogeneous environments.
It requires the client be built using .NET, enforcing homogenous environment.
WCF is used to implement Service oriented architecture. Service oriented architecture means collection of services communicated with each other with the help of messages

ABC of an EndPoint in WCF


  • "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?

How to configuring a WCF service is always a 3 steps process
  • You have to define a contract and implement it on a service
  • You have to choose or define a service binding that selects a transport along with quality of service, security and other options
  • You have to deploy an endpoint for the contract by binding it (using the binding definition, hence the name) to a network address.

Contracts in WCF

The contract is a platform-neutral and standard way of describing what the service doesWCF defines four types of contracts.
  •     Service Contracts
  •     Data Contracts
  •     Fault Contracts
  •     Message Contracts
----

Service Contracts
Describe which operations the client can perform on the service. There are two types of Service Contracts.
  •   ServiceContract - This attribute is used to define the Interface.
  •   OperationContract - This attribute is used to define the method inside Interface.

Data contracts
Define which data types are passed to and from the service. WCF defines implicit contracts for built-in types such as int and string, but we can easily define explicit opt-in data contracts for custom types. There are two types of Data Contracts.
  • DataContract: attribute used to define the class
  • DataMember: attribute used to define the properties

If DataMember attributes are not specified for a properties in the class, that property can't be passed to-from web service.

Fault contracts
Define which errors are raised by the service, and how the service handles and propagates errors to its clients.

Message contracts
Allow the service to interact directly with messages. Message contracts can be typed or untyped, and are useful in interoperability cases and when there is an existing message format we have to comply with.

Example: Defining Service Contracts

A contract is defined explicitly, via a class. You add a [ServiceContract] attribute to the class. All methods you want to expose in your service, you mark as [OperationContract], as methods are called operations in services.

[ServiceContract]
        public class Hello
        {
            [OperationContract]
            string HelloWorld()
            {
                return "Hello world";
            }

            [OperationContract]
            string HelloComputer()
            {
                return "Hello computer";
            }

        }

Interfaces
It's always best to have an interface for our contract and have our actual service implement the interface. That's because:
  • Interfaces can extend/inherit other interfaces
  • A single class can implement multiple interfaces
  • You can modify the implementation of a service without breaking the contract
  • You can version your service via old and new interfaces
The attributes also must be specified in the interface. Eg.

[ServiceContract]
        public interface IHello
        {
            [OperationContract]
            string HelloWorld();

            [OperationContract]
            string HelloComputer();
        }

        public class Hello : IHello
        {
            string IHello.HelloWorld()
            {
                return "Hello world";
            }

            string IHello.HelloComputer()
            {
                return "Hello computer";
            }

        }

Defining Data Contracts
While a service contract defines the shape and rules for interfaces along with their associated messages and operations, the data contract defines the shape and rules for the data that is exchanged through operation's input and output messages.

See below a data contract for a person:

[DataContract]
    public class Person
    {
        [DataMember]
        public int Id;
        [DataMember]
        public string FirstName;
        [DataMember]
        public string LastName;

    }

Address of an Endpoint (A)



  • Address specifies where the service is residing.
  • This is an URL( Uniform Resource Locator)
  • Address URL identifies , location of the service.
  • Address should follow the Web Service Addressing(WS-Addressing) standard.


Scheme: This is top level portion of the address. This is not as same as protocol.
Machine: This identifies the machine name. This can be a public URL or a local identifier. 
Port: This is port number. (Optional)
Path: This is used to locate the path. This gives path of service.

The Address depends on whether it is hosted in IIS or managed application or WAS. This also depends on BINDING being used.

Example of different type of Addresses



Binding of an Endpoint (B)

Binding specifies:
  • Which protocol to be used
  • Which encoding to be used.
  • What type of security requirement to be used like SSL or SOAP message security.

Different types of Binding in WCF


1. basicHttpBinding
  • This is interoperable binding.
  • This is commonly used as replacement for earler web service based on ASMX.
  • It supports HTTP & HTTPS protocols.
  • It supports MTOM encoding.
  • It supports text encoding.
2. wsHttpBinding
  • This is a secure binding.
  • This is interoperable binding.
  • This uses SOAP over HTTP.
  • Supports reliability over Internet.
  • Supports transaction over Internet.
  • Supports security over Internet.
  • Supports HTTP/HTTPS proptcol
  • Supports text and MTOM encoding.
  • This is default binding provided by WCF.
3. wsDualHttpBinding
  • Supports all the feature of wsHttpBinding.
  • This is mainly used for DUPLEX SERVICE CONTRACTS.
  • Supports bidirectional communication.
4. webHttpBinding
  • This is a secure binding.
  • This is a interoperable binding.
  • Supports Http/Https protocol.
  • It does not use SOAP message format. It support JSON format. 
Note: This binding is mainly used for REST full services.

5. wsFederationHttpBinding:

  • This is a secure Binding.
  • This is interoperable binding.
  • Supports federated security
  • Supports HTTP/HTTPS protocols.
  • This uses text/MTOM encoding.
Note: This binding supports federated Identity.

6. netTCPBinding
  • This is a secure Binding.
  • This could only be used if client is also a WCF machine.
  • This is used to send Binary encoded SOAP message from one WCF computer to another.
  • This uses TCP (Transmission Control Protocol)
  • This supports reliability.
  • Supports transaction,
  • Supports security.
7. netNamedPipeBinding:
  • This is a secure Binding.
  • This could be used over a single WCF computer.
  • This sends Binary encoded SOAP message over named pipes.
8. netMSMQBinding:
  • This is a queued Binding.
  • This uses Binary encoded SOAP message.
  • This sends message over MSMQ.
  • Here communication should occur between two computers.
9. netPeerTCPBinding:
  • This is a secure Binding.
  • This uses TCP over peeer to peer.
  • Communication should occur between two or more computers.
10. msmqIntegrationBinding:
  • This interoperable binding is used for existing MSMQ application that uses COM and C++ API
11. basicHttpContextBinding:
 
This Binding is same as of basicHttpBinding with more attributes , like below
  • It supports HTTP cookies
  • It enable SOAP headers to exchange context.
  • This binding is mainly used for Durable services.
12. netTCPContextBinding:
This Binding is same as of netTCPBinding with more attributes , like below
  • It enable SOAP headers to exchange context.
  • This binding is mainly used for Durable services.
13. wsHttpContextBinding
This Binding is same as of wsHttpBinding with more attributes , like below
  • It enable SOAP headers to exchange context.
  • This binding is mainly used for Durable services.
Web.Config
<system.serviceModel>
                   <services>
                             <
service name="WcfService2.Service1"behaviorConfiguration="WcfService2.Service1Behavior">
                                      <!--
 Service Endpoints -->
<endpoint  address="" binding="wsHttpBinding" contract="WcfService2.IService1">
                                                <!--

              Upon deployment, the following identity element should be removed or replaced to reflect the
              identity under which the deployed service runs.  If removed, WCF will infer an appropriate identity
              automatically.
          
-->
                                                <
identity>
                                                          <
dns value="localhost"/>
                                                </
identity>
                                      </
endpoint>
                                      <
endpoint address="mex" binding="mexHttpBinding"contract="IMetadataExchange"/>
                             </
service>
                   </
services>
                   <
behaviors>
                             <
serviceBehaviors>
                                      <
behavior name="WcfService2.Service1Behavior">
                                                <!--
 To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
                                                <
serviceMetadata httpGetEnabled="true"/>
                                                <!--
 To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
                                                <
serviceDebug includeExceptionDetailInFaults="false"/>
                                      </
behavior>
                             </
serviceBehaviors>
                   </
behaviors>
          </
system.serviceModel>

Contract of and EndPoint (C)

This identify the operation exposed by the service.
  • Contract should be an Interface
  • Contract could be a class also but better approach is interface.
  • In config file this is preceded by project name space name

<endpoint  address="" binding="wsHttpBinding" contract="WcfService2.IService1">



7 comments:

  1. This is the best article I've seen on the basics of WCF. It's very clear. Thank you.

    ReplyDelete
  2. You're always welcome my friend!:)
    and thank you too for taking time to read it and share your so appreciable comment ..

    ReplyDelete
  3. one of the best example of wcf.thanx sir

    ReplyDelete

All Rights Reserved by Etechpulse © 2015 - 2016
Powered By Blogger

Contact Form

Name

Email *

Message *

Powered by Blogger.