Jenna 009

Jenna 009

1580466360

Building a Chat application with Angular 8, SignalR and ASP.NET Core

In this post, we are going to create a simple chat application using Angular 8, ASP.NET Core 2.2.0, and SignalR 1.1.0 as shown below.

Chat Application Using Angular 8, ASP.NET Core, Signal R

We need to install all the below-mentioned prerequisites on our development machine.

Prerequisite

  • .NET Core SDK 2.2.0 – download from here.
  • Node.js 10.15.3 – download from here.
  • Angular CLI 8.0 – Install Angular command package by executing this command: “npm install -g @angular/cli@8.0.0”

Set up ASP.NET Core with SignalR Project

Open the command prompt and enter the following command to create an ASP.NET Core web project as below.

Chat Application Using Angular 8, ASP.NET Core, Signal R

Install the following NuGet package in your project.

  • Microsoft.AspNetCore.SignalR
  • Microsoft.AspNetCore.SpaServices.Extensions

Chat Application Using Angular 8, ASP.NET Core, Signal R

Call SignalR in the “Startup.ConfigureServices” method to add SignalR services.

services.AddSignalR();

Create MessageHub Class

SignalR makes real-time client-to-server and server-to-client communications possible and it will call methods to connect clients from a server using SignalR Hub API. You can find more details about SignalR from here. Now, we need to perform the following steps to create the MessageHub class that is extending SignalR Hub API features.

  • Create Hubs Folder in the project
  • Declare MessageHub class that inherits from SignalR Hub
  • Add the NewMessage public method to get a new message from a connected client.
  • Then, Send an async message to all connected clients.
using ChatApp.Models;  
using Microsoft.AspNetCore.SignalR;  
using System.Threading.Tasks;  
  
namespace ChatApp.Hubs  
{  
    public class MessageHub : Hub  
    {  
        public async Task NewMessage(Message msg)  
        {  
            await Clients.All.SendAsync("MessageReceived", msg);  
        }  
    }  
}  

Then, add route to handle a request in Startup.ConfigureService method for MessageHub.

app.UseSignalR(options =>  
{  
      options.MapHub<MessageHub>("/MessageHub");  
 });  

Add a Message Class

public class Message  
   {  
       public string clientuniqueid { get; set; }  
       public string type { get; set; }  
       public string message { get; set; }  
       public DateTime date { get; set; }  
   }  

Add Angular 8 into the project

We will scaffold Angular into our project. For this, we need to execute “ng new ClientApp --skip-install” on Visual Studio Code terminal. Here, --skip-install option is used to skip installation of the npm packages.

Chat Application Using Angular 8, ASP.NET Core, Signal R

Now, let us enter the “npm install” command to install all Angular npm packages in the terminal. And then, update the SPA static file service configuration to the Angular output files folder location. For this, we will add the below code to the “Startup.Configure” method.

app.UseSpa(spa =>  
            {  
                // To learn more about options for serving an Angular SPA from ASP.NET Core,  
                // see https://go.microsoft.com/fwlink/?linkid=864501  
  
                spa.Options.SourcePath = "ClientApp";  
  
                if (env.IsDevelopment())  
                {  
                    //spa.UseProxyToSpaDevelopmentServer("http://localhost:4200");  
                    spa.UseAngularCliServer(npmScript: "start");  
                }  
            });  

Here, UseAngularCliServer will pass the request through to an instance of Angular CLI server which keeps up-to-date CLI-built resources without having to run the Angular CLI server manually.

Now, add SignalR client library to connect MessageHub from the Angular as below screenshot.

Chat Application Using Angular 8, ASP.NET Core, Signal R

Create Chat Service to connect SignalR

Create chat.service.ts class to establish a connection with Message Hub and to publish & receive chat messages.

Then, we have added chat service as a provider in Ng Modules.

import { EventEmitter, Injectable } from '@angular/core';  
import { HubConnection, HubConnectionBuilder } from '@aspnet/signalr';  
import { Message } from '../models/message';  
  
@Injectable()  
export class ChatService {  
  messageReceived = new EventEmitter<Message>();  
  connectionEstablished = new EventEmitter<Boolean>();  
  
  private connectionIsEstablished = false;  
  private _hubConnection: HubConnection;  
  
  constructor() {  
    this.createConnection();  
    this.registerOnServerEvents();  
    this.startConnection();  
  }  
  
  sendMessage(message: Message) {  
    this._hubConnection.invoke('NewMessage', message);  
  }  
  
  private createConnection() {  
    this._hubConnection = new HubConnectionBuilder()  
      .withUrl(window.location.href + 'MessageHub')  
      .build();  
  }  
  
  private startConnection(): void {  
    this._hubConnection  
      .start()  
      .then(() => {  
        this.connectionIsEstablished = true;  
        console.log('Hub connection started');  
        this.connectionEstablished.emit(true);  
      })  
      .catch(err => {  
        console.log('Error while establishing connection, retrying...');  
        setTimeout(function () { this.startConnection(); }, 5000);  
      });  
  }  
  
