Building Duplex WCF Services

Building Duplex WCF Services

Take advantage of the duplex message exchange pattern to send messages from the server to the connected clients in WCF.

The Windows Communication Foundation (WCF) is a Microsoft programming framework that enables developers to implement service-oriented applications. WCF supports messaging and can be used to design and implement platform-independent, scalable services. Microsoft created WCF to unify a number of enterprise technologies under one model. WCF was introduced as part of .NET Framework 3.0 and Visual Studio 2005. The latest stable version is WCF 4.5. This article takes a look at how you can program duplex services using WCF.

What are duplex WCF Services?

Generally, a service resides on the server side and they are consumed by applications on the client side ? these are also known as service consumers or service clients. When working with WCF services you can implement a two-way communication as well. Such services in WCF are known as Duplex services. Duplex services are also known as callbacks and can invoke a method on the client.

Message Exchange Patterns in WCF

There are three message exchange patterns in WCF. These include the following:

One Way– this is a message exchange pattern in which the client sends a request to the server and doesn’t need any response from the server. You should turn one way message exchange by specifying “IsOneWay = true” in the operation contract of the service. Here’s an example of a service contract that specifies one way operation in its operation contract.

[ServiceContract]    public interface ICustomers    {        [OperationContract(IsOneWay=true)]        public void DeleteCustomer(int customerID);    }

Request-response– this is the commonly used message exchange pattern used in service oriented applications that leverage WCF. In this mode of operation the service consumer sends a message to the server and then the service running at the server processes the request and sends a response. Note that you needn’t specify anything extra to provide support for this message exchange pattern as the default value of the IsOneWay property is false. The following code snippet illustrates how you can use the request-response message exchange pattern in your service operation in WCF.

[ServiceContract]    public interface ICustomers    {        [OperationContract]        public void DeleteCustomer(int customerID);    }

Duplex is a two way message exchange pattern in WCF. In this pattern the service provider and the service consumer can communicate independently of each other. In this message exchange pattern both the server and the client endpoints can send messages to each other independently. After the service client connects to the service, it provides a channel for the service running at the server to send messages back to the client.

Implementing a Duplex WCF Service

In this section we’ll explore how we can build a duplex service using WCF. The first step to build a duplex service using WCF is creating the service contract and the service callback contract and then implementing the service contract and specifying the necessary service configuration.

The following code listing shows the declaration of the duplex service and the duplex service callback interfaces.

using System.Runtime.Serialization;using System.ServiceModel;namespace Duplex{    [ServiceContract(CallbackContract = typeof(IDuplexServiceCallback))]    public interface IDuplexService    {        [OperationContract]        void MyDuplexMethod();    }    public interface IDuplexServiceCallback    {        [OperationContract]        void OnCallback();    }}

We would use wsDualHttpBinding here to provide support for duplex communication. Here’s how the service configuration file needs to be configured.

                                                                                                                        

The next step is to host the WCF you have created. You can take advantage of a console application to do this.

static void Main(string[] args)        {            var serviceHost = new ServiceHost(typeof(DuplexService));            serviceHost.Open();            Console.WriteLine("Service started ...");            Console.WriteLine("Press key to stop the service.");            Console.ReadLine();            serviceHost.Close();        }

Now that the service and the service host is ready, you can implement the client application that would typically consist of a callback class and a console application. The following is the callback class that defines the OnCallback method.

public class DuplexServiceCallback : IDuplexServiceCallback    {        public void OnCallback()        {            Console.WriteLine("Callback at {0}", DateTime.Now);        }    }

The last step is to implement the client application that makes use of the callback class we just implemented. Here’s the complete code for your reference.

using DuplexServiceClient.DuplexServiceReference;using System;using System.ServiceModel;namespace DuplexServiceClient{    public class DuplexServiceCallback : IDuplexServiceCallback    {        public void OnCallback()        {            Console.WriteLine("Callback at {0}", DateTime.Now);        }    }    class Program    {        static void Main(string[] args)        {            try            {                DuplexServiceCallback callback = new DuplexServiceCallback();                var instanceContext = new InstanceContext(callback);                var client = new DuplexServiceReference.DuplexServiceClient(instanceContext);                client.Open();            }            catch            { }            Console.ReadLine();        }    }}

And, you are done! You would now need to start the service and then the client to see the callback in action!

Summary

WCF provides you a programming model and a framework that has support for interoperable, reliable, secure communication. In essence, it provides a framework for designing and developing a service-oriented messaging system that is reliable and transacted. This article presented a discussion on duplex services and explored how we can build duplex services using WCF.

Share the Post:
XDR solutions

The Benefits of Using XDR Solutions

Cybercriminals constantly adapt their strategies, developing newer, more powerful, and intelligent ways to attack your network. Since security professionals must innovate as well, more conventional endpoint detection solutions have evolved

AI is revolutionizing fraud detection

How AI is Revolutionizing Fraud Detection

Artificial intelligence – commonly known as AI – means a form of technology with multiple uses. As a result, it has become extremely valuable to a number of businesses across

AI innovation

Companies Leading AI Innovation in 2023

Artificial intelligence (AI) has been transforming industries and revolutionizing business operations. AI’s potential to enhance efficiency and productivity has become crucial to many businesses. As we move into 2023, several

data fivetran pricing

Fivetran Pricing Explained

One of the biggest trends of the 21st century is the massive surge in analytics. Analytics is the process of utilizing data to drive future decision-making. With so much of

kubernetes logging

Kubernetes Logging: What You Need to Know

Kubernetes from Google is one of the most popular open-source and free container management solutions made to make managing and deploying applications easier. It has a solid architecture that makes

ransomware cyber attack

Why Is Ransomware Such a Major Threat?

One of the most significant cyber threats faced by modern organizations is a ransomware attack. Ransomware attacks have grown in both sophistication and frequency over the past few years, forcing

data dictionary

Tools You Need to Make a Data Dictionary

Data dictionaries are crucial for organizations of all sizes that deal with large amounts of data. they are centralized repositories of all the data in organizations, including metadata such as