Praveen Katiyar' Blog

Learning along the way . . . .

Understanding Operations in WCF

WCF supports 3 ways for a client to call a service.

  1. Request Reply : default way of invocation, the client would issue a call, block while the call was in progress, and would continue executing once the method returned. If service doesn’t respond to the service within receiveTimeout, client will receive TimeOutException.
  2. One way calls: fire and forget type operations. that simply means client will send a request to the server and does not care whether service execution was a success or failure. There is no return value from the server side. Client will be blocked only for a moment till it dispatches its call to service. Client can continue to execute its statement, after making one-way call to the service. sometime calls are queued at the server side to be dispatched one at a time. if the number of queued messages has exceeded the queue’s capacity, client will be blocked for the moment till the message is being queued. and as soon as the call is queued, the client will be unblocked and can continue executing, while the service processes the operation in the background.
  3. Call back Operation: WCF Supports allowing a service to call back to its clients. They are specially useful, for notifying client(s) that something happened on the service side. call backs are also commonly referred as duplex operations. not all binding types support call back operations. for example HTTP (for obvious reasons of being a connectionless nature). only two commonly used binding that offer call backs are NetTcpBinding and NetNamedBinding. to offer call backs over HTTP, WCF offers the WSDualHttpBinding, which actually sets up two WS channels. 

Now to see all these things in action let’s create a service.

Creating the Class Library

let’s create a service, create a new project, take a Class Library template, name it OperationLib, let’s do some house keeping with the newly created project.

  • Delete the file Class1.cs from the project workspace.
  • Add a new Interface named IRequestReplyService to the project, a new file IRequestReplyService.cs will be added to the project. 5t6
  • Add a new Class named RequestReplyService, to the project. that will implement the IRequestReplyService interface, a new file RequestReplyService.cs will be added to the project.
  • Add a new Interface named IOneWayCallService to the project, a new file IOneWayCallService.cs will be added to the project.
  • Add a new Class named OneWayCallService, to the project. that will implement the IOneWayCallService interface, a new file OneWayCallService.cs will be added to the project.
  • Add a new Interface named IDuplexService to the project, a new file IDuplexService.cs will be added to the project.
  • Add a new Class named DuplexService, to the project. that will implement the IDuplexService interface, a new file DuplexService.cs will be added to the project.

to keep the things simple, let’s assume that each interface defines only one method, which simply adds a passed value, to  its member variable.

Defining Interfaces

so let’s define interface for each service.

// Listing of IRequestReplyService.cs

using System;
using System.Text;
using System.ServiceModel;

namespace OperationLib
{
    [ServiceContract]
    interface IRequestReplyService
    {
        [OperationContract]
        double AddValue(double dblNum1, double dblNum2);
    }
}


// Listing of RequestReplyService.cs

using System;
using System.Text;

namespace OperationLib
{
    public class RequestReplyService : IRequestReplyService
    {
        public double AddValue(double dblNum1, double dblNum2)
        {
            return (dblNum1 + dblNum2);
        }
    }
}

// Listing of IOneWayCallService.cs

using System;
using System.ServiceModel;
using System.Text;

namespace OperationLib
{
[ServiceContract(SessionMode = SessionMode.Required)]
   interface IOneWayCallService
   {
        [OperationContract(IsOneWay = true)]
        void AddValue(double dblNum );

        [OperationContract]
        double GetResult();
    }

}


// Listing of OneWayCallService.cs

public class OneWayCallService : IOneWayCallService
    {
        private double m_dblResult = 0;

        public void AddValue(double dblVal)
        {
            m_dblResult += dblVal;
        }

        public double GetResult()
        {
            return m_dblResult;
        }
    }

// Listing of IDuplexService.cs

using System;
using System.ServiceModel;
using System.Text;

namespace OperationLib
{
    interface IDuplexServiceCallback
    {
        [OperationContract]
        void OnValueAdded(double dblNum1, double dblNum2, double dblResult);
    }

    [ServiceContract(CallbackContract = typeof(IDuplexServiceCallback))]
    interface IDuplexService
    {
        [OperationContract()]
        void AddValue(double dblNum1, double dblNum2);
    }
}


// Listing of DuplexService.cs

using System;
using System.ServiceModel ;
using System.Text;

namespace OperationLib
{
    public class DuplexService : IDuplexService
    {
        public void AddValue(double dblNum1, double dblNum2)
        {
            double dblResult = dblNum1 + dblNum2;
            IDuplexServiceCallback callbackInstance = OperationContext.Current.GetCallbackChannel<IDuplexServiceCallback>();
            callbackInstance.OnValueAdded(dblNum1, dblNum2, dblResult);
        }
    }
}

