.NET HttpClient should be shared

While toying around with Azure Functions for some app idea, I came across some documentation on best practices for using it.

The article continues further into detail on Patterns and Practices HTTP Performance Optimizations where I discovered something about HttpClient I would have never guessed:

[HttpClient is] intended to be instantiated once and reused throughout the lifetime of an application. However, it’s a common misunderstanding that these classes should be acquired only as necessary and released quickly

new HttpClient object is created for each user request. Under heavy load, the web server may exhaust the number of available sockets, resulting in SocketException errors.

The HttpClient class is designed to be shared rather than pooled

Well whaddayaknow, until know I have always designed my applications to keep the HttpClient as short-lived as possible, always wrapping it in a using block to ensure proper disposal.

Turns out this is an anti-pattern, they actually advice you to create a static readonly HttpClient, which you reuse in your app.

Going to apply some improvements right now!

Theme music for this blog post

.NET HttpClient should be shared

GraphQL as a silver bullet

I learned about GraphQL somewhere this year and thought it was genius.

Check out the official site to see what it is, but in short, you call an API and specify in your request the response contract you expect. This sounds lovely for supporting a wide range of use cases with a single API. No upfront rigid API contract, let the clients decide how they want the data.

So in my mind this sounded like the future for providing flexible API’s.

Thankfully the Internet provided some critical thinking, check out this presentation for a guide on when REST still trumps GraphQL:

https://www.infoq.com/presentations/api-rest-graphql

Highlights are your ability to rely on HTTP caching with REST and the self describing nature of HTTP verbs, things you lose with GraphQL.

And so the universally correct answer continues to be “its depends”.

Theme music for this blog post

GraphQL as a silver bullet

Fix unable to access /.config/git/config in VS2017 as administrator

The GIT integration in Visual Studio 2017 seems to have regressed back to the initial buggy state in Visual Studio 2015.

A new issue I had when starting VS2017 as an administrator was:

Git failed with a fatal error
fatal: unable to access '\/.config/git/config': Invalid argument

This was visible in the output window, if you miss it you’re clueless.

The result is the GIT integration did not work at all and I had to fall back to VS2015 when I needed a UI to to GIT operations (e.g. merging)

You can fix this by setting an environment variable HOME that points to your folder with git repositories.

Theme music for this blog post

Fix unable to access /.config/git/config in VS2017 as administrator

ASP.NET Core does not start up when static file path does not exist

So by default ASP.NET Core only serves static files from wwwroot. Since I’m sold by architecture in vertical slices, I like to have feature folders.

This means I will put the controller, model, view and any static files in a single feature folder. To expose these static files, I just configure:

