Bruce Sterling's "Black Swan"

December 31 2013

What is the black swan? Check out the short story "Black Swan" by the venerable Bruce Sterling from his collection Gothic High Tech.

Yet the news never shouts out that history has black swans. The news never tells us that our universe is contingent, that our fate hinges on changes too huge for us to comprehend, or too small for us to see. We can never accept the black swan's arbitrary carelessness. So our news is never about how the news can make no sense to human beings. Our news is always about how well we understand.

Whenever our wits are shattered by the impossible, we swiftly knit the world back together again, so that our wits can return to us. We pretend that we've lost nothing, not one single illusion. Especially, certainly, we never lose our minds. No matter how strange the news is, we're always sane and sensible. That is what we tell each other.

..."You've got a look on your face right now like a drowned fish."



Adding A Custom Header When Posting JSON Using HttpClient

November 8 2013

UPDATE: See the comments for a better way to do this!

HttpClient comes with handy methods for the very common task of posting JSON to a web service using the various PostAsJsonAsync methods. It handles serializing your object and crafting up the http request for you, aka

var gizmo = new Product() { Name = "Gizmo", Price = 100, Category = "Widget" };
Uri gizmoUri = null;
response = client.PostAsJsonAsync("api/products", gizmo).Result;
if (response.IsSuccessStatusCode)
    gizmoUri = response.Headers.Location;
    Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);

However, what happens if you need to add a custom header to your request? The only way to add a custom header is to craft up an HttpRequestMessage. And the nifty PostAsJsonAsync won’t take a HttpRequestMessage as a parameter; you have to use the SendAsync method.  No sweat; you have to write a little more code but it is no big deal. Here’s what it looks like:

var gizmo = new Product() { Name = "Gizmo", Price = 100, Category = "Widget" }; 
Uri gizmoUri = null;
MediaTypeFormatter jsonFormatter = new JsonMediaTypeFormatter(); HttpContent content = new ObjectContent<Product>(gizmo , jsonFormatter); var request = new HttpRequestMessage() { RequestUri = new Uri("api/products"), Method = HttpMethod.Post, Content = content }; request.Headers.Add("My-Special-Header", "xx-oo-xx-oo"); var response = _httpClient.SendAsync(request).Result;

Unit Testing HttpClient In An ASP.NET MVC Controller

November 7 2013

The nice thing about HttpClient is that it was designed with unit testing in mind, unlike previous .NET http objects like WebClient and WebRequest which required you to write wrappers. As such you don’t need to use dependency injection in order to unit test HttpClient, which keeps your code that much more readable.

So, how to do it?

First, you need to pass HttpClient into the controller’s constructor in your MVC project. Again, the nice thing is that you don’t have to do dependency injection for this with a framework like Unity. The easiest way to do that is via constructor chaining, like this:

public class MyController: Controller
  private readonly HttpClient _httpClient;

  public MyController() : this(new HttpClient())

  public MyController(HttpClient httpClient)
    _httpClient= httpClient;


Then, in your tests, you’ll need to fashion up a FakeHandler like this:

 public class FakeHandler : DelegatingHandler
            public HttpResponseMessage Response { get; set; }

            protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
                                                        CancellationToken cancellationToken)
                return Task.Factory.StartNew(() => Response);

which you will use when you new up your HttpClient in your tests. Now, in you’ll need to set up the HttpResponseMessage before you instantiate the HttpClient in your tests. If you are expecting string content in the response, in the case of getting JSON for instance, here’s how that might look:

string json;
using (StreamReader reader = new StreamReader("json.txt"))
        json = reader.ReadToEnd();
var response = new HttpResponseMessage(HttpStatusCode.OK);
byte[] array = Encoding.ASCII.GetBytes(json);
ByteArrayContent content = new ByteArrayContent(array);
response.Content = content;

Here we are grabbing some pre crafted JSON from the file system, throwing it in a byte array and then giving that to our HttpResponseMessage.

Now, that we have our expected response set up, we use that in our FakeHandler when we instantiate the HttpClient for the test:

var httpClient = new HttpClient(new FakeHandler
       Response = response,
       InnerHandler = new HttpClientHandler()
MyContoller myController = new MyController(httpClient);

And, there you have it!

Fluent Validation and ASP.NET MVC

October 23 2013

Enamoured with Fluent Validation. So easy to use, well documented, intuitive. Plumbed right into ASP.NET MVC with an addition to Application_Start and an attribute on your model and yr good to go. I was up and running with the project in no time at all. Not all open source projects are like that. :)

I think the coolest part is the fluent interface, which allows super cool chaining logic. The When() and Unless() methods are quite handy as well, which makes creating complex logic when validating your model simple.

Was going to provide some code samples, but the project is so well documented that I don’t think that’s even necessary!

Using GitFlow With Powershell

October 11 2013

We are using GitFlow on our team but I don't want to use CygWin; I'm not a Bash kind of guy. There are instructions for installing GitFlow for use with the Git PowerShell window here.  However, there are some gotchas. First, you'll need getopt.exe and libintl3.dll. To make your life easier, I've attached them as a zip file to this post.

Second, note that you have to follow their instructions exactly when cloning the gitflow repo. You have to run the command

git clone --recursive git://

If you don't and just run a git clone command without specifying recursive, you may get the following error when you attempt to run the msysgit-install script:

File not found - shflags
0 File(s) copied
Some unexpected errors happened. Sorry, you'll have to fix them by yourself. [Y]?Y

Hopefully, that might help someone out there... (59.05 kb)

Getting Twitter Profile Image Via C# With 1.1 API

May 1 2013