  private registerOnServerEvents(): void {  
    this._hubConnection.on('MessageReceived', (data: any) => {  
      this.messageReceived.emit(data);  
    });  
  }  
}    

Create a Chat App Component

app.component.html:

<div class="container">  
  <h3 class=" text-center chat_header">Chat Application</h3>  
  <div class="messaging">  
    <div class="inbox_msg">  
      <div class="mesgs">  
        <div class="msg_history">  
          <div *ngFor="let msg of messages">  
          <div class="incoming_msg" *ngIf="msg.type == 'received'">  
            <div class="incoming_msg_img"> </div>  
            <div class="received_msg">  
              <div class="received_withd_msg">  
                <p>  
                 {{msg.message}}   
                </p>  
                <span class="time_date"> {{msg.date | date:'medium'}} </span>  
              </div>  
            </div>  
          </div>  
          <div class="outgoing_msg" *ngIf="msg.type == 'sent'">  
            <div class="sent_msg">  
              <p>  
                  {{msg.message}}   
              </p>  
              <span class="time_date"> {{msg.date | date:'medium'}}</span>  
            </div>  
          </div>  
        </div>  
        </div>  
        <div class="type_msg">  
          <div class="input_msg_write">  
            <input type="text" class="write_msg" [value]="txtMessage"  
            (input)="txtMessage=$event.target.value" (keydown.enter)="sendMessage()" placeholder="Type a message" />  
            <button class="msg_send_btn" type="button"  (click)="sendMessage()"><i class="fa fa-paper-plane-o" aria-hidden="true"></i></button>  
          </div>  
        </div>  
      </div>  
    </div>  
  
  </div>  
</div>  

app.component.ts :

import { Component, NgZone } from '@angular/core';  
import { Message } from '../models/Message';  
import { ChatService } from '../services/chat.service';  
  
@Component({  
  selector: 'app-root',  
  templateUrl: './app.component.html',  
  styleUrls: ['./app.component.css']  
})  
export class AppComponent {  
  
  title = 'ClientApp';  
  txtMessage: string = '';  
  uniqueID: string = new Date().getTime().toString();  
  messages = new Array<Message>();  
  message = new Message();  
  constructor(  
    private chatService: ChatService,  
    private _ngZone: NgZone  
  ) {  
    this.subscribeToEvents();  
  }  
  sendMessage(): void {  
    if (this.txtMessage) {  
      this.message = new Message();  
      this.message.clientuniqueid = this.uniqueID;  
      this.message.type = "sent";  
      this.message.message = this.txtMessage;  
      this.message.date = new Date();  
      this.messages.push(this.message);  
      this.chatService.sendMessage(this.message);  
      this.txtMessage = '';  
    }  
  }  
  private subscribeToEvents(): void {  
  
    this.chatService.messageReceived.subscribe((message: Message) => {  
      this._ngZone.run(() => {  
        if (message.clientuniqueid !== this.uniqueID) {  
          message.type = "received";  
          this.messages.push(message);  
        }  
      });  
    });  
  }  
}  

Now, our chat application is ready. Let’s run the following command in terminal and test apps.

dotnet run  

Summary

In this article, we have learned how we can create a sample chat app using Angular 8 and ASP.NET Core with SignalR.

Please find the entire source code here as an attachment and also on GitHub.

Thanks!

#angular #angular8 #asp.net #signair

What is GEEK

Buddha Community

Building a Chat application with Angular 8, SignalR and ASP.NET Core

Me T

1581057842

Good

Build Chat Application at affordable price

Get a free quote: https://bit.ly/3biqmad

Einar  Hintz

Einar Hintz

1602560783

jQuery Ajax CRUD in ASP.NET Core MVC with Modal Popup

In this article, we’ll discuss how to use jQuery Ajax for ASP.NET Core MVC CRUD Operations using Bootstrap Modal. With jQuery Ajax, we can make HTTP request to controller action methods without reloading the entire page, like a single page application.

To demonstrate CRUD operations – insert, update, delete and retrieve, the project will be dealing with details of a normal bank transaction. GitHub repository for this demo project : https://bit.ly/33KTJAu.

Sub-topics discussed :

  • Form design for insert and update operation.
  • Display forms in modal popup dialog.
  • Form post using jQuery Ajax.
  • Implement MVC CRUD operations with jQuery Ajax.
  • Loading spinner in .NET Core MVC.
  • Prevent direct access to MVC action method.

Create ASP.NET Core MVC Project

In Visual Studio 2019, Go to File > New > Project (Ctrl + Shift + N).

From new project window, Select Asp.Net Core Web Application_._

Image showing how to create ASP.NET Core Web API project in Visual Studio.

Once you provide the project name and location. Select Web Application(Model-View-Controller) and uncheck HTTPS Configuration. Above steps will create a brand new ASP.NET Core MVC project.

