Subscribe Us

LightBlog
Showing posts with label Web API. Show all posts
Showing posts with label Web API. Show all posts

Saturday, 1 May 2021

May 01, 2021

CRUD Operation in Asp.Net Core Web API with Swagger

Introduction

In this article, I explain how to integrate our API with the swagger and execute our web API using swagger, In this article, I explain CRUD operation with a Repository pattern in .net Core Web API.

Step 1: Create new Web API with using .Net cores

Step 2: Now install the package of swagger

Open your NuGet package manager console and write below command into it.

Install-Package Swashbuckle

if you need more details about this package please click here (https://www.nuget.org/packages/Swashbuckle/)

Step 3: Register the swagger generator

now open the startup.cs file and go to ConfigureServices, add below code into it.

services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Version = "v1",
                    Title = "Employee API",
                    Description = "A simple example ASP.NET Core Web API",
                    TermsOfService = new Uri("https://example.com/terms"),
                    Contact = new OpenApiContact
                    {
                        Name = "abc",
                        Email = "abc@gmail.com",
                    }                    
                });
            });

now go to the Configure in the same file and Enable middleware to serve generated Swagger as a JSON endpoint, paste the below code into it.

// Enable middleware to serve generated Swagger as a JSON endpoint.
           app.UseSwagger();
           // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
           // specifying the Swagger JSON endpoint.
           app.UseSwaggerUI(c =>
           {
               c.SwaggerEndpoint("/swagger/v1/swagger.json", "Employee.API V1");
               c.RoutePrefix = string.Empty;
           });
now build your web API and run it.

Step 4: Create a folder name is “Models” in your web API, right-click on the models and create a new class for the model.
make a model like given below code.

using System.ComponentModel.DataAnnotations;
namespace SwaggerDemoWebAPI.Models
{
    public class MEmployee
    {
        [Key]
        public int EmpID { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public string Phone { get; set; }
        public string Gender { get; set; }
        public string Password { get; set; }
    }
}
Step 5: Create a folder name is “Data” in your web API, right-click on the data and create a new class for the DB context.

now add the DB set in the DB context like give below code.

using Microsoft.EntityFrameworkCore;
using SwaggerDemoWebAPI.Models;
namespace Employee.API
{
    public class DBContext : DbContext
    {
        public DBContext(DbContextOptions<DBContext> options) : base(options) { }
        public DbSet<MEmployee> Emp { get; set; }
    }
}
Step 6: Make the connection
now open the appsettings.json file and add the connection string like given below code.

{
  "ConnectionStrings": {
    "IdentityConnection": "Data Source=abc\\SQLEXPRESS01;Initial Catalog=Employee;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"
  },
  "CatalogBaseUrl": "",
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning",
      "Microsoft": "Warning",
      "System": "Warning"
    }
  }
}
Now we need to configure the connection string so please open the startups.cs file and go to the configure services, paste below line at the first

// Add Identity DbContext
 services.AddDbContext<DBContext>(options =>options.UseSqlServer(Configuration.GetConnectionString("IdentityConnection")));
make sure your connection string name same in both file (appsettings.json & startup.cs)

Step 7: Add repository in our web API project, so you need to create a new folder Repository in your Web API project

In the repository create one interface like “IEmployeeRepository” please write the name of your register starting with I if that is interface then, copy below code and paste into your interface.

using SwaggerDemoWebAPI.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace SwaggerDemoWebAPI.Repository
{
   public interface IEmployeeRepository
    {
        void Create(MEmployee item);
        MEmployee GetById(int Id);
        List<MEmployee> GetAll();
        void Update(int id,MEmployee item);
        void Delete(int Id);
    }
}
now add the one class for the employee repository, copy below code into your employee repository

using System.Collections.Generic;
using System.Linq;
using Employee.API;
using SwaggerDemoWebAPI.Models;
namespace SwaggerDemoWebAPI.Repository
{
    public class EmployeeRepository : IEmployeeRepository
    {
        private readonly DBContext _context;
        public EmployeeRepository(DBContext context)
        {
            _context = context;
        }
        public void Create(MEmployee item)
        {
            _context.Emp.Add(item);
            _context.SaveChanges();
        }
        public MEmployee GetById(int Id)
        {
            return _context.Emp.FirstOrDefault(t => t.EmpID == Id);
        }
        public List<MEmployee> GetAll()
        {
            return _context.Emp.ToList();
        }
        public void Update(int id,MEmployee item)
        {
            var entity = _context.Emp.Find(id);
            if (entity == null)
            {
                return;
            }
            _context.Entry(entity).CurrentValues.SetValues(item);
            _context.SaveChanges();
        }
        public void Delete(int id)
        {
            var entity = _context.Emp.Find(id);
            if (entity == null)
            {
                return;
            }
            _context.Emp.Remove(entity);
            _context.SaveChanges();
        }
    }
}
Step 8: Create Employee API, now you need to create a controller in your web API controller folder, copy below code and paste into your controller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SwaggerDemoWebAPI.Models;
using SwaggerDemoWebAPI.Repository;
namespace SwaggerDemoWebAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class EmployeeController : ControllerBase
    {
        public EmployeeController(IEmployeeRepository emp)
        {
            _Emp = emp;
        }
        public IEmployeeRepository _Emp { get; set; }
        [HttpPost]
        public void Post([FromBody] MEmployee modal)
        {
            _Emp.Create(modal);
        }
        [HttpGet("{id}")]
        public IActionResult Get(int id)
        {
            var item = _Emp.GetById(id);
            if (item == null)
            {
                return NotFound();
            }
            return new ObjectResult(item);
        }
        [HttpGet]
        public List<MEmployee> Get()
        {   
            return _Emp.GetAll();
        }
        [HttpPut("{id}")]
        public void Put(int id, [FromBody] MEmployee modal)
        {
            _Emp.Update(id, modal);
        }
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
            _Emp.Delete(id);
        }
    }
}
make sure don’t ambiguous the method, after all code complete please rebuild your solution explorer.

now Run your web API and test your web API with the swagger.

Wednesday, 28 October 2020

October 28, 2020

CRUD Operations In Angular 7 Using Web API (PART-2)

 Step 5. Build UI Application

 
Now, we create the Web application in Angular 7 that will consume Web API.
First we have to make sure that we have Angular CLI installed. 
Open command prompt and type below code and press ENTER:
 
npm install -g @angular/cli
 
Now, open Visual Studio Code and create a project.
Open TERMINAL in Visual Studio Code and type the following syntax to create a new project. We name it Angularcrud.
 
ng new Angularcrud
 
After that, hit ENTER. It will take a while to create the project.
Now, we can create some components to provide the UI.
 
I'm going to create a new component, Employee.
 
Go to the TERMINAL and go our angular project location using the following command:
 
cd projectName
 Now, write the following command that will create a component.
 
ng g c employee 
 
Press ENTER.
 
Note: you can use see the component is created.
 
Step 6. Create a Service
 
Now, we will create a service.
 
Open the TERMINAL and write the below command:
 
ng g s employee
 
Press ENTER and you will see two service files.
Now, we create a class like model class.
 
Open TERMINAL and write the below command:
 
ng g class employee
 
Now, write all properties of the Employee class related to an employee that matches with the database. 
  1. export class Employee {  
  2.     EmpId: string;  
  3.     EmpName: string;  
  4.     DateOfBirth: Date;  
  5.     EmailId: string;  
  6.     Gender: string;  
  7.     Address: string;  
  8.     PinCode: string;  
  9. }  

