    <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:admin="http://webns.net/mvcb/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:content="http://purl.org/rss/1.0/modules/content/">
     <channel>
        <title>ACCU  :: Secrets of Testing WCF Services</title>
        <link>https://members.accu.org/index.php/journals/1873</link>
        <description>Professionalism in Programming</description>
        <dc:language>en-us</dc:language> 
        <dc:creator>Administrator</dc:creator> 
        <admin:generatorAgent rdf:resource="http://www.xaraya.org" /> 
        <admin:errorReportsTo rdf:resource="mailto:webeditor@accu.org" />
       <sy:updatePeriod>hourly</sy:updatePeriod>
       <sy:updateFrequency>1</sy:updateFrequency>
       <docs>http://backend.userland.com/rss</docs>


        <h2>Journal Articles</h2>


<div class="xar-mod-head"><span class="xar-mod-title">Overload Journal #113 - February 2013 + Programming Topics</span></div>

<table border="0" cellpadding="1" cellspacing="0">
    <tbody>
    <tr>
        <td valign="top">
            Browse in :
       </td>
       <td valign="top">

                                            <a href="https://members.accu.org/index.php/journals/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c76/">Journals</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c78/">Overload</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c320/">o113</a>
                    (7)
<br />

                                            <a href="https://members.accu.org/index.php/journals/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c13/">Topics</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c65/">Programming</a>
                    (877)
<br />

                                            <a href="https://members.accu.org/index.php/journals/c320-65/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/journals/c320+65/">All of these categories</a>
<br />
</td>
   </tr>
   </tbody>
</table>




<div class="xar-error">
   <p>
 <strong>Note:</strong> when you create a new publication type,
the articles module will automatically use the templates
<em>user-display-[publicationtype].xt</em>
and <em>user-summary-[publicationtype].xt</em>.
If those templates do not exist when you try to preview or display a new article,
you'll get this warning :-)  Please place your own templates in themes/<em>yourtheme</em>/modules/articles . The templates will get the extension .xt there. </p>
</div>
<div class="xar-norm xar-standard-box-padding">
   <h1><strong>Title:</strong>&nbsp;Secrets of Testing WCF Services</h1>
<p><strong>Author:</strong>&nbsp;Martin Moene</p>
<p>
<strong>Date:</strong> 02 February 2013 20:41:38 +00:00 or Sat, 02 February 2013 20:41:38 +00:00</p>
<p><strong>Summary:</strong>&nbsp;WCF services provide middleware for applications but can be hard to test. Steve Love describes a way to develop a testable app.</p>
<p><strong>Body:</strong>&nbsp;<p>The Windows Communication Foundation, or WCF, is part of a loosely related family of frameworks from Microsoft for developing robust and reliable systems. I say loosely because WCF and the other libraries can be used independently or in concert. The other main frameworks are WPF for presentation, and WF for workflow. WCF is for distributed and inter-process communications. Specifically, it is the middleware that applications can use to talk to each other, whether they are on the same machine, distributed over a LAN or even on the Internet.</p>

<p>There is a wealth of information about WCF on the MSDN [<a href="#[WCF]">WCF</a>, <a href="#[MSDN]">MSDN</a>], and in a whole range of books [<a href="#[Resnick08]">Resnick08</a>] which presents the details of writing and configuring services and client applications. From reading this documentation, one would be forgiven for thinking that the â€˜Wâ€™ in WCF was â€˜Webâ€™ rather than â€˜Windowsâ€™ because much of it covers setting up a web-service, and using SOAP to establish communications and discover services over HTTP. WCF is, however, the official replacement for .Net Remoting Services, which itself superceded Distributed COM. Itâ€™s my experience that WCF is actually really quite good in this application space, even if the documentation (official and otherwise) wants you, the developer, to think about web services and SOAP instead of RPC.</p>

<p>In this article, I want to explore some of those almost-hidden secrets of configuring and running WCF service- and client-applications. By going off the beaten path blazed by the example code that is available on MSDN, I hope to demonstrate how the resulting code can be more flexible and less intrusive in your applications.</p>

<p>The full source code for this is available on github [<a href="#[Love]">Love</a>]. Itâ€™s a Microsoft Visual Studio 2010 solution in C#, but should work in VS2012. A wiki page on the github site explains the different projects in the code.</p>

<h2>A standing start</h2>

<p>There are two main starting points from where discussion of using WCF for applications might commence. The first is to begin with the premise that the application will be distributed, that WCF has been chosen as the facilitator for that, and so we would start with defining some service contracts and definitions. The second scenario â€“ which is probably much more common â€“ is to begin with the premise that there is some application already in existence, for which WCF has been chosen as the technology to turn it into a distributed application. Most of the MSDN introductions, and many of the books on WCF follow the first scenario, but Iâ€™m now going to introduce a third possibility.</p>

