feat(backend): implement .NET 8 Clean Architecture with CQRS, EF Core MySQL and unit tests #4

Merged
Bryan.bano merged 2 commits from feature/backend-clean-architecture into develop 2026-10-20 15:05:10 +00:00
75 changed files with 2132 additions and 0 deletions
Showing only changes of commit bfc20f6fcd - Show all commits

View File

@ -96,3 +96,20 @@ jobs:
run: | run: |
cd src/frontend cd src/frontend
npm run build -- --configuration production npm run build -- --configuration production
validate-backend:
name: Build & Test Backend (.NET)
runs-on: dotnet-runner
steps:
- name: Checkout Code
run: |
command -v git >/dev/null || (apt-get update && apt-get install -y --no-install-recommends git)
git config --global --add safe.directory "*"
git init
git remote add origin https://git.bryan-bano.com/Bryan.bano/PORTFOLIO.git 2>/dev/null || git remote set-url origin https://git.bryan-bano.com/Bryan.bano/PORTFOLIO.git
git fetch --depth 1 origin ${{ github.sha }}
git checkout --force FETCH_HEAD
- name: Build & Run Backend Unit Tests
run: |
dotnet test src/backend/Portfolio.sln -c Release --verbosity normal

View File

@ -96,3 +96,20 @@ jobs:
run: | run: |
cd src/frontend cd src/frontend
npm run build -- --configuration production npm run build -- --configuration production
validate-backend:
name: Build & Test Backend (.NET)
runs-on: dotnet-runner
steps:
- name: Checkout Code
run: |
command -v git >/dev/null || (apt-get update && apt-get install -y --no-install-recommends git)
git config --global --add safe.directory "*"
git init
git remote add origin https://git.bryan-bano.com/Bryan.bano/PORTFOLIO.git 2>/dev/null || git remote set-url origin https://git.bryan-bano.com/Bryan.bano/PORTFOLIO.git
git fetch --depth 1 origin ${{ github.sha }}
git checkout --force FETCH_HEAD
- name: Build & Run Backend Unit Tests
run: |
dotnet test src/backend/Portfolio.sln -c Release --verbosity normal

6
.gitignore vendored
View File

@ -41,3 +41,9 @@ desktop.ini
*.pem *.pem
*.key *.key
*.pfx *.pfx
# .NET Configuration & Sensitive AppSettings
**/appsettings.json
**/appsettings.Production.json
!**/appsettingsdevelop.json

57
src/backend/Portfolio.sln Normal file
View File

