Contact Application Using ASP.NET Core Web API, Angular 6.0, And Visual Studio Code - Part One

We will develop a contact application using ASP.NET Core Web API, Angular 6.0, and Angular Material UI as shown in the below screenshots. 




We will use Visual Studio code (VS code) for the development editor. 
I have divided contact application development into two articles,
  1. Contact Application using ASP.NET Core Web API, Angular 6.0, and Visual Studio Code Part – 1
    In the article, we will set up ASP.NET Core Web API project, and develop the Web API controller for contact CRUD operations.
  2. Contact Application using ASP.NET Core Web API, Angular 6.0, and Visual Studio Code Part – 2
    In the article, we will setup Angular 6 within ASP.NET Core Web API Project, and develop the contact form & list component using Angular Material UI.
So, starting with this article, first, we will see how we can create ASP.Net Core Web API Project.
We have the following prerequisites,
  • Visual Studio Code (VS code) editorPlease see this article to see how we can setup Visual Studio code.
  • .Net CoreI have used .Net Core version 2.0.3 for this contact application. Please see this link from where we can download .Net Core SDK.
When .Net Core SDK is installed, we can check version from the console as shown in the screenshot:

After this, we require VS code extensions that adds languages, debuggers, and tools to support our development workflow. Please see this article to see how we can manage extension in VS code.
We have added these extensions in VS code:

Now, we are ready for setup ASP.Net Core Web API project.
  • Open Command Prompt and enter the following commands,
    1. mkdir contact-app  
    2. cd contact-app  
    3. dotnet new webapi 
  • Web API project has been created in the contact-app folder. Then go to the VS code, and open contact-app folder.


  • We can see one notification in  the VS code's right end corner.


  • Build and debugger tool has been set up in VS Code.


Here now we are going to create the following API for the contact application:


API
Description
Request body
Response body
GET /api/contact/getAllContact
Get all contacts
None
Array of to-do items
GET /api/contact/getContact
Get contact Item
Contact Item
Contact Item
POST /api/contact/addContact
Add a new contact
Contact Item
Contact Item
PUT /api/contact/updateContact{id}
Update an existing contact item
Contact item
None
DELETE /api/contact/deleteContact{id}
Delete an contact item
None
None


Create contact model
In this, we are creating a contact class that has getter-setter property as shown in snippet,
  1. public class Contact {  
  2.     public long ? id {  
  3.         get;  
  4.         set;  
  5.     }  
  6.     public string name {  
  7.         get;  
  8.         set;  
  9.     }  
  10.     public string email {  
  11.         get;  
  12.         set;  
  13.     }  
  14.     public byte gender {  
  15.         get;  
  16.         set;  
  17.     }  
  18.     public DateTime ? birth {  
  19.         get;  
  20.         set;  
  21.     }  
  22.     public string techno {  
  23.         get;  
  24.         set;  
  25.     }  
  26.     public string message {  
  27.         get;  
  28.         set;  
  29.     }  
  30. }  
Create the database context for contact model
Here we are using a code-first approach to develop the contact application. So we have created ‘ContactAppContext’ class to communicate contact model to contact table.


  1. public class ContactAppContext: DbContext {  
  2.     public ContactAppContext(DbContextOptions < ContactAppContext > options): base(options) {}  
  3.     public DbSet < Contact > Contact {  
  4.         get;  
  5.         set;  
  6.     }  
  7. }  
Register database context in startup:
To register database context we have followed these steps:
  • Go to ‘startup.cs ‘ and update this code for SQL server connection in ‘ConfigureServices’ method,
    1. services.AddDbContext<ContactAppContext>(options =>  
    2. options.UseSqlServer(Configuration.GetConnectionString("ContactDb"))); 


Then added ‘Microsoft.EntityFrameworkCore.SqlServer’ Package in this project to support SQL server connection.



Here we need to configure connection string in appsettings.json file as shown in the snippet.
  1. "ConnectionStrings": {  
  2.    "ContactDb""Data Source=JAYESH-PC\\SQLEXPRESS;Initial Catalog=ContactDb;Integrated Security=True"  
  3. }  
Initiate Database Migration
To create Initial migration script as per model, we enter ‘dotnet ef migrations add InitialCreate’ command in VS code terminal and we get this issue:


To solve the issue we have to add this .Net Core CLI tool package in ‘contact-app.csproj’ file and then enter ‘dotnet restore’ in VS code terminal to restore these packages to create initial migration script:
  • Microsoft.EntityFrameworkCore.Tools
  • Microsoft.EntityFrameworkCore.Tools.DotNet

Now we enter ‘dotnet of migrations add InitialCreate’ in VS code terminal and we can see that it will create migration folder and script ‘InitialCreate’ in the project as shown in the screenshot:

