Task Management Application with .NET Core, Angular, and SQL Server

Task Management Application with .NET Core, Angular, and SQL Server

Create a full-stack Task Management App that uses .NET Core API, Angular for the frontend, and SQL Server for storing tasks.

Task management API develepment guide

Introduction

Task management apps help users stay organized by tracking tasks and their progress. In this tutorial, we’ll build a simple task management application using a full-stack approach. The backend will be powered by .NET Core, and the frontend will be built using Angular. We will use SQL Server to store task data and demonstrate CRUD (Create, Read, Update, Delete) functionality for managing tasks.

This guide will walk you through the process of setting up the API backend, connecting it to a SQL Server database, building the Angular frontend, and deploying the app.

Prerequisites

  • Basic knowledge of .NET Core, Angular, and SQL Server.
  • Node.js and npm installed.
  • Visual Studio or any IDE for .NET Core development.
  • SQL Server installed locally or access to a cloud-based instance.
  • Postman or any API testing tool (optional, for testing endpoints).

If you're new to .NET Core or Angular, it's recommended to learn about their basic setup before diving into this full-stack application tutorial.

Backend Setup with .NET Core

We will start by creating a new .NET Core Web API project that will handle all the backend functionality for our task management app.

  1. Open a terminal or command prompt and create a new .NET Core Web API project:
    dotnet new webapi -n TaskManagementApp
  2. Navigate to the project folder:
    cd TaskManagementApp
  3. Install Entity Framework Core and SQL Server NuGet packages:
    dotnet add package Microsoft.EntityFrameworkCore.SqlServer
    dotnet add package Microsoft.EntityFrameworkCore.Tools

Now, let’s set up the Task model class to represent a task in our system. Create a new file called Task.cs inside the Models folder:

public class Task
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    public bool IsCompleted { get; set; }
}
            

Next, create a TaskContext class inside the Data folder to manage the Entity Framework Core database context:

using Microsoft.EntityFrameworkCore;

public class TaskContext : DbContext
{
    public TaskContext(DbContextOptions<TaskContext> options) : base(options) { }

    public DbSet<Task> Tasks { get; set; }
}
            

Now, open the Startup.cs file to configure the services and the database connection:

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<TaskContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("TaskDb")));
        services.AddControllers();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseRouting();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}
            

In the appsettings.json file, add the connection string to SQL Server:

{
  "ConnectionStrings": {
    "TaskDb": "Server=localhost;Database=TaskDb;Trusted_Connection=True;"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}
            

Now, let’s create a TaskController to handle the CRUD operations for tasks:

using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

[Route("api/[controller]")]
[ApiController]
public class TaskController : ControllerBase
{
    private readonly TaskContext _context;

    public TaskController(TaskContext context)
    {
        _context = context;
    }

    [HttpGet]
    public async Task<ActionResult<IEnumerable<Task>>> GetTasks()
    {
        return await _context.Tasks.ToListAsync();
    }

    [HttpPost]
    public async Task<ActionResult<Task>> CreateTask(Task task)
    {
        _context.Tasks.Add(task);
        await _context.SaveChangesAsync();
        return CreatedAtAction(nameof(GetTasks), new { id = task.Id }, task);
    }

    [HttpPut("{id}")]
    public async Task<IActionResult> UpdateTask(int id, Task task)
    {
        if (id != task.Id)
        {
            return BadRequest();
        }

        _context.Entry(task).State = EntityState.Modified;
        await _context.SaveChangesAsync();
        return NoContent();
    }

    [HttpDelete("{id}")]
    public async Task<IActionResult> DeleteTask(int id)
    {
        var task = await _context.Tasks.FindAsync(id);
        if (task == null)
        {
            return NotFound();
        }

        _context.Tasks.Remove(task);
        await _context.SaveChangesAsync();
        return NoContent();
    }
}
            

This controller will handle CRUD operations for our task resource. We can now create, retrieve, update, and delete tasks via HTTP requests.

Frontend Setup with Angular

Next, let’s build the Angular frontend to interact with our .NET Core API. First, create a new Angular application:

ng new task-manager

Navigate into the project folder:

cd task-manager

Install the Angular HTTP client module to communicate with the backend API:

ng add @angular/common/http

Now, let’s generate a new service to handle API calls:

ng generate service task

In the task.service.ts file, implement methods to interact with the API:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Task } from './task.model';

@Injectable({
  providedIn: 'root'
})
export class TaskService {
  private apiUrl = 'http://localhost:5000/api/task';

  constructor(private http: HttpClient) { }

  getTasks(): Observable<Task[]> {
    return this.http.get<Task[]>(this.apiUrl);
  }

  createTask(task: Task): Observable<Task> {
    return this.http.post<Task>(this.apiUrl, task);
  }

  updateTask(task: Task): Observable<void> {
    return this.http.put<void>(`${this.apiUrl}/${task.id}`, task);
  }

  deleteTask(id: number): Observable<void> {
    return this.http.delete<void>(`${this.apiUrl}/${id}`);
  }
}
            

Next, define the Task model in the task.model.ts file:

export interface Task {
  id: number;
  title: string;
  description: string;
  isCompleted: boolean;
}
            

Now, in the app.component.ts file, call the service methods to manage tasks:

import { Component, OnInit } from '@angular/core';
import { TaskService } from './task.service';
import { Task } from './task.model';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  tasks: Task[] = [];

  constructor(private taskService: TaskService) {}

  ngOnInit(): void {
    this.loadTasks();
  }

  loadTasks(): void {
    this.taskService.getTasks().subscribe(tasks => this.tasks = tasks);
  }

  addTask(task: Task): void {
    this.taskService.createTask(task).subscribe(() => this.loadTasks());
  }

  deleteTask(id: number): void {
    this.taskService.deleteTask(id).subscribe(() => this.loadTasks());
  }

  updateTask(task: Task): void {
    this.taskService.updateTask(task).subscribe(() => this.loadTasks());
  }
}
            

Finally, in the app.component.html file, display the task list and include forms for adding or updating tasks:

<div class="container">
  <h2>Task Management</h2>
  <div *ngFor="let task of tasks">
    <p>{{ task.title }} - {{ task.description }}</p>
    <button (click)="updateTask(task)">Update</button>
    <button (click)="deleteTask(task.id)">Delete</button>
  </div>
  <button (click)="addTask({ title: 'New Task', description: 'Description' })">Add Task</button>
</div>
            

Running the Application

  1. Start the backend .NET Core Web API:
    dotnet run
  2. Start the Angular frontend:
    ng serve

Your task management application is now live! You can create, update, and delete tasks from the UI, and the backend will handle all the database operations.

Conclusion

In this post, we’ve built a full-stack task management application using .NET Core, Angular, and SQL Server. We demonstrated how to handle CRUD operations in .NET Core API, interact with Angular frontend, and store tasks in SQL Server. You can expand this project by adding user authentication, task prioritization, and more features.

By following this guide, you can quickly create your own task management application and use it as a starting point for building more complex apps.

Sandip Mhaske

I’m a software developer exploring the depths of .NET, AWS, Angular, React, and digital entrepreneurship. Here, I decode complex problems, share insightful solutions, and navigate the evolving landscape of tech and finance.

Post a Comment

Previous Post Next Post