Adding Tiered Compilation in .Net Core 2.1

One of the many great features of .Net Core is its performance, which it certainly excels at.

A few weeks back I seen a new performance feature, well preview feature in .Net Core 2.1 – called “Tiered compilation”.

What is it

Well you could say at its core in enables applications to not only start faster but also run faster. It has a lot to do with the JIT(Just In Time) compilation process – first let me explain a little about JIT.

JIT

Leaving aside AOT compilation for now, The .Net CLR typically uses the JIT compiler to compile the MSIL against the CLR using CIL metadata to machine native code for the target machines architecture.

It performs this process either on startup with full assembly compilation when its loaded or on demand at runtime when a particular method is called – what happens here is basically that when a method is called first time it gets JIT compiled then on subsequent calls the calling code effectively just references the native/Jitted version of the method in memory.

Typically in JIT each method would be JIT compiled once either using aggressive optimization on startup sacrificing startup time but benefitting from steady state runtime performance, or simple optimization at the start sacrificing steady state performance throughout runtime.  There was typically only a single choice.

Back to tiered compilation

With tiered compilation you can JIT compile the same method more than once to  produce a more optimized version depending on its usage, it is hot swapped at runtime automatically for you making the decision for you.

On startup it performs a basic compilation(tier 0) but if the method gets used frequently the method is recompiled on  the background thread to produce a more optimized version(tier 1) for you to improve the runtime performance. This is sometime termed called adaptive optimization.

This in effect produces both fast startup and fast steady state performance.

Another benefit of tiered compilations is faster steady state with applications that use precompiled images shipped with the framework code of .net core, with tiered compilation it can produce more  optimized versions of the code at runtime.

How

In order to try it out for yourself, there are a few options

1. Assumes you have access to or are building the source code, then it is a trivial change to your csproj file by simply adding the MSBuild property :

like below

2. If the app was previously built and you have no access to the source code but you have access to the appsettings file simply add

to the configProperties.

For example:

Resources:

  • You can check out official Microsoft article here: Tiered Compilation
  • Check out the GitHub thread indicating performance comparisons of Tiered vs non-tiered apps : GitHub

Happy coding!

Versioning to an Asp.Net Core Web API

There are occasions you would like or need to add versioning to your API in order to specify availability or non-availability of functionality.

There are a few options available to such as Query String, Url based as well as Http header.

For my purposes I am going to talk about the Url based approach, as I have implemented this option in my MyReverie repo due to a matter of preference of being cleaner and more explicit.

First things first we will need to go ahead and install the Nuget package:

  • Microsoft.AspNetCore.Mvc.Versioning

Within the Startup class ConfigureServices method add the below:

services.AddApiVersioning(v =>
{
    v.ReportApiVersions = true;
    v.AssumeDefaultVersionWhenUnspecified = true;
    v.DefaultApiVersion = new ApiVersion(1, 0);
});

 

The above three properties are particularly useful in that they allow default versions to be set if none are explicitly set as well as providing header information on versioning that are supported.

ReportApiVersions: we are requesting the header to respond with supported API versions

AssumeDefaultVersionWhenUnspecified: set the default version if none are explicitly requested

DefaultApiVersion: Set the default version to 1.0 if default is used

To better illustrate the first property above see below. I used Postman to see the response header with supported versions listed, which I highlighted

Versioning_thumb7

Now all I have to do is simply add and update the controller attribute in my case

At the moment as I am still on version 1, I will add the attribute

 [ApiVersion("1.0")] 

and update the route attribute like so:

 [Route("api/{v:apiVersion}/[controller]")] 

So the result of the Controller class(GoalsController in my case) attributes should look like the below

Versioning_thumb1

Now let’s test our F5 and browse to our API endpoint with suffix : /api/1.0/goals, in my case below.

Versioning_thumb3

That’s it my API is now versioned v1.0

Integration Testing an Asp.Net Core Web API with xUnit.net

Summary

In this post I would like to show you how to go about adding Integration tests to your Asp.Net Core Web API project using Xunit.net.

Pre-requisites

Why I would want to add Integration testing to my Web API

