18 November 2009

A light-weight .NET framework for publishing Layar layers using WCF and Unity (C#)

Thus speaks Wikipedia:

Augmented reality (AR) is a term for a live direct or indirect view of a physical real-world environment whose elements are merged with (or augmented by) virtual computer-generated imagery - creating a mixed reality.

Amen. Fact is that AR is currently as hot a nuclear reactor core making its way to China, and that everyone and his aunt are scrambling to get a piece of the action. So why not me ;-)

On November 9th this year, my colleague Jeroen Prins, who did some prototyping with Layar, pushed a HTC Hero in my hands with the words “see if you can do something nice with it”. So in a few evenings I created a little framework for making Layar layers in an easier and consistent way. It is based upon some of Jeroen’s prototype, but since he insisted on not having credits for this I won’t give him any ;-). The framework uses the Enterprise Library, most notably Unity, and I assume you are familiar with it.

Since WCF can be bent in almost every direction as far as generating content is concerned, I decided to use it for my solution. I started, as you always start, with the data contract. The object model is pretty simple: a Layer object has Point-Of-Interest (Poi) objects, a Poi has Action objects. If you study the Layar GetPointsOfInterest page for a few minutes you will see the implementation is WCF 101. Maybe 102 ;-). Contrary to my habits, I forego on the comments – those are all on the GetPointsOfInterest page. First, the Action object:

using System.Runtime.Serialization;

namespace LocalJoost.Layar
{
  [DataContract(Name = "Action")]
  public class Action
  {
    [DataMember(Name = "uri")]
    public string Uri { get; set; }

    [DataMember(Name = "label")]
    public string Label { get; set; }
  }
}

The member name is “Uri” (following the .NET coding guidelines) but with adding “Name=uri” in the DataMember attribute I tell WCF to serialize the member as “uri”, without the capital “U”, thus following exactly the Layer API description. This is standard WCF stuff. Then, the Poi class:

using System;
using System.Collections.Generic;
using System.Runtime.Serialization;

namespace LocalJoost.Layar
{
  [DataContract (Name="POI")]
  public class Poi
  {
    public Poi()
    {
      Actions = new List();
    }
    [DataMember(Name = "actions")]
    public List Actions { get; set; }

    [DataMember(Name = "attribution")]
    public String Attribution { get; set; }

    [DataMember(Name = "distance")]
    public double Distance { get; set; }

    [DataMember(Name = "id")]
    public string Id { get; set; }

    [DataMember(Name = "imageURL")]
    public string ImageUrl { get; set; }

    [DataMember(Name = "lat")]
    public int Latitude { get; set; }

    [DataMember(Name = "lon")]
    public int Longitude { get; set; }

    [DataMember(Name = "line2")]
    public string Line2 { get; set; }

    [DataMember(Name = "line3")]
    public string Line3 { get; set; }

    [DataMember(Name = "line4")]
    public string Line4 { get; set; }

    [DataMember(Name = "title")]
    public string Title { get; set; }

    [DataMember(Name = "type")]
    public int Type { get; set; }
  }
}

and finally, the Layer object itself:

using System.Collections.Generic;
using System.Runtime.Serialization;

namespace LocalJoost.Layar
{
  [DataContract]
  public class Layer
  {
    public Layer()
    {
      Hotspots = new List();
    }

    [DataMember(Name = "nextPageKey")]
    public string NextPageKey { get; set; }

    [DataMember(Name = "morePages")]
    public bool MorePages { get; set; }

    [DataMember(Name = "hotspots")]
    public List Hotspots { get; set; }

    [DataMember(Name = "layer")]
    public string LayerName { get; set; }

    [DataMember(Name = "errorCode")]
    public int ErrorCode { get; set; }

    [DataMember(Name = "errorString")]
    public string ErrorString { get; set; }
  }
}

I move on to the whopping complex service contract:

using System.ServiceModel;
using System.ServiceModel.Web;

namespace LocalJoost.Layar
{
  [ServiceContract(Namespace = "www.yournamespacehere.nl/layar")]
  public interface ILayarService
  {
    [OperationContract]
    [WebGet(UriTemplate = "Layar/{layerName}/*", 
      ResponseFormat=WebMessageFormat.Json)]
    Layer GetLayerData(string layerName);
  }
}

