Monday, 1 October 2012

Basics of WCF


Introduction to Windows Communication Foundation(WCF)

WCF is a Microsoft Distributed Technology.

 WCF is a Unified Programming Model, which allows clients to write a simplified Programming Model  to Develop Distributed Programming Model.
Microsoft Distributed Environments
1.       .Net Remoting.(.Net to .Net)=è net.tcp binding in wcf
2.       Asp.net Web services(.asmx)à basicHttpBinding in wcf
3.       WCF

.NET Remoting
.Net Remoting is a distributed technology of Microsoft but which a homogenious.
Which is compatability of client and server both should be .net applications. Which is also supports Binary, SOAP formats between the client and server communication. Which is fast, more convent way of communication between .net applications.
Advantages:
Which supports statefull environments like PerCall, PerSession,Single.
Which supports communications : Binary SOAP formats.
Drawbacks:
.net to .net applications only[client and server should be .net applications].
ASP.NET Web services.
ASP.NET is a Microsoft distributed  technology for  communicate with client and server.which is hetrogenious distributed service provided by the Microsoft. We also called as ASP.NET XML web services.
but in case of  asp.net web service we have only one communicate is SOAP based communication.
Advantages:
Which is Hetrogenius communication.
So asp.net web service can be independent of platform so any technology platform can consume  it.
Which supports only SOAP Format(not supports binary like .net remoting).
The client and service applications can be any applications because the request and response are xml derived type of SOAP(Simple Object Application Protocol).
Soap Versions
SOAP 1.1
 SOAP 1.2 support s from WS* -Specifications[Web Service Extensions].
WCF

WCF supports 4 types of Contracts :
What is a contract?
Contract is an aggrement between client and server for communication.like we can say a strongly typed data between client and server.
We know Exchanging data between client and server is xml-based SOAP formats. When client consume the service reference for generating proxy at client which generates few .XSD files at client which are platform independent files. Using this schema client and server exchange the data between them.

Finally Contracts are Platfrom netural  aggrements which can be

                                                              Contracts                                                                                  

 Service contract,
 Datacontract,
 Message Contract,
 Fault Contract.

ServiceContract

Service Contract makes the service available to all consumers without any platform independents of communication.

This attribute makes our .NET CLR type to WSDL.

Service Contract describes what funcationalities(operations) client can perform when consume this service.
Service is Self- described funcationality.-à as SOA rule.
Which is exposed as a wsdl to clients.

In case of Object oriented Programming. Class has Boundary means which is not exposed to out-side world to make our type funcationality  to others through web.

So make that type marked as [ServiceContract] attribute. To accessible to through out web.
Service Contract makes our funcational schema to client as a WSDL.
Inside ServiceContract every member exposed as [operationcontract].

In WCF
System.ServiceModel-à has good properties
Name, Namespace, ProtectionLevel….ect.

Data Contract:
Data Contract is an attribute in System.ServiceModel . this attribute used to define complex types used in WCF Service.
Data Contract has a complier is called DataContractSerializer. Which is used to serialize/de-serialize the type.
DataContract for  type and  DataMember for property. So inside DataContract every member should be datamember.
Which will serialize all public and private fields but not static members. Which support Enum Serialization.
Which makes communication faster. But we don’t have any control over soap message. Which is generalized xsd based soap format will generates. At server.
Supports: Versioning and Hirerchies.
Like
DataContractCollection---makes our Custom Collection
DataContract Version----using loosely copuled  xsd.  So we can add new data members to existing datacontract type.
At server newly added members are ignored at server while datacontract deserilaization.
Rules :
A data contract can be defined as follows:
·         It describes the external format of data passed to and from service operations
·         It defines the structure and types of data exchanged in service messages
·         It maps a CLR type to an XML Schema
·         t defines how data types are serialized and deserialized. Through serialization, you convert an object into a sequence of bytes that can be transmitted over a network. Through deserialization, you reassemble an object from a sequence of bytes that you receive from a calling application.
·         It is a versioning system that allows you to manage changes to structured data

Message Contract:

Message Contract is a types which is used by developer to control over the soap message. Which has types . like MessageHeader, MessageBody, MeeageHeaderArray…ect  for message format.between client and server.
Which is opt-out model.
Rules :
Below rules have to be followed while implementing a Message Contract:
·         When using Message contract type as parameter, Only one parameter can be used in service Operation
        [OperationContract]
        void SaveProductInfo(ProductInfo product);
·         Service operation either should return Messagecontract type or it should not return any value
        [OperationContract]
        ProductInfo GetProductInfo();

        ProductInfo GetProductInfo(int Productid); -----------------------Not Possible because
       Return type and Parameters are not same type. 

parameter is primative type and return type is Message based type.
·         Service operation will accept and return only message contract type. Other data types are not allowed.
        [OperationContract]
        ProductInfo ModifyProductInfo(ProductInfo productInfo);
Note: If a type has both Message and Data contract, service operation will accept only message contract