Integration tests are a great way to test infrastructure connectivity of various components of a solution such as testing request/response to your Web API, against external systems such as databases file systems etc..

Why am I choosing to use xUnit.net as my test framework

ASP.NET Core uses it internally to test the product. So it will be well supported and improved throughout Asp.Net Core’s evolution.

Asp.Net Core makes it easy and efficient to perform integration testing due to its support of a test web host and and in-memory test server allowing us to make actual HttpClient requests without going over the wire so no firewall or network config issues to deal with as well as this these calls are fast whilst still working with routing, model binding & validation etc.

I will use an already created out of the box Asp.Net Core Web API which will be our ‘SUT’ or System Under Test and create our Test(xUnit.net) project which will be the project containing and executing our tests against our SUT using the test runner.

Lets’ go….

I am purposely neglecting clean typical solution folder structure, exception handling etc. in order to keep the post focused on the objective.

This is how the Solution currently stands

image

It just has an out of the box Web API project I called Test.API

Create the Test project

Right click the solution and select Add then New project

type xunit in the search field on the top right of the window, the results should be filtered and you should see  ‘xUnit Test Project(.Net Core)’

image

select it and name the project ‘IntegrationTests’

Lets go ahead and delete the class UnitTest1.cs file that gets created by default and create two new classes called:

‘TestScenarios’ and ‘TestScenarioBase’

TestScenarios is our class containing our tests and TestScenarioBase is our base class containing the code to create a server to fire up our API in order to call that we will leverage in our out TestScenarios class.

Within the base class make the class public and paste the below method in to the class

We will want to add the following Nuget packages :

  • Microsoft.AspNetCore
  • Microsoft.AspNetCore.TestHost
  • Microsft.AspNetCore.MVC

And we will need to add the folowing namespaces to the top of our class

  • using Microsoft.AspNetCore;
  • using Microsoft.AspNetCore.Hosting;
  • using Microsoft.AspNetCore.TestHost;
  • using Test.API;

The class should finally look like the below

image

In our TestScenarios class lets add the following code

Inherit from TestScenarioBase

Reference the namespaces:

  • using System.Threading.Tasks;
  • using Xunit;

Make the class public

The class should finally look like the below

image

In the code above we are calling our Get method in our Values Controller passing in an arbitrary value(5) to receive a response back to compare – by default our method simply returns “value”

Run the test using the test runner and we should receive a Successful test run.

That’s it!

In my MyReverie repository in GitHub I have implemented Integration Testing in to my Solution if you would like to see the code I referenced.

Adding Swagger to my ASP.Net Core API

I would like to show just how easy it is to add testing and documentation to your Asp.Net Core API using Swagger.

The reason I chose Swagger is simply that it is the largest framework of API developer tools for the OpenAPI specific which allows rapid documentation and testing of APIs with great ease.

For reference check out their website @ https://swagger.io/

First we want to add the Swashbuckle package from Nuget.

Right click your API project and click Manage Nuget Packages

Under the Browse tab search for Swashbuckle.AspNetCore

Package

Once found click install

Once installed we want to add the Swashbuckle namespace ‘Swashbuckle.AspNetCore.Swagger’ to our Startup class and in the ConfigureServices method the following:

services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new Info { Title = "[Title]", Version = "v1" });
});

Replacing [Title] with the Title you would like to set

Next, In the Configure method within the scope of the env.IsDevelopment() check add

app.UseSwagger();

app.UseSwaggerUI(options =>
{
    options.SwaggerEndpoint("/swagger/v1/swagger.json", "[Name]");
});

Replacing [Name] with the API spec you would like to set

To try it out simply select one of the buttons corresponding to one of your API methods

Click the ‘Try it out’ button on top right

Then hit the Execute button

image

That’s it!

We’ve just added swagger, which will dynamically update as you add, remove or update your API removing the maintenance of separate documentation processes – fantastic.

My Reverie

MyReverie is a new simple side project I am working on. The idea is to build a goal tracking solution and be able to set target dates and milestone markers against those goals to track progress.

I will routinely push new updates to the GitHub repo : MyReverie

I have a rough idea of some of the features to add which I will list under the Projects Tab.

