Implementing CQRS Pattern with Vue.js and ASP.NET Core MVC

Introduction 

 
If you’re a software professional, then you’re familiar with the Software enhancement and maintenance work. This is the part of the software development life cycle, so you can correct the faults, and delete or enhance existing features. The software maintenance cost can be minimized if you use a software architectural pattern, choose the right technologies, and are aware of the industry trends for the future. It also helps to consider resource reliability/availability for now and the future, use a design pattern/principle in your code, re-use your code and keep your options open for future extensions, etc. Anyway, if you use any known software architectural pattern in your application, then it will be easy for others to understand the structure/component design of your application. I’ll explain a sample project implementation according to the CQRS pattern using MediatR in ASP.NET Core MVC with vue.js.
 

Coverage Topics

  • Implementation of CQRS Pattern
  • Configure MediatR Package for ASP.NET Core
  • Data read/write Handler Implantation using MediatR
  • Integrating MediatR with API Controller/Controller
  • Passing Command/Query Object using MediatR
  • Converting image to byte array/byte array to base64 string
Prerequisites

Drilldown the Basic Shorty

  • CQRS Pattern: In a short, Command – Query Separation Responsibility (CQRS) pattern separates the READ query operation which returns the data without changing the database/system and WRITE command (insert/update/delete) operation which changes the data into the database/system. NEVER mix the read and write operation together. 
  • Mediator Pattern: This is a design pattern that has an impact on the code where Mediator is used when you need centralized control and communication between multiple classes/objects. For example, Facebook Messenger is a mediator to send messages to multiple users. 
  • MVC Pattern: This is an architectural pattern for the application where Model, View, and Controller are separated by their responsibility. Model is the data of an object; View presents data to the user and handles user interaction, and the Controller acts as a mediator between View & Model.

Application Solution Structure

 
The main goal of this project is to explain the CQRS architectural pattern. I’m planning to implement a tiny Single-Page-Application (SPA) project. The choice of technology is important, and you should choose it according to your requirements. For the User Interface (UI) and Presentation Logic Layer (PLL), I chose ASP.NET Core MVC and Vue.js (JavaScript framework). For the data access, I chose the Entity Framework (EF) Core Code First Approach. It will be implemented into the Data-Access-Layer (DAL). Intentionally, I’m avoiding a separate Business Logic Layer (BLL) and other layers to minimize the length of this article.
 

Image Upload & Display Application

 
In this project, considering the CQRS pattern, at first, I will upload the image file to save it into the database; it will explain the write command operation. Secondly, I will read the data from the database to display the image; it will explain the read query operation.

I’ve added two separate projects in the same solution. One is the ClassLibrary (.NET Core) project which is named “HR.App.DAL.CQRS” and another is the ASP.NET Core Web Application project which is named “HR.App.Web”.
 
HR.App.Solution
 

Communication Design Between MVC & JS Framework

 
In this stage, I’m pointing the UI/PLL and how they will talk to each other. Look at the diagram below, I’m placing the JS framework in between the View and Web API Controller.

UI and PLL
 
According to the above diagram, ASP.NET MVC Controller renders the View. JS passes the HTTP request (GET/PUT/POST/DELETE) from the view to the Web API Controller as well as update the response data (JSON/XML) from Web API Controller to the View.
 
MVC and Javascript Communication
 
Note
I’m guessing, you know, how to configure the Vue.js in ASP.NET Core MVC project. If you need the step by step instructions to configure the Vue.js in the ASP.NET Core with a sample project, then recommended reading: "Integrating/Configuring Vue.js in ASP.NET Core 3.1 MVC"
 

