Skip to main content

.NET5 Blazor Server CRUD Operation Using Entity Framework Core

In this article, we are going to implement CRUD operations in .Net5 Blazor Server application.

Blazor Server:

Blazor Server is a single-page application. At the server, a pre-rendered HTML output of the page will be delivered to the user browsers. Any UI update, event handling, javascript calls will carry over by a SignalR connection to the server. So application updates or depends on the continuous connection of the SignalR.

So Blazor Server is a single-page application that will be made of c#. Since the blazor server only outputs the pre-rendered HTML to the client, so there is no c# code downloading into user browsers like in Blazor Webassembly(c# code downloaded and runs in browser for blazor webassembly application).

Role Of SignalR Connection:


A Blazor Server application works over a SignalR connection. A Blazor Server application creates a UI State memory at the server which will be interacted by the SignalR connections. If a SignalR connection got interrupted, then the client tries to maintain the same state of the application by initiating a new SignalR connection and uses the existing UI state memory at the server. App routing changes, event changes, data changes everything will be carried out by the SignalR connection without any page reloads.

Each browser screen or browser tab has its own SignalR connection channels and UI states at the application. So each browser screen or browser tab acts as an individual user request.

Blazor Components:

Blazor Server application built on top of the 'Blazor Components'. A blazor component file will be created like 'Example.razor', the file extension is '.razor'. A blazor component file consists of both c# and razor syntaxes. Blazor component also provides an option to split the files like 'Example.razor'(contains all razor code) and 'Example.razor.cs'(contains all c# code).

Create A .Net5 Blazor Server Application:

Let's start our learning journey by creating a .Net5 Blazor Server Application sample project.

Visual Studio users can easily create .Net5 Blazor Server Application. On creating application visual studio UI shows different application template options in that we have to select 'Blazor Server App'.

Here for this demo, I'm going to use Visual Studio Code editor and  .NET CLI commands. Run the below .NET CLI command to create Blazor Server App.
CLI Command To Blazor Server Application:
dotnet new blazorserver -n your_project_name
After creating an application, few things we need to aware of about the project:

Register RazorPages And Blazor Server Service- In the 'Startup.cs' file registered with 'AddRazorPages' and 'AddServerSideBlazor' services to gain dependency injection benefits.

Endpoint Routing Middleware - In the 'Starup.cs' file configured endpoint middleware with 'MapBlazorHub'(for SignalR routing) and 'MapFallbackToPage' (for Blazor Server routing).

Pages/_Host.cshtml - It is the entry file for any of our first requests to the server. It renders the default blazor component like 'App.razor'.

App.razor -  This is then the entry Blazor component. It contains a default blazor router component like 'Router'. The 'Router' component handles the user request and loads the appropriate Blazor Page components.

MainLayout.razor and NavMenu.razor - Default layout blazor component.

Pages Folder - Area to create blazor components

wwwroot Folder - Area to store all static files like js, css, images, etc.

Entity Framework Core:

Entity Framework Core is an Object/Relational Mapping(ORM) framework. EF Core makes database communication more fluent and easy. 
EF Core supports:
  • Database First Approach.
  • Code First Approach.
Code First Approach means first we will create c# POCO classes and then create the database tables. Code First Approach has one more sub-category like 'Code First With Existing Database'. So the 'Code First With Existing Database' can work with the already created tables in the database which is an ideal choice for real-time development. Our demo will be implemented using 'Code First With Existing Database'.

Install EF Core Nuget:

Now install ef core and SQL ef core extension Nuget package into our application.
Package Manager(Visual Studio):
Install-Package Microsoft.EntityFrameworkCore -Version 5.0.6
Install-Package Microsoft.EntityFrameworkCore.SqlServer -Version 5.0.6
CLI Commands(Visual Studio Code):
dotnet add package Microsoft.EntityFrameworkCore --version 5.0.6
dotnet add package Microsoft.EntityFrameworkCore.SqlServer --version 5.0.6

Sample SQL Script:

