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

Angular 14 Reactive Forms Example

In this article, we will explore the Angular(14) reactive forms with an example. Reactive Forms: Angular reactive forms support model-driven techniques to handle the form's input values. The reactive forms state is immutable, any form filed change creates a new state for the form. Reactive forms are built around observable streams, where form inputs and values are provided as streams of input values, which can be accessed synchronously. Some key notations that involve in reactive forms are like: FormControl - each input element in the form is 'FormControl'. The 'FormControl' tracks the value and validation status of form fields. FormGroup - Track the value and validate the state of the group of 'FormControl'. FormBuilder - Angular service which can be used to create the 'FormGroup' or FormControl instance quickly. Form Array - That can hold infinite form control, this helps to create dynamic forms. Create An Angular(14) Application: Let'

.NET 7 Web API CRUD Using Entity Framework Core

In this article, we are going to implement a sample .NET 7 Web API CRUD using the Entity Framework Core. Web API: Web API is a framework for building HTTP services that can be accessed from any client like browser, mobile devices, and desktop apps. In simple terminology API(Application Programming Interface) means an interface module that contains programming functions that can be requested via HTTP calls either to fetch or update 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 the REST full services. Install The SQL Server And SQL Management Studio: Let's install the SQL server on our l

ReactJS(v18) JWT Authentication Using HTTP Only Cookie

In this article, we will implement the ReactJS application authentication using the HTTP-only cookie. HTTP Only Cookie: In a SPA(Single Page Application) Authentication JWT token either can be stored in browser 'LocalStorage' or in 'Cookie'. Storing the 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 the authentication with HTTP-only JWT cookie then we no need to implement the 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 authenticate our client application with JWT HTTP-only cookie, I developed a NetJS(which is a node) Mock API. Check the GitHub link and read the document on G

.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

Angular 14 State Management CRUD Example With NgRx(14)

In this article, we are going to implement the Angular(14) state management CRUD example with NgRx(14) NgRx Store For State Management: In an angular application to share consistent data between multiple components, we use NgRx state management. Using NgRx state helps to avoid unwanted API calls, easy to maintain consistent data, etc. The main building blocks for the NgRx store are: Actions - NgRx actions represents event to trigger the reducers to save the data into the stores. Reducer - Reducer's pure function, which is used to create a new state on data change. Store - The store is the model or entity that holds the data. Selector - Selector to fetch the slices of data from the store to angular components. Effects - Effects deals with external network calls like API. The effect gets executed based the action performed Ngrx State Management flow: The angular component needs data for binding.  So angular component calls an action that is responsible for invoking the API call.  Aft

Angular 14 Crud Example

In this article, we will implement CRUD operation in the Angular 14 application. Angular: Angular is a framework that can be used to build a single-page application. Angular applications are built with components that make our code simple and clean. Angular components compose of 3 files like TypeScript File(*.ts), Html File(*.html), CSS File(*.cs) Components typescript file and HTML file support 2-way binding which means data flow is bi-directional Component typescript file listens for all HTML events from the HTML file. Create Angular(14) Application: Let's create an Angular(14) application to begin our sample. Make sure to install the Angular CLI tool into our local machine because it provides easy CLI commands to play with the angular application. Command To Install Angular CLI npm install -g @angular/cli Run the below command to create the angular application. Command To Create Angular Application ng new name_of_your_app Note: While creating the app, you will see a noti

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

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

ReactJS(v18) Authentication With JWT AccessToken And Refresh Token

In this article, we are going to do ReactJS(v18) application authentication using the JWT Access Token and Refresh Token. JSON Web Token(JWT): JSON Web Token is a digitally signed and secured token for user validation. The JWT is constructed with 3 important parts: Header Payload Signature Create ReactJS Application: Let's create a ReactJS application to accomplish our demo. npx create-react-app name-of-your-app Configure React Bootstrap Library: Let's install the React Bootstrap library npm install react-bootstrap bootstrap Now add the bootstrap CSS reference in 'index.js'. src/index.js: import 'bootstrap/dist/css/bootstrap.min.css' Create A React Component 'Layout': Let's add a React component like 'Layout' in 'components/shared' folders(new folders). src/components/shared/Layout.js: import Navbar from "react-bootstrap/Navbar"; import { Container } from "react-bootstrap"; import Nav from "react-boot

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