Monday, June 26, 2023

Full Stack Web App using Angular 16, .NET Core Web API and Microsoft SQL Server

Please check out the below video to understand the tutorial much better.

In this tutorial, we will learn how to build a simple “To Do” application from scratch using

Angular 16 as the front end, .NET Core Web API as the backend, and Microsoft SQL server as the database.

Ø Install Node JS:

https://nodejs.org/en/download

Ø Install Angular CLI:

Use the below command to install angular CLI.

npm install -g @angular/cli



 

Ø  Install SQL Server Management Studio (SSMS) to interact with SQL Server.

https://learn.microsoft.com/en-us/sql/ssms/download-sql-server-management-studio-ssms?view=sql-server-ver16

 

Ø Install Visual Studio Community (Free for learning purpose only).

https://visualstudio.microsoft.com/vs/community/

 

Ø Create the database table and insert couple of records:







 

Ø Open Visual Studio and create the .NET Core Web API Project.



Ø Install Newtonsoft.Json Nuget package.



 

 

Ø Program.cs :

 

using Newtonsoft.Json.Serialization;

 

var builder = WebApplication.CreateBuilder(args);

 

// Add services to the container.

 

builder.Services.AddControllers();

// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle

builder.Services.AddEndpointsApiExplorer();

builder.Services.AddSwaggerGen();

 

//JSON Serializer

builder.Services.AddControllers().AddNewtonsoftJson(options=>

options.SerializerSettings.ReferenceLoopHandling=Newtonsoft.Json.ReferenceLoopHandling.Ignore).AddNewtonsoftJson(

    options=>options.SerializerSettings.ContractResolver=new DefaultContractResolver());

 

 

 

var app = builder.Build();

 

//Enable CORS

app.UseCors(c => c.AllowAnyHeader().AllowAnyOrigin().AllowAnyMethod());

 

// Configure the HTTP request pipeline.

if (app.Environment.IsDevelopment())

{

    app.UseSwagger();

    app.UseSwaggerUI();

}

 

app.UseAuthorization();

 

app.MapControllers();

 

app.Run();

 

 

Ø Add connection strings in appsetting.json:

 

{

  "ConnectionStrings": {

    "todoAppDBCon": "<<Your SQL Server Connection String here>>"

  },

  "Logging": {

    "LogLevel": {

      "Default": "Information",

      "Microsoft.AspNetCore": "Warning"

    }

  },

  "AllowedHosts": "*"

}

 

 

Ø Create a new Controller TodoAppController.cs:

 

using Microsoft.AspNetCore.Http;

using Microsoft.AspNetCore.Mvc;

using System.Data;

using System.Data.SqlClient;

using System.Security.AccessControl;

 

namespace WebApplication1.Controllers

{

    [Route("api/[controller]")]

    [ApiController]

    public class TodoAppController : ControllerBase

    {

        private IConfiguration _configuration ;

        public TodoAppController(IConfiguration configuration)

        {

            _configuration = configuration;

 

        }

 

        [HttpGet]

        [Route("GetNotes")]

        public JsonResult GetNotes()

        {

            string query = "select * from dbo.Notes";

            DataTable table = new DataTable();

            string sqlDatasource = _configuration.GetConnectionString("todoAppDBCon");

            SqlDataReader myReader;

            using(SqlConnection myCon=new SqlConnection(sqlDatasource))

            {

                myCon.Open();

                using(SqlCommand myCommand = new SqlCommand(query,myCon))

                {

                    myReader=myCommand.ExecuteReader();

                    table.Load(myReader);

                    myReader.Close();

                    myCon.Close();

                }

            }

 

            return new JsonResult(table);

        }

 

        [HttpPost]

        [Route("AddNotes")]

        public JsonResult AddNotes([FromForm] string newNotes)

        {

            string query = "insert into dbo.Notes values(@newNotes)";

            DataTable table = new DataTable();

            string sqlDatasource = _configuration.GetConnectionString("todoAppDBCon");

            SqlDataReader myReader;

            using (SqlConnection myCon = new SqlConnection(sqlDatasource))

            {

                myCon.Open();

                using (SqlCommand myCommand = new SqlCommand(query, myCon))

                {

                    myCommand.Parameters.AddWithValue("@newNotes", newNotes);

                    myReader = myCommand.ExecuteReader();

                    table.Load(myReader);

                    myReader.Close();

                    myCon.Close();

                }

            }

 

            return new JsonResult("Added Successfully");

        }

 

        [HttpDelete]

        [Route("DeleteNotes")]

        public JsonResult DeleteNotes(int id)

        {

            string query = "delete from dbo.Notes where id=@id";

            DataTable table = new DataTable();

            string sqlDatasource = _configuration.GetConnectionString("todoAppDBCon");

            SqlDataReader myReader;

            using (SqlConnection myCon = new SqlConnection(sqlDatasource))

            {

                myCon.Open();

                using (SqlCommand myCommand = new SqlCommand(query, myCon))

                {

                    myCommand.Parameters.AddWithValue("@id", id);

                    myReader = myCommand.ExecuteReader();

                    table.Load(myReader);

                    myReader.Close();

                    myCon.Close();

                }

            }

 

            return new JsonResult("Deleted Successfully");

        }

 

    }

}

 

 

Ø Create Angular Project:



 

Ø Changes in app.module.ts:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from './app.component';
import {HttpClientModule} from '@angular/common/http';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Ø Changes in app.component.ts:

 import { Component } from '@angular/core';

import {HttpClient} from '@angular/common/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'todoapp';
  readonly APIUrl="http://localhost:5038/api/todoapp/";

  constructor(private http:HttpClient){
  }
  notes:any=[];

  refreshNotes(){
    this.http.get(this.APIUrl+'GetNotes').subscribe(data=>{
      this.notes=data;
    })
  }

  ngOnInit(){
    this.refreshNotes();
  }

  addNotes(){
    var newNotes=(<HTMLInputElement>document.getElementById("newNotes")).value;
    var formData=new FormData();
    formData.append("newNotes",newNotes);
    this.http.post(this.APIUrl+'AddNotes',formData).subscribe(data=>{
      alert(data);
      this.refreshNotes();
    })
  }


   deleteNotes(id:any){
   
    this.http.delete(this.APIUrl+'DeleteNotes?id='+id).subscribe(data=>{
      alert(data);
      this.refreshNotes();
    })
  }
}

Ø Changes in app.component.html:

 <h2>Todo App</h2>

<input id="newNotes">
<button (click)="addNotes()">Add Notes</button>

<h3 *ngFor="let note of notes">
  <b>* {{note.description}}</b>
  <button (click)="deleteNotes(note.id)">Delete Notes</button>
</h3>

 

 

 

No comments:

Post a Comment

Full Stack Web App using Vue JS, .NET Core Web API and Microsoft SQL Server

 Please check out the below video to understand the tutorial much better.   In this tutorial, we will learn how to build a simple “To Do...