sobota, 1 grudnia 2012

WCF

WHAT IS IT?

Windows Communication Foundation - WCF - (Code named Indigo) is a programming platform and runtime system for building, configuring and deploying network-distributed services.
WCF allows developers to create, host, consume and secure services using Microsoft platform in a most productive way so that developers can focus on their implementation rather than communication protocols and low level messaging details.

A WCF Service is the heart of the communication process. This kind of service is basically a component running within a host such as IIS or a custom executable. The host runs the service and directs calls to it over supported protocols such as http. External clients interact with the WCF service via a proxy that acts as a local instance of the service. The proxy takes the client request to call an operation on the service, packages it using the protocol that the service supports, and sends it to the service by way of the service host. The service then executes the operation and sends back any output to the proxy. The proxy in turn unpackages that information and returns it to the client.

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
Difference between WCF and Web service
Web service is a part of WCF. WCF offers much more flexibility and portability to develop a service when comparing to web service. Still we are having more advantages over Web service, following table provides detailed difference between them.

Features Web Service WCF
Hosting It can be hosted in IIS It can be hosted in IIS, windows activation service, Self-hosting, Windows service
Programming [WebService] attribute has to be added to the class [ServiceContraact] attribute has to be added to the class
Model [WebMethod] attribute represents the method exposed to client [OperationContract] attribute represents the method exposed to client
Operation One-way, Request- Response are the different operations supported in web service One-Way, Request-Response, Duplex are different type of operations supported in WCF
XML System.Xml.serialization name space is used for serialization System.Runtime.Serialization namespace is used for serialization
Encoding XML 1.0, MTOM(Message Transmission Optimization Mechanism), DIME, Custom XML 1.0, MTOM, Binary, Custom
Transports Can be accessed through HTTP, TCP, Custom Can be accessed through HTTP, TCP, Named pipes, MSMQ,P2P, Custom
Protocols Security Security, Reliable messaging, Transactions

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
WCF Architecture

http://www.c-sharpcorner.com/uploadfile/suthish_nair/wcf-architecture/
http://www.codeproject.com/Articles/188917/WCF-Architecture
http://msdn.microsoft.com/en-us/library/ms733128.aspx

The following figure illustrates the major components of WCF.


Contracts
Contracts layer are next to that of Application layer. Developer will directly use this contract to develop the service. Let us see briefly what these contracts will do for us and we will also know that WCF is working on message system.
  • Service contracts
    Describe about the operation that service can provide. Example, Service provided to know the temperature of the city based on the zip code, this service we call as Service contract. It will be created using Service and Operational Contract attribute.

    [ServiceContract]
    interface IMyContract
    {
       [OperationContract]
       string MyMethod( );
    }

    class MyService : IMyContract
    {
       public string MyMethod( )
       {
          return "Hello World";
       }
    }
  • Data contract
    It describes the custom data type which is exposed to the client. This defines the data types, are passed to and from service. Data types like int, string are identified by the client because it is already mention in XML schema definition language document, but custom created class or datatype cannot be identified by the client e.g. Employee data type. By using DataContract we can make client aware that we are using Employee data type for returning or passing parameter to the method.

    [DataContract]
    class Contact
    {
       [DataMember]
       public string FirstName;

       [DataMember]
       public string LastName;
    }
  • Message Contract
    Default SOAP message format is provided by the WCF runtime for communication between Client and service. If it is not meeting your requirements then we can create our own message format. This can be achieved by using Message Contract attribute.

    [MessageContract]
    public class BankingTransaction
    {
      [MessageHeader]
      public Operation operation;

      [MessageBodyMember]
      private Account sourceAccount;
    }
  • Policies and Binding
    Specify conditions required to communicate with a service e.g security requirement to communicate with service, protocol and encoding used for binding.
Sample Image - maximum width is 600 pixels