@ -0,0 +1,57 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.0.31903.59
MinimumVisualStudioVersion = 10.0.40219.1
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{2FE66466-0214-4DBE-BF8A-F9101D6E2FF7}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Portfolio.Domain", "src\Portfolio.Domain\Portfolio.Domain.csproj", "{36CD767F-7762-4EDF-B71E-94A78B020FE0}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Portfolio.Application", "src\Portfolio.Application\Portfolio.Application.csproj", "{A279BB0E-7D67-4BCB-81FC-F487737A568C}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Portfolio.Infrastructure", "src\Portfolio.Infrastructure\Portfolio.Infrastructure.csproj", "{484FA7A3-6CAA-4C40-8E51-EDB22B5F6D39}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Portfolio.WebApi", "src\Portfolio.WebApi\Portfolio.WebApi.csproj", "{3FD30B3E-9B89-4882-B075-BDD2CAE348ED}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{E7DB5FDA-B947-4EC2-9868-421E8E4FCCD6}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Portfolio.UnitTests", "tests\Portfolio.UnitTests\Portfolio.UnitTests.csproj", "{EF9CB490-2460-42FF-A58D-616191B87DAC}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{36CD767F-7762-4EDF-B71E-94A78B020FE0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{36CD767F-7762-4EDF-B71E-94A78B020FE0}.Debug|Any CPU.Build.0 = Debug|Any CPU
{36CD767F-7762-4EDF-B71E-94A78B020FE0}.Release|Any CPU.ActiveCfg = Release|Any CPU
{36CD767F-7762-4EDF-B71E-94A78B020FE0}.Release|Any CPU.Build.0 = Release|Any CPU
{A279BB0E-7D67-4BCB-81FC-F487737A568C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A279BB0E-7D67-4BCB-81FC-F487737A568C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A279BB0E-7D67-4BCB-81FC-F487737A568C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A279BB0E-7D67-4BCB-81FC-F487737A568C}.Release|Any CPU.Build.0 = Release|Any CPU
{484FA7A3-6CAA-4C40-8E51-EDB22B5F6D39}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{484FA7A3-6CAA-4C40-8E51-EDB22B5F6D39}.Debug|Any CPU.Build.0 = Debug|Any CPU
{484FA7A3-6CAA-4C40-8E51-EDB22B5F6D39}.Release|Any CPU.ActiveCfg = Release|Any CPU
{484FA7A3-6CAA-4C40-8E51-EDB22B5F6D39}.Release|Any CPU.Build.0 = Release|Any CPU
{3FD30B3E-9B89-4882-B075-BDD2CAE348ED}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3FD30B3E-9B89-4882-B075-BDD2CAE348ED}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3FD30B3E-9B89-4882-B075-BDD2CAE348ED}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3FD30B3E-9B89-4882-B075-BDD2CAE348ED}.Release|Any CPU.Build.0 = Release|Any CPU
{EF9CB490-2460-42FF-A58D-616191B87DAC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{EF9CB490-2460-42FF-A58D-616191B87DAC}.Debug|Any CPU.Build.0 = Debug|Any CPU
{EF9CB490-2460-42FF-A58D-616191B87DAC}.Release|Any CPU.ActiveCfg = Release|Any CPU
{EF9CB490-2460-42FF-A58D-616191B87DAC}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{36CD767F-7762-4EDF-B71E-94A78B020FE0} = {2FE66466-0214-4DBE-BF8A-F9101D6E2FF7}
{A279BB0E-7D67-4BCB-81FC-F487737A568C} = {2FE66466-0214-4DBE-BF8A-F9101D6E2FF7}
{484FA7A3-6CAA-4C40-8E51-EDB22B5F6D39} = {2FE66466-0214-4DBE-BF8A-F9101D6E2FF7}
{3FD30B3E-9B89-4882-B075-BDD2CAE348ED} = {2FE66466-0214-4DBE-BF8A-F9101D6E2FF7}
{EF9CB490-2460-42FF-A58D-616191B87DAC} = {E7DB5FDA-B947-4EC2-9868-421E8E4FCCD6}
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,36 @@
using FluentValidation;
using MediatR;
namespace Portfolio.Application.Common.Behaviors;
public sealed class ValidationBehavior<TRequest, TResponse>(IEnumerable<IValidator<TRequest>> validators)
: IPipelineBehavior<TRequest, TResponse>
where TRequest : notnull
{
public async Task<TResponse> Handle(
TRequest request,
RequestHandlerDelegate<TResponse> next,
CancellationToken cancellationToken)
{
if (!validators.Any())
{
return await next();
}
var context = new ValidationContext<TRequest>(request);
var validationResults = await Task.WhenAll(
validators.Select(v => v.ValidateAsync(context, cancellationToken)));
var failures = validationResults
.SelectMany(r => r.Errors)
.Where(f => f is not null)
.ToList();
if (failures.Count != 0)
{
throw new ValidationException(failures);
}
return await next();
}
}

View File

@ -0,0 +1,15 @@
using Portfolio.Domain.Entities;
namespace Portfolio.Application.Common.Interfaces;
public interface IJwtTokenGenerator
{
string GenerateAccessToken(User user);
string GenerateRefreshToken();
}
public interface IPasswordHasher
{
string Hash(string password);
bool Verify(string password, string passwordHash);
}

View File

@ -0,0 +1,25 @@
using System.Reflection;
using FluentValidation;
using MediatR;
using Microsoft.Extensions.DependencyInjection;
using Portfolio.Application.Common.Behaviors;
namespace Portfolio.Application;
public static class DependencyInjection
{
public static IServiceCollection AddApplication(this IServiceCollection services)
{
var assembly = Assembly.GetExecutingAssembly();
services.AddMediatR(cfg =>
{
cfg.RegisterServicesFromAssembly(assembly);
cfg.AddBehavior(typeof(IPipelineBehavior<,>), typeof(ValidationBehavior<,>));
});
services.AddValidatorsFromAssembly(assembly);
return services;
}
}

View File

@ -0,0 +1,39 @@
using MediatR;
using Portfolio.Application.Features.Guestbook.DTOs;
using Portfolio.Domain.Entities;
using Portfolio.Domain.Enums;
using Portfolio.Domain.Interfaces;
namespace Portfolio.Application.Features.Guestbook.Commands;
public sealed record CreateGuestbookMessageCommand(
string SenderName,
string Message,
MessageOrigin Origin = MessageOrigin.WebForm,
string? SenderContact = null
) : IRequest<GuestbookMessageResponseDto>;
public sealed class CreateGuestbookMessageCommandHandler(IInteractiveMessageRepository messageRepository)
: IRequestHandler<CreateGuestbookMessageCommand, GuestbookMessageResponseDto>
{
public async Task<GuestbookMessageResponseDto> Handle(CreateGuestbookMessageCommand request, CancellationToken cancellationToken)
{
var message = InteractiveMessage.Create(
request.SenderName,
request.Message,
request.Origin,
request.SenderContact
);
await messageRepository.AddAsync(message, cancellationToken);
await messageRepository.SaveChangesAsync(cancellationToken);
return new GuestbookMessageResponseDto(
message.Id,
message.SenderName,
message.Message,
message.Origin,
message.CreatedAtUtc
);
}
}

View File

@ -0,0 +1,18 @@
using Portfolio.Domain.Enums;
namespace Portfolio.Application.Features.Guestbook.DTOs;
public sealed record GuestbookMessageResponseDto(
Guid Id,
string SenderName,
string Message,
MessageOrigin Origin,
DateTime CreatedAtUtc
);
public sealed record CreateGuestbookMessageRequestDto(
string SenderName,
string Message,
MessageOrigin Origin = MessageOrigin.WebForm,
string? SenderContact = null
);

View File

@ -0,0 +1,24 @@
using MediatR;
using Portfolio.Application.Features.Guestbook.DTOs;
using Portfolio.Domain.Interfaces;
namespace Portfolio.Application.Features.Guestbook.Queries;
public sealed record GetGuestbookMessagesQuery(int Limit = 50) : IRequest<IReadOnlyList<GuestbookMessageResponseDto>>;
public sealed class GetGuestbookMessagesQueryHandler(IInteractiveMessageRepository messageRepository)
: IRequestHandler<GetGuestbookMessagesQuery, IReadOnlyList<GuestbookMessageResponseDto>>
{
public async Task<IReadOnlyList<GuestbookMessageResponseDto>> Handle(GetGuestbookMessagesQuery request, CancellationToken cancellationToken)
{
var messages = await messageRepository.GetRecentApprovedAsync(request.Limit, cancellationToken);
return messages.Select(m => new GuestbookMessageResponseDto(
m.Id,
m.SenderName,
m.Message,
m.Origin,
m.CreatedAtUtc
)).ToList();
}
}

View File

@ -0,0 +1,19 @@
using FluentValidation;
using Portfolio.Application.Features.Guestbook.Commands;
namespace Portfolio.Application.Features.Guestbook.Validators;
public sealed class CreateGuestbookMessageCommandValidator : AbstractValidator<CreateGuestbookMessageCommand>
{
public CreateGuestbookMessageCommandValidator()
{
RuleFor(x => x.SenderName)
.NotEmpty().WithMessage("El nombre o alias del remitente es obligatorio.")
.MaximumLength(60).WithMessage("El nombre no puede exceder 60 caracteres.");
RuleFor(x => x.Message)
.NotEmpty().WithMessage("El mensaje no puede estar vacío.")
.MinimumLength(3).WithMessage("El mensaje debe contener al menos 3 caracteres.")
.MaximumLength(500).WithMessage("El mensaje no puede exceder 500 caracteres.");
}
}

View File

@ -0,0 +1,42 @@
using MediatR;
using Portfolio.Application.Features.Leaderboard.DTOs;
using Portfolio.Domain.Entities;
using Portfolio.Domain.Interfaces;
namespace Portfolio.Application.Features.Leaderboard.Commands;
public sealed record SubmitGameScoreCommand(
string PlayerName,
string GameName,
int Score,
int DurationSeconds,
string? CountryCode = null
) : IRequest<GameScoreResponseDto>;
public sealed class SubmitGameScoreCommandHandler(IGameScoreRepository scoreRepository)
: IRequestHandler<SubmitGameScoreCommand, GameScoreResponseDto>
{
public async Task<GameScoreResponseDto> Handle(SubmitGameScoreCommand request, CancellationToken cancellationToken)
{
var gameScore = GameScore.Create(
request.PlayerName,
request.GameName,
request.Score,
request.DurationSeconds,
request.CountryCode
);
await scoreRepository.AddAsync(gameScore, cancellationToken);
await scoreRepository.SaveChangesAsync(cancellationToken);
return new GameScoreResponseDto(
gameScore.Id,
gameScore.PlayerName,
gameScore.GameName,
gameScore.Score,
gameScore.DurationSeconds,
gameScore.CountryCode,
gameScore.CreatedAtUtc
);
}
}

View File

@ -0,0 +1,19 @@
namespace Portfolio.Application.Features.Leaderboard.DTOs;
public sealed record GameScoreResponseDto(
Guid Id,
string PlayerName,
string GameName,
int Score,
int DurationSeconds,
string? CountryCode,
DateTime CreatedAtUtc
);
public sealed record SubmitGameScoreRequestDto(
string PlayerName,
string GameName,
int Score,
int DurationSeconds,
string? CountryCode = null
);

View File

@ -0,0 +1,27 @@
using MediatR;
using Portfolio.Application.Features.Leaderboard.DTOs;
using Portfolio.Domain.Interfaces;
namespace Portfolio.Application.Features.Leaderboard.Queries;
public sealed record GetLeaderboardQuery(string GameName = "Minesweeper", int Limit = 10)
: IRequest<IReadOnlyList<GameScoreResponseDto>>;
public sealed class GetLeaderboardQueryHandler(IGameScoreRepository scoreRepository)
: IRequestHandler<GetLeaderboardQuery, IReadOnlyList<GameScoreResponseDto>>
{
public async Task<IReadOnlyList<GameScoreResponseDto>> Handle(GetLeaderboardQuery request, CancellationToken cancellationToken)
{
var scores = await scoreRepository.GetTopScoresAsync(request.GameName, request.Limit, cancellationToken);
return scores.Select(s => new GameScoreResponseDto(
s.Id,
s.PlayerName,
s.GameName,
s.Score,
s.DurationSeconds,
s.CountryCode,
s.CreatedAtUtc
)).ToList();
}
}

View File

@ -0,0 +1,24 @@
using FluentValidation;
using Portfolio.Application.Features.Leaderboard.Commands;
namespace Portfolio.Application.Features.Leaderboard.Validators;
public sealed class SubmitGameScoreCommandValidator : AbstractValidator<SubmitGameScoreCommand>
{
public SubmitGameScoreCommandValidator()
{
RuleFor(x => x.PlayerName)
.NotEmpty().WithMessage("El nombre del jugador es obligatorio.")
.MaximumLength(30).WithMessage("El nombre no puede exceder 30 caracteres.");
RuleFor(x => x.GameName)
.NotEmpty().WithMessage("El nombre del juego es obligatorio.")
.MaximumLength(30);
RuleFor(x => x.Score)
.GreaterThanOrEqualTo(0).WithMessage("La puntuación no puede ser negativa.");
RuleFor(x => x.DurationSeconds)
.GreaterThanOrEqualTo(0).WithMessage("La duración no puede ser negativa.");
}
}

View File

@ -0,0 +1,15 @@
namespace Portfolio.Application.Features.Projects.DTOs;
public sealed record ProjectResponseDto(
Guid Id,
string Slug,
string Title,
string ShortDescription,
string FullDescription,
string RepositoryUrl,
string? LiveDemoUrl,
string? ThumbnailUrl,
bool IsFeatured,
ushort DisplayOrder,
IReadOnlyList<string> Skills
);

View File

@ -0,0 +1,32 @@
using MediatR;
using Portfolio.Application.Features.Projects.DTOs;
using Portfolio.Domain.Exceptions;
using Portfolio.Domain.Interfaces;
namespace Portfolio.Application.Features.Projects.Queries;
public sealed record GetProjectBySlugQuery(string Slug) : IRequest<ProjectResponseDto>;
public sealed class GetProjectBySlugQueryHandler(IProjectRepository projectRepository)
: IRequestHandler<GetProjectBySlugQuery, ProjectResponseDto>
{
public async Task<ProjectResponseDto> Handle(GetProjectBySlugQuery request, CancellationToken cancellationToken)
{
var p = await projectRepository.GetBySlugAsync(request.Slug, cancellationToken)
?? throw new NotFoundException("Project", request.Slug);
return new ProjectResponseDto(
p.Id,
p.Slug,
p.Title,
p.ShortDescription,
p.FullDescription,
p.RepositoryUrl,
p.LiveDemoUrl,
p.ThumbnailUrl,
p.IsFeatured,
p.DisplayOrder,
p.ProjectSkills.Select(ps => ps.Skill.Name).ToList()
);
}
}

View File

@ -0,0 +1,30 @@
using MediatR;
using Portfolio.Application.Features.Projects.DTOs;
using Portfolio.Domain.Interfaces;
namespace Portfolio.Application.Features.Projects.Queries;
public sealed record GetProjectsQuery(bool FeaturedOnly = false) : IRequest<IReadOnlyList<ProjectResponseDto>>;
public sealed class GetProjectsQueryHandler(IProjectRepository projectRepository)
: IRequestHandler<GetProjectsQuery, IReadOnlyList<ProjectResponseDto>>
{
public async Task<IReadOnlyList<ProjectResponseDto>> Handle(GetProjectsQuery request, CancellationToken cancellationToken)
{
var projects = await projectRepository.GetAllAsync(request.FeaturedOnly, cancellationToken);
return projects.Select(p => new ProjectResponseDto(
p.Id,
p.Slug,
p.Title,
p.ShortDescription,
p.FullDescription,
p.RepositoryUrl,
p.LiveDemoUrl,
p.ThumbnailUrl,
p.IsFeatured,
p.DisplayOrder,
p.ProjectSkills.Select(ps => ps.Skill.Name).ToList()
)).ToList();
}
}

View File

@ -0,0 +1,13 @@
using Portfolio.Domain.Enums;
namespace Portfolio.Application.Features.Skills.DTOs;
public sealed record SkillResponseDto(
Guid Id,
string Name,
SkillCategory Category,
string? IconSlug,
byte ProficiencyPercentage,
ushort DisplayOrder,
bool IsFeatured
);

View File

@ -0,0 +1,27 @@
using MediatR;
using Portfolio.Application.Features.Skills.DTOs;
using Portfolio.Domain.Enums;
using Portfolio.Domain.Interfaces;
namespace Portfolio.Application.Features.Skills.Queries;
public sealed record GetSkillsQuery(SkillCategory? Category = null) : IRequest<IReadOnlyList<SkillResponseDto>>;
public sealed class GetSkillsQueryHandler(ISkillRepository skillRepository)
: IRequestHandler<GetSkillsQuery, IReadOnlyList<SkillResponseDto>>
{
public async Task<IReadOnlyList<SkillResponseDto>> Handle(GetSkillsQuery request, CancellationToken cancellationToken)
{
var skills = await skillRepository.GetAllAsync(request.Category, cancellationToken);
return skills.Select(s => new SkillResponseDto(
s.Id,
s.Name,
s.Category,
s.IconSlug,
s.ProficiencyPercentage,
s.DisplayOrder,
s.IsFeatured
)).ToList();
}
}

View File

@ -0,0 +1,19 @@
namespace Portfolio.Application.Features.Telemetry.DTOs;
public sealed record ServerTelemetryDto(
string Status,
string Region,
string Provider,
string Architecture,
string RuntimeVersion,
TimeSpan Uptime,
double ProcessMemoryMb,
int ActiveThreads,
DateTime ServerTimeUtc
);
public sealed record PingResponseDto(
string Message,
long LatencyMs,
DateTime TimestampUtc
);

View File

@ -0,0 +1,34 @@
using System.Diagnostics;
using System.Runtime.InteropServices;
using MediatR;
using Portfolio.Application.Features.Telemetry.DTOs;
namespace Portfolio.Application.Features.Telemetry.Queries;
public sealed record GetServerTelemetryQuery : IRequest<ServerTelemetryDto>;
public sealed class GetServerTelemetryQueryHandler : IRequestHandler<GetServerTelemetryQuery, ServerTelemetryDto>
{
private static readonly DateTime StartTime = DateTime.UtcNow;
public Task<ServerTelemetryDto> Handle(GetServerTelemetryQuery request, CancellationToken cancellationToken)
{
var process = Process.GetCurrentProcess();
var memoryMb = Math.Round((double)process.WorkingSet64 / (1024 * 1024), 2);
var uptime = DateTime.UtcNow - StartTime;
var dto = new ServerTelemetryDto(
Status: "OPERATIONAL",
Region: "us-ashburn-1",
Provider: "Oracle Cloud Infrastructure (OCI)",
Architecture: $"{RuntimeInformation.OSDescription} ({RuntimeInformation.ProcessArchitecture})",
RuntimeVersion: RuntimeInformation.FrameworkDescription,
Uptime: uptime,
ProcessMemoryMb: memoryMb,
ActiveThreads: process.Threads.Count,
ServerTimeUtc: DateTime.UtcNow
);
return Task.FromResult(dto);
}
}

View File

@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<ProjectReference Include="..\Portfolio.Domain\Portfolio.Domain.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="FluentValidation.DependencyInjectionExtensions" Version="12.2.0" />
<PackageReference Include="MediatR" Version="14.2.0" />
</ItemGroup>
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

View File

@ -0,0 +1,7 @@
namespace Portfolio.Domain.Common;
public abstract class BaseEntity
{
public Guid Id { get; protected set; } = Guid.NewGuid();
public DateTime CreatedAtUtc { get; protected set; } = DateTime.UtcNow;
}

View File

@ -0,0 +1,42 @@
using Portfolio.Domain.Common;
using Portfolio.Domain.Enums;
namespace Portfolio.Domain.Entities;
public sealed class ContactInquiry : BaseEntity
{
public string FullNameOrCompany { get; private set; } = string.Empty;
public string Email { get; private set; } = string.Empty;
public string? Phone { get; private set; }
public string ServiceType { get; private set; } = "General";
public string ProjectDetails { get; private set; } = string.Empty;
public InquiryStatus Status { get; private set; } = InquiryStatus.New;
public string? IpAddress { get; private set; }
public DateTime? RepliedAtUtc { get; private set; }
private ContactInquiry() { }
public static ContactInquiry Create(
string fullNameOrCompany,
string email,
string projectDetails,
string serviceType = "General",
string? phone = null,
string? ipAddress = null)
{
ArgumentException.ThrowIfNullOrWhiteSpace(fullNameOrCompany);
ArgumentException.ThrowIfNullOrWhiteSpace(email);
ArgumentException.ThrowIfNullOrWhiteSpace(projectDetails);
return new ContactInquiry
{
FullNameOrCompany = fullNameOrCompany.Trim(),
Email = email.Trim().ToLowerInvariant(),
ProjectDetails = projectDetails.Trim(),
ServiceType = serviceType.Trim(),
Phone = phone?.Trim(),
IpAddress = ipAddress,
Status = InquiryStatus.New
};
}
}

View File

@ -0,0 +1,34 @@
using Portfolio.Domain.Common;
namespace Portfolio.Domain.Entities;
public sealed class GameScore : BaseEntity
{
public string PlayerName { get; private set; } = string.Empty;
public string GameName { get; private set; } = "Minesweeper";
public int Score { get; private set; }
public int DurationSeconds { get; private set; }
public string? CountryCode { get; private set; }
private GameScore() { }
public static GameScore Create(
string playerName,
string gameName,
int score,
int durationSeconds,
string? countryCode = null)
{
ArgumentException.ThrowIfNullOrWhiteSpace(playerName);
ArgumentException.ThrowIfNullOrWhiteSpace(gameName);
return new GameScore
{
PlayerName = playerName.Trim(),
GameName = gameName.Trim().ToLowerInvariant(),
Score = score,
DurationSeconds = durationSeconds,
CountryCode = countryCode?.Trim().ToUpperInvariant()
};
}
}

View File

@ -0,0 +1,34 @@
using Portfolio.Domain.Common;
using Portfolio.Domain.Enums;
namespace Portfolio.Domain.Entities;
public sealed class InteractiveMessage : BaseEntity
{
public string SenderName { get; private set; } = string.Empty;
public string? SenderContact { get; private set; }
public string Message { get; private set; } = string.Empty;
public MessageOrigin Origin { get; private set; }
public bool IsApproved { get; private set; } = true;
private InteractiveMessage() { }
public static InteractiveMessage Create(
string senderName,
string message,
MessageOrigin origin = MessageOrigin.Terminal,
string? senderContact = null)
{
ArgumentException.ThrowIfNullOrWhiteSpace(senderName);
ArgumentException.ThrowIfNullOrWhiteSpace(message);
return new InteractiveMessage
{
SenderName = senderName.Trim(),
Message = message.Trim(),
Origin = origin,
SenderContact = senderContact?.Trim(),
IsApproved = true
};
}
}

View File

@ -0,0 +1,49 @@
using Portfolio.Domain.Common;
namespace Portfolio.Domain.Entities;
public sealed class Project : BaseEntity
{
public string Slug { get; private set; } = string.Empty;
public string Title { get; private set; } = string.Empty;
public string ShortDescription { get; private set; } = string.Empty;
public string FullDescription { get; private set; } = string.Empty;
public string RepositoryUrl { get; private set; } = string.Empty;
public string? LiveDemoUrl { get; private set; }
public string? ThumbnailUrl { get; private set; }
public bool IsFeatured { get; private set; }
public ushort DisplayOrder { get; private set; }
public DateTime? UpdatedAtUtc { get; private set; }
public ICollection<ProjectSkill> ProjectSkills { get; private set; } = [];
private Project() { }
public static Project Create(
string slug,
string title,
string shortDescription,
string fullDescription,
string repositoryUrl,
string? liveDemoUrl = null,
string? thumbnailUrl = null,
bool isFeatured = false,
ushort displayOrder = 0)
{
ArgumentException.ThrowIfNullOrWhiteSpace(slug);
ArgumentException.ThrowIfNullOrWhiteSpace(title);
return new Project
{
Slug = slug.Trim().ToLowerInvariant(),
Title = title.Trim(),
ShortDescription = shortDescription.Trim(),
FullDescription = fullDescription.Trim(),
RepositoryUrl = repositoryUrl.Trim(),
LiveDemoUrl = liveDemoUrl?.Trim(),
ThumbnailUrl = thumbnailUrl?.Trim(),
IsFeatured = isFeatured,
DisplayOrder = displayOrder
};
}
}

View File

@ -0,0 +1,10 @@
namespace Portfolio.Domain.Entities;
public sealed class ProjectSkill
{
public Guid ProjectId { get; set; }
public Project Project { get; set; } = null!;
public Guid SkillId { get; set; }
public Skill Skill { get; set; } = null!;
}

View File

@ -0,0 +1,35 @@
using Portfolio.Domain.Common;
namespace Portfolio.Domain.Entities;
public sealed class RefreshToken : BaseEntity
{
public Guid UserId { get; private set; }
public User User { get; private set; } = null!;
public string TokenHash { get; private set; } = string.Empty;
public DateTime ExpiresAtUtc { get; private set; }
public bool IsRevoked { get; private set; }
public string? ReplacedByToken { get; private set; }
public bool IsActive => !IsRevoked && DateTime.UtcNow < ExpiresAtUtc;
private RefreshToken() { }
public static RefreshToken Create(Guid userId, string tokenHash, DateTime expiresAtUtc)
{
return new RefreshToken
{
UserId = userId,
TokenHash = tokenHash,
ExpiresAtUtc = expiresAtUtc,
IsRevoked = false
};
}
public void Revoke(string? replacedBy = null)
{
IsRevoked = true;
ReplacedByToken = replacedBy;
}
}

View File

@ -0,0 +1,39 @@
using Portfolio.Domain.Common;
using Portfolio.Domain.Enums;
namespace Portfolio.Domain.Entities;
public sealed class Skill : BaseEntity
{
public string Name { get; private set; } = string.Empty;
public SkillCategory Category { get; private set; }
public string? IconSlug { get; private set; }
public byte ProficiencyPercentage { get; private set; }
public ushort DisplayOrder { get; private set; }
public bool IsFeatured { get; private set; }
public ICollection<ProjectSkill> ProjectSkills { get; private set; } = [];
private Skill() { }
public static Skill Create(
string name,
SkillCategory category,
string? iconSlug = null,
byte proficiency = 85,
ushort displayOrder = 0,
bool isFeatured = true)
{
ArgumentException.ThrowIfNullOrWhiteSpace(name);
return new Skill
{
Name = name.Trim(),
Category = category,
IconSlug = iconSlug?.Trim(),
ProficiencyPercentage = Math.Min((byte)100, proficiency),
DisplayOrder = displayOrder,
IsFeatured = isFeatured
};
}
}

View File

@ -0,0 +1,31 @@
using Portfolio.Domain.Common;
namespace Portfolio.Domain.Entities;
public sealed class User : BaseEntity
{
public string Username { get; private set; } = string.Empty;
public string Email { get; private set; } = string.Empty;
public string PasswordHash { get; private set; } = string.Empty;
public string Role { get; private set; } = "Admin";
public DateTime? UpdatedAtUtc { get; private set; }
public ICollection<RefreshToken> RefreshTokens { get; private set; } = [];
private User() { }
public static User Create(string username, string email, string passwordHash, string role = "Admin")
{
ArgumentException.ThrowIfNullOrWhiteSpace(username);
ArgumentException.ThrowIfNullOrWhiteSpace(email);
ArgumentException.ThrowIfNullOrWhiteSpace(passwordHash);
return new User
{
Username = username.Trim(),
Email = email.Trim().ToLowerInvariant(),
PasswordHash = passwordHash,
Role = role
};
}
}

View File

@ -0,0 +1,9 @@
namespace Portfolio.Domain.Enums;
public enum InquiryStatus
{
New = 1,
Read = 2,
Replied = 3,
Archived = 4
}

View File

@ -0,0 +1,8 @@
namespace Portfolio.Domain.Enums;
public enum MessageOrigin
{
Terminal = 1,
WebForm = 2,
ApiTester = 3
}

View File

@ -0,0 +1,10 @@
namespace Portfolio.Domain.Enums;
public enum SkillCategory
{
Backend = 1,
Frontend = 2,
Database = 3,
DevOps = 4,
Architecture = 5
}

View File

@ -0,0 +1,6 @@
namespace Portfolio.Domain.Exceptions;
public class DomainException(string message) : Exception(message);
public class NotFoundException(string entityName, object key)
: DomainException($"Entity '{entityName}' with key ({key}) was not found.");

View File

@ -0,0 +1,10 @@
using Portfolio.Domain.Entities;
namespace Portfolio.Domain.Interfaces;
public interface IGameScoreRepository
{
Task<IReadOnlyList<GameScore>> GetTopScoresAsync(string gameName, int limit = 10, CancellationToken ct = default);
Task AddAsync(GameScore score, CancellationToken ct = default);
Task<int> SaveChangesAsync(CancellationToken ct = default);
}

View File

@ -0,0 +1,10 @@
using Portfolio.Domain.Entities;
namespace Portfolio.Domain.Interfaces;
public interface IInteractiveMessageRepository
{
Task<IReadOnlyList<InteractiveMessage>> GetRecentApprovedAsync(int limit = 50, CancellationToken ct = default);
Task AddAsync(InteractiveMessage message, CancellationToken ct = default);
Task<int> SaveChangesAsync(CancellationToken ct = default);
}

View File

@ -0,0 +1,14 @@
using Portfolio.Domain.Entities;
namespace Portfolio.Domain.Interfaces;
public interface IProjectRepository
{
Task<IReadOnlyList<Project>> GetAllAsync(bool featuredOnly = false, CancellationToken ct = default);
Task<Project?> GetBySlugAsync(string slug, CancellationToken ct = default);
Task<Project?> GetByIdAsync(Guid id, CancellationToken ct = default);
Task AddAsync(Project project, CancellationToken ct = default);
void Update(Project project);
void Delete(Project project);
Task<int> SaveChangesAsync(CancellationToken ct = default);
}

View File

@ -0,0 +1,12 @@
using Portfolio.Domain.Entities;
using Portfolio.Domain.Enums;
namespace Portfolio.Domain.Interfaces;
public interface ISkillRepository
{
Task<IReadOnlyList<Skill>> GetAllAsync(SkillCategory? category = null, CancellationToken ct = default);
Task<Skill?> GetByIdAsync(Guid id, CancellationToken ct = default);
Task AddAsync(Skill skill, CancellationToken ct = default);
Task<int> SaveChangesAsync(CancellationToken ct = default);
}

View File

@ -0,0 +1,12 @@
using Portfolio.Domain.Entities;
namespace Portfolio.Domain.Interfaces;
public interface IUserRepository
{
Task<User?> GetByUsernameOrEmailAsync(string identifier, CancellationToken ct = default);
Task<User?> GetByIdAsync(Guid id, CancellationToken ct = default);
Task AddRefreshTokenAsync(RefreshToken refreshToken, CancellationToken ct = default);
Task<RefreshToken?> GetRefreshTokenAsync(string tokenHash, CancellationToken ct = default);
Task<int> SaveChangesAsync(CancellationToken ct = default);
}

View File

@ -0,0 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

View File

@ -0,0 +1,38 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Portfolio.Application.Common.Interfaces;
using Portfolio.Domain.Interfaces;
using Portfolio.Infrastructure.Persistence.Context;
using Portfolio.Infrastructure.Persistence.Repositories;
using Portfolio.Infrastructure.Security;
namespace Portfolio.Infrastructure;
public static class DependencyInjection
{
public static IServiceCollection AddInfrastructure(this IServiceCollection services, IConfiguration configuration)
{
var connectionString = configuration.GetConnectionString("DefaultConnection")
?? "Server=localhost;Port=3306;Database=portfolio_db;User=root;Password=;CharSet=utf8mb4;";
services.AddDbContext<PortfolioDbContext>(options =>
{
options.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString), mysqlOptions =>
{
mysqlOptions.EnableRetryOnFailure(maxRetryCount: 3, maxRetryDelay: TimeSpan.FromSeconds(5), errorNumbersToAdd: null);
});
});
services.AddScoped<IProjectRepository, ProjectRepository>();
services.AddScoped<ISkillRepository, SkillRepository>();
services.AddScoped<IInteractiveMessageRepository, InteractiveMessageRepository>();
services.AddScoped<IGameScoreRepository, GameScoreRepository>();
services.AddScoped<IUserRepository, UserRepository>();
services.AddSingleton<IPasswordHasher, PasswordHasher>();
services.AddScoped<IJwtTokenGenerator, JwtTokenGenerator>();
return services;
}
}

