Sunday, September 23, 2012

IMPORTANT: Please resubscribe to my feed

Maybe the writing has been on the wall for Feedburner for a long time. No features were added for over four years, no bugs were fixed, the look-and-feel wasn't updated to be consistent with other Google products, support channels were being shut down,... But it wasn't until last Friday that the degradation of the service really got tangible: all subscriber counts indicated zero. Dozens of people complained, using all possible communication channels, but nobody listened.

When I set up this blog almost five years ago, I made the mistake of pointing people to a naked Feedburner url, which now forces me to ask my subscribers to resubscribe. I've learned my lesson, and I've set up a more sustainable url: http://feed.jefclaes.be/jefclaes.

I always valued RSS subscribers more than people coming from search engines; it encourages me to know there are people curious for more content. So if you're reading this, please unsubscribe from this feed, and resubscribe to http://feed.jefclaes.be/jefclaes, the current feed will phase out over the next thirty days.

TL;DR: Feedburner is dead. I messed up by pointing you there. Please resubscribe to http://feed.jefclaes.be/jefclaes.

Finding the gaps in a sequence of dates

Somewhere earlier this week I had to find the gaps in a sequence of dates. Admittedly, my first action was to search Stackoverflow for a clean solution. But since no one asked the question there yet, I had to implement it myself.

The solution comes in the form of an extension method on IEnumerable<DateTime>, which takes a lower bound and an upper bound, and returns an enumerable of dates.
public static IEnumerable<DateTime> GetGaps(
    this IEnumerable<DateTime> sequence, DateTime lowerbound, DateTime upperbound)
{          
    var completeSequence = new List<DateTime>();           
    var tmpDay = lowerbound.Date;

    while (tmpDay <= upperbound.Date)
    {
        completeSequence.Add(tmpDay);
        tmpDay = tmpDay.AddDays(1);
    }
    
    var gaps = completeSequence.Except(sequence.Select(d => d.Date));
    
    return gaps;
}
I start with building a second - from lower bound to upper bound, thus gapless - sequence. Then I use the LINQ Except method to compare the complete sequence to the input sequence, and produce a difference set.

It was only after a few not so successful iterations that I found this - for me - satisfactory solution though. If I hadn't intellistumbled upon the LINQ Except method, I probably would have ended up with something a lot less elegant.


This extension method is backed up by a few tests.
[TestMethod()]
public void Given_an_empty_sequence_everything_between_bounds_is_a_gap()
{
    var sequence = new List<DateTime>();            
 
    var actual = sequence.GetGaps(new DateTime(2012, 1, 6), new DateTime(2012, 1, 9));

    Assert.IsTrue(actual.Count() == 4);
    Assert.IsTrue(actual.Contains(new DateTime(2012, 1, 6)));
    Assert.IsTrue(actual.Contains(new DateTime(2012, 1, 7)));
    Assert.IsTrue(actual.Contains(new DateTime(2012, 1, 8)));
    Assert.IsTrue(actual.Contains(new DateTime(2012, 1, 9)));
}

[TestMethod()]        
public void Given_sequence_with_duplicate_dates_one_is_not_returned_as_gap()
{
    var sequence = new[] 
    { 
        new DateTime(2012, 1, 6, 10, 0, 0), // double date
        new DateTime(2012, 1, 6, 11, 0, 0), // double date
        new DateTime(2012, 1, 7) 
    };

    var actual = sequence.GetGaps(new DateTime(2012, 1, 6), new DateTime(2012, 1, 9));

    Assert.IsTrue(actual.Count() == 2);
    Assert.IsTrue(actual.Contains(new DateTime(2012, 1, 8)));
    Assert.IsTrue(actual.Contains(new DateTime(2012, 1, 9)));
}