To follow the demo, run the SQL script to generate the table.
CREATE TABLE [dbo].[Gadgets](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[ProductName] [varchar](max) NULL,
	[Brand] [varchar](max) NULL,
	[Cost] [decimal](18, 0) NOT NULL,
	[ImageName] [varchar](1024) NULL,
	[Type] [varchar](128) NULL,
	[CreatedDate] [datetime] NULL,
	[ModifiedDate] [datetime] NULL,
PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

Setup Entity Framework Core DbContext:

First, let's create POCO class that represents our table. So let's create a new folder 'Entities' inside of the Data Folder, then inside of the 'Entities' folder creates our POCO class.
Data/Entities/Gadgets.cs:
namespace Dotnet5.BlazorServer.CRUD.EFCore.Data.Entities
{
    public class Gadgets
    {
        public int Id { get; set; }
        public string ProductName { get; set; }
        public string Brand { get; set; }
        public decimal Cost { get; set; }
        public string Type { get; set; }
    }
}
In EF Core DbContext is like a database that manages all POCO classes(classes represent tables). Inside the 'Data' folder create a context class.
Data/MyWorldDbContext.cs:
using Dotnet5.BlazorServer.CRUD.EFCore.Data.Entities;
using Microsoft.EntityFrameworkCore;

namespace Dotnet5.BlazorServer.CRUD.EFCore.Data
{
    public class MyWorldDbContext : DbContext
    {
        public MyWorldDbContext(DbContextOptions<MyWorldDbContext> options) : base(options)
        {

        }
        public DbSet<Gadgets> Gadgets { get; set; }
    }
}
Add database connection string into 'appsetting.Development.json'.
appsetings.Development.json:
"ConnectionStrings":{
    "MyWorldDbConnection":"your_connection"
}
Register 'MyWorlDbContext' into the dependency services.
services.AddDbContext<MyWorldDbContext>(options =>
{
	options.UseSqlServer(Configuration.GetConnectionString("MyWorldDbConnection"));
});

Read Operation:

First, let's register some namespaces into the '_Imports.razor' file.
_Imports.razor:
@using Dotnet5.BlazorServer.CRUD.EFCore.Data
@using Dotnet5.BlazorServer.CRUD.EFCore.Data.Entities
@using Microsoft.EntityFrameworkCore
For our demo, we will use the existing blazor page component that is 'Pages/Index.razor'. So let's start working on implementing 'Read Operation.
Pages/Index.razor:(HTML Part)
@page "/"
@inject MyWorldDbContext _myWorldDbContext;

<div>
    <table class="table table-bordered">
        <thead>
            <tr>
                <th scope="col">Id</th>
                <th scope="col">Product Name</th>
                <th scope="col">Brand</th>
                <th scope="col">Cost</th>
                <th scope="col">Type</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var item in AllGadgets)
            {
                <tr>
                    <th scope="row">@item.Id</th>
                    <td>@item.ProductName</td>
                    <td>@item.Brand</td>
                    <td>@item.Cost</td>
                    <td>@item.Type</td>
                </tr>
            }
        </tbody>
    </table>
</div>
  • (Line: 1) Routing to a blazor component should be defined using the '@page' directive.
  • (Line: 2) Injected our database context using the '@Inject' directive.
  • (Line: 16-25) The 'AllGadgets' is a c# property that contains a collection. Here binding the data to the bootstrap table.
Pages/Index.razor:(Code Part)
@code {

    public List<Gadgets> AllGadgets = new List<Gadgets>();
    protected override async Task OnInitializedAsync()
    {
        AllGadgets = await _myWorldDbContext.Gadgets.OrderByDescending(_ => _.Id).ToListAsync();
    }
}
  • (Line: 1) The entire c# code must be encapsulated inside of the '@code' directive.
  • (Line: 2)  Declared and initialized a collection property like 'AllGadgets'.
  • By default, it always recommended to use asynchronous calls to scale up the application. So for a method to we must use the 'async' keyword and output must be either 'Task' or 'Task<T>' and inside the method, every asynchronous job must be prefixed with the 'await' keyword.
  • (Line: 4-7) The 'OnInitializedAsync' is the default life cycle method of Blazor Server. Here fetching all data from the database and assigning to the 'AllGadgets' property.

Create Operation:

Bootstrap modal will be used for 'Create Operation'. So first let's add the Bootstrap 'js' and JQuery 'js' into the '_Host.cshtml'.
Pages/_Host.cshtml:(Above the closing body tag)
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin="anonymous"></script>
In Blazor c# code can invoke the javascript code that is called 'Blazor JavaScript Interoperability'. Now we have to write some javascript code to open and close the Bootstrap Modal. That javascript code will be called from the c# code in upcoming steps. So in 'wwwroot' folder add a new folder like 'js' and then add a new file like 'app.js'.
wwwroot/js/app.js:
window.global = {
  openModal: function (modalId) {
    modalId = "#" + modalId;
    $(modalId).modal("show");
  },
  closeModal: function (modalId) {
    modalId = "#" + modalId;
    $(modalId).modal("hide");
  },
};
  • Here written javascript code to open the bootstrap modal by its HTML id value.