If you know someone's Twitter handle and would like to display their twitter avatar on your website, here's some code to get the URL of their avatar.  First, you'll need to register at and acquire a ConsumerKey, ConsumerSecret, Token and TokenSecret -- now that Twitter supports application only authentication, there isn't any handshaking involved; you just need to craft up the right OAuthCredentials for a ProtectedResource, which the Hammock library does for you. Love that library: you can get it here: or grab it as a NuGet package:

Here’s the code; nothing too fancy:

using System;
using Hammock;
using Hammock.Authentication.OAuth;
using Hammock.Web;
using Newtonsoft.Json.Linq;

namespace ExternalServices
    public class TwitterAvatarLookup : ITwitterAvatarLookup
        const string ConsumerKey = "";
        const string ConsumerSecret = "";
        const string Token = "";
        const string TokenSecret = "";

        public string GetTwitterAvatarUrl(string twitterHandle)
            string avatarUrl = string.Empty;
            var request = new RestRequest
                Credentials = new OAuthCredentials
                    Type = OAuthType.ProtectedResource,
                    SignatureMethod = OAuthSignatureMethod.HmacSha1,
                    ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
                    ConsumerKey = ConsumerKey,
                    ConsumerSecret = ConsumerSecret,
                    Token = Token,
                    TokenSecret = TokenSecret,
            request.Path =

            request.Method = WebMethod.Get;
            RestClient client = new RestClient();
                RestResponse response = client.Request(request);
                JArray jArray = JArray.Parse(response.Content);
                avatarUrl = (string)jArray[0]["profile_image_url_https"];

            catch (Exception)
                return "default.png";
            return avatarUrl;


If you know more than one handle whose avatar you need to get, the API supports passing multiple user handles; see

Saving a PDFSharp PDF File To Azure Blob Storage

March 1 2013

Love the PDFSharp library. Here’s how I went about saving a PDF generated with that library to Azure blob storage:

const bool unicode = false;
const PdfFontEmbedding embedding = PdfFontEmbedding.Always;
PdfDocumentRenderer pdfRenderer = new PdfDocumentRenderer(unicode, embedding);
pdfRenderer.Document = document;
MemoryStream memStream = new MemoryStream();

var client = new CloudBlobClient(new Uri("http://*", UriKind.Absolute),
new StorageCredentialsAccountAndKey("*",

var container = client.GetContainerReference("temp");
memStream.Seek(0, SeekOrigin.Begin);
string filename = DateTime.Now.ToString().GetHashCode().ToString("x") + ".pdf";
var pdf = container.GetBlobReference(filename);
pdf.Properties.ContentType = "application/pdf";
pdf.UploadFromStream(memStream, new BlobRequestOptions { Timeout = TimeSpan.FromMinutes(10) });

The crux of the code is the line where pass false to the Save method of PdfDocument, which keeps the memory stream open. And, then, before giving that stream to the Azure SDK method, you need to rewind the stream to the beginning. Other than that, all pretty boilerplate.

Capture ClickOnce File Downloads With Event Tracking In Google Analytics

March 1 2013

This flummoxed me for a bit, so I figured I post it. If you wire the event up to an onClick handler as the docs suggest:

<a href="app.application" onClick="_gaq.push(['_trackEvent', 'ClickOnce', 

Your event will never fire. The trick is to add the target attribute and set it to _blank which opens a new tab in the browser and immediately closes it:

<a href="app.application" target="_blank" onClick="_gaq.push(['_trackEvent', 'ClickOnce',

Windows Azure Table Storage Emulator UpdateObject Error

January 21 2013

Was getting this:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<error xmlns="">
  <message xml:lang="en-US">One of the request inputs is not valid.</message>

When calling UpdateObject from the Azure SDK when using the table storage emulator. Turns out the emulator doesn’t exactly emulate as per MSDN documentation: “The storage emulator does not support Insert-Or-Replace Entity or Insert-Or-Merge Entity, known as upsert features.”

So, to work around, I changed the code to delete then reinsert.  Or not. Turned out I had lots of concurrancy problems with doing a delete/insert which were resolved with the more transactional upsert. 

Sorting ListBlobs By LastModifiedUtc

December 3 2012

I had a list of JSON objects stored as individual blobs in Azure blob storage. I needed to get them out of blob storage sorted by last modified time and then reconstitute them as an array of JSON objects. Hit a few curiosities in writing this code, which someone else may benefit from. Without further ado, here’s the code:

            CloudBlobDirectory dir = eventContainer.GetDirectoryReference("http://---");
            SortedDictionary<DateTime, string> dictionary = new SortedDictionary<DateTime, string>();
            foreach (CloudBlob blob in dir.ListBlobs())
                if (blob.Name == string.Format("{0}/$$$.$$$", "live")) continue;
                dictionary.Add(blob.Properties.LastModifiedUtc, blob.DownloadText());
            StringBuilder json = new StringBuilder();
            foreach (string s in dictionary.Values)
            json.Remove(json.Length - 1, 1);
            CloudBlob liveJson = dir.GetBlobReference("live.json");
            liveJson.Properties.CacheControl = cacheControl;

Okay, so what is going on here?

I start out with a nifty SortedDictionary, which will sort my items by the key of the dictionary as I add them.

I then call ListBlobs(). There’s this peculiar oddity with Blob Storage when you use CloudXplorer where this ghost file name $$$.$$$ gets created, which is why I have to check the name of the file. I then throw the string and the date into the dictionary.

Once that finishes, I iterate the dictionary, adding the callback and syntax for making a json array. Get rid of the final comma and then throw the whole deal back into blob storage. Hoorah!

At first, I was actually deserializing the strings into objects using JSON.Net and then I realized there was no reason to do that when all I needed to do was manipulate strings.