The Windows Communication Foundation (or WCF),
previously known as "Indigo", is a runtime and a set of APIs (application
programming interface) in the .NET
Framework for building connected, service-oriented applications.
The architecture
Endpoints
Behaviors
Migrating
ASP.NET Web Services to WCF
These standards are defined by big leaders in the industry such as Microsoft, IBM, VeriSign, SUN and many others so that they can expose their services through a common protocol. These standards includes:
1.
WS-I Profiles
2.
WS-Addressing
3.
WS-Security
4.
WS-Reliable Messaging
5.
WS-Coordination and WS-Transaction
What’s new in WCF 4.5? let’s start with WCF configuration
Improved Intellisense Support in VS2012
Intellisense in
Configuration
Improved Validations
with Configuration
New Https protocol mapping on IIS
Multiple Authentication support for single endpoint hosted on IIS
The architecture
WCF is a tool often used to implement and deploy a service-oriented architecture (SOA). It is designed using service-oriented
architecture principles to support distributed computing where services have remote consumers. Clients can consume multiple services; services can
be consumed by multiple clients. Services are loosely coupled to
each other. Services typically have a WSDL interface (Web Services Description Language) that any WCF
client can use to consume the service, regardless of which platform the service
is hosted on. WCF implements many advanced Web services (WS) standards such as WS-Addressing, WS-ReliableMessaging and WS-Security. With the release
of .NET Framework 4.0,
WCF also provides RSS Syndication Services, WS-Discovery, routing and
better support for RESTservices.
Endpoints
A WCF client connects to a WCF service via an Endpoint. Each service exposes its contract via one or more
endpoints. An endpoint has an address (which is a URL specifying where the
endpoint can be accessed) and binding properties that specify how the data will
be transferred.
The mnemonic "ABC"
can be used to remember address / binding / Contract. Binding specifies what communication protocols are used to access the service, whether security
mechanisms are to be used, and the like. WCF includes predefined bindings for
most common communication protocols such as SOAP over HTTP, SOAP over TCP, and SOAP over Message
Queues, etc. Interaction between WCF endpoint and client is done using a SOAP
envelope. SOAP envelopes are in simple XML form, which makes WCF
platform-independent. When a client wants to access the service via an
endpoint, it not only needs to know the contract, but it also has to adhere to
the binding specified by the endpoint. Thus, both client and server must have
compatible endpoints.
With the release of the .NET Framework 3.5 in November
2007, Microsoft released an encoder that added support for the JSON serialization format
to WCF. This allows WCF service
endpoints to service requests from AJAX-powered Web pages which only accept JSON
Behaviors
Behaviors are just types that modify or extend service
or client functionality. Behaviors allow the developer to create custom
processing, transformation, or inspection that is applied to messages as they
are sent or received. Some examples of uses for behaviors are:
·
Controlling
whether metadata is published with a service.
·
Adding
security features to a service, such as impersonation, authorization, or
managing tokens
·
Recording
information about messages, such as tracking, tracing, or logging
·
Message
and validation.
·
Invoking
all additional operations when messages are received--such as notifying users
when certain messages arrive
Behaviors implement the
IServiceBehavior interface for service extensions, the IEndpointBehavior for endpoints, the IContractBehavior interface for service contracts, or
theIOperationBehavior for operations. Service behaviors are
used for message processing across a service, rather than processing that would
be specific to a single operation.
Interoperability
WCF supports interoperability with WCF applications
running on the same Windows machine or WCF running on a different Windows
machines or standard Web services built on platforms such as Java running on Windows or other operating systems. In
addition to SOAP, WCF 4 supports non-SOAP XML, RSS, JSON, and binary formats for external communication via
HTTP or HTTPS.
Migrating
ASP.NET Web Services to WCF
ASP.NET provides .NET Framework
class libraries and tools for building Web services, as well as facilities for
hosting services within Internet Information Services (IIS). Windows
Communication Foundation (WCF) provides .NET Framework class libraries, tools
and hosting facilities for enabling software entities to communicate using any
protocols, including those used by Web services. Migrating ASP.NET Web Services
to WCF allows your applications to take advantage of new features and
improvements that are unique to WCF.
WCF has several important advantages
relative to ASP.NET Web services. While ASP.NET Web services tools are solely
for building Web services, WCF provides tools that can be used when software
entities must be made to communicate with one another. This will reduce the
number of technologies that developers are required to know in order to
accommodate different software communication scenarios, which in turn will
reduce the cost of software development resources, as well as the time to
complete software development projects.
Even for Web service development
projects, WCF supports more Web service protocols than ASP.NET Web services
support. These additional protocols provide for more sophisticated solutions involving,
amongst other things, reliable sessions and transactions.
Web Services: Standards and Specifications
Web
Service standards and specifications are known as "WS-*". This
represents a set of protocols and specifications. These are used to extend the
capability of web service.
These standards are defined by big leaders in the industry such as Microsoft, IBM, VeriSign, SUN and many others so that they can expose their services through a common protocol. These standards includes:
1.
WS-I Profiles
The Web Services Interoperability Organization (WS-I)
is an industry group to pro-mote interoperability across the stack of web
services specifications. It publishes web service profiles, sample
applications, and test tools for help. One of the popular profiles it has
published is the WS-I Basic Profile. WS-I is governed by a Board of Directors,
and Microsoft is one of the board members.
2.
WS-Addressing
This is a mechanism that allows web services to
communicate addressing infor-mation. With traditional web services, addressing
information is carried by the transport layer, and the web service message
itself knows nothing about its destination. With this new standard, addressing
in-formation will be included in the XML message itself. A SOAP header can be
added to the message for this purpose. The network-level transport is now
responsible only for delivering that message to a dispatcher capable of reading
the metadata.
3.
WS-Security
This describes how to handle security issues within
SOAP messages. It attaches signature and encryption information as well as
security tokens to SOAP messages. In addition to the traditional HTTP/HTTPS
authentications, it incorporates extra security features in the header of the
SOAP message, working in the application layer. Also, it ensures end-to-end
security.
There are several specifications associated with
WS-Security, such as WS-SecureConversation, WS-Federation, WS-Authorization,
WS-Policy, WS-Trust, and WS-Privacy.
4.
WS-Reliable Messaging
This describes a protocol that allows SOAP messages to
be delivered reliably between distributed applications. The
WS-ReliableMessaging model enforces reliability between the message source and
destination. If a message cannot be delivered to the destination, the model
must raise an exception or indicate to the source that the message can't be
delivered.
There are several Delivery Assurance options for
WS-ReliableMessaging, including AtLeastOnce, AtMostOnce, ExactlyOnce, and
InOrder.
5.
WS-Coordination and WS-Transaction
WS-Coordination describes an extensible framework for
providing protocols that coordinate the actions of distributed applications.
The framework enables existing transaction processing, workflow, and other
systems for coordination, to hide their proprietary protocols and to operate in
a heterogeneous environment. Additionally, this specification provides a
definition for the structure of the context and the requirements for
propagating context be-tween cooperating services.
WS-Transaction describes coordination types that are
used with the extensible coordination frame-work described in the
WS-Coordination specification. It defines two coordination types: Atomic
Trans-action (AT) for individual operations and Business Activity (BA) for
long-running transactions.
What’s new in WCF 4.5? let’s start with WCF configuration
This
week the new version of .NET was revealed at BUILD – .NET 4.5, and with it also
the new version of WCF – WCF 4.5
There
are many new features of WCF 4.5, most of them intended to make your life
easier when configuring and hosting services, and some other to support
features that we all waited for, such as UDP transport support and compressed
binary encoding.
So
what will be the first new feature to explore? Why configuration of course, the
thing that troubles all WCF developers.
Ever
had the following scenario? – you create a service, expose it through an HTTP
or a TCP endpoint without any binding configuration changes, but when you add a
service reference to it from a client application, you get a whole bunch of binding
configuration which
is basically the default
configuration.
At
first, you delete all of the extra configuration, hoping it won’t be created
again when you update the service reference (yeah, right), but after a while,
you just leave it as it is, giving up in advance.
No more! One
of the new features of WCF 4.5 is simplifying the generated configuration file
in clients. From now on, the generated configuration will only include
non-default binding configuration.
Improved Intellisense Support in VS2012
Intellisense in
Configuration
As we know, Intellisense support for code
is a major productivity boost when developing in Visual Studio. However, while
creating configuration files, Intellisense support has been ‘weak’ to say the
least. Many a times, we make mistakes in writing Service name, Binding name,
Contract name, Behavior name etc. resulting in runtime errors. With WCF 4.5,
Visual Studio 2012 provides significantly improved Intellisense support in
configuration files too. For example as we can see below we have auto
completion of Service Names.
This type of Intellisense supports easier
creation of WCF configuration.
Improved Validations
with Configuration
Validation of the configuration file is
another important feature in VS 2012. This reduces possible validation
mistakes. Any mistakes in configuration will be displayed as below:
Also the configuration errors come up in
the Tasks window as warnings:
The validation message of the
configuration file will be shown as above.
These subtle improvements in VS 2012
improves developer productivity and takes away some of the pains associated
with WCF configuration.
New Https protocol mapping on IIS
Transport security is an important factor
of WCF service. In WCF 4.0, we have been provided with default endpoint feature
which defines protocol mapping for ‘basicHttpBinding’. In WCF 4.5, if IIS is
enabled for SSL and if the service does not have any explicit endpoint defined
for the specific binding, then WCF can be hosted on IIS with default HTTPs
enabled i.e. ‘basicHttpsBinding’.
To experience the automatic Https protocol
mapping on IIS, you need to create an Application Pool with Identity as
‘LocalSystem’. This must be targeted to .NET 4.0 framework as below:
The Identity property is set to the LocalSystem as shown below:
Now we need to create a Web Site under the
application pool which will contain the WCF 4.5 service published in it:
The web site must be provided with the SSL
certificate which you need to create. The port is set to 443.
Now Open Visual Studio 2012 and create a
new WCF Service application and set a Service Name. When you browse the
service.svc, you will get the ‘basicHttpBinding’ endpoint in WSDL as shown
here:
Now publish the WCF service on IIS in the
site created above and browse the service.svc, you will find endpoints as
below:
This new feature reduces the amount of
configuration required. Although we had SSL support in previous versions of
WCF, but it was necessary to declare an explicit endpoint. Now in WCF 4.5,
using the default endpoint we can have smaller configuration.
Multiple Authentication support for single endpoint hosted on IIS
Technically, when a WCF service is to be
used by multiple client applications over a large network, then the recommended
host is IIS. IIS 7.x with Windows Process Activation Service (WAS) enables
multi-protocol support to WCF services and various client applications can make
calls to WCF service over these protocols.
To setup authentication on the WCF
service, the authentication values need to be applied in Web.config file of the
Service application and also on IIS. If there are any authentication value
mismatches between the Endpoint authentication and the IIS authentication, then
authentication mismatch error will occur.
Consider a scenario where the WCF service
is configured to use ‘basicHttpBinding’ endpoint with Security mode as
‘Transport’ and ClientCredentialType as ‘Windows’.
Improved Intellisense
Support in VS2012
Intellisense in
Configuration
As we know, Intellisense
support for code is a major productivity boost when developing in Visual
Studio. However, while creating configuration files, Intellisense support has
been ‘weak’ to say the least. Many a times, we make mistakes in writing Service
name, Binding name, Contract name, Behavior name etc. resulting in runtime
errors. With WCF 4.5, Visual Studio 2012 provides significantly improved
Intellisense support in configuration files too. For example as we can see
below we have auto completion of Service Names
i1-config-intellisense
This type of Intellisense
supports easier creation of WCF configuration.
Improved Validations with Configuration
Validation of the
configuration file is another important feature in VS 2012. This reduces
possible validation mistakes. Any mistakes in configuration will be displayed
as below:
i2-configvalidations
Also the configuration
errors come up in the Tasks window as warnings:
i3-config-validations
The validation message of
the configuration file will be shown as above.
These subtle improvements
in VS 2012 improves developer productivity and takes away some of the pains
associated with WCF configuration.
New Https protocol
mapping on IIS
Transport security is an
important factor of WCF service. In WCF 4.0, we have been provided with default
endpoint feature which defines protocol mapping for ‘basicHttpBinding’. In WCF
4.5, if IIS is enabled for SSL and if the service does not have any explicit
endpoint defined for the specific binding, then WCF can be hosted on IIS with
default HTTPs enabled i.e. ‘basicHttpsBinding’.
To experience the
automatic Https protocol mapping on IIS, you need to create an Application Pool
with Identity as ‘LocalSystem’. This must be targeted to .NET 4.0 framework as
below:
i4-apppool
The Identity property is
set to the LocalSystem as shown below:
i5-application-pool-identity
Now we need to create a
Web Site under the application pool which will contain the WCF 4.5 service
published in it:
i6-web-site
The web site must be
provided with the SSL certificate which you need to create. The port is set to
443. Now Open Visual Studio 2012 and create a new WCF Service application and
set a Service Name. When you browse the service.svc, you will get the
‘basicHttpBinding’ endpoint in WSDL as shown here:
i7-basichttpbinding
Now publish the WCF
service on IIS in the site created above and browse the service.svc, you will
find endpoints as below:
i8-autp-ssl-on-iis
This new feature reduces
the amount of configuration required. Although we had SSL support in previous
versions of WCF, but it was necessary to declare an explicit endpoint. Now in
WCF 4.5, using the default endpoint we can have smaller configuration.
Multiple Authentication
support for single endpoint hosted on IIS
Technically, when a WCF
service is to be used by multiple client applications over a large network,
then the recommended host is IIS. IIS 7.x with Windows Process Activation
Service (WAS) enables multi-protocol support to WCF services and various client
applications can make calls to WCF service over these protocols.
To setup authentication
on the WCF service, the authentication values need to be applied in Web.config
file of the Service application and also on IIS. If there are any
authentication value mismatches between the Endpoint authentication and the IIS
authentication, then authentication mismatch error will occur.
Consider a scenario where
the WCF service is configured to use ‘basicHttpBinding’ endpoint with Security
mode as ‘Transport’ and ClientCredentialType as ‘Windows’.
i9-multiple-auth
The WCF service is
published on IIS with authentication set like as the following:
i10-multiple-auth
When we try to access the
service, we will get the following error
i11-multi-auth
This happens because, the
WCF service endpoint is expecting Windows Authentication and the IIS is enabled
for anonymous authentication only. To support multiple clients for making call
to WCF service with different authentication, developer has to define multiple
endpoints for the WCF service.
The solution here is that
WCF needs be configured to have capability for inheriting the authentication
types provided by IIS. This can be achieved using the ClientCredentialType
value on the transport security set to ‘InheritedFromHost’. Now the
configuration of the endpoint will be as below:
i12-multi-auth-config
The ‘InheritedFromHost’
value for the ClientCredentialType is newly introduced in WCF 4.5. This
configures, the single endpoint WCF service hosted on IIS to use the
authentication types defined on IIS. Now the IIS authentication can be as
below:
i13-multi-auth-iis
Now if you browse the
service.svc, you will be able to get the WSDL. (Note: The endpoint uses
Transport security, so for publishing on IIS 7.x, you need to have Web site
enable for SSL.) The client application can have various ClientCredentialType
values e.g.
i14-multi-auth-client
Here the client
applications need not pass of any credential information to WCF service,
because IIS has authentication type set to Anonymous as enabled. The response
from the WCF service, will be successfully delivered to client if the value of
the ClientCredentialType is set to Windows as below:
i15-multi-auth-client-windows
In this case also, the
response will be successfully delivered to client, because the Service on IIS
has set the Windows Authentication as Enabled if the client application set the
ClientCredentialType to ‘Basic’ as below:
i16-amuti-auth-client-basic
This mandates that the
client application should send the credentials to WCF service for successful
communication otherwise the following exception will be displayed:
i17-multi-auth-basic-exception
So to ensure successful
communication between client and the WCF service the credentials are passed as
below:
i18-multi-auth-credentials
The advantage of this
feature is that, for single endpoint WCF service hosted on IIS with multiple
authentication type set, multiple client applications with different
credentials can communicate with WCF service successfully and hence developer
is free from providing several endpoints making WCF service less complex and
more manageable.
Support for UDP Endpoint
One of the most
attractive and beneficial features of WCF 4.5 is the out-of-box support for UDP
protocol. We have been provided with ‘udpBinding’. In some cases the UDP is
proven far better than TCP and HTTPS which are the most popular protocols.
Typically TCP is used in the non-time critical (may be non-real-time)
applications but UDP is very useful for real-time applications e.g. Games or
the applications which requires fast data communication. Since TCP performs
data-packets checking for the order of the message to be send, it is slower
than UDP. In UDP, packet delivery is not guaranteed
and loss or
out-of-arrival of packets is acceptable. Thus it is faster that TCP.
Using TCP vs. UDP
Let us setup a simple
comparison between the TCP and UDP binding for database communication.
For this example a SQL
Server Database is used with following table design:
i19-table-design
Task 1: Open VS2012 and
create a blank solution, name it as ‘WCF45_UDP_Comparision’. In this solution, add
a new WCF Service application; name it as ‘WCF45_UPD_Binding_Service’. Rename,
IService1.cs to IService.cs and Service1.svc to Service.svc. Add the below
methods in the IService interface:
using
System.Runtime.Serialization;
using
System.ServiceModel;
namespace
WCF45_UPD_Binding_Service
{
[ServiceContract]
public interface IService
{
[OperationContract(IsOneWay=true)]
void PostMessages(MessagePost message);
}
[DataContract]
public class MessagePost
{
[DataMember]
public string MessageDetails { get; set; }
}
}
_____________________________________________________________________________
Task 2: Implement the
IService interface in the service class as below:
using
System.Data.SqlClient;
namespace
WCF45_UPD_Binding_Service
{
public class Service :
IService
{
SqlConnection Conn;
SqlCommand Cmd;
public Service()
{
Conn = new SqlConnection("Data
Source=.;Initial Catalog=Company;Integrated Security=SSPI");
}
public void
PostMessages(MessagePost message)
{
Conn.Open();
Cmd = new SqlCommand();
Cmd.Connection = Conn;
Cmd.CommandText = "Insert into
MessagePost Values(@PostDetails)";
Cmd.Parameters.AddWithValue("@PostDetails",message.MessageDetails);
Cmd.ExecuteNonQuery();
Conn.Close();
}
}
}
The fact about the UDP
binding is that it is not supported by IIS/WAS because there is no UDP shared
listener available on this host, so we need to host via a managed Exe (.NET
application). Also one important thing to note is the service contract defines
one-way message i.e. Fire and forget which is the most suitable mechanism for
UDP based Communication. Other important facts about the UDP Binding are:
The binding is supported
only for .NET client applications. SOAP-based service messaging is not
supported.
No support for transport
or message security is available.
Only text encoding is
supported.
Task 3: In the solution
created, add a new Console Application and add the App.Config file with the
below configuration:
______________________________________________________________________________
binding="basicHttpBinding"
contract="WCF45_UPD_Binding_Service.IService">
binding="netTcpBinding"
contract="WCF45_UPD_Binding_Service.IService">
binding="udpBinding"
contract="WCF45_UPD_Binding_Service.IService">
Note that, in the above
configuration, 3 endpoints HTTP, Tcp and UDP are defined for comparison. Note
that, the address schema defined for the UDP endpoint is “soap.udp”.
Following is the code for
hosting in Program class:
class Program
{
static void Main(string[] args)
{
ServiceHost Host = new
ServiceHost(typeof(WCF45_UPD_Binding_Service.Service));
Host.Open();
Console.WriteLine("Service
Started...");
Console.ReadLine();
Host.Close();
Console.ReadLine();
}
}
Task 4: Add the service
reference of the above WCF service in Windows application by adding Windows
application in the solution created above, name it as
‘WCF45_UDP_Comparision_Client’. The reference will be added using the following
URI 'http://localhost:3400/MyServ'. In the App.Config file of the client
application, you will get 3 endpoints, one each for Tcp, Udp and Http.
Task 5: Design the
WinFrom as below:
i20-form-design
Task 6: Write the
following code in the Form Code behind:
using System;
using System.Diagnostics;
using
System.Windows.Forms;
namespace
WCF45_UDP_Comparision_Client
{
public partial class
Form1 : Form
{
#region
Class Level Declaration
string Protocol = string.Empty;
MyRef.ServiceClient Proxy;
#endregion
public Form1()
{
InitializeComponent();
}
#region Radio Button Events
private void rdTcp_CheckedChanged(object
sender, EventArgs e)
{
Protocol = "Tcp";
}
private void rdHttp_CheckedChanged(object
sender, EventArgs e)
{
Protocol = "Http";
}
private void rdUdp_CheckedChanged(object
sender, EventArgs e)
{
Protocol = "Udp";
}
#endregion
///
/// Method for Posting Messages to Database
///
///
///
private void button1_Click(object sender,
EventArgs e)
{
try
{
if (Protocol == string.Empty)
{
MessageBox.Show("Please
select the Protocol");
}
else
{
switch (Protocol)
{
case "Tcp":
Proxy = new
MyRef.ServiceClient("NetTcpBinding_IService");
break;
case "Http":
Proxy = new
MyRef.ServiceClient("BasicHttpBinding_IService");
break;
case "Udp":
Proxy = new
MyRef.ServiceClient("UdpBinding_IService");
break;
}
}
Stopwatch stopWatch = new
Stopwatch();
stopWatch.Start();
for (int i = 0; i < 2000; i++)
{
MyRef.MessagePost msg = new
MyRef.MessagePost()
{
MessageDetails = "My
Message Post No" + i.ToString() + "with Protocol " + Protocol
};
Proxy.PostMessages(msg);
}
stopWatch.Stop();
if (Protocol == "Tcp")
{
lblTcpTime.Text +=
stopWatch.ElapsedMilliseconds;
}
if (Protocol == "Http")
{
lblHttpTime.Text +=
stopWatch.ElapsedMilliseconds;
}
if (Protocol == "Udp")
{
lblUdpTime.Text +=
stopWatch.ElapsedMilliseconds;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
The Button click event
will make call to ‘PostMessage()’ method of the WCF service based upon the
Protocol selected from the Radio Button on the UI.
Task 7: To test the
comparison, run the Host Application and run the Client application in multiple
instances:
i21-udp-host
Run the client
application, and select various Protocols e.g. UDP, TCP and Http and click on
the ‘Post Message’ button, the result will be shown as below:
i22-udp-client
It is clearly shown that
for 2000 Database Insert transactions, UDP takes only 165 Milliseconds whereas
TCP takes 669 and HTTP takes 1806 milliseconds. Hence it is proven that UDP is
faster for performance as compare other protocols.
One more feature worth
mentioning is support for WebSockets using NetHttpBinding.
NetHttpBinding and
NetHttpsBinding
This is provided for
WebSocket programming. WebSocket is the new protocol for bidirectional communication
over port 80 and 443. This has provided enhanced performance like TCP protocol.
Typically we can make use of this for Duplex communication with WCF 4.5.
The WCF service is published on IIS with
authentication set like as the following:
When we try to access the service, we will
get the following error
This happens because, the WCF service
endpoint is expecting Windows Authentication and the IIS is enabled for
anonymous authentication only. To support multiple clients for making call to
WCF service with different authentication, developer has to define multiple
endpoints for the WCF service.
The solution here is that WCF needs be
configured to have capability for inheriting the authentication types provided
by IIS. This can be achieved using the ClientCredentialType value on the
transport security set to ‘InheritedFromHost’. Now the configuration of the
endpoint will be as below:
The ‘InheritedFromHost’ value for the
ClientCredentialType is newly introduced in WCF 4.5. This configures, the single
endpoint WCF service hosted on IIS to use the authentication types defined on
IIS. Now the IIS authentication can be as below:
Now if you browse the service.svc, you
will be able to get the WSDL. (Note: The endpoint uses Transport security, so
for publishing on IIS 7.x, you need to have Web site enable for SSL.) The
client application can have various ClientCredentialType values e.g.
Here the client applications need not pass
of any credential information to WCF service, because IIS has authentication
type set to Anonymous as enabled. The response from the WCF service, will be
successfully delivered to client if the value of the ClientCredentialType is
set to Windows as below:
In this case also, the response will be
successfully delivered to client, because the Service on IIS has set the
Windows Authentication as Enabled if the client application set the
ClientCredentialType to ‘Basic’ as below:
This mandates that the client application
should send the credentials to WCF service for successful communication
otherwise the following exception will be displayed:
So to ensure successful communication
between client and the WCF service the credentials are passed as below:
The advantage of this feature is that, for
single endpoint WCF service hosted on IIS with multiple authentication type
set, multiple client applications with different credentials can communicate
with WCF service successfully and hence developer is free from providing
several endpoints making WCF service less complex and more manageable.
Support for UDP Endpoint
One of the most
attractive and beneficial features of WCF 4.5 is the out-of-box support for UDP
protocol. We have been provided with ‘udpBinding’. In some cases the UDP is
proven far better than TCP and HTTPS which are the most popular protocols.
Typically TCP is used in the non-time critical (may be non-real-time)
applications but UDP is very useful for real-time applications e.g. Games or
the applications which requires fast data communication. Since TCP performs
data-packets checking for the order of the message to be send, it is
slower than UDP. In UDP, packet delivery is not guaranteed
and loss or out-of-arrival of packets is acceptable. Thus it is faster that TCP.
and loss or out-of-arrival of packets is acceptable. Thus it is faster that TCP.
Using TCP vs. UDP
Let us setup a simple comparison between
the TCP and UDP binding for database communication.
For this example a SQL Server
Database is used with following table design:
Task 1: Open VS2012 and create a blank solution, name it as
‘WCF45_UDP_Comparision’. In this solution, add a new WCF Service application;
name it as ‘WCF45_UPD_Binding_Service’. Rename, IService1.cs to IService.cs and
Service1.svc to Service.svc. Add the below methods in the IService interface:
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel;
namespace WCF45_UPD_Binding_Service
{
[ServiceContract]
public interface IService
{
[OperationContract(IsOneWay=true)]
void PostMessages(MessagePost message);
}
{
[ServiceContract]
public interface IService
{
[OperationContract(IsOneWay=true)]
void PostMessages(MessagePost message);
}
[DataContract]
public class MessagePost
{
[DataMember]
public string MessageDetails { get; set; }
}
}
public class MessagePost
{
[DataMember]
public string MessageDetails { get; set; }
}
}
Task 2: Implement the IService interface in the service class as
below:
using System.Data.SqlClient;
namespace WCF45_UPD_Binding_Service
{
public class Service : IService
{
SqlConnection Conn;
SqlCommand Cmd;
public Service()
{
Conn = new SqlConnection("Data Source=.;Initial Catalog=Company;Integrated Security=SSPI");
}
{
public class Service : IService
{
SqlConnection Conn;
SqlCommand Cmd;
public Service()
{
Conn = new SqlConnection("Data Source=.;Initial Catalog=Company;Integrated Security=SSPI");
}
public void PostMessages(MessagePost message)
{
Conn.Open();
Cmd = new SqlCommand();
Cmd.Connection = Conn;
Cmd.CommandText = "Insert into MessagePost Values(@PostDetails)";
Cmd.Parameters.AddWithValue("@PostDetails",message.MessageDetails);
Cmd.ExecuteNonQuery();
Conn.Close();
}
}
}
The fact about the
UDP binding is that it is not supported by IIS/WAS because there is no UDP shared
listener available on this host, so we need to host via a managed Exe
(.NET application). Also one important thing to note is the service contract
defines one-way message i.e. Fire and forget which is the most suitable
mechanism for UDP based Communication. Other important facts about the UDP
Binding are:
·
The binding is supported only for .NET client applications.
SOAP-based service messaging is not supported.
·
No support for transport or message security is available.
·
Only text encoding is supported.
Task 3: In the solution created, add a new Console Application and
add the App.Config file with the below configuration:
binding="basicHttpBinding"
contract="WCF45_UPD_Binding_Service.IService">
contract="WCF45_UPD_Binding_Service.IService">
contract="WCF45_UPD_Binding_Service.IService">
Note that, in the above configuration, 3
endpoints HTTP, Tcp and UDP are defined for comparison. Note that, the address
schema defined for the UDP endpoint is “soap.udp”.
Following is the code for hosting in
Program class:
class Program
{
static void Main(string[] args)
{
ServiceHost Host = new ServiceHost(typeof(WCF45_UPD_Binding_Service.Service));
Host.Open();
Console.WriteLine("Service Started...");
Console.ReadLine();
Host.Close();
Console.ReadLine();
{
static void Main(string[] args)
{
ServiceHost Host = new ServiceHost(typeof(WCF45_UPD_Binding_Service.Service));
Host.Open();
Console.WriteLine("Service Started...");
Console.ReadLine();
Host.Close();
Console.ReadLine();
}
}
}
Task 4: Add the service reference of the above WCF service in
Windows application by adding Windows application in the solution created
above, name it as ‘WCF45_UDP_Comparision_Client’. The reference will be added
using the following URI 'http://localhost:3400/MyServ'. In the App.Config file
of the client application, you will get 3 endpoints, one each for Tcp, Udp and
Http.
Task 5: Design the WinFrom as below:
Task 6: Write the following code in the Form Code behind:
using System;
using System.Diagnostics;
using System.Windows.Forms;
using System.Diagnostics;
using System.Windows.Forms;
namespace WCF45_UDP_Comparision_Client
{
public partial class Form1 : Form
{
{
public partial class Form1 : Form
{
#region Class
Level Declaration
string Protocol = string.Empty;
MyRef.ServiceClient Proxy;
#endregion
public Form1()
{
InitializeComponent();
}
string Protocol = string.Empty;
MyRef.ServiceClient Proxy;
#endregion
public Form1()
{
InitializeComponent();
}
#region Radio Button
Events
private void rdTcp_CheckedChanged(object sender, EventArgs e)
{
Protocol = "Tcp";
}
private void rdTcp_CheckedChanged(object sender, EventArgs e)
{
Protocol = "Tcp";
}
private void
rdHttp_CheckedChanged(object sender, EventArgs e)
{
Protocol = "Http";
}
{
Protocol = "Http";
}
private void
rdUdp_CheckedChanged(object sender, EventArgs e)
{
Protocol = "Udp";
}
#endregion
{
Protocol = "Udp";
}
#endregion
///
/// Method for Posting Messages to Database
///
///
///
private void button1_Click(object sender, EventArgs e)
{
try
{
if (Protocol == string.Empty)
{
MessageBox.Show("Please select the Protocol");
}
else
{
switch (Protocol)
{
case "Tcp":
Proxy = new MyRef.ServiceClient("NetTcpBinding_IService");
break;
case "Http":
Proxy = new MyRef.ServiceClient("BasicHttpBinding_IService");
break;
case "Udp":
Proxy = new MyRef.ServiceClient("UdpBinding_IService");
break;
}
}
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
for (int i = 0; i < 2000; i++)
{
MyRef.MessagePost msg = new MyRef.MessagePost()
{
MessageDetails = "My Message Post No" + i.ToString() + "with Protocol " + Protocol
};
Proxy.PostMessages(msg);
}
stopWatch.Stop();
if (Protocol == "Tcp")
{
lblTcpTime.Text += stopWatch.ElapsedMilliseconds;
}
if (Protocol == "Http")
{
lblHttpTime.Text += stopWatch.ElapsedMilliseconds;
}
if (Protocol == "Udp")
{
lblUdpTime.Text += stopWatch.ElapsedMilliseconds;
}
/// Method for Posting Messages to Database
///
///
///
private void button1_Click(object sender, EventArgs e)
{
try
{
if (Protocol == string.Empty)
{
MessageBox.Show("Please select the Protocol");
}
else
{
switch (Protocol)
{
case "Tcp":
Proxy = new MyRef.ServiceClient("NetTcpBinding_IService");
break;
case "Http":
Proxy = new MyRef.ServiceClient("BasicHttpBinding_IService");
break;
case "Udp":
Proxy = new MyRef.ServiceClient("UdpBinding_IService");
break;
}
}
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
for (int i = 0; i < 2000; i++)
{
MyRef.MessagePost msg = new MyRef.MessagePost()
{
MessageDetails = "My Message Post No" + i.ToString() + "with Protocol " + Protocol
};
Proxy.PostMessages(msg);
}
stopWatch.Stop();
if (Protocol == "Tcp")
{
lblTcpTime.Text += stopWatch.ElapsedMilliseconds;
}
if (Protocol == "Http")
{
lblHttpTime.Text += stopWatch.ElapsedMilliseconds;
}
if (Protocol == "Udp")
{
lblUdpTime.Text += stopWatch.ElapsedMilliseconds;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
The Button click event will make call to
‘PostMessage()’ method of the WCF service based upon the Protocol selected from
the Radio Button on the UI.
Task 7: To test the comparison, run the Host Application and run
the Client application in multiple instances:
Run the client application, and select
various Protocols e.g. UDP, TCP and Http and click on the ‘Post Message’
button, the result will be shown as below:
It is clearly shown that for 2000 Database
Insert transactions, UDP takes only 165 Milliseconds whereas TCP takes 669 and
HTTP takes 1806 milliseconds. Hence it is proven that UDP is faster for
performance as compare other protocols.
One more feature worth mentioning is
support for WebSockets using NetHttpBinding.
NetHttpBinding and NetHttpsBinding
This is provided for WebSocket
programming. WebSocket is the new protocol for bidirectional communication over
port 80 and 443. This has provided enhanced performance like TCP protocol.
Typically we can make use of this for Duplex communication with WCF 4.5.
_____________________________________________________________________________
Reach us At: - 0120-4029000; 0120-4029024; 0120-4029025,
0120-4029027; 0120-4029029
Mbl: 9953584548





















I appreciate your blog ,Very Nice
ReplyDelete.Net Online Trining Hyderabad