NMoneys 2.2

on Monday, 13 February 2012

It is hard to believe the last release was on September. That only means one thing: I was about time!

There are quite a few changes in the release, so I will get straight to the point(s)

Money Allocation

2.2 should be a happy release. Why? Well, besides the fact it is the first release in more than 6 months it is the first one that contains code contributed by someone else but me.
Thank you, Berryl, for the feature, let’s hope it’s useful to many.

The problem that we try to solve is a simple one: we have a certain amount of money and we want to allocate it amongst several recipients. If we are lucky (and so are the receivers) the amount can be distributed evenly and so every recipient will receive the same amount of money. But most of the time that is not the case and we since money cannot be subdivided forever (there are no coins for one thousandth of a euro, for instance) we need to find away to distribute the money as fair (or unfair) as possible.

How to allocate a monetary quantity? Invoke .Allocate() on the quantity. How is the remainder distributed? An implementation of IRemainderAllocator will decide. There a some ready to use implementations, accessible using the static factory RemainderAllocator: FirstToLast, LastToFirst and Random. The significant decimals of the currency of the monetary quantity are used to determine the minimal amount of money that can be allocated.

Money[] allocated = 8.3m.Usd().Allocate(4, RemainderAllocator.LastToFirst);
Asscert.That(allocated, Is.EqualTo(new[] { 2.07m.Usd(), 2.07m.Usd(), 2.08m.Usd(), 2.08m.Usd() }));
Money[] allocated = 34m.Jpy().Allocate(4, RemainderAllocator.FirstToLast);
Assert.That(allocated, Is.EqualTo(new[] { 9m.Jpy(), 9m.Jpy(), 8m.Jpy(), 8m.Jpy() }));

Of course, no one prevents passing a custom IRemainderAllocator as long as the allocator distributes all the money.

ISO is as ISO does

NMoneys claims to implement the ISO4217 standard for the .NET platform. That was accurate to a certain extent. It is true all currencies defined in the standard were present. But not all the information they contained was as the standard defines, because the baseline of the information was not the standard, was the information contained in the .NET culture tables.

But from this version on, all currencies will have the name as defined in the standard list (except some Bond Market units that lost their prefix).

But most importantly, currencies will have as many significant decimal digits as the specification says.

As a result, a bunch of currencies have changed name and precision. For a complete list, head to the Changelog.

Get it while it’s hot

As usual, visit the download page for the latest binary package. Or update/install the Nuget package. Or let the hipster in you install the Ruby Gem.

 

Oh, and if you like what you see. Spread the word, contribute or, simply, use it.

REST Raiding. WebApi

on Thursday, 9 February 2012

WebApi looked as one of the strongest contenders at first, just by its lineage (MSFT is his champion). But when I saw its pre-beta status I had second thoughts. And third thoughts remembering all the horror stories I have had with its father: Windows Communication Foundation. Since I spent less time than I wanted evaluating OpenRasta I gave WebApi a spin. And here are my thoughts.

Get It!

Getting WebApi up and running is simple enough: install the WebApi package and you are good to go. There are a number of other packages that add some interesting features, but I only went for the simple, barebones, server side of things.

Documentation

The walkthrough is pretty comprehensive but the site does not have a whole lot of “official” documentation. But the package comes with a pair of .chm files that are really handy.

And one cannot complain about the number of people writing about the product in their blogs. The information might be outdated, but it should give an idea of the activity of the community around the product, which is pretty nice, in my opinion.

The Services

Creating services (or APIs, as they are called in WebApi jargon) is a two step thing out-of-the-box.

  1. Create a class decorated with the ServiceContract attribute that contains one or more related methods (and related means URL-related) and implement your logic:
    [WebGet(UriTemplate = "")]
    public Resources.Catalog[] GetCatalogs()
    {
        // fancy population of 'resource'
        return resource;
    }
  2. And register the route corresponding to the resource you are serving when the application starts:
    RouteTable.Routes.Add(
            new ServiceRoute(
                "catalogs",
                new HttpServiceHostFactory(),
                typeof(CatalogsApi)));

Some content negotiation is included out of the box by adding an Accept request header, being the default XML and JSON is also included. A nice touch is that it supports qualified values (see the spec), meaning that will return the supported type with the higher relative quality factor or default to XML. Another nice touch is the fact that the response includes the codification charset of the data, which helps with those “weird” characters that we all love (ñ, æ, å,…)

One of the things that impressed me the most was how the whole URL placeholder and extra request information is handled. If one wants to have another API hanging from an already defined base route (in this case, /catalogs) another method in the api class is created and decorated with the WebGet attribute, setting the UriTemplate property to a string that will contain the placeholder information for that route, including any query string information that we may want to get and that information will be set in the parameters defined for the method. Pretty nifty.

[WebGet(UriTemplate = "{catalogName}?lang={lang}")]
public Resources.Catalog Get(string catalogName, string lang)
{
    // even more fancy stuff
    return resource;
}

And the icing of the cake for those who need it? Easy OData support. Apparently it does not get on well with REST according to some, but it is a pretty popular format of delivering information.

Opinion

I was pleasantly surprised by how smooth WebApi looks like. That only mean they did a good job to come up with a nice to work with API on top of the configuration hell that WCF is. And that is a compliment, by the way.
It does what it does in a nice manner but I do not have an opinion about extensibility points and customizations as I did not push it. But I know from my light reading about the subject that it supports the concept of resource factory, allowing to use your IOC container of choice to inject the dependencies your service might have in an easy manner.

Probably one the nicest things one can say is that it gets the job done without getting in one’s way, with a simple api, meaningful defaults and adherence to the spec. Do not know about relative performance, compared to some of the other contenders, though.

I have very few bad things (if any) to say. The only but is the two step creation of services (service plus the route), but I am confident there might be an extension to have it in one single step.

Would I use WebApi? I cannot see why not.
Was it the one I chose? No, it was not. Only because I tried it by chance and expected worse (due to its WCF heritage) it did not get higher in my list of preferences.
Would I recommend its use? Yeah, give it a go. It may suit your needs.

REST Raiding. OpenRasta

on Sunday, 29 January 2012

I had very high hopes for this one. I was really, really, ready to like it. I had the preconceived idea that this was going to be the one to be chosen. But…

Get It!

I really do not want to be mean or sound (too) rant-y. But I need to tell the whole story.

Let’s face it, looks matter. Compare these two sites. If they were a web-shop, from which you would buy from? If they were a web framework, which one projects quality and care? I do not intend to be cheap, but… seriously?

 OpenRasta_Home_2 nancy_home

 

Ok, dodgy as it looks I bit the bullet and tried my luck finding a NuGet package. None. Nil. Zero. If you want a package, go install OpenWrap and let it take over the soul and guts from your .csproj. Not an option. Not for me, at least.
Ok, let’s find a binary download… Hitting the documentation page… Looks promising. Darn! It points to an apparently outdated source code repository. Well, it links to a list of the various repositories (and no links to them?). Fine, I know how the Web works Sad smile and how to navigate GitHub, so stop complaining already! What? No binaries? I already broke my rules with this project, that is how ready to like it I was…
Cloning a couple of repositories and for once in my life I will read the doc first, as I know these guys can get funky with the build process. Oh dear, the instructions are outdated, there is no make.bat anywhere the new source tree. Some investigation tells me it is just a shortcut for msbuild. Fire it and… what is the result? An assembly with version 0.0.0.0. WTF?

Documentation

Being the most mature of the contenders I was expecting documentation to be more comprehensive and a wealth blog posts about how to get started. And I was not disappointed. I have little to none complaints in the documentation are.

The Services

Or handlers as they are called in Open Rasta are the classes that give access to our resources (the snapshots of information). They are truly POCOs, not needing any parent class, interface or attribute. Just name the methods wisely (correlating to HTTP verbs) or drive the default behavior with the configuration:

public class CatalogsHandler
{
    public CatalogCollection Get()
    {
        var resource = // get the resource 

        return resource;
    }
}

Speaking of which, one of the things that caught my attention when I first saw the framework was how much it relied in configuration and how “beautiful” was the API to handle it. I still think the effort they put in having an elegant configuration API was worthy, but having seen other frameworks in which configuration is superfluous it now seems almost like a waste. An exercise of waste, nonetheless.

public class Configuration : IConfigurationSource
{
    public void Configure()
    {
        using (OpenRastaConfiguration.Manual)
        {
            ResourceSpace.Has
                .ResourcesOfType<CatalogCollection>()
                    .AtUri("/catalogs")
                    .HandledBy<CatalogsHandler>()
                    .AsXmlDataContract().And.AsJsonDataContract();
        }
    }
}

And precisely with configuration came the last sin I committed with the framework. I got overconfident with the usage of the API and I forgot to include the using (OpenRastaConfiguration.Manual) statement. It may not look as much, but was capital in me giving up. Because it makes nothing work with a dreadful ArgumentNullException. Swallowing my pride again I dived in the code but could not make any sense of such a complex framework in such short period of time. So I reverted to community support, which turns out to be just StackOverflow (having read that the Google Groups is dead). I cannot complain, as I got my question answered and my thanks were given in less than a week.
By that time it was too late. I had seen enough, given up and tagged the framework as not viable for this project, thanks for asking.

Opinion

As one can imagine, I cannot be too happy about my time with the framework. And definitely was not the chosen one.

I tried very hard to like it. And being disappointed is partly my fault (a combination of high expectations and carelessness in reading the walkthrough).
I still believe is one the nicest frameworks to work with (once you get it up and running) with tons of places to hook up your own behavior and probably the most HTTP-friendly of them all (for example, requesting a resource in a format that is not configured, returns a proper 406 Not Acceptable code).
Their support for dependency management is kind of nice, but a bit verbose for my liking, but one can use of of the multiple hooks to have the IOC container of the month working with the framework and using all the coolness of the container for dependency registration.

Final sayings? It will be a killer framework once it settles down from the code/project/repository migrations turmoil, the new version is released and contributors fix the build and the doc. Until that happens, I won’t be getting anywhere close for production purposes.

And for pity’s sake! Include some sort of binary distribution for those that have not drunk from the OpenWrap chalice! I am not even suggesting a lame NuGet package. That would be too low, wouldn’t it? Winking smile

REST Raiding. Nancy

on Friday, 20 January 2012

The first contender has a lovely woman’s name: Nancy.

Get it!

Getting Nancy up and running is as straightforward as it can be: create a Visual Studio Web Application project and install the nuget package. That is it.

Documentation

If the homepage was both elegant and useful, the documentation page is mouth watering. Simple and straight to the point. I was pleasantly surprised by the quality and the general vibe of the project.
This one is for those that claim that all OSS projects are a waste of time and lack documentation. Watch and cry.

The services

The service that returns all snapshots will be hosted in the url /catalogs and the one that returns the single detail in /catalogs/{catalog_name}. Resources are accessed in Nancy via modules (inheritors of NancyModule). Modules specify the URL and the HTTP method using a very neat indexer-function syntax. Since both services are related by the base URL, Nancy allows them to be grouped in the same module. No more configuration. As DRY and simple as it gets.

public class CatalogsModule : NancyModule
{
    public CatalogsModule() : base("/catalogs")
    {
        Get["/"] = parameters =>
        {
            var model = new[]
            {
                // define the model
            };

            return Response.BarebonesContentNegotiation(Request, model);
        };

        Get["/{catalogName}"] = parameters =>
        {
            string name = parameters.catalogName;
            CultureInfo language = Request.GetLanguage();
            var model = new Catalog
            {
                // model
            };
            return Response.BarebonesContentNegotiation(Request, model);
        };
    }
}

The /catalogs service is as simple as it gets as no argument is needed and uses no globalization. The only thing to point out is the Response.BarebonesContentNegotiation() method. Since Nancy does not implement (yet) any content negotiation or dynamic response formatting I developed a coarse method to find out whether to return XML or default to JSON, using the Nancy extensions .AsXml() and .AsJson(). It is clumsy and incorrect to an extreme, but since it is a POC I am not that embarrassed Winking smile

public static Response BarebonesContentNegotiation<TModel>(this IResponseFormatter response, Request request, TModel model)
{
    bool acceptsXml = request.Headers.Accept
        .Any(a => a.IndexOf("xml", StringComparison.OrdinalIgnoreCase) >= 0);

    return acceptsXml ? response.AsXml(model) : response.AsJson(model);
}

