Category Archives: WCF

A Lambda Expression Pattern for WCF Clients

I’ve sometimes ended up repeating the same blocks of boilerplate code when consuming WCF services: open the connection; do work; close the connection; wrap it all in a try-catch; close the exception differently depending on the type of exception thrown. I wanted to put the boilerplate code somewhere else to keep the rest of my service-calling code as clean and DRY as possible. This post discusses an approach I’ve used to achieve it.

Download the example project

Screenshot of server and client applications

There were a few key things I wanted from the pattern:

  • I don’t want to worry about the connection code. I just want to call the service and move on.
  • Exceptions must bubble up—unmodified—so that they can be handled appropriately.
  • If an exception does get thrown, the connection needs to be closed or aborted as appropriate. It’s important to do this correctly since connections left hanging around can very quickly kill your application—for more on this, see the MSDN article: Expected Exceptions.

I decided to use a lambda expression pattern so I could replace code like this:

Code snippet

…with something like this:

Code snippet

It’s worth pointing out that I prefer to use a shared services assembly if it’s feasible to do so, and that’s the approach I’ve taken in this example. It’s a topic for another blog post, but things can get complicated with svcutil-generated proxies if you have DataContract classes that are shared across multiple endpoints.

The example shows a really simple service that takes a name and returns a greeting such as “Hello, Mike!” The service contract looks like this:

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

If you’ve made it this far, I expect you can guess what the implementation looks like. The example solution includes a really simple Console application to host the service on TCP port 8000 using the following WCF configuration:

<system.serviceModel>
  <services>
    <service name="GreetingServices.GreetingService">
      <endpoint
        address="net.tcp://localhost:8000/GreetingService"
        binding="netTcpBinding"
        contract="GreetingServices.IGreetingService"/>
    </service>
  </services>
</system.serviceModel>

On the client side, there’s a similar TCP/IP binding to the service:

<system.serviceModel>
  <client>
    <endpoint
      name="GreetingServices.IGreetingService"
      address="net.tcp://localhost:8000/GreetingService"
      binding="netTcpBinding"
      contract="GreetingServices.IGreetingService"/>
  </client>
</system.serviceModel>

Now for the important bit: the services will be called using a lambda expression, so the first thing is to declare a delegate through which the client logic will be passed.

public delegate void DoWithServiceDelegate(T serviceClient);

Next, a “Services” class will present the proxy into the service. It contains a private method that sends a generic delegate into a generic service endpoint:

private static void WithServiceClient<T>(T serviceClient, DoWithServiceDelegate<T> serviceDelegate)
{
    try
    {
        serviceDelegate(serviceClient);
        ((IClientChannel)serviceClient).Close();
    }
    catch (TimeoutException)
    {
        // Abort the connection if it times out
        ((IClientChannel)serviceClient).Abort();
        throw;
    }
    catch (CommunicationException)
    {
        // Abort the connection if there's a connection-level failure
        ((IClientChannel)serviceClient).Abort();
        throw;
    }
    catch (Exception)
    {
        // The connection should be valid for other exception types, so close it normally
        ((IClientChannel)serviceClient).Close();
        throw;
    }
}

The key points covered by the above code are:

  • Make sure the connection gets closed properly, even if something throws an exception.
  • Allow exceptions to bubble up to the surface intact.

Finally, the service proxy is presented through a public method:

public static void WithGreetingService(DoWithServiceDelegate<IGreetingService> serviceDelegate)
{
    // Create the connection to IGreetingService
    var channelFactory = new ChannelFactory<IGreetingService>("*");
    IGreetingService channel = channelFactory.CreateChannel();

    // Execute the delegated logic
    WithServiceClient(channel, serviceDelegate);
}

Each new service will need its own public method similar to the WithGreetingService(…) method but, unless project contains a really high number of endpoints, this shouldn’t become too cumbersome. To make a really simple, one-line call to the service:

Services.WithGreetingService(service => service.SomeMethod(…));

– Mike Clift

JSON Services: A Comparison of WCF and Web API

This blog post shows two implementations of a really simple JSON calculator service: one using WCF and one using Web API. To show the services in action, there’s also a single webpage that exposes the calculator services though a Web form.

Download the example project

Blog post header

WCF

I’ve used a self-hosted WCF service for this example as I want control over the URL through which it’s accessed. I start by creating a new Console Application and adding references to System.Runtime.Serialization, System.ServiceModel and System.ServiceModel.Web.

The service will expose a method to add two numbers together, so I add a class to contain the parameters to this method:

[DataContract]
public class AddParameters
{
    [DataMember(Name = "left")]
    public decimal Left { get; set; }

    [DataMember(Name = "right")]
    public decimal Right { get; set; }
}

I also create a class to contain the result of the calculation.

[DataContract]
public class CalculationResult
{
    [DataMember(Name = "result")]
    public decimal Result { get; set; }
}

