You are currently viewing Azure Relay Service with WCF Relay

Azure Relay Service with WCF Relay

In last few articles, we have been seeing how relay service works. If you are new to Azure relay service, then I would strongly suggest to go through my previous blog articles. Below are the links for ready reference:

In this article, we try to create a sample application to demonstrate WCF relay.

Prerequisites

For following steps in this article, you will need access to Azure Portal. If you don’t have an Azure subscription, create a free account before you begin.

In Azure portal, I assume you already have completed below steps:

  • Create relay namespace
  • Get key name and key from Shared access policies of relay namespace

If you have not completed these prerequisites, you can refer to respective sections of my previous blog to get them done.

You can also find the sample console applications at my GitHub repository. You will need a visual studio to run this sample.

This article assumes that you have basic knowledge of WCF. You should know concepts like ServiceContract, Channels, Bindings, Endpoint Behaviors, Service Host, Behavior Extensions, etc.

Contracts Library

For this demo I have created a sample IMathService, which has two operations – Add and subtract. Each of these two operations takes two parameters and returns the result by performing simple math calculation.

This service contract is defined in a library and this library is shared between client and the service.

I have not generated proxy. I have created channel through code and used the same configuration on both service side and client side.

Below is the snippet from the code:

public interface IMathService
{
   [OperationContract]
   int Add(int first, int second);

   [OperationContract]
   int Subtract(int first, int second);
}


public interface IMathServiceChannel 
              : IMathService, IClientChannel 
{ 
};

On-Premise WCF Service

This is .Net framework console application with name – WcfListenerConsole.

This has references to System.ServiceModel and System.Runtime.Serialization assemblies.

This project also refers WindowsAzure.ServiceBase nuget package and uses behavior extensions and binding extension from that package.

The service implementation is pretty simple, the contract of Add and Subtract operation is implemented. Then there is some code to host the service.

The connectivity mode describes the protocol the service uses to communicate with the relay service either HTTP or TCP. Using the default setting AutoDetect, the service attempts to connect to Azure Relay over TCP if it is available, and HTTP if TCP is not available.

ServiceBusEnvironment.SystemConnectivity.Mode = ConnectivityMode.AutoDetect;

// Create the service host reading the configuration.
ServiceHost host = new ServiceHost(typeof(MathService));

// Open the service.
host.Open();

Console.WriteLine("Press [Enter] to exit");
Console.ReadLine();

// Close the service.
host.Close();

Below is the snippet from configuration section. You will need to replace your relay namespace name, the SAS key and the key name in the configuration settings.

<services>
   <service name="WcfListenerConsole.MathService" >
       <endpoint contract="WcfContracts.IMathService" 
           binding="netTcpRelayBinding" 
           address="sb://{namespace-name}.servicebus.windows.net/math" 
           behaviorConfiguration="sbTokenProvider" />
   </service>
</services>
    
<behaviors>
   <endpointBehaviors>
       <behavior name="sbTokenProvider">
         <serviceRegistrySettings discoveryMode="Public" />
 
         <transportClientEndpointBehavior>
           <tokenProvider>
             <sharedAccessSignature keyName="{key-name}" 
                                    key="{key}" />
            </tokenProvider>
         </transportClientEndpointBehavior>
      </behavior>
   </endpointBehaviors>
</behaviors>

WCF Client

This is again a .Net framework console application. It simply creates a channel and calls the API and prints the result. This project also refers to the WindowsAzure.ServiceBus nuget package.

Below is the C# code from client application:

ServiceBusEnvironment.SystemConnectivity.Mode = ConnectivityMode.AutoDetect;

var cf = new ChannelFactory<IMathServiceChannel>("echo");

Console.WriteLine();
Console.WriteLine("Sending Add request with parameters 4 and 5");

using (var ch = cf.CreateChannel())
{
    Console.WriteLine("Result = " + ch.Add(4, 5));
}

The client also uses same configuration as of server.

You can see clients section has one endpoint with name echo and it has URL and binding details. There is one endpoint behavior which attaches SAS Key and Key name in the request message.

<client>
    <endpoint name="math" 
       contract="WcfContracts.IMathService"
       binding="netTcpRelayBinding"
       address="sb://{namespace-name}.servicebus.windows.net/math"
       behaviorConfiguration="sbTokenProvider"/>
</client>

<behaviors>
  <endpointBehaviors>
    <behavior name="sbTokenProvider">
      <serviceRegistrySettings discoveryMode="Public" />
      <transportClientEndpointBehavior>
        <tokenProvider>
          <sharedAccessSignature keyName="{key-name}" 
                                 key="{key}" />
        </tokenProvider>
      </transportClientEndpointBehavior>
    </behavior>
  </endpointBehaviors>
</behaviors>

Running the Applications

You can either clone my GitHub repository or you can download the source code.

Then you can open the solution using Visual Studio 2019. Then you can run the WcfListenerConsole to start the service. Once service is ready, you can run client application.

Please note that even though these two applications are running on same machine, they are communicating through relay service.

I hope this article helped you to understand WCF relay using relay service. Please do comment and let me know your thoughts and experiences.

Leave a Reply Cancel reply