From be8cc7ded4ae2092d472a512c38e4684d38a365d Mon Sep 17 00:00:00 2001 From: Eugene Fox Date: Thu, 22 Feb 2024 11:06:44 +0000 Subject: [PATCH 1/4] Added ASP.NET backend with SQLite --- .devcontainer/devcontainer.json | 35 ++ .github/dependabot.yml | 12 + .vscode/launch.json | 35 ++ .vscode/tasks.json | 41 ++ backend/.gitignore | 488 ++++++++++++++++++ .../Controllers/ApiControllerBase.cs | 57 ++ .../Controllers/ErrorController.cs | 19 + .../Controllers/PointsController.cs | 219 ++++++++ .../Controllers/TracksController.cs | 180 +++++++ backend/MuiCharts.Api/MuiCharts.Api.csproj | 26 + backend/MuiCharts.Api/Program.cs | 42 ++ .../Properties/launchSettings.json | 41 ++ .../appsettings.Development.json | 8 + backend/MuiCharts.Api/appsettings.json | 9 + .../MuiCharts.Contracts.csproj | 13 + .../Point/GetPointsRequest.cs | 13 + .../Point/GetPointsResponse.cs | 11 + .../Point/PointResponse.cs | 10 + .../Point/UpsertPointRequest.cs | 11 + .../Track/TrackResponse.cs | 14 + .../Track/UpsertTrackRequest.cs | 15 + backend/MuiCharts.Domain/Enums/MaxSpeed.cs | 11 + backend/MuiCharts.Domain/Enums/Surface.cs | 11 + backend/MuiCharts.Domain/Models/Point.cs | 25 + backend/MuiCharts.Domain/Models/Track.cs | 36 ++ .../MuiCharts.Domain/MuiCharts.Domain.csproj | 13 + .../Repositories/IPointRepository.cs | 44 ++ .../Repositories/ITrackRepository.cs | 46 ++ .../PointEntityTypeConfiguration.cs | 19 + .../TrackEntityTypeConfiguration.cs | 19 + .../MuiCharts.Infrastructure/DataContext.cs | 46 ++ .../InfrastructrureExtensions.cs | 25 + .../20240221200319_InitialCreate.Designer.cs | 62 +++ .../20240221200319_InitialCreate.cs | 53 ++ .../Migrations/DataContextModelSnapshot.cs | 59 +++ .../MuiCharts.Infrastructure.csproj | 23 + .../Repositories/PointRepository.cs | 122 +++++ .../Repositories/TrackRepository.cs | 153 ++++++ backend/MuiCharts.sln | 43 ++ 39 files changed, 2109 insertions(+) create mode 100644 .devcontainer/devcontainer.json create mode 100644 .github/dependabot.yml create mode 100644 .vscode/launch.json create mode 100644 .vscode/tasks.json create mode 100644 backend/.gitignore create mode 100644 backend/MuiCharts.Api/Controllers/ApiControllerBase.cs create mode 100644 backend/MuiCharts.Api/Controllers/ErrorController.cs create mode 100644 backend/MuiCharts.Api/Controllers/PointsController.cs create mode 100644 backend/MuiCharts.Api/Controllers/TracksController.cs create mode 100644 backend/MuiCharts.Api/MuiCharts.Api.csproj create mode 100644 backend/MuiCharts.Api/Program.cs create mode 100644 backend/MuiCharts.Api/Properties/launchSettings.json create mode 100644 backend/MuiCharts.Api/appsettings.Development.json create mode 100644 backend/MuiCharts.Api/appsettings.json create mode 100644 backend/MuiCharts.Contracts/MuiCharts.Contracts.csproj create mode 100644 backend/MuiCharts.Contracts/Point/GetPointsRequest.cs create mode 100644 backend/MuiCharts.Contracts/Point/GetPointsResponse.cs create mode 100644 backend/MuiCharts.Contracts/Point/PointResponse.cs create mode 100644 backend/MuiCharts.Contracts/Point/UpsertPointRequest.cs create mode 100644 backend/MuiCharts.Contracts/Track/TrackResponse.cs create mode 100644 backend/MuiCharts.Contracts/Track/UpsertTrackRequest.cs create mode 100644 backend/MuiCharts.Domain/Enums/MaxSpeed.cs create mode 100644 backend/MuiCharts.Domain/Enums/Surface.cs create mode 100644 backend/MuiCharts.Domain/Models/Point.cs create mode 100644 backend/MuiCharts.Domain/Models/Track.cs create mode 100644 backend/MuiCharts.Domain/MuiCharts.Domain.csproj create mode 100644 backend/MuiCharts.Domain/Repositories/IPointRepository.cs create mode 100644 backend/MuiCharts.Domain/Repositories/ITrackRepository.cs create mode 100644 backend/MuiCharts.Infrastructure/Configurations/PointEntityTypeConfiguration.cs create mode 100644 backend/MuiCharts.Infrastructure/Configurations/TrackEntityTypeConfiguration.cs create mode 100644 backend/MuiCharts.Infrastructure/DataContext.cs create mode 100644 backend/MuiCharts.Infrastructure/InfrastructrureExtensions.cs create mode 100644 backend/MuiCharts.Infrastructure/Migrations/20240221200319_InitialCreate.Designer.cs create mode 100644 backend/MuiCharts.Infrastructure/Migrations/20240221200319_InitialCreate.cs create mode 100644 backend/MuiCharts.Infrastructure/Migrations/DataContextModelSnapshot.cs create mode 100644 backend/MuiCharts.Infrastructure/MuiCharts.Infrastructure.csproj create mode 100644 backend/MuiCharts.Infrastructure/Repositories/PointRepository.cs create mode 100644 backend/MuiCharts.Infrastructure/Repositories/TrackRepository.cs create mode 100644 backend/MuiCharts.sln diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json new file mode 100644 index 0000000..3251b59 --- /dev/null +++ b/.devcontainer/devcontainer.json @@ -0,0 +1,35 @@ +// For format details, see https://aka.ms/devcontainer.json. For config options, see the +// README at: https://github.com/devcontainers/templates/tree/main/src/dotnet +{ + "name": "MuiCharts", + // Or use a Dockerfile or Docker Compose file. More info: https://containers.dev/guide/dockerfile + "image": "mcr.microsoft.com/devcontainers/dotnet:1-8.0-bookworm", + // Features to add to the dev container. More info: https://containers.dev/features. + "features": { + "ghcr.io/devcontainers/features/node:1": { + "nodeGypDependencies": true, + "version": "latest", + "nvmVersion": "latest" + } + }, + + // Use 'forwardPorts' to make a list of ports inside the container available locally. + // "forwardPorts": [5000, 5001], + // "portsAttributes": { + // "5001": { + // "protocol": "https" + // } + // } + + // Use 'postCreateCommand' to run commands after the container is created. + "postCreateCommand": { + "backend": "cd backend && dotnet restore" + // "frontend": "cd frontend && yarn install" + } + + // Configure tool-specific properties. + // "customizations": {}, + + // Uncomment to connect as root instead. More info: https://aka.ms/dev-containers-non-root. + // "remoteUser": "root" +} diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..f33a02c --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,12 @@ +# To get started with Dependabot version updates, you'll need to specify which +# package ecosystems to update and where the package manifests are located. +# Please see the documentation for more information: +# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates +# https://containers.dev/guide/dependabot + +version: 2 +updates: + - package-ecosystem: "devcontainers" + directory: "/" + schedule: + interval: weekly diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000..edc366b --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,35 @@ +{ + "version": "0.2.0", + "configurations": [ + { + // Use IntelliSense to find out which attributes exist for C# debugging + // Use hover for the description of the existing attributes + // For further information visit https://github.com/dotnet/vscode-csharp/blob/main/debugger-launchjson.md. + "name": ".NET Core Launch (web)", + "type": "coreclr", + "request": "launch", + "preLaunchTask": "build", + // If you have changed target frameworks, make sure to update the program path. + "program": "${workspaceFolder}/MuiCharts.Api/bin/Debug/net8.0/MuiCharts.Api.dll", + "args": [], + "cwd": "${workspaceFolder}/MuiCharts.Api", + "stopAtEntry": false, + // Enable launching a web browser when ASP.NET Core starts. For more information: https://aka.ms/VSCode-CS-LaunchJson-WebBrowser + "serverReadyAction": { + "action": "openExternally", + "pattern": "\\bNow listening on:\\s+(https?://\\S+)" + }, + "env": { + "ASPNETCORE_ENVIRONMENT": "Development" + }, + "sourceFileMap": { + "/Views": "${workspaceFolder}/Views" + } + }, + { + "name": ".NET Core Attach", + "type": "coreclr", + "request": "attach" + } + ] +} \ No newline at end of file diff --git a/.vscode/tasks.json b/.vscode/tasks.json new file mode 100644 index 0000000..48ea68a --- /dev/null +++ b/.vscode/tasks.json @@ -0,0 +1,41 @@ +{ + "version": "2.0.0", + "tasks": [ + { + "label": "backend: build", + "command": "dotnet", + "type": "process", + "args": [ + "build", + "${workspaceFolder}/MuiCharts.sln", + "/property:GenerateFullPaths=true", + "/consoleloggerparameters:NoSummary;ForceNoAlign" + ], + "problemMatcher": "$msCompile" + }, + { + "label": "backend: publish", + "command": "dotnet", + "type": "process", + "args": [ + "publish", + "${workspaceFolder}/MuiCharts.sln", + "/property:GenerateFullPaths=true", + "/consoleloggerparameters:NoSummary;ForceNoAlign" + ], + "problemMatcher": "$msCompile" + }, + { + "label": "backend: watch", + "command": "dotnet", + "type": "process", + "args": [ + "watch", + "run", + "--project", + "${workspaceFolder}/MuiCharts.sln" + ], + "problemMatcher": "$msCompile" + } + ] +} diff --git a/backend/.gitignore b/backend/.gitignore new file mode 100644 index 0000000..6f08c89 --- /dev/null +++ b/backend/.gitignore @@ -0,0 +1,488 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from `dotnet new gitignore` + +# dotenv files +.env + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET +project.lock.json +project.fragment.lock.json +artifacts/ + +# Tye +.tye/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.tlog +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# SQLite database files +*.sqlite +*.db + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio 6 auto-generated project file (contains which files were open etc.) +*.vbp + +# Visual Studio 6 workspace and project file (working project files containing files to include in project) +*.dsw +*.dsp + +# Visual Studio 6 technical files +*.ncb +*.aps + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# Visual Studio History (VSHistory) files +.vshistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +# VS Code files for those working on multiple tools +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Local History for Visual Studio Code +.history/ + +# Windows Installer files from build outputs +*.cab +*.msi +*.msix +*.msm +*.msp + +# JetBrains Rider +*.sln.iml +.idea + +## +## Visual studio for Mac +## + + +# globs +Makefile.in +*.userprefs +*.usertasks +config.make +config.status +aclocal.m4 +install-sh +autom4te.cache/ +*.tar.gz +tarballs/ +test-results/ + +# Mac bundle stuff +*.dmg +*.app + +# content below from: https://github.com/github/gitignore/blob/master/Global/macOS.gitignore +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +# content below from: https://github.com/github/gitignore/blob/master/Global/Windows.gitignore +# Windows thumbnail cache files +Thumbs.db +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk + +# Vim temporary swap files +*.swp diff --git a/backend/MuiCharts.Api/Controllers/ApiControllerBase.cs b/backend/MuiCharts.Api/Controllers/ApiControllerBase.cs new file mode 100644 index 0000000..745970a --- /dev/null +++ b/backend/MuiCharts.Api/Controllers/ApiControllerBase.cs @@ -0,0 +1,57 @@ +using ErrorOr; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.ModelBinding; + +namespace MuiCharts.Api.Controllers; + +/// +/// Base class for API controllers that provides common functionality and error handling. +/// +/// The type of the derived controller. +[ApiController] +[Route("[controller]")] +public abstract class ApiControllerBase(ILogger logger) + : ControllerBase where T : ApiControllerBase +{ + /// + /// Gets the logger instance used for logging. + /// + protected ILogger Logger { get; } = logger; + + /// + /// Handles the response for a list of errors. + /// + /// The list of errors. + /// An representing the response. + protected IActionResult Problem(List errors) + { + if (errors.All(error => error.Type == ErrorType.Validation)) + { + ModelStateDictionary modelState = new(); + + foreach (Error error in errors) + modelState.AddModelError(error.Code, error.Description); + + return ValidationProblem(modelState); + } + + Error firstError = errors[0]; + + Logger.LogError("An error occured during request processing: {Error}", firstError); + + int statusCode = firstError.Type switch + { + ErrorType.Validation => StatusCodes.Status400BadRequest, + ErrorType.Unauthorized => StatusCodes.Status401Unauthorized, + ErrorType.Forbidden => StatusCodes.Status403Forbidden, + ErrorType.NotFound => StatusCodes.Status404NotFound, + ErrorType.Conflict => StatusCodes.Status409Conflict, + _ => StatusCodes.Status500InternalServerError + }; + + return Problem( + statusCode: statusCode, + detail: firstError.Description + ); + } +} diff --git a/backend/MuiCharts.Api/Controllers/ErrorController.cs b/backend/MuiCharts.Api/Controllers/ErrorController.cs new file mode 100644 index 0000000..5caaff0 --- /dev/null +++ b/backend/MuiCharts.Api/Controllers/ErrorController.cs @@ -0,0 +1,19 @@ +using Microsoft.AspNetCore.Mvc; + +namespace MuiCharts.Api; + +/// +/// Controller for handling errors. +/// +[ApiController] +[Route("[controller]")] +public class ErrorController: ControllerBase +{ + /// + /// Handles the HTTP GET request for the error endpoint. + /// + /// An IActionResult representing the error response. + [HttpGet] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + public IActionResult Error() => Problem(); +} diff --git a/backend/MuiCharts.Api/Controllers/PointsController.cs b/backend/MuiCharts.Api/Controllers/PointsController.cs new file mode 100644 index 0000000..4801491 --- /dev/null +++ b/backend/MuiCharts.Api/Controllers/PointsController.cs @@ -0,0 +1,219 @@ +using ErrorOr; +using Microsoft.AspNetCore.Mvc; +using MuiCharts.Contracts.Point; +using MuiCharts.Domain.Models; +using MuiCharts.Domain.Repositories; + +namespace MuiCharts.Api.Controllers; + +/// +/// Controller for managing points. +/// +public class PointsController( + ILogger logger, + IPointRepository pointRepository +) : ApiControllerBase(logger) +{ + private readonly IPointRepository _repository = pointRepository; + + /// + /// Creates a new point. + /// + /// The new point model. + /// An representing the asynchronous operation result. + [HttpPost] + [ProducesResponseType(StatusCodes.Status201Created)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + [ProducesDefaultResponseType(typeof(ProblemDetails))] + public async Task CreatePointAsync(UpsertPointRequest request) + { + Logger.LogInformation("Creating point with name {Name} and height {Height}", request.Name, request.Height); + + Point point = new() + { + Id = default, + Name = request.Name, + Height = request.Height + }; + + ErrorOr createResult = await _repository.AddPointAsync(point); + + if (createResult.IsError) + return Problem(createResult.Errors); + + Logger.LogInformation("Point created with id {Id}", createResult.Value.Id); + + return CreatedAtPointResult(createResult.Value); + } + + /// + /// Retrieves an array of points based on the provided IDs. + /// + /// The array of point IDs. + /// An representing the asynchronous operation result. + [HttpPost("Array")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status206PartialContent)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + [ProducesDefaultResponseType(typeof(ProblemDetails))] + public async Task GetPointsArrayAsync(int[] ids) + { + Logger.LogInformation("Getting points with ids {Ids}", ids); + + IQueryable query = await _repository.GetPointsRangeAsync(); + + PointResponse[] points = [ + .. query + .Where(point => ids.Contains(point.Id)) + .Select(point => MapPointResponse(point)) + ]; + + if (points.Length == 0) + { + Logger.LogInformation("No points found with ids {Ids}", ids); + return NotFound(); + } + + if (points.Length != ids.Length) + { + Logger.LogInformation("Not all points found with ids {Ids}", ids); + return StatusCode(StatusCodes.Status206PartialContent, points); + } + + Logger.LogInformation("Returning {Count} points", points.Length); + + return Ok(points); + } + + /// + /// Retrieves a range of points based on the specified page and count. + /// + /// The request object containing the page and count parameters. + /// An representing the asynchronous operation result. + [HttpGet] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + [ProducesDefaultResponseType(typeof(ProblemDetails))] + public async Task GetPointsAsync([FromQuery] GetPointsRequest request) + { + Logger.LogInformation("Getting points with page {Page} and count {Count}", request.Page, request.Count); + + IQueryable query = await _repository.GetPointsRangeAsync(); + + PointResponse[] points = [ + .. query + .Skip((request.Page - 1) * request.Count) + .Take(request.Count) + .Select(point => MapPointResponse(point)) + ]; + + GetPointsResponse response = new( + points, + query.Count(), + points.Length, + request.Page + ); + + Logger.LogInformation("Returning {Count} points", response.Count); + + return Ok(response); + } + + /// + /// Retrieves a point with the specified ID. + /// + /// The ID of the point to retrieve. + /// An representing the asynchronous operation result. + [HttpGet("{id:int}")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesDefaultResponseType(typeof(ProblemDetails))] + public async Task GetPointAsync(int id) + { + Logger.LogInformation("Getting point with id {Id}", id); + + ErrorOr getResult = await _repository.GetPointAsync(id); + + if (getResult.IsError) + return Problem(getResult.Errors); + + Logger.LogInformation("Returning point with id {Id}", id); + + return Ok(MapPointResponse(getResult.Value)); + } + + /// + /// Upserts a point with the specified ID and request data. + /// + /// The ID of the point. + /// The request data for the point. + /// An representing the asynchronous operation result. + [HttpPut("{id:int}")] + [ProducesResponseType(StatusCodes.Status201Created)] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + [ProducesDefaultResponseType(typeof(ProblemDetails))] + public async Task UpsertPointAsync(int id, UpsertPointRequest request) + { + Logger.LogInformation("Upserting point with id {Id}", id); + + Point point = new() + { + Id = id, + Name = request.Name, + Height = request.Height + }; + + ErrorOr upsertResult = await _repository.AddOrUpdatePointAsync(point); + + if (upsertResult.IsError) + return Problem(upsertResult.Errors); + + if (upsertResult.Value is Point value) + { + Logger.LogInformation("Point created with id {Id}", value.Id); + return CreatedAtPointResult(value); + } + + Logger.LogInformation("Point updated with id {Id}", id); + return NoContent(); + } + + /// + /// Deletes a point with the specified ID. + /// + /// The ID of the point to delete. + /// An representing the asynchronous operation result. + [HttpDelete("{id:int}")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesDefaultResponseType(typeof(ProblemDetails))] + public async Task DeletePointAsync(int id) + { + Logger.LogInformation("Deleting point with id {Id}", id); + + ErrorOr deleteResult = await _repository.DeletePointAsync(id); + + if (deleteResult.IsError) + return Problem(deleteResult.Errors); + + Logger.LogInformation("Point deleted with id {Id}", id); + + return NoContent(); + } + + private CreatedAtActionResult CreatedAtPointResult(Point point) => + CreatedAtAction( + actionName: nameof(GetPointAsync), + routeValues: new { id = point.Id }, + value: MapPointResponse(point) + ); + + private static PointResponse MapPointResponse(Point value) => + new( + value.Id, + value.Name, + value.Height + ); +} diff --git a/backend/MuiCharts.Api/Controllers/TracksController.cs b/backend/MuiCharts.Api/Controllers/TracksController.cs new file mode 100644 index 0000000..a4395e3 --- /dev/null +++ b/backend/MuiCharts.Api/Controllers/TracksController.cs @@ -0,0 +1,180 @@ +using ErrorOr; +using Microsoft.AspNetCore.Mvc; +using MuiCharts.Contracts.Track; +using MuiCharts.Domain.Models; +using MuiCharts.Domain.Repositories; + +namespace MuiCharts.Api.Controllers; + +/// +/// Controller for managing tracks. +/// +/// The logger. +/// The track repository. +public class TracksController( + ILogger logger, + ITrackRepository trackRepository +) : ApiControllerBase(logger) +{ + private readonly ITrackRepository _repository = trackRepository; + + /// + /// Creates a new track. + /// + /// The request containing the track details. + /// An representing the asynchronous operation result. + [HttpPost] + [ProducesResponseType(StatusCodes.Status201Created)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + [ProducesResponseType(StatusCodes.Status409Conflict)] + [ProducesDefaultResponseType(typeof(ProblemDetails))] + public async Task CreateTrackAsync(UpsertTrackRequest request) + { + // TODO: Check if points exist + Logger.LogInformation("Creating track with first ID {FirstId} and second ID {SecondId}", request.FirstId, request.SecondId); + + if (request.FirstId == request.SecondId) + return Problem([Error.Validation(description: "First ID and second ID cannot be the same.")]); + + Track track = new() + { + FirstId = request.FirstId, + SecondId = request.SecondId, + Distance = request.Distance, + Surface = request.Surface, + MaxSpeed = request.MaxSpeed + }; + + ErrorOr createResult = await _repository.AddTrackAsync(track); + + if (createResult.IsError) + return Problem(createResult.Errors); + + Logger.LogInformation("Track created with first ID {FirstId} and second ID {SecondId}", createResult.Value.FirstId, createResult.Value.SecondId); + + return CreatedAtTrackResult(createResult.Value); + } + + /// + /// Retrieves a track with the specified first ID and second ID. + /// + /// The first point ID of the track. + /// The second point ID of the track. + /// An representing the asynchronous operation result. + [HttpGet("{firstId:int}/{secondId:int}")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesDefaultResponseType(typeof(ProblemDetails))] + public async Task GetTrackAsync(int firstId, int secondId) + { + Logger.LogInformation("Retrieving track with first ID {FirstId} and second ID {SecondId}", firstId, secondId); + + ErrorOr getResult = await _repository.GetTrackAsync(firstId, secondId); + + if (getResult.IsError) + return Problem(getResult.Errors); + + Logger.LogInformation("Track retrieved with first ID {FirstId} and second ID {SecondId}", getResult.Value.FirstId, getResult.Value.SecondId); + + return Ok(MapTrackResponse(getResult.Value)); + } + + /// + /// Retrieves all tracks. + /// + /// An representing the asynchronous operation result. + [HttpGet] + [ProducesResponseType>(StatusCodes.Status200OK)] + [ProducesDefaultResponseType(typeof(ProblemDetails))] + public async Task GetAllTracksAsync() + { + Logger.LogInformation("Retrieving all tracks"); + + IQueryable tracks = await _repository.GetTracksRangeAsync(); + + Logger.LogInformation("All tracks retrieved"); + + return Ok(tracks.Select(MapTrackResponse)); + } + + /// + /// Upserts a track with the specified first point ID, second point ID, and request data. + /// + /// The first point ID of the track. + /// The second point ID of the track. + /// The request data containing the track details. + /// An representing the asynchronous operation result. + [HttpPut("{firstId:int}/{secondId:int}")] + [ProducesResponseType(StatusCodes.Status201Created)] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + [ProducesDefaultResponseType(typeof(ProblemDetails))] + public async Task UpsertTrackAsync(int firstId, int secondId, UpsertTrackRequest request) + { + // TODO: Check if points exist + Logger.LogInformation("Upserting track with first ID {FirstId} and second ID {SecondId}", firstId, secondId); + + Track track = new() + { + FirstId = firstId, + SecondId = secondId, + Distance = request.Distance, + Surface = request.Surface, + MaxSpeed = request.MaxSpeed + }; + + ErrorOr upsertResult = await _repository.AddOrUpdateTrackAsync(track); + + if (upsertResult.IsError) + return Problem(upsertResult.Errors); + + if (upsertResult.Value is Track value) + { + Logger.LogInformation("Track created with first ID {FirstId} and second ID {SecondId}", value.FirstId, value.SecondId); + return CreatedAtTrackResult(value); + } + + Logger.LogInformation("Track updated with first ID {FirstId} and second ID {SecondId}", firstId, secondId); + return NoContent(); + } + + /// + /// Deletes a track with the specified first point ID and second point ID. + /// + /// The first point ID of the track to delete. + /// The second point ID of the track to delete. + /// An representing the asynchronous operation result. + [HttpDelete("{firstId:int}/{secondId:int}")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesDefaultResponseType(typeof(ProblemDetails))] + public async Task DeleteTrackAsync(int firstId, int secondId) + { + Logger.LogInformation("Deleting track with first ID {FirstId} and second ID {SecondId}", firstId, secondId); + + ErrorOr deleteResult = await _repository.DeleteTrackAsync(firstId, secondId); + + if (deleteResult.IsError) + return Problem(deleteResult.Errors); + + Logger.LogInformation("Track deleted with first ID {FirstId} and second ID {SecondId}", firstId, secondId); + + return NoContent(); + } + + private CreatedAtActionResult CreatedAtTrackResult(Track track) => + CreatedAtAction( + actionName: nameof(GetTrackAsync), + routeValues: new { firstId = track.FirstId, secondId = track.SecondId }, + value: MapTrackResponse(track) + ); + + private static TrackResponse MapTrackResponse(Track track) => + new( + track.FirstId, + track.SecondId, + track.Distance, + track.Surface, + track.MaxSpeed + ); +} diff --git a/backend/MuiCharts.Api/MuiCharts.Api.csproj b/backend/MuiCharts.Api/MuiCharts.Api.csproj new file mode 100644 index 0000000..63f2990 --- /dev/null +++ b/backend/MuiCharts.Api/MuiCharts.Api.csproj @@ -0,0 +1,26 @@ + + + + net8.0 + enable + enable + true + true + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + + + + + + diff --git a/backend/MuiCharts.Api/Program.cs b/backend/MuiCharts.Api/Program.cs new file mode 100644 index 0000000..d0d903a --- /dev/null +++ b/backend/MuiCharts.Api/Program.cs @@ -0,0 +1,42 @@ +using System.Reflection; +using MuiCharts.Infrastructure; + +WebApplicationBuilder builder = WebApplication.CreateBuilder(args); +{ + // Add services to the container. + // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle + builder.Services.AddLogging(options => + { + options.AddConfiguration(builder.Configuration.GetSection("Logging")); + options.AddConsole(); + options.AddDebug(); + options.AddEventSourceLogger(); + }); + + builder.Services.AddControllers(options => + { + options.SuppressAsyncSuffixInActionNames = false; + }); + builder.Services.AddInfrastructure(); + + builder.Services.AddEndpointsApiExplorer(); + builder.Services.AddSwaggerGen(options => + { + string xmlFileName = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; + string xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFileName); + options.IncludeXmlComments(xmlPath); + }); +} + +WebApplication app = builder.Build(); +{ + // Configure the HTTP request pipeline. + app.UseExceptionHandler("/error"); + app.UseSwagger(); + app.UseSwaggerUI(); + + // app.UseHttpsRedirection(); + app.MapControllers(); + + app.Run(); +} diff --git a/backend/MuiCharts.Api/Properties/launchSettings.json b/backend/MuiCharts.Api/Properties/launchSettings.json new file mode 100644 index 0000000..f116d86 --- /dev/null +++ b/backend/MuiCharts.Api/Properties/launchSettings.json @@ -0,0 +1,41 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:34734", + "sslPort": 44380 + } + }, + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "launchUrl": "swagger", + "applicationUrl": "http://localhost:5152", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "launchUrl": "swagger", + "applicationUrl": "https://localhost:7096;http://localhost:5152", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "launchUrl": "swagger", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/backend/MuiCharts.Api/appsettings.Development.json b/backend/MuiCharts.Api/appsettings.Development.json new file mode 100644 index 0000000..a919448 --- /dev/null +++ b/backend/MuiCharts.Api/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/backend/MuiCharts.Api/appsettings.json b/backend/MuiCharts.Api/appsettings.json new file mode 100644 index 0000000..2f36700 --- /dev/null +++ b/backend/MuiCharts.Api/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +} diff --git a/backend/MuiCharts.Contracts/MuiCharts.Contracts.csproj b/backend/MuiCharts.Contracts/MuiCharts.Contracts.csproj new file mode 100644 index 0000000..c6e88d0 --- /dev/null +++ b/backend/MuiCharts.Contracts/MuiCharts.Contracts.csproj @@ -0,0 +1,13 @@ + + + + + + + + net8.0 + enable + enable + + + diff --git a/backend/MuiCharts.Contracts/Point/GetPointsRequest.cs b/backend/MuiCharts.Contracts/Point/GetPointsRequest.cs new file mode 100644 index 0000000..98daf8f --- /dev/null +++ b/backend/MuiCharts.Contracts/Point/GetPointsRequest.cs @@ -0,0 +1,13 @@ +using System.ComponentModel.DataAnnotations; + +namespace MuiCharts.Contracts.Point; + +/// +/// Represents a request to get a collection of points. +/// +public record class GetPointsRequest( + [Range(1, int.MaxValue)] + int Page = 1, + [Range(1, int.MaxValue)] + int Count = 50 +); diff --git a/backend/MuiCharts.Contracts/Point/GetPointsResponse.cs b/backend/MuiCharts.Contracts/Point/GetPointsResponse.cs new file mode 100644 index 0000000..7cbd2c5 --- /dev/null +++ b/backend/MuiCharts.Contracts/Point/GetPointsResponse.cs @@ -0,0 +1,11 @@ +namespace MuiCharts.Contracts.Point; + +/// +/// Represents the response object for retrieving points. +/// +public record class GetPointsResponse( + PointResponse[] Points, + int TotalCount, + int Count, + int Page +); diff --git a/backend/MuiCharts.Contracts/Point/PointResponse.cs b/backend/MuiCharts.Contracts/Point/PointResponse.cs new file mode 100644 index 0000000..e2b6289 --- /dev/null +++ b/backend/MuiCharts.Contracts/Point/PointResponse.cs @@ -0,0 +1,10 @@ +namespace MuiCharts.Contracts.Point; + +/// +/// Represents a response object containing information about a point. +/// +public record PointResponse( + int Id, + string Name, + int Height +); diff --git a/backend/MuiCharts.Contracts/Point/UpsertPointRequest.cs b/backend/MuiCharts.Contracts/Point/UpsertPointRequest.cs new file mode 100644 index 0000000..e17edb6 --- /dev/null +++ b/backend/MuiCharts.Contracts/Point/UpsertPointRequest.cs @@ -0,0 +1,11 @@ +using System.ComponentModel.DataAnnotations; + +namespace MuiCharts.Contracts.Point; + +/// +/// Represents a request to upsert a point. +/// +public record UpsertPointRequest( + [MinLength(1)] string Name, + int Height +); diff --git a/backend/MuiCharts.Contracts/Track/TrackResponse.cs b/backend/MuiCharts.Contracts/Track/TrackResponse.cs new file mode 100644 index 0000000..5d72aab --- /dev/null +++ b/backend/MuiCharts.Contracts/Track/TrackResponse.cs @@ -0,0 +1,14 @@ +using MuiCharts.Domain.Enums; + +namespace MuiCharts.Contracts.Track; + +/// +/// Represents a response object for a track. +/// +public record TrackResponse( + int FirstId, + int SecondId, + int Distance, + Surface Surface, + MaxSpeed MaxSpeed +); diff --git a/backend/MuiCharts.Contracts/Track/UpsertTrackRequest.cs b/backend/MuiCharts.Contracts/Track/UpsertTrackRequest.cs new file mode 100644 index 0000000..86b37af --- /dev/null +++ b/backend/MuiCharts.Contracts/Track/UpsertTrackRequest.cs @@ -0,0 +1,15 @@ +using System.ComponentModel.DataAnnotations; +using MuiCharts.Domain.Enums; + +namespace MuiCharts.Contracts.Track; + +/// +/// Represents a request to upsert a track. +/// +public record UpsertTrackRequest( + [Range(0, int.MaxValue)] int FirstId, + [Range(0, int.MaxValue)] int SecondId, + [Range(1, int.MaxValue)] int Distance, + Surface Surface, + MaxSpeed MaxSpeed +); diff --git a/backend/MuiCharts.Domain/Enums/MaxSpeed.cs b/backend/MuiCharts.Domain/Enums/MaxSpeed.cs new file mode 100644 index 0000000..ec60911 --- /dev/null +++ b/backend/MuiCharts.Domain/Enums/MaxSpeed.cs @@ -0,0 +1,11 @@ +namespace MuiCharts.Domain.Enums; + +/// +/// Represents the maximum speed options. +/// +public enum MaxSpeed +{ + Fast = 0, + Normal = 1, + Slow = 2 +} diff --git a/backend/MuiCharts.Domain/Enums/Surface.cs b/backend/MuiCharts.Domain/Enums/Surface.cs new file mode 100644 index 0000000..c139fb4 --- /dev/null +++ b/backend/MuiCharts.Domain/Enums/Surface.cs @@ -0,0 +1,11 @@ +namespace MuiCharts.Domain.Enums; + +/// +/// Represents the surface types. +/// +public enum Surface +{ + Sand = 0, + Asphalt = 1, + Ground = 2 +} diff --git a/backend/MuiCharts.Domain/Models/Point.cs b/backend/MuiCharts.Domain/Models/Point.cs new file mode 100644 index 0000000..6e69f16 --- /dev/null +++ b/backend/MuiCharts.Domain/Models/Point.cs @@ -0,0 +1,25 @@ +using System.ComponentModel.DataAnnotations; + +namespace MuiCharts.Domain.Models; + +/// +/// Represents a point with an ID, name, and height. +/// +public class Point +{ + /// + /// Gets or sets the ID of the point. + /// + public required int Id { get; init; } + + /// + /// Gets or sets the name of the point. + /// + [MinLength(1)] + public required string Name { get; init; } + + /// + /// Gets or sets the height of the point. + /// + public required int Height { get; init; } +} diff --git a/backend/MuiCharts.Domain/Models/Track.cs b/backend/MuiCharts.Domain/Models/Track.cs new file mode 100644 index 0000000..d73571e --- /dev/null +++ b/backend/MuiCharts.Domain/Models/Track.cs @@ -0,0 +1,36 @@ +using System.ComponentModel.DataAnnotations; +using MuiCharts.Domain.Enums; + +namespace MuiCharts.Domain.Models; + +/// +/// Represents a track with information about the first point ID, second point ID, distance, surface, and maximum speed. +/// +public class Track +{ + /// + /// Gets or sets the first ID. + /// + public required int FirstId { get; init; } + + /// + /// Gets or sets the second ID. + /// + public required int SecondId { get; init; } + + /// + /// Gets or sets the distance. + /// + [Range(1, int.MaxValue)] + public required int Distance { get; init; } + + /// + /// Gets or sets the surface. + /// + public required Surface Surface { get; init; } + + /// + /// Gets or sets the maximum speed. + /// + public required MaxSpeed MaxSpeed { get; init; } +} diff --git a/backend/MuiCharts.Domain/MuiCharts.Domain.csproj b/backend/MuiCharts.Domain/MuiCharts.Domain.csproj new file mode 100644 index 0000000..ec7908f --- /dev/null +++ b/backend/MuiCharts.Domain/MuiCharts.Domain.csproj @@ -0,0 +1,13 @@ + + + + net8.0 + enable + enable + + + + + + + diff --git a/backend/MuiCharts.Domain/Repositories/IPointRepository.cs b/backend/MuiCharts.Domain/Repositories/IPointRepository.cs new file mode 100644 index 0000000..f5e5ac0 --- /dev/null +++ b/backend/MuiCharts.Domain/Repositories/IPointRepository.cs @@ -0,0 +1,44 @@ +using ErrorOr; +using MuiCharts.Domain.Models; + +namespace MuiCharts.Domain.Repositories; + +/// +/// Represents a repository for managing points. +/// +public interface IPointRepository +{ + /// + /// Adds a new point asynchronously. + /// + /// The point to add. + /// A task that represents the asynchronous operation. The task result contains the added point or an error. + Task> AddPointAsync(Point point); + + /// + /// Retrieves a point by its ID asynchronously. + /// + /// The ID of the point to retrieve. + /// A task that represents the asynchronous operation. The task result contains the retrieved point or an error. + Task> GetPointAsync(int id); + + /// + /// Retrieves a range of points asynchronously. + /// + /// A task that represents the asynchronous operation. The task result contains a queryable collection of points. + Task> GetPointsRangeAsync(); + + /// + /// Adds or updates a point asynchronously. + /// + /// The point to add or update. + /// A task that represents the asynchronous operation. The task result contains the added or updated point or an error. + Task> AddOrUpdatePointAsync(Point point); + + /// + /// Deletes a point by its ID asynchronously. + /// + /// The ID of the point to delete. + /// A task that represents the asynchronous operation. The task result contains a flag indicating if the point was deleted successfully or an error. + Task> DeletePointAsync(int id); +} diff --git a/backend/MuiCharts.Domain/Repositories/ITrackRepository.cs b/backend/MuiCharts.Domain/Repositories/ITrackRepository.cs new file mode 100644 index 0000000..a1d8f51 --- /dev/null +++ b/backend/MuiCharts.Domain/Repositories/ITrackRepository.cs @@ -0,0 +1,46 @@ +using ErrorOr; +using MuiCharts.Domain.Models; + +namespace MuiCharts.Domain.Repositories; + +/// +/// Represents a repository for managing tracks. +/// +public interface ITrackRepository +{ + /// + /// Adds a new track asynchronously. + /// + /// The track to add. + /// A task that represents the asynchronous operation. The task result contains the added track if successful, or an error if unsuccessful. + Task> AddTrackAsync(Track track); + + /// + /// Retrieves a track asynchronously based on the specified IDs. + /// + /// The first ID. + /// The second ID. + /// A task that represents the asynchronous operation. The task result contains the retrieved track if successful, or an error if unsuccessful. + Task> GetTrackAsync(int firstId, int secondId); + + /// + /// Retrieves a range of tracks asynchronously. + /// + /// A task that represents the asynchronous operation. The task result contains the range of tracks. + Task> GetTracksRangeAsync(); + + /// + /// Adds or updates a track asynchronously. + /// + /// The track to add or update. + /// A task that represents the asynchronous operation. The task result contains the added or updated track if successful, or an error if unsuccessful. + Task> AddOrUpdateTrackAsync(Track track); + + /// + /// Deletes a track asynchronously based on the specified IDs. + /// + /// The first ID. + /// The second ID. + /// A task that represents the asynchronous operation. The task result contains the deletion status if successful, or an error if unsuccessful. + Task> DeleteTrackAsync(int firstId, int secondId); +} diff --git a/backend/MuiCharts.Infrastructure/Configurations/PointEntityTypeConfiguration.cs b/backend/MuiCharts.Infrastructure/Configurations/PointEntityTypeConfiguration.cs new file mode 100644 index 0000000..887be51 --- /dev/null +++ b/backend/MuiCharts.Infrastructure/Configurations/PointEntityTypeConfiguration.cs @@ -0,0 +1,19 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; +using MuiCharts.Domain.Models; + +namespace MuiCharts.Infrastructure.Configurations; + +/// +/// Represents the entity type configuration for the entity. +/// +public class PointEntityTypeConfiguration : IEntityTypeConfiguration +{ + /// + public void Configure(EntityTypeBuilder builder) + { + builder.HasKey(p => p.Id); + builder.Property(p => p.Name).IsRequired(); + builder.Property(p => p.Height).IsRequired(); + } +} diff --git a/backend/MuiCharts.Infrastructure/Configurations/TrackEntityTypeConfiguration.cs b/backend/MuiCharts.Infrastructure/Configurations/TrackEntityTypeConfiguration.cs new file mode 100644 index 0000000..ae424d9 --- /dev/null +++ b/backend/MuiCharts.Infrastructure/Configurations/TrackEntityTypeConfiguration.cs @@ -0,0 +1,19 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace MuiCharts.Domain.Models; + +/// +/// Represents the entity type configuration for the entity. +/// +public class TrackEntityTypeConfiguration : IEntityTypeConfiguration +{ + /// + public void Configure(EntityTypeBuilder builder) + { + builder.HasKey(t => new { t.FirstId, t.SecondId }); + builder.Property(t => t.Distance).IsRequired(); + builder.Property(t => t.Surface).IsRequired(); + builder.Property(t => t.MaxSpeed).IsRequired(); + } +} diff --git a/backend/MuiCharts.Infrastructure/DataContext.cs b/backend/MuiCharts.Infrastructure/DataContext.cs new file mode 100644 index 0000000..168d9d3 --- /dev/null +++ b/backend/MuiCharts.Infrastructure/DataContext.cs @@ -0,0 +1,46 @@ +using Microsoft.EntityFrameworkCore; +using MuiCharts.Domain.Models; +using MuiCharts.Infrastructure.Configurations; + +namespace MuiCharts.Infrastructure; + +/// +/// Represents the database context for MuiCharts application. +/// +public class DataContext : DbContext +{ + /// + /// table. + /// + public DbSet Points { get; set; } + + /// + /// table. + /// + public DbSet Tracks { get; set; } + + /// + public DataContext() : base() {} + + /// + public DataContext(DbContextOptions options) : base(options) {} + + /// + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + { + optionsBuilder + .UseSqlite("Data Source=data.db") + .EnableSensitiveDataLogging( + Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "Development" + ); + } + + /// + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + base.OnModelCreating(modelBuilder); + + modelBuilder.ApplyConfiguration(new PointEntityTypeConfiguration()); + modelBuilder.ApplyConfiguration(new TrackEntityTypeConfiguration()); + } +} diff --git a/backend/MuiCharts.Infrastructure/InfrastructrureExtensions.cs b/backend/MuiCharts.Infrastructure/InfrastructrureExtensions.cs new file mode 100644 index 0000000..858917e --- /dev/null +++ b/backend/MuiCharts.Infrastructure/InfrastructrureExtensions.cs @@ -0,0 +1,25 @@ +using Microsoft.Extensions.DependencyInjection; +using MuiCharts.Domain.Repositories; +using MuiCharts.Infrastructure.Repositories; + +namespace MuiCharts.Infrastructure; + +/// +/// Provides extension methods for configuring infrastructure services. +/// +public static class InfrastructrureExtensions +{ + /// + /// Adds infrastructure services to the specified . + /// + /// The to add the services to. + /// The modified . + public static IServiceCollection AddInfrastructure(this IServiceCollection services) + { + services.AddDbContext(); + services.AddScoped(); + services.AddScoped(); + + return services; + } +} diff --git a/backend/MuiCharts.Infrastructure/Migrations/20240221200319_InitialCreate.Designer.cs b/backend/MuiCharts.Infrastructure/Migrations/20240221200319_InitialCreate.Designer.cs new file mode 100644 index 0000000..2634cc1 --- /dev/null +++ b/backend/MuiCharts.Infrastructure/Migrations/20240221200319_InitialCreate.Designer.cs @@ -0,0 +1,62 @@ +// +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace MuiCharts.Infrastructure.Migrations +{ + [DbContext(typeof(DataContext))] + [Migration("20240221200319_InitialCreate")] + partial class InitialCreate + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "8.0.2"); + + modelBuilder.Entity("MuiCharts.Domain.Models.Point", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Height") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("Points"); + }); + + modelBuilder.Entity("MuiCharts.Domain.Models.Track", b => + { + b.Property("FirstId") + .HasColumnType("INTEGER"); + + b.Property("SecondId") + .HasColumnType("INTEGER"); + + b.Property("Distance") + .HasColumnType("INTEGER"); + + b.Property("MaxSpeed") + .HasColumnType("INTEGER"); + + b.Property("Surface") + .HasColumnType("INTEGER"); + + b.HasKey("FirstId", "SecondId"); + + b.ToTable("Tracks"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/backend/MuiCharts.Infrastructure/Migrations/20240221200319_InitialCreate.cs b/backend/MuiCharts.Infrastructure/Migrations/20240221200319_InitialCreate.cs new file mode 100644 index 0000000..176c534 --- /dev/null +++ b/backend/MuiCharts.Infrastructure/Migrations/20240221200319_InitialCreate.cs @@ -0,0 +1,53 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace MuiCharts.Infrastructure.Migrations +{ + /// + public partial class InitialCreate : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "Points", + columns: table => new + { + Id = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + Name = table.Column(type: "TEXT", nullable: false), + Height = table.Column(type: "INTEGER", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Points", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "Tracks", + columns: table => new + { + FirstId = table.Column(type: "INTEGER", nullable: false), + SecondId = table.Column(type: "INTEGER", nullable: false), + Distance = table.Column(type: "INTEGER", nullable: false), + Surface = table.Column(type: "INTEGER", nullable: false), + MaxSpeed = table.Column(type: "INTEGER", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Tracks", x => new { x.FirstId, x.SecondId }); + }); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "Points"); + + migrationBuilder.DropTable( + name: "Tracks"); + } + } +} diff --git a/backend/MuiCharts.Infrastructure/Migrations/DataContextModelSnapshot.cs b/backend/MuiCharts.Infrastructure/Migrations/DataContextModelSnapshot.cs new file mode 100644 index 0000000..824b223 --- /dev/null +++ b/backend/MuiCharts.Infrastructure/Migrations/DataContextModelSnapshot.cs @@ -0,0 +1,59 @@ +// +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; + +#nullable disable + +namespace MuiCharts.Infrastructure.Migrations +{ + [DbContext(typeof(DataContext))] + partial class DataContextModelSnapshot : ModelSnapshot + { + protected override void BuildModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "8.0.2"); + + modelBuilder.Entity("MuiCharts.Domain.Models.Point", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Height") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("Points"); + }); + + modelBuilder.Entity("MuiCharts.Domain.Models.Track", b => + { + b.Property("FirstId") + .HasColumnType("INTEGER"); + + b.Property("SecondId") + .HasColumnType("INTEGER"); + + b.Property("Distance") + .HasColumnType("INTEGER"); + + b.Property("MaxSpeed") + .HasColumnType("INTEGER"); + + b.Property("Surface") + .HasColumnType("INTEGER"); + + b.HasKey("FirstId", "SecondId"); + + b.ToTable("Tracks"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/backend/MuiCharts.Infrastructure/MuiCharts.Infrastructure.csproj b/backend/MuiCharts.Infrastructure/MuiCharts.Infrastructure.csproj new file mode 100644 index 0000000..6ed9754 --- /dev/null +++ b/backend/MuiCharts.Infrastructure/MuiCharts.Infrastructure.csproj @@ -0,0 +1,23 @@ + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + + + + + + net8.0 + enable + enable + + + diff --git a/backend/MuiCharts.Infrastructure/Repositories/PointRepository.cs b/backend/MuiCharts.Infrastructure/Repositories/PointRepository.cs new file mode 100644 index 0000000..c526e38 --- /dev/null +++ b/backend/MuiCharts.Infrastructure/Repositories/PointRepository.cs @@ -0,0 +1,122 @@ +using ErrorOr; +using Microsoft.EntityFrameworkCore.ChangeTracking; +using Microsoft.Extensions.Logging; +using MuiCharts.Domain.Models; +using MuiCharts.Domain.Repositories; + +namespace MuiCharts.Infrastructure.Repositories; + +/// +/// Represents a repository for points. +/// +/// The data context. +/// The logger. +public class PointRepository( + DataContext context, + ILogger logger +) : IPointRepository +{ + private readonly DataContext _context = context; + private readonly ILogger _logger = logger; + + /// + public async Task> AddOrUpdatePointAsync(Point point) + { + try + { + _logger.LogInformation("Adding or updating point {point}", point); + + bool doesExist = _context.Points.Any(p => p.Id == point.Id); + + if (doesExist) + { + _logger.LogInformation("Point {id} exists, updating", point.Id); + _context.Points.Update(point); + await _context.SaveChangesAsync(); + return (Point?)null; + } + else + { + _logger.LogInformation("Point {id} does not exist, adding", point.Id); + EntityEntry result = _context.Points.Add(point); + await _context.SaveChangesAsync(); + + return result.Entity; + } + } + catch (Exception e) + { + _logger.LogError(e, "Error adding or updating point {point}", point); + return Error.Failure(); + } + } + + /// + public async Task> AddPointAsync(Point point) + { + try + { + _logger.LogInformation("Adding or updating point {point}", point); + EntityEntry result = await _context.Points.AddAsync(point); + await _context.SaveChangesAsync(); + + return result.Entity; + } + catch (Exception e) + { + _logger.LogError(e, "Error adding point {point}", point); + return Error.Failure(); + } + } + + /// + public async Task> DeletePointAsync(int id) + { + try + { + _logger.LogInformation("Deleting point {id}", id); + + Point? point = await _context.Points.FindAsync(id); + + if (point == null) + return Error.NotFound(); + + _context.Points.Remove(point); + await _context.SaveChangesAsync(); + + return Result.Deleted; + } + catch (Exception e) + { + _logger.LogError(e, "Error deleting point {id}", id); + return Error.Failure(); + } + } + + /// + public async Task> GetPointAsync(int id) + { + try + { + _logger.LogInformation("Getting point {id}", id); + + Point? point = await _context.Points.FindAsync(id); + + if (point == null) + return Error.NotFound(); + + return point; + } + catch (Exception e) + { + _logger.LogError(e, "Error getting point {id}", id); + return Error.Failure(); + } + } + + /// + public Task> GetPointsRangeAsync() + { + return Task.FromResult(_context.Points.AsQueryable()); + } +} diff --git a/backend/MuiCharts.Infrastructure/Repositories/TrackRepository.cs b/backend/MuiCharts.Infrastructure/Repositories/TrackRepository.cs new file mode 100644 index 0000000..f5671bd --- /dev/null +++ b/backend/MuiCharts.Infrastructure/Repositories/TrackRepository.cs @@ -0,0 +1,153 @@ +using ErrorOr; +using Microsoft.EntityFrameworkCore.ChangeTracking; +using Microsoft.Extensions.Logging; +using MuiCharts.Domain.Models; +using MuiCharts.Domain.Repositories; + +namespace MuiCharts.Infrastructure.Repositories; + +/// +/// Represents a repository for tracks. +/// +/// The data context. +/// The logger. +public class TrackRepository( + DataContext context, + ILogger logger +) : ITrackRepository +{ + private readonly DataContext _context = context; + private readonly ILogger _logger = logger; + + /// + public async Task> AddOrUpdateTrackAsync(Track track) + { + try + { + _logger.LogInformation("Adding or updating track {track}", track); + + if (!IsValidTrack(track)) + { + _logger.LogInformation("Points with first ID {FirstId} and second ID {SecondId} do not exist", track.FirstId, track.SecondId); + return Error.Validation(description: "One or both specified points do not exist."); + } + + bool doesExist = _context.Tracks.Any(t => t.FirstId == track.FirstId && t.SecondId == track.SecondId); + + if (doesExist) + { + _logger.LogInformation("Track with first ID {FirstId} and second ID {SecondId} exists, updating", track.FirstId, track.SecondId); + _context.Tracks.Update(track); + await _context.SaveChangesAsync(); + return (Track?)null; + } + else + { + _logger.LogInformation("Track with first ID {FirstId} and second ID {SecondId} does not exist, adding", track.FirstId, track.SecondId); + EntityEntry result = _context.Tracks.Add(track); + await _context.SaveChangesAsync(); + + return result.Entity; + } + } + catch (Exception e) + { + _logger.LogError(e, "Error adding or updating track {track}", track); + return Error.Failure(); + } + } + + /// + public async Task> AddTrackAsync(Track track) + { + try + { + _logger.LogInformation("Adding track with first ID {FirstId} and second ID {SecondId}", track.FirstId, track.SecondId); + + if (!IsValidTrack(track)) + { + _logger.LogInformation("Points with first ID {FirstId} and second ID {SecondId} do not exist", track.FirstId, track.SecondId); + return Error.Validation(description: "One or both specified points do not exist."); + } + + if (_context.Tracks.Any(t => t.FirstId == track.FirstId && t.SecondId == track.SecondId)) + { + _logger.LogInformation("Track with first ID {FirstId} and second ID {SecondId} already exists", track.FirstId, track.SecondId); + return Error.Conflict(); + } + + EntityEntry result = _context.Tracks.Add(track); + await _context.SaveChangesAsync(); + + return result.Entity; + } + catch (Exception e) + { + _logger.LogError(e, "Error adding track with first ID {FirstId} and second ID {SecondId}", track.FirstId, track.SecondId); + return Error.Failure(); + } + } + + /// + public async Task> DeleteTrackAsync(int firstId, int secondId) + { + try + { + _logger.LogInformation("Deleting track with first ID {FirstId} and second ID {SecondId}", firstId, secondId); + + Track? track = await _context.Tracks.FindAsync(firstId, secondId); + + if (track is null) + { + _logger.LogInformation("Track with first ID {FirstId} and second ID {SecondId} does not exist", firstId, secondId); + return Error.NotFound(); + } + + _context.Tracks.Remove(track); + await _context.SaveChangesAsync(); + + return new Deleted(); + } + catch (Exception e) + { + _logger.LogError(e, "Error deleting track with first ID {FirstId} and second ID {SecondId}", firstId, secondId); + return Error.Failure(); + } + } + + /// + public async Task> GetTrackAsync(int firstId, int secondId) + { + try + { + _logger.LogInformation("Getting track with first ID {FirstId} and second ID {SecondId}", firstId, secondId); + + Track? track = await _context.Tracks.FindAsync(firstId, secondId); + + if (track is null) + { + _logger.LogInformation("Track with first ID {FirstId} and second ID {SecondId} does not exist", firstId, secondId); + return Error.NotFound(); + } + + return track; + } + catch (Exception e) + { + _logger.LogError(e, "Error getting track with first ID {FirstId} and second ID {SecondId}", firstId, secondId); + return Error.Failure(); + } + } + + /// + public Task> GetTracksRangeAsync() + { + return Task.FromResult(_context.Tracks.AsQueryable()); + } + + private bool IsValidTrack(Track track) + { + return _context.Points.Any(p => p.Id == track.FirstId) && + _context.Points.Any(p => p.Id == track.SecondId); + } +} diff --git a/backend/MuiCharts.sln b/backend/MuiCharts.sln new file mode 100644 index 0000000..20730a0 --- /dev/null +++ b/backend/MuiCharts.sln @@ -0,0 +1,43 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.5.002.0 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MuiCharts.Domain", "MuiCharts.Domain\MuiCharts.Domain.csproj", "{46BF0964-24CC-4757-9A10-9F29F6CCA9E7}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MuiCharts.Api", "MuiCharts.Api\MuiCharts.Api.csproj", "{E0B3F765-138A-4784-8349-C45E8F0673E0}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MuiCharts.Infrastructure", "MuiCharts.Infrastructure\MuiCharts.Infrastructure.csproj", "{810B3986-E864-4B7F-BFCF-B849FD950C99}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MuiCharts.Contracts", "MuiCharts.Contracts\MuiCharts.Contracts.csproj", "{21E46377-9EF8-4981-8593-CEFEE3A3CBB6}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {46BF0964-24CC-4757-9A10-9F29F6CCA9E7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {46BF0964-24CC-4757-9A10-9F29F6CCA9E7}.Debug|Any CPU.Build.0 = Debug|Any CPU + {46BF0964-24CC-4757-9A10-9F29F6CCA9E7}.Release|Any CPU.ActiveCfg = Release|Any CPU + {46BF0964-24CC-4757-9A10-9F29F6CCA9E7}.Release|Any CPU.Build.0 = Release|Any CPU + {E0B3F765-138A-4784-8349-C45E8F0673E0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E0B3F765-138A-4784-8349-C45E8F0673E0}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E0B3F765-138A-4784-8349-C45E8F0673E0}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E0B3F765-138A-4784-8349-C45E8F0673E0}.Release|Any CPU.Build.0 = Release|Any CPU + {810B3986-E864-4B7F-BFCF-B849FD950C99}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {810B3986-E864-4B7F-BFCF-B849FD950C99}.Debug|Any CPU.Build.0 = Debug|Any CPU + {810B3986-E864-4B7F-BFCF-B849FD950C99}.Release|Any CPU.ActiveCfg = Release|Any CPU + {810B3986-E864-4B7F-BFCF-B849FD950C99}.Release|Any CPU.Build.0 = Release|Any CPU + {21E46377-9EF8-4981-8593-CEFEE3A3CBB6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {21E46377-9EF8-4981-8593-CEFEE3A3CBB6}.Debug|Any CPU.Build.0 = Debug|Any CPU + {21E46377-9EF8-4981-8593-CEFEE3A3CBB6}.Release|Any CPU.ActiveCfg = Release|Any CPU + {21E46377-9EF8-4981-8593-CEFEE3A3CBB6}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {2FAC24E8-FCA3-4D28-A826-031825B5A057} + EndGlobalSection +EndGlobal From 39bc85c9d91f2b092ff2e5bfff285b8aae4098ac Mon Sep 17 00:00:00 2001 From: Eugene Fox Date: Thu, 22 Feb 2024 14:56:15 +0000 Subject: [PATCH 2/4] - Reworked Infrastructure injection - Added LettuceEncrypt for HTTPS - Fixed DataContext - Moved connection string to appsettings.json --- backend/MuiCharts.Api/MuiCharts.Api.csproj | 1 + backend/MuiCharts.Api/Program.cs | 12 ++++++++++-- .../appsettings.Development.json | 3 +++ backend/MuiCharts.Api/appsettings.json | 5 ++++- .../MuiCharts.Infrastructure/DataContext.cs | 19 ++++++------------- .../InfrastructrureExtensions.cs | 19 +++++++++++++------ .../MuiCharts.Infrastructure.csproj | 2 +- 7 files changed, 38 insertions(+), 23 deletions(-) diff --git a/backend/MuiCharts.Api/MuiCharts.Api.csproj b/backend/MuiCharts.Api/MuiCharts.Api.csproj index 63f2990..c8baf23 100644 --- a/backend/MuiCharts.Api/MuiCharts.Api.csproj +++ b/backend/MuiCharts.Api/MuiCharts.Api.csproj @@ -9,6 +9,7 @@ + runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/backend/MuiCharts.Api/Program.cs b/backend/MuiCharts.Api/Program.cs index d0d903a..7caeb6f 100644 --- a/backend/MuiCharts.Api/Program.cs +++ b/backend/MuiCharts.Api/Program.cs @@ -1,4 +1,5 @@ using System.Reflection; +using LettuceEncrypt; using MuiCharts.Infrastructure; WebApplicationBuilder builder = WebApplication.CreateBuilder(args); @@ -17,7 +18,8 @@ WebApplicationBuilder builder = WebApplication.CreateBuilder(args); { options.SuppressAsyncSuffixInActionNames = false; }); - builder.Services.AddInfrastructure(); + + builder.AddInfrastructure(); builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(options => @@ -26,6 +28,10 @@ WebApplicationBuilder builder = WebApplication.CreateBuilder(args); string xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFileName); options.IncludeXmlComments(xmlPath); }); + + if (builder.Configuration.GetSection("LettuceEncrypt").Exists()) + builder.Services.AddLettuceEncrypt() + .PersistDataToDirectory(new DirectoryInfo("/persistence"), null); } WebApplication app = builder.Build(); @@ -35,7 +41,9 @@ WebApplication app = builder.Build(); app.UseSwagger(); app.UseSwaggerUI(); - // app.UseHttpsRedirection(); + if (app.Configuration.GetSection("LettuceEncrypt").Exists()) + app.UseHttpsRedirection(); + app.MapControllers(); app.Run(); diff --git a/backend/MuiCharts.Api/appsettings.Development.json b/backend/MuiCharts.Api/appsettings.Development.json index a919448..78e579c 100644 --- a/backend/MuiCharts.Api/appsettings.Development.json +++ b/backend/MuiCharts.Api/appsettings.Development.json @@ -4,5 +4,8 @@ "Default": "Information", "Microsoft.AspNetCore": "Warning" } + }, + "ConnectionStrings": { + "DataContext": "Data Source=app.db" } } diff --git a/backend/MuiCharts.Api/appsettings.json b/backend/MuiCharts.Api/appsettings.json index 2f36700..943f5d5 100644 --- a/backend/MuiCharts.Api/appsettings.json +++ b/backend/MuiCharts.Api/appsettings.json @@ -5,5 +5,8 @@ "Microsoft.AspNetCore": "Warning" } }, - "AllowedHosts": "*" + "AllowedHosts": "*", + "ConnectionStrings": { + "DataContext": "Data Source=/persistence/data.db" + } } diff --git a/backend/MuiCharts.Infrastructure/DataContext.cs b/backend/MuiCharts.Infrastructure/DataContext.cs index 168d9d3..c5b60a0 100644 --- a/backend/MuiCharts.Infrastructure/DataContext.cs +++ b/backend/MuiCharts.Infrastructure/DataContext.cs @@ -19,20 +19,13 @@ public class DataContext : DbContext /// public DbSet Tracks { get; set; } - /// - public DataContext() : base() {} - - /// - public DataContext(DbContextOptions options) : base(options) {} - - /// - protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + /// + /// Initializes a new instance of . + /// + /// The options for this context. + public DataContext(DbContextOptions options) : base(options) { - optionsBuilder - .UseSqlite("Data Source=data.db") - .EnableSensitiveDataLogging( - Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "Development" - ); + Database.Migrate(); } /// diff --git a/backend/MuiCharts.Infrastructure/InfrastructrureExtensions.cs b/backend/MuiCharts.Infrastructure/InfrastructrureExtensions.cs index 858917e..c82c37c 100644 --- a/backend/MuiCharts.Infrastructure/InfrastructrureExtensions.cs +++ b/backend/MuiCharts.Infrastructure/InfrastructrureExtensions.cs @@ -1,6 +1,9 @@ -using Microsoft.Extensions.DependencyInjection; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; using MuiCharts.Domain.Repositories; using MuiCharts.Infrastructure.Repositories; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Configuration; namespace MuiCharts.Infrastructure; @@ -14,12 +17,16 @@ public static class InfrastructrureExtensions /// /// The to add the services to. /// The modified . - public static IServiceCollection AddInfrastructure(this IServiceCollection services) + public static void AddInfrastructure(this IHostApplicationBuilder builder) { - services.AddDbContext(); - services.AddScoped(); - services.AddScoped(); + builder.Services.AddDbContext(options => + { + options + .UseSqlite(builder.Configuration.GetConnectionString(nameof(DataContext))) + .EnableSensitiveDataLogging(builder.Environment.IsDevelopment()); + }); - return services; + builder.Services.AddScoped(); + builder.Services.AddScoped(); } } diff --git a/backend/MuiCharts.Infrastructure/MuiCharts.Infrastructure.csproj b/backend/MuiCharts.Infrastructure/MuiCharts.Infrastructure.csproj index 6ed9754..f089afc 100644 --- a/backend/MuiCharts.Infrastructure/MuiCharts.Infrastructure.csproj +++ b/backend/MuiCharts.Infrastructure/MuiCharts.Infrastructure.csproj @@ -6,8 +6,8 @@ runtime; build; native; contentfiles; analyzers; buildtransitive all - + From af7d4e0ec93a6c1b03a3440f88ac8e9a7f4afb43 Mon Sep 17 00:00:00 2001 From: Eugene Fox Date: Thu, 22 Feb 2024 14:56:32 +0000 Subject: [PATCH 3/4] Minor fixes and refactoring --- backend/MuiCharts.Api/Controllers/ApiControllerBase.cs | 2 +- backend/MuiCharts.Api/Controllers/PointsController.cs | 7 ++++--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/backend/MuiCharts.Api/Controllers/ApiControllerBase.cs b/backend/MuiCharts.Api/Controllers/ApiControllerBase.cs index 745970a..8c0ccc0 100644 --- a/backend/MuiCharts.Api/Controllers/ApiControllerBase.cs +++ b/backend/MuiCharts.Api/Controllers/ApiControllerBase.cs @@ -37,7 +37,7 @@ public abstract class ApiControllerBase(ILogger logger) Error firstError = errors[0]; - Logger.LogError("An error occured during request processing: {Error}", firstError); + Logger.LogWarning("An error occured during request processing: {Error}", firstError); int statusCode = firstError.Type switch { diff --git a/backend/MuiCharts.Api/Controllers/PointsController.cs b/backend/MuiCharts.Api/Controllers/PointsController.cs index 4801491..3dad5e7 100644 --- a/backend/MuiCharts.Api/Controllers/PointsController.cs +++ b/backend/MuiCharts.Api/Controllers/PointsController.cs @@ -103,9 +103,10 @@ public class PointsController( PointResponse[] points = [ .. query - .Skip((request.Page - 1) * request.Count) - .Take(request.Count) - .Select(point => MapPointResponse(point)) + .OrderBy(i => i.Id) + .Skip((request.Page - 1) * request.Count) + .Take(request.Count) + .Select(point => MapPointResponse(point)) ]; GetPointsResponse response = new( From f399b380104884e6c0242ba9eb3124e2a31e0c07 Mon Sep 17 00:00:00 2001 From: Eugene Fox Date: Thu, 22 Feb 2024 14:56:48 +0000 Subject: [PATCH 4/4] Updated docker files for devcontainers and backend build --- .devcontainer/devcontainer.json | 27 +- backend/.dockerignore | 488 ++++++++++++++++++++++++++++++++ backend/Dockerfile | 26 ++ docker-compose.yml | 17 ++ 4 files changed, 548 insertions(+), 10 deletions(-) create mode 100644 backend/.dockerignore create mode 100644 backend/Dockerfile create mode 100644 docker-compose.yml diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index 3251b59..31d208c 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -1,11 +1,19 @@ // For format details, see https://aka.ms/devcontainer.json. For config options, see the -// README at: https://github.com/devcontainers/templates/tree/main/src/dotnet +// README at: https://github.com/devcontainers/templates/tree/main/src/docker-in-docker { "name": "MuiCharts", // Or use a Dockerfile or Docker Compose file. More info: https://containers.dev/guide/dockerfile - "image": "mcr.microsoft.com/devcontainers/dotnet:1-8.0-bookworm", + "image": "mcr.microsoft.com/devcontainers/base:bullseye", // Features to add to the dev container. More info: https://containers.dev/features. "features": { + "ghcr.io/devcontainers/features/docker-in-docker:2": { + "version": "latest", + "enableNonRootDocker": "true", + "moby": "false" + }, + "ghcr.io/devcontainers/features/dotnet:2": { + "version": "latest" + }, "ghcr.io/devcontainers/features/node:1": { "nodeGypDependencies": true, "version": "latest", @@ -14,18 +22,17 @@ }, // Use 'forwardPorts' to make a list of ports inside the container available locally. - // "forwardPorts": [5000, 5001], - // "portsAttributes": { - // "5001": { - // "protocol": "https" - // } - // } + // "forwardPorts": [], // Use 'postCreateCommand' to run commands after the container is created. "postCreateCommand": { - "backend": "cd backend && dotnet restore" + // "workload": "sudo /usr/share/dotnet/dotnet workload update", + "eftool": "/usr/share/dotnet/dotnet tool install --global dotnet-ef", + "system": "sudo apt update && sudo apt upgrade -y", + "backend": "cd backend && /usr/share/dotnet/dotnet restore" // "frontend": "cd frontend && yarn install" - } + }, + "postStartCommand": "sudo /usr/share/dotnet/dotnet workload update", // Configure tool-specific properties. // "customizations": {}, diff --git a/backend/.dockerignore b/backend/.dockerignore new file mode 100644 index 0000000..6f08c89 --- /dev/null +++ b/backend/.dockerignore @@ -0,0 +1,488 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from `dotnet new gitignore` + +# dotenv files +.env + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET +project.lock.json +project.fragment.lock.json +artifacts/ + +# Tye +.tye/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.tlog +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# SQLite database files +*.sqlite +*.db + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio 6 auto-generated project file (contains which files were open etc.) +*.vbp + +# Visual Studio 6 workspace and project file (working project files containing files to include in project) +*.dsw +*.dsp + +# Visual Studio 6 technical files +*.ncb +*.aps + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# Visual Studio History (VSHistory) files +.vshistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +# VS Code files for those working on multiple tools +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Local History for Visual Studio Code +.history/ + +# Windows Installer files from build outputs +*.cab +*.msi +*.msix +*.msm +*.msp + +# JetBrains Rider +*.sln.iml +.idea + +## +## Visual studio for Mac +## + + +# globs +Makefile.in +*.userprefs +*.usertasks +config.make +config.status +aclocal.m4 +install-sh +autom4te.cache/ +*.tar.gz +tarballs/ +test-results/ + +# Mac bundle stuff +*.dmg +*.app + +# content below from: https://github.com/github/gitignore/blob/master/Global/macOS.gitignore +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +# content below from: https://github.com/github/gitignore/blob/master/Global/Windows.gitignore +# Windows thumbnail cache files +Thumbs.db +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk + +# Vim temporary swap files +*.swp diff --git a/backend/Dockerfile b/backend/Dockerfile new file mode 100644 index 0000000..9465077 --- /dev/null +++ b/backend/Dockerfile @@ -0,0 +1,26 @@ +FROM mcr.microsoft.com/dotnet/sdk:8.0 as build + +WORKDIR /app + +COPY ./MuiCharts.sln ./ +COPY ./MuiCharts.Domain/*.csproj MuiCharts.Domain/ +COPY ./MuiCharts.Contracts/*.csproj MuiCharts.Contracts/ +COPY ./MuiCharts.Infrastructure/*.csproj MuiCharts.Infrastructure/ +COPY ./MuiCharts.Api/*.csproj MuiCharts.Api/ + +RUN dotnet restore + +COPY . ./ + +RUN dotnet publish --configuration Release -o out MuiCharts.Api/MuiCharts.Api.csproj + +FROM mcr.microsoft.com/dotnet/aspnet:8.0 as runtime + +WORKDIR /app + +COPY --from=build /app/out ./ + +ENV HTTP_PORTS=80 +EXPOSE 80 + +ENTRYPOINT ["dotnet", "MuiCharts.Api.dll"] diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..ec95a56 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,17 @@ +version: "3.8" + +services: + backend: + image: "muicharts-backend:latest" + build: + context: ./backend + ports: + - "80:80" + - "443:443" + volumes: + - ./persistence:/persistence + environment: + - "HTTPS_PORTS=443" + - "LettuceEncrypt:AcceptTermsOfService=true" + - "LettuceEncrypt:DomainNames:0=containers.xfox111.net" + - "LettuceEncrypt:EmailAddress=eugene@xfox111.net"