<p>I want to start with a new application that doesnâ€™t use WCF in any way, and turn it into a distributed application.1 The main reason for this is about testing. Distributed applications that use technologies like WCF are notoriously hard to test in an automated fashion. Testing the client usually has to assume that a corresponding server is available, and the client must be configured correctly to use it. Testing the server is notionally simpler if you separate the communications code from the â€˜serverâ€™ code (as it were) internally, so you can at least automate testing the code that provides the logic for your service, but itâ€™s all rather messy. Which is probably why discussion of this kind is conspicuously absent from MSDN examples and books about WCF.</p>

<p>The example code for this article is a recipe book application for cocktails. It isnâ€™t terribly sophisticated, and the outline of the design ought to be clear from Listing 1.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
public interface RecipeBook : IDisposable
{
  IEnumerable&lt; Drink &gt; AllDrinks { get; }
  IEnumerable&lt; string &gt; AllIngredients { get; }
  void Add( params Drink [] newDrinks );
  IEnumerable&lt; Drink &gt; WithIngredients
     ( params string [] selected );
}

public interface Drink : IEquatable&lt; Drink &gt;
{
  string Name { get; }
  string Method { get; }
  IEnumerable&lt; Ingredient &gt; Ingredients { get; }
}

public enum Measurement
{
  Fill, Measure, Drop, Tsp,
}

