Thursday, October 17, 2019

Angular with .Net Core 3 and Visual Studio Code

Visual Studio Code is a cross platform light weight editor. Visual Studio Code can be used to work with a lot of languages and technologies including .Net Core and Angular.

Start a new  .Net Core  Angular Project with Authentication.

dotnet new angular -au Individual -o ngcore


The  above command will create a .Net Core project inside a folder called ngcore.

Navigate to the folder.


code .

Opens the current project folder in Visual Studio Code.

The ClientApp Folder contains the Angular app.

Open the terminal and issue the command


dotnet run 


A few packages are requires for creating Entity Framework Core and Web Api Controller.

 dotnet tool install --global dotnet-ef
dotnet add package Microsoft.VisualStudio.Web.CodeGeneration.Design    

dotnet add package Microsoft.EntityFrameworkCore.SqlServer

dotnet add package Microsoft.EntityFrameworkCore.Tools 

dotnet tool install --global dotnet-aspnet-codegenerator



Proceed on to create Database and Table using sqlcmd tool from terminnal.
sqlcmd -S .
 create database CM
go
use CM
 go
 create table Contacts (ContactId int identity(1,1) primary key, ContactName varchar(40), Location varchar(40))
 go
 insert into Contacts values ('Vishnu', 'Kochi'), ('Sarathlal', 'Kakkanad'), ('Vaishak', 'Palarivattom')
go



For scaffolding the DataContext
dotnet ef dbcontext scaffold  "Data Source=.;Initial Catalog=CM;Integrated Security=True" Microsoft.EntityFrameworkCore.SqlServer -o Models


It will create a DbContext with the Name CMContext (DatabaseName followed by Context suffix) and C# classes corresponding to Database Tables.

Now we want to create WebApis

dotnet-aspnet-codegenerator controller -name ContactsController -api -m ngcore.Models.Contacts -dc CMContext -outDir Controllers 





This command will create a WebApi with the name Contacts using Contact Class previously generated and  Context.

For using the DbContext we can to register it with the Dependency Injection Contrainer. Go to ConfigureServices section in Startup.cs


services.AddScoped<CMContext>();

The controller is ready. We can test the controller with following url https://localhost:5000/api/Contacts.

Angular 
Project created with ng new angular contains  both WebApi and Angular files. The Angular files are placed inside ClientApp folder.

Here I am creating a typescript class called contact.


export class Contact {
  contactId?: number;
  contactName?: string;
  location?: string;
}


HttpClient Get 

Since we have created the Angular project with Individual User Account a lot of code is getting adding. Along with that is the import statement for HttpClient.

Create a contacts componenet with the following command

>ng g c contacts -m appp


import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Contact } from '../contact';

@Component({
  selector: 'app-contacts',
  templateUrl: './contacts.component.html',
  styleUrls: ['./contacts.component.css']
})
export class ContactsComponent implements OnInit {

  constructor( private http: HttpClient) { }

  ngOnInit() {
    this.showData();
  }
  contacts: Contact[];

  showData() {
    this.http.get<Contact[]>('https://localhost:44391/api/contacts')
      .subscribe(contacts => this.contacts = contacts);
  }
}

<p>contacts</p>

<ul>
  <li *ngFor="let contact of contacts">
    {{contact.contactName}}
  </li>
</ul>

{{contacts | json}}


HttpClient Post


import { Component, OnInit } from '@angular/core';
import { Contact } from '../contact';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Component({
  selector: 'app-contact-insert',
  templateUrl: './contact-insert.component.html',
  styleUrls: ['./contact-insert.component.css']
})
export class ContactInsertComponent implements OnInit {

  constructor(private http: HttpClient) { }

  ngOnInit() {
  }

  httpOptions = {
    headers: new HttpHeaders({ 'Content-Type': 'application/json' })
  };

  contact: Contact = {};
  Save() {
    this.http.post<Contact>('https://localhost:44391/api/contacts', this.contact, this.httpOptions)
      .subscribe(
      (data: any) => {
        console.log(data);
        alert('Record Saved')
      });
    
  }
}



<p>Contact Insert</p>

<div>
  <div>
    <label>Name</label>
    <input type="text" name="contactName" [(ngModel)]="contact.contactName" />
  </div>
  <div>
    <label>Location</label>
    <input type="text" name="contactName" [(ngModel)]="contact.location" />
  </div>
  <input type="button" name="name" value="Save" (click)="Save()" />
</div>

{{contact | json}}