[TestMethod()]
public void Given_sequence_with_gaps_the_gaps_are_returned()
{
    var sequence = new[] 
    { 
        // gap
        new DateTime(2012, 1, 4), 
        new DateTime(2012, 1, 5), 
        // gap
        new DateTime(2012, 1, 7, 11, 10, 1) 
        // gap
    };

    var actual = sequence.GetGaps(new DateTime(2012, 1, 3), new DateTime(2012, 1, 8));

    Assert.IsTrue(actual.Count() == 3);
    Assert.IsTrue(actual.Contains(new DateTime(2012, 1, 3)));
    Assert.IsTrue(actual.Contains(new DateTime(2012, 1, 6)));
    Assert.IsTrue(actual.Contains(new DateTime(2012, 1, 8)));
}

[TestMethod()]
public void Given_sequence_with_no_gaps_an_empty_enumerable_is_returned()
{
    var sequence = new[] 
    {                
        new DateTime(2012, 1, 4), 
        new DateTime(2012, 1, 5),                 
        new DateTime(2012, 1, 6)                 
    };

    var actual = sequence.GetGaps(new DateTime(2012, 1, 4), new DateTime(2012, 1, 6));

    Assert.IsFalse(actual.Any());
}
Do you know of a better way to do this?

Thursday, September 20, 2012

To intellistumble

To accidentally or unexpectedly discover a method or property whilst using IntelliSense to browse through symbol names.
We should add this term to the Microsoft developer jargon.

Monday, September 17, 2012

The 7 R's of Hypermedia

While most REST concepts are rather easy to grok, there is one concept which I found harder to understand at first: Hypermedia. Let it be that without this concept, you're missing out on an extremely important strength of REST. Hypermedia enables you to build dumb - or smart, depending on your perspective - clients, which are mostly driven by the server. Practically, this is implemented as resources embedding links which allow the client to discover and navigate through your RESTful service.

Accidentally actually, I saw someone tweet a link over the weekend to a Deep Fried Bytes episode, featuring Darrel Miller, where he talks about the seven R's of Hypermedia. I listened to it on my morning commute, and the 56 minutes long show contained one of the best summaries on the uses of Hypermedia I've heard or read so far.

Here are some of my notes...
  1. Relations: Make your service discoverable and self-documenting by embedding links to related concepts.
  2. Embedded resources: Instead of embedding resources (for example: a company logo) into your client, and having to deal with specific storage techniques, make them available through your service and use built-in HTTP caching.
  3. Reference data: Provide links to where your client can find optional or required reference data. Populating a dropdownlist is a good example. 
  4. Redistribution of effort: Instead of putting a dumb load balancer in front of your machines, you can use your links to refer certain functionality to a specific machine.
  5. Reduction of payload size: Show clients where they can get extra data. Think endless scrolling, or more detailed resources.
  6. Reflow: Allow the server to control the flow. The server can use links to dictate the next available steps in a business process. 
  7. Restriction of functionality: The client can derive from the presence of a certain link whether a certain functionality is enabled or disabled.
You can find the full show here.

Sunday, September 16, 2012

Value object obsession

Primitive obsession is one of the more popular (hyped?) code smells these days.
Primitive obsession is the name of a code smell that occurs when we use primitive data types to represent domain ideas. For example, we use a string to describe a message or an integer to represent an amount of money.
The antidote is creating a value object instead of using a primitive. A value object is an immutable object which (in its DDD definition) carries no identity, but is compared based on the value of its attributes.

While primitive obsession is still very much the standard, newer projects seem to regularly suffer from the other extreme; introducing value objects as the de facto standard.

For example, let's look at the implementation of this AccountNumber class I found in the first C# DDD Github repository.

The equality implementations are only included in the last snippet.
public class AccountNumber
{
    public AccountNumber(string value)
    {
        Value = value;
    }

    public string Value { get; private set; }
}
Expressing intent

It's possible that the author of this snippet thought that extracting this object would help express intent, justifying abstraction early on. I don't see it though. To me, it seems to be introduced prematurely, screaming YAGNI. Clients are capable of thinking in primitives; be it text (string), number (int)... Obvious and consistent naming can get you far.

Composition

One of the scenarios which justify the extra boilerplate, is composition.

If we would be interested in the different parts of an account number, we could introduce a composite object, assembling all its parts through the constructor.
public class AccountNumber
{
    public AccountNumber(
        string countryCode, 
        string checkDigits,
        string basicAccountNumber)
    {
        CountryCode = countryCode;
        CheckDigits = checkDigits;
        BasicAccountNumber = basicAccountNumber;
    }