This is also a way to experiment and learn new technologies as I go, some technologies I will be looking to incorporate are Asp.Net Core, Swagger, Docker,  xUnit.Net and EF Core as well as patterns and approaches such as Microservices and DDD among others.

Let’s see how it goes!

Getting Started with Azure Service Fabric

I wanted to show a simple example of using Azure Service Fabric to create a reliable & scalable micro service that would perform addition functionality on an input string for example “1+1” using a console application as the client.

The string is parsed out to two integers and calculates the result. Obviously this is extremely simplistic type of example. I wanted to really just do a quick test on passing input and expecting output.

The code is listed up on my GitHub account under the ServiceFabric Repo.

ASP.NET Core Web API with Docker

This post simply demonstrates creating a simple service called ‘AdditionMicroservice’ that adds two numbers provided as query string parameters.

I will add this code to my GitHub account under Getting started with Microservices repo

Pre-requisites:

Docker for Windows

1) Create a new ASP.NET Core Web Application project

image

Select the Web API Template

image

Check the Enable Docker Support checkbox

Select Windows as the OS

Click

Open Values Controller file under Controllers

image 

Remove all other methods except first Get method and change to below as below

image

The change  launchUrl’s from api/value to api/addition in launchsettngs.json file:

image

Run the app and append to the URL both the x and y parameters along with their set values to view the result:

image

Visual Studio 2015 debugging lambda expressions

Debugging Lambda expressions is certainly a very welcome feature of Visual Studio 2015. Before when trying to evaluate lambda expressions within either the watch or immediate windows we would see the message “Expression cannot contain lambda expressions”.

The great thing about this feature is that it really speeds up the diagnoses of possible bugs being faced within your application and being able to really dig in to your collections and query the data right there and then on the fly.

For instance if you are retrieving a result set from a collection but not getting the results you are expecting, you can now query the collection using lambda expressions within either the immediate or watch window during debug to give you a direct view of what data is resident within your collection that particular point in time, from there you can then dynamically make changes to your query within the immediate or watch windows necessary to confirm your hypothesis of why you are not seeing the results you were expecting – all while in debug mode without having to perform that oh so fun process of stop debugging –> make a change –> re-run –> confirm results if yes stop else go again.

Once you confirm that you are now getting the results expected from your changes you can then go ahead an make the necessary adjustments to your source code.

This is really well demonstrated by Andrew Hall in the below video.

 

Resources that helped me pass the 70-483 exam

Well a few weeks back I passed the 70-483 Programming in C# exam, it had been several years since I took an exam so I did not know how I would do.

I had worked in c# for quite some time now but all of my knowledge was pretty much self taught on the job so I knew there were some gaps in my knowledge so I thought going for the exam would at least highlight the areas in which I need to focus on. Indeed there were some areas I had touched on very little throughout my career so it was definitely a worthwhile cause from that perspective alone.

In my previous employment I had the opportunity to attend the Microsoft official course for this exam which lasted a week which was really beneficial and was a great resource, however it was expensive and not sure I personally would have attended I have had to foot the bill. Other resources that I took advantage of where pluralsight courses, virtual academy jumpstart videos as well as the MCSD Certification Toolkit.

To mention the pluralsight course there is blog post covering this exam course : http://blog.pluralsight.com/learning-path-c-microsoft-exam-70-483 which indicates the videos to check out that would be specific to the exam areas, I cannot rate pluralsight enough to be honest I truly believe it to be one of my best subscriptions I cannot tell you the amount of information I have learnt over the years using this resource as well as solving many technical issues that I had faced – if you do not have a subscription I would encourage you to take advantage of their free trial.

The virtual academy jump start videos were awesome too : http://www.microsoftvirtualacademy.com/training-courses/developer-training-with-programming-in-c, the videos were very entertaining and the presenters knew their stuff best of all it is free so definitely check them out. It is a great resource for some free training.

Other than this plenty of hands on coding there is really no substitute for actual coding I believe it is not only the best way to learn as it will quickly let you know when you hit an area you do not truly fully grasp but also the best way to retain what you learn for longer.