View File

@ -0,0 +1,28 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Portfolio.Domain.Entities;
namespace Portfolio.Infrastructure.Persistence.Configurations;
public sealed class ContactInquiryConfiguration : IEntityTypeConfiguration<ContactInquiry>
{
public void Configure(EntityTypeBuilder<ContactInquiry> builder)
{
builder.ToTable("contact_inquiries");
builder.HasKey(c => c.Id);
builder.Property(c => c.Id).HasColumnName("id").HasMaxLength(36);
builder.Property(c => c.FullNameOrCompany).HasColumnName("full_name_or_company").HasMaxLength(100).IsRequired();
builder.Property(c => c.Email).HasColumnName("email").HasMaxLength(100).IsRequired();
builder.Property(c => c.Phone).HasColumnName("phone").HasMaxLength(30);
builder.Property(c => c.ServiceType).HasColumnName("service_type").HasMaxLength(50).IsRequired();
builder.Property(c => c.ProjectDetails).HasColumnName("project_details").HasColumnType("TEXT").IsRequired();
builder.Property(c => c.Status).HasColumnName("status").HasConversion<string>().HasMaxLength(20).IsRequired();
builder.Property(c => c.IpAddress).HasColumnName("ip_address").HasMaxLength(45);
builder.Property(c => c.CreatedAtUtc).HasColumnName("created_at_utc").IsRequired();
builder.Property(c => c.RepliedAtUtc).HasColumnName("replied_at_utc");
builder.HasIndex(c => new { c.Status, c.CreatedAtUtc });
}
}

