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
.Handle<SqlException>()
.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();
cts.CancelAfter(timeout);

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

[ServiceContract]
public interface ICalculatorActor {

[OperationContract]
double Add(double x, double y);
[OperationContract]
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()) {

fabric.RegisterActor(typeof(CalculatorActor));
Thread.Sleep(Timeout.Infinite);

And WCF

ServiceHost fabric
 = new ServiceHost(typeof(CalculatorActor)); 
      
host.AddServiceEndpoint(typeof(ICalculatorActor),
     actorId, applicationName);
host.Open();
Thread.Sleep(Timeout.Infinite);

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.

http://techcrunch.com/2015/04/20/microsoft-announces-azure-service-fabric-a-new-framework-for-building-scalable-cloud-services/

azure-service-fabric

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 () {
    $.scrollUp();
});

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.

MOAR BLOGZ

So it’s been a somewhat rather long time since I’ve posted. Numerous times I’ve said to myself I need to dedicate time and post some real blogs. Clearly that didn’t work out. Since that hasn’t absolutely occurred. I’m going to do some pseudo-micro-blogging and talk about some stuff I’ve learned recently. Each post will likely be short, but I’ll have new stuff! Finally!

Also I’ll have an elaborate bookmark for myself. I’m self serving, what can I say.

MySpace releases a new version, and a lesson in the worst things you can do to your users

Below is a screen shot of the new myspace:


what myspace does wrong in their new release

First the most blatant and unacceptable thing to do to your users is throw out all of their existing content. Not only did it seem to not carry over one single shred of my profile other than name and location, it does not even seem to have carried over my friends list. That is just unbelievably silly.

Next up is the primary input box is nearly entirely off the page. I run 1920×1200 resolution and do not browse with my window full screen. It seems that they just assume you have your viewport to be the same size as your resolution.

For some reason this layout uses horizontal scrolling, i think this is more related to buggy design than actual intent. Next to the text input and where it says my “stream is empty” is a gigantic void that goes over some 1000+ pixels off screen. (Did it erroneously calculate resolution based on the fact I’m using dual monitors?)

When you get the mouse anywhere near the bottom of the page, that hideous gigantic thing pops up, I don’t even know what it is. I assume it’s a track list for listening to music on myspace. This thing pops up incredibly easily and then stays there. When it’s there you can no longer across the horizontal scroll bar so depending where you are you might actually be blocked from interacting with the site altogether until you trigger a hover out to make it go away. (I really hope it doesn’t function like this on a tablet/phone)

I could point out alot of things they got right with the new myspace, but these flaws are just so gigantic and so gaping there is no room for discussion of improvement when you drop a nuclear bomb on your users and delete all of their created content. [Naysayers hush, yes I know the content likely exists still on old myspace somewhere, somehow, but i’m speaking in terms of how a user would feel about their usage and their experience].

Comcast Metro Ethernet and How much does it cost?

Comcast has been advertising a new line of service for business users called Comcast Metro Ethernet. This is really just standard fiber to the premises. They do a good job of not making any information available online to figure out pricing.

Recently I was involved with discussions about this service. These figures are loose numbers for the Central PA region. I cannot be certain whether the prices are wildly different across the country. These prices also assume Comcast does not need to incur very significant costs for running fiber to your premises. These costs also expect a multiple year commitment.

Comcast Metro Ethernet is unmetered fiber to the building. You purchase it per megabit and as a symmetric connection. There is no option for asymmetric speed, and there is no option for metered traffic. Basically they expect you to purchase a line that sits idle for a significant portion the month as opposed to selling you service based on actual usage. This is very disappointing.

On to the numbers!

10 mbps – $800/month

20mbps – $1100/month

50mbps – $1500/month

70mbps – $1800/month

100mbps – $2300/month

Not very impressive.

Edit: Apparently my not very impressive remarks are for US high speed internet industry as a whole. Comcast’s pricing was competitive compared against Level 3 and lower cost than most other providers in our region. It’s still disappointing to see that apparently no provider offers a plan along the lines of 500mbps or 1000mbps metered pay as you go. Or even sold with XXXX GB allocated upfront and then per use fees afterwards.