Showing project template selection for .NET Core MVC.

Setup a Database

Let’s create a database for this application using Entity Framework Core. For that we’ve to install corresponding NuGet Packages. Right click on project from solution explorer, select Manage NuGet Packages_,_ From browse tab, install following 3 packages.

Showing list of NuGet Packages for Entity Framework Core

Now let’s define DB model class file – /Models/TransactionModel.cs.

public class TransactionModel
{
    [Key]
    public int TransactionId { get; set; }

    [Column(TypeName ="nvarchar(12)")]
    [DisplayName("Account Number")]
    [Required(ErrorMessage ="This Field is required.")]
    [MaxLength(12,ErrorMessage ="Maximum 12 characters only")]
    public string AccountNumber { get; set; }

    [Column(TypeName ="nvarchar(100)")]
    [DisplayName("Beneficiary Name")]
    [Required(ErrorMessage = "This Field is required.")]
    public string BeneficiaryName { get; set; }

    [Column(TypeName ="nvarchar(100)")]
    [DisplayName("Bank Name")]
    [Required(ErrorMessage = "This Field is required.")]
    public string BankName { get; set; }

    [Column(TypeName ="nvarchar(11)")]
    [DisplayName("SWIFT Code")]
    [Required(ErrorMessage = "This Field is required.")]
    [MaxLength(11)]
    public string SWIFTCode { get; set; }

    [DisplayName("Amount")]
    [Required(ErrorMessage = "This Field is required.")]
    public int Amount { get; set; }

    [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
    public DateTime Date { get; set; }
}

C#Copy

Here we’ve defined model properties for the transaction with proper validation. Now let’s define  DbContextclass for EF Core.

#asp.net core article #asp.net core #add loading spinner in asp.net core #asp.net core crud without reloading #asp.net core jquery ajax form #asp.net core modal dialog #asp.net core mvc crud using jquery ajax #asp.net core mvc with jquery and ajax #asp.net core popup window #bootstrap modal popup in asp.net core mvc. bootstrap modal popup in asp.net core #delete and viewall in asp.net core #jquery ajax - insert #jquery ajax form post #modal popup dialog in asp.net core #no direct access action method #update #validation in modal popup

Einar  Hintz

Einar Hintz

1602564619

MVC User Registration & Login with ASP.NET Core Identity

User registration and authentication are mandatory in any application when you have little concern about privacy. Hence all most all application development starts with an authentication module. In this article, we will discuss the quickest way to use **ASP.NET Core Identity for User Login and Registration **in a new or existing MVC application.

Sub-topics discussed :

  • How to add ASP.NET Core Identity to MVC application.
  • Customize ASP.NET Core Identity.
  • Identity.UI Design Customization.
  • Next step.

Background

ASP.NET Core Identity is an API, which provides both user interface(UI) and functions for user authentication, registration, authorization, etc. Modules/ APIs like this will really be helpful and fasten the development process. It comes with ASP.NET Core Framework and used in many applications before. Which makes the API more dependable and trustworthy.

ASP.NET Core MVC with user authentication can easily be accomplished using Identity.UI. While creating the MVC project, you just need to select Authentication as Individual User Accounts.

Showing how to create an MVC application with ASP.NET Core Identity API

The rest will be handled by ASP.NET Core Identity UI. It already contains razor view pages and backend codes for an authentication system. But that’s not what we want in most of the cases. we want to customize ASP.NET Core Identity as per our requirement. That’s what we do here.

Create an ASP.NET Core MVC Project

First of all, I will create a brand new ASP.NET Core MVC application without any authentication selected. We could add ASP.NET Core Identity later into the project.

In Visual Studio 2019, Go to File > New > Project (Ctrl + Shift + N). From new project window, select ASP.NET Core Web Application.

Create an ASP.NET Core Web application

Once you provide the project name and location. A new window will be opened as follows, Select _Web Application(Model-View-Controller), _uncheck _HTTPS Configuration _and DO NOT select any authentication method. Above steps will create a brand new ASP.NET Core MVC project.

Select Model View Controller templet under .NET Core

#asp.net core article #asp.net core #add asp.net core identity to existing project #asp.net core identity in mvc #asp.net core mvc login and registration #login and logout in asp.net core

Asp.Net Core MVC Bangla Tutorials - 53 (Complete eCommerce Application)

#Asp.net core #Asp.net core mvc #Core #Asp.net core tutotials #Asp.net core with entity framework

Asp.Net Core MVC Bangla Tutorials -08 (Complete eCommerce Application)

#Asp.net core #Asp.net core mvc #Core #Asp.net core tutorials #Asp.net core with entity framework

Asp.Net Core MVC Bangla Tutorials - 37 (Complete eCommerce Application)

#Asp.net core #Asp.net core mvc #Core #Asp.net core tutorials #Asp.net core with entity framework