In SPA, Adding the UI and PLL in the Presentation Layer

 
In “HR.App.Web” project, add the Index.cshtml view and Index.cshtml.js file. I add the following HTML scripts for the Image upload and Image view tag/control into the Index.cshtml. These are associated with reading and write actions.
  1. @{    
  2.     ViewData["Title"] = "Home Page";    
  3. }    
  4.     
  5.     <div id="view" v-cloak>    
  6.         <div class="card">    
  7.             <div class="card-header">    
  8.                 <div class="row">    
  9.                     <div class="col-10">    
  10.                         <h5>Upload File</h5>    
  11.                     </div>    
  12.                 </div>    
  13.             </div>    
  14.             <div class="card-body">    
  15.                 <dropzone id="uploadDropZone" url="/HomeApi/SubmitFile"    
  16.                           :use-custom-dropzone-options="useUploadOptions"    
  17.                           :dropzone-options="uploadOptions" v-on:vdropzone-success="onUploaded"    
  18.                           v-on:vdropzone-error="onUploadError">    
  19.                     <!-- Optional parameters if any! -->    
  20.                     <input type="hidden" name="token" value="xxx">    
  21.                 </dropzone>    
  22.             </div>    
  23.         </div>    
  24.         <br/>    
  25.         <div class="card">    
  26.             <div class="card-header">    
  27.                 <div class="row">    
  28.                     <div class="col-10">    
  29.                         <h5>Image viewer</h5>    
  30.                     </div>    
  31.                 </div>    
  32.             </div>    
  33.             <div class="card-body">    
  34.                 <img v-bind:src="imageData" v-bind:alt="imageAlt" style="width:25%;height:25%; display: block;margin-left: auto; margin-right: auto;" />    
  35.                 <hr />    
  36.                 <div class="col-6">    
  37.                     <button id="viewFile" ref="viewFileRef" type="button" class="btn btn-info" v-on:click="viewImageById">View Image</button>    
  38.                     <button type="button" class="btn btn-info" v-on:click="onClear">Clear</button>    
  39.                 </div>    
  40.     
  41.             </div>    
  42.         </div>    
  43.     </div>    
  44. <script type="text/javascript">    
  45. </script>    
  46. <script type="text/javascript" src="~/dest/js/home.bundle.js" asp-append-version="true"></script>    
Add the following Vue.js script for the HTTP GET and POST request into the Index.cshtml.js file:
  1. import Vue from 'vue';  
  2. import Dropzone from 'vue2-dropzone';  
  3.   
  4. document.addEventListener('DOMContentLoaded'function (event) {  
  5.     let view = new Vue({  
  6.         el: document.getElementById('view'),  
  7.         components: {  
  8.             "dropzone": Dropzone  
  9.         },  
  10.         data: {  
  11.             message: 'This is the index page',  
  12.             useUploadOptions: true,  
  13.             imageData: '',  
  14.             imageAlt: 'Image',  
  15.             imageId: 0,  
  16.             uploadOptions: {  
  17.                 acceptedFiles: "image/*",  
  18.                 //acceptedFiles: '.png,.jpg',  
  19.                 dictDefaultMessage: 'To upload the image click here. Or, drop an image here.',  
  20.                 maxFiles: 1,  
  21.                 maxFileSizeInMB: 20,  
  22.                 addRemoveLinks: true  
  23.             }  
  24.         },  
  25.         methods: {  
  26.             onClear() {  
  27.                 this.imageData = '';  
  28.             },  
  29.             viewImageById() {  
  30.                 try {  
  31.                     this.dialogErrorMsg = "";  
  32.                     //this.imageId = 1;  
  33.                     var url = '/HomeApi/GetImageById/' + this.imageId;  
  34.   
  35.                     console.log("===URL===>" + url);  
  36.                     var self = this;  
  37.   
  38.                     axios.get(url)  
  39.                         .then(response => {  
  40.                             let responseData = response.data;  
  41.   
  42.                             if (responseData.status === "Error") {  
  43.                                 console.log(responseData.message);  
  44.                             }  
  45.                             else {  
  46.                                 self.imageData = responseData.imgData;  
  47.                                 console.log("Image is successfully loaded.");  
  48.                             }  
  49.                         })  
  50.                         .catch(function (error) {  
  51.                             console.log(error);  
  52.                         });  
  53.                 } catch (ex) {  
  54.   
  55.                     console.log(ex);  
  56.                 }  
  57.             },  
  58.             onUploaded: function (file, response) {  
  59.                 if (response.status === "OK" || response.status === "200") {  
  60.                     let finalResult = response.imageId;  
  61.                     this.imageId = finalResult;  
  62.                     console.log('Successfully uploaded!');  
  63.                 }  
  64.                 else {  
  65.                     this.isVisible = false;  
  66.                     console.log(response.message);  
  67.                 }  
  68.             },  
  69.             onUploadError: function (file, message, xhr) {  
  70.                 console.log("Message ====> " + JSON.stringify(message));  
  71.             }  
  72.         }  
  73.     });  
  74. });  
