Nullable Date Format in C#


If we have to format the Nullable Date in C#, We can do like this

DateTime? date = new DateTime(2021, 05, 10, 22, 45, 12, 004);
//Will through exception
// string date_str = date.ToString("dd/MM/yyyy");

//Working Syntax:
string date_str= (date != null ? date.Value.ToString("dd/MM/yyyy") : "n/a");

CQRS with MediatR Pattern in Asp.net Core Web Api 5.0


What is the CQRS ?

CQRS is the Command Query Responsibility Segregation design pattern. In this pattern Command is used to Insert/Update/Delete operation . Query is used to fetching data from database.

What are advantages of CQRS Pattern ?

  1. Highly scalable : while creating microservice api, we can easily scale up our application, if we we have written the code for command and query in separate layer.
  2. Improved Performance : If we have segregated the read and write functionalities separate layer and deployed as separately then it will give very good performance.

What is the MediatR Pattern ?

Mediator is a behavioral design pattern that lets you reduce chaotic dependencies between objects. The pattern restricts direct communications between the objects and forces them to collaborate only via a mediator object. It supports easy maintenance of the code by loose coupling. Mediator pattern falls under behavioral pattern category.

How to implement in Asp.net core web api 5.0 ?

I m creating very simple application to understand this pattern, I m going to use VS 2019. We are going to achieve CQRS pattern using MediatR nuget package manager

Step 1: Create the Asp.net Web Api 5.0 application.

Step 2: Install the MediatR package like given below

Make sure to install Entity Framework related package

Step 3: Go to the start up file of ConfigureService and add the MediatR Service like this

Step 4: Go to the Model folder of Application and create the Emp Class like

Step 5: Create the Context folder in application and Create the IApplicationContext interface like this

using CQRS_Emp_Demo.Model;
using Microsoft.EntityFrameworkCore;
using System.Threading.Tasks;

namespace CQRS_Emp_Demo.Context
{
    public interface IApplicationContext
    {
        DbSet<Emp> Emps { get; set; }

        Task<int> SaveChangesAsync();
    }
}

Step 6: Create ApplicationContext class for Emp Model like this

using CQRS_Emp_Demo.Model;
using Microsoft.EntityFrameworkCore;
using System.Threading.Tasks;

namespace CQRS_Emp_Demo.Context
{
    public class ApplicationContext : DbContext, IApplicationContext
    {
        public DbSet<Emp> Emps { get; set; }
        public ApplicationContext(DbContextOptions<ApplicationContext> options) : base(options)
        {

        }
        public async Task<int> SaveChangesAsync()
        {
            return await base.SaveChangesAsync();
        }
    }
}

Step 7: Clean and rebuild the application then run this command

add-migration “initial”
update-database

Step 8: Create the Command and Query Folder as given below image

Step 9: In Queries folder create GetAllEmpsQuery class and write the code like this

using CQRS_Emp_Demo.Context;
using CQRS_Emp_Demo.Model;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

namespace CQRS_Emp_Demo
{
    public class GetAllEmpsQuery : IRequest<IEnumerable<Emp>>
    {
        public class GetAllEmpsQueryHandler : IRequestHandler<GetAllEmpsQuery, IEnumerable<Emp>>
        {
            private readonly IApplicationContext _context;
            public GetAllEmpsQueryHandler(IApplicationContext context)
            {
                _context = context;
            }
            public async Task<IEnumerable<Emp>> Handle(GetAllEmpsQuery request, CancellationToken cancellationToken)
            {
                var emplist = await _context.Emps.ToListAsync();
                if (emplist == null)
                {
                    return null;
                }
                return emplist.AsReadOnly();
            }
        }
    }
}

In the above code we are using IRequest and IRequestHandler interface of mediator library to make loose couple code.

Step 9: Create the Class i.e. GetEmpByIdQuery.cs and write the code like this

using CQRS_Emp_Demo.Context;
using CQRS_Emp_Demo.Model;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace CQRS_Emp_Demo
{
    public class GetEmpByIdQuery : IRequest<Emp>
    {
        public int Id { get; set; }
        public class GetEmpByIdQueryHandler : IRequestHandler<GetEmpByIdQuery, Emp>
        {
            private readonly IApplicationContext _context;
            public GetEmpByIdQueryHandler(IApplicationContext context)
            {
                _context = context;
            }

            public async Task<Emp> Handle(GetEmpByIdQuery request, CancellationToken cancellationToken)
            {
                var emp = await _context.Emps.Where(m => m.Id == request.Id).FirstOrDefaultAsync();
                if (emp == null) return null;
                return emp;
            }
        }
    }
}