Now, open employee.service.ts and first import necessary class and libraries and then make calls to the WebAPI methods. 
  1. import { Injectable } from '@angular/core';  
  2. import { HttpClient } from '@angular/common/http';  
  3. import { HttpHeaders } from '@angular/common/http';  
  4. import { Observable } from 'rxjs';  
  5. import { Employee } from './employee';  
  6.   
  7. After that we write all methods related to consume web in employee.service.ts  
  8.  @Injectable({  
  9.   providedIn: 'root'  
  10. })  
  11.   
  12. export class EmployeeService {  
  13.   url = 'http://localhost:65389/Api/Employee';  
  14.   constructor(private http: HttpClient) { }  
  15.   getAllEmployee(): Observable<Employee[]> {  
  16.     return this.http.get<Employee[]>(this.url + '/AllEmployeeDetails');  
  17.   }  
  18.   getEmployeeById(employeeId: string): Observable<Employee> {  
  19.     return this.http.get<Employee>(this.url + '/GetEmployeeDetailsById/' + employeeId);  
  20.   }  
  21.   createEmployee(employee: Employee): Observable<Employee> {  
  22.     const httpOptions = { headers: new HttpHeaders({ 'Content-Type''application/json'}) };  
  23.     return this.http.post<Employee>(this.url + '/InsertEmployeeDetails/',  
  24.     employee, httpOptions);  
  25.   }  
  26.   updateEmployee(employee: Employee): Observable<Employee> {  
  27.     const httpOptions = { headers: new HttpHeaders({ 'Content-Type''application/json'}) };  
  28.     return this.http.put<Employee>(this.url + '/UpdateEmployeeDetails/',  
  29.     employee, httpOptions);  
  30.   }  
  31.   deleteEmployeeById(employeeid: string): Observable<number> {  
  32.     const httpOptions = { headers: new HttpHeaders({ 'Content-Type''application/json'}) };  
  33.     return this.http.delete<number>(this.url + '/DeleteEmployeeDetails?id=' +employeeid,  
  34.  httpOptions);  
  35.   }  
  36. }  
Our service is completed now.
 
If you consume the Web API, Angular blocks the URL and we called this issue CORS(Cross OriginResource Sharing).
 
First, let's resolve this problem.
 
Go to the Web API project.
Download a Nuget package for CORS. Go to NuGet Package ManagerConsole install this package:
Install-Package Microsoft.AspNet.WebApi.Cors

After that, go to App_Start folder in Web API project and open WebApiConfig.cs class. Here, modify the Register method with the below code.
  1. Add namespace  
  2. using System.Web.Http.Cors;  
  3. var cors = new EnableCorsAttribute("*","*","*");//origins,headers,methods   
  4. config.EnableCors(cors);  
Step 7. Install and Configure Angular Material Theme
 
As I said earlier, we will use the Angular Material theme to create a rich, interactive, and device-oriented UI for our Web app. 
 
Let's install Install Angular Material theme.
 
Open TERMINAL again and write the below command:
 
npm install --save @angular/material @angular/cdk @angular/animations


Now, let's all required libraries in app.module.ts. We also import a date picker because we'll use the date picker for date of birth field.
 
Now, open app.module.ts class and write the below code.
  1. import { BrowserModule } from '@angular/platform-browser';  
  2. import { NgModule } from '@angular/core';  
  3. import { EmployeeService } from './employee.service';  
  4. import { FormsModule, ReactiveFormsModule } from '@angular/forms';  
  5. import { HttpClientModule, HttpClient } from '@angular/common/http';  
  6. import {  
  7.   MatButtonModule, MatMenuModule, MatDatepickerModule,MatNativeDateModule , MatIconModule, MatCardModule, MatSidenavModule,MatFormFieldModule,  
  8.   MatInputModule, MatTooltipModule, MatToolbarModule  
  9. } from '@angular/material';  
  10. import { MatRadioModule } from '@angular/material/radio';  
  11. import { BrowserAnimationsModule } from '@angular/platform-browser/animations';  
  12.   
  13. import { AppRoutingModule } from './app-routing.module';  
  14. import { AppComponent } from './app.component';  
  15. import { EmployeeComponent } from './employee/employee.component';  
  16.   
  17. @NgModule({  
  18.   declarations: [  
  19.     AppComponent,  
  20.     EmployeeComponent  
  21.   ],  
  22.   imports: [  
  23.     BrowserModule,  
  24.     FormsModule,  
  25.     ReactiveFormsModule,  
  26.     HttpClientModule,  
  27.     BrowserAnimationsModule,  
  28.     MatButtonModule,  
  29.     MatMenuModule,  
  30.     MatDatepickerModule,  
  31.     MatNativeDateModule,  
  32.     MatIconModule,  
  33.     MatRadioModule,  
  34.     MatCardModule,  
  35.     MatSidenavModule,  
  36.     MatFormFieldModule,  
  37.     MatInputModule,  
  38.     MatTooltipModule,  
  39.     MatToolbarModule,  
  40.     AppRoutingModule  
  41.   ],  
  42.   providers: [HttpClientModule, EmployeeService,MatDatepickerModule],  
  43.   bootstrap: [AppComponent]  
  44. })  
  45. export class AppModule { }  
 Now, we have to import library in styles.css file.
  1. @import '@angular/material/prebuilt-themes/indigo-pink.css';  