which defines the output for this as being JSON, and a custom URI matching pattern which allows us to put the actual layer name in the URL. The * at the end means "and the rest is also accepted". Now the title of this posting says I was doing something with Unity, and here it comes: I define an equally complex interface for a Layar "provider" which will be used by the service implementation:

using System.Collections.Generic;

namespace LocalJoost.Layar
{
  public interface ILayarProvider
  {
    Layer Get(double? lat, double? lon, 
      int? radius, int? accuracy, 
      IDictionary requestParameters);
  }
}

The final piece of real code is the implementation of the ILayarService service contract, with apologies for the crappy layout, but some WCF class names are a wee bit long:

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Globalization;
using System.ServiceModel.Web;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using LocalJoost.Utilities.Unity;

namespace LocalJoost.Layar
{
  /// <summary>
  /// Layar service implementation
  /// </summary>
  public class LayarService : ILayarService
  {
    /// <summary>
    /// Request parameters
    /// </summary>
    private static NameValueCollection RequestParams
    {
      get
      {
        return WebOperationContext.Current != null ?          WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters
: null;
      }
    }

    private static readonly List<string> KeyWordsProcessed = 
      new List<string> { "lat", "lon", "radius", "accuracy" };

    /// <summary>
    /// Gets the layer data.
    /// </summary>
    /// <param name="layerName">Name of the layer.</param>
    /// <returns></returns>
    public Layer GetLayerData(string layerName)
    {
      try
      {
        if (WebOperationContext.Current != null )
        {
          Logger.Write("Layar call: " +             WebOperationContext.Current.IncomingRequest.UriTemplateMatch.RequestUri);
        }
        // Note: layername is lowercase
        var provider =
          new UnityResolver(
             layerName.ToLowerInvariant()).Resolve<ILayarProvider>();

        // Collect the other parameters
        var reqParms = new Dictionary<string, string>();
        foreach( var key in RequestParams.Keys)
        {
          var keyS = key.ToString();
          if (!KeyWordsProcessed.Contains(keyS))
            reqParms.Add(keyS, RequestParams[keyS]);
        };
        
        return provider.Get(
          GetRequestDouble("lat"), GetRequestDouble("lon"),
          GetRequestInt("radius"), GetRequestInt("accuracy"),
          reqParms);
      }
      catch( Exception ex)
      {
        Logger.Write(ex,"Exceptions");
        return null;
      }
    }

    #region Utility methods
    private double GetRequestDouble(String keyname)
    {
      if (!(RequestParams == null || 
         string.IsNullOrEmpty(RequestParams[keyname])))
      {
        return Convert.ToDouble(RequestParams[keyname], 
         CultureInfo.InvariantCulture);
      }
      return -1;
    }

    private int GetRequestInt(String keyname)
    {
      if (!(RequestParams == null || 
         string.IsNullOrEmpty(RequestParams[keyname])))
      {
        return Convert.ToInt32(RequestParams[keyname],
          CultureInfo.InvariantCulture);
      }
      return -1;
    }
    #endregion
  }
}

Here comes my little UnityResolver into play, which was described earlier in this blog. What this LayarService basically does is accept a layer name, burp the call into a log file, get the lat, lon, radius, and accuracy from the query string, dump the rest of the query string parameters into a dictionary, use Unity to determine which ILayerProvider implementation is to be loaded, call it’s Get method with the collected data, and return the result.

Now there are only six steps to make this actually work. First, you define a web application project. You reference the LocalJoost.Layar project, System.ServiceModel.dll, System.Runtime.Serialization, every file in the Enterprise Library that starts with "Microsoft.Practices.Unity" (I have 5), and Microsoft.Practices.EnterpriseLibrary.Logging.dll.

The second step is: add a text file to the web application, for instance "LayarService.txt". You enter the following text in it:

<%@ ServiceHost Language="C#" 
    Debug="true" Service="LocalJoost.Layar.LayarService" %>

and rename this the file to "LayerService.svc". The third step is some WCF configuration in the web.config of your web application to host the service as a webHttpBinding, thus making it accept calls via http get:

<services>
  <service name="LocalJoost.Layar.LayarService">
    <endpoint address="" binding="webHttpBinding"
 behaviorConfiguration="WebHttpBehavior"
 contract="LocalJoost.Layar.ILayarService" 
 bindingNamespace="http://whatever/layar">
    </endpoint>
   </service>
</services>
<behaviors>
  <endpointBehaviors>
    <behavior name="WebHttpBehavior">
      <webHttp/>
    </behavior>
  </endpointBehaviors>
</behaviors>

The fourth step is to map your implementations of ILayarProvider to your layers. The LayerService class works in such a way that a layer maps directly to a Unity container, so a configuration might look like this:

<unity>
  <typeAliases>
   <typeAlias alias="ILayarProvider" 
        type="LocalJoost.ILayarProvider,LocalJoost.Layar"/>
   <typeAlias alias="SampleProvider" 
        type="SomeAssembly.SampleProvider,SomeAssembly"/>
   <typeAlias alias="AnotherProvider"
         type="SomeotherAssembly.AnotherProvider, SomeotherAssembly"/>
  </typeAliases>
  <containers>
   <container name="mylayer">
    <types>
     <type type="ILayarProvider" 
     mapTo="SampleProvider"/>
    </types>
   </container>
   <container name="someotherlayer">
    <types>
     <type type="ILayarProvider"
        mapTo="AnotherProvider"/>
    </types>
   </container>
  </containers>
</unity>

Here I have defined two sample containers, thus layers. If, for instance, your service is hosted as “http://mydomain.com/LayarServer/LayerService.svc” you can register your Layer with the Layar developer portal (which is, incidentally, the fifth step) as “http://mydomain.com/LayarServer/LayerService.svc/Layar/mylayer/” (mind the trailing slash!) and the framework will do the rest.

Now the sixth and final step is the real hard part: writing actual implementations of the ILayarProvider. This depends or what you are actually wanting to show. And this it where my help ends ;-).

A simple Unity helper for making class decoupling easier

Unity, a part of the Enterprise Library, is a great way of decoupling interfaces and implementation, and for opening a road into unit testing with mock objects. Unfortunately, using it can be a bit cumbersome. You have to create a container, configure it from code or from configuration, and have to decide when to do what. I thought it could do with some help, so I created some helper classes. I must admit this inspired by The Common Service Locator and some code for that I got from Dennis van der Stelt, but it is a little simpler to use. And it works only with Unity ;-) The idea is to define a factory and a resolver, that know of each other only trough an interface:
namespace LocalJoost.Utilities.Unity
{
  public interface IUnityResolver
  {
    Resolve<T>();
  }
}
Then, I define a UnityResolver, which is basically a wrapping around a UnityContainer class:
using System;
using System.Configuration;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;

namespace LocalJoost.Utilities.Unity
{
  /// <summary>
  /// Base class for unity resolvers
  /// </summary>
  [Serializable]
  public class UnityResolver : IUnityResolver
  {
    protected static string _defaultContainer = "Default";
    protected IUnityContainer Container{get; set;}

    /// <summary>
    /// Initializes a new instance of the UnityResolver
    /// Override this constructor if you want to write your own default
/// behaviour. /// Register in code by adding lines like: /// Container.RegisterType(Type.GetType("NameSpace.IMyClass",true), /// Type.GetType("NameSpace.MyClass",true)); /// </summary> public UnityResolver() : this(_defaultContainer) { } /// <summary> /// Initializes a new instance of the UnityResolver class. /// </summary> /// <param name="containerName">Name of the container.</param> public UnityResolver(string containerName) { Container = new UnityContainer(); var section = ConfigurationManager.GetSection("unity") as UnityConfigurationSection; if (section != null) { var containerConfiguration = section.Containers[containerName]; if (containerConfiguration != null) { section.Containers[containerName].Configure(Container); } } } /// <summary> /// Resolves an instance of T /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public T Resolve<T>() { return Container.Resolve<T>(); } } }

You can use this class directly, by calling new UnityResolver(“MyContainer”).Resolve<IMyType>(). The UnityResolver looks for a Unity container named “Default” in your configuration file. If that is not present, it creates an empty container. Use of the latter feature is described below.

This is not very efficient when all your classes are sitting into one and the same container, and you may want to have some consistent behavior of your classes during unit testing with mockups. So I created the UnityFactory class that can accept a resolver and hold it:

using System;
using System.Configuration;
using System.Reflection;
using System.Web;

namespace LocalJoost.Utilities.Unity
{
  /// <summary>
  /// Static helper class for shortcutting Unity instantiated 
  /// classes
  /// </summary>
  public class UnityFactory
  {
    /// <summary>
    /// Method to set the resolver manually - use this for unit testing
    /// </summary>
    /// <param name="resolver">The resolver.</param>
    public static void SetResolver( IUnityResolver resolver)
    {
      Resolver = resolver;
    }

