Wednesday, June 28, 2023

Full Stack Web App using React 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” application from scratch using

React JS 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 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 React JS Project using below command:



Ø Modify App.js:

 import logo from './logo.svg';

import './App.css';
import { Component } from 'react';
class App extends Component{

constructor(props){
    super(props);
    this.state={
      notes:[]
    }
}

API_URL="http://localhost:5038/";

componentDidMount(){
  this.refreshNotes();
}

async refreshNotes(){
  fetch(this.API_URL+"api/todoapp/GetNotes").then(response=>response.json())
  .then(data=>{
    this.setState({notes:data});
  })
}

async addClick(){
  var newNotes=document.getElementById("newNotes").value;
  const data=new FormData();
  data.append("newNotes",newNotes);

  fetch(this.API_URL+"api/todoapp/AddNotes",{
    method:"POST",
    body:data
  }).then(res=>res.json())
  .then((result)=>{
    alert(result);
    this.refreshNotes();
  })
}

async deleteClick(id){
  fetch(this.API_URL+"api/todoapp/DeleteNotes?id="+id,{
    method:"DELETE",
  }).then(res=>res.json())
  .then((result)=>{
    alert(result);
    this.refreshNotes();
  })
}
render() {
  const{notes}=this.state;
  return (
    <div className="App">
     <h2>Todo App</h2>
      <input id="newNotes"/>&nbsp;
      <button onClick={()=>this.addClick()}>Add Notes</button>
     {notes.map(note=>
      <p>
        <b>* {note.description}</b>&nbsp;
        <button onClick={()=>this.deleteClick(note.id)}>Delete Notes</button>
      </p>
      )}
    </div>
  );
}
}


export default App;

Ø Use Below command to run the react project:



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...