Step 8. Design HTML
 
Let's design our HTML page now.
 
Open employee.component.html and write the below code.
  1. <div class="container">  
  2.   
  3. <mat-card>  
  4.   <mat-toolbar color="accent">  
  5.     <div align="center" style="color:white;text-align: right;">  
  6.       CRUD operation in Angular 7 using Web api and Sql Database  
  7.     </div>    
  8.   </mat-toolbar>  
  9. <br><br>  
  10.   <mat-card-content>  
  11.     <form [formGroup]="employeeForm"(ngSubmit)="onFormSubmit(employeeForm.value)">  
  12.             <table>  
  13.               <tr>  
  14.                 <td class="tbl1">  
  15.                   <mat-form-field class="demo-full-width">  
  16.                     <input formControlName="EmpName" matTooltip="Enter Employee Name" matInput placeholder="Employee Name">  
  17.                   </mat-form-field>  
  18.                   <mat-error>  
  19.                     <span *ngIf="!employeeForm.get('EmpName').value && employeeForm.get('EmpName').touched"></span>  
  20.                   </mat-error>  
  21.                 </td>  
  22.                 <td class="tbl1">  
  23.                   <mat-form-field class="demo-full-width">  
  24.                     <input matInput [matDatepicker]="picker"matTooltip="Enter Date Of Birth" formControlName="DateOfBirth"placeholder="Choose Date Of Birth">  
  25.                     <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>  
  26.                     <mat-datepicker #picker></mat-datepicker>  
  27.                   </mat-form-field>  
  28.                   <mat-error>  
  29.                     <span *ngIf="!employeeForm.get('DateOfBirth').value && employeeForm.get('DateOfBirth').touched"></span>  
  30.                   </mat-error>  
  31.                 </td>  
  32.                 <td class="tbl1">  
  33.                   <mat-form-field class="demo-full-width">  
  34.                     <input formControlName="EmailId" matTooltip="Enter EmailId" matInput placeholder="EmailId">  
  35.                   </mat-form-field>  
  36.                   <mat-error>  
  37.                     <span *ngIf="!employeeForm.get('EmailId').value && employeeForm.get('EmailId').touched"></span>  
  38.                   </mat-error>  
  39.                 </td>  
  40.               </tr>  
  41.               <tr>  
  42.                 <td class="tbl1">  
  43.                   <span>Gender</span>  
  44.                   <br><br>  
  45.                   <mat-radio-group matTooltip="Enter Gender"formControlName="Gender">  
  46.                       <mat-radio-button value="0">Male</mat-radio-button>    
  47.                       <mat-radio-button value="1">Female</mat-radio-button>  
  48.                     </mat-radio-group>  
  49.                   <mat-error>  
  50.                     <span *ngIf="!employeeForm.get('Gender').value && employeeForm.get('Gender').touched"></span>  
  51.                   </mat-error>  
  52.                 </td>  
  53.                 <td class="tbl1">  
  54.                   <mat-form-field class="demo-full-width">  
  55.                     <input matTooltip="Enter Address"formControlName="Address" matInput placeholder="Address">  
  56.                   </mat-form-field>  
  57.                   <mat-error>  
  58.                     <span *ngIf="!employeeForm.get('Address').value && employeeForm.get('Address').touched"></span>  
  59.                   </mat-error>  
  60.                 </td>  
  61.                 <td class="tbl1">  
  62.                   <mat-form-field class="demo-full-width">  
  63.                     <input formControlName="PinCode" matTooltip="Enter Pine Code" matInput placeholder="PinCode">  
  64.                   </mat-form-field>  
  65.                   <mat-error>  
  66.                     <span *ngIf="!employeeForm.get('PinCode').value && employeeForm.get('PinCode').touched"></span>  
  67.                   </mat-error>  
  68.                 </td>  
  69.               </tr>  
  70.               <tr>  
  71.                 <td></td>  
  72.                 <td  class="content-center">  
  73.                   <button type="submit" mat-raised-button color="accent"matTooltip="Click Submit Button"[disabled]="!employeeForm.valid">Submit</button>      
  74.                   <button type="reset" mat-raised-button color="accent"matTooltip="Click Reset Button" (click)="resetForm()">Reset</button>  
  75.                 </td>  
  76.                 <td>  
  77.                   <p *ngIf="dataSaved" style="color:rgb(0, 128, 0);font-size:20px;font-weight:bold" Class="success" align="left">  
  78.                     {{massage}}  
  79.                   </p>  
  80.                 </td>  
  81.               </tr>  
  82.             </table>  
  83. <br><br>  
  84.       <table class="table" >  
  85.           <tr ngclass="btn-primary">  
  86.             <th class="tbl2">Employee Name</th>  
  87.             <th class="tbl2">Date Of Birth</th>  
  88.             <th class="tbl2">Email Id</th>  
  89.             <th class="tbl2">Gender</th>  
  90.             <th class="tbl2">Address</th>  
  91.             <th class="tbl2">Pine Code</th>  
  92.             <th class="tbl2">Edit</th>  
  93.             <th class="tbl2">Delete</th>  
  94.           </tr>  
  95.           <tr *ngFor="let employee of allEmployees | async">  
  96.             <td class="tbl2">{{employee.EmpName}}</td>  
  97.             <td class="tbl2">{{employee.DateOfBirth | date }}</td>  
  98.             <td class="tbl2">{{employee.EmailId}}</td>  
  99.             <td class="tbl2">{{employee.Gender ==0? 'Male' : 'Female'}}</td>  
  100.             <td class="tbl2">{{employee.Address}}</td>  
  101.             <td class="tbl2">{{employee.PinCode}}</td>  
  102.             <td class="tbl2">  
  103.               <button type="button" class="btn btn-info"matTooltip="Click Edit Button"(click)="loadEmployeeToEdit(employee.EmpId)">Edit</button>  
  104.             </td>  
  105.             <td class="tbl2">  
  106.               <button type="button" class="btn btn-danger"matTooltip="Click Delete Button"(click)="deleteEmployee(employee.EmpId)">Delete</button>  
  107.             </td>  
  108.           </tr>  
  109.   
  110.         </table>  
  111.     </form>  
  112.   </mat-card-content>  
  113. </mat-card>  
  114. </div>  