Now update the database by entering ‘dotnet ef database update’ command in VS code terminal and it will create a database in SQL server:
Please see this article regarding .Net Core Migration.
Create contact API controller
After the database is ready, we have created API controller for CRUD operations as in the below snippet:
  1. // set route attribute to make request as 'api/contact'  
  2. [Route("api/[controller]")]  
  3. public class ContactController: Controller {  
  4.     private readonly ContactAppContext _context;  
  5.     // initiate database context  
  6.     public ContactController(ContactAppContext context) {  
  7.             _context = context;  
  8.         }  
  9.         [HttpGet]  
  10.         [Route("getAllContact")]  
  11.     public IEnumerable < Contact > GetAll() {  
  12.             // fetch all contact records  
  13.             return _context.Contact.ToList();  
  14.         }  
  15.         [HttpGet("{id}")]  
  16.         [Route("getContact")]  
  17.     public IActionResult GetById(long id) {  
  18.             // filter contact records by contact id  
  19.             var item = _context.Contact.FirstOrDefault(t => t.id == id);  
  20.             if (item == null) {  
  21.                 return NotFound();  
  22.             }  
  23.             return new ObjectResult(item);  
  24.         }  
  25.         [HttpPost]  
  26.         [Route("addContact")]  
  27.     public IActionResult Create([FromBody] Contact item) {  
  28.             // set bad request if contact data is not provided in body  
  29.             if (item == null) {  
  30.                 return BadRequest();  
  31.             }  
  32.             _context.Contact.Add(new Contact {  
  33.                 name = item.name,  
  34.                     email = item.email,  
  35.                     gender = item.gender,  
  36.                     birth = item.birth,  
  37.                     techno = item.techno,  
  38.                     message = item.message  
  39.             });  
  40.             _context.SaveChanges();  
  41.             return Ok(new {  
  42.                 message = "Contact is added successfully."  
  43.             });  
  44.         }  
  45.         [HttpPut("{id}")]  
  46.         [Route("updateContact")]  
  47.     public IActionResult Update(long id, [FromBody] Contact item) {  
  48.             // set bad request if contact data is not provided in body  
  49.             if (item == null || id == 0) {  
  50.                 return BadRequest();  
  51.             }  
  52.             var contact = _context.Contact.FirstOrDefault(t => t.id == id);  
  53.             if (contact == null) {  
  54.                 return NotFound();  
  55.             }  
  56.             contact.name = item.name;  
  57.             contact.email = item.email;  
  58.             contact.gender = item.gender;  
  59.             contact.birth = item.birth;  
  60.             contact.techno = item.techno;  
  61.             contact.message = item.message;  
  62.             _context.Contact.Update(contact);  
  63.             _context.SaveChanges();  
  64.             return Ok(new {  
  65.                 message = "Contact is updated successfully."  
  66.             });  
  67.         }  
  68.         [HttpDelete("{id}")]  
  69.         [Route("deleteContact")]  
  70.     public IActionResult Delete(long id) {  
  71.         var contact = _context.Contact.FirstOrDefault(t => t.id == id);  
  72.         if (contact == null) {  
  73.             return NotFound();  
  74.         }  
  75.         _context.Contact.Remove(contact);  
  76.         _context.SaveChanges();  
  77.         return Ok(new {  
  78.             message = "Contact is deleted successfully."  
  79.         });  
  80.     }  
  81. }  
  82. }  
Build and run contact application project
To build contact application project we have entered ‘dotnet build’ command VS code terminal,
Setup development variable and URL for project in terminal:
  • set ASPNETCORE_ENVIRONMENT=Development
  • set ASPNETCORE_URLS=http://localhost:5000
Then, to run project we have to enter ‘dotnet run’:



Please see this article for more information regarding .Net Core 2x commands.
Test API
To test API we have installed ChromeRestClient.
Then we have to open Rest Client, to get contact item by id we set HTTP parameter to get and request URL as shown in the below screenshot:

For adding contact item, we have set the body to contact JSON object:


Then, we request add contact URL and set HTTP parameter to post.



Conclusion
In this article, we learned about how we can develop ASP.Net Core Web API using VS code.
In the next article, we will learn about how we can set up Angular 6 in Web API Project and develop the contact list & contact form component using Angular Material UI. Please see this link of the Part-2 article.
Please see entire code in this GitHub link.
Please share your feedback.

Comments

  1. Thank you for sharing this wonderful article.

    ReplyDelete

Post a Comment

Popular Posts

Chat Application using Angular 8, Asp.net Core 2.2.0, Signal R 1.1.0

Contact application - Upgrade Asp.net Core 2.0 to 2.1

Send an Email Reminder Notification Based on an Expiration Date using Power Automate

MySQL Data Access API Development Using Express.JS, Node.JS

ReactNative FlatList

SharePoint Interview Questions and Answers - Part Three

Contact Application Using ASP.NET Core Web API, Angular 6.0, And Visual Studio Code - Part Two

SharePoint Interview Questions and Answers - Part Two

Typescript Basics