Learning C# and ASP.NET Core

In a bid to break into the enterprise programming space, I have decided to embark on a learning journey through the world of C# and the ASP.NET Core framework.

The first application I have developed uses a test-driven development approach and demonstrates the use of some basic services including static files, web and api endpoints, and database integration.

The premise of the application is to create and display a collection of the Appointment resource.

public class Appointment
{
    [Key]
    public Guid Id { get; set; }
    public string? Title { get; set; }
    public string? Description { get; set; }
    public DateTime StartTime { get; set; }
    public DateTime EndTime { get; set; }
    public bool IsAllDay { get; set; } 
}

The application uses a SQLite database and Entity Framework Core which requires that a database context be registered in the dependency injection system.

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddDbContext<AppointmentsDbContext>(options =>
    options.UseSqlite(builder.Configuration.GetConnectionString("DefaultConnection")));

var app = builder.Build();

The AppointmentsDbContext defines a set of data that the context understands and can perform operations on. This includes a collection of Appointment entities which can be queried and saved.

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

    public DbSet<Appointment> Appointments { get; set; }
}

Appointments can be viewed and created through static, unstyled html files which have built-in JavaScript to call the api. These files can be served by adding the static file middleware to the application pipeline and creating a web route that redirects to them.

app.UseStaticFiles();

app.MapGet("/", () => Results.Redirect("/index.html"));
app.MapGet("/create", () => Results.Redirect("/create.html"));

The api is accessed through the /appointment endpoints. The GET method returns the appointment collection and the POST method adds a new appointment.

app.MapGet("/api/appointments", async (AppointmentsDbContext db) =>
{
    var appointments = await db.Appointments.ToListAsync();
    return Results.Ok(appointments);
});

app.MapPost("/api/appointments", async (AppointmentsDbContext db, Appointment newAppointment) => {
    db.Appointments.Add(newAppointment);
    await db.SaveChangesAsync();
    return Results.Created($"/api/appointments/{newAppointment.Id}", newAppointment);
});

The next steps of this application might involve defining suitable validation rules for an appointment resource, implementing a basic authentication and authorisation system, and styling the front-end.

🛈 The full code for this ASP.NET Core Identity app, including the test suite, can be found on my GitHub.

Leave a Comment