Polly Transient Fault handling UPDATE

I am now using Polly in production and it works awesomely. I followed the same fault handling policy noted on Hanselman’s blog about Polly.

var policy = Policy
.WaitAndRetry(5, retryAttempt => 
  TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), 
  (exception, span) =>
// Log transient error
} );

This is a decidedly easy way to implement an exponential back-off retry policy. On the first retry it waits 2 seconds, by the 5th and final retry it will wait 32 seconds. This means this sql call will wait up to 1 minute for attempting to complete the sql call (ignoring any time spent executing the sql call prior to a sql exception being raised)

Working with HttpClient is absurd

Using Microsoft.AspNet.WebApi.Client (HttpClient) safely to handle both http errors and timeouts is flatly absurd. Look at the follow giant block of code it requires to merely request a URL and record the result or failure reason.

var apiResult = new MyApiResult();

var cts = new CancellationTokenSource();

using (var client = new HttpClient { BaseAddress = host }) {
try {

var response = await client.GetAsync("api", cts.Token);

apiResult.IsHostReachable = true;

if (response.IsSuccessStatusCode) {
    apiResult.Status =
        await response.Content.ReadAsAsync<MyApiStatus>();
else {
    string content = null;
    string reasonPhrase = null;

    try { content = await response.Content.ReadAsStringAsync(); }
    catch (Exception) { /*ignored*/ }

    try { reasonPhrase = response.ReasonPhrase; }
    catch (Exception) { /*ignored*/ }

    apiResult.FaultDescription =  string.Format("{0}-{1} {2}",
        response.StatusCode, reasonPhrase, content);
catch (Exception e) {
var canceled = e as TaskCanceledException;

if (canceled != null && cts.Token.IsCancellationRequested) {
    apiResult.FaultDescription =  host + " timed out";
else {
    apiResult.FaultDescription = e.Message;

    if (e.InnerException != null)
        apiResult.FaultDescription +=  e.InnerException.Message;

I apologize for the awkward placement of braces however between the length and depth of nesting involved it was very difficult to format to even display at all here.

HttpClient was created to replace how poor it was working with the WebRequest class that was from the webforms era long before RESTFUL services existed. It was supposed to eliminate the pain and make things easy to work with modern HTTP APIs. Instead it is arguably even more cumbersome to use. There isn’t even a way to handle timeouts without resorting to exception catching and Liskov Substitution violating direct casts of a base type to a more specific type.

But it supports async/await… that’s something right? right?

The SOA Model Service Fabric vs WCF

I’ve started my trek into analyzing all of the information that has been published by Microsoft on Azure Service Fabric. One of the very first things I noticed is strikingly similar it is WCF. This may be a surprise to some but is not at all surprising to me. WCF has been a much maligned technology, largely for being widely misunderstood.

Let me start with where I feel people were so put off by WCF.

  1. XML configuration. WCF is one of the most (if not the most) interopable and configurable frameworks in the world. This is a double edged sword when coupled with XML. WCF was created in the hayday of XML configuration being the “new hotness” everything needed XML and so it was thrust upon WCF. WCF has never meant to be configured via XML it was built fully strong typed and in fact can be used without a single line of XML configuration entirely. Ask yourself, did you know you could use WCF with strongly typed configuration? That standard configuration exists out of the box in predefined strong types?
  2. WS-* and the web. WCF is at its heart WINDOWS Communication Foundation. It was never built with any concern given to the web. The fact that WCF is immensely interopable it was decided WCF needs to become the replacement for ASMX web services, because it could. This was the early days of SOA and the WS-* standards were created with the belief if they created a wide set of standards that SOA apps would emerge with guaranteed connectivity with each other. Unfortunately the standards that were created were horrific. WCF then took the blame for the standards as it was one of the few systems that was so extensible it could actually even implement the standards for how bad they are.

Now that we’ve talked about is commonly attributed as what’s wrong with WCF let’s talk about WCF and Azure Service Fabric. Working with the examples from Microsoft the following is an illustration of an Actor

public interface ICalculatorActor : IActor {

Task<double> AddAsync(double x, double y);
Task<double> SubtractAsync(double x, double y);

public class CalculatorActor
     : Actor, ICalculatorActor { ....

If this was done in WCF you would have

public interface ICalculatorActor {

double Add(double x, double y);
double Subtract(double x, double y);

public class CalculatorActor
     : ICalculatorActor { ....

So the only difference here is whether you have an decoration model or a marker model. Just to clarify with WCF the async keyword doesn’t need to exist. Whether a service call in WCF will be asynchronous depends on your hosting model, but it absolutely can be asynchronous.

On to the usage model

ActorId actorId = ActorId.NewId();
var applicationName = "fabric:/CalculatorActorApp";

ICalculatorActor calculatorActor
 = ActorProxy.Create<ICalculatorActor>
   (actorId, applicationName);

var result = calculatorActor.AddAsync(2, 3).Result;

With WCF

var actorId = new BasicHttpBinding();
var applicationName = "http://localhost/Service";

ICalculatorActor calculatorActor
 = new ChannelFactory<ICalculatorActor>
    (actorId, applicationName).CreateChannel();
double result = calculatorActor.Add(2, 3);

There is no difference here at all. The only minor difference is the transport binding in the Actor Api is fixed whereas it is configurable in WCF.

What about hosting?

using (FabricRuntime fabric
  = FabricRuntime.Create()) {



ServiceHost fabric
 = new ServiceHost(typeof(CalculatorActor)); 
     actorId, applicationName);

Once again they are virtually identical. The minute difference again is declaring the binding for the end point since WCF supports any binding whereas Service Fabric supports itself only.

Something else that is directly shared between WCF and Service Fabric is the DataContract serialization model.

I’m immensely excited about Azure Service Fabric. I do not wish to be in the plumbing business nor the hosting business. While this is likely premature to state definitively, but it is likely I would never choose to build an application without the Azure Service Fabric. The only question left is when could I go to production and that I have no answer to.

Microsoft announces Azure Service Fabric

Big news today from Microsoft with the announcement of Service Fabric, Redmond’s product answering the needs of not only the future of PaaS (platform as a service) but also the way applications are built and run.

Microsoft has in fact been using the technologies within its own projects for the past five years. Lync, Cortana and Service Bus among other solutions are actually built and deployed using ServiceFabric.

Service Fabric offers the following benefits:

  • It supports creating both stateless and stateful microservices – an architectural approach where complex applications are composed of small, independently versioned services – to power the most complex, low-latency, data-intensive scenarios and scale them into the cloud.
  • Provides the benefits of orchestration and automation for microservices with new levels of app awareness and insight.
  • Solves hard distributed systems problems like state management and provides application lifecycle management capabilities so developers don’t have to re-architect their applications as usage grows.
  • Includes Visual Studio tooling as well as command line support, which enables developers to quickly and easily build, test, debug, deploy and update their Service Fabric applications on single-box deployments, test deployments and production deployments.

Service Fabric sits between the different microservices that make up a modern application and the cloud the application is hosted on. Microsoft itself describes the new service it as “a developer framework that intrinsically understands the available infrastructure resources and needs of applications, enabling automatically updating, self-healing behavior that is essential to delivering highly available and durable services at hyper-scale.”

Even though many of us probably equate microservices with Docker containers, this first version of Service Fabric will focus on Microsoft’s own technologies and Java applications. Microsoft plans to launch support for Docker and its own Windows Server Containers with the next version of Windows Server and it will then also support on-premise support for Service Fabric running on Windows Server.



These are not the widths you were looking for – CSS media query max-width

Today I encountered something very unexpected. I was using basic CSS media queries.

@media (max-width:1205px) {

[role=main] > .row
        padding-left: 8px;

And I have Firebug open because my rows do not have padding-left applied. Firebug is clearly telling me the width of HTML is 1199px well under 1205px.

At this point I’m outright stumped. I copy my CSS outside the media query thinking my selector usage is somehow faulty, and it works fine.

I take to the googles and locate issue with CSS media queries(scrollbar) on stackoverflow. This question acknowledges that browsers treat the scrollbar differently for whether it’s included in the width of the viewport. So when Firebug was reporting 1199px for the width of <html> it was not adding 15px for the scrollbar for a total of  1214px greater than my max-width.

these are not the widths you were looking for

The solution to this problem is mqGenie. Effectively this is a polyfill that normalizes browsers behavior in regards to scrollbars and updates your media queries to account for the scrollbar width if neccessary. It likely has the caveat that it will only work on stylesheets that are served inside the same origin policy.

jQuery Trunk8

Have you written an app where you have an unknown length text block that’s going to go into a grid layout. Perhaps the description to an event? You expect most descriptions to be 1 or 2 lines max, but then someone goes and copy-pastes a word document into your description field.

A great solution to this problem is a jquery plugin Trunk8. You can checkout the demos or view the source on github.

Ultimately trunk8 takes a very long textblock and based on configurable settings will truncate it to … ellipses. The great thing about trunk8 is that it actually analyzes the element that contains the text and bases it’s calculations on actual screen space. It doesn’t do a naive attempt based on number of characters. It also supports html, this was key for me. Using it to truncate a long markdown description block when in general it will consistent of 1 or 2 lines.

jQuery ScrollUp plugin

I wanted to add a scroll to top button to my website. I didn’t want it to rely on being random buttons in the middle of the html. A button like this makes way more sense to be affixed to the UI. It also shouldn’t be visible when you can’t actually scroll up.  Mark Goodyear wrote a great (and simple) jQuery plugin to do this: ScrollUp it is MIT licensed and you can check out the source on github.

View the live demo

$(function () {

Is literally all the source it takes after you include jquery and jquery.scrollup.js files to your page.

It is also highly configurable. Definitely worth a look.

jQuery on click is raised by text selection

So today I was building some basic toggle capabilities into a web page. Everything is working well, then I test selecting the text. Of course this causes the element to collapse on mouse up.

After some googling Stackoverflow of course had the answer…

$('h4').on('click', function() {
    if (getSelection() == "") {
        //do stuff

All it took was wrapping my code in a single if statement using getSelection().

dynamitey and dynamic MVC models

So today I’m building out my new MVC application and get to writing this small block of code

  return View(new { Items = model });


Server Error in ‘/’ Application.

‘object’ does not contain a definition for ‘Items’

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: ‘object’ does not contain a definition for ‘Items’

Apparently what I want to do is literally impossible. Ironically I had already commented on one of these answers.

Eventually the rabbit hole leads me to dynamitey (github)   and now I can do:

  return View(Build<ExpandoObject>.NewObject(Items: model });


Recent learns for Javascript / Web Development

File this in the unusual category, XHTML which likely all of us have used, never officially supported target=_blank for hyperlinks. XHTML Strict 1.0 – target=“_blank” not valid? is a more detailed discussion of this on StackOverflow. Ultimately it was only ever incorporated into the transitional specification. I just find it really ironic how something all of us take for granted wasn’t even in the official language specification.

Douglas Crockford knows how to troll. Straight from Code Conventions for the JavaScript Programming Language

Avoid conventions that demonstrate a lack of competence

Straight up says don’t do stuff just because it’s easier. Do stuff right. Or you suck.

Well said Crockford, well said.

At the bottom of his conventions I actually found out that JavaScript has a comma operator. I did a serious WTF when I read that. Of course it says to not use it. I did a little bit of digging to find out what is a comma operator Comma operator(,) Where it can “really” be useful.

Taking the best real world example from StackOverflow:

A Fibonacci generator:

for (
    var i=2, r=[0,1];
    r.push(r[i-1] + r[i-2]), i++
// 0,1,1,2,3,5,8,13,21,34,55,89,144,233,377

That’s some crazy stuff there. It certainly looks cool at how you just 1 lined the Fibonacci sequence, but it certainly doesn’t add readability to code. I’m sure this is why Crockford advises against it.

Code that your first thought looking at it is #WTF does not belong in your codebase. The only exceptions to this are extreme performance optimized codeblocks that were deemed necessary by actual profiling. Optimizing without a profiler is the ultimate exercise in futility. You will most likely just make your application slower, harder to understand, and never touched the original problem.