Note : We can’t mex these Datacontract and Message Contracts in single operation.
Fault Contract:
How to Handle Exceptions in .net ?
Using try and catch blocks we handles the exceptions in .net. these exceptions are specific to .net. but service exceptions should be understood by every technology so exceptions can’t be technology specific.
Service for technology independent so any one can consume it. So service exceptions also should understood by every one. So Universally accessable and understood format.
This Fault contract is exposed to client as <FaultTo> tag in wsdl. This is exposed to client as type. To handle exception at Client.
Note:
 Every type it can be DataContract,MessageContract,Fault Contract are Platform Netural .

                                                                    Bindings:                                                                            

What is Binding?

Binding is a type of communication between client and server. Binding is collection of binding elements/protocols.
Every binding has their own settings. And their own default values. The lowest level protocol is Transport protocol.
WS* Specifications are build on these bindings:
WS*-Reliable Session: supports Session Management.
WS*-Transaction : supports Transaction Management.
…ect like Every binding supports their own binding mechanism.
so finally as per our requirement we have to choose an apporiate binding model.
Wcf provides build-in buildings:
basicHttpBinding:
which is used to support introbility between wcf service and legacy asp.net web service(.asmx service) . which dosen’t support any transactions, security(but can provide) by default, and which are not WSE service. Using SOAP 1.1 Version
Advantage:
Introbiltity with old .asmx web services.
WsHttpBinding:
This binding suppots all WS* specifications. So which supports Transactions,Security,session management ..ect. using SOAP 1.2 Version.
Advantages:
Supports WS* Extensions features.
Net.tcp Binding
This binding supports binary communication between client and service. And supports message level and transport security.
WSDualHttpBindig:
This binding support Dual(bi-directional) communication between client and service. Service and client both can independently send requests and response in bi-directional formation.
…like wise every binding supports their own advantages.

WSFederationHttpBinding ,  
WS2007FederationHttpBinding ,
NetNamedPipeBinding , 
NetMsmqBinding ,
NetPeerTcpBinding ,
MsmqIntegrationBinding.. are availbel wcf build-in bindings.

Address:
WCF supports WS*-Addressing

[transport]://[machine or domain][:optional port]

Schema:[transport] protocol  schemas are
http, net.tcp
machine or domain: name of service hosted PC ( default localhost for single system);
Port Number: Every service require a port number to run the service.
EX:
http://localhost:8001
http://localhost:8001/MyService
net.tcp://localhost:8002/MyService.
 
What is Endpoint in WCF?

WCF Provides 2 endpoints:

1.    Service Endpoint.      2. Intrastructure Endpoint.
  
<endpoint         
address="http://localhost:8731/Design_Time_Addresses/WcfEmployeeCollection/Service1/"
            binding="wsHttpBinding"
            contract="ServiceReference1.IService1"

      </endpoint>
 
Address : Service is Hosted---à WHERE
         which specifies a location client has to send messages to server.
 
 
Binding : Service and Client Communication -à HOW
         How Client and service Can Communicate eachother.
                                      Means which binding.
          
Contract : What Messages and Service and Client can share eachother.
this is done through shared Schema between both.
then Exchange the data.
        Which is an Interface.
 
Interface is Platform netural type.(Java, PhP, .net)
Which doesn’t contain any type logic.(only definications)
So interace is light-weight type. Remoting also sharing the Schema same way.
 

2.  Intrastructure Endpoint
 
As per service endpoint service is hosted succefully and runs succefully.
But what is use without consumation?
So
Wcf supports WS-MetadataExchange Standard for Exposing metadata to client 
 
Which is done through 
1.  ServiceBehaviour   2. Dedicated mex Endpoint.
 
Publishing or Exposing Service metadata is responsibility of service.—SOA says[expose metadata about service opeataions].
 
1.  ServiceBehaviour
 
  <behaviors>
      <serviceBehaviors>
        <behavior name="WcfEmployeeCollection.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> 
2.  Dedicated Mex endpoint
 
Mex endpoint is used to expose service funcationality to clients.
  <endpoint address="mex" 
            binding="mexHttpBinding" 
            contract="IMetadataExchange"/>
 
If in case ServiceBehaviour set httpGetEnabled="False"/>
 
BasicHttpBinding, wsHttpBinding, wsDualHttpbinding means all Http based binds meta data is exposed with single mexHttpBinding.
 
Then service expose metadata to client using mex endpoint.(dedicated endpoint).
 
 In case of NetTcpBinding :
<endpoint        address="mex" 
                 binding="mexTcpBinding" 
                 contract="IMetadataExchange"/>
this for net.tcp based schema bindings.
 
So exposing service metadata is 2 ways
 
1.  Using ServiceBehaviour of service and
2.  Relavent Mex-Endpoint.

Note: Services should run as a adminstractor mode otherwise service will pick-up default values as service configuration.
so the hosting settings may not applicable to service till we run as service[visual studio as a adminstractor mode].

 
 
 

No comments:

Post a Comment