Using .Net Core 2.2 in Azure DevOps

I recently had to restore and build a project in AzureDevOps that turned out to be currently not supported.

Resulting in the error message below:

“The current .NET SDK does not support targeting .NET Core 2.2. Either target .NET Core 2.1 or lower, or use a version of the .NET SDK that supports .NET Core 2.2. “

image

image

How I got around it was with the help of Scott Hanselmans blog post: https://www.hanselman.com/blog/AzureDevOpsContinuousBuildDeployTestWithASPNETCore22PreviewInOneHour.aspx

What I done was effectively add the SDK installer as a task as part of my build pipeline

image

and move it to the top of my build pipleline before the restore task as below

image

in my project I am building against SDK version 2.2.101 so I chose this in the “Version” textbox as below

image

Once I run again I get a clean bill of health

image

This is simple a quick way to get around SDK support in Azure DevOps.

My Git Command Line Toolbelt

Overview

Lately I have been getting a little more familiar with the Git command line and I have to say I am liking it. The reason why I had stayed away from it until now was that I found the GUI(SourceTree in my case) to be a safe/easier interactive medium for something I was not at all that familiar with. However I realize the CLI is faster for issuing commands so I made a conscious effort to start familiarizing myself with it.

The idea of this post was to demonstrate and explain the most frequent commands I typically use and will hopefully help others interested in understanding the Git CLI basics but may be a little apprehensive.

I will demo operations from both a repository owner as well as a repository contributor perspective.

Disclaimer: I know there are many more commands that I am excluding however I just wanted to focus on what I believe are the most frequent most used day to day commands for a beginner.

I wanted to not only list the commands with their explanations but provide a real example against a sample application for better context.

To follow these examples, you will need to have some pre-requisites installed.

Pre-requisites