public void Configure(...)
{
...
  app.UseStaticFiles(new StaticFileOptions
  {
    FileProvider = new PhyiscalPhileProvider(
      Path.Combine(Directory.GetCurrentDirectory(), 
        @"Features\MyFeature\www)),
      Request.Path = new PathString("/MyFeature")
  });
...
}

Now, if the “Features\MyFeature\www” part is an invalid path, you will get a clear exception when you are debugging. Typically however, the static files will be file types that are not included in the build output by default (e.g. js)

So on your machine while you are developing everything is fine. But when you publish, the static files are not included, which results in an empty directory which is then not  included, which ends with the web application not starting up!

In my case, this was on an Azure App Service, which showed a nice custom error page without any clue. Took me some troubleshooting to get the logs that pointed me to the root cause.

Ah well, TheMoreYouKnow.

Theme music for this blog post

ASP.NET Core does not start up when static file path does not exist

VSTS build agent without Visual Studio

Visual Studio Team Services (VSTS) come with hosted agents that allow you to build .NET applications out of the box.

If you want to run an on-premise agent however, and prefer not to install Visual Studio on it, the setup might not be so straightforward. Maarten Balliauw covered this topic perfectly.

This is what got me up and running, after the default on-premise agent installation:

  1. Install the correct .NET SDK
    1. For example a 4.6.2 app would require the .NET Framework 4.6.2 Developer Pack
    2. This installs the required reference assemblies under Program Files, which are used by the build to compile your application
    3. Don’t confuse this with the .NET framework, which is just the runtime to execute a compiled .NET app
  2. MSBuild tools to use msbuild
    1. For Visual Studio 2015 and previous versions, get the Microsoft Build Tools, so for VS2015 install Microsoft Build Tools 2015
    2. For 2017 they changed up the name to Build Tools for Visual Studio 2017 (scroll down and look under Other Tools and Frameworks)
      1. In response to Maarten’s post, Phil Haacked opened a uservoice which resulted in this which attempts to improve things, nice!
  3. MSTest if you use it
    1. The Agents for Microsoft Visual Studio 2015 installs mstest.exe, the description focuses on distributing automated tests to remote machines, don’t worry, it is what you need

So MSBuild uses targets to do its job, which usually come with installations of other software. I got away without installing extra tools, by using these nugets in my project instead:

  1. MSBuild targets for WebApplications
  2. TypeScript MSBuild nuget
    1. Instead of installing the TypeScript tools on the server, this nuget provides everything you need

Then after installing node, I run Grunt from the local node_modules directory of my application, instead of depending on grunt-cli to be installed globally.

Good luck!

Theme music for this blog post

VSTS build agent without Visual Studio

Books part two

I didn’t slow down the pace after the last books post, but I did change the category. Last year was more focused on technical books, mostly catching up with classics. The first couple of months of this year, have all had a startup business theme by chance (at first, and then because I wanted to soak up more on the topic).

I wouldn’t endorse them as must-reads, but they are motivating, inspiring or relevant if you are pondering your next 5 year plan (which I finally understood you should have, because nothing happens without a plan and life just continues). So if you are looking for any of those things, consider:

Rework

Rework reminded me of the author’s company style, 37 signals. It takes common sense and truths about businesses, but presents them very clear without clutter or noise, allowing you to really take in the message.

Read this to get motivated about getting things done, does not contain very deep things to learn.

The 100$ Startup

The $100 Startup: Reinvent the Way You Make a Living, Do What You Love, and Create a New Future is chuck full of experiences of other people to learn from. Despite the almost cheap sounding title, the book is really not a completely empty promise.

Read this to learn about tons of experiences of entrepreneurs bootstrapping a small time business.

Traction

Traction: A Startup Guide to Getting Customers is an exhaustive list of all the ways to get customers.

Although they make a good point that you should start working on traction right from the beginning together with the product, I felt so overwhelmed with all the information, I would recommend reading it when you are ready to actually start going out to look for customers.

The 4-Hour Workweek

The 4-Hour Workweek: Escape 9-5, Live Anywhere, and Join the New Rich sounds douchy, and it is at times. It focuses a lot on outsourcing and exploiting lower living standards around the world, to increase your productivity and free up time. After checking out a couple of the author’s podcasts, you understand he’s not a bad guy, globalization is just a thing and he explains how to work it.

Fun things happen when you earn dollars, live on pesos, and compensate in rupees.

Tim Ferris

Read this when you have a business and are overwhelmed with work, it has some useful approaches around automating processes at least, even if you don’t want to go the virtual assistants route.

Escape from Cubicle Nation

Escape from Cubicle Nation: From Corporate Prisoner to Thriving Entrepreneur, I think I enjoyed the title more than the content of the book, it is catchy isn’t it. I didn’t hate it though and did learn things, but a lot of parts felt long-winded and seemed to be overly referencing other books just to pad the contents.

Read this to straighten your thoughts about whether being self employed is something for you.

Theme music for this blog post

Books part two

Other types of testing

Some interesting other types of testing paradigms and approaches I came across, since the last year or so up to recently.

Mutation testing

Mutation testing helps you in guarding your code coverage. The goal here is for your tests to kill all mutants. A mutant, is a mutation to your code. If you have strictly specified the behavior of your code, any significant change should trigger a failing test. A failing test, kills a mutant.

This is a bit abstract, so here’s a pseudo code example:

// Some business logic
public bool Foo(string input)
{
  if(input == "some-condition")
    return true;

  return false;
}

// Test that specifies expected behavior of business logic
[TestMethod]
public void WhenFooGivenInputIsSomeConditionThenResultShouldBeTrue()
{
  var input = "some-condition";
  var result = Foo(input);
  Assert.IsTrue(result);
}
// Mutant in action
public bool Foo(string input)
{
  if(input == "some-condition")
    return false; // If statement inverted by mutant

  return true; // If statement inverted by mutant
}

// The test method above now fails, mutant succesfully killed

The changing of your code and checking that a test fails, is something that is gets handled by a framework. Unfortunately, I’m only aware of 1 active mutation testing framework for .NET, I admit this particular framework doesn’t convince me to start using it.

A user friendly mutation testing framework for .NET, would convince me to integrate it into a CI pipeline. Maybe only execute it in a nightly build, for critical components.

Scientist.NET

I first heard about Scientist.NET on Pluralsight, then later learned on .NET Rocks that Phil Haacked is the author that ported it to .NET.

The idea here is to test code refactorings in a live system with real data. So you would make a change, but still keep the original code in place. Then you call both the original and the new piece of code via Scientist (result of original is used, result of new is recorded for comparison and discarded). This goes into production.

Now Scientist collects the results of both pieces of code and after a period of time, you can validate that the refactored code returned the same results under real use and did not introduce any unexpected behavioral changes.

I was almost completely sold, until I understood that of course, you have to ensure there are no unwanted side effects. Since you executing the same action twice, albeit with different versions, it’s up to you not to duplicate the impact.

So this would work great for purely CPU bound calculations, but other than that you need to pay attention. Thing is, this is typically an approach I would want to use in legacy code, which are traditionally an entangled mess where database access is spread over long methods.

Property based testing

I heard this before but it didn’t stick. After a presentation on the subject it did. Here the approach is to describe the expected behavior as properties, instead of writing them out in tests.

The advantage is, this allows the computer to write the tests. The computer can then generate hundreds or thousands of test cases, that all validate that your business logic acts as you specified in the properties. Kind of reminds me of Pex, which became IntelliTest I guess.

But this post is getting way longer than I intended, so I suggest to check out the presentation for a proper introduction. From the three different approaches to testing here, this is the one I’m most interesting in pursuing. FsCheck seems like the framework to get started with in .NET, so gonna give that a try soon!

Theme music for this blog post

House Shoes w/guest mix by Kutmah – Magic
(scroll down on the page for the player or download if you prefer, no embed available this time)

Other types of testing