In this JS file, the “viewImageById” method is used for the read request and “onUploaded” method is used for the write request. The screen looks like:
 
 

Data Access Layer for Data READ & WRITE Operations

 
I’m guessing you know the EF Core Code First Approach and you have the domain models and context class. You may use a different approach. Here, I’ll implement the Read and Write operations for data access. Look at the diagram below to understand the whole process of the application.
Full Diagram
 
Packages Installation
 
In “HR.App.DAL.CQRS” project, I’ve installed MediatR.Extensions.Microsoft.DependencyInjection, Microsoft.EntityFrameworkCore and Microsoft.EntityFrameworkCore.SqlServer “ using NuGet Package Manager.
 
Packages Installation
 
I need the MediatR to implement the Command and Query handlers. I’ll use the MediatR.Extensions for ASP.NET Core to resolve the dependency.
 

Read Query Handler Implementation

 
To get an image from the database, I’ve added the GetImageQuery.cs class with the following code:
  1. using HR.App.DAL.CQRS.Models;  
  2. using HR.App.DAL.CQRS.ViewModel;  
  3. using MediatR;  
  4. using Microsoft.EntityFrameworkCore;  
  5. using System;  
  6. using System.Linq;  
  7. using System.Threading;  
  8. using System.Threading.Tasks;  
  9.   
  10. namespace HR.App.DAL.CQRS.Query  
  11. {  
  12.     public class GetImageQuery : IRequest<ImageResponse>  
  13.     {  
  14.         public int ImageId { getset; }  
  15.     }  
  16.   
  17.     public class GetImageQueryHandler : IRequestHandler<GetImageQuery, ImageResponse>  
  18.     {  
  19.         private readonly HrAppContext context;  
  20.   
  21.         public GetImageQueryHandler(HrAppContext context)  
  22.         {  
  23.             this.context = context;  
  24.         }  
  25.   
  26.         public async Task<ImageResponse> Handle(GetImageQuery request, CancellationToken cancellationToken)  
  27.         {  
  28.             ImageResponse imageResponse = new ImageResponse();  
  29.   
  30.             try  
  31.             {  
  32.                 UploadedImage uploadedImage = await context.UploadedImage.AsNoTracking()  
  33.                     .Where(x => x.ImageId == request.ImageId).SingleAsync();  
  34.                   
  35.                 if (uploadedImage == null)  
  36.                 {  
  37.                     imageResponse.Errors.Add("No Image found!");  
  38.                     return imageResponse;  
  39.                 }  
  40.   
  41.                 imageResponse.UploadedImage = uploadedImage;  
  42.                 imageResponse.IsSuccess = true;  
  43.             }  
  44.             catch (Exception exception)  
  45.             {  
  46.                 imageResponse.Errors.Add(exception.Message);  
  47.             }  
  48.   
  49.             return imageResponse;  
  50.         }  
  51.     }  
  52. }  
The GetImageQuery class inherits IRequest; the ImageResponse type indicates the response. On the other hand, the GetImageQueryHandler class inherits the IRequestHandler where the GetImageQuery type indicates the request/message and the ImageResponse type indicates the response/output. This GetImageQueryHandler class implements the Handle method which returns the ImageResponse object.
 

