Code quality: Using CodeAnalysis.FxCopAnalyzers and Stylecop in .NET Core 2 applications

 

Introduction

Why Code quality is important? Because correctness, maintainability, and even elegance are all involved in creating great code.

Code Quality is a fascinating subject, which comprises a mixture of knowledge, experience, guidelines, principles, patterns and conventions. And if that wasn’t enough, they all should be carefully adapted to each particular team and use case.

The subject gets even more confusing when you start considering tooling. However, choosing the right tools for each team and use case will make achieving quality code simpler.

This article contains an introduction to the Code Quality subject in the .Net Core ecosystem.

CodeAnalysis.FxCopAnalyzers

There are several analyzers available, the most interesting ones in my opinion are:

  • Microsoft.AnalyzerPowerPack
  • Microsoft.CodeAnalysis.FxCopAnalyzers
  • codecracker.CSharp
  • SonarAnalyzer.CSharp
  • StyleCop.Analyzers
  • Microsoft.VisualStudio.Azure.CodeAnalysis (for Azure projects)

In this article I have chosen CodeAnalysis.FxCopAnalyzers.

It can be installed via Nuget Packages, it’s easy to install and it uses a ruleset file, you can download a sample here we will see later how to configure it: myrules.ruleset

Installation

Depending the version Visual Studio you have to be careful with what package version you have to install:

If you don’t install the right package with your current version of Visual Studio you may have issues when you compile your project.

For more information you can referer to the GitHub web page: https://github.com/dotnet/roslyn-analyzers#recommended-version-of-analyzer-packages

In my case I have Visual Studio 2017 15.3 so I have to install the version 2.3.0.

StyleCop.Analyzers

StyleCop is like CodeAnalysis, it uses Roslyn Analyzers but does only care about style programming.

Code analysis searches for patterns which may indicate a bug, while StyleCop is simply enforcing style rules, a simple convention used by your team.

Installation

After installing the Nuget package add in your solution items folder the file stylecop.json (at the same place as your ruleset file), it’s mandatory to add this file to make it work

Then edit your csproj to link your stylecop.json to the project you want to analyze like this (there is no visual tool for this in Visual Studio 2017 for StyleCop):

In the mean time add the ruleset file as follow as well:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>    
     <OutputType>Exe</OutputType>    
     <TargetFramework>netcoreapp2.0</TargetFramework>  
  </PropertyGroup>
  <ItemGroup>  
     <PackageReference Include="Microsoft.CodeAnalysis.FxCopAnalyzers" Version="2.3.0-beta1" />    
     <PackageReference Include="StyleCop.Analyzers" Version="1.0.2" />  
  </ItemGroup>    

  <PropertyGroup> 
     <CodeAnalysisRuleSet>$(SolutionDir)\myrules.ruleset</CodeAnalysisRuleSet> 
     <Features>IOperation</Features> 
     <NoWarn></NoWarn>   
  </PropertyGroup>     

  <ItemGroup>    
     <AdditionalFiles Include="$(SolutionDir)\stylecop.json" Link="stylecop.json" />  
  </ItemGroup>  
</Project>

When you are done with that, you can select the rules you want to enable / disable (None, Warning, Error…):

CodeAnalysis rules:

StyleCop rules:

Then when you compile Warnings or Errors appear:

Sample of underlined code:

 

Great isn’t it? 😉

Now your turn to fix analyze your code 😮

Code reliability: Unit testing with XUnit and FluentAssertions in .NET Core 2 apps

Introduction

I decided to write this article because I’m really fan of XUnit and FluentAssertions expecially for its great syntax.

Xunit

xUnit.net is a free, open source, community-focused unit testing tool for the .NET Framework. Written by the original inventor of NUnit v2, xUnit.net is the latest technology for unit testing C#, F#, VB.NET and other .NET languages. xUnit.net works with ReSharper, CodeRush, TestDriven.NET and Xamarin. It is part of the .NET Foundation, and operates under their code of conduct. It is licensed under Apache 2 (an OSI approved license).

FluentAssertions

FluentAssertions is the best assertion framework in the .NET realm.

FluentAssertions supports the following .NET versions:

  • .NET 4.0, 4.5 and 4.6
  • CoreCLR, .NET Native, and Universal Windows Platform
  • Windows Store Apps for Windows 8.1
  • Silverlight 5
  • Windows Phone 8.1
  • Windows Phone Silverlight 8.0 and 8.1
  • Portable Class Libraries

Fluent Assertions supports the following unit test frameworks:

 

Setup your .NET Core 2 project