    public string CountryCode { get; private set; }

    public string CheckDigits { get; private set; }

    public string BasicAccountNumber { get; private set; }            
}
The account number is self contained now; its parts won't leak all over the place.

Valid instantiation

Another valid reason to introduce a value object is when you need to guarantee valid instances.

In this example, I could guard for empty values in the constructor, taking that responsibility/problem out of consumers' hands.
public AccountNumber(
    string countryCode, 
    string checkDigits,
    string basicAccountNumber)
{
    Guard.NotEmpty(countryCode);
    Guard.NotEmpty(checkDigits);
    Guard.NotEmpty(basicAccountNumber);

    CountryCode = countryCode;
    CheckDigits = checkDigits;
    BasicAccountNumber = basicAccountNumber;
}
Encapsulating behaviour

One more important reason to use a value object, is when there is behaviour to add; encapsulation makes for good OO. In the example below, the Check method - which verifies the check digits - is contained by the AccountNumber class itself, abstracting the algorithmic logic and preventing duplication.
public class AccountNumber
{
    public AccountNumber(
        string countryCode,
        string checkDigits,
        string basicAccountNumber)
    {
        Guard.NotEmpty(countryCode);
        Guard.NotEmpty(checkDigits);
        Guard.NotEmpty(basicAccountNumber);

        CountryCode = countryCode;
        CheckDigits = checkDigits;
        BasicAccountNumber = basicAccountNumber;
    }

    public void Check()
    {
        // verify checkdigits
    }

    public string CountryCode { get; private set; }

    public string CheckDigits { get; private set; }

    public string BasicAccountNumber { get; private set; }

    public bool Equals(AccountNumber other)
    {
        if (ReferenceEquals(null, other)) return false;
        if (ReferenceEquals(this, other)) return true;
        return Equals(other.CountryCode, CountryCode) && 
                Equals(other.CheckDigits, CheckDigits) && 
                Equals(other.BasicAccountNumber, BasicAccountNumber);
    }

    public override bool Equals(object obj)
    {
        if (ReferenceEquals(null, obj)) return false;
        if (ReferenceEquals(this, obj)) return true;
        if (obj.GetType() != typeof (AccountNumber)) return false;
        return Equals((AccountNumber) obj);
    }

    public override int GetHashCode()
    {
        unchecked
        {
            int result = CountryCode.GetHashCode();
            result = (result*397) ^ CheckDigits.GetHashCode();
            result = (result*397) ^ BasicAccountNumber.GetHashCode();
            return result;
        }
    }

    public static bool operator ==(AccountNumber left, AccountNumber right)
    {
        return Equals(left, right);
    }

    public static bool operator !=(AccountNumber left, AccountNumber right)
    {
        return !Equals(left, right);
    }
}
Summarized

Introducing value objects instead of simple types, can add useless boilerplate and unnecessary levels of indirection. Value objects should arise out of certain necessity, and should not be the de facto standard.

Turn to using value objects:
  • when they help express intent
  • for composition
  • to guarantee valid instantiation
  • to encapsulate behaviour

If you disagree, please show me the light.

Thursday, September 13, 2012

Slides and code from my Tunisia REST and ASP.NET Web API session

I just returned from a four day trip to Tunisia with Euricom. Next to indulging on the sun, food and all-inclusive cocktails, getting to know each other in a less professional setting, we spent somewhere around half of our days - and this is a rather generous estimate - doing technical sessions and workshops.

I gave a 90 minute long crash course on REST and ASP.NET Web API.

Content

REST
  • Concepts
  • Architectural values
  • Left overs

ASP.NET Web API
  • Server/client
  • Exception handling
  • Content negotiation
  • Message handlers
  • IoC
  • Testing

You can find the slides on SlideShare (or embedded below). The code is hosted on GitHub.

Sunday, September 2, 2012

Supporting the OPTIONS verb in ASP.NET Web API