Now, let's import our 'app.js' file onto the '_Host.cshtml' file.
Pages/_Host.csthml:
<script src="js/app.js"></script>
Now let's add our 'Create Operation' changes onto the 'Index.razor' component.
Index.razor:(HTML Part)
@page "/"
@inject MyWorldDbContext _myWorldDbContext;
@inject IJSRuntime _jsRuntime;
<!-- Some code hidden for display purpose -->
<button class="btn btn-primary" @onclick='@(e => CreateOrUpdateOpenModal(0))'>Add</button>
<div>
    <table class="table table-bordered">
        
    </table>
</div>


<div class="modal fade" id="createOrupdateModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">@CreateOrUpdateTitle</h5>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label for="txtProductName" class="form-label">Product Name</label>
                    <input @bind="FormPayload.ProductName" type="text" class="form-control" id="txtProductName">
                </div>
                <div class="mb-3">
                    <label for="txtBrand" class="form-label">Brand</label>
                    <input @bind="FormPayload.Brand" type="text" class="form-control" id="txtBrand">
                </div>
                <div class="mb-3">
                    <label for="txtCost" class="form-label">Cost</label>
                    <input @bind="FormPayload.Cost" type="text" class="form-control" id="txtCost">
                </div>
                <div class="mb-3">
                    <label for="txtType" class="form-label">Type</label>
                    <input @bind="FormPayload.Type" type="text" class="form-control" id="txtType">
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" @onclick='@(e => CloseModal("global.closeModal", "createOrupdateModal"))'
                    data-bs-dismiss="modal">Close</button>
                <button type="button" class="btn btn-success" @onclick="Save">Save</button>
            </div>
        </div>
    </div>
</div>
  • (Line: 3) Injected 'IJSRuntime' that helps to invoke the javascript code from the c# code.
  • (Line: 5) Created 'Add' button. Here button registered with c# method to  'onclick' event. To use c# method that has parameters we need to call like delegate(eg: e => method_name(param1)) in the HTML.
  • (Line: 13-44) Add the Bootstrap Modal Html. Our Bootstrap Modal popup furnished with all HTML input fields for creating a new record. To achieve a 2-way binding input HTML field must be decorated with the '@bind' directive.
  • (Line: 17) Rendering popup title dynamically using the property 'CreateOrUpdateTitle'. So that same popup can be used for Edit operation as well in the coming steps.
  • (Line: 38-39) Added the popup close button and its click event registered with a method like 'CloseModal'.
  • (Line: 40) Added the popup save button and its click event registered with a method like 'Save'.
Pages/Index.razor:(Code Part)
@code {

    public List<Gadgets> AllGadgets = new List<Gadgets>();

    public Gadgets FormPayload = new Gadgets();
    public string CreateOrUpdateTitle = string.Empty;
    protected override async Task OnInitializedAsync()
    {
        AllGadgets = await _myWorldDbContext.Gadgets.OrderByDescending(_ => _.Id).ToListAsync();
    }

    public async Task CreateOrUpdateOpenModal(int gadgetId)
    {
        if (gadgetId == 0)
        {
            CreateOrUpdateTitle = "Create A Gadget";
            FormPayload = new Gadgets();
            await _jsRuntime.InvokeVoidAsync("global.openModal", "createOrupdateModal");
        }
    }

    public async Task CloseModal(string jsMethodName, string popupHtmlId)
    {
        await _jsRuntime.InvokeVoidAsync(jsMethodName, popupHtmlId);
    }

    public async Task Save()
    {
        if (FormPayload.Id == 0)
        {
            _myWorldDbContext.Gadgets.Add(FormPayload);
            await _myWorldDbContext.SaveChangesAsync();
        }
        AllGadgets.Insert(0, FormPayload);
        await CloseModal("global.closeModal", "createOrupdateModal");
    }
}
  • (Line: 5) Added property 'FormPayload' of type 'Gadgets'. This 'FormPayload' property will be utilized by the input fields of our Bootstrap Modal for 2-way binding.
  • (Line: 6) Added the property 'CreateOrUpdateTitle' to dynamically add the title to Bootstrap Modal.
  • (Line: 12-20) Method to open the bootstrap modal on clicking the 'Add' button.
  • (Line: 16) Defining the title for our bootstrap modal.
  • (Line: 17) Since it creates a new record, so will assign an empty memory to our 'FormPayload' property.
  • (Line: 18) Using 'JSRuntime' invoking the javascript method. So for the method 'InvokeVoidAsync', the first parameter will be the javascript function name and the second parameter will be the input parameters array for the javascript method.
  • (Line: 22-25) Method to close the bootstrap modal. Here it was written in a generic way so any number of popups can use this method as a close event.
  • (Line: 27-36) The 'Save' method used to create new records into the database.
  • (Line: 29) Checking the 'Id' value because 'Save' method we will use for both 'Create' and 'Update' operations. If the 'Id' value is '0' then it is a 'Create' operation.
  • (Line: 31-32) Saving the new record into the database.
  • (Line: 34) Added the newly created or update record into the 'AllGadgets' collection. So our table gets updated with newly created or updated data.
  • (Line: 35) Finally closing the modal.