Step 9
 
Open app.component.html and write the below code.
  1. <p>  
  2.   <app-employee></app-employee>  
  3. </p>  
Step 10
 
Open employee.component.ts file and write the below code.
  1. import { Component, OnInit } from '@angular/core';  
  2. import { FormBuilder, Validators } from '@angular/forms';  
  3. import { Observable } from 'rxjs';  
  4. import { EmployeeService } from '../employee.service';  
  5. import { Employee } from '../employee';  
  6.   
  7. @Component({  
  8.   selector: 'app-employee',  
  9.   templateUrl: './employee.component.html',  
  10.   styleUrls: ['./employee.component.css']  
  11. })  
  12. export class EmployeeComponent implements OnInit {  
  13.   dataSaved = false;  
  14.   employeeForm: any;  
  15.   allEmployees: Observable<Employee[]>;  
  16.   employeeIdUpdate = null;  
  17.   massage = null;  
  18.   
  19.   constructor(private formbulider: FormBuilder, private employeeService:EmployeeService) { }  
  20.   
  21.   ngOnInit() {  
  22.     this.employeeForm = this.formbulider.group({  
  23.       EmpName: ['', [Validators.required]],  
  24.       DateOfBirth: ['', [Validators.required]],  
  25.       EmailId: ['', [Validators.required]],  
  26.       Gender: ['', [Validators.required]],  
  27.       Address: ['', [Validators.required]],  
  28.       PinCode: ['', [Validators.required]],  
  29.     });  
  30.     this.loadAllEmployees();  
  31.   }  
  32.   loadAllEmployees() {  
  33.     this.allEmployees = this.employeeService.getAllEmployee();  
  34.   }  
  35.   onFormSubmit() {  
  36.     this.dataSaved = false;  
  37.     const employee = this.employeeForm.value;  
  38.     this.CreateEmployee(employee);  
  39.     this.employeeForm.reset();  
  40.   }  
  41.   loadEmployeeToEdit(employeeId: string) {  
  42.     this.employeeService.getEmployeeById(employeeId).subscribe(employee=> {  
  43.       this.massage = null;  
  44.       this.dataSaved = false;  
  45.       this.employeeIdUpdate = employee.EmpId;  
  46.       this.employeeForm.controls['EmpName'].setValue(employee.EmpName);  
  47.      this.employeeForm.controls['DateOfBirth'].setValue(employee.DateOfBirth);  
  48.       this.employeeForm.controls['EmailId'].setValue(employee.EmailId);  
  49.       this.employeeForm.controls['Gender'].setValue(employee.Gender);  
  50.       this.employeeForm.controls['Address'].setValue(employee.Address);  
  51.       this.employeeForm.controls['PinCode'].setValue(employee.PinCode);  
  52.     });  
  53.   
  54.   }  
  55.   CreateEmployee(employee: Employee) {  
  56.     if (this.employeeIdUpdate == null) {  
  57.       this.employeeService.createEmployee(employee).subscribe(  
  58.         () => {  
  59.           this.dataSaved = true;  
  60.           this.massage = 'Record saved Successfully';  
  61.           this.loadAllEmployees();  
  62.           this.employeeIdUpdate = null;  
  63.           this.employeeForm.reset();  
  64.         }  
  65.       );  
  66.     } else {  
  67.       employee.EmpId = this.employeeIdUpdate;  
  68.       this.employeeService.updateEmployee(employee).subscribe(() => {  
  69.         this.dataSaved = true;  
  70.         this.massage = 'Record Updated Successfully';  
  71.         this.loadAllEmployees();  
  72.         this.employeeIdUpdate = null;  
  73.         this.employeeForm.reset();  
  74.       });  
  75.     }  
  76.   }   
  77.   deleteEmployee(employeeId: string) {  
  78.     if (confirm("Are you sure you want to delete this ?")) {   
  79.     this.employeeService.deleteEmployeeById(employeeId).subscribe(() => {  
  80.       this.dataSaved = true;  
  81.       this.massage = 'Record Deleted Succefully';  
  82.       this.loadAllEmployees();  
  83.       this.employeeIdUpdate = null;  
  84.       this.employeeForm.reset();  
  85.   
  86.     });  
  87.   }  
  88. }  
  89.   resetForm() {  
  90.     this.employeeForm.reset();  
  91.     this.massage = null;  
  92.     this.dataSaved = false;  
  93.   }  
  94. }  
Step 11. Run
  
Open TERMINAL and write the following command to run the program.
 
ng serve -o