Monthly Archives: July 2014

Query expressions in F#

Not quite the same as LINQ in syntax terms, F# includes query expressions which are in essence it’s own style of LINQ.

If we assume we have a simple example of some code in C# which uses LINQ to get strings from an array where their length is 3. In C# this might look like the following

string[] sample = {"One", "Two", "Three", "Four", "Five"};

IEnumerable<string> result = 
   from s in sample 
   where s.Length == 3 
   select s;

Note: I’ve purposefully put each part of the LINQ query on a new line for easier comparison with the equivalent F# query expression.

So here’s the same in F#

let sample = [| "One" ; "Two" ; "Three" ; "Four" ; "Five" |]

let result = query {
   for s in sample do
   where (s.Length = 3)
   select s
}

The main differences are the use of the query expression syntax query { … } and the use of the for s in sample do instead of from s in sample

References

See Query Expressions (F#) for a few examples of different query expressions and how they relate to SQL queries (and more).

Type extensions in F#

We can extend F# types by adding the equivalent of C# extension methods or something similar to partial classes in C#.

Let’s not waste time but instead get straight into the code

The type extension syntax is taken from Type Extensions (F#) which is well worth a read

type typename with
   member self-identifier.member-name =
      body
   ...
   [ end ]

[ end ] is optional in lightweight syntax.

Here’s an example of a type method for the System.String type, we’re going to add a simple Reverse function

type System.String with
    member __.Reverse = String(__.ToCharArray() |> Array.rev)

also we can create new functions like adding to a partial class

type System.String with
    member __.Append s = __.Substring(0) + s

A slightly pointless method, but at the time of writing I couldn’t think of anything more interesting.

Creating an F# WinForms application

I wanted to mess around with the FSharp.Charting library and needed to create an F# WinForms application to use it.

It’s pretty simple but there’s no template by default in Visual Studio (well not in 2013).

So here the steps to create a WinForms F# application

  • Create a new Project and select F# Application
  • This will be a console application, so next select the project properties and change the Application | Output type from Console Application to Windows Application
  • Add a reference to System.Windows.Forms
  • Change your main function to look like the following
    open System
    open System.Windows.Forms
    
    [<EntryPoint>]
    [<STAThread>]
    let main argv = 
    
        Application.EnableVisualStyles()
        Application.SetCompatibleTextRenderingDefault false
    
        use form = new Form()
    
        Application.Run(form);
    
        0 
    

Obviously this example shows us creating an empty Form. By default F# (at least in Visual Studio 2013) doesn’t include WinForm design surfaces or the likes. So it’s probably best to design your forms in a C# library and reference from your F# applications. Or, alternatively, you can hand code your WinForms.

A quick example of using FSharp.Charting

This is not mean’t to be anything other than a quick example, but as I wanted to get a F# WinForms application specifically to try out some FSharp.Charting, here’s the steps…

  • Using NuGet add a reference to FSharp.Charting to your project (developed above)
  • Add open FSharp.Charting to your Program.fs file
  • I’m going to simple use some code from the FSharp.Charting github samples, so first we need to add a reference to System.Drawing
  • Add a reference to System.Windows.Forms.DataVisualization
  • Finally change the Application.Run method to look like the following
    Application.Run (Chart.Line([ for x in 0 .. 10 -> x, x*x ]).ShowChart())
    

Now your code should look like the following

open System
open System.Windows.Forms
open FSharp.Charting

[<EntryPoint>]
[<STAThread>]
let main argv = 

    Application.EnableVisualStyles()
    Application.SetCompatibleTextRenderingDefault false

    Application.Run (Chart.Line([ for x in 0 .. 10 -> x, x*x ]).ShowChart())

    0

and this should (when run) display a line chart.

Operator overloading in F#

More adventures with F#…

Operator overloading is documented perfectly well in Operator Overloading (F#) but to summarize I’ve created this post…

Operators in F# can be overloaded at the class, record type or global level.

Overloading an operator on a class or record type

Let’s look at the syntax for overloading an operator on a class or record type.

Note: Reproduced from the Operator Overloading (F#) page

static member (operator-symbols) (parameter-list> =
    method-body

Overloading an operator which is globally accessible

Let’s look at the syntax for overloading an operator at a global level.

Note: Reproduced from the Operator Overloading (F#) post

let [inline] (operator-symbols) parameter-list = 
    function-body

More…

You can overload the “standard” operators but you can also create your own operators. For example FAKE creates it’s own global operator to combine two file paths using the @@ operator

The below is taken from the FAKE source code available in github

let inline (@@) path1 path2 = combinePaths path1 path2

As it’s pretty obvious, this is a global level overload of a newly created operator, the @@ which takes two parameters.

Where an operator may be used for binary or unary (infix or prefix), such as + or – (+., -., &, &&, %, and %% may also be used for infix or prefix operators) we need to prefix the operator with a tilde ~, hence to overload the + and use as a unary operator we’d write something like

let inline (~+) x = [ x ]

// in use we'd have

let v = + "hello"

Whereas using the + as a binary operator we’d write something like

let inline (+) x y = [ x, y ]

// in use we'd have

let v = "hello" + "world"

If you’re coming from C# to F# you’ll have already noticed the “funky” set of operators that F# supports. As already shown with the @@ operator sample (taken from FAKE) you can combine operators to produce all sorts of new operators, for example

let (<==>) x  y = [ x, y]

Describing my tables, views, stored procs etc.

Having become a little too reliant (at times) on great GUI tools for interacting with my databases, I had to remind myself it’s pretty easy to use code to do this, sure good old Aqua Studio does it with CTRL+D on a data object in the editor, or both Oracle SQL Developer and the MS SQL Server Management Studio allow us to easily drill down the item in the data object tree, but still. Here it is in code…

Tables and views

For Oracle

desc TableName

For SQL Server

exec sp_columns TableName

Stored Procs

For Oracle

desc StoredProceName

For SQL Server

exec sp_help StoredProceName

In fact sp_help can be used for Stored Procs and Tables/Views.

Entity Framework & AutoMapper with navigational properties

I’ve got a webservice which uses EF to query SQL Server for data. The POCO’s for the three tables we’re interested in are listed below:

public class Plant
{
   public int Id { get; set; }

   public PlantType PlantType { get; set; }
   public LifeCycle LifeCycle { get; set; }

  // other properties
}

public class PlantType
{
   public int Id { get; set; }
   public string Name { get; set; }
}

public class LifeCycle
{
   public int Id { get; set; }
   public string Name { get; set; }
}

The issue is that when a new plant is added (or updated for that matter) using the AddPlant (or UpdatePlant) method we need to ensure EF references the LifeCycle and PlantType within its context. i.e. if we try to simply call something like

context.Plants.Add(newPlant);

then (and even though the LifeCycle and PlantType have an existing Id in the database) EF appears to create new PlantTypes and LifeCycles. Thus giving us multiple instances of the same LifeCycle or PlantType name. For the update method I’ve been using AutoMapper to map all the properties, which works well except for the navigational properties. The problem with EF occurs.

I tried several ways to solve this but kept hitting snags. For example we need to get the instance of the PlantType and LifeCycle from the EF context and assign these to the navigational properties to solve the issue of EF adding new PlantTypes etc. I wanted to achieve this in a nice way with AutoMapper. By default the way to create mappings in AutoMapper is with the static Mapper class which suggests the mappings should not change based upon the current data, so what we really need is to create mappings for a specific webservice method call.

To create an instance of the mapper and use it we can do the following (error checking etc. remove)

using (PlantsContext context = new PlantsContext())
{
   var configuration = new ConfigurationStore(
                     new TypeMapFactory(), MapperRegistry.AllMappers());
   var mapper = new MappingEngine(configuration);
   configuration.CreateMap<Plant, Plant>()
         .ForMember(p => p.Type, 
            c => c.MapFrom(pl => context.PlantTypes.FirstOrDefault(pt => pt.Id == pl.Type.Id)))
	 .ForMember(p => p.LifeCycle, 
            c => c.MapFrom(pl => context.LifeCycles.FirstOrDefault(lc => lc.Id == pl.LifeCycle.Id)));

   //... use the mapper.Map to map our data and then context.SaveChanges() 
}

So it can be seen that we can now interact with the instance of the context to find the PlantType and LifeCycle to map and we do not end up trying to create mappings on the static class.

My first attempt as implementing a Computational Expression in F#

So this is my first attempt at implementing a computational expression in F#. I’m not going to go into definitions or the likes as to what computational expressions are as there are far better posts out there on this subject than I could probably write, at this time. I’ll list some in a “further reading” section at the end of the post.

What I’m going to present here is a builder which really just creates a list of names – nothing particularly clever – but it gives a basic idea on getting started with computational expressions (I hope).

So first off we need to create a builder type, mine’s called CurveBuilder

type Items = Items of string list

type CurveBuilder() =
    member this.Yield (()) = Items []

    [<CustomOperation ("create", MaintainsVariableSpace = true)>]
    member this.Create (Items sources, name: string) = 
        Items [ yield! sources
                yield name ]

As this is just a simple demo, the only thing I’m doing is creating a list of strings which you would be correct in thinking that I could do easier using a collection class, but I’m really just interested in seeing the builder and it’s interactions without too much clutter, so go with me on this one…

Before we discuss the builder code, let’s take a look at how we’d use a builder in our application

let builder = CurveBuilder()

let curves = 
   builder {
      create "risky_curve1.gbp"
      create "risky_curve2.usd"
   }

In this code we first create an instance of a CurveBuilder, then when we use the builder to create a list of the curves. The Yield method is first called on the CurveBuilder, returning an empty Items value. Subsequent calls to the create method then call the Create method of the CurveBuilder and, as can be seen, create a new Items value containing the previous Items plus our new curve name.

Simple enough but surely there’s more to this than meets the eye

The example above is a minimal implementation, of course, of a builder. You’ll notice that we have an attribute on one method (the Create method) and not on the Yield method.

So the attribute CustomOperation is used on a member of a builder to create new “query operators”. Basically it extends the builder functionality with new operators named whatever you want to name them.

On the other hand the Yield method is a “standard” builder method. There are several other methods which F# knows about implicitly within a builder class, including Return, Zero, Bind, For, YieldFrom, ReturnFrom, Delay, Combine, Run and more, see Computation Expressions (F#)
for a full list of “built-in workflows”. With these we can obviously produce something more complex than the example presented in this post – which is in essence a glorified “list” builder with snazzy syntax.

Discriminated Union gotcha

One thing I got caught out with from the above code is that I wanted to simply list the curves I’d created but couldn’t figure out how to “deconstruct” the discriminated union

type Items = Items of string list

to a simple string list – at this point I claim ignorance as I’m not using F# as much as I’d like so am still fairly inexperienced with it.

My aim was to produce something like this

for curve in curves do
   printfn "Curve: %s" curve

but this failed with the error The type ‘Items’ is not a type whose values can be enumerated with this syntax, i.e. is not compatible with either seq<_>, IEnumerable<_> or IEnumerable and does not have a GetEnumerator method

I need to in essence disconnect the Items from the string list, to achieve this I found the excellent post Discriminated Unions.

The solution is as follows

let (Items items) = curves

for curve in items do
    printfn "Curve: %s" curve

Note: the let (Items items) = curves

Further Reading
Implementing a builder: Zero and Yield
Implementing a builder: Combine
Implementing a builder: Delay and Run
Implementing a builder: Overloading
Implementing a builder: Adding laziness
Implementing a builder: The rest of the standard methods

Computation Expressions (F#)

The Vending Machine Change problem

I was reading about the “Vending Machine Change” problem the other day. This is a well known problem, which I’m afraid to admit I had never heard of, but I thought it was interesting enough to take a look at now.

Basically the problem that we’re trying to solve is – you need to write the software to calculate the minimum number of coins required to return an amount of change to the user. In other words if a vending machine had the coins 1, 2, 5 & 10, what is the minimum number of coins required to make up the change of 43 pence (or whatever units of currency you want to use).

The coin denominations should be supplied, so the algorithm is not specific to the UK or any other country and the amount in change should also be supplied to the algorithm.

First Look

This is a standard solution to the Vending Machine problem (please note: this code is all over the internet in various languages, I’ve just made a couple of unimpressive changes to it)

static int Calculate(int[] coins, int change)
{
   int[] counts = new int[change + 1];
   counts[0] = 0;

   for(int i = 1; i <= change; i++)
   {
      int count = int.MaxValue;
      foreach(int coin in coins)
      {
         int total = i - coin;
         if(total >= 0 && count > counts[total])
         {
            count = counts[total];
         }
      }
      counts[i] = (count < int.MaxValue) ? count + 1 : int.MaxValue;
   }
   return counts[change];
}

What happens in this code is that we create an array counts which will contains the minimum number of coins for each value between 1 and the amount of change required. We use the 0 index as a counter start value (hence we set counts[0] to 0).

Next we look through each possible change value calculating the number of coins required to make up each value, we use the int.MaxValue to indicate no coins could be found to match the amount of change.

This algorithm assumes an infinite number of coins of each denomination, but this is obviously an unrealistic scenario, so let’s have a look at my attempt to solve this problem for a finite number of each coin.

Let’s try to make things a little more complex

So, as mentioned above, I want to now try to calculate the minimum number of coins to produce the amount of change required, where the number of coins of each denomination is finite.

Let’s start by defining a Coin class

public class Coin
{
   public Coin(int denomition, int count)
   {
      Denomination = denomition;
      Count = count;
   }

   public int Denomination { get; set; }
   public int Count { get; set; }
}

Before I introduce my attempt at a solution, let’s write some tests, I’ve not got great names for many of the tests, they’re mainly for me to try different test scenarios out, but I’m sure you get the idea.

public class VendingMachineTests
{
   private bool Expects(IList<Coin> coins, int denomination, int count)
   {
      Coin c = coins.FirstOrDefault(x => x.Denomination == denomination);
      return c == null ? false : c.Count == count;
   }

   [Fact]
   public void Test1()
   {
      List<Coin> coins = new List<Coin>
      {
         new Coin(10, 100),
         new Coin(5, 100),
         new Coin(2, 100),
         new Coin(1, 100),
      };

      IList<Coin> results = VendingMachine.Calculate(coins, 15);
      Assert.Equal(2, results.Count);
      Assert.True(Expects(results, 10, 1));
      Assert.True(Expects(results, 5, 1));
   }

   [Fact]
   public void Test2()
   {
      List<Coin> coins = new List<Coin>
      {
         new Coin(10, 100),
         new Coin(5, 100),
         new Coin(2, 100),
         new Coin(1, 100),
      };

      IList<Coin> results = VendingMachine.Calculate(coins, 1);
      Assert.Equal(1, results.Count);
      Assert.True(Expects(results, 1, 1));
   }

   [Fact]
   public void Test3()
   {
      List<Coin> coins = new List<Coin>
      {
         new Coin(10, 1),
         new Coin(5, 1),
         new Coin(2, 100),
         new Coin(1, 100),
      };

      IList<Coin> results = VendingMachine.Calculate(coins, 20);
      Assert.Equal(4, results.Count);
      Assert.True(Expects(results, 10, 1));
      Assert.True(Expects(results, 5, 1));
      Assert.True(Expects(results, 2, 2));
      Assert.True(Expects(results, 1, 1));
   }

   [Fact]
   public void NoMatchDueToNoCoins()
   {
      List<Coin> coins = new List<Coin>
      {
         new Coin(10, 0),
         new Coin(5, 0),
         new Coin(2, 0),
         new Coin(1, 0),
      };

      Assert.Null(VendingMachine.Calculate(coins, 20));
   }

   [Fact]
   public void NoMatchDueToNotEnoughCoins()
   {
      List<Coin> coins = new List<Coin>
      {
         new Coin(10, 5),
         new Coin(5, 0),
         new Coin(2, 0),
         new Coin(1, 0),
      };

      Assert.Null(VendingMachine.Calculate(coins, 100));
   }

   [Fact]
   public void Test4()
   {
      List<Coin> coins = new List<Coin>
      {
         new Coin(10, 1),
         new Coin(5, 1),
         new Coin(2, 100),
         new Coin(1, 100),
      };

      IList<Coin> results = VendingMachine.Calculate(coins, 3);
      Assert.Equal(2, results.Count);
      Assert.True(Expects(results, 2, 1));
      Assert.True(Expects(results, 1, 1));
   }

   [Fact]
   public void Test5()
   {
      List<Coin> coins = new List<Coin>
      {
         new Coin(10, 0),
         new Coin(5, 0),
         new Coin(2, 0),
         new Coin(1, 100),
      };

      IList<Coin> results = VendingMachine.Calculate(coins, 34);
      Assert.Equal(1, results.Count);
      Assert.True(Expects(results, 1, 34));
   }

   [Fact]
   public void Test6()
   {
      List<Coin> coins = new List<Coin>
      {
         new Coin(50, 2),
         new Coin(20, 1),
         new Coin(10, 4),
         new Coin(1, int.MaxValue),
      };

      IList<Coin> results = VendingMachine.Calculate(coins, 98);
      Assert.Equal(4, results.Count);
      Assert.True(Expects(results, 50, 1));
      Assert.True(Expects(results, 20, 1));
      Assert.True(Expects(results, 10, 2));
      Assert.True(Expects(results, 1, 8));
   }

   [Fact]
   public void Test7()
   {
      List<Coin> coins = new List<Coin>
      {
         new Coin(50, 1),
         new Coin(20, 2),
         new Coin(15, 1),
         new Coin(10, 1),
         new Coin(1, 8),
      };

      IList<Coin> results = VendingMachine.Calculate(coins, 98);
      Assert.Equal(3, results.Count);
      Assert.True(Expects(results, 50, 1));
      Assert.True(Expects(results, 20, 2));
      Assert.True(Expects(results, 1, 8));
   }
}

Now, here’s the code for my attempt at solving this problem, it uses a “Greedy” algorithm, i.e. trying to find the largest coin(s) first. The code therefore requires that the coins are sorted largest to smallest, I have not put the sort within the Calculate method because it’s recursively called, so it’s down to the calling code to handle this.

There may well be a better way to implement this algorithm, obviously one might prefer to remove the recursion (I may revisit the code when I have time to implement that change).

public static class VendingMachine
{
   public static IList<Coin> Calculate(IList<Coin> coins, int change, int start = 0)
   {
      for (int i = start; i < coins.Count; i++)
      {
         Coin coin = coins[i];
         // no point calculating anything if no coins exist or the 
         // current denomination is too high
         if (coin.Count > 0 && coin.Denomination <= change)
         {
            int remainder = change % coin.Denomination;
            if (remainder < change)
            {
               int howMany = Math.Min(coin.Count, 
                   (change - remainder) / coin.Denomination);

               List<Coin> matches = new List<Coin>();
               matches.Add(new Coin(coin.Denomination, howMany));

               int amount = howMany * coin.Denomination;
               int changeLeft = change - amount;
               if (changeLeft == 0)
               {
                   return matches;
               }

               IList<Coin> subCalc = Calculate(coins, changeLeft, i + 1);
               if (subCalc != null)
               {
                  matches.AddRange(subCalc);
                  return matches;
               }
            }
         }
      }
      return null;
   }
}

Issues with this solution

Whilst this solution does the job pretty well, it’s not perfect. If we had the coins, 50, 20, 11, 10 and 1 the optimal minimum number of coins to find the change for 33 would be 3 * 11 coins. But in the algorithm listed above, the result would be 1 * 20, 1 * 11 and then 2 * 1 coins.

Ofcourse the above example assumed we have 3 of the 11 unit coins in the Vending machine

To solve this we could call the same algorithm but for each call we remove the largest coin type each time. Let’s look at this by first adding the unit test

[Fact]
public void Test8()
{
   List<Coin> coins = new List<Coin>
   {
      new Coin(50, 1),
      new Coin(20, 2),
      new Coin(11, 3),
      new Coin(10, 1),
      new Coin(1, 8),
   };

   IList<Coin> results = VendingMachine.CalculateMinimum(coins, 33);
   Assert.Equal(1, results.Count);
   Assert.True(Expects(results, 11, 3));
}

To just transition the previous solution to the new improved solution, we’ve simply added a new method named CalculateMinimum. The purpose of this method is to try and find the best solution by calculate with all coins, then we reduce the types of available coins by remove the largest coin, then find the best solution, then remove the next largest coin and so on. Here’s some code which might better demonstrate this

public static IList<Coin> CalculateMinimum(IList<Coin> coins, int change)
{
   // used to store the minimum matches
   IList<Coin> minimalMatch = null;
   int minimalCount = -1;

   IList<Coin> subset = coins;
   for (int i = 0; i < coins.Count; i++)
   {
      IList<Coin> matches = Calculate(subset, change);
      if (matches != null)
      {
         int matchCount = matches.Sum(c => c.Count);
         if (minimalMatch == null || matchCount < minimalCount)
         {
            minimalMatch = matches;
            minimalCount = matchCount;
         }
      }
      // reduce the list of possible coins
      subset = subset.Skip(1).ToList();
   }

   return minimalMatch;
}

Performance wise, this (in conjunction with the Calculate method) are sub-optimal if we needed to calculate such minimum numbers of coins many times in a short period of time. A lack of state means we may end up calculating the same change multiple times. Ofcourse we might save such previous calculations and first check whether the algorithm already has a valid solution each time we calculate change if performance was a concern and/or me might calculate a “standard” set of results at start up. For example if we’re selling can’s of drinks for 80 pence we could pre-calculate change based upon likely inputs to the vending machine, i.e. 90p, £1 or £2 coins.

On and we might prefer to remove to use of the Linq code such as Skip and ToList to better utilise memory etc.

References

http://onestopinterviewprep.blogspot.co.uk/2014/03/vending-machine-problem-dynamic.html
http://codercareer.blogspot.co.uk/2011/12/no-26-minimal-number-of-coins-for.html
http://techieme.in/techieme/minimum-number-of-coins/
http://www.careercup.com/question?id=15139685

Adding data to WCF headers

As I’ve covered this subject using WSE3, now to look at adding an SSO token to a WCF header.

Configuration

In your App.config you’ve probably got something like

<system.serviceModel>
   <client configSource="Config\servicemodel-client-config.xml" />
   <bindings configSource="Config\servicemodel-bindings-config.xml" />
</system.serviceModel>

We’re going to add two more configuration files, as follows

<system.serviceModel>
   <client configSource="Config\servicemodel-client-config.xml" />
   <bindings configSource="Config\servicemodel-bindings-config.xml" />
   <!-- Additions -->
   <behaviors configSource="Config\servicemodel-behaviors-config.xml" />
   <extensions configSource="Config\servicemodel-extensions-config.xml" />
</system.serviceModel>

As the names suggest, these file will include the config for behaviors and extensions.

Let’s take a look at the servicemodel-behaviors-config.xml first

<?xml version="1.0" encoding="utf-8" ?>
<behaviors>
   <endpointBehaviors>
      <behavior name="serviceEndpointBehaviour">
         <ssoEndpointBehaviorExtension />
         <!-- insert any other behavior extensions here -->
      </behavior>
   </endpointBehaviors>
</behaviors>

Now we need to actually define what implements ssoEndpointBehaviorExtension. So in the servicemodel-extensions-config.xml configuration, we might have something like the following

<?xml version="1.0" encoding="utf-8" ?>
<extensions>
   <behaviorExtensions>
      <add name="ssoEndpointBehaviorExtension"
            type="SsoService.SsoEndpointBehaviorExtensionElement, SsoService"/>
      <!-- insert other extensions here -->
   </behaviorExtensions>
</extensions>

So as we can see, the ssoEndpointBehaviorExtension behavior is associated with the SsoService assembly and the type SsoEndpointBehaviorExtensionElement.

Implementing the behavior/extension

Unlike WSE3 we do not need to use an attribute to associate the extension with a service call.

Let’s start by looking at the SsoEndpointBehaviorExtensionElement behavior extension.

public class SsoEndpointBehaviorExtensionElement : BehaviorExtensionElement
{
   public override Type BehaviorType
   {
      get { return typeof(SsoEndpointBehavior); }
   }
   
   protected override object CreateBehavior()
   {
      return new SsoEndpointBehavior();
   }
}

The code above relates to the actual extension element, so really just creates the actual behavior when required. Here’s the SsoEndpointBehavior.

public class SsoEndpointBehavior : IEndpointBehavior
{
   public void AddBindingParameters(ServiceEndpoint endpoint, 
                 BindingParameterCollection bindingParameters)
   {
   }

   public void ApplyClientBehavior(ServiceEndpoint endpoint, 
                 ClientRuntime clientRuntime)
   {
      clientRuntime.MessageInspectors.Add(new SsoMessageInspector());
   }

   public void ApplyDispatchBehavior(ServiceEndpoint endpoint, 
                 EndpointDispatcher endpointDispatcher)
   {
   }

   public void Validate(ServiceEndpoint endpoint)
   {
   }
}

This code simply adds the inspector to the message inspector. Finally let’s look at the code that actual intercepts the send requests to add the SSO token to the header.

public class SsoMessageInspector : IClientMessageInspector
{
   public object BeforeSendRequest(ref Message request, IClientChannel channel)
   {
      request.Headers.Add(MessageHeader.CreateHeader("ssoToken", 
              String.Empty, 
              SsoManager.TokenString);
      return null;
   }

   public void AfterReceiveReply(ref Message reply, object correlationState)
   {
   }
}

In the above code, we create an addition to the message header, with the name “ssoToken” followed by any namespace and then the value we wish to store with the header item. In this case our SSO token.

Creating a text templating engine Host

I’m in the process of creating a little application to codegen some source code for me from an XML schema (yes I can do this with xsd but I wanted the code to be more configurable). Instead of writing my own template language etc. I decided to try and leverage the T4 templating language.

I could simply write some code that can be called from a T4 template, but I decided it would be nicer if the codegen application simply acted as a host to the T4 template and allowed the template to call code on the host, so here’s what I did…

Running a T4 template from your application

The first thing I needed was to be able to actually run a T4 template. To do this you’ll need to add the following references

  • Microsoft.VisualStudio.TextTemplating.11.0
  • Microsoft.VisualStudio.TextTemplating.Interfaces10.0
  • Microsoft.VisualStudio.TextTemplating.Interfaces.11.0

Obviously these are the versions at the time of writing, things may differ in the future.

Next we need to instantiate the T4 engine, this is achieved by using the Microsoft.VisualStudio.TextTemplating namespace and with the following code

Engine engine = new Engine();
string result = engine.ProcessTemplate(File.ReadAllText("sample.tt"), host);

Note: The host will be supplied by us in the next section and obviously “sample.tt” would be supplied at runtime in the completed version of the code.

So, here we create a Engine and supply the template string and host to the ProcessTemplate method. The result of this call is the processed template.

Creating the host

Our host implementation will need to derive from MarshalByRefObject and implement the ITextTemplatingEngineHost interface.

Note: See Walkthrough: Creating a Custom Text Template Host for more information of creating a custom text template.

What follows is a basic implementation of the ITextTemplatingEngineHost based upon the Microsoft article noted above.

public class TextTemplatingEngineHost : MarshalByRefObject, ITextTemplatingEngineHost
{
   public virtual object GetHostOption(string optionName)
   {
      return (optionName == "CacheAssemblies") ? (object)true : null;
   }

   public virtual bool LoadIncludeText(string requestFileName, 
            out string content, out string location)
   {
      content = location = String.Empty;

      if (File.Exists(requestFileName))
      {
         content = File.ReadAllText(requestFileName);
         return true;
      }
      return false;
   }

   public virtual void LogErrors(CompilerErrorCollection errors)
   {
   }

   public virtual AppDomain ProvideTemplatingAppDomain(string content)
   {
      return AppDomain.CreateDomain(&quot;TemplatingHost AppDomain&quot;);
   }

   public virtual string ResolveAssemblyReference(string assemblyReference)
   {
      if (File.Exists(assemblyReference))
      {
         return assemblyReference;
      }

      string candidate = Path.Combine(Path.GetDirectoryName(TemplateFile), 
            assemblyReference);
      return File.Exists(candidate) ? candidate : String.Empty;
   }

   public virtual Type ResolveDirectiveProcessor(string processorName)
   {
      throw new Exception(&quot;Directive Processor not found&quot;);
   }

   public virtual string ResolveParameterValue(string directiveId, 
            string processorName, string parameterName)
   {
      if (directiveId == null)
      {
         throw new ArgumentNullException(&quot;directiveId&quot;);
      }
      if (processorName == null)
      {
         throw new ArgumentNullException(&quot;processorName&quot;);
      }
      if (parameterName == null)
      {
         throw new ArgumentNullException(&quot;parameterName&quot;);
      }

      return String.Empty;
   }

   public virtual string ResolvePath(string path)
   {
      if (path == null)
      {
         throw new ArgumentNullException(&quot;path&quot;);
      }

      if (File.Exists(path))
      {
         return path;
      }
      string candidate = Path.Combine(Path.GetDirectoryName(TemplateFile), path);
      if (File.Exists(candidate))
      {
         return candidate;
      }
      return path;
   }

   public virtual void SetFileExtension(string extension)
   {
   }

   public virtual void SetOutputEncoding(Encoding encoding, bool fromOutputDirective)
   {
   }

   public virtual IList&lt;string&gt; StandardAssemblyReferences
   {
      // bare minimum, returns the location of the System assembly
      get { return new[] { typeof (String).Assembly.Location }; }
   }

   public virtual IList&lt;string&gt; StandardImports
   {
      get { return new[] { &quot;System&quot; }; }
   }

   public string TemplateFile { get; set; }
}

Now the idea is that we can subclass the TextTemplatingEngineHost to implement a version specific for our needs.

Before we look at a specialization of this for our purpose, let’s look at a T4 template sample for generating our code

Note: mycodegen is both my assembly name and the namespace for my code generator which itself hosts the T4 engine.

<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ assembly name="mycodegen" #>
<#@ import namespace="mycodegen" #>
<#@ output extension=".cs" #>

<#
   ICodeGenerator cg = ((ICodeGenerator)this.Host);
#>

namespace <#= cg.Namespace #>
{
   <# 
   foreach(var c in cg.Classes) 
   {
   #>
   public partial class <#= c.Name #>
   { 
      <#  
      foreach(Property p in c.Properties)
      {
          if(p.IsArray)
          {
      #>
         public <#= p.Type #>[] <#= p.Name #> { get; set; }
      <#
           }
           else
           {
      #>
         public <#= p.Type #> <#= p.Name #> { get; set; }
      <#
           }
      }
      #>
   }
   <#
   }
   #>
}

So in the above code you can see that our host will support an interface named ICodeGenerator (which is declared in the mycodegen assembly and namespace). ICodeGenerator will simply supply the class names and properties for the classes extracted from the XML schema and we’ll use the T4 template to generate the output. By using this template we can easily change how we output our classes and properties, for example xsd creates fields which are not required if we use auto-implemented property syntax, plus we can change the naming convention, property name case and so on an so forth. Whilst we could add code to the partial classes generated by including other files implementing further partial methods etc. if a type no longer exists in a month or two we need to ensure we deleted the manually added code if we want to keep our code clean. Using the T4 template we can auto generate everything we need.

References

Walkthrough: Creating a Custom Text Template Host
Processing Text Templates by using a Custom Host