step1:

step2:

step3:

Update Operation:

Now let's implement our logic to fulfill our 'Update Operation'.
Pages/Index.razor:(HTML Part)
<!-- Code hidden for display purpose -->
<div>
    <table class="table table-bordered">
        <thead>
            <tr>
                <th scope="col">Actions</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var item in AllGadgets)
            {
                <tr>
                    <td>
                        <button class="btn btn-primary" @onclick='@(e => CreateOrUpdateOpenModal(item.Id))'>Edit</button>
                    </td>
                </tr>
            }
        </tbody>
    </table>
</div>
  • (Line: 6) Created a new table column like 'Actions'.
  • (Line: 14) Added the edit button for each record in the table. So here we will use the same methods that are used in 'Create Operation'.
Pages/Index.razor:(Code Part)
@code {

    public List<Gadgets> AllGadgets = new List<Gadgets>();

    public Gadgets FormPayload = new Gadgets();
    public string CreateOrUpdateTitle = string.Empty;
    protected override async Task OnInitializedAsync()
    {
        AllGadgets = await _myWorldDbContext.Gadgets.OrderByDescending(_ => _.Id).ToListAsync();
    }

    public async Task CreateOrUpdateOpenModal(int gadgetId)
    {
        if (gadgetId == 0)
        {
            CreateOrUpdateTitle = "Create A Gadget";
            FormPayload = new Gadgets();
        }
        else
        {
            CreateOrUpdateTitle = "Update The Gadget";
            FormPayload = await _myWorldDbContext.Gadgets.Where(_ => _.Id == gadgetId).FirstOrDefaultAsync();
        }
        await _jsRuntime.InvokeVoidAsync("global.openModal", "createOrupdateModal");
    }

    public async Task CloseModal(string jsMethodName, string popupHtmlId)
    {
        await _jsRuntime.InvokeVoidAsync(jsMethodName, popupHtmlId);
    }

    public async Task Save()
    {
        if (FormPayload.Id == 0)
        {
            _myWorldDbContext.Gadgets.Add(FormPayload);
            await _myWorldDbContext.SaveChangesAsync();
        }
        else
        {
            _myWorldDbContext.Update(FormPayload);
            await _myWorldDbContext.SaveChangesAsync();
            AllGadgets = AllGadgets.Where(_ => _.Id != FormPayload.Id).ToList();
        }
        AllGadgets.Insert(0, FormPayload);
        await CloseModal("global.closeModal", "createOrupdateModal");
    }
}
  • (Line: 21-22) Updating the 'CreateOrUpdateTitle' property as per the operation type. Updating the 'FormPayload' with data fetched from the database with help of the 'gadgetId' value.
  • (Line: 41-42) Updating the Dbcontext with our record to be updated.
  • (Line: 43) Remove the record that is updated from the old collection 'AllGadgets'.
step1:

step2:

step3:

Delete Operation:

Now let's implement our logic for 'Delete Operation'.
Pages/Index.razor:(HTML Part)
<!-- Some code hidden for display purpose -->
<div>
    <table class="table table-bordered">
        
        <tbody>
            @foreach (var item in AllGadgets)
            {
                <tr>
                    <td>
                        <button class="btn btn-primary" @onclick='@(e => CreateOrUpdateOpenModal(item.Id))'>Edit</button> |
                        <button class="btn btn-danger"
                        @onclick='@(e => OpenDeleteConfrimationModal(item.Id))'>Delete</button>
                    </td>
                </tr>
            }
        </tbody>
    </table>
</div>

<div class="modal fade" id="deleteGadgetModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">

            <div class="modal-body">
                <h4>Are you sure, you want to delete?</h4>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary"
                    @onclick='@(e => CloseModal("global.closeModal", "deleteGadgetModal"))'
                    data-bs-dismiss="modal">Close</button>
                <button type="button" class="btn btn-danger" @onclick='ConfirmDelete'>Confirm Delete</button>
            </div>
        </div>
    </div>
</div>
  • (Line: 11-12) Add the new button like 'Delete'. Click event registered with method 'OpenDeleteConfirmationModal'.
  • (Line: 20-35) Add a new bootstrap modal for the delete confirmation.
  • (Line: 31) Delete button added and registered with 'ConfirmDelete' method.
Pages/Index.razor:(Code Part)
@code {

    public List<Gadgets> AllGadgets = new List<Gadgets>();

    public Gadgets FormPayload = new Gadgets();
    public string CreateOrUpdateTitle = string.Empty;

    public int GadgetIdToRemove = 0;
    protected override async Task OnInitializedAsync()
    {
        AllGadgets = await _myWorldDbContext.Gadgets.OrderByDescending(_ => _.Id).ToListAsync();
    }

    public async Task CreateOrUpdateOpenModal(int gadgetId)
    {
        if (gadgetId == 0)
        {
            CreateOrUpdateTitle = "Create A Gadget";
            FormPayload = new Gadgets();
        }
        else
        {
            CreateOrUpdateTitle = "Update The Gadget";
            FormPayload = await _myWorldDbContext.Gadgets.Where(_ => _.Id == gadgetId).FirstOrDefaultAsync();
        }
        await _jsRuntime.InvokeVoidAsync("global.openModal", "createOrupdateModal");
    }

    public async Task CloseModal(string jsMethodName, string popupHtmlId)
    {
        await _jsRuntime.InvokeVoidAsync(jsMethodName, popupHtmlId);
    }

    public async Task Save()
    {
        if (FormPayload.Id == 0)
        {
            _myWorldDbContext.Gadgets.Add(FormPayload);
            await _myWorldDbContext.SaveChangesAsync();
        }
        else
        {
            _myWorldDbContext.Update(FormPayload);
            await _myWorldDbContext.SaveChangesAsync();
            AllGadgets = AllGadgets.Where(_ => _.Id != FormPayload.Id).ToList();
        }
        AllGadgets.Insert(0, FormPayload);
        await CloseModal("global.closeModal", "createOrupdateModal");
    }

    public async Task OpenDeleteConfrimationModal(int gadgetId)
    {
        GadgetIdToRemove = gadgetId;
        await _jsRuntime.InvokeVoidAsync("global.openModal", "deleteGadgetModal");
    }

    public async Task ConfirmDelete()
    {
        var gadtetToDelete = await _myWorldDbContext.Gadgets.Where(_ => _.Id == GadgetIdToRemove).FirstOrDefaultAsync();
        _myWorldDbContext.Gadgets.Remove(gadtetToDelete);
        await _myWorldDbContext.SaveChangesAsync();
         AllGadgets = AllGadgets.Where(_ => _.Id != GadgetIdToRemove).ToList();
        await CloseModal("global.closeModal", "deleteGadgetModal");
    }
}
  • (Line: 8) Added variable 'GadgetIdToRemove' to store the 'Id' value of the record that needs to be deleted.
  • (Line: 51-55) Opens the delete confirmation popup.
  • (Line: 57-64) The 'ConfirmDelete' method to delete the record from the database.
So that's all about the CRUD operation in .Net5 Blazor Server application.

Video Session:

Support Me!
Buy Me A Coffee PayPal Me

Wrapping Up:

Hopefully, I think this article delivered some useful information on .Net5 Blazor Server CRUD operation with the entity framework. I love to have your feedback, suggestions, and better techniques in the comment section below.

Refer:

Follow Me:

Comments

  1. don't you think it might be good somehow to allow "printing" ?
    I just can't do that because of the "trimmed " source code in those magic code boxes
    which inhibit seeing the full lenght of the code lines

    ReplyDelete

Post a Comment

Popular posts from this blog

.NET6 Web API CRUD Operation With Entity Framework Core

In this article, we are going to do a small demo on AspNetCore 6 Web API CRUD operations. What Is Web API: Web API is a framework for building HTTP services that can be accessed from any client like browser, mobile devices, desktop apps. In simple terminology API(Application Programming Interface) means an interface module that contains a programming function that can be requested via HTTP calls to save or fetch the data for their respective clients. Some of the key characteristics of API: Supports HTTP verbs like 'GET', 'POST', 'PUT', 'DELETE', etc. Supports default responses like 'XML' and 'JSON'. Also can define custom responses. Supports self-hosting or individual hosting, so that all different kinds of apps can consume it. Authentication and Authorization are easy to implement. The ideal platform to build REST full services. Create A .NET6 Web API Application: Let's create a .Net6 Web API sample application to accomplish our

Usage Of CancellationToken In Asp.Net Core Applications

When To Use CancellationToken?: In a web application request abortion or orphan, requests are quite common. On users disconnected by network interruption or navigating between multiple pages before proper response or closing of the browser, tabs make the request aborted or orphan. An orphan request can't deliver a response to the client, but it will execute all steps(like database calls, HTTP calls, etc) at the server. Complete execution of an orphan request at the server might not be a problem generally if at all requests need to work on time taking a job at the server in those cases might be nice to terminate the execution immediately. So CancellationToken can be used to terminate a request execution at the server immediately once the request is aborted or orphan. Here we are going to see some sample code snippets about implementing a CancellationToken for Entity FrameworkCore, Dapper ORM, and HttpClient calls in Asp.NetCore MVC application. Note: The sample codes I will show in

A Small Guide On NestJS Queues

NestJS Application Queues helps to deal with application scaling and performance challenges. When To Use Queues?: API request that mostly involves in time taking operations like CPU bound operation, doing them synchronously which will result in thread blocking. So to avoid these issues, it is an appropriate way to make the CPU-bound operation separate background job.  In nestjs one of the best solutions for these kinds of tasks is to implement the Queues. For queueing mechanism in the nestjs application most recommended library is '@nestjs/bull'(Bull is nodejs queue library). The 'Bull' depends on Redis cache for data storage like a job. So in this queueing technique, we will create services like 'Producer' and 'Consumer'. The 'Producer' is used to push our jobs into the Redis stores. The consumer will read those jobs(eg: CPU Bound Operations) and process them. So by using this queues technique user requests processed very fastly because actually

Blazor WebAssembly Custom Authentication From Scratch

In this article, we are going to explore and implement custom authentication from the scratch. In this sample, we will use JWT authentication for user authentication. Main Building Blocks Of Blazor WebAssembly Authentication: The core concepts of blazor webassembly authentication are: AuthenticationStateProvider Service AuthorizeView Component Task<AuthenticationState> Cascading Property CascadingAuthenticationState Component AuthorizeRouteView Component AuthenticationStateProvider Service - this provider holds the authentication information about the login user. The 'GetAuthenticationStateAsync()' method in the Authentication state provider returns user AuthenticationState. The 'NotifyAuthenticationStateChaged()' to notify the latest user information within the components which using this AuthenticationStateProvider. AuthorizeView Component - displays different content depending on the user authorization state. This component uses the AuthenticationStateProvider

How Response Caching Works In Asp.Net Core

What Is Response Caching?: Response Caching means storing of response output and using stored response until it's under it's the expiration time. Response Caching approach cuts down some requests to the server and also reduces some workload on the server. Response Caching Headers: Response Caching carried out by the few Http based headers information between client and server. Main Response Caching Headers are like below Cache-Control Pragma Vary Cache-Control Header: Cache-Control header is the main header type for the response caching. Cache-Control will be decorated with the following directives. public - this directive indicates any cache may store the response. private - this directive allows to store response with respect to a single user and can't be stored with shared cache stores. max-age - this directive represents a time to hold a response in the cache. no-cache - this directive represents no storing of response and always fetch the fr

Part-1 Angular JWT Authentication Using HTTP Only Cookie[Angular V13]

