From 3cc0af97ceb93e5d71d1698eaf770421c4cfd62a Mon Sep 17 00:00:00 2001 From: Chase Swick Date: Tue, 13 May 2025 18:30:14 -0400 Subject: [PATCH 1/9] Create web api project --- InvestmentPerformanceApi/.gitignore | 484 ++++++++++++++++++ .../InvestmentPerformanceApi.csproj | 13 + .../InvestmentPerformanceApi.http | 6 + InvestmentPerformanceApi/Program.cs | 18 + .../Properties/launchSettings.json | 23 + .../appsettings.Development.json | 8 + InvestmentPerformanceApi/appsettings.json | 9 + 7 files changed, 561 insertions(+) create mode 100644 InvestmentPerformanceApi/.gitignore create mode 100644 InvestmentPerformanceApi/InvestmentPerformanceApi.csproj create mode 100644 InvestmentPerformanceApi/InvestmentPerformanceApi.http create mode 100644 InvestmentPerformanceApi/Program.cs create mode 100644 InvestmentPerformanceApi/Properties/launchSettings.json create mode 100644 InvestmentPerformanceApi/appsettings.Development.json create mode 100644 InvestmentPerformanceApi/appsettings.json diff --git a/InvestmentPerformanceApi/.gitignore b/InvestmentPerformanceApi/.gitignore new file mode 100644 index 00000000..bc78471d --- /dev/null +++ b/InvestmentPerformanceApi/.gitignore @@ -0,0 +1,484 @@ +## 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 + +# 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/main/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/main/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/InvestmentPerformanceApi/InvestmentPerformanceApi.csproj b/InvestmentPerformanceApi/InvestmentPerformanceApi.csproj new file mode 100644 index 00000000..ee25c2ff --- /dev/null +++ b/InvestmentPerformanceApi/InvestmentPerformanceApi.csproj @@ -0,0 +1,13 @@ + + + + net9.0 + enable + enable + + + + + + + diff --git a/InvestmentPerformanceApi/InvestmentPerformanceApi.http b/InvestmentPerformanceApi/InvestmentPerformanceApi.http new file mode 100644 index 00000000..002cb631 --- /dev/null +++ b/InvestmentPerformanceApi/InvestmentPerformanceApi.http @@ -0,0 +1,6 @@ +@InvestmentPerformanceApi_HostAddress = http://localhost:5034 + +GET {{InvestmentPerformanceApi_HostAddress}}/weatherforecast/ +Accept: application/json + +### diff --git a/InvestmentPerformanceApi/Program.cs b/InvestmentPerformanceApi/Program.cs new file mode 100644 index 00000000..ff07ed82 --- /dev/null +++ b/InvestmentPerformanceApi/Program.cs @@ -0,0 +1,18 @@ +var builder = WebApplication.CreateBuilder(args); + +// Add services to the container. +// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi +builder.Services.AddOpenApi(); + +var app = builder.Build(); + +// Configure the HTTP request pipeline. +if (app.Environment.IsDevelopment()) +{ + app.MapOpenApi(); +} + +app.UseHttpsRedirection(); + +app.Run(); + diff --git a/InvestmentPerformanceApi/Properties/launchSettings.json b/InvestmentPerformanceApi/Properties/launchSettings.json new file mode 100644 index 00000000..ded471a7 --- /dev/null +++ b/InvestmentPerformanceApi/Properties/launchSettings.json @@ -0,0 +1,23 @@ +{ + "$schema": "https://json.schemastore.org/launchsettings.json", + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "applicationUrl": "http://localhost:5034", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "applicationUrl": "https://localhost:7116;http://localhost:5034", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/InvestmentPerformanceApi/appsettings.Development.json b/InvestmentPerformanceApi/appsettings.Development.json new file mode 100644 index 00000000..0c208ae9 --- /dev/null +++ b/InvestmentPerformanceApi/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/InvestmentPerformanceApi/appsettings.json b/InvestmentPerformanceApi/appsettings.json new file mode 100644 index 00000000..10f68b8c --- /dev/null +++ b/InvestmentPerformanceApi/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +} From a6af21e918bf485bfbec6464027364817fd15841 Mon Sep 17 00:00:00 2001 From: Chase Swick Date: Tue, 13 May 2025 18:37:36 -0400 Subject: [PATCH 2/9] Move gitignore to top level --- InvestmentPerformanceApi/.gitignore => .gitignore | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename InvestmentPerformanceApi/.gitignore => .gitignore (100%) diff --git a/InvestmentPerformanceApi/.gitignore b/.gitignore similarity index 100% rename from InvestmentPerformanceApi/.gitignore rename to .gitignore From c9233574f8c589f6871da44b595e0b059ae4fe2c Mon Sep 17 00:00:00 2001 From: Chase Swick Date: Tue, 13 May 2025 19:01:43 -0400 Subject: [PATCH 3/9] Create models and mock repository --- InvestmentPerformanceApi/Models/Investment.cs | 24 +++++++++++++++++++ InvestmentPerformanceApi/Models/User.cs | 17 +++++++++++++ .../Repos/InvestmentRepository.cs | 23 ++++++++++++++++++ 3 files changed, 64 insertions(+) create mode 100644 InvestmentPerformanceApi/Models/Investment.cs create mode 100644 InvestmentPerformanceApi/Models/User.cs create mode 100644 InvestmentPerformanceApi/Repos/InvestmentRepository.cs diff --git a/InvestmentPerformanceApi/Models/Investment.cs b/InvestmentPerformanceApi/Models/Investment.cs new file mode 100644 index 00000000..e0e0002d --- /dev/null +++ b/InvestmentPerformanceApi/Models/Investment.cs @@ -0,0 +1,24 @@ +namespace InvestmentPerformanceApi.Models; + +public class Investment +{ + public int Id { get; set; } + + public string Name { get; set; } = string.Empty; + + public int UserId { get; set; } + + public int Shares { get; set; } + + public decimal CostBasisPerShare { get; set; } + + public decimal CurrentPrice { get; set; } + + public DateTime PurchaseDate { get; set; } + + public decimal CurrentValue => Shares * CurrentPrice; + + public string Term => (DateTime.UtcNow - PurchaseDate).TotalDays > 365 ? "Long Term" : "Short Term"; + + public decimal TotalGainOrLoss => CurrentValue - (Shares * CostBasisPerShare); +} diff --git a/InvestmentPerformanceApi/Models/User.cs b/InvestmentPerformanceApi/Models/User.cs new file mode 100644 index 00000000..934544a2 --- /dev/null +++ b/InvestmentPerformanceApi/Models/User.cs @@ -0,0 +1,17 @@ +namespace InvestmentPerformanceApi.Models; + +public class User +{ + public int Id { get; set; } + + public string FirstName { get; set; } + + public string LastName { get; set; } + + public string Email { get; set; } + + public DateTime CreatedAt { get; set; } = DateTime.UtcNow; + + public ICollection Investments { get; set; } +} + diff --git a/InvestmentPerformanceApi/Repos/InvestmentRepository.cs b/InvestmentPerformanceApi/Repos/InvestmentRepository.cs new file mode 100644 index 00000000..52b5baf5 --- /dev/null +++ b/InvestmentPerformanceApi/Repos/InvestmentRepository.cs @@ -0,0 +1,23 @@ +using InvestmentPerformanceApi.Models; + +namespace InvestmentPerformanceApi.Repos; + +public static class InvestmentRepository +{ + private static readonly List _investments = new() + { + new Investment { Id = 1, Name = "Apple", UserId = 1, Shares = 10, CostBasisPerShare = 150, CurrentPrice = 170, PurchaseDate = DateTime.UtcNow.AddMonths(-14) }, + new Investment { Id = 2, Name = "Google", UserId = 1, Shares = 5, CostBasisPerShare = 1200, CurrentPrice = 1400, PurchaseDate = DateTime.UtcNow.AddMonths(-10) }, + new Investment { Id = 2, Name = "Microsoft", UserId = 1, Shares = 2, CostBasisPerShare = 450, CurrentPrice = 435, PurchaseDate = DateTime.UtcNow.AddMonths(-2) }, + new Investment { Id = 2, Name = "Amazon", UserId = 1, Shares = 8, CostBasisPerShare = 2010, CurrentPrice = 1950, PurchaseDate = DateTime.UtcNow.AddMonths(-16) }, + new Investment { Id = 2, Name = "Oracle", UserId = 1, Shares = 15, CostBasisPerShare = 150, CurrentPrice = 162, PurchaseDate = DateTime.UtcNow.AddMonths(-1) }, + new Investment { Id = 2, Name = "Dell", UserId = 1, Shares = 5, CostBasisPerShare = 100, CurrentPrice = 107, PurchaseDate = DateTime.UtcNow.AddMonths(-5) }, + new Investment { Id = 2, Name = "Google", UserId = 2, Shares = 100, CostBasisPerShare = 1200, CurrentPrice = 1400, PurchaseDate = DateTime.UtcNow.AddMonths(-6) }, + new Investment { Id = 2, Name = "Nvidia", UserId = 2, Shares = 150, CostBasisPerShare = 1300, CurrentPrice = 1330, PurchaseDate = DateTime.UtcNow.AddMonths(-6) }, + new Investment { Id = 2, Name = "Netflix", UserId = 1, Shares = 12, CostBasisPerShare = 1050, CurrentPrice = 1130, PurchaseDate = DateTime.UtcNow.AddMonths(-3) }, + new Investment { Id = 2, Name = "Google", UserId = 3, Shares = 10000, CostBasisPerShare = 1200, CurrentPrice = 1400, PurchaseDate = DateTime.UtcNow.AddYears(-3) }, + }; + + public static IEnumerable GetByUserId(int userId) => _investments.Where(i => i.UserId == userId); + public static Investment? GetById(int userId, int investmentId) => _investments.FirstOrDefault(i => i.UserId == userId && i.Id == investmentId); +} From 24047a39f2543641f5309515ada34f306ff05877 Mon Sep 17 00:00:00 2001 From: Chase Swick Date: Tue, 13 May 2025 19:02:19 -0400 Subject: [PATCH 4/9] Update investment PK values --- .../Repos/InvestmentRepository.cs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/InvestmentPerformanceApi/Repos/InvestmentRepository.cs b/InvestmentPerformanceApi/Repos/InvestmentRepository.cs index 52b5baf5..560f0164 100644 --- a/InvestmentPerformanceApi/Repos/InvestmentRepository.cs +++ b/InvestmentPerformanceApi/Repos/InvestmentRepository.cs @@ -8,14 +8,14 @@ public static class InvestmentRepository { new Investment { Id = 1, Name = "Apple", UserId = 1, Shares = 10, CostBasisPerShare = 150, CurrentPrice = 170, PurchaseDate = DateTime.UtcNow.AddMonths(-14) }, new Investment { Id = 2, Name = "Google", UserId = 1, Shares = 5, CostBasisPerShare = 1200, CurrentPrice = 1400, PurchaseDate = DateTime.UtcNow.AddMonths(-10) }, - new Investment { Id = 2, Name = "Microsoft", UserId = 1, Shares = 2, CostBasisPerShare = 450, CurrentPrice = 435, PurchaseDate = DateTime.UtcNow.AddMonths(-2) }, - new Investment { Id = 2, Name = "Amazon", UserId = 1, Shares = 8, CostBasisPerShare = 2010, CurrentPrice = 1950, PurchaseDate = DateTime.UtcNow.AddMonths(-16) }, - new Investment { Id = 2, Name = "Oracle", UserId = 1, Shares = 15, CostBasisPerShare = 150, CurrentPrice = 162, PurchaseDate = DateTime.UtcNow.AddMonths(-1) }, - new Investment { Id = 2, Name = "Dell", UserId = 1, Shares = 5, CostBasisPerShare = 100, CurrentPrice = 107, PurchaseDate = DateTime.UtcNow.AddMonths(-5) }, - new Investment { Id = 2, Name = "Google", UserId = 2, Shares = 100, CostBasisPerShare = 1200, CurrentPrice = 1400, PurchaseDate = DateTime.UtcNow.AddMonths(-6) }, - new Investment { Id = 2, Name = "Nvidia", UserId = 2, Shares = 150, CostBasisPerShare = 1300, CurrentPrice = 1330, PurchaseDate = DateTime.UtcNow.AddMonths(-6) }, - new Investment { Id = 2, Name = "Netflix", UserId = 1, Shares = 12, CostBasisPerShare = 1050, CurrentPrice = 1130, PurchaseDate = DateTime.UtcNow.AddMonths(-3) }, - new Investment { Id = 2, Name = "Google", UserId = 3, Shares = 10000, CostBasisPerShare = 1200, CurrentPrice = 1400, PurchaseDate = DateTime.UtcNow.AddYears(-3) }, + new Investment { Id = 3, Name = "Microsoft", UserId = 1, Shares = 2, CostBasisPerShare = 450, CurrentPrice = 435, PurchaseDate = DateTime.UtcNow.AddMonths(-2) }, + new Investment { Id = 4, Name = "Amazon", UserId = 1, Shares = 8, CostBasisPerShare = 2010, CurrentPrice = 1950, PurchaseDate = DateTime.UtcNow.AddMonths(-16) }, + new Investment { Id = 5, Name = "Oracle", UserId = 1, Shares = 15, CostBasisPerShare = 150, CurrentPrice = 162, PurchaseDate = DateTime.UtcNow.AddMonths(-1) }, + new Investment { Id = 6, Name = "Dell", UserId = 1, Shares = 5, CostBasisPerShare = 100, CurrentPrice = 107, PurchaseDate = DateTime.UtcNow.AddMonths(-5) }, + new Investment { Id = 7, Name = "Google", UserId = 2, Shares = 100, CostBasisPerShare = 1200, CurrentPrice = 1400, PurchaseDate = DateTime.UtcNow.AddMonths(-6) }, + new Investment { Id = 8, Name = "Nvidia", UserId = 2, Shares = 150, CostBasisPerShare = 1300, CurrentPrice = 1330, PurchaseDate = DateTime.UtcNow.AddMonths(-6) }, + new Investment { Id = 9, Name = "Netflix", UserId = 1, Shares = 12, CostBasisPerShare = 1050, CurrentPrice = 1130, PurchaseDate = DateTime.UtcNow.AddMonths(-3) }, + new Investment { Id = 10, Name = "Google", UserId = 3, Shares = 10000, CostBasisPerShare = 1200, CurrentPrice = 1400, PurchaseDate = DateTime.UtcNow.AddYears(-3) }, }; public static IEnumerable GetByUserId(int userId) => _investments.Where(i => i.UserId == userId); From 7c1f2cd0805db5ec4224a6c8f32d060c77ffb940 Mon Sep 17 00:00:00 2001 From: Chase Swick Date: Tue, 13 May 2025 19:17:52 -0400 Subject: [PATCH 5/9] Create controller and update repo to non-static --- .../Controllers/InvestmentsController.cs | 40 +++++++++++++++++++ InvestmentPerformanceApi/Program.cs | 4 ++ .../Repos/InvestmentRepository.cs | 8 ++-- 3 files changed, 48 insertions(+), 4 deletions(-) create mode 100644 InvestmentPerformanceApi/Controllers/InvestmentsController.cs diff --git a/InvestmentPerformanceApi/Controllers/InvestmentsController.cs b/InvestmentPerformanceApi/Controllers/InvestmentsController.cs new file mode 100644 index 00000000..54e6559c --- /dev/null +++ b/InvestmentPerformanceApi/Controllers/InvestmentsController.cs @@ -0,0 +1,40 @@ +using Microsoft.AspNetCore.Mvc; +using InvestmentPerformanceApi.Repos; + +[ApiController] +[Route("api/users/{userId}/investments")] +public class InvestmentsController : ControllerBase +{ + private readonly InvestmentRepository _repository; + + public InvestmentsController(InvestmentRepository repository) + { + _repository = repository; + } + + [HttpGet] + public IActionResult GetInvestments(int userId) + { + var investments = _repository.GetByUserId(userId) + .Select(i => new { i.Id, i.Name }); + return Ok(investments); + } + + [HttpGet("{investmentId}")] + public IActionResult GetInvestmentDetails(int userId, int investmentId) + { + var investment = _repository.GetById(userId, investmentId); + if (investment == null) + return NotFound(); + + return Ok(new + { + investment.Shares, + investment.CostBasisPerShare, + investment.CurrentPrice, + investment.CurrentValue, + investment.Term, + TotalGainOrLoss = investment.TotalGainOrLoss + }); + } +} diff --git a/InvestmentPerformanceApi/Program.cs b/InvestmentPerformanceApi/Program.cs index ff07ed82..976a36cd 100644 --- a/InvestmentPerformanceApi/Program.cs +++ b/InvestmentPerformanceApi/Program.cs @@ -1,9 +1,13 @@ +using InvestmentPerformanceApi.Repos; + var builder = WebApplication.CreateBuilder(args); // Add services to the container. // Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi builder.Services.AddOpenApi(); +builder.Services.AddSingleton(); + var app = builder.Build(); // Configure the HTTP request pipeline. diff --git a/InvestmentPerformanceApi/Repos/InvestmentRepository.cs b/InvestmentPerformanceApi/Repos/InvestmentRepository.cs index 560f0164..26bee660 100644 --- a/InvestmentPerformanceApi/Repos/InvestmentRepository.cs +++ b/InvestmentPerformanceApi/Repos/InvestmentRepository.cs @@ -2,9 +2,9 @@ namespace InvestmentPerformanceApi.Repos; -public static class InvestmentRepository +public class InvestmentRepository { - private static readonly List _investments = new() + private readonly List _investments = new() { new Investment { Id = 1, Name = "Apple", UserId = 1, Shares = 10, CostBasisPerShare = 150, CurrentPrice = 170, PurchaseDate = DateTime.UtcNow.AddMonths(-14) }, new Investment { Id = 2, Name = "Google", UserId = 1, Shares = 5, CostBasisPerShare = 1200, CurrentPrice = 1400, PurchaseDate = DateTime.UtcNow.AddMonths(-10) }, @@ -18,6 +18,6 @@ public static class InvestmentRepository new Investment { Id = 10, Name = "Google", UserId = 3, Shares = 10000, CostBasisPerShare = 1200, CurrentPrice = 1400, PurchaseDate = DateTime.UtcNow.AddYears(-3) }, }; - public static IEnumerable GetByUserId(int userId) => _investments.Where(i => i.UserId == userId); - public static Investment? GetById(int userId, int investmentId) => _investments.FirstOrDefault(i => i.UserId == userId && i.Id == investmentId); + public IEnumerable GetByUserId(int userId) => _investments.Where(i => i.UserId == userId); + public Investment? GetById(int userId, int investmentId) => _investments.FirstOrDefault(i => i.UserId == userId && i.Id == investmentId); } From 4c1d2f45f9a7d22711517636cdd8862eb4f6d423 Mon Sep 17 00:00:00 2001 From: Chase Swick Date: Tue, 13 May 2025 19:37:50 -0400 Subject: [PATCH 6/9] Add controller mappings --- .../InvestmentPerformanceApi.http | 6 ------ InvestmentPerformanceApi/Program.cs | 6 +++++- .../Properties/launchSettings.json | 14 +++----------- 3 files changed, 8 insertions(+), 18 deletions(-) delete mode 100644 InvestmentPerformanceApi/InvestmentPerformanceApi.http diff --git a/InvestmentPerformanceApi/InvestmentPerformanceApi.http b/InvestmentPerformanceApi/InvestmentPerformanceApi.http deleted file mode 100644 index 002cb631..00000000 --- a/InvestmentPerformanceApi/InvestmentPerformanceApi.http +++ /dev/null @@ -1,6 +0,0 @@ -@InvestmentPerformanceApi_HostAddress = http://localhost:5034 - -GET {{InvestmentPerformanceApi_HostAddress}}/weatherforecast/ -Accept: application/json - -### diff --git a/InvestmentPerformanceApi/Program.cs b/InvestmentPerformanceApi/Program.cs index 976a36cd..f7bec517 100644 --- a/InvestmentPerformanceApi/Program.cs +++ b/InvestmentPerformanceApi/Program.cs @@ -6,6 +6,8 @@ // Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi builder.Services.AddOpenApi(); +builder.Services.AddControllers(); + builder.Services.AddSingleton(); var app = builder.Build(); @@ -16,7 +18,9 @@ app.MapOpenApi(); } -app.UseHttpsRedirection(); +//app.UseHttpsRedirection(); + +app.MapControllers(); app.Run(); diff --git a/InvestmentPerformanceApi/Properties/launchSettings.json b/InvestmentPerformanceApi/Properties/launchSettings.json index ded471a7..3d4d08eb 100644 --- a/InvestmentPerformanceApi/Properties/launchSettings.json +++ b/InvestmentPerformanceApi/Properties/launchSettings.json @@ -1,23 +1,15 @@ { "$schema": "https://json.schemastore.org/launchsettings.json", "profiles": { - "http": { + "NuixInvestmentApi": { "commandName": "Project", "dotnetRunMessages": true, "launchBrowser": false, - "applicationUrl": "http://localhost:5034", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - } - }, - "https": { - "commandName": "Project", - "dotnetRunMessages": true, - "launchBrowser": false, - "applicationUrl": "https://localhost:7116;http://localhost:5034", + "applicationUrl": "https://localhost:7116;http://localhost:5000", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } } } } + From 80b20d8744af0762ed25599464c0b4890869f25a Mon Sep 17 00:00:00 2001 From: Chase Swick Date: Tue, 13 May 2025 19:48:21 -0400 Subject: [PATCH 7/9] Add Swagger UI for easier testing --- .../InvestmentPerformanceApi.csproj | 1 + InvestmentPerformanceApi/Program.cs | 18 +++++++++++------- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/InvestmentPerformanceApi/InvestmentPerformanceApi.csproj b/InvestmentPerformanceApi/InvestmentPerformanceApi.csproj index ee25c2ff..a3b5dcc5 100644 --- a/InvestmentPerformanceApi/InvestmentPerformanceApi.csproj +++ b/InvestmentPerformanceApi/InvestmentPerformanceApi.csproj @@ -8,6 +8,7 @@ + diff --git a/InvestmentPerformanceApi/Program.cs b/InvestmentPerformanceApi/Program.cs index f7bec517..867f9bb1 100644 --- a/InvestmentPerformanceApi/Program.cs +++ b/InvestmentPerformanceApi/Program.cs @@ -1,22 +1,26 @@ using InvestmentPerformanceApi.Repos; +using Microsoft.OpenApi.Models; var builder = WebApplication.CreateBuilder(args); -// Add services to the container. -// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi -builder.Services.AddOpenApi(); - builder.Services.AddControllers(); +builder.Services.AddSwaggerGen(c => +{ + c.SwaggerDoc("v1", new OpenApiInfo { Title = "Investment Performance API", Version = "v1" }); +}); + builder.Services.AddSingleton(); var app = builder.Build(); // Configure the HTTP request pipeline. -if (app.Environment.IsDevelopment()) +app.UseSwagger(); +app.UseSwaggerUI(c => { - app.MapOpenApi(); -} + c.SwaggerEndpoint("/swagger/v1/swagger.json", "Investment Performance API v1"); + c.RoutePrefix = string.Empty; +}); //app.UseHttpsRedirection(); From 2c04e8626b89a29091d57166890cbd20fa3249bc Mon Sep 17 00:00:00 2001 From: Chase Swick Date: Tue, 13 May 2025 20:06:00 -0400 Subject: [PATCH 8/9] Add console logging and exception handling --- .../Controllers/InvestmentController.cs | 67 +++++++++++++++++++ .../Controllers/InvestmentsController.cs | 40 ----------- 2 files changed, 67 insertions(+), 40 deletions(-) create mode 100644 InvestmentPerformanceApi/Controllers/InvestmentController.cs delete mode 100644 InvestmentPerformanceApi/Controllers/InvestmentsController.cs diff --git a/InvestmentPerformanceApi/Controllers/InvestmentController.cs b/InvestmentPerformanceApi/Controllers/InvestmentController.cs new file mode 100644 index 00000000..5d9baef3 --- /dev/null +++ b/InvestmentPerformanceApi/Controllers/InvestmentController.cs @@ -0,0 +1,67 @@ +using Microsoft.AspNetCore.Mvc; +using InvestmentPerformanceApi.Repos; + +[ApiController] +[Route("api/users/{userId}/investments")] +public class InvestmentController : ControllerBase +{ + private readonly InvestmentRepository _repository; + private readonly ILogger _logger; + + public InvestmentController(InvestmentRepository repository, ILogger logger) + { + _repository = repository; + _logger = logger; + } + + [HttpGet] + public IActionResult GetInvestments(int userId) + { + try + { + _logger.LogInformation("Fetching investments for user {UserId}", userId); + + var investments = _repository.GetByUserId(userId) + .Select(i => new { i.Id, i.Name }); + + return Ok(investments); + } + catch (Exception ex) + { + _logger.LogError(ex, "An error occurred while fetching investments for user {UserId}", userId); + return StatusCode(500, new { message = "Something went wrong while processing your request." }); + } + } + + [HttpGet("{investmentId}")] + public IActionResult GetInvestmentDetails(int userId, int investmentId) + { + try + { + _logger.LogInformation("Fetching details for investment {InvestmentId} for user {UserId}", investmentId, userId); + + var investment = _repository.GetById(userId, investmentId); + + if (investment == null) + { + _logger.LogWarning("Investment {InvestmentId} not found for user {UserId}", investmentId, userId); + return NotFound(); + } + + return Ok(new + { + investment.Shares, + investment.CostBasisPerShare, + investment.CurrentPrice, + investment.CurrentValue, + investment.Term, + TotalGainOrLoss = investment.TotalGainOrLoss + }); + } + catch (Exception ex) + { + _logger.LogError(ex, "An error occurred while fetching investment {InvestmentId} for user {UserId}", investmentId, userId); + return StatusCode(500, new { message = "Something went wrong while processing your request." }); + } + } +} diff --git a/InvestmentPerformanceApi/Controllers/InvestmentsController.cs b/InvestmentPerformanceApi/Controllers/InvestmentsController.cs deleted file mode 100644 index 54e6559c..00000000 --- a/InvestmentPerformanceApi/Controllers/InvestmentsController.cs +++ /dev/null @@ -1,40 +0,0 @@ -using Microsoft.AspNetCore.Mvc; -using InvestmentPerformanceApi.Repos; - -[ApiController] -[Route("api/users/{userId}/investments")] -public class InvestmentsController : ControllerBase -{ - private readonly InvestmentRepository _repository; - - public InvestmentsController(InvestmentRepository repository) - { - _repository = repository; - } - - [HttpGet] - public IActionResult GetInvestments(int userId) - { - var investments = _repository.GetByUserId(userId) - .Select(i => new { i.Id, i.Name }); - return Ok(investments); - } - - [HttpGet("{investmentId}")] - public IActionResult GetInvestmentDetails(int userId, int investmentId) - { - var investment = _repository.GetById(userId, investmentId); - if (investment == null) - return NotFound(); - - return Ok(new - { - investment.Shares, - investment.CostBasisPerShare, - investment.CurrentPrice, - investment.CurrentValue, - investment.Term, - TotalGainOrLoss = investment.TotalGainOrLoss - }); - } -} From 370e388747745777c69ef431499749a596ca22d6 Mon Sep 17 00:00:00 2001 From: Chase Swick Date: Tue, 13 May 2025 20:44:14 -0400 Subject: [PATCH 9/9] Create tests for investment controller --- .../InvestmentControllerTests.cs | 112 ++++++++++++++++++ .../InvestmentPerformanceApi.Tests.csproj | 26 ++++ .../Controllers/InvestmentController.cs | 6 +- .../Repos/IInvestmentRepository.cs | 10 ++ .../Repos/InvestmentRepository.cs | 2 +- ReadMe.md | 42 ++++--- 6 files changed, 173 insertions(+), 25 deletions(-) create mode 100644 InvestmentPerformanceApi.Tests/InvestmentControllerTests.cs create mode 100644 InvestmentPerformanceApi.Tests/InvestmentPerformanceApi.Tests.csproj create mode 100644 InvestmentPerformanceApi/Repos/IInvestmentRepository.cs diff --git a/InvestmentPerformanceApi.Tests/InvestmentControllerTests.cs b/InvestmentPerformanceApi.Tests/InvestmentControllerTests.cs new file mode 100644 index 00000000..35218d4e --- /dev/null +++ b/InvestmentPerformanceApi.Tests/InvestmentControllerTests.cs @@ -0,0 +1,112 @@ +using Xunit; +using Moq; +using Microsoft.Extensions.Logging; +using Microsoft.AspNetCore.Mvc; +using System.Collections.Generic; +using System.Linq; +using System; + +using InvestmentPerformanceApi.Controllers; +using InvestmentPerformanceApi.Models; +using InvestmentPerformanceApi.Repos; + +public class InvestmentControllerTests +{ + private readonly Mock _mockRepo; + private readonly Mock> _mockLogger; + private readonly InvestmentController _controller; + + public InvestmentControllerTests() + { + _mockRepo = new Mock(); + _mockLogger = new Mock>(); + _controller = new InvestmentController(_mockRepo.Object, _mockLogger.Object); + } + + [Fact] + public void GetInvestments_ReturnsOk_WhenDataExists() + { + // Arrange + int userId = 1; + _mockRepo.Setup(r => r.GetByUserId(userId)).Returns(new List + { + new Investment { Id = 1, Name = "Apple", UserId = userId }, + new Investment { Id = 2, Name = "Google", UserId = userId } + }); + + // Act + var result = _controller.GetInvestments(userId); + + // Assert + var okResult = Assert.IsType(result); + var investments = Assert.IsAssignableFrom>(okResult.Value); + Assert.Equal(2, investments.Count()); + } + + [Fact] + public void GetInvestments_Returns500_OnException() + { + // Arrange + int userId = 1; + _mockRepo.Setup(r => r.GetByUserId(userId)).Throws(new Exception("DB failure")); + + // Act + var result = _controller.GetInvestments(userId); + + // Assert + var errorResult = Assert.IsType(result); + Assert.Equal(500, errorResult.StatusCode); + } + + [Fact] + public void GetInvestmentDetails_ReturnsOk_WhenFound() + { + // Arrange + int userId = 1, investmentId = 1; + _mockRepo.Setup(r => r.GetById(userId, investmentId)).Returns(new Investment + { + Id = investmentId, + UserId = userId, + Shares = 10, + CostBasisPerShare = 100, + CurrentPrice = 150, + PurchaseDate = DateTime.UtcNow.AddMonths(-6) + }); + + // Act + var result = _controller.GetInvestmentDetails(userId, investmentId); + + // Assert + var okResult = Assert.IsType(result); + Assert.NotNull(okResult.Value); + } + + [Fact] + public void GetInvestmentDetails_ReturnsNotFound_WhenNull() + { + // Arrange + int userId = 1, investmentId = 99; + _mockRepo.Setup(r => r.GetById(userId, investmentId)).Returns((Investment)null); + + // Act + var result = _controller.GetInvestmentDetails(userId, investmentId); + + // Assert + Assert.IsType(result); + } + + [Fact] + public void GetInvestmentDetails_Returns500_OnException() + { + // Arrange + int userId = 1, investmentId = 1; + _mockRepo.Setup(r => r.GetById(userId, investmentId)).Throws(new Exception("Unexpected failure")); + + // Act + var result = _controller.GetInvestmentDetails(userId, investmentId); + + // Assert + var errorResult = Assert.IsType(result); + Assert.Equal(500, errorResult.StatusCode); + } +} diff --git a/InvestmentPerformanceApi.Tests/InvestmentPerformanceApi.Tests.csproj b/InvestmentPerformanceApi.Tests/InvestmentPerformanceApi.Tests.csproj new file mode 100644 index 00000000..22b1e3a0 --- /dev/null +++ b/InvestmentPerformanceApi.Tests/InvestmentPerformanceApi.Tests.csproj @@ -0,0 +1,26 @@ + + + + net9.0 + enable + enable + false + + + + + + + + + + + + + + + + + + + diff --git a/InvestmentPerformanceApi/Controllers/InvestmentController.cs b/InvestmentPerformanceApi/Controllers/InvestmentController.cs index 5d9baef3..2b81f1e8 100644 --- a/InvestmentPerformanceApi/Controllers/InvestmentController.cs +++ b/InvestmentPerformanceApi/Controllers/InvestmentController.cs @@ -1,14 +1,16 @@ using Microsoft.AspNetCore.Mvc; using InvestmentPerformanceApi.Repos; +namespace InvestmentPerformanceApi.Controllers; + [ApiController] [Route("api/users/{userId}/investments")] public class InvestmentController : ControllerBase { - private readonly InvestmentRepository _repository; + private readonly IInvestmentRepository _repository; private readonly ILogger _logger; - public InvestmentController(InvestmentRepository repository, ILogger logger) + public InvestmentController(IInvestmentRepository repository, ILogger logger) { _repository = repository; _logger = logger; diff --git a/InvestmentPerformanceApi/Repos/IInvestmentRepository.cs b/InvestmentPerformanceApi/Repos/IInvestmentRepository.cs new file mode 100644 index 00000000..cf6fa932 --- /dev/null +++ b/InvestmentPerformanceApi/Repos/IInvestmentRepository.cs @@ -0,0 +1,10 @@ +using InvestmentPerformanceApi.Models; + +namespace InvestmentPerformanceApi.Repos; + +public interface IInvestmentRepository +{ + IEnumerable GetByUserId(int userId); + + Investment? GetById(int userId, int investmentId); +} diff --git a/InvestmentPerformanceApi/Repos/InvestmentRepository.cs b/InvestmentPerformanceApi/Repos/InvestmentRepository.cs index 26bee660..c20028b1 100644 --- a/InvestmentPerformanceApi/Repos/InvestmentRepository.cs +++ b/InvestmentPerformanceApi/Repos/InvestmentRepository.cs @@ -2,7 +2,7 @@ namespace InvestmentPerformanceApi.Repos; -public class InvestmentRepository +public class InvestmentRepository : IInvestmentRepository { private readonly List _investments = new() { diff --git a/ReadMe.md b/ReadMe.md index ad2afefb..99d3f973 100644 --- a/ReadMe.md +++ b/ReadMe.md @@ -1,28 +1,26 @@ -# Coding Exercise -> This repository holds coding exercises for candidates going through the hiring process. +# InvestmentPerformanceApi -You should have been assigned one of the coding exercises in this list. More details can be found in the specific md file for that assignment. +This repository contains the Investment Performance API, which provides functionality for managing and retrieving investment details for users. +Test data is available in InvestmentRepository.cs. Database creation was foregone for simplicity sake. -Instructions: Fork this repository, do the assigned work, and submit a pull request for review. +## Getting Started -[Investment Performance Web API](InvestmentPerformanceWebAPI.md#investment-performance-web-api) +### Clone the repository +git clone https://github.com/Swicky97/NuixCodeExercise.git +open project in visual studio -[Online Ordering SQL](OnlineOrderingSQL.md#online-ordering) +### Restore installed dependencies +run dotnet restore -# License +### Run the api +cd InvestmentPerformanceApi from proj base +select InvestmentPerformanceApi.csproj as startup project (if not already selected) +run dotnet run +SwaggerUI is available at the base url or endpoints can be tested manually by navigating to the controller endpoints + -- localhost:5000/api/users/{userId}/investments + -- localhost:5000/api/users/{userId}/investments/{investmentId} -``` -Copyright 2021 Nuix - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -``` \ No newline at end of file +### Run tests +cd InvestmentPerformanceApi.Tests from proj base +run dotnet test +