Now to see all these things in action let’s create a service.

Hosting the Service

for the sake of simplicity, i have have hosted this service as a self hosted service, to create the Host application, create a new Console based application.

Before we write any code for the Host application, let’s define the configuration file for the Service(s).

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.serviceModel>
    <services>
     
    

<!–************************* Request Reply Service **************************** –>
      <service name="OperationLib.RequestReplyService" behaviorConfiguration="RequestReplyServiceBehavior">
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:9011/RequestReplyService"/&gt;
            <add baseAddress="net.tcp://localhost:9012/RequestReplyService"/>
          </baseAddresses>
        </host>
       
        <endpoint address="http://localhost:9011/RequestReplyService" binding="wsHttpBinding" contract="OperationLib.IRequestReplyService"/>
        <endpoint address="net.tcp://localhost:9012/RequestReplyService" binding="netTcpBinding" contract="OperationLib.IRequestReplyService"/>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
        <endpoint address="mex" binding="mexTcpBinding" contract="IMetadataExchange"/>
      </service>

      <!—******************** OnewayCall Service ************************* –>

<service name="OperationLib.OneWayCallService" behaviorConfiguration="OneWayCallServiceBehavior">
       <host>
         <baseAddresses>
           <add baseAddress="http://localhost:9013/OneWayCallService"/&gt;
           <add baseAddress="net.tcp://localhost:9014/OneWayCallService"/>
         </baseAddresses>
       </host>

       <endpoint address="http://localhost:9013/OneWayCallService" binding="wsHttpBinding" contract="OperationLib.IOneWayCallService"/>
       <endpoint address="net.tcp://localhost:9014/OneWayCallService" binding="netTcpBinding" contract="OperationLib.IOneWayCallService"/>
       <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
       <endpoint address="mex" binding="mexTcpBinding" contract="IMetadataExchange"/>
     </service>

     <!—********************* Duplex Service ***************************** –>

<service name="OperationLib.DuplexService" behaviorConfiguration="DuplexServiceBehavior" >
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:9015/DuplexService"/&gt;
            <add baseAddress="net.tcp://localhost:9016/DuplexService"/>
          </baseAddresses>
        </host>

        <endpoint address="http://localhost:9015/DuplexService" binding="wsDualHttpBinding" contract="OperationLib.IDuplexService"/>
        <endpoint address="net.tcp://localhost:9016/DuplexService" binding="netTcpBinding" contract="OperationLib.IDuplexService"/>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
        <endpoint address="mex" binding="mexTcpBinding" contract="IMetadataExchange"/>
      </service>

</services>

    <!– ********************************** behaviors ********************************** –>
   

<behaviors>
     <serviceBehaviors>

       <!– Single Call Service Behavior –>
       <behavior name="RequestReplyServiceBehavior">
         <serviceMetadata httpGetEnabled="true"/>
         <serviceDebug includeExceptionDetailInFaults="true "/>
       </behavior>

       <!–Single Session Service Behavior –>
       <behavior name="OneWayCallServiceBehavior">
         <serviceMetadata httpGetEnabled="true"/>
         <serviceDebug includeExceptionDetailInFaults="true "/>
       </behavior>

       <!–Singleton Service Behavior –>
       <behavior name="DuplexServiceBehavior" >
         <serviceMetadata httpGetEnabled="true"  />
         <serviceDebug includeExceptionDetailInFaults="true "/>
       </behavior>
      
     </serviceBehaviors>
   </behaviors>

   
  </system.serviceModel>
</configuration>

Now let’s explain the configuration of each service.

 

<service name="OperationLib.RequestReplyService" behaviorConfiguration="RequestReplyServiceBehavior">
        <host>
          <baseAddresses>
           <add baseAddress="http://localhost:9011/RequestReplyService"/>
            <add baseAddress="net.tcp://localhost:9012/RequestReplyService"/>
          </baseAddresses>
        </host>
       
        <endpoint address="http://localhost:9011/RequestReplyService&quot; binding="wsHttpBinding" contract="OperationLib.IRequestReplyService"/>
        <endpoint address="net.tcp://localhost:9012/RequestReplyService" binding="netTcpBinding" contract="OperationLib.IRequestReplyService"/>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
        <endpoint address="mex" binding="mexTcpBinding" contract="IMetadataExchange"/>
      </service>

Explanation:

>> to do

      <!– ******************** Single Session Service ************************* –>
      <service name="OperationLib.OneWayCallService" behaviorConfiguration="OneWayCallServiceBehavior">
        <host>
          <baseAddresses>
           <add baseAddress="http://localhost:9013/OneWayCallService"/&gt;
            <add baseAddress="net.tcp://localhost:9014/OneWayCallService"/>

          </baseAddresses>
        </host>

        <endpoint address="http://localhost:9013/OneWayCallService" binding="wsHttpBinding" contract="OperationLib.IOneWayCallService"/>
        <endpoint address="net.tcp://localhost:9014/OneWayCallService" binding="netTcpBinding" contract="OperationLib.IOneWayCallService"/>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
        <endpoint address="mex" binding="mexTcpBinding" contract="IMetadataExchange"/>
      </service>

Explanation:

>> to do

<!– ********************* Singleton Service ***************************** –>
      <service name="OperationLib.DuplexService" behaviorConfiguration="DuplexServiceBehavior">
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:9015/DuplexService"/&gt;
            <add baseAddress="net.tcp://localhost:9016/DuplexService"/>
          </baseAddresses>
        </host>

        <endpoint address="http://localhost:9015/DuplexService&quot; binding="wsDualHttpBinding" contract="OperationLib.IDuplexService"/>
        <endpoint address="net.tcp://localhost:9016/DuplexService" binding="netTcpBinding" contract="OperationLib.IDuplexService"/>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
        <endpoint address="mex" binding="mexTcpBinding" contract="IMetadataExchange"/>
      </service>

Explanation:

Now to see all these things in action let’s create a service.
    

Writing code to host the service.

// Listing of Program.cs

using System;
using System.Text;
using System.ServiceModel;

