Wednesday, 12 August 2020

Setup C# Rest api with Unit testing

Lets start building a REST api; we are going to make a tic-tac-toe api with unit testing. To get started lets create a main folder were we will hold two projects, our source code and our unit testing project.

 

what we did above is create a main directory "tictactoe" then we added a webapi project as well as a testing project for our unit tests.

mkdir tictactoe creates our root folder 

donet new webapi -n tictactoe.game -o source creates a webapi project named "tictactoe.game" in a source folder

dotnet new xunit -n tictactoe.unitTests -o tests creates a xunit project named tictactoe.unitests in a tests folder.

we end up with something like the following

which is nice, but we still have a ways to go

next we are going to have to reference our game project in our unit tests project, since the unit test project will be testing all of our game artifacts.

dotnet add tests/tictactoe.unitTests.csproj reference source/tictactoe.game.csproj

to ensure that we didn't mix up our references open up the tictactoe.unitTests.csproj and check that there is in fact a reference to the tictactoe.game.csproj

<!-- tictactoe.unitTests.csproj file -->
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>

    <IsPackable>false</IsPackable>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.5.0" />
    <PackageReference Include="xunit" Version="2.4.0" />
    <PackageReference Include="xunit.runner.visualstudio" Version="2.4.0" />
    <PackageReference Include="coverlet.collector" Version="1.2.0" />
  </ItemGroup>

  <ItemGroup>
    <ProjectReference Include="..\source\tictactoe.game.csproj" />
  </ItemGroup>

</Project>

and sure enough there it is.

now we have one last optional thing that we can do, and in this case will do and that is add a solution file to our project, so that we can open our project in visual studio senior as well as just have a reference point that describes our project

dotnet new sln creates a solution file in our project root folder, now it defaults to the folder name if a -n parameter is not passed, in this case it's exactly what i wanted.

next we executed 

dotnet sln tictactoe.sln add source/tictactoe.game.csproj tests/tictactoe.unitTests.csproj

this references our two projects in our newly created solution file

then finally we ran 

dotnet sln list

just to confirm that we successfully referenced our two project in our solution file.

now of course if we would like we can now use the solution file to open our project in visual studio senior

however I am going to focus on visual studio code so lets open our project there instead, 

back in our terminal window in our root folder, that's where we configured our solution file type in 

code .

this will open the current directory in visual studio code

notice the .vs folder, this is a visual studio senior specific folder that was created automatically when we opened our solution file, we can just ignore it.

however now visual studio code is asking to create its own folder, just click yes on the bottom right modal, it will ask you which project to configure for launch choose the web api one. This will add a .vscode folder which holds visual studio code specific configurations for our project.

now that our project is configured lets delete the out of the box controller the WeatherForecastController.

now we are almost ready to get started building our api with unit tests, but lets set up a git repo for it, but lets do that in the next post. 


Monday, 10 August 2020

Anatomy of C# Core Rest API

Lets talk about dot net core for a quick second, the short of it is it's awesome and you should switch from dotnet sooner than later. With that out of the way lets take a look at the autonomy of the web api project. 

The dotnet core web api project starts in the main method of the program class.

using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;

namespace pav {
  public class Program {
    public static void Main(string[] args) =>
      CreateHostBuilder(args).Build().Run();

    public static IHostBuilder CreateHostBuilder(string[] args) =>
      Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder => webBuilder.UseStartup<Startup>());
  }
}

Here the main method calls the Create host builder function which uses the Startup class to instantiate the web service. 

the Startup.cs file is really where all the interesting stuff happens out of the box, later you can do some cool integration with azure key vault in the main.cs class but for now lets take a look at startup.cs since otb (out of the box) it's far more interesting.

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace pav {
  public class Startup {
    public IConfiguration Configuration { get; }
    public Startup(IConfiguration configuration) => Configuration = configuration;
    
    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services) => services.AddControllers();
    
    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
      if (env.IsDevelopment())
        app.UseDeveloperExceptionPage();
      app.UseHttpsRedirection();
      app.UseRouting();
      app.UseAuthorization();
      app.UseEndpoints(endpoints => endpoints.MapControllers());
    }
  }
}


our main.cs class first calls the constructor of the startup class which instantiates an instance of the IConfiguration interface using dependency injection, basically this is just a dictionary which is defined in our appsettings.json file allowing us to have a place to store things like connection strings or tenant ids or even passwords.... though you should never store a production password in your appsettings.json file, but that's another story for a different blog post.

Next the ConfigureServices method executes which registers all of our services as well as any dependencies to be used by the default IOC container within dotnet core.

then finally the configure method is executed where the request pipeline is configured, basically an http request comes in and all of the registered middle-ware components act on the request. 

In short the program.cs class is the entry point and it uses the startup.cs were all of our app services and dependencies are registered as well as our request pipeline is configured.

next lets take a look at the controller

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace pav.Controllers.V1 {

  [ApiController]
  [Route("api/v1/[controller]")]
  public class WeatherForecastController : ControllerBase {
    private static readonly string[] Summaries = new[] {
      "Freezing", "Bracing", "Chilly", "Cool", "Mild", 
      "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

    private readonly ILogger<WeatherForecastController> _logger;

    public WeatherForecastController(ILogger<WeatherForecastController> logger) {
      _logger = logger;
    }

    [HttpGet]
    public IEnumerable<WeatherForecast> Get() {
      var rng = new Random();

      return Enumerable.Range(1, 5).Select(index => new WeatherForecast {
        Date = DateTime.Now.AddDays(index),
        TemperatureC = rng.Next(-20, 55),
        Summary = Summaries[rng.Next(Summaries.Length)]
      }).ToArray();
    }
  }
}

This is where the magic happens this is our entry point when a user hits an endpoint, each endpoint is contained within a controller, these controllers can have multiple functions that take in request and provide responses. 

the most common requests are:
  • Get: should not have a body makes a request for date
  • Post: sends data usually for creating something
  • Delete: sends a command to delete something
  • Put: sends an update to overwrite an existing something
  • Patch: sends an update to modify and existing something
that's pretty much it for the basics