How Intercept HTTP calls from WCF client to service

Standard

Today I faced some problem, I had to intercept HTTP calls from WCF proxy to WCF service. I was using Fiddler 4. But unfortunely it was not working :( I tried many options.(It was not working for me, but it may work for you)

  1. By using system.net proxy setting – In the clientapp.exe.config, you need to add following configuration settings.
    <system.net>
      <defaultProxy enabled="true">
        <proxy proxyaddress="http://127.0.0.1:8888" bypassonlocal="False" />
      </defaultProxy>
    </system.net>
    
  2. By using useDefaultWebProxy attribute in the binding element.
    <bindings>
      <basicHttpBinding>
        <binding name="BasicHttpBinding_IService1" 
                 useDefaultWebProxy="false" />
      </basicHttpBinding>
    </bindings>
    

    For me it is also not working :(

  3. By using Hostname instead of localhost. – This is the only solution worked for me. :) Modify you clientapp.exe.config, and change the endpoint address from localhost to the actual host name.
    <client>
      <endpoint address="http://anurajp/WcfService1/Service1.svc" 
          binding="basicHttpBinding"
          bindingConfiguration="BasicHttpBinding_IService1" 
          contract="ServiceReference1.IService1"
          name="BasicHttpBinding_IService1" />
    </client>
    

    This is the proxy request and response captured using Fiddler.

    WCF Request and Response using Fiddler

    WCF Request and Response using Fiddler

    Happy Programming :)

Creating a WCF service proxy with ChannelFactory <T>

Standard

A proxy, in its most general form, is a class functioning as an interface to something else. The proxy could interface to anything: a network connection, a large object in memory, a file, or some other resource that is expensive or impossible to duplicate.(From wiki). In case of WCF, proxy class helps client application to use WCF service,without knowing the address or implementation details. Here is the code for generic WCF proxy, using ChannelFactory class. ChannelFactory enables you to dynamically creating a proxy object based on the Service Contract. It will help you to avoid update service references or proxies generated using svcutil utility.

internal sealed class GenericProxy<TContract> : IDisposable where TContract : class
{
    private ChannelFactory<TContract> _channelFactory;
    private TContract _channel;

    public GenericProxy()
    {
        _channelFactory = new ChannelFactory<TContract>();
    }

    public GenericProxy(Binding binding, EndpointAddress remoteAddress)
    {
        _channelFactory = new ChannelFactory<TContract>(binding, remoteAddress);
    }

    public void Execute(Action<TContract> action)
    {
        action.Invoke(Channel);
    }

    public TResult Execute<TResult>(Func<TContract, TResult> function)
    {
        return function.Invoke(Channel);
    }

    private TContract Channel
    {
        get
        {
            if (_channel == null)
            {
                _channel = _channelFactory.CreateChannel();
            }

            return _channel;
        }
    }

    public void Dispose()
    {
        try
        {
            if (_channel != null)
            {
                var currentChannel = _channel as IClientChannel;
                if (currentChannel.State == CommunicationState.Faulted)
                {
                    currentChannel.Abort();
                }
                else
                {
                    currentChannel.Close();
                }
            }
        }
        finally
        {
            _channel = null;
            GC.SuppressFinalize(this);
        }
    }
}

The IDisposable implementation will help developers to close / abort channel with “using” statement.

And you can use this like the following.

using (var proxy = new GenericProxy<ICalculator>())
{
    var result = proxy.Execute<int>(x => x.Add(1, 2));
    return result;
}

The code is invoking Add method of Calculator service. The EndPoint and Binding information will fetched from the app.config file.

Happy Programming :)

First look into Visual Studio Community 2013

Standard

Yesterday Connect(); Event, Scott Guthrie and Soma Somasegar made a number of important announcements for the cloud-first, mobile-first developer. Visual Studio Community 2013 is a new free, fully-featured edition of Visual Studio that lets developers target any platform, from desktop and mobile to web and cloud.

Visual Studio Community 2013

Visual Studio Community 2013

Visual Studio Community 2013 also supports full Visual Studio extensibility, offering access to the ecosystem of over 5000 extensions. You can download it from here. You can also try Visual Studio Community 2013 in Azure VM image.

What is new in Visual Studio Community 2013

  • Professional-grade editing, code analysis, and debugging support – Your favourite Refactor and Debugging features are included.
  • Support for open-source workflows (Git).
  • Compilers for managed languages, C++ and more
  • Cross-platform mobile development including the web, Android, iOS, and Windows Phone with the free Visual Studio Tools for Apache Cordova extension.
  • Take advantage of cloud services with simplified Azure SDK integration, and incorporate modern app analytics and telemetry with Application Insights. Application Insights collects, processes and presents a wide variety of telemetry including performance, usage, availability, exception, crash, environment, log and developer-supplied data from all components of a modern application – including clients (devices and browser), servers, databases and services.
    Application Insights

    Application Insights

  • Access to all the Visual Studio 2013 extensions on the Visual Studio Gallery