Now I’m ready to define the WCF service interface…

[ServiceContract]
public interface ICalculator
{
    [OperationContract]
    CalculationResult Add(AddParameters addParameters);
}

…and its implementation.

public class Calculator : ICalculator
{
    [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, 
        ResponseFormat = WebMessageFormat.Json,
        BodyStyle = WebMessageBodyStyle.Wrapped)]
    public CalculationResult Add(AddParameters addParameters)
    {
        decimal result = addParameters.Left + addParameters.Right;

        return new CalculationResult
        {
            Result = result
        };
    }
}

The code to create the service host is pretty straightforward. In Program.cs, I update the Main(…) method:

static void Main(string[] args)
{
    using (ServiceHost serviceHost = new ServiceHost(typeof(Calculator)))
    {
        serviceHost.Open();

        Console.WriteLine("The Calculator service is available at:");
        foreach (var endpoint in serviceHost.Description.Endpoints)
        {
            Console.WriteLine(endpoint.Address);
        }

        Console.WriteLine();
        Console.WriteLine("Press any key to exit...");
        Console.ReadKey();
    }
}

Next, I add the WCF service configuration that’ll allow the service to be called from within a webpage.

<system.serviceModel>
  <services>
    <service name="WcfJsonServices.Calculator">
      <endpoint address="http://localhost:8080/Calculator"
                binding="webHttpBinding"
                contract="WcfJsonServices.ICalculator"/>
    </service>
  </services>
  <behaviors>
    <endpointBehaviors>
      <behavior>
        <webHttp />
      </behavior>
    </endpointBehaviors>
  </behaviors>
</system.serviceModel>

Finally, since I’m going to run this on a system with UAC enabled, I give my user account the necessary permission to create an HTTP service on port 8080. To do this, I use the “Run as Administrator” option to open a new Command Prompt window and then enter the following command:

netsh http add urlacl url=http://+:8080/ user="Mike"

WebAPI

To make the demo hang together as simply as possible, I’m going to host my client webpage and my Web API service in the same project. I start by creating a new ASP.NET Web Application project and choosing the Web API project template when prompted.

As per the WCF example, I create classes to contain my input and output parameters for my Add service. I create them both under the Models folder.

public class AddParameters
{
    public decimal Left { get; set; }

    public decimal Right { get; set; }
}

public class CalculationResult
{
    public decimal Result { get; set; }
}

Notice that the above classes don’t need to be declared as Serializable since the ASP.NET MVC framework automatically handles the JSON serialisation.

Next, I create a new controller class that’ll expose the addition service. I create the AddController class under the Controllers folder.

public class AddController : ApiController
{
    public CalculationResult Post(AddParameters addParameters)
    {
        decimal result = addParameters.Left + addParameters.Right;

        return new CalculationResult
        {
            Result = result
        };
    }
}

Note that there’s no need to declare a separate service interface. Just inherit from ApiController and ensure the method name begins with the HTTP verb (“POST’ in this case) that the client is expected to use.

I don’t need to add any special HTTP routes as the default handles it nicely—the new addition service has the URL /api/Add (see the default mappings in the WebApiConfig class under the App_Start folder) and it accepts POST requests.

The Client Web Page

To test the two services side-by-side, I want a single Web page that lets me fire JSON requests at each service and displays the results they return. As I’m going to use jQuery to do most of the client-side work, I first add the following line into the <head> section of _Layout.cshtml, which is located under /Views/Shared:

@Scripts.Render("~/bundles/jquery")

Now, I delete the contents of Index.cshtml, which is located under /Views/Home, and import my default layout.