For the /catalogs/{catalog_name} service there are some more interesting points. The first one is how route parameters are passed: that is what the function argument parameters is for. It cleverly uses dynamics to give access to the parameters by name. The other thing to point out is how the language is retrieved by extending the  Nancy type Request. It should be easy enough since it exposes the Headers.AcceptLanguage property. Unfortunately, the language string is not parsed and weighed as it should be (yet) and the whole language string is passed in the first element of the collection. Well, since I am hosting Nancy in ASP.NET, I have all the “power” of the ASP.NET pipeline, and the weighed collection of languages can be accessed from the current HttpRequest.UserLanguages property (as long as testability is not a big concern).

public static CultureInfo GetLanguage(this Request request)
{
    HttpRequest http = HttpContext.Current.Request;

    return request.Query.lang.HasValue ?
        CultureInfo.GetCultureInfo(request.Query.lang.Value) :
        fromRequestOrInvariant(http);
}
private static CultureInfo fromRequestOrInvariant(HttpRequest request)
{
    return (request.UserLanguages ?? Enumerable.Empty<string>())
        .Select(CultureInfo.GetCultureInfo)
        .FirstOrDefault(ci => !ci.IsNeutralCulture) ?? CultureInfo.InvariantCulture;
}

In the above snippet one can see the clever use of dynamics to access query-string values (via a dynamic property with the key of the element that gives access to an object that let know whether the key has a value and which value is that).

Opinion

I have to admit I did not expect Nancy to be in such a good shape. The site looks gorgeous, documentation is available, community is growing and getting it up and running was a pleasure.

And what is more important: what they preach about low ceremony and simplicity cannot be more true. Most of the decisions make sense and look clean and approachable.

Its simplicity and youth make it lack some features I needed out of the box (such as dynamic response formatting) but I am certain that they will come.

Definitely a strong candidate to be taken very seriously.

 

UPDATE: I mentioned that how the Accept-Language header was not parsed correctly. Well, I created a new issue in their GitHub repository. Literally, minutes passed until I received feedback and hours until a pull request was issued with the fix. That, dear readers, is just another testimony of how awesome OSS can become.

RESTing in the Laurels

on Wednesday, 11 January 2012

Late Happy New Year to everyone!

For the first of 2012 let’s start with a short series of post about my adventures in finding a suitable web framework that makes likeable building REST services.

Corralling the Problem

Very rarely I write about concrete pieces of work I perform for my customers. This time I will break the rule, since this instance is about a proof of concept and no details are going to be given away.
Hopefully, someone that faces the same problem I faced when choosing, can find my journey interesting.

The proof of concept that scopes my findings is about creating simple URL-accessible read-only services. The information returned can be localized and be returned in various formats (XML and JSON), chosen by the consumer. Of the services to be built, the most “complex” is returning some sort of catalog information, having two endpoints: one that returns a snapshot of all of them and another endpoint that returns an extended version of a single one.

Non-Functional

As the reader can see, the functional requirements aforementioned are really simple. The non-functional requirements will, as well, be concrete.

For one, services need to be easy to develop. That rules out any framework that require extensive configuration and/or a great deal of ceremony (yeah, WCF I am looking at you!).

They also need to be HTTP-friendly. HTTP is a simple protocol but often misunderstood and underestimated. It covers all my requirements and a great deal more. For example, content negotiation is possible by expressing a rich set of formats accepted by the client in the headers, and extra formats can be defined to cover scenarios such as versioning. Likewise, localization is achieved with the same technique, including a weighted list of languages the client request the information in. Standard return codes provide a standard vocabulary of possible outcome and caching information can be specified.

Unfortunately, as rich as HTTP is, there are a wealth of bad clients to the protocol and shortcuts to be taken. Of those, we contemplate an easy way to override both the language and format of the response by the means of providing query-string arguments.

Nice-to-have extras that won’t probably be needed in the firsts versions are:

performance: it should  lightweight enough to not become a problem when multiple clients perform requests. I want my code to be the scalability problem if they ever exists

extensibility: being able to easily get in the middle of the request pipeline at several stages in order to clean up the implementation of the service itself