What I use (in case you were wondering from the images)

  • PoshGit – nice PowerShell module to allow me to see git status from the prompt(https://github.com/dahlbyk/posh-git)
  • PowerShell through command line – easier to see command colors in black background

What I will cover

I will list the commands with their explanations, then apply them on a sample application which I will build completely from scratch using .Net Core.

I will be 100% in the command line from creating the application to interacting with Git outside of using an editor to update files.

The .Net Core application that I will create will be a simple console application to keep things as light as possible and focus on Git rather the application itself.

Commands I will be using:

  • Git Config
    This command is to set your initial one-time configuration, I will use it to set my Identity (Name and Email).
    Note: You can set either global or project specific configuration, meaning the scope at which the configuration takes affect. I will apply it to the new project.

If you want to set the configuration globally you simply add the ‘—global’ switch.

  • Git Init
    This initializes our new project directory to be a git repository.
  • Git Add
    This command adds your files from your working directory to staging or to the git Index to be committed.
  • Git Status
    This allow us to view the files which have been updated, added or deleted.
  • Git Commit
    This command commits your changes ready to be pushed to your repository.

You add the -m switch to attach a message to your commit.

Tip: You can bypass the add command above and combine the add command to the commit command as one single command by adding the ‘-am’  switch –> I will demonstrate below.

  • Git Push
    Pushes committed changes to your remote repository(GitHub in our case)
  • Git Checkout
    Allows you to switch to a different branch, you can also add the ‘-b’ switch to create a new branch based off your current branch –> I will demonstrate below.
  • Git Diff
    Finds differences between of files before and after changes.
  • Git Merge
    Merges changes from one branch to another.
  • Git Stash
    This command allows you to store away changes that you may not want to apply right away.
  • Git Clone
    Clones from a remote repository to a local repository
  • Git Pull
    Pull all the latest changes that may have been applied on your remote repository and applies them to your local repository.

Okay, let’s begin

First, we need to create our .Net Core Console application to work with.

Open up PowerShell, I will open it within the command prompt – by simply typing ‘PowerShell’ within the command prompt – and you will see below that PowerShell is listed on the top bar.

image

Next just browse to a directory in which you want to create the new project, in my case I will create in ‘c:\dev\github’.

Now create the application and name it ‘GitCommandLine’ by typing  ->

‘dotnet new console -n GitCommandLine’.

You should see the below..

image

Now that we have our dotnet core console app created, now let’s start with Git.

First, Lets’ navigate in to our project directory we just created.

Git Init

Now we want to initialize our new project as a Git repository so we will want to use the ‘Git Init’ command like below.

image

Git Config

Now we want to set the config specifically the Identity (user name and email) to associate with our commits, I will use

User name: John Doe
Email address: [email protected]

Note: The configuration scope is just this project so I excluded the –global switch.

image

Git Config –l

  • Let’s view the current configuration to confirm out setting for applied correctly by issuing the ‘git config –l command’

image

and it looks like they did as you can see near the bottom.

Git Status

Let’s call a Git status to see the current changes in our repository.

image

What this is telling us is that we have not specified any files to be included in the next commit.

Git Add

As mentioned above we can either call a Git add as a separate command or within the commit command, let’s call it separately for now.

Here we specify what is to be added to staging, we are adding everything with ‘git add .’ we could have specified individual files if we wanted to.

Now let’s rerun our git status after applying the git add command.

image

You will now see the output is different – stating we have new files ready to be committed.

Git Commit

Let’s go ahead and commit them, we will add a message to our commit let’s call it ‘Initial commit’

image

Git Push

Now we will want to push our local repository changes to our remote repository (GitHub).

FYI: I have already created a new repository in my GitHub account(https://github.com/andrewcahill/GitCommandLine).

In order to push I will need to specify my remote repository details, specifically where it is located so I use the below command.

‘git remote add origin https://github.com/andrewcahill/GitCommandLine.git’.

image

Now we will issue a push command with ‘git push -u origin master’.

image

Great, now we have our repository in GitHub.

Now let’s create a new development branch, make some changes in this new branch then push them to GitHub and then finally merge these changes to master.

Git Checkout

We will use the ‘-b’ switch to specify a new branch and call the new branch “development”

image

I will make a minor change to our Program.cs file and change the “Hello world!” output to “Hello GitHub!”

Quick tip: To view content of a file there is a PowerShell command ‘Get-Content’ which will allow you to do exactly that.

We can use this to view a before and after, like below..

image

And after the change..

image

Git Diff

We can use ‘Git diff’ to view the changes that will be applied on our next commit

image

Now let’s commit them, why not this time add our ‘add’ command within our commit command and add the message “Updated output”.

image

Now let’s push our changes to a new remote ‘development’ branch. In order to do this we will want to create our new remote branch by issuing the command ‘git push –set-upstream origin development’

Note  this is only a one-time operation

Git Merge

Now let’s merge these development changes to master so both are in sync.

This is a two-step process first lets checkout or switch to our master branch then we will call merge – like below.

image

Now we can see the master branch has an update pending so let’s push this change to our remote repository.

image

That’s it, well at least from the point of view of the creator of the repository, what about the point of view of a contributor, they may want to make contributions to your repository. In this case the process is quite straight forward.

All we really need to do is clone down this repository, to a directory of our choosing, make the changes and push them back up.

Let’s do that..

I will create a new folder under my github directory called ‘GitCommandLineContributor’.

Git Clone

Now let’s navigate in to our new directory and clone using ‘git clone https://github.com/andrewcahill/GitCommandLine.git’.

image

Typically changes are done within either the development or feature branches so let’s switch to the development branch here, by issuing ‘git checkout development’.

Now as a contributor lets make another change to the Program.cs file –> we will change from “Hello GitHub” to “Hello from contributor”.

Okay, now let’s go ahead and commit and push as before.

image

Git Pull

Now go back to our owner viewpoint(c:\dev\github\gitcommandline) in my case, switch to development and pull down any changes that may have happened by contributors by issuing ‘git pull‘.

image

And we see after we perform a pull we can see new changes being applied.

Now let’s merge these contributor changes to master.

So we issue ‘git checkout master’ & ‘git merge development’ and finally ‘git push’ as before.

image

Git –Help

At any point you can run a ‘git –help’ command which lists all the available git commands available to run. As well as that you can run a ;git [command] –help; to bring up a webpage detailing further information on that specific command. For example ‘git commit –help’ –> pretty cool.

Git Stash

Finally one last command I wanted to show was the Git Stash command, as I have on more than one occasion forgotten to switch to the correct branch before making changes, for example accidentally making changes on master instead of development – this command really helps me out. As I usually try to make my commits small and often I had previously ended up simply copying my changes to the new branch –> a pain and error prone.

How I will show it is:

As an example we accidentally make a change to master that we wanted to make to development so we  stash these changes, switch to the correct branch(development) and apply the changes to the development branch.

First make sure we are in the master branch by running ‘git status’

image

Lets again make a change to our Program.cs file with “Hello owner!” in our output.

Again let’s confirm our changes..

image

Now we realize this change should have been in development, so, lets stash these changes.

image

Checkout development and run ‘git stash apply’.

image

Now perform the same steps again(git commit with add – git push – git checkout master – git merge development & finally git push) as below..

image

Conclusion

That’s it a top to bottom of all my frequent Git commands, I hope somebody may find this overview useful.

Resources:

For further information on Git commands, explanations etc. check out: https://git-scm.com/

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