In this article, we are going to implement a sample angular application authentication using HTTP only cookie that contains a JWT token. HTTP Only JWT Cookie: In a SPA(Single Page Application) Authentication JWT token either can be stored in browser 'LocalStorage' or in 'Cookie'. Storing JWT token inside of the cookie then the cookie should be HTTP Only. The HTTP-Only cookie nature is that it will be only accessible by the server application. Client apps like javascript-based apps can't access the HTTP-Only cookie. So if we use authentication with HTTP only JWT cookie then we no need to implement custom logic like adding authorization header or storing token data, etc at our client application. Because once the user authenticated cookie will be automatically sent to the server by the browser on every API call. Authentication API: To implement JWT cookie authentication we need to set up an API. For that, I had created a mock authentication API(Using the NestJS Se

Unit Testing Asp.NetCore Web API Using xUnit[.NET6]

In this article, we are going to write test cases to an Asp.NetCore Web API(.NET6) application using the xUnit. xUnit For .NET: The xUnit for .Net is a free, open-source, community-focused unit testing tool for .NET applications. By default .Net also provides a xUnit project template to implement test cases. Unit test cases build upon the 'AAA' formula that means 'Arrange', 'Act' and 'Assert' Arrange - Declaring variables, objects, instantiating mocks, etc. Act - Calling or invoking the method that needs to be tested. Assert - The assert ensures that code behaves as expected means yielding expected output. Create An API And Unit Test Projects: Let's create a .Net6 Web API and xUnit sample applications to accomplish our demo. We can use either Visual Studio 2022 or Visual Studio Code(using .NET CLI commands) to create any.Net6 application. For this demo, I'm using the 'Visual Studio Code'(using the .NET CLI command) editor. Create a fo

Different HttpClient Techniques To Consume API Calls In Minimal API[.NET6]

In this article, we are going to implement different HttpClient techniques to consume API calls in minimal API. The different HttpClient techniques that we are going to explore are like: Register HttpClient Object Explicitly In DI(Dependency Injection Service) Named Client Type Client HttpRequestMessage Object Create A .NET6 Minimal API Project: Let's create a .Net6 Minimal API sample project to accomplish our demo. We can use either Visual Studio 2022 or Visual Studio Code(using .NET CLI commands) to create any.Net6 application. For this demo, I'm using the 'Visual Studio Code'(using the .NET CLI command) editor. CLI command For Minimal API Project dotnet new webapi -minimal -o Your_Project_Name Create A Third Party API Response Model: Here I'm going to use a free third-party rest API that is "https://jsonplaceholder.typicode.com/posts". So to receive the response let's create a response model like 'Post.cs'. Program.cs:(Add Post.cs c

.Net5 Web API Managing Files Using Azure Blob Storage

In this article, we are going to understand the different file operations like uploading, reading, downloading, and deleting in .Net5 Web API application using Azure Blob Storage. Azure Blob Storage: Azure blob storage is Microsoft cloud storage. Blob storage can store a massive amount of file data as unstructured data. The unstructured data means not belong to any specific type, which means text or binary data. So something like images or pdf or videos to store in the cloud, then the most recommended is to use the blob store. The key component to creating azure blob storage resource: Storage Account:- A Storage account gives a unique namespace in Azure for all the data we will save. Every object that we store in Azure Storage has an address. The address is nothing but the unique name of our Storage Account name. The combination of the account name and the Azure Storage blob endpoint forms the base address for each object in our Storage account. For example, if our Storage Account is n

.Net5 Web API Redis Cache Using StackExchange.Redis.Extensions.AspNetCore Library

In this article, we are going to explore the integration of Redis cache in .Net5 Web API application using the 'StackExchange.Redis.Exntensions' library. Note:- Microsoft has introduced an 'IDistributedCache' interface in dotnet core which supports different cache stores like In-Memory, Redis, NCache, etc. It is simple and easy to work with  'IDistributedCache', for the Redis store with limited features but if we want more features of the Redis store we can choose to use 'StackExchange.Redis.Extensions'.  Click here for Redis Cache Integration Using IDistributedCache Interface . Overview On StackExchange.Redis.Extnesions Library: The 'StackExchange.Redis.Extension' library extended from the main library 'StackExchange.Redis'. Some of the key features of this library like: Default serialization and deserialization. Easy to save and fetch complex objects. Search key. Multiple Database Access Setup Redis Docker Instance: For this sampl