coolness: it should be pleasant to work with and have a strong community that can provide knowledge when newer features that need advanced usages come. OSS is a plus, but not required. Oddly enough all the frameworks analyzed give access to their source code.

The Contenders

My time is limited for the task and there are lots of such frameworks that can be used for my problem. So I framed the products to evaluate to:

  1. Nancy
  2. OpenRasta
  3. ServiceStack
  4. WebApi

Contract Verification in NUnit. Comparisons

on Monday, 12 December 2011

Before anyone gets confused I am using a very broad definition of contract that it is not related at all with Code Contracts or Design by Contract.
What I mean by contract is the correct implementation of an interface that has become idiomatic. And before you ask, an interface is not a contract. I consider it part of the definition of a contract, but it lacks on the definition of the obligations of client and supplier and most importantly, the verification of such contract. And also before you ask, no, Code Contracts do not provide all the means to express complex obligations and outcomes when conditions are met.

One of such contracts that are pervasive in the .NET Framework is IComparable<T>. This useful interface define how two types can be compared for the purpose of sorting. As a matter of fact, it is so useful I have already written about it in the past in the Equality and Comparison series. One missing point in such series is how to check that we have fulfilled all the un-checked obligations (they are written, although scattered, in the interface and operators documentation).

Greener Pastures

Other testing frameworks, such as MbUnit, have had a way to verify those obligations for some time now, in the shape of contract verifiers. Their implementation of the idea is such that complete test fixtures are created for the verification purpose, making my endeavor of porting such functionality to the NUnit I use and almost love a pretty difficult one, as that would make me dig deeper than I feel compelled to in the inner working of its provider model. Besides, MbUnit’s syntax is not something I am very fond of, so a re-write was bound to happen.

Framing the Problem

The problem with comparison if not very complex, but it has to be done right.

In its simplest form, can be defined that types should return a negative value when compared against a bigger value, a positive value when compared against a smaller value and zero when compared against an equal value. Oh, and one has to keep in mind those pesky nulls. Oh, and one has a handful operators that could ne checked too. Oh, and one can compare types against other types, not just itself. Oh, and what we have to check is the same regardless of the type that implements the comparison we are testing.

It is easy to see that the number of combinations and the fact they are repetitive make the subject a perfect candidate to receive a helping hand.

The helping hand

Testing? Asserting for correctness? Looks like a task for Testing.Commons.NUnit. And indeed it is.

To start with, the problem can be presented like an assertion over several values and can be split into several parts: the implementation of IComparable<T>, being T the same type of the instance being asserted; the implementation of IComparable<T>, where T is not the same type as the instance being asserted; the implementation of comparison operators (<, >, >=, <=) against the same type as the instance being asserted; and the implementation of comparison operators against other types.

For the first two cases (the implementation of IComparable<T>), the custom constraint ImplementsComparableConstraint is used, maybe through the Must.Satisfy.ComparableSpecificationAgainst() extension. Its usage is really simple:

[Test]
public void ComparableToSelf()
{
    ComparableSubject target = //...
    ComparableSubject lessThanTarget = //... 
    ComparableSubject greaterThanTarget = //... 

    Assert.That(target, new ImplementsComparableConstraint<ComparableSubject>(lessThanTarget, lessThanTarget));
    Assert.That(target, Must.Satisfy.ComparableSpecificationAgainst(lessThanTarget, lessThanTarget));
}
[Test]
public void ComparableToOther()
{
    string eq = "eq", lt = "lt", gt = "gt";
    ComparableSubject target = //...

    Assert.That(target, Must.Satisfy.ComparableSpecificationAgainst(lt, gt, eq));
}

Provide either two or three instances of the type it is being compared against, one that is greater and one that is smaller and maybe one that is equal (when comparison to itself is not possible) and the combinations with null and not null values will be checked, providing a nice informative message when the type does not honor the contract.

A type that implements comparison operators to <ComparisonAgainstSelf>.
<target> must be <= (less than or equal to) <target>
  Expected: True
  But was:  False
A type that implements comparison operators to <String>.
<target> must be < (less than) "gt"
  Expected: True
  But was:  False
A type that implements IComparable<ComparableSubject> contract.
<target> must be greater than <lt>
  Expected: greater than 0
  But was:  -1