Step 10: Now we will the code command service for Insert/Update/ Delete in Command folder like this

For CreateEmpCommand.cs

using CQRS_Emp_Demo.Context;
using CQRS_Emp_Demo.Model;
using MediatR;
using System.Threading;
using System.Threading.Tasks;

namespace CQRS_Emp_Demo
{
    public class CreateEmpCommand : IRequest<int>
    {
        public int Id { get; set; }
        public string EmpName { get; set; }
        public string EmpAddress { get; set; }
        public string Country { get; set; }

        public class CreateEmpCommandHandler : IRequestHandler<CreateEmpCommand, int>
        {
            private readonly IApplicationContext _context;
            public CreateEmpCommandHandler(IApplicationContext context)
            {
                _context = context;
            }
            public async Task<int> Handle(CreateEmpCommand request, CancellationToken cancellationToken)
            {
                var emp = new Emp();
                emp.EmpName = request.EmpName;
                emp.EmpAddress = request.EmpAddress;
                emp.Country = request.Country;
                _context.Emps.Add(emp);
                int flag = await _context.SaveChangesAsync();
                return flag;
            }
        }
    }
}

For UpdateCommand.cs

using CQRS_Emp_Demo.Context;
using MediatR;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace CQRS_Emp_Demo
{
    public class UpdateEmpCommand : IRequest<int>
    {
        public int Id { get; set; }
        public string EmpName { get; set; }
        public string EmpAddress { get; set; }
        public string Country { get; set; }
        public class UpdateEmpCommandHandler : IRequestHandler<UpdateEmpCommand, int>
        {
            private readonly IApplicationContext _context;
            public UpdateEmpCommandHandler(IApplicationContext context)
            {
                _context = context;
            }
            public async Task<int> Handle(UpdateEmpCommand request, CancellationToken cancellationToken)
            {
                var emp = _context.Emps.Where(a => a.Id == request.Id).FirstOrDefault();
                if (emp == null)
                {
                    return default;
                }
                else
                {
                    emp.Country = request.Country;
                    emp.EmpAddress = request.EmpAddress;
                    emp.EmpName = request.EmpName;
                    int flag = await _context.SaveChangesAsync();
                    return flag;
                }
            }
        }
    }
}

For DeleteEmpCommand.cs

using CQRS_Emp_Demo.Context;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace CQRS_Emp_Demo
{
    public class DeleteEmpCommand : IRequest<int>
    {
        public int Id { get; set; }
        public class DeleteEmpCommandHandler : IRequestHandler<DeleteEmpCommand, int>
        {
            public readonly IApplicationContext _context;
            public DeleteEmpCommandHandler(IApplicationContext context)
            {
                _context = context;
            }

            public async Task<int> Handle(DeleteEmpCommand request, CancellationToken cancellationToken)
            {
                var emp = await _context.Emps.Where(m => m.Id == request.Id).FirstOrDefaultAsync();
                if (emp == null) return default;
                _context.Emps.Remove(emp);
                int flag = await _context.SaveChangesAsync();
                return flag;

            }
        }
    }
}

Step 11: Create the EmpController in Controller folder and write code like this

using MediatR;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using System.Threading.Tasks;


namespace CQRS_Emp_Demo.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class EmpController : ControllerBase
    {
        private IMediator _mediator;
        protected IMediator Mediator => _mediator ??= HttpContext.RequestServices.GetService<IMediator>();

        // GET: api/<EmpController>
        [HttpGet]
        public async Task<IActionResult> Get()
        {
            return Ok(await Mediator.Send(new GetAllEmpsQuery()));
        }

        // GET api/<EmpController>/5
        [HttpGet("{id}")]
        public async Task<IActionResult> GetEmpById(int id)
        {
            return Ok(await Mediator.Send(new GetEmpByIdQuery { Id = id }));
        }

        // POST api/<EmpController>
        [HttpPost]
        public async Task<IActionResult> SaveEmp(CreateEmpCommand command)
        {
            return Ok(await Mediator.Send(command));
        }

        // PUT api/<EmpController>/5
        [HttpPut("{id}")]
        public async Task<IActionResult> UpdateEmpById(int id, UpdateEmpCommand command)
        {
            if (id != command.Id)
            {
                return BadRequest();
            }
            return Ok(await Mediator.Send(command));
        }

        // DELETE api/<EmpController>/5
        [HttpDelete("{id}")]
        public async Task<IActionResult> Delete(int id)
        {
            return Ok(await Mediator.Send(new DeleteEmpCommand { Id = id }));
        }
    }
}

Step 12: Rebuild and run the application then execute the get method in swagger, You will get output like this