public sealed class Ingredient 
   : IEquatable&lt; Ingredient &gt;
{
  public Ingredient( string name,
                     Measurement mmt, int qty )
  {
    if( string.IsNullOrEmpty( name ) )
      throw new ArgumentNullException( &quot;name&quot; );
    Name = name;
    Amount = mmt;
    Qty = qty;
  }

  public string Name { get; private set; }
  public Measurement Amount { get; private set; }
  public int Qty { get; private set; }
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 1</td>
	</tr>
</table>

<p>One thing of note here, for the sake of brevity later, is that the <code>Drink</code> type is an interface instead of a value-type like <code>Ingredient</code>. Consider it a foresight of things to come in the design when we start considering distributed communications.</p>

<p>In any case, there is nothing here, or in the implementing types, to do with WCF or any kind of remoting. To make the example more interesting, letâ€™s introduce a new class that uses the recipe book, and adds some value. Listing 2 uses the <code>RecipeBook</code> interface, and provides some simple queries over those in <code>RecipeBook</code>. Lastly listing 3 has some unit tests for the <code>DrinksCabinet</code> queries. In this test class you can see that the concrete <code>LocalDrink</code> type is used; this is a value-like implementation of the <code>Drink</code> interface mentioned previously. The <code>DrinksCabinet</code> constructor takes a <code>RecipeBook</code> reference, and the test creates a <code>LocalRecipeBook</code> which implements that interface using simple collection types to store the data.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
public class DrinksCabinet
{
  public DrinksCabinet( RecipeBook recipes )
  {
    this.recipes = recipes;
  }
  public Drink Find( string name )
  {
    return recipes.AllDrinks.Single
       ( d =&gt; d.Name == name );
  }
  public IEnumerable&lt; string &gt; Ingredients
  {
    get { return recipes.AllIngredients; }
  }
  public IEnumerable&lt; Drink &gt; NotContaining
     ( params string [] selected )
  {
    var remain = Ingredients.Except( selected );
    return recipes.WithIngredients
       ( remain.ToArray() );
  }
  private readonly RecipeBook recipes;
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 2</td>
	</tr>
</table>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
[ TestFixture ]
public class DrinksCabinetTests
{
  private RecipeBook recipes;
  [SetUp]
  public void Start()
  {
    recipes = new LocalRecipeBook();
  }
  [TearDown]
  public void End()
  {
    recipes.Dispose();
  }
  [Test]
  public void EmptyCabinetHasNoIngredients()
  {
    var cabinet = new DrinksCabinet( recipes );
    var results = cabinet.Ingredients;
    Assert.IsFalse( results.Any() );
  }
  [ Test ]
  public void CanLocateSpecificDrinkByName()
  {
    var cabinet = new DrinksCabinet( recipes );
    var expected = new LocalDrink( &quot;a&quot;, &quot;&quot;,
      new[] { new Ingredient( &quot;1&quot;,
      Measurement.Tsp, 1 ) } );
    var error = new LocalDrink( &quot;b&quot;, &quot;&quot;, new[] {
      new Ingredient( &quot;2&quot;, Measurement.Tsp, 1 )
    } );
    recipes.Add( expected, error );
    var result = cabinet.Find( expected.Name );
    Assert.AreEqual( expected, result );
  }
  [ Test ]
  public void CanFilterDrinksOnNotSpecified()
  {
    var cabinet = new DrinksCabinet( recipes );
    var expected = new LocalDrink( &quot;a&quot;, &quot;&quot;,
       new[] {
      new Ingredient( &quot;1&quot;, Measurement.Tsp, 1 )
      } );
    var error = new LocalDrink( &quot;b&quot;, &quot;&quot;, new[] {
      new Ingredient( &quot;2&quot;, Measurement.Tsp, 1 )
    } );
    recipes.Add( expected, error );
    var results = cabinet.NotContaining( &quot;2&quot; );
    Assert.AreEqual( expected, results.Single() );
  }
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 3</td>
	</tr>
</table>

<p>Clearly, we could use any implementation of <code>RecipeBook</code> to provide to the <code>DrinksCabinet</code> object, which brings us neatly to the next section.</p>

<h2>Pace yourself</h2>

<p>Would it be possible to use the <code>RecipeBook</code> interface as the contract for a remote service? If it is, then the service can implement it in some way, and the client can use a proxy implementation to communicate. Well, we canâ€™t use the interface directly, but it would certainly be possible to modify it in simple ways to operate as a WCF contract. However, letâ€™s step back for a moment. WCF can be used to provide network communications, as well as inter-process, and should be less â€˜chattyâ€™ than a native interface. A direct port may not be at all appropriate if it would introduce the need for unnecessary communications between client and server. Adapting a native interface to reduce the communications requires an intermediate abstraction.</p>

<p>Additionally, WCF imposes some restrictions on the way you compose contracts. WCF requires those contracts to explicitly attribute the interfaces, methods and types used in the contract. Ideally, keeping these WCF specific warts out of the way of application code would be a Good Idea.</p>

<p>Listing 4 shows what a WCF contract version of the <code>RecipeBook</code> interface might look like. Itâ€™s not a direct port from <code>RecipeBook</code>, partly because I want to demonstrate adapting one interface to the other, but there are other differences that are due to it being part of the WCF subsystem. Also note the use of names such as <code>IngredientDto</code> (<code>Dto</code> indicates itâ€™s a <span class="pattern">DataTransferObject</span>, see [<a href="#[Fowler]">Fowler</a>, <a href="#[Fowler02]">Fowler02</a>]) instead of just <code>Ingredient</code>. We could easily use the same names for the component types as in the original <code>RecipeBook</code> interface that weâ€™re adapting, and namespaces would take care of clashes. However, the adapting code would necessarily contain lots of explicit namespace qualification to distinguish between the native and DTO versions, and it can get difficult to keep track of which side of the WCF boundary you are on.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
[ ServiceContract ]
public interface RecipeBookContract
{
  [ OperationContract ]
  IEnumerable&lt; DrinkDto &gt; AllDrinks();

  [ OperationContract ]
  IEnumerable&lt; string &gt; AllIngredients();

  [ OperationContract ]
  IEnumerable&lt; IngredientDto &gt; IngredientsOf
     ( string drink );

  [ OperationContract ]
  void Add( DrinkDto drink,
    IEnumerable&lt; IngredientDto &gt; newIngredients );

  [ OperationContract ]
  IEnumerable&lt; DrinkDto &gt; WithIngredients
     ( IEnumerable&lt; string &gt; ingredients );
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 4</td>
	</tr>
</table>

<p>The <code>AllIngredients</code> and <code>AllDrinks</code> properties from <code>RecipeBook</code> are methods in the contract. A <code>ServiceContract</code> is essentially a collection of <code>OperationContracts</code>, which are required to be methods (as opposed to properties). Another restriction is on the use of <code>params</code> arrays, so these have become <code>IEnumerable</code> objects instead, which is only a minor inconvenience really in any case.</p>

<p>Listing 5 shows the participating classes. Note that <code>DrinksDto</code> is <em>not</em> an interface here, because itâ€™s not a <code>ServiceContract</code>, itâ€™s a <code>DataContract</code>. One other difference to note is that a <code>DrinksDto</code> doesnâ€™t directly expose its ingredients. The facility to associate ingredients with drinks has moved up to the contract interface, in order to keep all the <code>OperationContract</code> methods in one place. It also permits me to illustrate some interface adapting between the contract and the native interfaces <a href="#FN01"><sup>1</sup></a>.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
[ DataContract ]
public class DrinkDto
{
  [ DataMember ]
  public string Name { get; set; }

  [ DataMember ]
  public string Method { get; set; }
}

[ DataContract ]
public class IngredientDto
{
  public enum Measurement { Fill, Measure,
     Drop, Tsp, }

  [ DataMember ]
  public string Name { get; set; }

  [ DataMember ]
  public Measurement Amount { get; set; }

  [ DataMember ]
  public int Qty { get; set; }
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 5</td>
	</tr>
</table>

<h2>Planning a route</h2>

<p>Adapting between the <code>RecipeBookContract</code> and <code>RecipeBook</code> interfaces is quite straightforward, but before getting to that, I want to briefly show the implementations of the WCF service and corresponding client applications, to illustrate some of the challenges with separating out the needs of the application from the requirements of WCF.</p>

<p>There are three main components to any WCF service, known as the ABCs:</p>

<ul>
	<li>A is the address</li>
	<li>B is the binding</li>
	<li>C is the contract</li>
</ul>

<p>We have already dealt with C, and the most flexible way of associating the contract with the binding is through a configuration file, such as that in listing 6.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
&lt;system.serviceModel&gt;
  &lt;services&gt;
    &lt;service
       name=&quot;Shaker.Service.RecipeBookService&quot;&gt;
      &lt;endpoint binding=&quot;basicHttpBinding&quot;
         contract=
         &quot;Recipes.Contract.RecipeBookContract&quot; /&gt;
    &lt;/service&gt;
  &lt;/services&gt;
&lt;/system.serviceModel&gt;
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 6</td>
	</tr>
</table>

<p>The service name in the <code>system.serviceModel</code> element is the fully-qualified type name of the implementing type of the contract (shown later in listing 8). The contract attribute of the endpoint element is the fully-qualified type name of the contract interface. Lastly for the configuration, this example uses the <code>basicHttpBinding</code> type which defines the communication method being exposed by the server.</p>

<p>One of the features of WCF is the ability to discover a service interface. The tool for this is <span class="filename">svcutil.exe</span>, which is also exposed inside Visual Studio as â€˜Add Service Referenceâ€™ in the project tree. This tool is there to allow you to reference not only WCF services, but SOAP services on other platforms. Likewise, with certain restrictions, WCF services can be exposed to other platforms to consume. This is achieved by setting up a meta-data exchange (mex) endpoint in the service configuration, which uses SOAP standards to â€˜explainâ€™ to the client the details of the contract. svcutil generates the client-side configuration and proxy code to handle the communication layer.</p>

<p>However, this is much more than this simple application needs, and where all the communicating parts of an application are in .Net, a shared library referenced by both client and server with the interface for the contract is sufficient, and thatâ€™s what the example here uses. Besides which, I have a phobia about generated code.</p>

<p>You can also add the base address for the server in the same configuration, but for reasons of brevity â€“ and because itâ€™ll become useful later â€“ the address for this server is directly in the server application code. This is a simple console application, shown in listing 7.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
class ShakerServiceProgram
{
  static int Main()
  {
    const string 
       address = &quot;http://localhost:5110&quot;;
    var recipes = new RecipeBookService();
    using( var host = new ServiceHost( recipes,
       new Uri( address ) ) )
    {
      host.Open();
      Console.WriteLine
         ( &quot;Press [Enter] to close&quot; );
      Console.ReadLine();
    }
    return 0;
  }
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 7</td>
	</tr>
</table>

<p>The heart of the application is the <code>ServiceHost</code> object, which uses the application configuration to determine the binding (and any other attributes which are defined in the configuration file), and to host the service. The default behaviour of a WCF service host is to create a single-threaded instance of the contract implementation (<code>RecipeBookService</code>, listing 8) for each call to the service. Other hosting options are available, including single-instance and per-session. Since this service is just using local collections to manage the objects to be stored and retrieved, itâ€™s important that successive calls to the service communicate with the same instance. To achieve this, two things are needed. First, the implementing class is attributed with the <code>Single</code> instance mode, and secondly an actual instance of the type is passed to the <code>ServiceHost</code> object, instead of a type for it to instantiate as it sees fit.</p>

<p>Finally, itâ€™s time to show the contract implementation. Listing 8 shows an example implementation of the <code>RecipeBookContract</code> service contract interface in listing 4. Note that the <code>IngredientDto</code> and <code>DrinkDto</code> types are already full classes â€“ not interfaces â€“ and can so be used directly.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
[ ServiceBehavior( InstanceContextMode 
   = InstanceContextMode.Single ) ]
public class RecipeBookService 
   : RecipeBookContract
{
  public RecipeBookService()
  {
    drinks = new List&lt; DrinkDto &gt;();
    ingredients = new Dictionary&lt; string,
       List&lt; IngredientDto &gt; &gt;();
  }
  public IEnumerable&lt; DrinkDto &gt; AllDrinks()
  {
    return drinks;
  }
  public IEnumerable&lt; string &gt; AllIngredients()
  {
    return drinks.SelectMany( d =&gt; IngredientsOf
       ( d.Name ) )
      .Select( i =&gt; i.Name ).Distinct();
  }
  public IEnumerable&lt; IngredientDto &gt;
     IngredientsOf( string drink )
  {
    return ingredients[ drink ];
  }
  public void Add( DrinkDto drink,
     IEnumerable&lt; IngredientDto &gt; i )
  {
    if( drinks.Any( d =&gt; d.Name == drink.Name ) )
    {
      throw new FaultException
         ( &quot;DuplicateDrink&quot; );
    }
    drinks.Add( drink );
    ingredients.Add( drink.Name, i.ToList() );
  }
  public IEnumerable&lt; DrinkDto &gt; WithIngredients
     ( IEnumerable&lt; string &gt; selectedIngredients )
  {
    var result = drinks.Where
       ( drink =&gt; ingredients[ drink.Name ]
       .Any( dto =&gt; selectedIngredients.Contains
       ( dto.Name ) ) );
    return result;
  }
  private readonly List&lt; DrinkDto &gt; drinks;
  private readonly Dictionary&lt; string,
     List&lt; IngredientDto &gt; &gt; ingredients;
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 8</td>
	</tr>
</table>

<p>The client application uses the same interface and data contract types to communicate with the server. A configuration is still required to set up the client-side WCF parts. The client configuration that corresponds to the server configuration in listing 6 is shown in listing 9.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot; ?&gt;
&lt;configuration&gt;
  &lt;system.serviceModel&gt;
    &lt;client&gt;
      &lt;endpoint name=&quot;ShakerService&quot;
        binding=&quot;basicHttpBinding&quot;
        contract=
          &quot;Recipes.Contract.RecipeBookContract&quot; /&gt;
    &lt;/client&gt;
  &lt;/system.serviceModel&gt;
&lt;/configuration&gt;
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 9</td>
	</tr>
</table>

<p>The differences are subtle; instead of a services collection, there is a single client section, and the endpoint definition has a name. This name is used in the client program to identify the endpoint to which to connect.</p>

<p>Lastly, of course, we need code in the client application to set up the channel, talk to the service and consume the results, such as that in listing listing 10.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
static class ShakerClientProgram
{
  static int Main()
  {
    const string name = &quot;ShakerService&quot;;
    const string address 
       = &quot;http://localhost:5110&quot;;

    using( var channel = new ChannelFactory
       &lt; RecipeBookContract &gt;( name ) )
    {
      var recipes = channel.CreateChannel
         ( new EndpointAddress( address ) );
      recipes.Add(
        new DrinkDto{ Name = &quot;G&amp;T&quot;,
           Method = &quot;Mix with ice and lime&quot; },
        new[] {
          new IngredientDto{ Name = &quot;Gin&quot;,
          Amount =
          IngredientDto.Measurement.Measure,
          Qty = 2 },
          new IngredientDto{ Name = &quot;Tonic Water&quot;,
          Amount = IngredientDto.Measurement.Fill,
          Qty = 1 }
      } );
      foreach( var d in recipes.AllDrinks() )
      {
        Console.WriteLine( d.Name );
      }
      Console.WriteLine(&quot;Press [Enter] to exit&quot;);
      Console.ReadLine();
      return 0;
    }
  }
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 10</td>
	</tr>
</table>

<p>This code sets up a connection to the endpoint on which the server is listening using the name of the client-side endpoint definition in the configuration file, and uses the service contract. The <code>ChannelFactory</code> is parameterised with the contract interface type, associates it with the endpoint address specified, and uses the application config shown in listing 9 to configure the channel.</p>

<p>Client and server are separate programs, using WCF to communicate with each other. In this instance, they are console applications (for the server, the correct terminology is â€˜self-hostingâ€™), but could be Windows Forms, WPF or (for the server) an IIS-hosted web app.</p>

<p>Since they share the service contract definition in the <code>RecipeBookContract</code> interface, it makes sense to create a shared library which both console applications can reference. It would be possible to have the contract definition as a class in the server application, and have the client application reference the server assembly directly, but there are many reasons why this would be a bad idea; having one executable directly reference another is rarely a sign of good design.</p>

<p>Figure 1 shows the basic architecture of this application.</p>

<table class="sidebartable">
	<tr>
		<td><img src="http://accu.org/content/images/journals/ol113/Love/Love-1.svg"/></td>
	</tr>
	<tr>
		<td class="title">Figure 1</td>
	</tr>
</table>

<h2>Back on track</h2>

<p>Clearly, having the client side of the WCF application running as a process is less than ideal with respect to using it from other parts of your codebase. It would be better to make the client operate from a library. The problem with that is the channel configuration. The <code>ChannelFactory</code> shown in listing 10 is hard-wired to use the application configuration file. This is a convenience for the supposed default case (where the client is the application), but is here exposed as a liability. The superficial answer to that is to put all the WCF configuration into the <span class="filename">app.config</span> file of whatever application is hosting the client, and this works. However, it pollutes the applicationâ€™s configuration, and means that the client <em>must</em> be hosted in an executable.</p>

<p>An alternative to that would be to remove all configuration from the client-side of the WCF channel. You can create a bare-bones channel, and set properties on it within the code, thus removing the need for a configuration file. This solution has some attractions, of course, but sometimes being able to fiddle with the settings without having to recompile the code is useful, perhaps even necessary.</p>

<p>Fortunately, Microsoft provide a solution. The <code>ConfigurationChannelFactory</code> is very similar to <code>ChannelFactory</code> except that it accepts a <code>System.Configuration</code> object in its constructor<a href="#FN02"><sup>2</sup></a>. In conjunction with the almost impenetrable interfaces to the .Net application configuration system â€“ with which details I shall not bore you â€“ you can load any configuration file of the correct format at runtime. Armed with this, a library assembly can have its own configuration file, and load it internally to configure the WCF subsystem for an implementation of the client-facing interface.</p>

<p>The constructor shown in listing 11 shows how the configuration is loaded and associated with the channel. Setting the <code>ExeConfigFileName</code> property of the <code>filemap</code> object instructs the system to look for the file in the working directory. Other properties exist to tell it to look in various profile folders. The remainder of the class, in listing 12, adapts the WCF contract interfaceâ€™s methods and objects into the client interface. All calls to the WCF service are wrapped in a delegate call to a private method that captures the common error handling.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
public class RecipeBookClient : Recipes.RecipeBook
{
  public RecipeBookClient( string address )
  {
    const string name = &quot;ShakerService&quot;;
    var cfgMap = new ExeConfigurationFileMap
      { ExeConfigFilename 
        = &quot;RecipeBook.Client.Config&quot; };
    var config = ConfigurationManager
          .OpenMappedExeConfiguration
        ( cfgMap, ConfigurationUserLevel.None );
    channel = new ConfigurationChannelFactory
       &lt; RecipeBookContract &gt;
      ( name, config,
        new EndpointAddress( address ) );
    recipes = channel.CreateChannel();
  }
  private readonly ConfigurationChannelFactory
     &lt; RecipeBookContract &gt; channel;
  private readonly RecipeBookContract recipes;
  }
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 11</td>
	</tr>
</table>

<p>Of more interest at this point is the implementation of the <code>Drink</code> interface first shown in listing 1 used by the <code>RecipeBookClient</code> in listing 12 to adapt between the native and contract interfaces. The implementation is in listing 13. Precisely why this was an interface should now be clear. Being able to implement it independently to communicate with a WCF service has great benefits for efficiently and effectively exposing the <code>ServiceContract</code> interface and its collaborators. Figure 2 shows the new architecture.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
public IEnumerable&lt; Drink &gt; AllDrinks
{
  get { return Call( () =&gt; recipes.AllDrinks()
    .Select( d =&gt; new DrinkAdapter
       ( recipes, d ) ) ); }
}

public IEnumerable&lt; string &gt; AllIngredients
{
  get { return Call( () =&gt; 
    recipes.AllIngredients() ); }
}

public void Add( params Drink[] newDrinks )
{
  foreach( var drink in newDrinks )
  {
    Call( () =&gt;
      recipes.Add( new DrinkDto {
        Name = drink.Name,
        Method = drink.Method },
      drink.Ingredients.Select
         ( i =&gt; new IngredientDto {
        Name = i.Name,
        Amount = 
           ( IngredientDto.Measurement )i.Amount,
        Qty = i.Qty
      } ) ) );
  }
}

public IEnumerable&lt; Drink &gt; WithIngredients
   ( params string[] s )
{
  return Call( () =&gt; recipes.WithIngredients( s )
    .Select( d =&gt;
      new DrinkAdapter( recipes, d ) ) );
}

public ResultType Call&lt; ResultType &gt;
   ( Func&lt; ResultType &gt; method )
{
  var result = default( ResultType );
  Call( () =&gt; { result = method(); } );
  return result;
}

public void Call( Action method )
{
  try
  {
    method();
  }
  catch( FaultException x )
  {
    switch( x.Message )
    {
      case &quot;DuplicateDrink&quot;:
        throw new DuplicateDrinkException
           ( x.Message );
    }
    throw;
  }
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 12</td>
	</tr>
</table>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
public class DrinkAdapter : Drink
{
  public DrinkAdapter( RecipeBookContract recipes,
     DrinkDto drinkDto )
  {
    this.recipes = recipes;
    Name = drinkDto.Name;
    Method = drinkDto.Method;
  }

  public string Name { get; private set; }
  public string Method { get; private set; }
  public IEnumerable&lt; Ingredient &gt; Ingredients
  {
    get { return recipes.IngredientsOf( Name )
      .Select( i =&gt; new Ingredient(
        i.Name,
        ( Measurement )i.Amount,
        i.Qty ) ); }
  }

  private readonly RecipeBookContract recipes;
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 13</td>
	</tr>
</table>

<table class="sidebartable">
	<tr>
		<td><img src="http://accu.org/content/images/journals/ol113/Love/Love-2.svg"/></td>
	</tr>
	<tr>
		<td class="title">Figure 2</td>
	</tr>
</table>

<p>Itâ€™s now possible to use the client code from anywhere â€“ a hosting executable, part of a library of shared code, or a test case in a DLL. It still depends on having a running server process, so such a test isnâ€™t really stand-alone, but it does allow us to provoke the code that uses the server. One of the benefits of this is that it is a test of the client configuration â€“ a reasonably novel concept.</p>

<h2>Going off-road</h2>

<p>The next step is to try and isolate the server code into a shared library. The benefits here are largely about testing, but having the service code in a shared library allows you to defer the decision on whether to host it in a console application, a Windows Service or some other solution.</p>

<p>Moving the implementation of the <code>RecipeBookContract</code> from listing 8 into a shared library is easy enough: it can be copied as it stands, since it doesnâ€™t use any WCF objects directly.</p>

<p>As with the <code>ChannelFactory</code> in the original client code (listing 10), the <code>ServiceHost</code> object in the server code (listing 7) is hard-wired to use the <span class="filename">app.config</span> for the WCF settings. There isnâ€™t a corresponding <code>ConfigurationServiceHost</code> class which can be used in place of it, but we can derive from it and override itâ€™s default behaviour. Listing 14 shows the new class.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
public class RecipeBookHost : ServiceHost
{
  public RecipeBookHost( string address )
  {
    var cfgMap = new ExeConfigurationFileMap
      { ExeConfigFilename =
        &quot;RecipeBook.Server.config&quot; };
    config = ConfigurationManager
      .OpenMappedExeConfiguration
      ( cfgMap, ConfigurationUserLevel.None );
    var service = new RecipeBookService();
      InitializeDescription( service,
      new UriSchemeKeyedCollection( new Uri
         ( address ) ) );
      Open();
  }

  protected override void ApplyConfiguration()
  {
    var section =
       ServiceModelSectionGroup.GetSectionGroup
       ( config );
    if( section == null )
      throw new ConfigurationErrorsException
        ( &quot;Failed to find service model
          configuration&quot; );
    foreach( ServiceElement service in
       section.Services.Services )
    {
      if( service.Name ==
         Description.ConfigurationName )
        base.LoadConfigurationSection
           ( service );
      else
        throw new ConfigurationErrorsException
           ( &quot;No match for description in
           Service model config&quot; );
    }
  }
  private readonly Configuration config;
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 14</td>
	</tr>
</table>

<p>The constructor sets up the configuration in much the same way as the <code>RecipeBook</code>-<code>Client</code> from listing 11.</p>

<p>The important method is the overridden <code>ApplyConfiguration</code>. This pulls the required WCF settings out of the configuration object and calls the base classâ€™s <code>LoadConfigurationSection</code> to apply those settings.</p>

<p><code>ApplyConfiguration</code> is called from the <code>InitializeDescription</code> invocation in the constructor. If this hasnâ€™t been done before <code>Open</code> is called, then the <span class="filename">app.config</span> is automatically loaded, so the order of operations is crucial. This class can be used in a hosting application such as that shown in listing 15, or (for example) a test case.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
static class ShakerServiceProgram
{
  static int Main()
  {
    const string address =
       &quot;http://localhost:5110&quot;;
    using( var host =
       new RecipeBookHost( address ) )
    {
        Console.WriteLine( &quot;v1 Shaker Service
           running. Press [Enter] to close&quot; );
        Console.ReadLine();
    }
    return 0;
  }
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 15</td>
	</tr>
</table>

<p>Figure 3 shows the architecture of the client/server portion now.</p>

<table class="sidebartable">
	<tr>
		<td><img src="http://accu.org/content/images/journals/ol113/Love/Love-3.svg"/></td>
	</tr>
	<tr>
		<td class="title">Figure 3</td>
	</tr>
</table>

<h2>Tests</h2>

<p>With the new server and client library code weâ€™ve now developed, itâ€™s possible to write a truly automated test that has no requirements on external running code. Just as importantly, we can test them independently of any other code in an application (but not independently of each other - the client code <em>must</em> have a server to talk to). listing 16 shows a very simple test that creates an instance of the server, an instance of the client, and asserts that they can communicate. This is effectively testing the configurations of both client and server (an important thing, to be sure), but a much more interesting test would be to reproduce the tests we performed at the very beginning - by using the <code>DrinksCabinet</code> object.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
[TestFixture, Explicit, Category(&quot;Service&quot;)]
public class ClientServiceTest
{
  [Test]
  public void
    ClientAndServiceStartAndCanCommunicate()
  {
    const string address 
       = &quot;http://localhost:5110&quot;;
    using( var host = new RecipeBookHost
       ( address ) )
    using( var recipes = new RecipeBookClient
       ( address ) )
    {
      Assert.IsNotNull( host );
      Assert.IsNotNull( recipes );
      Assert.DoesNotThrow( () =&gt; {
        var x = recipes.AllDrinks; } );
    }
  }
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 16</td>
	</tr>
</table>

<p>Recall from listing 2 that <code>DrinksCabinet</code> accepts an instance of the <code>RecipeBook</code> interface. Our new client code implements that interface, and adapts it to the WCF contract. Itâ€™s now possible to reproduce the <code>DrinksCabinetTests</code> from listing 3 but instead of using an instance of <code>LocalRecipeBook</code>, use an instance of <code>RecipeBook-Client</code>, as shown in listings 11 and 12.</p>

<p>Listing 17 shows the new tests using a locally running instance of the server, and the WCF implementation of the <code>RecipeBook</code> interface. Of course, the service implementation of the <code>RecipeBook</code> interface, and its client-side counterpart, can be tested in a similar way.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
[ TestFixture, Explicit, Category( &quot;Service&quot; ) ]
public class ServiceDrinksCabinetTests
{
  private RecipeBookHost host;
  private Recipes.RecipeBook recipes;
  [ SetUp ]
  public void Start()
  {
    const string address 
       = &quot;http://localhost:5110&quot;;
    host = new RecipeBookHost( address );
    recipes = new RecipeBookClient( address );
  }

  [ TearDown ]
  public void End()
  {
    recipes.Dispose();
    host.Close();
  }

  [Test]
  public void EmptyCabinetHasNoIngredients()
  {
    var cabinet = new DrinksCabinet(recipes);
    var results = cabinet.Ingredients;
    Assert.IsFalse(results.Any());
  }

  [Test]
  public void CanLocateSpecificDrinkByName()
  {
    var cabinet = new DrinksCabinet(recipes);
    var expected = new LocalDrink(&quot;a&quot;, &quot;&quot;, new[] {
      new Ingredient( &quot;1&quot;, Measurement.Tsp, 1 )
    });
    var error = new LocalDrink(&quot;b&quot;, &quot;&quot;, new[] {
      new Ingredient( &quot;2&quot;, Measurement.Tsp, 1 )
    });
    recipes.Add(expected, error);
    var result = cabinet.Find(expected.Name);
    Assert.AreEqual(expected, result);
  }

  [Test]
  public void CanFilterDrinksOnNotSpecified()
  {
    var cabinet = new DrinksCabinet(recipes);
    var expected = new LocalDrink(&quot;a&quot;, &quot;&quot;, new[] {
      new Ingredient( &quot;1&quot;, Measurement.Tsp, 1 )
    });
    var error = new LocalDrink(&quot;b&quot;, &quot;&quot;, new[] {
      new Ingredient( &quot;2&quot;, Measurement.Tsp, 1 )
    });
    recipes.Add(expected, error);
    var results = cabinet.NotContaining(&quot;2&quot;);
    Assert.AreEqual(expected, results.Single());
  }
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 17</td>
	</tr>
</table>

<h2>Conclusion</h2>

<p>In this article, Iâ€™ve described a simple application, beginning from a basic native (and testable) interface and implementation, then showing how that interface and its collaborators could be transposed into a WCF service application. The flaws in the direct translation using a process to represent the server and client sides were that the implementation code wasnâ€™t shareable easily with other applications, and that it wasnâ€™t easily (and automatically) testable. The solution to both of those problems involved investigating WCF and by necessity, the .Net Configuration management systems to allow both server implementation and the client proxy adapter code to be exposed from their own shared assembly using their own configurations for the WCF subsystem. Being able to automatically test the WCF portions of your application should give you greater confidence that it works correctly â€“ including the fact that the configuration is correct and sufficient â€“ without having to run your application end-to-end to provoke it. Of course, that shouldnâ€™t stop you from performing end-to-end testing!</p>

<h2>Acknowledgements</h2>

<p>Many thanks to Frances Buontempo for reading and commenting on initial drafts of this, and to Roger Orr and Chris Oldwood for valuable feedback on it.</p>

<h2>References and source</h2>

<p class="bibliomixed"><a id="[Fowler]"></a>[Fowler]  Martin Fowler. Data transfer object. Technical report,<a href="http://martinfowler.com/eaaCatalog/dataTransferObject.html">http://martinfowler.com/eaaCatalog/dataTransferObject.html</a>.</p>

<p class="bibliomixed"><a id="[Fowler02]"></a>[Fowler02]  Martin Fowler. <em>Patterns of Enterprise Application Architecture</em>. AddisonWesley, 2002.</p>

<p class="bibliomixed"><a id="[Love]"></a>[Love]  Source code at: <a href="https://github.com/essennell/WcfTestingSecrets">https://github.com/essennell/WcfTestingSecrets</a></p>

<p class="bibliomixed"><a id="[MSDN]"></a>[MSDN]  MSDN(WCF). Windows communication foundation reference. Technical report, Microsoft, <a href="http://msdn.microsoft.com/en-us/library/dd456779.aspx">http://msdn.microsoft.com/en-us/library/dd456779.aspx</a>.</p>

<p class="bibliomixed"><a id="[Resnick08]"></a>[Resnick08] Bowen Resnick, Crane. <em>Essential Windows Communication Foundation</em>. Microsoft .Net Development Series. Addison Wesley, 2008. .Net 3.5.</p>

<p class="bibliomixed"><a id="[WCF]"></a>[WCF]  Microsoft(WCF). Windows communication foundation msdn articles. Technical report, Microsoft, <a href="http://msdn.microsoft.com/en-us/library/dd560536.aspx">http://msdn.microsoft.com/en-us/library/dd560536.aspx</a>.</p>

<p class="footnote"></p>
<ol>
	<li><a id="FN01"></a>Itâ€™s not entirely specious; the new interface allows ingredients to be lazy-loaded on demand.</li>
	<li><a id="FN02"></a>It is not hard to argue that making this the default, or an overloaded constructor on ChannelFactory, might be better than a separate type.</li>
</ol>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