    /// <summary>
    /// Gets a resolver from configuration.
    /// </summary>
    /// <returns></returns>
    private static IUnityResolver GetResolverFromConfiguration()
    {
      var configuredDefaultResolver = 
	    ConfigurationManager.AppSettings["UnityResolver"];
      if (!string.IsNullOrEmpty(configuredDefaultResolver))
      {
        var specParts = configuredDefaultResolver.Split(',');
        var ass = Assembly.Load(specParts[1]);
        var objType = ass.GetType(specParts[0]);
        return Activator.CreateInstance(objType) as IUnityResolver;
      }
      return null;
    }

    /// <summary>
    /// Gets the instance of an object via an interface
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <returns></returns>
    public static T GetInstance<T>()
    {
      // First, make sure there is a resolver. 
      // If none is defined, try to load one from configuration
      // If that fails too, use the default resolver
      if (Resolver == null)
      {
        Resolver = GetResolverFromConfiguration() ?? new UnityResolver();
      }

      // Then, resolve the interface to an object instance
      return Resolver.Resolve<T>();
    }

    #region Properties
    /// <summary>
    /// Gets or sets the resolver. Uses Http context or static variable
    /// to store a created resolver
    /// </summary>
    /// <value>The resolver.</value>
    private static IUnityResolver Resolver
    {
      get
      {
        if (HttpContext.Current == null)
        {
          return _resolver;
        }
        return HttpContext.Current.Application["__UnityResolver"]
          as IUnityResolver;
      }

      set
      {
        if (HttpContext.Current == null)
        {
          _resolver = value;
        }
        else
        {
          HttpContext.Current.Application["__UnityResolver"] = value;
        }
      }
    }

    private static IUnityResolver _resolver;
    #endregion
  }
}

Usage of this class is UnityFactory.Resolve<IMyType>(). And presto, you have got a reference to your implementation class. That’s all there is. Except for some configuration, of course ;-).

Another feature of this class is that it looks for a config setting “UnityResolver”. If that is present, it tries to load that class for a resolver in stead of the default UnityResolver. For instance, you can subclass UnityResolver, override the default constructor and define your interface-to-implementation mapping in code. Now this may look strange, because what is the point of decoupling classes and then make the mappings in code again? Well, for a scenario in which you want to use Unity for unit testing with mockups, this makes sense – when you want to deliver your production application without the necessity for a (possible very large) unity mapping section in your configuration file. If you want to register objects from code, you can do it for instance like this in the constructor of your UnityResolver override:

Container.RegisterType(
 Type.GetType("SomeNamespace.IMyInterface,SomeNamespace", true),
 Type.GetType("SomeOtherNamespace.MyImplementation,SomeOtherNamespace", true));

where "SomeNamespace" and "SomeOtherNamespace" after the comma are assembly names. If you use this construct, because it looks nice in NDepend and you don't have to make references, make sure your set the second parameter of Type.GetType, throwOnError, to true or it will fail silently and you might spend an uncomfortable long time debugging (I am talking from experience here). Personally I would go for typeof in stead of using Type.GetType but that is a matter of taste.

As a last feature, in unit testing scenarios, you can make another subclass of UnityResolver, call UnityFactory.SetResolver(myResolver) and the UnityFactory will store your resolver in a static variable (or the application context). Subsequently, all your classes will use the mapping logic defined in your own resolver, which makes a great starting point for mockup testing.

I hope this little sample will make decoupling, unit testing and mockup objects using Unity a bit more accessible.