Sunday, 11 December 2022

Generic Attributes in C#11

 

In C# 11 comes with .Net 7, Attribute is enhanced to use with generic type. This feature provides a convenient way for attributes to avoid System.Type constructor parameter (the old way).

Attributes are metadata extensions that give additional information to the compiler about the elements in the program code at runtime. Attributes are used to impose conditions or to increase the efficiency of a piece of code.

Being a programmer I love this. Here I will try to explain to you how to define Attributes with generic types. To understand the enhancement, let's see how we used to do the Attributes with type in C# 10 or before.

For example, we will create an Asp.Net core web API project template with the target framework net7.0 so the same project will be using the demonstration of old and new syntax.

Here I will be creating an Action Filter called LoggingFilter and will be logging some info before and after the execution of an action.

The above code is straightforward. So now we add this to the service collection.

To use this action filter with an Action method we will use Microsoft.AspNetCore.Mvc.ServiceFilter attribute which is using the old syntax which takes System.Type as a parameter for the constructor and the definition of ServiceFilterAttribute.

Next, we will use the action filter with the Get action method of the WeatherForecastController generated from the template.

Now you run the application and execute the GetWeatherForecast endpoint from the swagger app, you will see the information log in the output window as

Cool, Everything works great but How about Microsoft would have made the ServiceFilterAttribute generic and avoid the type parameter in the constructor? Well, we will do it and will write better code than Microsoft. :) Just kidding. Actually, this is the enhancement done in C#11, thanks to Microsoft for that.

To redefine the ServiceFilterAttribute using the Generic Attribute feature, let’s see the ServiceFilterAttribute code which is available under Microsoft.AspNetCore.Mvc namespace:

As per the above Microsoft code here, ServiceFilter takes Type as a parameter in the constructor which we pass as typeof(LoggingFilter) in the action method. So now we will recreate the ServiceFilterAttribute by defining a generic attribute and the syntax would be as:

public class MyServiceFilterAttribute<T> : Attribute

and the code as:

Wow, no more type parameters and a very convenient way of making the attribute class generic.

Again if you run the application, the logs will be displayed in the output window as with the earlier code.

No difference in functionality but a huge difference in terms of better code.

Here is the full code used for this example:
https://github.com/binodmahto/FunProjects/tree/main/CSharp11WebAPIDemo

To know more about C#11 new features please read through:
https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-11

Hope you enjoyed the content, follow me for more like this, and please don’t forget to LIKE it. Happy programming.

Monday, 5 December 2022

CICD best practices

 CICD is the process of automating the building, testing & deploying of your application.

  1. Plan your repo
  2. Choose your tools
  3. Plan your Tests automation
  4. Secure your pipelines and secrets
  5. Pipelines for early-stage verification and deployment
  6. Involve the Team.

CI/CD with GitHub Actions pipeline to run the .Net unit test and publish results

 Writing Tests (Unit Tests, Integration Tests) is not only the best practice but also essential to ensure quality code.

From the DevOps side, it is essential to put a gate to check for successful unit test execution with each pull request or push. So in this article, we will see how to implement a pipeline to run the unit tests and publish the results.

What do we need?

  1. We need a pipeline to be triggered with every pull request for your code repo.
  2. Jobs to run the unit tests and publish the results.

Please follow my other articles to learn more about GitHub Actions: CI/CD with GitHub ActionsCI/CD with GitHub Actions to deploy Applications to Azure App ServiceCI/CD with GitHub Actions to deploy Application to Azure Kubernetes Cluster

Let’s create our pipeline for unit test execution. To do this add a yaml/yml file as .github/workflows/buildAndRunTest.yml in the root project folder and then starts with defining the name & triggering action.

name: Build and run tests

env:
DOTNET_VERSION: '6.0' # set this to the .NET Core version to use
WORKING_DIRECTORY: './src' #define the root folder path

on:
workflow_dispatch: #for manual trigger
pull_request: #trigger action with pull request
branches:
- main #your branch name

Next step, we will define the job and mention the target machine (Linux/windows) then perform the necessary steps for code checkout and setting .net core

jobs:
build:
runs-on: ubuntu-latest #target machine is ubuntu

steps:
- uses: actions/checkout@v2

- name: Setup .NET Core
uses: actions/setup-dotnet@v1
with:
dotnet-version: ${{ env.DOTNET_VERSION }} #reading it from env variable defined above

I’m using “EnricoMi/publish-unit-test-result-action” action from the marketplace with JUnit logger hence we need to install the related package for each test project as the next step.

Xml logger for JUnit v5 compliant xml report when test is running with “dotnet test” or “dotnet vstest”.

- name: Setup test loggers
shell: pwsh
run: |
foreach ($file in Get-ChildItem -Path .src/tests/*Tests.csproj -Recurse)
{
dotnet add $file package JunitXml.TestLogger --source 'https://api.nuget.org/v3/index.json'
}

From the above code, looping through all test projects inside the src/tests folder.

Next step we will execute the tests with dotnet command.

- name: Run unit tests
shell: bash
working-directory: ./src
run: |
dotnet test myDemoApp.sln --logger 'junit;LogFileName=TestResults.xml' \
--verbosity normal --results-directory ./_test-results

The above code will run all the unit tests in the project and save the result inside the src/_test-results/TestResults.xml file.

If you have categorized tests then you can use the filter option with dotnet test as:
dotnet test — filter “TestCategory=CategoryA”

Finally will publish the results using “EnricoMi/publish-unit-test-result-action” from the marketplace.

 - name: Publish Unit Test Results
uses: EnricoMi/publish-unit-test-result-action@v2
if: always()
with:
junit_files: ./src/_test-results/*.xml

We are done so With this if you the actions pipeline you will see the results as:

Note: There are various actions available in the GitHub marketplace to publish your test results, please explore them too.

Hope you enjoyed the content, follow me for more like this, and please don’t forget to LIKE  it. Happy programming.