Friday, December 16, 2011

Duplex Service in WCF .net Application


 Duplex Service in WCF .net Application:
A duplex service contract is a message exchange pattern in which both endpoints can send messages to the other independently. A duplex service, therefore, can send messages back to the client endpoint, providing event-like behavior. Duplex communication occurs when a client connects to a service and provides the service with a channel on which the service can send messages back to the client. Note that the event-like behavior of duplex services only works within a session.
To create a duplex contract you create a pair of interfaces. The first is the service contract interface that describes the operations that a client can invoke. That service contract must specify a callback contract in the System.ServiceModel.ServiceContractAttribute.CallbackContract property. The callback contract is the interface that defines the operations that the service can call on the client endpoint. A duplex contract does not require a session, although the system-provided duplex bindings make use of them.
Example:
Interface:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace WCFDuplexServ
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
    [ServiceContract(CallbackContract = typeof(IClientCallback))]
    public interface ITemperature
    {
        [OperationContract(IsOneWay = true)]
        void RegisterForTempDrops();

        // TODO: Add your service operations here
    }
    public interface IClientCallback
    {
        [OperationContract(IsOneWay = true)]
        void TempUpdate(double temp);
    }
}

Service Implementation:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Threading;
namespace WCFDuplexServ
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in both code and config file together.
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession,
                 ConcurrencyMode = ConcurrencyMode.Single)]
    public class Temperature : ITemperature
    {
       
        public void RegisterForTempDrops()
        {
            OperationContext ctxt = OperationContext.Current;
            IClientCallback callBack = ctxt.GetCallbackChannel<IClientCallback>();
            Thread.Sleep(3000); //simulate update happens somewhere;
                                //for example monitoring a database field
            callBack.TempUpdate(10);
        }
    }
}

Service App.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.web>
    <compilation debug="true" />
  </system.web>
  <!-- When deploying the service library project, the content of the config file must be added to the host's 
  app.config file. System.Configuration does not support config files for libraries. -->
  <system.serviceModel>
    <services>
      <service name="WCFDuplexServ.Temperature" behaviorConfiguration="ServiceBehaviour">
        <endpoint address="http://localhost:8732/Design_Time_Addresses/WCFDuplexServ/Temperature/" binding="wsDualHttpBinding" contract="WCFDuplexServ.ITemperature">
          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8732/Design_Time_Addresses/WCFDuplexServ/Temperature/" />
          </baseAddresses>
        </host>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehaviour">
          <!-- To avoid disclosing metadata information, 
          set the value below to false and remove the metadata endpoint above before deployment -->
          <serviceMetadata httpGetEnabled="True"/>
          <!-- To receive exception details in faults for debugging purposes, 
          set the value below to true.  Set to false before deployment 
          to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="False" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>

Client Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WCFDuplexServClient.ServiceReference1;
using System.ServiceModel;
namespace WCFDuplexServClient
{
    public partial class WebForm1 : System.Web.UI.Page, ITemperatureCallback
    {
        
        protected void Page_Load(object sender, EventArgs e)
        {
            InstanceContext site = new InstanceContext(this);
            TemperatureClient proxy = new TemperatureClient(site);
            proxy.RegisterForTempDrops();
        }
        void ITemperatureCallback.TempUpdate(double temp)
        {
            Response.Write(temp);
        }
    }
}

Client web.config:

<?xml version="1.0"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
 
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
    <authentication mode="None">
      
    </authentication>  
  </system.web>
  <system.webServer>
     <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>
  <system.serviceModel>
    <bindings>
      <wsDualHttpBinding>
        <binding name="WSDualHttpBinding_ITemperature" closeTimeout="00:01:00"
          openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
          bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard"
          maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text"
          textEncoding="utf-8" useDefaultWebProxy="true">
          <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
            maxBytesPerRead="4096" maxNameTableCharCount="16384" />
          <reliableSession ordered="true" inactivityTimeout="00:10:00" />
          <security mode="Message">
            <message clientCredentialType="Windows" negotiateServiceCredential="true"
              algorithmSuite="Default" />
          </security>
        </binding>
      </wsDualHttpBinding>
    </bindings>
    <client>
      <endpoint address="http://localhost:8732/Design_Time_Addresses/WCFDuplexServ/Temperature/"
        binding="wsDualHttpBinding" bindingConfiguration="WSDualHttpBinding_ITemperature"
        contract="ServiceReference1.ITemperature" name="WSDualHttpBinding_ITemperature">
        <identity>
          <dns value="localhost" />
        </identity>
      </endpoint>
    </client>
  </system.serviceModel>
</configuration>

No comments: