AutoMapper in .NET 6

Adding AutoMapper to ASP.NET 6 application;

dotnet add package AutoMapper --version 10.1.1
dotnet add package AutoMapper.Extensions.Microsoft.DependencyInjection --version 8.1.1

The next step is adding the AutoMapper to our DI container, inside the program.cs we need to add the following;

builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

Now its time to create our AutoMapper profiles, so on the root directory of our application we need to create AutoMapperProfile.cs

We are going to map the below entity (“User”) to the a Dto (“UserDto”)

public class User
    {
        public Guid Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        public string Phone { get; set; }
        public DateTime DateOfBirth { get; set; }
        public string Country { get; set; }
        public string Address { get; set; }
        public string MobileNumber { get; set; }
        public string Sex { get; set; }
    }
public class UserDto
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        public string Phone { get; set; }
        public string DateOfBirth { get; set; }
        public string Country { get; set; }
    }
}

Now inside the AutoMapperProfile class we need to add the following

public class AutoMapperProfile : Profile
    {
        public AutoMapperProfile()
        {
            CreateMap<UserDto, User>()
                .ForMember(
                    dest => dest.FirstName,
                    opt => opt.MapFrom(src => $"{src.FirstName}")
                )
                .ForMember(
                    dest => dest.LastName,
                    opt => opt.MapFrom(src => $"{src.LastName}")
                )
                .ForMember(
                    dest => dest.Email,
                    opt => opt.MapFrom(src => $"{src.Email}")
                )
                .ForMember(
                    dest => Convert.ToDateTime(dest.DateOfBirth),
                    opt => opt.MapFrom(src => $"{src.DateOfBirth}")
                )
                .ForMember(
                    dest => dest.Phone,
                    opt => opt.MapFrom(src => $"{src.Phone}")
                )
                .ForMember(
                    dest => dest.Country,
                    opt => opt.MapFrom(src => $"{src.Country}")
                )
                .ForMember(
                    dest => dest.Status,
                    opt => opt.MapFrom(src => 1)
                );
        }
    }

The AutoMapperProfile class MUST inherit from Profile class in order for AutoMapper to recognise it.

Inside the constructor we define the mapping between the Entity and the Dto.

Once we complete our profile mapping its now to utilise our new map in our controller.

public class UsersController : ControllerBase
{
    public IUnitOfWork _unitOfWork;
    // define the mapper
    public readonly IMapper _mapper;

    // initialise the dependencies with constructor initialisation
    public UsersController(
        IMapper mapper,
        IUnitOfWork unitOfWork)
    {   
        _mapper = mapper;
        _unitOfWork = unitOfWork;
    }

    [HttpPost]
    public async Task<IActionResult> AddUser(UserDto user)
    {
        // utilise the mapping :)
        var _mappedUser = _mapper.Map<User>(user);

        await _unitOfWork.Users.Add(_mappedUser);
        await _unitOfWork.CompleteAsync();

        var result = new Result<UserDto>();
        result.Content = user;

        return CreatedAtRoute("GetUser", new { id = _mappedUser.Id}, result); // return a 201
    }
}

So basically we need to initialise the mapper with constructor initialisation.

Then we need to utilise as follow

var _mappedUser = _mapper.Map<Entity>(dto);

AutoMapper is a powerful tool to keep in our toolset.

Angular13 and .NET 6 – Getting started

We would need to install Visual Studio 2022.

https://visualstudio.microsoft.com/

Install .NET 6 SDK

This can be downloaded either from Microsoft official URL;

https://dotnet.microsoft.com/en-us/download/dotnet/6.0

Or from the GitHub official release page;

https://github.com/dotnet/core/tree/main/release-notes/6.0

Check the SDK version by opening a command prompt;

> dotnet –help
> dot net –version

Install NVM

If we need to work with different Node.js version, we would need to install nvm.

To prepare for angular development, we would need following components;

  1. Nvm – Node Version Manager. Its is a tool that allows us to download install Node.js. It allows us to pick and choose the Node.js version.
  2. Node.js – Its is a platform for running Javascript applications.

To install node version manager for windows (nvm), click here;

https://github.com/coreybutler/nvm-windows/releases

Scroll to Assets tab and download either nvm-setup.zip or nvm-setup.exe.

If download is for nvm-setup.zip, Unzip download zip file and run nvm-setup.exe. Select Symlink for Node.js. When finished, run this command;

> nvm –version

To install node.js, use this;

//installs the latest version of node.js
> nvm install latest              

//this will install specific version of node.js
> nvm install <<version number>> 

If we have multiple versions of node.js and wanted to use a specific version in our environment, try this in elevated command prompt;

> nvm use 18.8.0

Install Angular CLI;

npm is alredy installed with Visual Studio 2022 installation. Time to install Angular CLI;

> npm install -g @angular/cli@13.0.1

When finished, run following command to check the version;

> ng –version

In my case, I got this error message;

Since I have installed node.js latest version v18.8.0 but Angular 13 doesn’t’ support this. To resolve, head to this link;

https://nodejs.org/en/

So version 16.17.0 is the LTS version. Download and use this version using nvm;

> nvm install 16.17.0
> nvm use 16.17.0

I tried to use ng –version command on my computer but it didn’t work. I needed to re-run this command for angular cli installation;

> npm install -g @angular/cli@13.0.1

restart your computer and run this command again to check Angular CLI version;

> ng --version

This time installation is successful with this message;

Path Variables

If nvm doesn’t work, add it to the environment variable. Press win+I on windows 11. Under About -> “Device specifications” box, click on “Advanced system settings” and select environment variables.

Add nvm.exe to “User variables for admin” section. Here are the values;

Restart your computer. Open command window and run following command any where;

> nvm --version

This should work.

Check All versions

> nvm –-version
> npm –-version
> node –version
> ng –version</p>

If all commands run successfully, We are ready to rock-n-roll with Angular 13 and .NET 6.

Creating test project using Visual Studio 2022

Microsoft has a template, ASP.NET Core with Angular, to create .NET core project with Angular. It’s a single project template with front-end and back-end project. We will not be using this template for our test project. We will create two projects, front-end and back-end and connect those projects.

Create front-end project, e.g. Foo, using “Standalone Typescript Angular Project” template. Create back-end web API project, e.g. FooAPI, within same solution. Double click on launchsettings.json file and change ports to 5001 for https and 5000 for http.

On front-end project, under /src/proxy.conf.js, make sure the port is configured to be 5001. This is the port kestrel web server is listening for incoming requests.

const PROXY_CONFIG = [
  {
    context: [
      "/weatherforecast",
    ],
    target: "https://localhost:5001",
    secure: false
  }
]

module.exports = PROXY_CONFIG;

Angular development port configuration are in /.vscode/launch.json file. If you don’t see it, it might be hidden. Usually it’s mapped to HTTPS on port 4200.

Last step is to setup startup project for this multi-project solution. Right click on solution and click on “Set startup project”. Change startup project from “single startup project” to “multiple startup projects” and select “start” for each project. Move FooAPI project on top so it can start first.

Do a quick test run of these multi-projects in Debug mode by pressing F5. Visual Studio will launch 3 process;

  1. ASP.NET Core Server (Kestral or IIS Express)
  2. Angular Live Development Server (using “ng serve” command from the Angular CLI)
  3. Web Server (Google or Edge)

We will be seeing this basic page;

Angular component performing a simple data fetching task from ASP.NET Core Web API project. A small but good working example without any boilerplate code / extra fluff.

A sample diagram how these 3 process interact with each other;

All components are working as expected.

Pass parameters to action method in ASP.NET Core

One of the simplest and easiest ways to pass parameters to an action method is passing it via the URL. The following code snippet illustrates how you can pass parameters in the URL.

[HttpGet]
[Route("Default/GetAuthor/{authorId:int}")]
public IActionResult GetAuthor(int authorId)
{
   var data = authorRepository.GetAuthor(authorId);
   return View(data);
}

The URL to the endpoint is:

GET: http://localhost:8061/Default/GetAuthor/1

Here are some of links;

https://www.infoworld.com/article/3568209/how-to-pass-parameters-to-action-methods-in-asp-net-core-mvc.html

Get file path in .net core from wwwroot folder

This is how;

public class HomeController : Controller {
    private IWebHostEnvironment _hostEnvironment;

    public HomeController(IWebHostEnvironment environment) {
        _hostEnvironment = environment;
    }

    [HttpGet]
    public IActionResult Get() {
        string path = Path.Combine(_hostEnvironment.WebRootPath, "Sample.PNG");
        return View();
    }
}

References

https://weblog.west-wind.com/posts/2020/Feb/26/Working-with-IWebHostEnvironment-and-IHostingEnvironment-in-dual-targeted-NET-Core-Projects#out-with-old-in-with-the-new-iwebhostenvironment

Decode JWT Token

Decoding JWT token and return value;

protected string GetCalimValue(string token)
{
   var handler = new JwtSecurityTokenHandler();
   var jsonToken = handler.ReadToken(token);
   var tokenJWT = jsonToken as JwtSecurityToken;
   //var jwtSecurityToken = handler.ReadJwtToken(token);

   var jti = tokenJWT.Claims.First(claim => claim.Type == "jti").Value;
   return jti;
}

Validating and Decoding JWT Token and return value;

protected string ValidateTokenAndGetClaimValue(string token)
{
    string secret = "this is a string used for encrypt and decrypt token";
    var key = Encoding.ASCII.GetBytes(secret);
    var handler = new JwtSecurityTokenHandler();
    var validations = new TokenValidationParameters
    {
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = new SymmetricSecurityKey(key),
        ValidateIssuer = false,
        ValidateAudience = false
    };
    var claims = handler.ValidateToken(token, validations, out var tokenSecure);

    var tokenJWT = tokenSecure as JwtSecurityToken;
    var emailAddress = tokenJWT.Claims.First(claim => claim.Type == "email").Value;
    return emailAddress;
}

We want to keep token inside cookies on a successful token acquisition;

Response.Cookies.Append("X-Access-Token", login.JwToken, new CookieOptions() { HttpOnly = true, SameSite = SameSiteMode.Strict });
Response.Cookies.Append("X-Email", login.Email, new CookieOptions() { HttpOnly = true, SameSite = SameSiteMode.Strict });

References

https://stackoverflow.com/questions/38340078/how-to-decode-jwt-token

https://www.codemag.com/Article/2105051/Implementing-JWT-Authentication-in-ASP.NET-Core-5