View File

@ -0,0 +1,25 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Portfolio.Domain.Entities;
namespace Portfolio.Infrastructure.Persistence.Configurations;
public sealed class GameScoreConfiguration : IEntityTypeConfiguration<GameScore>
{
public void Configure(EntityTypeBuilder<GameScore> builder)
{
builder.ToTable("game_scores");
builder.HasKey(g => g.Id);
builder.Property(g => g.Id).HasColumnName("id").HasMaxLength(36);
builder.Property(g => g.PlayerName).HasColumnName("player_name").HasMaxLength(30).IsRequired();
builder.Property(g => g.GameName).HasColumnName("game_name").HasMaxLength(30).IsRequired();
builder.Property(g => g.Score).HasColumnName("score").IsRequired();
builder.Property(g => g.DurationSeconds).HasColumnName("duration_seconds").IsRequired();
builder.Property(g => g.CountryCode).HasColumnName("country_code").HasMaxLength(5);
builder.Property(g => g.CreatedAtUtc).HasColumnName("created_at_utc").IsRequired();
builder.HasIndex(g => new { g.GameName, g.Score });
}
}

View File

@ -0,0 +1,25 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Portfolio.Domain.Entities;
namespace Portfolio.Infrastructure.Persistence.Configurations;
public sealed class InteractiveMessageConfiguration : IEntityTypeConfiguration<InteractiveMessage>
{
public void Configure(EntityTypeBuilder<InteractiveMessage> builder)
{
builder.ToTable("interactive_messages");
builder.HasKey(m => m.Id);
builder.Property(m => m.Id).HasColumnName("id").HasMaxLength(36);
builder.Property(m => m.SenderName).HasColumnName("sender_name").HasMaxLength(60).IsRequired();
builder.Property(m => m.SenderContact).HasColumnName("sender_contact").HasMaxLength(100);
builder.Property(m => m.Message).HasColumnName("message").HasMaxLength(500).IsRequired();
builder.Property(m => m.Origin).HasColumnName("origin").HasConversion<string>().HasMaxLength(20).IsRequired();
builder.Property(m => m.IsApproved).HasColumnName("is_approved").IsRequired();
builder.Property(m => m.CreatedAtUtc).HasColumnName("created_at_utc").IsRequired();
builder.HasIndex(m => new { m.IsApproved, m.CreatedAtUtc });
}
}

View File

@ -0,0 +1,32 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Portfolio.Domain.Entities;
namespace Portfolio.Infrastructure.Persistence.Configurations;
public sealed class ProjectConfiguration : IEntityTypeConfiguration<Project>
{
public void Configure(EntityTypeBuilder<Project> builder)
{
builder.ToTable("projects");
builder.HasKey(p => p.Id);
builder.Property(p => p.Id).HasColumnName("id").HasMaxLength(36);
builder.Property(p => p.Slug).HasColumnName("slug").HasMaxLength(100).IsRequired();
builder.HasIndex(p => p.Slug).IsUnique();
builder.Property(p => p.Title).HasColumnName("title").HasMaxLength(150).IsRequired();
builder.Property(p => p.ShortDescription).HasColumnName("short_description").HasMaxLength(255).IsRequired();
builder.Property(p => p.FullDescription).HasColumnName("full_description").HasColumnType("TEXT").IsRequired();
builder.Property(p => p.RepositoryUrl).HasColumnName("repository_url").HasMaxLength(255).IsRequired();
builder.Property(p => p.LiveDemoUrl).HasColumnName("live_demo_url").HasMaxLength(255);
builder.Property(p => p.ThumbnailUrl).HasColumnName("thumbnail_url").HasMaxLength(255);
builder.Property(p => p.IsFeatured).HasColumnName("is_featured").IsRequired();
builder.Property(p => p.DisplayOrder).HasColumnName("display_order").IsRequired();
builder.Property(p => p.CreatedAtUtc).HasColumnName("created_at_utc").IsRequired();
builder.Property(p => p.UpdatedAtUtc).HasColumnName("updated_at_utc");
builder.HasIndex(p => new { p.IsFeatured, p.DisplayOrder });
}
}

View File

@ -0,0 +1,27 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Portfolio.Domain.Entities;
namespace Portfolio.Infrastructure.Persistence.Configurations;
public sealed class ProjectSkillConfiguration : IEntityTypeConfiguration<ProjectSkill>
{
public void Configure(EntityTypeBuilder<ProjectSkill> builder)
{
builder.ToTable("project_skills");
builder.HasKey(ps => new { ps.ProjectId, ps.SkillId });
builder.Property(ps => ps.ProjectId).HasColumnName("project_id").HasMaxLength(36);
builder.Property(ps => ps.SkillId).HasColumnName("skill_id").HasMaxLength(36);
builder.HasOne(ps => ps.Project)
.WithMany(p => p.ProjectSkills)
.HasForeignKey(ps => ps.ProjectId)
.OnDelete(DeleteBehavior.Cascade);
builder.HasOne(ps => ps.Skill)
.WithMany(s => s.ProjectSkills)
.HasForeignKey(ps => ps.SkillId)
.OnDelete(DeleteBehavior.Restrict);
}
}

View File

@ -0,0 +1,30 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Portfolio.Domain.Entities;
namespace Portfolio.Infrastructure.Persistence.Configurations;
public sealed class RefreshTokenConfiguration : IEntityTypeConfiguration<RefreshToken>
{
public void Configure(EntityTypeBuilder<RefreshToken> builder)
{
builder.ToTable("refresh_tokens");
builder.HasKey(rt => rt.Id);
builder.Property(rt => rt.Id).HasColumnName("id").HasMaxLength(36);
builder.Property(rt => rt.UserId).HasColumnName("user_id").HasMaxLength(36).IsRequired();
builder.Property(rt => rt.TokenHash).HasColumnName("token_hash").HasMaxLength(255).IsRequired();
builder.Property(rt => rt.ExpiresAtUtc).HasColumnName("expires_at_utc").IsRequired();
builder.Property(rt => rt.IsRevoked).HasColumnName("is_revoked").IsRequired();
builder.Property(rt => rt.ReplacedByToken).HasColumnName("replaced_by_token").HasMaxLength(255);
builder.Property(rt => rt.CreatedAtUtc).HasColumnName("created_at_utc").IsRequired();
builder.HasOne(rt => rt.User)
.WithMany(u => u.RefreshTokens)
.HasForeignKey(rt => rt.UserId)
.OnDelete(DeleteBehavior.Cascade);
builder.HasIndex(rt => new { rt.UserId, rt.IsRevoked, rt.ExpiresAtUtc });
}
}

View File

@ -0,0 +1,28 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Portfolio.Domain.Entities;
namespace Portfolio.Infrastructure.Persistence.Configurations;
public sealed class SkillConfiguration : IEntityTypeConfiguration<Skill>
{
public void Configure(EntityTypeBuilder<Skill> builder)
{
builder.ToTable("skills");
builder.HasKey(s => s.Id);
builder.Property(s => s.Id).HasColumnName("id").HasMaxLength(36);
builder.Property(s => s.Name).HasColumnName("name").HasMaxLength(50).IsRequired();
builder.HasIndex(s => s.Name).IsUnique();
builder.Property(s => s.Category).HasColumnName("category").HasConversion<string>().HasMaxLength(30).IsRequired();
builder.Property(s => s.IconSlug).HasColumnName("icon_slug").HasMaxLength(50);
builder.Property(s => s.ProficiencyPercentage).HasColumnName("proficiency_percentage").IsRequired();
builder.Property(s => s.DisplayOrder).HasColumnName("display_order").IsRequired();
builder.Property(s => s.IsFeatured).HasColumnName("is_featured").IsRequired();
builder.Property(s => s.CreatedAtUtc).HasColumnName("created_at_utc").IsRequired();
builder.HasIndex(s => new { s.Category, s.DisplayOrder });
}
}

View File

@ -0,0 +1,27 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Portfolio.Domain.Entities;
namespace Portfolio.Infrastructure.Persistence.Configurations;
public sealed class UserConfiguration : IEntityTypeConfiguration<User>
{
public void Configure(EntityTypeBuilder<User> builder)
{
builder.ToTable("users");
builder.HasKey(u => u.Id);
builder.Property(u => u.Id).HasColumnName("id").HasMaxLength(36);
builder.Property(u => u.Username).HasColumnName("username").HasMaxLength(50).IsRequired();
builder.HasIndex(u => u.Username).IsUnique();
builder.Property(u => u.Email).HasColumnName("email").HasMaxLength(100).IsRequired();
builder.HasIndex(u => u.Email).IsUnique();
builder.Property(u => u.PasswordHash).HasColumnName("password_hash").HasMaxLength(255).IsRequired();
builder.Property(u => u.Role).HasColumnName("role").HasMaxLength(20).IsRequired();
builder.Property(u => u.CreatedAtUtc).HasColumnName("created_at_utc").IsRequired();
builder.Property(u => u.UpdatedAtUtc).HasColumnName("updated_at_utc");
}
}

View File

@ -0,0 +1,23 @@
using System.Reflection;
using Microsoft.EntityFrameworkCore;
using Portfolio.Domain.Entities;
namespace Portfolio.Infrastructure.Persistence.Context;
public sealed class PortfolioDbContext(DbContextOptions<PortfolioDbContext> options) : DbContext(options)
{
public DbSet<Project> Projects => Set<Project>();
public DbSet<Skill> Skills => Set<Skill>();
public DbSet<ProjectSkill> ProjectSkills => Set<ProjectSkill>();
public DbSet<InteractiveMessage> InteractiveMessages => Set<InteractiveMessage>();
public DbSet<GameScore> GameScores => Set<GameScore>();
public DbSet<ContactInquiry> ContactInquiries => Set<ContactInquiry>();
public DbSet<User> Users => Set<User>();
public DbSet<RefreshToken> RefreshTokens => Set<RefreshToken>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());
}
}

View File

@ -0,0 +1,30 @@
using Microsoft.EntityFrameworkCore;
using Portfolio.Domain.Entities;
using Portfolio.Domain.Interfaces;
using Portfolio.Infrastructure.Persistence.Context;
namespace Portfolio.Infrastructure.Persistence.Repositories;
public sealed class GameScoreRepository(PortfolioDbContext context) : IGameScoreRepository
{
public async Task<IReadOnlyList<GameScore>> GetTopScoresAsync(string gameName, int limit = 10, CancellationToken ct = default)
{
return await context.GameScores
.AsNoTracking()
.Where(g => g.GameName == gameName.ToLower())
.OrderByDescending(g => g.Score)
.ThenBy(g => g.DurationSeconds)
.Take(limit)
.ToListAsync(ct);
}
public async Task AddAsync(GameScore score, CancellationToken ct = default)
{
await context.GameScores.AddAsync(score, ct);
}
public Task<int> SaveChangesAsync(CancellationToken ct = default)
{
return context.SaveChangesAsync(ct);
}
}

View File

@ -0,0 +1,29 @@
using Microsoft.EntityFrameworkCore;
using Portfolio.Domain.Entities;
using Portfolio.Domain.Interfaces;
using Portfolio.Infrastructure.Persistence.Context;
namespace Portfolio.Infrastructure.Persistence.Repositories;
public sealed class InteractiveMessageRepository(PortfolioDbContext context) : IInteractiveMessageRepository
{
public async Task<IReadOnlyList<InteractiveMessage>> GetRecentApprovedAsync(int limit = 50, CancellationToken ct = default)
{
return await context.InteractiveMessages
.AsNoTracking()
.Where(m => m.IsApproved)
.OrderByDescending(m => m.CreatedAtUtc)
.Take(limit)
.ToListAsync(ct);
}
public async Task AddAsync(InteractiveMessage message, CancellationToken ct = default)
{
await context.InteractiveMessages.AddAsync(message, ct);
}
public Task<int> SaveChangesAsync(CancellationToken ct = default)
{
return context.SaveChangesAsync(ct);
}
}

View File

@ -0,0 +1,64 @@
using Microsoft.EntityFrameworkCore;
using Portfolio.Domain.Entities;
using Portfolio.Domain.Interfaces;
using Portfolio.Infrastructure.Persistence.Context;
namespace Portfolio.Infrastructure.Persistence.Repositories;
public sealed class ProjectRepository(PortfolioDbContext context) : IProjectRepository
{
public async Task<IReadOnlyList<Project>> GetAllAsync(bool featuredOnly = false, CancellationToken ct = default)
{
var query = context.Projects
.AsNoTracking()
.Include(p => p.ProjectSkills)
.ThenInclude(ps => ps.Skill)
.AsQueryable();
if (featuredOnly)
{
query = query.Where(p => p.IsFeatured);
}
return await query
.OrderBy(p => p.DisplayOrder)
.ThenByDescending(p => p.CreatedAtUtc)
.ToListAsync(ct);
}
public async Task<Project?> GetBySlugAsync(string slug, CancellationToken ct = default)
{
return await context.Projects
.AsNoTracking()
.Include(p => p.ProjectSkills)
.ThenInclude(ps => ps.Skill)
.FirstOrDefaultAsync(p => p.Slug == slug.ToLower(), ct);
}
public async Task<Project?> GetByIdAsync(Guid id, CancellationToken ct = default)
{
return await context.Projects
.Include(p => p.ProjectSkills)
.FirstOrDefaultAsync(p => p.Id == id, ct);
}
public async Task AddAsync(Project project, CancellationToken ct = default)
{
await context.Projects.AddAsync(project, ct);
}
public void Update(Project project)
{
context.Projects.Update(project);
}
public void Delete(Project project)
{
context.Projects.Remove(project);
}
public Task<int> SaveChangesAsync(CancellationToken ct = default)
{
return context.SaveChangesAsync(ct);
}
}

View File

@ -0,0 +1,40 @@
using Microsoft.EntityFrameworkCore;
using Portfolio.Domain.Entities;
using Portfolio.Domain.Enums;
using Portfolio.Domain.Interfaces;
using Portfolio.Infrastructure.Persistence.Context;
namespace Portfolio.Infrastructure.Persistence.Repositories;
public sealed class SkillRepository(PortfolioDbContext context) : ISkillRepository
{
public async Task<IReadOnlyList<Skill>> GetAllAsync(SkillCategory? category = null, CancellationToken ct = default)
{
var query = context.Skills.AsNoTracking().AsQueryable();
if (category.HasValue)
{
query = query.Where(s => s.Category == category.Value);
}
return await query
.OrderBy(s => s.Category)
.ThenBy(s => s.DisplayOrder)
.ToListAsync(ct);
}
public async Task<Skill?> GetByIdAsync(Guid id, CancellationToken ct = default)
{
return await context.Skills.FindAsync([id], ct);
}
public async Task AddAsync(Skill skill, CancellationToken ct = default)
{
await context.Skills.AddAsync(skill, ct);
}
public Task<int> SaveChangesAsync(CancellationToken ct = default)
{
return context.SaveChangesAsync(ct);
}
}

View File

@ -0,0 +1,41 @@
using Microsoft.EntityFrameworkCore;
using Portfolio.Domain.Entities;
using Portfolio.Domain.Interfaces;
using Portfolio.Infrastructure.Persistence.Context;
namespace Portfolio.Infrastructure.Persistence.Repositories;
public sealed class UserRepository(PortfolioDbContext context) : IUserRepository
{
public async Task<User?> GetByUsernameOrEmailAsync(string identifier, CancellationToken ct = default)
{
var lower = identifier.ToLower().Trim();
return await context.Users
.Include(u => u.RefreshTokens)
.FirstOrDefaultAsync(u => u.Username.ToLower() == lower || u.Email.ToLower() == lower, ct);
}
public async Task<User?> GetByIdAsync(Guid id, CancellationToken ct = default)
{
return await context.Users
.Include(u => u.RefreshTokens)
.FirstOrDefaultAsync(u => u.Id == id, ct);
}
public async Task AddRefreshTokenAsync(RefreshToken refreshToken, CancellationToken ct = default)
{
await context.RefreshTokens.AddAsync(refreshToken, ct);
}
public async Task<RefreshToken?> GetRefreshTokenAsync(string tokenHash, CancellationToken ct = default)
{
return await context.RefreshTokens
.Include(rt => rt.User)
.FirstOrDefaultAsync(rt => rt.TokenHash == tokenHash, ct);
}
public Task<int> SaveChangesAsync(CancellationToken ct = default)
{
return context.SaveChangesAsync(ct);
}
}

View File

@ -0,0 +1,22 @@
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<ProjectReference Include="..\Portfolio.Application\Portfolio.Application.csproj" />
<ProjectReference Include="..\Portfolio.Domain\Portfolio.Domain.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="BCrypt.Net-Next" Version="4.2.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.10" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="8.0.10" />
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="8.0.2" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.23.0" />
</ItemGroup>
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

View File

@ -0,0 +1,52 @@
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using Portfolio.Application.Common.Interfaces;
using Portfolio.Domain.Entities;
namespace Portfolio.Infrastructure.Security;
public sealed class JwtTokenGenerator(IConfiguration configuration) : IJwtTokenGenerator
{
public string GenerateAccessToken(User user)
{
var secret = configuration["JwtSettings:Secret"]
?? "DefaultDevelopmentSecretKeyMustBeOverriddenInProduction123456789";
var issuer = configuration["JwtSettings:Issuer"] ?? "PortfolioBackend";
var audience = configuration["JwtSettings:Audience"] ?? "PortfolioFrontend";
var expiryMinutes = int.TryParse(configuration["JwtSettings:ExpiryMinutes"], out var exp) ? exp : 60;
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret));
var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, user.Id.ToString()),
new Claim(JwtRegisteredClaimNames.UniqueName, user.Username),
new Claim(JwtRegisteredClaimNames.Email, user.Email),
new Claim(ClaimTypes.Role, user.Role),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
};
var token = new JwtSecurityToken(
issuer: issuer,
audience: audience,
claims: claims,
expires: DateTime.UtcNow.AddMinutes(expiryMinutes),
signingCredentials: credentials
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
public string GenerateRefreshToken()
{
var randomBytes = new byte[64];
using var rng = RandomNumberGenerator.Create();
rng.GetBytes(randomBytes);
return Convert.ToBase64String(randomBytes);
}
}

View File

@ -0,0 +1,16 @@
using Portfolio.Application.Common.Interfaces;
namespace Portfolio.Infrastructure.Security;
public sealed class PasswordHasher : IPasswordHasher
{
public string Hash(string password)
{
return BCrypt.Net.BCrypt.HashPassword(password, workFactor: 11);
}
public bool Verify(string password, string passwordHash)
{
return BCrypt.Net.BCrypt.Verify(password, passwordHash);
}
}

View File

@ -0,0 +1,41 @@
using MediatR;
using Microsoft.AspNetCore.Mvc;
using Portfolio.Application.Features.Guestbook.Commands;
using Portfolio.Application.Features.Guestbook.DTOs;
using Portfolio.Application.Features.Guestbook.Queries;
namespace Portfolio.WebApi.Controllers;
[ApiController]
[Route("api/v1/[controller]")]
[Produces("application/json")]
public sealed class GuestbookController(ISender sender) : ControllerBase
{
[HttpGet]
[ProducesResponseType(typeof(IReadOnlyList<GuestbookMessageResponseDto>), StatusCodes.Status200OK)]
public async Task<ActionResult<IReadOnlyList<GuestbookMessageResponseDto>>> GetRecent(
[FromQuery] int limit = 50,
CancellationToken ct = default)
{
var result = await sender.Send(new GetGuestbookMessagesQuery(limit), ct);
return Ok(result);
}
[HttpPost]
[ProducesResponseType(typeof(GuestbookMessageResponseDto), StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<ActionResult<GuestbookMessageResponseDto>> Create(
[FromBody] CreateGuestbookMessageRequestDto request,
CancellationToken ct = default)
{
var command = new CreateGuestbookMessageCommand(
request.SenderName,
request.Message,
request.Origin,
request.SenderContact
);
var result = await sender.Send(command, ct);
return StatusCode(StatusCodes.Status201Created, result);
}
}

View File

@ -0,0 +1,43 @@
using MediatR;
using Microsoft.AspNetCore.Mvc;
using Portfolio.Application.Features.Leaderboard.Commands;
using Portfolio.Application.Features.Leaderboard.DTOs;
using Portfolio.Application.Features.Leaderboard.Queries;
namespace Portfolio.WebApi.Controllers;
[ApiController]
[Route("api/v1/[controller]")]
[Produces("application/json")]
public sealed class LeaderboardController(ISender sender) : ControllerBase
{
[HttpGet]
[ProducesResponseType(typeof(IReadOnlyList<GameScoreResponseDto>), StatusCodes.Status200OK)]
public async Task<ActionResult<IReadOnlyList<GameScoreResponseDto>>> GetLeaderboard(
[FromQuery] string game = "Minesweeper",
[FromQuery] int limit = 10,
CancellationToken ct = default)
{
var result = await sender.Send(new GetLeaderboardQuery(game, limit), ct);
return Ok(result);
}
[HttpPost]
[ProducesResponseType(typeof(GameScoreResponseDto), StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<ActionResult<GameScoreResponseDto>> SubmitScore(
[FromBody] SubmitGameScoreRequestDto request,
CancellationToken ct = default)
{
var command = new SubmitGameScoreCommand(
request.PlayerName,
request.GameName,
request.Score,
request.DurationSeconds,
request.CountryCode
);
var result = await sender.Send(command, ct);
return StatusCode(StatusCodes.Status201Created, result);
}
}

View File

@ -0,0 +1,31 @@
using MediatR;
using Microsoft.AspNetCore.Mvc;
using Portfolio.Application.Features.Projects.DTOs;
using Portfolio.Application.Features.Projects.Queries;
namespace Portfolio.WebApi.Controllers;
[ApiController]
[Route("api/v1/[controller]")]
[Produces("application/json")]
public sealed class ProjectsController(ISender sender) : ControllerBase
{
[HttpGet]
[ProducesResponseType(typeof(IReadOnlyList<ProjectResponseDto>), StatusCodes.Status200OK)]
public async Task<ActionResult<IReadOnlyList<ProjectResponseDto>>> GetAll(
[FromQuery] bool featuredOnly = false,
CancellationToken ct = default)
{
var result = await sender.Send(new GetProjectsQuery(featuredOnly), ct);
return Ok(result);
}
[HttpGet("{slug}")]
[ProducesResponseType(typeof(ProjectResponseDto), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<ActionResult<ProjectResponseDto>> GetBySlug(string slug, CancellationToken ct = default)
{
var result = await sender.Send(new GetProjectBySlugQuery(slug), ct);
return Ok(result);
}
}

View File

@ -0,0 +1,23 @@
using MediatR;
using Microsoft.AspNetCore.Mvc;
using Portfolio.Application.Features.Skills.DTOs;
using Portfolio.Application.Features.Skills.Queries;
using Portfolio.Domain.Enums;
namespace Portfolio.WebApi.Controllers;
[ApiController]
[Route("api/v1/[controller]")]
[Produces("application/json")]
public sealed class SkillsController(ISender sender) : ControllerBase
{
[HttpGet]
[ProducesResponseType(typeof(IReadOnlyList<SkillResponseDto>), StatusCodes.Status200OK)]
public async Task<ActionResult<IReadOnlyList<SkillResponseDto>>> GetAll(
[FromQuery] SkillCategory? category = null,
CancellationToken ct = default)
{
var result = await sender.Send(new GetSkillsQuery(category), ct);
return Ok(result);
}
}

View File

@ -0,0 +1,35 @@
using System.Diagnostics;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using Portfolio.Application.Features.Telemetry.DTOs;
using Portfolio.Application.Features.Telemetry.Queries;
namespace Portfolio.WebApi.Controllers;
[ApiController]
[Route("api/v1/[controller]")]
[Produces("application/json")]
public sealed class TelemetryController(ISender sender) : ControllerBase
{
[HttpGet]
[ProducesResponseType(typeof(ServerTelemetryDto), StatusCodes.Status200OK)]
public async Task<ActionResult<ServerTelemetryDto>> GetServerTelemetry(CancellationToken ct)
{
var result = await sender.Send(new GetServerTelemetryQuery(), ct);
return Ok(result);
}
[HttpGet("ping")]
[ProducesResponseType(typeof(PingResponseDto), StatusCodes.Status200OK)]
public ActionResult<PingResponseDto> Ping()
{
var sw = Stopwatch.StartNew();
sw.Stop();
return Ok(new PingResponseDto(
Message: "PONG // ZEN SERVER HEALTHY",
LatencyMs: sw.ElapsedMilliseconds,
TimestampUtc: DateTime.UtcNow
));
}
}

View File

@ -0,0 +1,54 @@
using FluentValidation;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using Portfolio.Domain.Exceptions;
namespace Portfolio.WebApi.Middleware;
public sealed class GlobalExceptionHandler(ILogger<GlobalExceptionHandler> logger) : IExceptionHandler
{
public async ValueTask<bool> TryHandleAsync(
HttpContext httpContext,
Exception exception,
CancellationToken cancellationToken)
{
logger.LogError(exception, "Unhandled exception occurred: {Message}", exception.Message);
var problemDetails = exception switch
{
ValidationException valEx => new ProblemDetails
{
Status = StatusCodes.Status400BadRequest,
Title = "Validation Error",
Detail = "One or more validation errors occurred.",
Extensions =
{
["errors"] = valEx.Errors.Select(e => new { e.PropertyName, e.ErrorMessage })
}
},
NotFoundException notFoundEx => new ProblemDetails
{
Status = StatusCodes.Status404NotFound,
Title = "Not Found",
Detail = notFoundEx.Message
},
DomainException domainEx => new ProblemDetails
{
Status = StatusCodes.Status400BadRequest,
Title = "Domain Rule Violation",
Detail = domainEx.Message
},
_ => new ProblemDetails
{
Status = StatusCodes.Status500InternalServerError,
Title = "Internal Server Error",
Detail = "An unexpected error occurred. Please contact the administrator."
}
};
httpContext.Response.StatusCode = problemDetails.Status ?? StatusCodes.Status500InternalServerError;
await httpContext.Response.WriteAsJsonAsync(problemDetails, cancellationToken);
return true;
}
}

View File

@ -0,0 +1,23 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.10" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.10">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Portfolio.Application\Portfolio.Application.csproj" />
<ProjectReference Include="..\Portfolio.Infrastructure\Portfolio.Infrastructure.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,6 @@
@Portfolio.WebApi_HostAddress = http://localhost:5117
GET {{Portfolio.WebApi_HostAddress}}/weatherforecast/
Accept: application/json
###

View File

@ -0,0 +1,119 @@
using Microsoft.OpenApi.Models;
using Portfolio.Application;
using Portfolio.Infrastructure;
using Portfolio.WebApi.Middleware;
var builder = WebApplication.CreateBuilder(args);
// 1. Configuracion en cascada: appsettingsdevelop.json (base segura en Git) + appsettings.json (secretos locales)
builder.Configuration
.SetBasePath(builder.Environment.ContentRootPath)
.AddJsonFile("appsettingsdevelop.json", optional: true, reloadOnChange: true)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{builder.Environment.EnvironmentName}.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables();
// 2. Inyeccion de dependencias de Capas (Clean Architecture)
builder.Services.AddApplication();
builder.Services.AddInfrastructure(builder.Configuration);
// 3. Manejo Global de Excepciones (RFC 7807 ProblemDetails)
builder.Services.AddExceptionHandler<GlobalExceptionHandler>();
builder.Services.AddProblemDetails();
// 4. Controladores y Serializacion JSON
builder.Services.AddControllers()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull;
});
// 5. Configuracion de CORS para Angular Frontend
var allowedOrigins = builder.Configuration.GetSection("CorsSettings:AllowedOrigins").Get<string[]>()
?? ["http://localhost:4200", "https://bryan-bano.com", "https://portfolio.bryan-bano.com"];
builder.Services.AddCors(options =>
{
options.AddPolicy("PortfolioCorsPolicy", policy =>
{
policy.WithOrigins(allowedOrigins)
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
});
});
// 6. OpenAPI / Swagger con documentacion Cyber-Zen
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo
{
Title = "Bryan Baño // Portfolio API",
Version = "v1",
Description = "API REST de alto rendimiento para el portafolio profesional interactivo. Clean Architecture, CQRS y persistencia MySQL.",
Contact = new OpenApiContact
{
Name = "Bryan Baño",
Email = "contacto@bryan-bano.com",
Url = new Uri("https://bryan-bano.com")
}
});
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.Http,
Scheme = "bearer"
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
Array.Empty<string>()
}
});
});
var app = builder.Build();
// 7. Pipeline de Solicitudes HTTP
app.UseExceptionHandler();
if (app.Environment.IsDevelopment() || builder.Configuration.GetValue<bool>("EnableSwaggerInProd", true))
{
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Portfolio API v1");
c.DocumentTitle = "Bryan Baño // API Documentation";
c.RoutePrefix = "swagger";
});
}
app.UseCors("PortfolioCorsPolicy");
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
// Healthcheck basico en raiz
app.MapGet("/", () => Results.Ok(new
{
service = "Portfolio Backend API",
status = "Online",
version = "1.0.0",
docs = "/swagger"
}));
app.Run();

View File

@ -0,0 +1,41 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:25368",
"sslPort": 44302
}
},
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "http://localhost:5117",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "https://localhost:7020;http://localhost:5117",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

View File

@ -0,0 +1,33 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning",
"Microsoft.EntityFrameworkCore.Database.Command": "Information"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"DefaultConnection": "Server=localhost;Port=3306;Database=portfolio_db;User=root;Password=;CharSet=utf8mb4;"
},
"JwtSettings": {
"Secret": "YOUR_SUPER_SECRET_KEY_MINIMUM_32_CHARACTERS_LONG_PLACEHOLDER",
"Issuer": "PortfolioBackend",
"Audience": "PortfolioFrontend",
"ExpiryMinutes": 60,
"RefreshTokenExpiryDays": 7
},
"CorsSettings": {
"AllowedOrigins": [
"http://localhost:4200",
"https://bryan-bano.com",
"https://portfolio.bryan-bano.com"
]
},
"ServerTelemetry": {
"Region": "us-ashburn-1",
"Provider": "Oracle Cloud Infrastructure (OCI)",
"ServerName": "srv-personal-core",
"Architecture": "ARM64 Ampere Altra"
}
}

View File

@ -0,0 +1,60 @@
using Portfolio.Domain.Entities;
using Portfolio.Domain.Enums;
namespace Portfolio.UnitTests;
public class DomainTests
{
[Fact]
public void Project_Create_WithValidArgs_ShouldInstantiateCorrectly()
{
// Act
var project = Project.Create(
slug: "test-project",
title: "Test Project Title",
shortDescription: "Short description of project",
fullDescription: "Detailed description of architecture and features",
repositoryUrl: "https://github.com/bryan/test-project",
isFeatured: true
);
// Assert
Assert.NotNull(project);
Assert.Equal("test-project", project.Slug);
Assert.Equal("Test Project Title", project.Title);
Assert.True(project.IsFeatured);
Assert.NotEqual(Guid.Empty, project.Id);
}
[Theory]
[InlineData("", "Title")]
[InlineData(" ", "Title")]
[InlineData("slug", "")]
[InlineData("slug", " ")]
public void Project_Create_WithInvalidArgs_ShouldThrowArgumentException(string slug, string title)
{
// Assert
Assert.Throws<ArgumentException>(() =>
Project.Create(
slug: slug,
title: title,
shortDescription: "Short",
fullDescription: "Full",
repositoryUrl: "https://repo"
)
);
}
[Fact]
public void Skill_Create_WithValidArgs_ShouldInstantiateCorrectly()
{
// Act
var skill = Skill.Create(".NET 8/9", SkillCategory.Backend, "dotnet", proficiency: 95);
// Assert
Assert.NotNull(skill);
Assert.Equal(".NET 8/9", skill.Name);
Assert.Equal(SkillCategory.Backend, skill.Category);
Assert.Equal(95, skill.ProficiencyPercentage);
}
}

View File

@ -0,0 +1,40 @@
using Portfolio.Application.Features.Guestbook.Commands;
using Portfolio.Application.Features.Guestbook.Validators;
namespace Portfolio.UnitTests;
public class GuestbookValidationTests
{
private readonly CreateGuestbookMessageCommandValidator _validator = new();
[Fact]
public void Validator_WithValidData_ShouldNotHaveErrors()
{
// Arrange
var command = new CreateGuestbookMessageCommand("Bryan Baño", "Excelente arquitectura.");
// Act
var result = _validator.Validate(command);
// Assert
Assert.True(result.IsValid);
Assert.Empty(result.Errors);
}
[Theory]
[InlineData("", "Mensaje de prueba")]
[InlineData("Bryan", "")]
[InlineData("Bryan", "ab")] // Menos de 3 caracteres
public void Validator_WithInvalidData_ShouldHaveValidationErrors(string senderName, string message)
{
// Arrange
var command = new CreateGuestbookMessageCommand(senderName, message);
// Act
var result = _validator.Validate(command);
// Assert
Assert.False(result.IsValid);
Assert.NotEmpty(result.Errors);
}
}

View File

@ -0,0 +1,28 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
<PackageReference Include="xunit" Version="2.5.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.5.3" />
</ItemGroup>
<ItemGroup>
<Using Include="Xunit" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\Portfolio.Application\Portfolio.Application.csproj" />
<ProjectReference Include="..\..\src\Portfolio.Domain\Portfolio.Domain.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,24 @@
using Portfolio.Application.Features.Telemetry.Queries;
namespace Portfolio.UnitTests;
public class TelemetryTests
{
[Fact]
public async Task GetServerTelemetryQueryHandler_ShouldReturnOperationalStatus()
{
// Arrange
var handler = new GetServerTelemetryQueryHandler();
var query = new GetServerTelemetryQuery();
// Act
var result = await handler.Handle(query, CancellationToken.None);
// Assert
Assert.NotNull(result);
Assert.Equal("OPERATIONAL", result.Status);
Assert.Equal("us-ashburn-1", result.Region);
Assert.True(result.ProcessMemoryMb > 0);
Assert.True(result.ActiveThreads > 0);
}
}