A type that implements IComparable<String> contract.
<target> must be less than null
  Expected: less than 0
  But was:  2

For the next two cases (the implementation of comparison operators) the custom constraint ImplementsComparisonConstraint is used, maybe using the Must.Satisfy.ComparisonSpecificationAgainst(). Again, the usage is really simple:

[Test]
public void ComparableToSelf()
{
    ComparisonAgainstSelf target = //...
    ComparisonAgainstSelf lt =  //...
    ComparisonAgainstSelf gt =  //...

    Assert.That(target, Must.Satisfy.ComparisonSpecificationAgainst(lt, gt));
}
[Test]
public void CanBeCreatedWithExtension_ComparableToOther()
{
    ComparisonAgainstReference target = //...
    string eq = "eq", lt = "lt", gt = "gt";

    Assert.That(target, Must.Satisfy.ComparisonSpecificationAgainst<ComparisonAgainstReference, string>(lt, gt, eq));
}

Again, just provide some instances to compare against and the right combinations of null and not null values would be checked. Error messages are likewise descriptive:

A type that implements comparison operators to <String>.
<target> must be < (less than) "gt"
  Expected: True
  But was:  False

Peek inside

The implementation itself is not terribly sophisticated once the problem is laid out. But there are a few important tricks that made the code so much easier to write (and much DRY-er).

One of the  most important internals is the concept of ChainedContraints. This is just a simple chain-of-responsibility collection of constraints, that will be lazily executed until one of them fail, in which case, it will be surfaced in order for part of the error message to be written by that failing constraint.

Another interesting trick has to do with the fact that operators are static constructs and, therefore, there is no way to represent them as an interface or a generic class. What one can do is, instead, use code generation to build a delegate that represents the operation. I used (and changed a bit) a working implementation from MiscUtil after remembering an article about generic numeric operations. Basically it uses expression trees to generate the delegates the execute the operators. Clever thing indeed.

What else?

So far, nothing else. Go get, use and give feedback Testing.Commons.NUnit from its Nuget home. And stay connected, if you will, for more of these contract checkers/verifiers.

The Sixth OSSense

on Thursday, 1 December 2011

I think I heard Mr. Hanselman say once that a .NET Open Source project does not exist if was not available through Nuget. That was said very, very early in the “packaging game”, but hey, bluffs are so cheap to make!
I did not take it seriously, of course. My lack of vision is legendary as I genuinely believed that finding the OSS project page, downloading a zip and adding an assembly reference was not that painful.

Oh, The Pain

I was wrong. Well, it is not that painful. But there are two steps in the process that can go horribly wrong.
First: finding the project. Even with pages and search engines devoted to the noble task of finding Open source projects, it is not a simple task to get a useful project found.
Second: downloading the binaries. Let’s face it, some of the people that write wonderfully handy tools and library are the same that do not know how to put together a nice, usable site for a fellow programmer to get a glimpse of what your useful piece of software can do and most importantly: how to even download it and get it running. And do not get me started with those projects that you have to build (compile is so unfashionable these days) in order to use. You should be writing OSS for people to use and for the clever, helping ones to contribute and improve it. But do not scare the hell of the less knowledgeable ones with a stupidly complex process when what they only want is use what you have created and, maybe, thank you.

Sucking a bit less

With the advent of packaging systems one of the steps is dead easy: finding the project becomes navigating the equivalent of an App Store (I hope I do not get sued for using the term) and read the more or less descriptive synopsis. That is how spoiled we have become.
Has “I want if now, fast and free” attitude, the instant gratification society, the epicureal orgy ruined the hippy OSS mindset? I do not think so. Everything evolves. What was acceptable some time ago it is not anymore, because something better/more accessible  substituted it. And now, there is little to none excuse to be snobbish and not making your OSS project available for the masses.

Not so fast, Tiger

Is it enough? Not for me. Let me tell you how it goes with me, dear OSS project:

image

Summing it up: if you are not in Nuget chances of finding you are slim and if you are up there, you better have a half-decent project page.

Mind you, I am not being spoiled or arrogant. Do not take it personally. It will be a loss for us both if we do not get to know each other.