There's always something new to learn today

Adding pure Java unit tests to an Android project

This post has a very slim target audience: developers who

  • are not familiar with gradle
  • are not familiar with android development
  • have some exposure to Java (enough to create a class)
  • have done mobile development (Windows Phone/iOS)
  • are interested in writing "pure" unit tests for Android
  • are working with an existing Android project that succesfully builds and runs

If you meet all those criteria, come join me on a journey that seems (mostly) poorly documented. Perhaps I haven't been searching for the right terms, but regardless I'm going to put my findings here. I'm currently using Android Studio 0.8.9.

We will assume the following project struture for the android app. The libraries folder is completely optional; the main thing is that the android-dependant app source code is in src.

    - build.gradle
- build.gradle
- settings.gradle

Here's what we want to accomplish:

  1. add a "regular" or "pure" Java module so that it can be used by the Android application
  2. be able to write jUnit tests for this module and then run these tests from Android Studio

1. Adding the Java module

  • Create a pure directory under libraries.
  • Create a src/main/java directory under pure (for source code). Under that, create the appropriate com.example.pure directory.
  • Add an empty Java class to the last-created directory (for this example, I'm using MyClass)
  • Create a file called build.gradle in your pure directory. It only needs to contain a single line: apply plugin: "java".

(Note: if you have the 1.8 JDK installed, you have to force your pure Java module to use 1.7, as that's what Android currently supports. If you do not, you will get a very weird build message like [ERROR] bad class file magic (cafebabe) or version (0035.0000). To do this, add the following two lines to build.gradle:

sourceCompatibility = 1.7  
targetCompatibility = 1.7  

We now have this:

      - build.gradle
- build.gradle
- settings.gradle
  • To get our module to build, update settings.gradle in the root folder.
include ....., ':pure'  
project('pure').projectDir = new File('libraries/pure')  

At this point you should be able to build your app and new module successfully.

Using the module from an Android app

We can ensure the "pure" module is accessible from our Android application by attempting to use it.

  • In $/app/build.gradle, add compile project(':pure') to the dependencies section.
  • Android Studio will probably tell you it needs to sync (let it). If you look at the Gradle Console, you should see :pure:compileJava, :pure:processResources, :pure:classes and :pure:jar in the output.
  • Reference your new object from any class in your Android application. It should still build and run as before.

2. Adding jUnit tests

  • Give your sample class an add() method that takes two integers and returns their sum. We need something to test :)
  • Add the following to build.gradle (the one in pure)
dependencies {  
    testCompile group: 'junit', name: 'junit', version: '4.11+'

(I'm assuming your main project already has repositories setup. If not, add repositories { jcenter() } as well.)

  • Create a new class in $/libraries/pure/src/test/java/com.... (For this example, I have MyClassTest). Make sure it is public.
  • Add a test to it. As an example, here's what I have:
import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class MyClassTest {

    public void testAdd_CanAddTwoNumbers() {
        MyClass sut = new MyClass();

        int result = sut.add(3, 4);

        assertEquals(7, result);
  • Make sure everything still builds.
  • Right-click on your class and choose 'Run {MyClassTest}'. The output should show "all tests passed."

The "protocol violation" with the misleading error message

Before reading this, refresh your memory of Joel Spolsky's wonderful post on the Law of Leaky Abstractions.

After determining it was possible to write a replacement HttpClient for WP8.1 Silverlight, I wanted to go a bit deeper and propose an actual fix for the devs at Mashape. Although submitting the error message (The server committed a protocol violation. Section=ResponseHeader Detail=CR must be followed by LF) seemed sufficient, given that the problem persisted a month later I wondered if something was wrong with the .Net framework (hah!)

Strings, Bytes, and CRLF

The relevant code in my "custom" HTTP client that read data from the StreamSocket.InputStream (via a DataReader) looked like this (simplified):

await reader.LoadAsync(10240);
data += 

Viewing the value in the debugger or outputting it to the debug window didn't show any obvious missing line-feeds, but perhaps the reader was doing something weird.

Swapping the code to

await reader.LoadAsync(bytesToRead);
var buffer = new byte[reader.UnconsumedBufferLength];

also showed that everything was as it should be. Every single line in the response header ended in 0D0A.

Just in case the reader was doing something weird, I double-checked in Fiddler. Sure enough, there were only 0D0A pairs.

Huh. I figured at this point it was time to go step through the Framework code.


I knew from reading Mehdi's extremely in-depth article on the same problem that problem probably stemmed from somewhere in ParseHeadersStrict, although it took me a while to get there. Given that I had verified from two different sources that every header line did end in CRLF, I thought perhaps something else in the Framework was acting up. As it turns out, it was exactly where I should have looked in the first place.

Here's the relevant code from WebHeaderCollection.cs. At this point we are looping through a byte[] buffer containing the response.

// Find the header name; only regular characters allowed.
int iBeginName = i;
for (; i < effectiveSize && 
      (ch = 
         byteBuffer[i] > 127 ? 
           RfcChar.High :
       == RfcChar.Reg; 

Gotta love the ternary operator and assignment used for the comparison inside the condition section of a for loop :) Basically, this is looping through each line of the response header looking for lines like

Content-Type: application/json; charset=UTF-8

and ensuring they're valid. The above loop is ensuring that the header name (before the colon) doesn't have any weird characters in it.

The next portion of code ensures that we read the colon and header value and Most Importantly that the line ends with CRLF. Given how many times I had seen the error message CR must be followed by LF, I was quite curious to see how this was going to fail.

// Read to a colon.
int iEndName = i - 1;
int crlf = 0;  // 1 = cr, 2 = crlf
for (; i < effectiveSize && 
      (ch = 
         byteBuffer[i] > 127 ? 
           RfcChar.High : 
      != RfcChar.Colon; 
  switch (ch)
    case RfcChar.WS:
    if (crlf == 1)
    crlf = 0;

    case RfcChar.CR:
    if (crlf == 0)
      crlf = 1;

    case RfcChar.LF:
    if (crlf == 1)
      crlf = 2;
  parseStatus = DataParseStatus.Invalid;
  parseErrorCode = WebParseErrorCode.CrLfError;
  goto quit;

And yet it blew up. Again. Even though I could see in the VS Memory window that every single 0D was followed by OA.

After a round of tracing, I noticed that the header was mostly being parsed. And then it jumped out at me. The line it was failing on looked like this:

X-RateLimit-API Requests-Limit: 7500

and there was definitely something different about that header name compared to all the others.

The Devil, the details, and RFCs

Those of you who have worked with HTTP at this level will immediately know the issue here, but I'm brand new to it so off to read the spec I went. It didn't take long to discover these very pertinent sections:

Message Headers

message-header = field-name ":" [ field-value ]
field-name     = token

Augmented BNF

SP             = <US-ASCII SP, space (32)>

token          = 1*<any CHAR except CTLs or separators>
separators     = "(" | ")" | "<" | ">" | "@"
                  | "," | ";" | ":" | "\" | <">
                  | "/" | "[" | "]" | "?" | "="
                  | "{" | "}" | SP | HT

I can't highlight code, but the point is that you can't have a space in the header name. Very simple. And although Microsoft was correct to disallow this in their strict interpretation of RFC2616, it would have been nicer to have a different error message for this scenario instead of:

The server committed a protocol violation. Section=ResponseHeader Detail=CR must be followed by LF`

I sent all this info off to Mashape this evening and am hoping they can fix it soon.

Update: Mashape fixed this issue on August 21.

Dealing with a "protocol violation" on WP 8.1

In my last post, I discussed how Windows Phone and Store apps will refuse to parse HTTP responses (namely headers) that do not strictly follow RFC2616. After a few weeks of waiting for Mashape to fix their responses, I thought it might be worth it to explore other options.

The first idea was to implement a custom handler, but that quickly ended when I found out that the system's handler gets called first for a response.

The above image used to be hosted at but the page disappeared in the last day or two.

After stumbling through the usual mix of Windows Phone 8.1 Silverlight vs Store (RT) docs, I came across an RT class that is also available on Silverlight: StreamSocket. Knowing very little about the protocol, this page and the RFC page on Messages the were a great resources.

It turns out (ignoring error handling, edge cases, etc. etc.) that you can implement your own HTTP client fairly simply!

var hostname = new HostName("");
var socket = new StreamSocket();
await socket.ConnectAsync(hostname, "80");

var request = "GET /Protocols/rfc2616/rfc2616-sec4.html HTTP/1.1\r\n" +
              "Host:\r\n" +

var writer = new DataWriter(socket.OutputStream);
await writer.StoreAsync();

var reader = new DataReader(socket.InputStream);
reader.InputStreamOptions = InputStreamOptions.Partial;

string data = string.Empty;    
var cts = new CancellationTokenSource();

bool doneReading = false;
uint bytesToRead = 4096;
uint totalBytesRead = 0;

while (!doneReading)
    cts.CancelAfter(10 * 1000);
    var bytesRead = 
      await reader.LoadAsync(bytesToRead).AsTask(cts.Token);
    data += reader.ReadString(reader.UnconsumedBufferLength);

    totalBytesRead += bytesRead;
  catch (TaskCanceledException)
    doneReading = true;


Since LoadAsync returns the # of bytes loaded into the stream, you might think (as I did) that if it was less than the bytesToRead parameter the response was over and you could close the socket. Unfortunately this isn't necessarily true.

This (lazy) sample solution lets the socket timeout after 10s and assumes that since the server has stopped sending information, all is well.

The correct way to do it, as Jon Skeet has already pointed out, is to parse the header, read the value of Content-Length and then request the appropriate amount of data aftewards. This is slightly non-trivial, as you are dealing with a stream and there is no built-in way of magically parsing out the header nor its contents. It's far from difficult, though, and I will post a Github link once I get some decent looking code prepared.

The only other tweak left was to switch to https to work with Mashape. This is as simple as replacing

await socket.ConnectAsync(hostname, "80");


await socket.ConnectAsync(hostname, "https", SocketProtectionLevel.Tls12);

Now we can handle "protocol violations" on Windows Phone/Store apps with no problems!

(Actually, if you are on a WinRT app, MessageWebSocket seems like an even easier solution.)

WP8 Debugging for Fun and ... Profit?

Since I lost several hours on this today, I thought I'd quickly share my experience. There were very few results for the inital terms I searched for so perhaps this may help someone in the future.


I've been working on what will hopefully be my first released Windows Phone app (8.1 Silverlight) for the last two months. When I say two months, I worked on it for two weeks before the World Cup started and finally picked it up again today.

In the interim, it appears that Mashape has slightly changed the way you use their API. Or, more specifically, they've removed developer keys and only app-specific keys remain. (This was the first 30 minutes lost; I still don't see a tweet or blog post about this).

So it's my own fault I'm only now discovering there have been some changes:

  • the removal of account keys
  • the websuite UI (which is very difficult to view in Chrome on Windows)
  • the data returned from an API call (?!)

Complete Confusion

After noticing the sample API page required you to now use X-Mashape-Key instead of X-Mashape-Authorization, I went ahead and made a bunch of other changes to my app without running it (Poor, poor Avatar). As soon as I made an API request, the code crashes with

Catastrophic failure
(Exception from HRESULT: 0x8000FFFF (E_UNEXPECTED))
at System.Runtime.CompilerServices
                 .ThrowForNonSuccess(Task task)
at System.Runtime
         .HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices

Here's the code that had worked so well a few weeks ago:

var httpClient = new HttpClient();
          .Add("X-Mashape-Authorization", "...");

var uri = new Uri("...");
var response = await httpClient.GetStringAsync(uri);

var stuff = JsonConvert.DeserializeObject<...>(response);

Huh. What had I missed?

  • using an await incorrectly
  • some kind of incorrect binding
  • a change to the WP SDK
  • ???

So I undid all my changes, changed the one header, and still got the same crash.

Which usually means the Emulator is broken. Or Visual Studio. Or perhaps even the OS. After a complete relaunch and reboot, it turned out it was still my problem.

Fiddler to the rescue! Or not.

My next thought was that perhaps along with the header name change, I needed to include some more information in the GET request. I could tell from my REST client that I shouldn't need anything else, but you never know. After hacking around with Fiddler for the better part of an hour (see here and here), I gave up.

Windows Store

I know Windows Phone Silverlight has its own quirks, but since there is still an overlap with WinRT apps, I thought perhaps creating a "normal" Windows Store app might help. There was also a better possibility of it working with Fiddler.

And yet the same crash persisted.

Even trying HttpRequestMessage and GetStringAsync yielded the same odd Catastrophic Failure. "PC Load Letter???" Seriously!

The one odd, ODD thing was now Fiddler was showing me a proper result. No HTTP error codes or gobbeldygook; the response seemed like exactly what I'd expect.

Good ol' WPF to the rescue

Throwing together a sample WPF app finally rewarded me with some useful information:

The server committed a protocol violation. Section=ResponseHeader Detail=CR must be followed by LF

And a few quick searches later,

(wonderful, for WPF apps - it took all of two seconds to verify the app.config change would let the SendAsync pass)

followed by

(not so good for Windows Store or Windows Phone apps. Sigh.)

Browsing through the code for unirest-net I couldn't see how it would possibly work even with Mashape's own recommended library. But, just in case, I downloaded it, built it, and was "rewarded" with the same message a few minutes later.


Windows Phone and WinRT error messages can be very annoying to debug. And depending on a third-party for your app can be very trying. But the sense of satisfaction at being able to submit a "good" bug report is ... almost worth it :)

I'm off to submit a bug report and cross my fingers. Let's hope I didn't miss something really simple in my investigation...

Update (July 25): Although I did get a dialog started with Marco and Morgan, the only advice I've received so far is to use the app.config fix (which doesn't work on Windows Phone). I'm really glad we hadn't launched a product yet; we'd have some very unhappy customers at this point.


I've been having a lot of fun playing Hearthstone recently; what's kind of interesting with the new Battle.Net app launcher is looking at your purchase history with Blizzard.

Somehow, between 2005-2007 (I blame Timm) and 2010 (I blame Brad, Scott, and Peter), I managed to spend over $500USD extra (mostly at a time when the Canadian dollar was substantially lower) on a $60 game.

Well done, Blizzard. Well done :)

Developers + Canadian non-profits = success


How to help out a Canadian non-profit on a shoestring budget.

I've been trying to share my progress with helping out the OrlĂ©ans Festival over the last few months, all the time saying to myself – I should really write one comprehensive page about all this.

Are you a developer? Do you live in Canada? Read more about why you should be helping a local non-profit.

After talking with a few people, I'm hoping that I can provide a list of services that developers can use to help out Canadian non-profits in their community.

tl;dr - Sign up for (at least):

All of this information is geared towards assising non-profits who have zero or no budget to spend on technology (like mine). For full disclosure, I have spent some of my own money on services (as a donation, because I think it's worth it) and have pointed that out where appropriate.

If you know what a CNAME record is, skip parts 1, 2 and possibly this entire post!

1. Domains

You must be master of your domain.

For an organization who doesn't have a domain name (e.g., go and register with a provider like EasyDNS. You might also want to register the French version (e.g.

If the organization you're working with already has a domain/website, ensure that they also own the account where the domain name is registered. A simple way to verify this is to ask "when is our domain name scheduled for renewal?" — a blank look is not a good sign.

With a blank look, you can start digging for information. Your domain name needs to be renewed on a yearly basis (usually) and with Murphy's Law in full effect for technology, you know that the registration will expire one week before your event/fund drive/etc. Figure this out now sooner rather than later!

2. Identity

You need to either own or register your non-profits name with Twitter, Facebook, Google+, Pinterest, etc.

Trust me. Do it now even if you don't intend to use it. Trying to "recover" a name later on is not fun.

At the very least, you can point these accounts to your domain name (registered in step 1).

3. Website Hosting

As we discussed earlier, "free" or "unlimited" web hosting may not be the best option for your site. If you're working with a non-profit that has one event per year and something goes wrong because your server neighbour is sending a million 419 Scams emails, your patrons will be less than pleased.

My research over the last few months (Oct 2013 - Jan 2014) indicates that Azure is probably the best bet given that you can host pretty much any platform (ASP.NET MVC, PHP, Node.js, etc.), storage prices at least match Amazon S3, and you can scale up or out whenever you need to.

4. Email

There is no question here - sign up for Office 365.

5. Document Storage

This one is a little bit tough. As I mentioned earlier, the best choice for total space (and privacy for Canadians) is definitely

However, if you sign up for Office 365, you do get a ton (25GB) of free storage (via SkyDrive Pro/Sharepoint). And the online editors for Word/Excel are hard to beat. Unfortunately syncing a massive amount of documents can give you some pain. After that, all is well.

6. Version Control

If you haven't yet jumped on the Git bandwagon, then is the answer for you. Anyone with a CVS, SVN, or Sourcesafe (gasp) background will feel right at home. Your projects are all private by default, and you don't need to submit any special paperwork to get extra priveleges. Also, the integration with Azure hosting is very cool. More details here.

Github is also very cool and does offer a great deal to non-profits. Just make sure that anyone helping you out down the road also knows Git...

7. Crowdfounding

As a non-profit, there is a surprising limit as to what is accessible vs a charity. Long story short, for a Canadian non-profit you probably want to use Causevox.

Go here for slightly more information.

8. CRM (Bonus)

Non-profits need to raise money every. single. year. I recently learned that they're only allowed to end each fiscal year with +/- $1000 unless there's proof that they are saving for something (e.g. a building).

You can imagine that fund-raising / sponsorship / grants are a huge things for non-profits. Unfortunately for Canadian ones, I haven't come across anything that's free.

  • Salesforce, regardless of what their webpage claims is NOT available to Canadian non-profits. I've asked them to update their wording.

  • SugarCRM doesn't seem to have any deals for non-profits.

What does that leave? The cheapest, again, is Microsoft's offering. You can get Dynamics (Basic) for $3.75 CAD/user.

Join a community of like-minded developers who want to help Canadian non-profits.