WRITE Command Handler

 
To save an image into the database, I’ve added the SaveImageCommand.cs class which contains the following code:
  1. using HR.App.DAL.CQRS.Models;  
  2. using HR.App.DAL.CQRS.ViewModel;  
  3. using MediatR;  
  4. using System;  
  5. using System.Threading;  
  6. using System.Threading.Tasks;  
  7.   
  8. namespace HR.App.DAL.CQRS.Command  
  9. {  
  10.     public class SaveImageCommand : IRequest<ResponseResult>  
  11.     {  
  12.         public UploadedImage UploadedImage { getset; }  
  13.     }  
  14.   
  15.     public class SaveImageCommandHandler : IRequestHandler<SaveImageCommand, ResponseResult>  
  16.     {  
  17.         private readonly HrAppContext context;  
  18.   
  19.         public SaveImageCommandHandler(HrAppContext context)  
  20.         {  
  21.             this.context = context;  
  22.         }  
  23.   
  24.         public async Task<ResponseResult> Handle(SaveImageCommand request, CancellationToken cancellationToken)  
  25.         {  
  26.             using (var trans = context.Database.BeginTransaction())  
  27.             {  
  28.                 ResponseResult response = new ResponseResult();  
  29.   
  30.                 try  
  31.                 {  
  32.                     context.Add(request.UploadedImage);  
  33.                     await context.SaveChangesAsync();  
  34.                     trans.Commit();  
  35.                     response.IsSuccess = true;  
  36.                     response.ImageId = request.UploadedImage.ImageId;  
  37.                 }  
  38.                 catch (Exception exception)  
  39.                 {  
  40.                     trans.Rollback();  
  41.                     response.Errors.Add(exception.Message);  
  42.                 }  
  43.   
  44.                 return response;  
  45.             }  
  46.         }  
  47.     }  
  48. }  

Integrating MediatR with API Controller/Controller

 
In the “HR.App.Web” project, I’ve installed MediatR.Extensions.Microsoft.DependencyInjection, using NuGet Package Manager. It may ask for permission to install the dependent package (Microsoft.Extensions.DependencyInjection.Abstractions).
 
Configuring MediatR
 
Add the following code in the ConfigureServices method into the Startup.cs class to register MediatR:
  1. services.AddMediatR(typeof(Startup));  
This configuration works well if you have all the handler classes into the same assembly of the ASP.NET Core MVC project (say, “HR.App.Web”). If you use a different assembly (say, HR.App.DAL.CQRS) in the same project solution, then you have to escape the above code and need to add the following code:
  1. services.AddMediatR(typeof(GetImageQuery));  
If you use multiple assemblies (say, AssemblyA and AnotherAssemblyB) in the same project solution, then you need to add all the types of assembly services.AddMediatR(typeof(AssemblyAClassName), typeof(AnotherAssemblyBClassName));
 

Injecting dependency into Web-API Controller/Controller

 
In the HomeApiController.cs class, I’ve added “SubmitFile” and “GetImageId” actions and these actions will send the command and query objects using MediatR. The below code indicates that I’ve injected a dependency Mediator object in the HomeApiController constructor. By the way, the web API controller returns the JSON/XML data.
 
Injecting dependency into Web-API Controller
 
The Controller returns the view, in the HomeController.cs, I just use the default Index action to return the view.
 
 

How to Send Command/Query Request

 
We can send the command/query object using the mediator object: mediator.Send(command/query Object). Look at the codes below.
 
HowToSendCmdQuery
 