@{
    ViewBag.Title = "Home Page";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

Now I add the UI components that’ll allow users to generate the service requests.

<div class="jumbotron">
    <h1>JSON Client Samples</h1>
</div>
<div class="row">
    <div class="row">
        <h2>Use WCF</h2>
        <p>
            Add <input type="text" id="wcfLeft" />
            to <input type="text" id="wcfRight" />
            <input type="button" id="wcfAdd" value="=" />
            <span id="wcfAnswer">&nbsp;</span>
        </p>
    </div>
    <div class="row">
        <h2>Use WebAPI</h2>
        <p>
            Add <input type="text" id="waLeft" />
            to <input type="text" id="waRight" />
            <input type="button" id="waAdd" value="=" />
            <span id="waAnswer">&nbsp;</span>
        </p>
    </div>
    <div>
        <p id="error"></p>
    </div>
</div>

Now I add a script block and begin wiring up the Web UI with the JSON services. I start by wiring up the each of the two buttons so that the “click” event will cause a method to be called with the values of the adjacent text boxes. For WCF, wcfAdd(…) will be called. For Web API, waAdd(…) will be called.

$(function () {
    // Bind the WCF button
    $("#wcfAdd").bind("click", function () {
        var left = $("#wcfLeft")[0].value;
        var right = $("#wcfRight")[0].value;
        wcfAdd(left, right);
    });

    // Bind the WebAPI button
    $("#waAdd").bind("click", function () {
        var left = $("#waLeft")[0].value;
        var right = $("#waRight")[0].value;
        waAdd(left, right);
    });
});

The function that calls WCF begins with some object literal notation to set up the parameters expected by the service (just a single parameter in this case: addParameters). The parameters are then converted into a JSON string. Finally, the JSON is POSTed to the service. On success, the calculation result is displayed; on failure, the user is notified that something went wrong.

// Call the WCF service to add the numbers together
function wcfAdd(left, right) {
    // Prepare the instance of AddParameters with the two numbers
    var parameters = {
        addParameters: {
            left: left,
            right: right
        }
    };
    // Convert to an escaped JSON string
    var json = JSON.stringify(parameters);
    // Make the request
    $.ajax({
        type: "POST",
        url: "http://localhost:8080/Calculator/Add",
        data: json,
        contentType: "application/json; charset=utf-8",
        success: function (result) {
            $("#wcfAnswer").text(result.AddResult.result);
        },
        error: function (xhr, msg, ex) {
            handleError(xhr, msg, ex);
        }
    });
}

The Web API version doesn’t need to explicitly define addParameters as a named object literal. Instead, it just needs to create an object with the correct members: Left and Right. The rest is almost identical to the WCF version, the only differences being the sevice URL and the structure of the returned result.

// Call the WebAPI service to add the numbers together
function waAdd(left, right) {
    // Prepare the instance of AddParameters with the two numbers
    var parameters = {
        Left: left,
        Right: right
    };
    // Convert to an escaped JSON string
    var json = JSON.stringify(parameters);
    // Make the request
    $.ajax({
        type: "POST",
        url: "/api/Add",
        data: json,
        contentType: "application/json; charset=utf-8",
        success: function (result) {
            $("#waAnswer").text(result.Result);
        },
        error: function (xhr, msg, ex) {
            handleError(xhr, msg, ex);
        }
    });
}

Finally, I add a method to notify the user of any errors.

function handleError(xhr, msg, ex) {
    $("#error").html(xhr.responseText);
    alert("Call failed: [" + xhr.status + "] " + ex);
}

Demo

The WCF service application needs to be running for the demo to work. When the Web application is launched, a simple form allows the use to call each service.

Screenshot of the test Web page

Conclusions

I’ve shown how to create a JSON service that’s accessible from a Web page with jQuery by using two different technologies: WCF and Web API. Going through this exercise has highlighted a few things for me about each technology.

WCF: Pros and Cons

  • Pro: I like that WCF can be hosted in a number of different ways, from a stand-alone console application to an IIS application.
  • Con: Perhaps because of WCF’s flexibility in terms of the transports and message formats it supports, getting the configuration right can be difficult. What makes it worse is that it really doesn’t help you when things aren’t set up correctly: you don’t get a chance to intercept an exception; you don’t get any hints about what the service is expecting; most of the time, you just get a boilerplate HTTP exception with no clues as to the cause of what’s wrong.

Web API: Pros and Cons

  • Pro: It’s really simple to get up and running, especially if you’re already used to the ASP.NET MVC framework.
  • Pro: Web API benefits from the transparency of the ASP.NET MVC framework: when something isn’t configured correctly or isn’t being called in the right way, there’s still usually somewhere where you can set a breakpoint or intercept an exception so you can see what’s going on. Having the Request and Response properties right there can also be really useful whilst debugging.
  • Con: This is a very pernickety point, but it feels like Web API isn’t that great as an API presentation framework. WCF’s requirement that any service be declared as an interface makes it very clear where your API’s boundaries lie. Not only does Web API not require your interfaces to be declared, it also obscures things by mapping HTTP verbs to methods by their names and signatures. Of course, this convention-over-configuration approach is one of the cornerstones of the technology that brings many advantages, but it also ties the API to HTTP.

At the time of writing, I’m a newbie to Web API but in a situation where I were consuming JSON services from the browser, I’d lean toward Web API as the framework of choice. This would be especially true if the consuming Web application were already an ASP.NET MVC project—the benefits of using the same underlying technology for the Web application and JSON services would be difficult to ignore.

Of course, this post has focused on a very small, specific scenario. WCF is a much broader technology than Web API in terms of the transports, methods of communication and types of hosting it supports, whilst Web API expands upon the very successful ASP.NET MVC to make it easy to write services for browsers. There’s a great blog post by Ido Flatow, “WCF or ASP.NET Web APIs? My two cents on the subject”, that gives a little bit of the history behind these two technologies and presents a range of scenarios in which one might be a better fit than the other.

For more information about Web API, the Official ASP.NET site is a good place to start. For WCF, visit the WCF portal on MSDN.

  – Mike Clift