Summary

In the above demo, we saw that how to implement CQRS using mediatR Nuget package manager in Asp.net Core web API 5.0 . I have implemented it in very simple database. If you want the source code then please download from below Github URL

https://github.com/Chandradev819/CQRS_Emp_Demo.git

How to split the C# code from Blazor Component ?


In so many scenario splitting the C# code from html file will be good decision like unit testing or code re-usability in blazor project.

We can do this task in blazor using two approach
1. Partial files approach
2. Base class approach

Partial files approach

In this approach we create the same class name as component name. Suppose i have component test3.razor
then i have to create Test3.cs partial class

test3.razor file

@page "/test3"
<h3>This is test3 page</h3>
<p>Message from C# Code Block: @msg</p>
<button @onclick="SayHello">Click Here</button>

Test3.cs partial class

namespace BlazorApp2.Pages
{
    public partial class Test3
    {
    public string msg = string.Empty;
    private void SayHello()
    {
        msg= "Hello Blazor";
    }
    }
}

2. Base class approach

In this approach the create the base class which will inherit the ComponentBase class.

using Microsoft.AspNetCore.Components;

namespace BlazorApp2.Pages
{
    public  class Test3Base: ComponentBase
    {
    public string msg = string.Empty;
    public void SayHello()
    {
        msg= "Hello Blazor";
    }
    }
}

In Test3.blazor file use @inherits Test3Base syantax.

@inherits Test3Base
@page "/test3"

<h3>This is test3 page</h3>
<p>Message from C# Code Block: @msg</p>
<button @onclick="SayHello">Click Here</button>

MOQ-unit test demo in Asp.net Core 2.2


In my current project we extensively used MOQ object to create the unit test case for API call method. So in this sample demo example i will explain, what is the scenario to use moq object while writing the unit test case.

what is the moq object ?

>>A mock object is an object that can act as a real object but can be controlled in test code. Moq is a library that allows us to create mock objects in test code. It is also available in NuGet. This library also supports .NET Core

When to use moq object ?

>> We are writing the test case for some method which is using some functionality like After saving the data in database “sending sms or email functionality” should work. But sending sms or email method is the part of some other API service. If we are writing the test case for complete method and service is down for sending sms or email then every time our test case will fail. If that service is taking more time due to some network issue then test case might also fail.

In this scenario to avoid the chance of getting failure of test case, we will use moq object and set to return true. So that our test case will execute smoothly without any problem

The Moq library can be added to test projects using package manager like this

PM> Install-Package Moq

Step 1: create the asp.net core 2.2 application using visual studio 2019/2017 like this

Step 2: Create the repository Folder in solution explorer and add the EmployeeRepository.cs file

Step 3: Add the interface IGetDataRepository in that file as given below


namespace MOQ_Object_Demo.Repository
{
    public interface IGetDataRepository
    {
        string GetEmpAddressByEmpId(int empId);
    }
    public class EmployeeRepository : IGetDataRepository
    {
        public string GetEmpAddressByEmpId(int empId)
        {
            string empAddress = string.Empty;
            if (empId == 1)
            {
                empAddress = "Bangalore";
            }
            else if (empId == 2)
            {
                empAddress = "Pune";
            }
            else
            {
                empAddress = "Not Found";
            }
            return empAddress;
        }
    }
}

Step 4: Go to home controller of application and create the constructor to inject the interface as given below

using Microsoft.AspNetCore.Mvc;
using MOQ_Object_Demo.Models;
using MOQ_Object_Demo.Repository;
using System.Diagnostics;

namespace MOQ_Object_Demo.Controllers
{
    public class HomeController : Controller
    {
       private readonly IGetDataRepository _data;

        public HomeController(IGetDataRepository data)
        {
            _data = data;
        }

        public IActionResult Index()
        {
            ViewBag.address = GetAddressByEmpId(1);
            return View();
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }

        public string GetAddressByEmpId(int empId)
        {
            return _data.GetEmpAddressByEmpId(empId);
        }
    }
}

Step 5: Go to index view and write the code to display address as given below

@{
    ViewData["Title"] = "Home Page";
}

<div class="text-center">
    <h1 class="display-4">Welcome</h1>
    <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>

    <br />
    <p>I am from  @ViewBag.address</p>

</div>

Now our demo project is ready to display employee address, We have to write the test case for GetEmpAddressByEmpId(int empId) method. For this we have to create the Test Project.

Step 6: Create the Test project and add the Moq framework using Nuget package manager

Step 7: Write the test case using moq object as given below

using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using MOQ_Object_Demo.Controllers;
using MOQ_Object_Demo.Repository;