Install XUnit

Download it via Nuget package manager:

Or type this command in Nuget package manager console:

PM> Install-Package xunit -Version 2.3.1

Install XUnit Visual Studio runner

This package allow to Visual Studio to discover XUnit unit tests, if you don’t install it, Visual Studio won’t detect them.

Download it via Nuget package manager:

Or type this command in Nuget package manager console:

PM> Install-Package xunit.runner.console -Version 2.3.1

Install FluentAssertions

Download it via Nuget package manager:

Or type this command in Nuget package manager console:

PM> Install-Package FluentAssertions -Version 5.0.0-rc0002

 

Write your unit tests

Example of a class to unit test:

public class Hello
{
   private string _firstName { get; set; }
   private string _lastName { get; set; }

   public Hello(string firstName, string lastName)
   {
      _firstName = firstName;
      _lastName = lastName;
   }

   public string HelloMan()
   {
      if (string.IsNullOrEmpty(_firstName))
         throw new MissingFirstNameException();

       return $"Hello {_firstName} {_lastName} !";
   }

   public string Your()
   {
      return $"Hello {_firstName} {_lastName} !";
   }
}

public class MissingFirstNameException: Exception
{
   public MissingFirstNameException(): base("FirstName is missing")
   {
   }
}

Example of a related Unit tests class:

public class HelloTests
{
   [Fact]
   public void HelloManShouldBeWellFormated()
   {
      // Arrange
      var hello = new Hello("John", "Doe");

     //Act
     var helloMan = hello.HelloMan();

     //Assert
     helloMan
     .Should()
     .StartWith("Hello")
     .And
     .EndWith("!")
     .And
     .Contain("John")
     .And
     .Contain("Doe");
   }

   [Fact]
   public void HelloManShouldBeRaiseExceptionWhenFirstNameIsNotSet()
   {
      // Arrange
      var hello = new Hello("", "Doe");

      //Act
      Action actionHelloMan = () => hello.HelloMan();

      //Assert
      actionHelloMan
      .Should()
      .Throw<MissingFirstNameException>()
      .WithMessage("FirstName is missing");
   }
}

 

Now just run your test with “Test” menu in Visual Studio:

 

That’s it!

Cute unit testing isn’t it? 😉

 

 

Streaming video asynchronously in ASP.NET Core 2 with Web API

 

Introduction

No matter what kind of project you are working on, at some point you will find the need to stream videos in your website or mobile apps for many purposes. So, we will learn how we can live stream our video content over HTTP, using ASP.NET Core 2 Web APIs.

Set up a service that get a Stream from a video hosted in the web using HttpClient

Example with videos hosted in Azure:

public class AzureVideoStreamService : IAzureVideoStreamService
{
   private HttpClient _client;

   public AzureVideoStreamService()
   {
      _client = new HttpClient();
   }

   public async Task<Stream> GetVideoByName(string name)
   {
      var urlBlob = string.Empty;
      switch (name)
      {
         case "earth":
         urlBlob = "https://anthonygiretti.blob.core.windows.net/videos/earth.mp4";
         break;
         case "nature1":
         urlBlob = "https://anthonygiretti.blob.core.windows.net/videos/nature1.mp4";
         break;
         case "nature2":
         default:
         urlBlob = "https://anthonygiretti.blob.core.windows.net/videos/nature2.mp4";
         break;
      }
      return await _client.GetStreamAsync(urlBlob);
   }

   ~AzureVideoStreamService()
   {
      if (_client != null)
      _client.Dispose();
   }
}
public interface IAzureVideoStreamService
{
   Task<Stream> GetVideoByName(string name);
}

Then don’t forget to register the service and it’s interface in Injection Dependency system

public void ConfigureServices(IServiceCollection services)
{
   services.AddMvc();
   services.AddScoped<IAzureVideoStreamService, AzureVideoStreamService>();
}

Set up a Streaming controller that stream videos using FileStreamResult object

FileStreamResult sends binary content to the response using a Stream instance

Example of an API that return a video by its name:

[Route("api/[controller]")]
public class StreamingController : Controller
{
   private IAzureVideoStreamService _streamingService;

   public StreamingController(IAzureVideoStreamService streamingService)
   {
      _streamingService = streamingService;
   }

   [HttpGet("{name}")]
   public async Task<FileStreamResult> Get(string name)
   {
      var stream = await _streamingService.GetVideoByName(name);
      return new FileStreamResult(stream, "video/mp4");
   }
}

Run the Web API to test….

 

 

Easy isn’t it ? 😉