The whole code is given below:
  1. using HR.App.DAL.CQRS.Command;  
  2. using HR.App.DAL.CQRS.Models;  
  3. using HR.App.DAL.CQRS.Query;  
  4. using HR.App.DAL.CQRS.ViewModel;  
  5. using MediatR;  
  6. using Microsoft.AspNetCore.Http;  
  7. using Microsoft.AspNetCore.Mvc;  
  8. using System;  
  9. using System.IO;  
  10. using System.Threading.Tasks;  
  11.   
  12. namespace HR.App.Web.Controllers  
  13. {  
  14.     [Route("api")]  
  15.     [ApiController]  
  16.     public class HomeApiController : Controller  
  17.     {  
  18.         private readonly IMediator mediator;  
  19.   
  20.         public HomeApiController(IMediator mediator)  
  21.         {  
  22.             this.mediator = mediator;  
  23.         }  
  24.   
  25.         [HttpPost("/HomeApi/SubmitFile")]  
  26.         public async Task<ActionResult> SubmitFile(IFormFile file)  
  27.         {  
  28.             try  
  29.             {  
  30.                 #region Validation & BL  
  31.                 if (file.Length == 0)  
  32.                 {  
  33.                     return Json(new { status = "Error", message = "Image is not found!" });  
  34.                 }  
  35.   
  36.                 if (!file.ContentType.Contains("image"))  
  37.                 {  
  38.                     return Json(new { status = "Error", message = "This is not an image file!" });  
  39.                 }  
  40.   
  41.                 string fileName = file.FileName;  
  42.   
  43.                 if (file.FileName.Length > 50)  
  44.                 {  
  45.                     fileName = string.Format($"{file.FileName.Substring(0, 45)}{Path.GetExtension(file.FileName)}");  
  46.                 }  
  47.                 #endregion  
  48.   
  49.                 byte[] bytes = null;  
  50.   
  51.                 using (BinaryReader br = new BinaryReader(file.OpenReadStream()))  
  52.                 {  
  53.                     bytes = br.ReadBytes((int)file.OpenReadStream().Length);  
  54.                 }  
  55.   
  56.                 UploadedImage uploadedImage = new UploadedImage()  
  57.                 {  
  58.                     ImageFileName= fileName,  
  59.                     FileContentType = file.ContentType,  
  60.                     ImageContent = bytes  
  61.                 };  
  62.   
  63.                 SaveImageCommand saveImageCommand = new SaveImageCommand()  
  64.                 {  
  65.                     UploadedImage = uploadedImage  
  66.                 };  
  67.   
  68.                 ResponseResult responseResult = await mediator.Send(saveImageCommand);  
  69.   
  70.                 if (!responseResult.IsSuccess)  
  71.                 {  
  72.                     return Json(new { status = "Error", message = string.Join("; ", responseResult.Errors) });  
  73.                 }  
  74.   
  75.                 return Json(new { status = "OK", imageId= responseResult.ImageId });  
  76.             }  
  77.             catch (Exception ex)  
  78.             {  
  79.                 return Json(new { status = "Error", message = ex.Message });  
  80.             }  
  81.         }  
  82.   
  83.         [HttpGet("/HomeApi/GetImageById/{imageId:int}")]  
  84.         public async Task<ActionResult> GetImageById(int imageId)  
  85.         {  
  86.             try  
  87.             {  
  88.                 ImageResponse imageResponse = await mediator.Send(new GetImageQuery()  
  89.                 {  
  90.                     ImageId = imageId  
  91.                 });  
  92.   
  93.                 UploadedImage uploadedImage = imageResponse.UploadedImage;  
  94.   
  95.                 if (!imageResponse.IsSuccess)  
  96.                 {  
  97.                     return Json(new { status = "Error", message = string.Join("; ", imageResponse.Errors) });  
  98.                 }  
  99.                 if (uploadedImage.FileContentType == null || !uploadedImage.FileContentType.Contains("image"))  
  100.                 {  
  101.                     return Json(new { status = "Error", message = string.Join("; ", imageResponse.Errors) });  
  102.                 }  
  103.   
  104.                 string imgBase64Data = Convert.ToBase64String(uploadedImage.ImageContent);  
  105.                 string imgDataURL = string.Format("data:{0};base64,{1}",   
  106.                     uploadedImage.FileContentType, imgBase64Data);  
  107.                   
  108.                 return Json(new { status = "OK", imgData = imgDataURL });  
  109.             }  
  110.             catch (Exception ex)  
  111.             {  
  112.                 return Json(new { status = "Error", message = ex.Message });  
  113.             }  
  114.         }  
  115.     }  
  116. }  
In the above codes into the “SubmitFile” action receives the HttpPost with IFormFile object with an image and it Converts image to byte array. Finally, it sends the SaveImageCommand object using mediator.

On the other hand, the GetImageById action receives a HttpGet request with an imageId and sends a query request using a mediator. Finally, it processes the image content from byte array to base64 string to send it to the view.

Anyway, now if you run the project, then you will see the following screen to upload and view the image:
 
Output Screen
 
There are many cases where we need to read and write operations to complete a single task. For example, say, I need to update few properties of an object. First, I can call a query operation to read the object and then, after putting the required values, I can call an update Operation to store it. In this case, NEVER mix-up the read query and write command into the same operation/handler. Keep them separate then, it will be easy to modify in the future.