namespace UnitTestProject1
{
    [TestClass]
    public class EmpAddressTest
    {
        [TestMethod]
        public void Verify_EmployeeAddress_ByEmpId()
        {
            var mock = new Mock<IGetDataRepository>();

            mock.Setup(p => p.GetEmpAddressByEmpId(1)).Returns("Birganj");

            HomeController home = new HomeController(mock.Object);
            string result = home.GetAddressByEmpId(1);
            Assert.AreEqual("Birganj", result);
        }
    }
}

Explanation:
In the above test method we are creating the mock object of interface using moq framework and setting the value for method return whatever we want.

In the similar way we can set the value for any API and Service method. I have created very simple example to understand the concept of creating moq object and set the value for it.

What are the different type of Constructor in C# ?


Constructor is the special method of class that will be executed whenever we will create the object of that class.

Some points

1. Class can have any number of constructors
2. Constructor doesn’t have any return type.
3. In one class we can create one static constructor

Type of Constructor in C#

1. Default constructor
2. Static Constructor
3. Private Constructor
4. Copy Constructor
5. Parameterized constructor

Default constructor

A constructor without any parameter is called the default constructor. This type of constructor dosnot take any parameter.

Sample Code

class Test
    {
        int a, b;
         public Test()
        {
            a = 10;
            b = 60;
        }
        static void Main(string[] args)
        {
            Test obj = new Test();
            Console.WriteLine(obj.a);
            Console.WriteLine(obj.b);
            Console.Read();
        }
    }

Parameterized Constructor:

A constructor with at least one parameter is called a Parameterized constructor. The advantage of a Parameterized constructor is that you can initialize each instance of the class to different values.


 class Test
    {
        int a, b;
         public Test(int x, int y)
        {
            a = x;
            b = y;
        }
        static void Main(string[] args)
        {
            Test obj = new Test(20,30);
            Test obj1 = new Test(200, 300);
            Console.WriteLine(obj.a);
            Console.WriteLine(obj.b);
            Console.WriteLine(obj1.a);
            Console.WriteLine(obj1.b);
            Console.Read();
        }
    }

Copy Constructor :

The constructor which creates an object by copying variables from another object is called a copy constructor. The purpose of a copy constructor is to initialize a new instance to the values of an existing instance.

 class Test
    {
        private string Name;
        private string Address;
        public Test(Test objTest)
        {
            Name = objTest.Name;
            Address = objTest.Address;
        }

        public Test(string Name,string Address)
        {
            this.Name = Name;
            this.Address = Address;
        }
        public string Details
        {
            get
            {
                return "The address of " + Name + " Is " +Address.ToString();
            }
        }


        static void Main(string[] args)
        {
            Test obj = new Test("Chandradev","Bangalore");
            Test obj1 = new Test(obj);
            Console.WriteLine(obj1.Details);
            Console.Read();
        }
    }

Static Constructor:

A static constructor is used to initialize static fields of the class and to write the code that needs to be executed only once.

It will execute only once for all instances of class.

 class StaticTest
    {
        static StaticTest()
        {
            Console.WriteLine("This is the static constructor");
        }
        static void Main(string[] args)
        {
            StaticTest obj = new StaticTest();
            StaticTest obj1 = new StaticTest();
            Console.WriteLine("Hello World!");
            Console.Read();
        }
    }

Some points related with Static Constructors

1. A static constructor does not take access modifiers or have parameters.

2. A static constructor is called automatically to initialize the class before the first instance
is created or any static members are referenced.

3. A static constructor cannot be called directly.

4. The user has no control on when the static constructor is executed in the program.

5. A typical use of static constructors is when the class is using a log file and the constructor is
used to write entries to this file.

Private Constructor

>> Private constructor is used to avoid the inheritance of class and we cant create the instance of that class.
>> private constructor is a special instance constructor. It is generally used in classes that contain static members only. If a class has one or more private constructors and no public constructors, other classes (except nested classes) cannot create instances of this class.

public class StaticTest
    {
        static void Main(string[] args)
        {
            Counter.currentCount = 10;
            Counter.IncrementCount();
            Console.WriteLine("New count: {0}", Counter.currentCount);
            Console.Read();
        }
    }
    public class Counter
    {
        private Counter() { }
        public static int currentCount;
        public static int IncrementCount()
        {
            return ++currentCount;
        }
    }

Some key points of a private constructor are:

1. One use of a private constructor is when we have only static members.

2. It provides an implementation of a singleton class pattern

3. Many time we don’t want to create instance of certain classes like utility, logs or conman routine classes in this scenario we can use the private constructor.