Visual Studio Community 2013 includes Update 4, which is a cumulative update of all previous Visual Studio 2013 updates.

Happy Programming :)

How to Implement Ad-Hoc Discovery in WCF

Standard

WCF 4.0 introduces a couple of service discovery techniques, which the client can use to discover the services dynamically through client probing or service announcement. WCF 4.0 comes up with the ability of dynamic discovery. This feature allows the client to probe for the services or reversely the services can also announce their presence on the network.The Discovery API supports two different modes: Managed and Ad-Hoc.

In Managed mode there is a centralized server called a discovery proxy that maintains information about available services. Clients use the discovery proxy to retrieve information about available services. When a client searches for a service it sends a Probe message to the discovery proxy and the proxy determines whether any of the services it knows about match the service the client is searching for. If there are matches the discovery proxy sends a ProbeMatch response back to the client. The client can then contact the service directly using the service information returned from the proxy.

In Ad-Hoc mode, there is no centralized server. All discovery messages such as service announcements and client requests are sent in a multicast fashion. When a client sends a Probe message for a service it is sent over the network using a multicast protocol. Each service that receives the request determines whether it matches the criteria in the Probe message and responds directly to the client with a ProbeMatch message if the service matches the criteria specified in the Probe message.
This post is about implementing Ad-Hoc Discovery in WCF, which is simple I feel compared to Managed mode.
Here is a HelloService, which has a SayHello method, which accepts a name parameter, and returns a string.

[ServiceContract]
interface IHelloService
{
    [OperationContract]
    string SayHello(string name);
}

class HelloService : IHelloService
{
    public string SayHello(string name)
    {
        return string.Format("Hello {0}", name);
    }
}

To enable Ad-Hoc discovery, we need to add ServiceDiscoveryBehavior to the service’s behavior collection. This behavior indicates to the WCF runtime that the service supports the WS-Discovery protocol.

var discoveryBehavior = new ServiceDiscoveryBehavior();
serviceHost.Description.Behaviors.Add(discoveryBehavior);

Next we need to add UdpDiscoveryEndpoint to the list of service endpoints so that our service can start listening for WS-Discovery messages.

serviceHost.AddServiceEndpoint(new UdpDiscoveryEndpoint());

To announce the existence of the service in the network, we need to add UdpAnnouncementEndpoint to the service’s endpoints.

discoveryBehavior.AnnouncementEndpoints.Add(new UdpAnnouncementEndpoint());

Here is the whole snippet, which combines all the above steps.

var baseAddress = new Uri("http://localhost:8080");
using (var serviceHost = new ServiceHost(typeof(HelloService), new[] { baseAddress }))
{
    serviceHost.AddServiceEndpoint(typeof(IHelloService), new BasicHttpBinding(), "HelloService");
    var metadataBehavior = serviceHost.Description.Behaviors.Find<ServiceMetadataBehavior>() ?? new ServiceMetadataBehavior();
    serviceHost.Description.Behaviors.Add(metadataBehavior);
    serviceHost.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexHttpBinding(), "Mex");
    // make the service discoverable by adding the discovery behavior
    var discoveryBehavior = new ServiceDiscoveryBehavior();
    serviceHost.Description.Behaviors.Add(discoveryBehavior);
    // send announcements on UDP multicast transport
    discoveryBehavior.AnnouncementEndpoints.Add(new UdpAnnouncementEndpoint());
    // add the discovery endpoint that specifies where to publish the services
    serviceHost.AddServiceEndpoint(new UdpDiscoveryEndpoint());

    serviceHost.Open();
    serviceHost.Description.Endpoints.ToList().ForEach(endpoint => Console.WriteLine(endpoint.Address));
    Console.ReadKey();
    serviceHost.Close();
}

You will get something like this, if you build and run the console application. You can see the third address, which the address of discovery endpoint.

WCF AdHoc discovery endpoints

WCF AdHoc discovery endpoints

And you can create the proxy / client using DiscoveryClient class. Here is a sample snippet which will create a proxy for the HelloService. In order to dynamically discover services using the Ad-Hoc model, a WCF client instantiates a DiscoveryClient that uses discovery endpoint specifying where to send Probe or Resolve messages. The client then calls Find that specifies search criteria within a FindCriteria instance. If matching services are found, Find returns a collection of EndpointDiscoveryMetadata. Here is the code snippet

var discoveryClient = new DiscoveryClient(new UdpDiscoveryEndpoint());
var discoveryResponse = discoveryClient.Find(new FindCriteria(typeof(IHelloService)));
var address = discoveryResponse.Endpoints[0].Address;
Console.WriteLine(address);

This will print out the address of the service.

Happy Programming :)