Service Runtime
It contains the behaviors that occur during runtime of service.
  • Throttling Behavior
    Controls how many messages are processed.
  • Error Behavior
    Specifies what occurs, when internal error occurs on the service.
  • Metadata Behavior
    Tells how and whether metadata is available to outside world.
  • Instance Behavior
    Specifies how many instance of the service has to be created while running.
  • Message Inspection
    Gives the service the ability to inspect all or parts of a message.
  • Transaction Behavior
    Enables the rollback of transacted operations if a failure occurs.
  • Dispatch Behavior
    Controls how a message is processed by the WCF Infrastructure. 
  • Concurrency Behavior
    Determines how each service, or instance of the service, handles threading.
  • Parameter Filtering
    Filters the message headers and executes preset actions based on the filter of the message headers. 
Messaging
Messaging layer is composed of channels. A channel is a component that processes a message in some way, for example, by authenticating a message. A set of channels is also known as a channel stack. Channels are the core abstraction for sending message to and receiving message from an Endpoint. Broadly we can categories channels as  

  1. Transport Channels
    Handles sending and receiving message from network. Protocols like HTTP, TCP, name pipes and MSMQ.
    • Encoders let you pick from a number of encodings for the message.
    • HTTP Channel tells the service that message delivery will take place via the HTTP protocol.
    • TCP Channel tells the service that message delivery will take place via the TCP protocol.
    • Transaction Flow Channel governs transacted message patterns.
    • NamedPipe Channel enables inter-process communication.
    • MSMQ Channel helps to use MSMQ.
  2. Protocol Channels
    Implements SOAP based protocol by processing and possibly modifying message. E.g. WS-Security and WS-Reliability.
    • WS Security Channel implements the WS-Security specification, which enables message security. 
    • WS Reliable Messaging Channel which provides guaranteed message delivery.

Activation and Hosting
Services can be hosted or executed, so that it will be available to everyone accessing from the client. WCF service can be hosted by following mechanism
  • IISInternet information Service provides number of advantages if a Service uses Http as protocol. It does not require Host code to activate the service, it automatically activates service code.
  • Windows Activation Service
    (WAS) is the new process activation mechanism that ships with IIS 7.0. In addition to HTTP based communication, WCF can also use WAS to provide message-based activation over other protocols, such as TCP and named pipes.
  • Self-Hosting
    WCF service can be self hosted as console application, Win Forms or WPF application with graphical UI.
  • Windows Service
    WCF can also be hosted as a Windows Service, so that it is under control of the Service Control Manager (SCM).   
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Endpoints  
Each WCF service exposes one or more endpoints to its clients and all the communication takes place through those endpoints. In simple words, an endpoint is a resource on the network to which clients can send messages. These messages are formatted according to the contract on which both client and service are agreed. For successful and meaningful communication between client and the service both parties needs to know the Address of the service, the binding and the contracts commonly known as ABCs of WCF. 
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.
Each endpoint consists of four properties:
- An address that indicates where the endpoint can be found.
- A binding that specifies how a client can communicate with the endpoint.
- A contract that identifies the operations available.
- A set of behaviors (OperationContract) that specify local implementation details of the endpoint. 

Sample Image - maximum width is 600 pixels


 

Address
The address (where) defines the location to which the messages must be send by the client to start the communication with the WCF service.
For HTTP, the address would look like
http://webserver/webservice 
and for TCP, it would look like
net.tcp://webserver:8080/webservice.

Binding
The binding (how) specifies how client will communicate with the service. It defines a serious of binding elements which can be configured to suit your application needs. The lowest level binding element is the transport that defines the base protocol to be used such as HTTP, Named Pipes, TCP, MSMQ etc. Encoding element defines the type of encoding to be used such as Text, Binary or MTOM. Other elements are related to security, transaction or reliable messaging capability etc. 

Fortunately, WCF has some predefined bindings with all these binding elements correctly configured for you to save your time of figuring it out yourself.  Some of the most common bindings are shown below: 

BindingDescription
BasicHttpBindingBasic Web service communication. No security by default
WSHttpBindingWeb services with WS-* support. Supports transactions
WSDualHttpBindingWeb services with duplex contract and transaction support
NetMsmqBindingCommunication between WCF applications by using queuing. Supports transactions
NetNamedPipeBindingCommunication between WCF applications on same computer. Supports duplex contracts and transactions
NetPeerTcpBindingCommunication between computers across peer-to-peer services. Supports duplex contracts
NetTcpBindingCommunication between WCF applications across computers. Supports duplex contracts and transactions

A binding will tell a client what's necessary to connect to the service. In other words, how we connect is described by the binding. As you can see in the image, this is composed from the protocols selected, the chosen encoder and chosen transport.


 

The image also shows the architecture of WCF. The service-host initiates one or more dispatchers. In configuration you setup the protocols, encoder and transport to use, per endpoint. At the client side you do this as well. When a message is send from client to service, it first goes through the (generated) proxy, through configured protocols, encoder and finally will be send over a transport layer.
On the other end, the same happens, but the other way around.
  • Protocols
    These can be anything, but some of the default delivered with WCF are, for example, reliable messaging or transactions. When the message should be encrypted, it's done in this layer.
  • Encoder
    This is text/xml for HTTP bindings, but binary xml for the TCP binding.
  • Transport
    This can be HTTP or TCP, NamedPipes or MSMQ.

Contract
The contract (what) is an agreement between two or more parties for common understanding and it is a platform-neutral and standard way of describing what the service does. In WCF, contracts are mapped to interfaces which describe the list of operations exposed to the clients from a particular endpoint. The following three types of contracts are supported by WCF.


Client Communication:
Consume Services via Channels based on Endpoints (Binding)
- Client retrieves Endpoint using Metadata information (WSDL)
- Regarding WSDL and Metadata we will see in coming articles.


 

A WCF service can expose multiple endpoints where each endpoint is defined by an address, binding and contract. Clients can also implicitly host endpoints to facilitate the message flow which is typically bidirectional.

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------WCF Communication Model

A WCF Service is comprised of the following major components. The diagram below shows how the components are related to each other:
  • Service Contract
    http://msdn.microsoft.com/en-us/library/system.servicemodel.servicecontractattribute.aspx
  • Operation Contract
    http://msdn.microsoft.com/en-us/library/system.servicemodel.operationcontractattribute.aspx
  • Data Contract
    http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractattribute.aspx
  • Data Member
    http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datamemberattribute.aspx


-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------WCF Configuration Complexity

Windows Communication Foundation supports a pretty extensive XML configuration schema in your app.config or web.config file to configure both service providers and service consumers as an alternative to using code to set things up.

Instead of using the XML hierarchical nature to represent a service or client configuration, the WCF configuration schema is based on keys (identifiers) and references, similar to how you'd do it in a relational database.

The most important difference is that a client configuration doesn't specify service behaviors (not needed), but otherwise it is pretty similar. 

The server configuration looks a bit like this:




A client configuration is somewhat similar:



-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
EXAMPLE OF CONFIG FILE:

http://msdn.microsoft.com/en-us/library/ms731354.aspx

<services>
   <service name="VoucherService" behaviorConfiguration="voucherServiceBehaviors">
      <endpoint contract="IVoucherService" binding="wsHttpBinding"
                bindingConfiguration="voucherServiceBinding"/>
      <endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex"/>
   </service>
</services>
<behaviors>
   <serviceBehaviors>
      <behavior name="voucherServiceBehaviors">
         <serviceMetadata httpGetEnabled="true"/>
         <serviceDebug includeExceptionDetailInFaults="true"/>
      </behavior>
   </serviceBehaviors>
</behaviors> 

<bindings>
   <wsHttpBinding>
      <binding name="voucherServiceBinding" closeTimeout="00:01:00"
          openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
          bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard"
          maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
          messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true"
          allowCookies="false">
         <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
             maxBytesPerRead="4096" maxNameTableCharCount="16384" />
         <reliableSession ordered="true" inactivityTimeout="00:10:00"
             enabled="false" />
         <security mode="None">
            <transport clientCredentialType="Windows" proxyCredentialType="None"
                realm="" />
            <message clientCredentialType="Windows" negotiateServiceCredential="true"
                establishSecurityContext="true" />
         </security>
      </binding>
   </wsHttpBinding>
</bindings> 

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------WCF Architecture: Messaging Runtime

The WCF runtime is divided into 2 primary layers as shown by the following picture:
  • The Service Layer aka Service Model defines the mechanisms and attributes used by developers to define and decorate service, message and data contracts.
  • The  Messaging Layer  is responsible for preparing a WCF message for transmission on the send side and produce a WCF message for the dispatcher on the receive side. The messaging layer accomplishes this task using a Channel Stack. This latter is a pipeline of channel components that handle different processing tasks.  Each channel stack is composed of exactly one transport channel, one message encoder, and zero or more protocol channel
WCF_Layers
A typical WCF communication can be described as follows:

  1. The client application creates one or more input parameters. Each of these parameters is defined by a data contract.
  2. The client application invokes one of the methods of the service contract exposed by the proxy.
  3. The proxy delivers a WCF Message object to the channel stack.
  4. At this point each protocol channel has a chance to operate on the message before the transport channel uses a message encoder to transmit the final Message as a sequence of bytes to the target service. Each protocol channel can modify the content or the headers of the message to implement specific functionalities or WS-* protocols like WS-AtomicTransaction, WS-Security.
  5. The raw stream of data is transmitted over the wire.
  6. On the service side, the transport channel receives the stream of data and uses a message encoder to interpret the bytes and to produce a WCF Message object that can continue up the channel stack. At this point each protocol channel has a chance to work on the message.
  7. The final Message is passed to the Dispatcher.
  8. The Dispatcher receives the WCF Message from the underlying channel stack, individuates the target service endpoint using the destination address and Action property contained in the Message, deserializes the content of the WCF Message into objects.
  9. Finally the target service method is invoked.
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
MSDN:
http://msdn.microsoft.com/en-us/library/ms195526.aspx
http://msdn.microsoft.com/en-us/library/system.servicemodel.servicecontractattribute.aspx
http://msdn.microsoft.com/en-us/library/system.servicemodel.operationcontractattribute.aspx
http://msdn.microsoft.com/en-us/library/system.servicemodel.endpoint.aspx
http://msdn.microsoft.com/en-us/library/system.servicemodel.channelfactory.aspx 

http://msdn.microsoft.com/en-us/library/bb907578.aspx
http://msdn.microsoft.com/en-us/library/dd560536.aspx
http://msdn.microsoft.com/en-us/library/dd456779%28v=vs.110%29.aspx 
http://msdn.microsoft.com/en-us/library/cc668792%28v=vs.100%29.aspx

 
Materials:
http://wcftutorial.net/WCF-Architecture.aspx
http://andrewtokeley.net/archive/2008/07/31/wcf-simplified-to-a-single-diagram.aspx
http://www.devproconnections.com/article/windows-communication-foundation-wcf2/Implementing-SOA-Patterns-with-WCF-and-NET-4-0-125163
http://www.iprodeveloper.com/print/otherlanguages/soa-using-ca-plex-and-wcf-26130
http://msdn.microsoft.com/en-us/library/orm-9780596527563-01-10.aspx
http://www.codeproject.com/Articles/255114/Windows-Communication-Foundation-Basics
http://visualstudiomagazine.com/articles/2011/06/01/pcnet_wcf-and-soa.aspx
http://blogs.msdn.com/b/appfabriccat/archive/2010/06/23/customizing-and-extending-the-biztalk-wcf-adapters.aspx
http://msdn.microsoft.com/en-us/magazine/dd347832.aspx
http://www.ezzylearning.com/tutorial.aspx?tid=2189233&q=programming-wcf-services
http://net-daylight.blogspot.com/2011/12/working-with-endpointbehavior-in-wcf.html
http://www.ezzylearning.com/tutorial.aspx?tid=3154426&q=introducing-windows-communication-foundation-wcf
http://davishucode.blogspot.com/2012/07/wcf-beginners-abc-of-endpoint-and.html
http://blogs.msdn.com/b/appfabriccat/archive/2010/06/23/customizing-and-extending-the-biztalk-wcf-adapters.aspx
http://www.codeproject.com/Articles/255114/Windows-Communication-Foundation-Basics
http://net-daylight.blogspot.com/2011/12/working-with-endpointbehavior-in-wcf.html
http://visualstudiomagazine.com/articles/2011/06/01/pcnet_wcf-and-soa.aspx
http://www.codeproject.com/Articles/29243/A-Windows-Communication-Foundation-WCF-Overview
http://jamescbender.com/bendersblog/archive/2011/12/06/getting-started-with-wcf-part-8-ndash-rest-services-the.aspx
http://www.c-sharpcorner.com/UploadFile/dhananjaycoder/creating-hosting-and-consuming-wcf-service-with-wcf-service-library-project-template/
http://www.c-sharpcorner.com/UploadFile/db2972/wcf-introduction-and-contracts-day-1/
http://www.packtpub.com/article/guide-wcf-vs-2008-sp1-vs-2010-express
http://www.paraesthesia.com/archive/2008/11/26/reading-wcf-configuration-from-a-custom-location.aspx
http://nareshkamuni.blogspot.com/2012/01/wcf-interview-questions.html
http://nareshkamuni.blogspot.com/search/label/WCF

http://msdn.microsoft.com/en-us/library/cc825354.aspx
http://www.cnblogs.com/malaikuangren/archive/2012/06/16/2552070.html
http://www.devproconnections.com/article/net-framework2/routing-messages-in-wcf-4-0

http://www.silverlightshow.net/items/WCF-RIA-Services-Part-1-Getting-Started.aspx
http://www.codeguru.com/csharp/.net/net_wcf/article.php/c19671/Windows-Communication-Foundation.htm


PL:
http://eastgroup.pl/post/70-562-Creating-and-Consuming-WCF-Services.aspx
http://eastgroup.pl/post/70-503-Windows-Communication-Foundation.aspx
http://www.codeguru.pl/baza-wiedzy/wcf-w-praktyce-czesc-1---wstep-kontrakt---definiujemy-usluge,1718
http://dev.cdur.pl/Artykuly/Artykul/31,Rozpoczynamy_przygode_z_WCF
http://patryknet.blogspot.com/2010/02/tworzenie-i-konsumpcja-webserwisu-wcf.html
http://kodzimy.net/2011/12/16/usluga-wcf-csharp/
http://www.pzielinski.com/?p=399
http://wcf.studentlive.pl/Podstawy.aspx
http://dev.cdur.pl/Artykuly/Artykul/35,Kontrakty_w_WCF
http://pl.wikipedia.org/wiki/WCF_Data_Services
http://www.codeguru.pl/baza-wiedzy/zaawansowane-elementy-modelu-obietkowego-wcf,2188
http://www.codeguru.pl/baza-wiedzy/wstep-do-technologii-wcf,2186
http://www.codeguru.pl/baza-wiedzy/wcf-w-praktyce-czesc-1---wstep-kontrakt---definiujemy-usluge,1718
http://kainos.pl/blog/tworzenie-kontraktu-uslugi-wcf/
http://www.pzielinski.com/?cat=21

CODE:
http://dotnetslackers.com/WSE/re-44236_Introducing_the_lt_DataContract_gt.aspx
http://robbincremers.me/2012/01/05/wcf-rest-service-with-xml-json-response-format-according-to-content-type-header/



http://wcftutorial.net/Home.aspx
http://msdn.microsoft.com/en-us/library/bb798084.aspx

Brak komentarzy:

Prześlij komentarz