ASP.NET Web API controllers support only four HTTP verbs by convention: GET, PUT, POST and DELETE. The full list of existing HTTP verbs is more extensive though. One of those unsupported verbs which can be particularly useful for API discovery and documentation is the OPTIONS verb.
The OPTIONS method represents a request for information about the communication options available on the request/response chain identified by the Request-URI. This method allows the client to determine the options and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action or initiating a resource retrieval.
If we wanted to implement controller support for the OPTIONS verb, we could manually map an action to the verb by decorating it with an AcceptVerbs attribute, and making the action return a response with a relevant Access-Control-Allow-Methods header.

For a values controller, with a GET and DELETE action, it could look like this.
public class ValuesController : ApiController
{        
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }                 
    
    public void Delete(int id) { }

    [AcceptVerbs("OPTIONS")]
    public HttpResponseMessage Options()
    {
        var resp = new HttpResponseMessage(HttpStatusCode.OK);
        resp.Headers.Add("Access-Control-Allow-Origin", "*");
        resp.Headers.Add("Access-Control-Allow-Methods", "GET,DELETE");

        return resp;
    }
}
If we now make an OPTIONS request to http://localhost:53314/api/values..
OPTIONS http://localhost:53314/api/values HTTP/1.1
User-Agent: Fiddler
Host: localhost:53314
..we receive following response.
HTTP/1.1 200 OK
Server: ASP.NET Development Server/10.0.0.0
Date: Sun, 02 Sep 2012 13:46:21 GMT
X-AspNet-Version: 4.0.30319
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET,DELETE
Cache-Control: no-cache
Pragma: no-cache
Expires: -1
Content-Length: 0
Connection: Close
While this works, it's not a great solution. We don't want to maintain the list of supported verbs manually, and we certainly don't want to repeat this for each controller.

ASP.NET Web API provides a nice way to have a more high level solution: HTTP message handlers. These basically behave as HTTP intermediaries, meaning we can intercept each OPTIONS request early, and bypass the whole request chain.
Another useful component we can make good use of is the default ApiExplorer; this abstraction allows us to obtain metadata of our API's stucture.

To create a new HTTP message handler, I inherited from the DelegatingHandler class, and overwrote the SendAsync method. Here we'll intercept the request when the verb equals "OPTIONS". An instance of the Api explorer can be resolved through the global configuration. I grab the requested controller from the request route data, and use that to search the Api explorer's ApiDescriptions collection for its associated actions, and its associated verbs. Once I get the outcome of this lookup, and at least one verb is supported (*), I'll return an OK response with the relevant headers, and thus short circuit the request.
public class OptionsHttpMessageHandler : DelegatingHandler
{
  protected override Task<HttpResponseMessage> SendAsync(
      HttpRequestMessage request, CancellationToken cancellationToken)
  {
      if (request.Method == HttpMethod.Options)
      {
          var apiExplorer = GlobalConfiguration.Configuration.Services.GetApiExplorer();

          var controllerRequested = request.GetRouteData().Values["controller"] as string;              
          var supportedMethods = apiExplorer.ApiDescriptions
              .Where(d => 
                {  
                    var controller = d.ActionDescriptor.ControllerDescriptor.ControllerName;
                    return string.Equals(
                        controller, controllerRequested, StringComparison.OrdinalIgnoreCase);
                })
              .Select(d => d.HttpMethod.Method)
              .Distinct();

          if (!supportedMethods.Any())
             return Task.Factory.StartNew(
                 () => request.CreateResponse(HttpStatusCode.NotFound));

          return Task.Factory.StartNew(() =>
            {
                var resp = new HttpResponseMessage(HttpStatusCode.OK);
                resp.Headers.Add("Access-Control-Allow-Origin", "*");
                resp.Headers.Add(
                    "Access-Control-Allow-Methods", string.Join(",", supportedMethods));

                return resp;
            });
    }

    return base.SendAsync(request, cancellationToken);
  }
}
Register this HTTP message handler by adding it to the configuration.
GlobalConfiguration.Configuration.MessageHandlers.Add(new OptionsHttpMessageHandler());
This second solution still yields the same result, but is far more scalable.

(*) When a resource can't be read nor manipulated, it must not exist right?