WCF
- Windows Communication Foundation (Code named Indigo) is
a programming platform and runtime system for building, configuring and
deploying network-distributed services.
- It is unified programming model provided in .Net
Framework 3.0. WCF is a combined feature of Web Service, Remoting, MSMQ
and COM+.
- WCF provides a
common platform for all .NET communication.
Difference
between WCF and Web service
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
|
[ServiceContract] 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
|
Different
bindings supported by WCF
Binding
|
Description
|
BasicHttpBinding
|
Basic Web service communication. No
security by default
|
WSHttpBinding
|
Web services with WS-* support.
Supports transactions
|
WSDualHttpBinding
|
Web services with duplex contract and
transaction support
|
WSFederationHttpBinding
|
Web services with federated security.
Supports transactions
|
MsmqIntegrationBinding
|
Communication directly with MSMQ
applications. Supports transactions
|
NetMsmqBinding
|
Communication between WCF
applications by using queuing. Supports transactions
|
NetNamedPipeBinding
|
Communication between WCF
applications on same computer. Supports duplex contracts and transactions
|
NetPeerTcpBinding
|
Communication between computers
across peer-to-peer services. Supports duplex contracts
|
NetTcpBinding
|
Communication between WCF
applications across computers. Supports duplex contracts and transactions
|
Different contracts in WCF
Service Contract
Service contracts describe the
operation that service can provide. For Eg, a Service provide to know the
temperature of the city based on the zip code, this service is called as
Service contract. It will be created using Service and Operational Contract
attribute.
Data Contract
Data contract describes the custom data
type which is exposed to the client. This defines the data types, which 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 data types cannot be identified by the
client e.g. Employee data type. By using DataContract we can make client to be
aware of Employee data type that are returning or passing parameter to the
method.
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.
Fault Contract
Suppose the service I consumed is not
working in the client application. I want to know the real cause of the
problem. How I can know the error? For this we are having Fault Contract. Fault
Contract provides documented view for error occurred in the service to client.
This helps us to easy identity, what error has occurred.
Now if you want to send exception information form service
to client, you have to use FaultException as shown below.
public int Add(int num1, int num2)
{
//Do something
throw new FaultException("Error while adding number");
}
ABC of Windows Communication Foundation
What are the ABCs of WCF? "ABC" stands for
address, binding and contract.
1.
Address (Where)
It specifies the location of the
service means, where the service is hosted. The service hosting URL may be like
http://server/wcfService. Clients will use this location to communicate with
your service.
2.
Binding (How)
It specifies how the client will
communicate to the service. We have different protocols (like http,tcp,named
pipe,msmq) for the WCF to communicate to the client.
3.
Contract (What)
It specifies what the service will do.
For this purpose we have different contract like as Data Contract, Operation
Contract, Message Contract, Fault Contract.
WCF Hosting
A WCF service is a component that can be called by other
applications. It must be hosted in an environment in order to be discovered and
used by others. The WCF host is an application that controls the lifetime of
the service. With .NET 3.0 and beyond, there are several ways to host the
service.
1.
Self hosting
A WCF service can be self-hosted, which
means that the service runs as a standalone application and controls its own
lifetime. This is the most flexible and easiest way of hosting a WCF service,
but its availability and features are limited.
2.
Windows services hosting
A WCF service can also be hosted as a
Windows service. A Windows service is a process managed by the operating system
and it is automatically started when Windows is started (if it is configured to
do so). However, it lacks some critical features (such as versioning) for WCF
services.
3.
IIS hosting
A better way of hosting a WCF service
is to use IIS. This is the traditional way of hosting a web service. IIS, by
nature, has many useful features, such as process recycling, idle shutdown,
process health monitoring, message-based activation, high availability, easy
manageability, versioning, and deployment scenarios. All of these features are
required for enterprise-level WCF services.
4.
Windows Activation Services hosting
The IIS hosting method, however, comes
with several limitations in the service-orientation world; the dependency on
HTTP is the main culprit. With IIS hosting, many of WCF's flexible options
can't be utilized. This is the reason why Microsoft specifically developed a
new method, called Windows Activation Services, to host WCF services.
Windows Process Activation Service
(WAS) is the new process activation mechanism for Windows Server 2008 that is
also available on Windows Vista. WAS hosting is possible only with IIS
7.0.Additional WCF components also plug into WAS to provide message-based
activation over the other protocols that WCF supports, such as TCP, MSMQ, and
named pipes. This allows applications that use the non-HTTP communication
protocols to use the IIS features such as process recycling, rapid fail
protection, and the common configuration systems that were only available to
HTTP-based applications.
Security Modes in WCF:
Many
WCF services will require secure communication, where
it is necessary to authenticate the sender of a message, and to ensure that
messages have not been read or tampered with by unauthorized third
parties.
WCF can provide authentication, privacy, and
integrity for messages by using two mechanisms.
The Security Modes are stated below
- Transport
Mode
- Message
Mode
- Mixed
Mode
Let us now explain each one of them in
details
Transport Mode
- Transport
mode, which uses the security features
of a transport layer such as HTTPS.
- This
mode has performance benefits due to the optimized nature of the
underlying protocols, but it has a restricted set of credential or claim
types.
- This
mode also only works between two transport endpoints
Message Mode
- Message
mode, which protects the message
itself by using a protocol such as WS-Security.
- Credential
information is embedded within the message so that this mode can support a
richer set of claim types at the expense of performance.
- This
mode provides end-to-end security for the message.
Mixed Mode
- WCF
also supports a mixed mode, where integrity and privacy are
provided by the transport, while authentication is handled by using
credentials in the message.
- This
can give the best balance of performance and flexibility.
- You
can specify the security for a binding by setting its SecurityMode
property.
- By
default, the BasicHttpBinding has no security configured. Other HTTP
bindings use WS-Security, and TCP and Named Pipe bindings use Windows
security
Metadata Exchange Endpoint
Exposing the metadata using HTTP-GET has a disadvantage,
such that there is no guarantee that other platforms you interact will support
it. There is other way of exposing the using special endpoint is called as
Metadata Exchange Endpoint. You can have as many metadata exchange endpoints as
you want.
Address
It is basically Uri to identify the metadata. You can
specify as address in the endpoint but append with "mex" keyword. For
example "http://localhost:9090/MyCalulatorService/mex"
Binding
There are four types of bindings supported for metadata
exchange. They are mexHttpBinding, mexHttpsBinding, mexNamedPipesBinding,
mexTcpBinding.
Contract
IMetadataExchange is the contract used for MEX endpoint. WCF
service host automatically provides the implementation for this
IMetadataExcahnge while hosting the service.
You can create the Metadata Exchange Endpoint either
Administrative (configuration file) or programmatically.
Administrative (Configuration file):
In the configuration file of the hosting application, you
can add metadata exchange endpoint as shown below.
<system.serviceModel>
<services>
<service name="MyService">
<endpoint address="http://localhost/IISHostedService/MyService.svc"
binding="wsHttpBinding" contract="IMyService">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
</system.serviceModel>
Channels:
Channels are the core abstraction for sending message to and
receiving message from an Endpoint. Broadly we can categories channels as
Transport Channels
- Handles
sending and receiving message from network. Protocols like HTTP, TCP name pipes
and MSMQ.
Protocol Channels
- Implements SOAP based protocol by processing and possibly
modifying message. e.g. WS-Security and WS-Reliability.
Instance Management
Instance management refers to the way a service handles a
request from a client. Instance management is set of techniques WCF uses to
bind client request to service instance, governing which service instance
handles which client request. It is necessary because application will differ
in their need for scalability, performance, durability, transaction and queued
calls.
Basically there are three instance modes in WCF:
Configuration:
Instance mode can be configured using ServiceBehavior
attribute. This can be specified at implementing the service contract as shown
below.
[ServiceContract()]
public interface IMyService
{
[OperationContract]
int MyMethod();
}
[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]
public class MyService:IMyService
{
public int MyMethod()
{
//Do something
}
}
Transfer mode
In our normal day today life, we need to transfer data from
one location to other location. If data transfer is taking place through WCF
service, message size will play major role in performance of the data transfer.
Based on the size and other condition of the data transfer, WCF supports two
modes for transferring messages
Buffer transfer
When the client and the service exchange messages, these
messages are buffered on the receiving end and delivered only once the entire
message has been received. This is true whether it is the client sending a
message to the service or the service returning a message to the client. As a
result, when the client calls the service, the service is invoked only after
the client's message has been received in its entirety; likewise, the client is
unblocked only once the returned message with the results of the invocation has
been received in its entirety.
Stream transfer
When client and Service exchange message using Streaming
transfer mode, receiver can start processing the message before it is
completely delivered. Streamed transfers can improve the scalability of a
service by eliminating the requirement for large memory buffers. If you want to
transfer large message, streaming is the best method.
StreamRequest
In this mode of configuration, message send from client to
service will be streamed
StreamRespone
In this mode of configuration, message send from service to
client will be streamed.
Configuration
<system.serviceModel>
<services >
<service behaviorConfiguration="ServiceBehavior" name="MyService">
<endpoint address="" binding="netTcpBinding"
bindingConfiguration="MyService.netTcpBinding" contract="IMyService">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding"
contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true "/>
</behavior>
</serviceBehaviors>
</behaviors>
<bindings >
<netTcpBinding>
<binding name="MyService.netTcpBinding"
transferMode="Buffered" closeTimeout ="0:01:00" openTimeout="0:01:00"></binding>
</netTcpBinding>
</bindings>
</system.serviceModel>
Differences between Buffered and Streamed Transfers
Buffered
|
Streamed
|
Target can process the message once
it is completely received.
|
Target can start processing the data
when it is partially received
|
Performance will be good when message
size is small
|
Performance will be good when message
size is larger(more than 64K)
|
Native channel shape is
IDuplexSessionChannel
|
Native channels are IRequestChannel
and IReplyChannel
|