namespace OperationLibHost
{
    class Program
    {
        static void Main(string[] args)
        {
            ServiceHost m_RequestReplyHost = null;
            ServiceHost m_OneWayCallHost = null;
            ServiceHost m_DuplexServiceHost = null;

            Console.WriteLine("\nHosting RequestReplyService at >> ");
            Console.WriteLine("    http://localhost:9011/RequestReplyService&quot;);
            Console.WriteLine("    net.tcp://localhost:9012/RequestReplyService");

            try
            {
                m_RequestReplyHost = new ServiceHost(typeof(OperationLib.RequestReplyService));
                m_RequestReplyHost.Open();
            }
            catch (Exception eX)
            {
                Console.WriteLine("Failed while starting RequestReplyService [" + eX.Message + "]");
                m_RequestReplyHost = null;
            }

            if (m_RequestReplyHost != null) Console.WriteLine("RequestReplyService hosted successfully . . .");

            Console.WriteLine("\nHosting OneWayCallService at >> ");
            Console.WriteLine("   
http://localhost:9013/OneWayCallService");
            Console.WriteLine("    net.tcp://localhost:9014/OneWayCallService");
            try
            {
                m_OneWayCallHost = new ServiceHost(typeof(OperationLib.OneWayCallService));
                m_OneWayCallHost.Open();
            }
            catch (Exception eX)
            {
                Console.WriteLine("Failed while starting OneWayCallService [" + eX.Message + "]");
                m_OneWayCallHost = null;
            }

            if (m_OneWayCallHost != null) Console.WriteLine("OneWayCallService hosted successfully . . .");

            Console.WriteLine("\nHosting DuplexService  at >> ");
            Console.WriteLine("   
http://localhost:9015/DuplexService");
            Console.WriteLine("    net.tcp://localhost:9016/DuplexService");

            try
            {
                m_DuplexServiceHost = new ServiceHost(typeof(OperationLib.DuplexService ));
                m_DuplexServiceHost.Open();
            }
            catch (Exception eX)
            {
                Console.WriteLine("Failed while starting Service [" + eX.Message + "]");
                m_DuplexServiceHost = null;
            }
            if (m_DuplexServiceHost != null) Console.WriteLine("DuplexService hosted successfully . . .");

            Console.WriteLine("\n\nPress any key to close . . .");
            Console.ReadKey();

            m_RequestReplyHost.Close();
            m_OneWayCallHost.Close();
            m_DuplexServiceHost.Close();

            m_RequestReplyHost = null;
            m_OneWayCallHost = null;
            m_DuplexServiceHost = null;
        }
    }
}

Explanation:

Now to see all these things in action let’s create a service.

Build and Execute the host application.

Open a command prompt and execute the host. here is the output.

image

Now when the service is hosted and running, let’s now create a client, which is actually going to use this service.

Creating Client

Creating the base project

Take a console based application.

Generating proxies

while the host application is running, right click on the client application project, click on

Generate Proxy for RequestReplyService.

References –> Add Service Reference

in the address bar type the address of the mex endpoint address of RequestReplyService as shown below.

image

Generate Proxy for OneWayCallService.

References –> Add Service Reference

in the address bar type the address of the mex endpoint address of OneWayCallService as shown below.

image

Generate Proxy for DuplexService.

References –> Add Service Reference

in the address bar type the address of the mex endpoint address of DuplexService as shown below.

image

Adding Callback implementation to the client.

Add a new Class to the Client Project, name it DuplexServiceCallbackSink, below is the listing.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace OperationClient
{
    class DuplexServiceCallbackSink : DuplexServiceReference.IDuplexServiceCallback
    {
        public void OnValueAdded(double dblNum1, double dblNum2, double dblResult)
        {
            Console.WriteLine("\n\n>> Duplex Service <<CallBack>> called in Client >> Value 1 : {0:F2} Value 2 : {1:F2} Result : {2:F2}", dblNum1, dblNum2, dblResult);
        }
    }
}

Calling Services

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;

namespace OperationClient
{
    class Program
    {
        static void Main(string[] args)
        {
            double dblVal1 = 100; double dblVal2 = 200;

            try
            {
                RequestReplyServiceReference.RequestReplyServiceClient obj1 = new RequestReplyServiceReference.RequestReplyServiceClient("WSHttpBinding_IRequestReplyService");
                RequestReplyServiceReference.RequestReplyServiceClient obj2 = new RequestReplyServiceReference.RequestReplyServiceClient("NetTcpBinding_IRequestReplyService");

                Console.WriteLine("Calling Request Reply Service");

                double dblResult1 = obj1.AddValue(dblVal1, dblVal2);
                Console.WriteLine("Using HTTP Binding >> Value 1: {0:F2} Value 2: {1:F2}  Returns : {2:F2}", dblVal1, dblVal2, dblResult1);

                dblVal1 = 100; dblVal2 = 200;
                double dblResult2 = obj2.AddValue(dblVal1, dblVal2);
                Console.WriteLine("Using TCP Binding >> Value 1: {0:F2} Value 2: {1:F2}  Return : {2:F2}", dblVal1, dblVal2, dblResult2);
            }
            catch (Exception eX)
            {
                Console.WriteLine("Error while calling Request Reply Service [ " + eX.Message + "]");
            }
           
            try
            {
                OneWayCallServiceReference.OneWayCallServiceClient obj3 = new OneWayCallServiceReference.OneWayCallServiceClient("WSHttpBinding_IOneWayCallService");
                OneWayCallServiceReference.OneWayCallServiceClient obj4 = new OneWayCallServiceReference.OneWayCallServiceClient("NetTcpBinding_IOneWayCallService");

                Console.WriteLine("Calling OneWayCall Service");

                obj3.AddValue(dblVal1);
                obj3.AddValue(dblVal2);
                double dblResult3 = obj3.GetResult();
                Console.WriteLine("Using HTTP Binding >> Value 1: {0:F2} Value 2: {1:F2}", dblVal1, dblVal2 );
                Console.WriteLine("Result : {0:F2}", dblResult3);

                obj4.AddValue(dblVal1);
                obj4.AddValue(dblVal2);
                double dblResult4 = obj4.GetResult();
                Console.WriteLine("Using TCP Binding >> Value 1: {0:F2} Value 2: {1:F2}", dblVal1, dblVal2);
                Console.WriteLine("Result : {0:F2}", dblResult4);
            }
            catch (Exception eX)
            {
                Console.WriteLine("Error while calling One way Service [ " + eX.Message + "]");
            }

            try
            {
                DuplexServiceCallbackSink callback = new DuplexServiceCallbackSink();
                InstanceContext insCntxt = new InstanceContext(callback);

                DuplexServiceReference.DuplexServiceClient obj5 = new DuplexServiceReference.DuplexServiceClient(insCntxt, "WSDualHttpBinding_IDuplexService");
                DuplexServiceReference.DuplexServiceClient obj6 = new DuplexServiceReference.DuplexServiceClient(insCntxt, "NetTcpBinding_IDuplexService");

                obj5.AddValue(dblVal1, dblVal2);
                obj6.AddValue(dblVal1, dblVal2);
            }
            catch (Exception eX)
            {
                Console.WriteLine("Error while calling Duplex Service [ " + eX.Message + "]");
            }

            Console.WriteLine("\n\nPress any key …");
            Console.ReadKey();
        }
    }
}

and here is the output.

image

Advertisements

October 4, 2013 - Posted by | .NET, SOA, WCF | , ,

No comments yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: