️ Implement Repository Pattern + some changes

Add repository pattern and Automapper nugget
pull/1/head
Leo TUAILLON 8 months ago
parent 90dab5667b
commit 6d234a65bd

734
.gitignore vendored

@ -0,0 +1,734 @@
# Created by https://www.toptal.com/developers/gitignore/api/csharp,rider,intellij+all,visualstudio,visualstudiocode
# Edit at https://www.toptal.com/developers/gitignore?templates=csharp,rider,intellij+all,visualstudio,visualstudiocode
### Csharp ###
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore
# 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 Core
project.lock.json
project.fragment.lock.json
artifacts/
# 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
# 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
### Intellij+all ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff
.idea/
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf
# AWS User-specific
.idea/**/aws.xml
# Generated files
.idea/**/contentModel.xml
# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml
# Gradle
.idea/**/gradle.xml
.idea/**/libraries
# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn. Uncomment if using
# auto-import.
# .idea/artifacts
# .idea/compiler.xml
# .idea/jarRepositories.xml
# .idea/modules.xml
# .idea/*.iml
# .idea/modules
# *.iml
# *.ipr
# CMake
cmake-build-*/
# Mongo Explorer plugin
.idea/**/mongoSettings.xml
# File-based project format
*.iws
# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# SonarLint plugin
.idea/sonarlint/
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
# Editor-based Rest Client
.idea/httpRequests
# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser
### Intellij+all Patch ###
# Ignore everything but code style settings and run configurations
# that are supposed to be shared within teams.
.idea/*
!.idea/codeStyles
!.idea/runConfigurations
### Rider ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff
# AWS User-specific
# Generated files
# Sensitive or high-churn files
# Gradle
# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn. Uncomment if using
# auto-import.
# .idea/artifacts
# .idea/compiler.xml
# .idea/jarRepositories.xml
# .idea/modules.xml
# .idea/*.iml
# .idea/modules
# *.iml
# *.ipr
# CMake
# Mongo Explorer plugin
# File-based project format
# IntelliJ
# mpeltonen/sbt-idea plugin
# JIRA plugin
# Cursive Clojure plugin
# SonarLint plugin
# Crashlytics plugin (for Android Studio and IntelliJ)
# Editor-based Rest Client
# Android studio 3.1+ serialized cache file
### VisualStudioCode ###
!.vscode/*.code-snippets
# Local History for Visual Studio Code
# Built Visual Studio Code Extensions
*.vsix
### VisualStudioCode Patch ###
# Ignore all local history of files
.history
.ionide
### VisualStudio ###
# User-specific files
# User-specific files (MonoDevelop/Xamarin Studio)
# Mono auto generated files
# Build results
# Visual Studio 2015/2017 cache/options directory
# Uncomment if you have tasks that create the project's static files in wwwroot
# Visual Studio 2017 auto generated files
# MSTest test Results
# NUnit
# Build Results of an ATL Project
# Benchmark Results
# .NET Core
# ASP.NET Scaffolding
# StyleCop
# Files built by Visual Studio
# Chutzpah Test files
# Visual C++ cache files
# Visual Studio profiler
# Visual Studio Trace Files
# TFS 2012 Local Workspace
# Guidance Automation Toolkit
# ReSharper is a .NET coding add-in
# TeamCity is a build add-in
# DotCover is a Code Coverage Tool
# AxoCover is a Code Coverage Tool
# Coverlet is a free, cross platform Code Coverage Tool
# Visual Studio code coverage results
# NCrunch
# MightyMoose
# Web workbench (sass)
# Installshield output folder
# DocProject is a documentation generator add-in
# Click-Once directory
# Publish Web Output
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
# 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
# NuGet Packages
# NuGet Symbol Packages
# The packages folder can be ignored because of Package Restore
# except build/, which is used as an MSBuild target.
# Uncomment if necessary however generally it will be regenerated when needed
# NuGet v3's project.json files produces more ignorable files
# Microsoft Azure Build Output
# Microsoft Azure Emulator
# Windows Store app package directories and files
# Visual Studio cache files
# files ending in .cache can be ignored
# but keep track of directories ending in .cache
# Others
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
# RIA/Silverlight projects
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
# SQL Server files
# Business Intelligence projects
# Microsoft Fakes
# GhostDoc plugin setting file
# Node.js Tools for Visual Studio
# Visual Studio 6 build log
# Visual Studio 6 workspace options file
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
# Visual Studio 6 auto-generated project file (contains which files were open etc.)
# Visual Studio 6 workspace and project file (working project files containing files to include in project)
# Visual Studio 6 technical files
# Visual Studio LightSwitch build output
# Paket dependency manager
# FAKE - F# Make
# CodeRush personal settings
# Python Tools for Visual Studio (PTVS)
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
# Telerik's JustMock configuration file
# BizTalk build output
# OpenCover UI analysis results
# Azure Stream Analytics local run output
# MSBuild Binary and Structured Log
# NVidia Nsight GPU debugger configuration file
# MFractors (Xamarin productivity tool) working folder
# Local History for Visual Studio
# Visual Studio History (VSHistory) files
# BeatPulse healthcheck temp database
# Backup folder for Package Reference Convert tool in Visual Studio 2017
# Ionide (cross platform F# VS Code tools) working folder
# Fody - auto-generated XML schema
# VS Code files for those working on multiple tools
# Local History for Visual Studio Code
# Windows Installer files from build outputs
# JetBrains Rider
### VisualStudio Patch ###
# Additional files built by Visual Studio
# End of https://www.toptal.com/developers/gitignore/api/csharp,rider,intellij+all,visualstudio,visualstudiocode

@ -1,4 +0,0 @@
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<s:String x:Key="/Default/Environment/UnitTesting/UnitTestSessionStore/Sessions/=711b0308_002Dc8c6_002D4423_002Db315_002D82f61e82bdb5/@EntryIndexedValue">&lt;SessionState ContinuousTestingMode="0" IsActive="True" Name="alumniTest" xmlns="urn:schemas-jetbrains-com:jetbrains-ut-session"&gt;
&lt;Solution /&gt;
&lt;/SessionState&gt;</s:String></wpf:ResourceDictionary>

@ -1,5 +1,4 @@
// See https://aka.ms/new-console-template for more information
using System;
using Infrastructure;
using Infrastructure.Entities;
using Infrastructure.Stub;
@ -8,359 +7,17 @@ using Microsoft.EntityFrameworkCore;
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<AlumniDbContext>()
var options = new DbContextOptionsBuilder<OptifitDbContext>()
.UseSqlite(connection)
.Options;
await using (var context = new StubbedContext(options))
{
await context.Database.EnsureCreatedAsync();
Console.WriteLine("============Events============");
//Display all events
var events = await context.Events.ToListAsync();
Console.WriteLine("--Display of the Events: (Tolal:" + events.Count + ")");
foreach (var eventEntity in events) Console.WriteLine(eventEntity);
Console.WriteLine("--Create an event");
//Create a new event
var evt = new EventEntity()
{
Title = "This is a title",
Description = "This is a description",
Date = DateTime.Now,
nbPlaces = 100
};
context.Events.Add(evt);
await context.SaveChangesAsync();
//verify if the event has been created
var getEvt = await context.Events.FirstOrDefaultAsync(e => e.Title == "This is a title");
if( getEvt == null)
{
Console.WriteLine("Event not found (Creation failed)");
}
else
{
Console.WriteLine("Event found (Creation success) :");
Console.WriteLine(getEvt);
}
//Update the event
Console.WriteLine("--Update event");
getEvt.Title = "Changed title";
await context.SaveChangesAsync();
//verify if the event has been updated
var getEvt2 = await context.Events.FirstOrDefaultAsync(e => e.Title == "Changed title");
if( getEvt2 == null)
{
Console.WriteLine("Event not found (Update failed)");
}
else
{
Console.WriteLine("Event found (Update success) :");
Console.WriteLine(getEvt2);
}
//Delete the event
Console.WriteLine("--Delete event");
context.Events.Remove(getEvt2);
await context.SaveChangesAsync();
//verify if the event has been deleted
var getEvt3 = await context.Events.FirstOrDefaultAsync(e => e.Title == "Changed title");
if( getEvt3 == null)
{
Console.WriteLine("Event not found (Deletion success)");
}
else
{
Console.WriteLine("Event found (Deletion failed) :");
Console.WriteLine(getEvt3);
}
Console.WriteLine("\n============Alumnis============");
//Display all alumnis
var alumnis = await context.Alumni.ToListAsync();
Console.WriteLine("Diplay the Alumnis: (Tolal:" + alumnis.Count + ")");
foreach (var alumniEntity in alumnis) Console.WriteLine(alumniEntity);
Console.WriteLine("--Create an alumni");
//Create a new alumni
var alumni = new User()
{
FirstName = "Leo",
LastName = "Tuaillon",
Email = "leo.tuaillon@gmail.com",
EntryYear = "2021",
Password = "1234567890",
Role = "ADMIN"
};
context.Alumni.Add(alumni);
await context.SaveChangesAsync();
//verify if the alumni has been created
var getAlumni = await context.Alumni.FirstOrDefaultAsync(a => a.FirstName == "Leo");
if( getAlumni == null)
{
Console.WriteLine("Alumni not found (Creation failed)");
}
else
{
Console.WriteLine("Alumni found (Creation success) :");
Console.WriteLine(getAlumni);
}
//Update the alumni
Console.WriteLine("--Update alumni");
getAlumni.FirstName = "Leo changed name";
await context.SaveChangesAsync();
//verify if the alumni has been updated
var getAlumni2 = await context.Alumni.FirstOrDefaultAsync(a => a.FirstName == "Leo changed name");
if( getAlumni2 == null)
{
Console.WriteLine("Alumni not found (Update failed)");
}
else
{
Console.WriteLine("Alumni found (Update success) :");
Console.WriteLine(getAlumni2);
}
//Delete the alumni
Console.WriteLine("--Delete alumni");
context.Alumni.Remove(getAlumni2);
await context.SaveChangesAsync();
//verify if the alumni has been deleted
var getAlumni3 = await context.Alumni.FirstOrDefaultAsync(a => a.FirstName == "Leo changed name");
if( getAlumni3 == null)
{
Console.WriteLine("Alumni not found (Deletion success)");
}
else
{
Console.WriteLine("Alumni found (Deletion failed) :");
Console.WriteLine(getAlumni3);
}
Console.WriteLine("\n============Experiences============");
//Display all experiences
var experiences = await context.Experiences.ToListAsync();
Console.WriteLine("Display the Experiences: (Tolal:" + experiences.Count + ")");
foreach (var experienceEntity in experiences) Console.WriteLine(experienceEntity);
Console.WriteLine("--Create an experience");
//Create a new experience
var experience = new ExperienceEntity()
{
Title = "Ingénieur logiciel",
StartDate = DateTime.Now,
CompanyName = "Capgemini",
IsCurrent = true
};
context.Experiences.Add(experience);
await context.SaveChangesAsync();
//verify if the experience has been created
var getExperience = await context.Experiences.FirstOrDefaultAsync(e => e.Title == "Ingénieur logiciel");
if( getExperience == null)
{
Console.WriteLine("Experience not found (Creation failed)");
}
else
{
Console.WriteLine("Experience found (Creation success) :");
Console.WriteLine(getExperience);
}
//Update the experience
Console.WriteLine("--Update experience");
getExperience.Title = "Ingénieur logiciel changed";
await context.SaveChangesAsync();
//verify if the experience has been updated
var getExperience2 = await context.Experiences.FirstOrDefaultAsync(e => e.Title == "Ingénieur logiciel changed");
if( getExperience2 == null)
{
Console.WriteLine("Experience not found (Update failed)");
}
else
{
Console.WriteLine("Experience found (Update success) :");
Console.WriteLine(getExperience2);
}
//Delete the experience
Console.WriteLine("--Delete experience");
context.Experiences.Remove(getExperience2);
await context.SaveChangesAsync();
//verify if the experience has been deleted
var getExperience3 = await context.Experiences.FirstOrDefaultAsync(e => e.Title == "Ingénieur logiciel changed");
if( getExperience3 == null)
{
Console.WriteLine("Experience not found (Deletion success)");
}
else
{
Console.WriteLine("Experience found (Deletion failed) :");
Console.WriteLine(getExperience3);
}
Console.WriteLine("\n============Formations============");
//Display all formations
var formations = await context.Formations.ToListAsync();
Console.WriteLine("Display the Formations: (Tolal:" + formations.Count + ")");
foreach (var formationEntity in formations) Console.WriteLine(formationEntity);
Console.WriteLine("--Create a formation");
//Create a new formation
var formation = new FormationEntity()
{
SchoolName = "IUT Clermont-Ferrand",
Name = "BUT GEA",
StartDate = DateTime.Now,
IsCurrent = true
};
context.Formations.Add(formation);
await context.SaveChangesAsync();
//verify if the formation has been created
var getFormation = await context.Formations.FirstOrDefaultAsync(f => f.Name == "BUT GEA");
if( getFormation == null)
{
Console.WriteLine("Formation not found (Creation failed)");
}
else
{
Console.WriteLine("Formation found (Creation success) :");
Console.WriteLine(getFormation);
}
//Update the formation
Console.WriteLine("--Update formation");
getFormation.Name = "BUT Mesures Physiques";
await context.SaveChangesAsync();
//verify if the formation has been updated
var getFormation2 = await context.Formations.FirstOrDefaultAsync(f => f.Name == "BUT Mesures Physiques");
if( getFormation2 == null)
{
Console.WriteLine("Formation not found (Update failed)");
}
else
{
Console.WriteLine("Formation found (Update success) :");
Console.WriteLine(getFormation2);
}
//Delete the formation
Console.WriteLine("--Delete formation");
context.Formations.Remove(getFormation2);
await context.SaveChangesAsync();
//verify if the formation has been deleted
var getFormation3 = await context.Formations.FirstOrDefaultAsync(f => f.Name == "BUT Mesures Physiques");
if( getFormation3 == null)
{
Console.WriteLine("Formation not found (Deletion success)");
}
else
{
Console.WriteLine("Formation found (Deletion failed) :");
Console.WriteLine(getFormation3);
}
Console.WriteLine("\nAlumni with their experiences, formations and events");
var alumniDetails = await context.Alumni
.Include(a => a.Experiences)
.Include(a => a.Formations)
.Include(a => a.Events)
.FirstOrDefaultAsync( a => a.FirstName == "Test");
if (alumniDetails == null)
{
Console.WriteLine("Alumni not found");
}
else
{
Console.WriteLine(alumniDetails);
}
Console.WriteLine("Subscribe to an event");
var eventToSubscribe = await context.Events.FirstOrDefaultAsync(e => e.Title == "Laser Game");
var eventToSubscribe2 = await context.Events.FirstOrDefaultAsync(e => e.Title == "Afterwork Raclette");
if (eventToSubscribe == null || eventToSubscribe2 == null)
{
Console.WriteLine("Event not found");
}
else
{
alumniDetails.Events.Add(eventToSubscribe);
alumniDetails.Events.Add(eventToSubscribe2);
await context.SaveChangesAsync();
Console.WriteLine(alumniDetails);
Console.WriteLine("\tEvents subscribed :");
foreach (var eventEntity in alumniDetails.Events)
{
Console.WriteLine("\t"+eventEntity);
}
}
Console.WriteLine("Unsubscribe to an event");
var eventToUnsubscribe = await context.Events.FirstOrDefaultAsync(e => e.Title == "Laser Game");
if (eventToUnsubscribe == null)
{
Console.WriteLine("Event not found");
}
else
{
alumniDetails.Events.Remove(eventToUnsubscribe);
await context.SaveChangesAsync();
Console.WriteLine(alumniDetails);
Console.WriteLine("\tEvents unsubscribed :");
foreach (var eventEntity in alumniDetails.Events)
{
Console.WriteLine("\t" + eventEntity);
}
}
Console.WriteLine("Add an experience and a formation to an alumni");
var experienceToAdd = new ExperienceEntity()
{
Title = "Stage",
StartDate = DateTime.Now,
CompanyName = "Capgemini",
IsCurrent = true
};
var formationToAdd = new FormationEntity()
{
SchoolName = "IUT Clermont-Ferrand",
Name = "BUT GEA",
StartDate = DateTime.Now,
IsCurrent = true
};
alumniDetails.Experiences.Add(experienceToAdd);
alumniDetails.Formations.Add(formationToAdd);
await context.SaveChangesAsync();
Console.WriteLine(alumniDetails);
Console.WriteLine("\tExperiences added :");
foreach (var experienceEntity in alumniDetails.Experiences)
{
Console.WriteLine("\t" + experienceEntity);
}
Console.WriteLine("\tFormations added :");
foreach (var formationEntity in alumniDetails.Formations)
{
Console.WriteLine("\t" + formationEntity);
}
Console.WriteLine("\n============Users============");
//Display all users
var users = await context.Users.ToListAsync();
Console.WriteLine("Diplay the Users: (Tolal:" + users.Count + ")");
foreach (var userEntity in users) Console.WriteLine(userEntity);
}
connection.Close();

@ -1,48 +0,0 @@
using Infrastructure.Entities;
using Microsoft.EntityFrameworkCore;
namespace Infrastructure;
public class AlumniDbContext : DbContext
{
public virtual DbSet<User> Alumni { get; set; }
public virtual DbSet<ExperienceEntity> Experiences { get; set; }
public virtual DbSet<FormationEntity> Formations { get; set; }
public virtual DbSet<EventEntity> Events { get; set; }
public AlumniDbContext()
{
}
public AlumniDbContext(DbContextOptions<AlumniDbContext> options)
: base(options)
{
}
protected override void OnConfiguring(DbContextOptionsBuilder options)
{
if (!options.IsConfigured)
{
options.UseSqlite("Data Source=FirstTest.db");
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<EventEntity>().Property(e => e.Title)
.IsRequired();
modelBuilder.Entity<User>().Property(a => a.FirstName)
.IsRequired();
modelBuilder.Entity<User>().Property(a => a.Email)
.IsRequired();
modelBuilder.Entity<ExperienceEntity>()
.Property(e => e.Title)
.IsRequired();
modelBuilder.Entity<FormationEntity>().Property(f => f.Name)
.IsRequired();
base.OnModelCreating(modelBuilder);
}
}

@ -1,3 +1,4 @@
using System;
using System.ComponentModel.DataAnnotations;
namespace Infrastructure.Base;

@ -1,5 +1,4 @@
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations;
using Infrastructure.Base;
namespace Infrastructure.Entities;
@ -7,45 +6,36 @@ namespace Infrastructure.Entities;
public class User : EntityBase
{
[Required]
[MaxLength(100)]
// Id is a field with a maximum length of 100 characters
public string Id { get; set; }
public string Name { get; set; }
[Required]
[MaxLength(200)]
// Title is a required field with a maximum length of 200 characters
public string FirstName { get; set; }
public int Age { get; set; }
[MaxLength(100)]
// Author is a field with a maximum length of 100 characters
public string LastName { get; set; }
public float Height { get; set; }
public int Age { get; set; }
public float Weight { get; set; }
[MinLength(10)]
// Password is a field with a minimum length of 10 characters
public string Password { get; set; }
public bool Sexe { get; set; }
public int Height { get; set; }
public string Logo { get; set; }
public int Weight { get; set; }
public int NbSessionPerWeek { get; set; }
public int Sexe { get; set; }
public string? EGoal { get; set; }
public string? WebSite { get; set; }
public string? ESleepLevel { get; set; }
public ICollection<ExperienceEntity> Experiences { get; set; } = new Collection<ExperienceEntity>();
public string? ESportLevel { get; set; }
public ICollection<FormationEntity> Formations { get; set; } = new Collection<FormationEntity>();
public string HashPassword { get; set; }
public ICollection<EventEntity> Events { get; set; } = new Collection<EventEntity>();
public string? OAuthProvider { get; set; }
public string? OAuthId { get; set; }
//public Program { get; set; }
public override string ToString()
{
return $"\t------------Alumni Id : {Id} ------------- :" +
$"\n\tFirstname : {FirstName} Lastname : {LastName} Email : {Email} Role : {Role}\n\t" +
$"Experiences : {Experiences.Count} \t" +
$"Formations : {Formations.Count} \t Events : {Events.Count}";
return $"\t------------User Id : {Id} ------------- :" +
$"\n\tName : {Name} Age : {Age}";
}
}

@ -0,0 +1,26 @@
using System.Linq.Expressions;
using Infrastructure.Base;
using Shared;
namespace Infrastructure;
public interface IRepository<T> where T : EntityBase
{
IEnumerable<T> GetAll(params Expression<Func<T, object>>[] includes);
Task<IEnumerable<T>> GetAllAsync(Expression<Func<T, bool>>? expression = null, CancellationToken cancellationToken = default, params Expression<Func<T, object>>[] includes);
Task<T?> GetByIdAsync(object id, params Expression<Func<T, object>>[] includes);
Task InsertAsync(T obj);
void Update(T obj);
void Delete(object id);
Task<PaginatedResult<T>> GetPaginatedListAsync(int pageNumber, int pageSize, string[]? orderBy = null, Expression<Func<T, bool>>? expression = null, CancellationToken cancellationToken = default, params Expression<Func<T, object>>[] includes);
Task<int> CountAsync(Expression<Func<T, bool>>? expression = null, CancellationToken cancellationToken = default);
Task<bool> ExistsAsync(Expression<Func<T, bool>> expression, CancellationToken cancellationToken = default);
}

@ -0,0 +1,6 @@
namespace Infrastructure;
public interface IUnitOfWork
{
Task SaveAsync();
}

@ -15,6 +15,15 @@
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="8.0.1"/>
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.1"/>
<PackageReference Include="System.Linq.Dynamic.Core" Version="1.4.6" />
</ItemGroup>
<ItemGroup>
<Folder Include="Migrations\" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Shared\Shared.csproj" />
</ItemGroup>
</Project>

@ -1,220 +0,0 @@
// <auto-generated />
using System;
using Infrastructure;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace Infrastructure.Migrations
{
[DbContext(typeof(AlumniDbContext))]
[Migration("20240328220800_migV1")]
partial class migV1
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "8.0.1");
modelBuilder.Entity("AlumniEntityEventEntity", b =>
{
b.Property<string>("EventsId")
.HasColumnType("TEXT");
b.Property<string>("ParticipantsId")
.HasColumnType("TEXT");
b.HasKey("EventsId", "ParticipantsId");
b.HasIndex("ParticipantsId");
b.ToTable("AlumniEntityEventEntity");
});
modelBuilder.Entity("Infrastructure.Entities.AlumniEntity", b =>
{
b.Property<string>("Id")
.HasColumnType("TEXT");
b.Property<string>("Email")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("TEXT");
b.Property<string>("EntryYear")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("FirstName")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("TEXT");
b.Property<string>("Github")
.HasColumnType("TEXT");
b.Property<string>("LastName")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("TEXT");
b.Property<string>("Linkedin")
.HasColumnType("TEXT");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("Role")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("WebSite")
.HasColumnType("TEXT");
b.HasKey("Id");
b.ToTable("Alumni");
});
modelBuilder.Entity("Infrastructure.Entities.EventEntity", b =>
{
b.Property<string>("Id")
.HasColumnType("TEXT");
b.Property<DateTime>("Date")
.HasColumnType("TEXT");
b.Property<string>("Description")
.IsRequired()
.HasMaxLength(512)
.HasColumnType("TEXT");
b.Property<string>("Title")
.IsRequired()
.HasMaxLength(128)
.HasColumnType("TEXT");
b.Property<int>("nbPlaces")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.ToTable("Events");
});
modelBuilder.Entity("Infrastructure.Entities.ExperienceEntity", b =>
{
b.Property<string>("Id")
.HasColumnType("TEXT");
b.Property<string>("AlumniId")
.HasColumnType("TEXT");
b.Property<string>("CompanyName")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("TEXT");
b.Property<DateTime?>("EndDate")
.HasColumnType("TEXT");
b.Property<bool>("IsCurrent")
.HasColumnType("INTEGER");
b.Property<DateTime>("StartDate")
.HasColumnType("TEXT");
b.Property<string>("Title")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("AlumniId");
b.ToTable("Experiences");
});
modelBuilder.Entity("Infrastructure.Entities.FormationEntity", b =>
{
b.Property<string>("Id")
.HasColumnType("TEXT");
b.Property<string>("AlumniId")
.HasColumnType("TEXT");
b.Property<DateTime?>("EndDate")
.HasColumnType("TEXT");
b.Property<bool>("IsCurrent")
.HasColumnType("INTEGER");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("TEXT");
b.Property<string>("SchoolName")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("TEXT");
b.Property<DateTime>("StartDate")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("AlumniId");
b.ToTable("Formations");
});
modelBuilder.Entity("AlumniEntityEventEntity", b =>
{
b.HasOne("Infrastructure.Entities.EventEntity", null)
.WithMany()
.HasForeignKey("EventsId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Infrastructure.Entities.AlumniEntity", null)
.WithMany()
.HasForeignKey("ParticipantsId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Infrastructure.Entities.ExperienceEntity", b =>
{
b.HasOne("Infrastructure.Entities.AlumniEntity", "Alumni")
.WithMany("Experiences")
.HasForeignKey("AlumniId");
b.Navigation("Alumni");
});
modelBuilder.Entity("Infrastructure.Entities.FormationEntity", b =>
{
b.HasOne("Infrastructure.Entities.AlumniEntity", "Alumni")
.WithMany("Formations")
.HasForeignKey("AlumniId");
b.Navigation("Alumni");
});
modelBuilder.Entity("Infrastructure.Entities.AlumniEntity", b =>
{
b.Navigation("Experiences");
b.Navigation("Formations");
});
#pragma warning restore 612, 618
}
}
}

@ -1,152 +0,0 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Infrastructure.Migrations
{
/// <inheritdoc />
public partial class migV1 : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Alumni",
columns: table => new
{
Id = table.Column<string>(type: "TEXT", nullable: false),
FirstName = table.Column<string>(type: "TEXT", maxLength: 200, nullable: false),
LastName = table.Column<string>(type: "TEXT", maxLength: 100, nullable: false),
Email = table.Column<string>(type: "TEXT", maxLength: 100, nullable: false),
EntryYear = table.Column<string>(type: "TEXT", nullable: false),
Password = table.Column<string>(type: "TEXT", nullable: false),
Role = table.Column<string>(type: "TEXT", nullable: false),
Linkedin = table.Column<string>(type: "TEXT", nullable: true),
Github = table.Column<string>(type: "TEXT", nullable: true),
WebSite = table.Column<string>(type: "TEXT", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Alumni", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Events",
columns: table => new
{
Id = table.Column<string>(type: "TEXT", nullable: false),
Title = table.Column<string>(type: "TEXT", maxLength: 128, nullable: false),
Description = table.Column<string>(type: "TEXT", maxLength: 512, nullable: false),
Date = table.Column<DateTime>(type: "TEXT", nullable: false),
nbPlaces = table.Column<int>(type: "INTEGER", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Events", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Experiences",
columns: table => new
{
Id = table.Column<string>(type: "TEXT", nullable: false),
Title = table.Column<string>(type: "TEXT", maxLength: 64, nullable: false),
StartDate = table.Column<DateTime>(type: "TEXT", nullable: false),
EndDate = table.Column<DateTime>(type: "TEXT", nullable: true),
CompanyName = table.Column<string>(type: "TEXT", maxLength: 64, nullable: false),
IsCurrent = table.Column<bool>(type: "INTEGER", nullable: false),
AlumniId = table.Column<string>(type: "TEXT", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Experiences", x => x.Id);
table.ForeignKey(
name: "FK_Experiences_Alumni_AlumniId",
column: x => x.AlumniId,
principalTable: "Alumni",
principalColumn: "Id");
});
migrationBuilder.CreateTable(
name: "Formations",
columns: table => new
{
Id = table.Column<string>(type: "TEXT", nullable: false),
SchoolName = table.Column<string>(type: "TEXT", maxLength: 64, nullable: false),
Name = table.Column<string>(type: "TEXT", maxLength: 64, nullable: false),
StartDate = table.Column<DateTime>(type: "TEXT", nullable: false),
EndDate = table.Column<DateTime>(type: "TEXT", nullable: true),
IsCurrent = table.Column<bool>(type: "INTEGER", nullable: false),
AlumniId = table.Column<string>(type: "TEXT", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Formations", x => x.Id);
table.ForeignKey(
name: "FK_Formations_Alumni_AlumniId",
column: x => x.AlumniId,
principalTable: "Alumni",
principalColumn: "Id");
});
migrationBuilder.CreateTable(
name: "AlumniEntityEventEntity",
columns: table => new
{
EventsId = table.Column<string>(type: "TEXT", nullable: false),
ParticipantsId = table.Column<string>(type: "TEXT", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AlumniEntityEventEntity", x => new { x.EventsId, x.ParticipantsId });
table.ForeignKey(
name: "FK_AlumniEntityEventEntity_Alumni_ParticipantsId",
column: x => x.ParticipantsId,
principalTable: "Alumni",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_AlumniEntityEventEntity_Events_EventsId",
column: x => x.EventsId,
principalTable: "Events",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_AlumniEntityEventEntity_ParticipantsId",
table: "AlumniEntityEventEntity",
column: "ParticipantsId");
migrationBuilder.CreateIndex(
name: "IX_Experiences_AlumniId",
table: "Experiences",
column: "AlumniId");
migrationBuilder.CreateIndex(
name: "IX_Formations_AlumniId",
table: "Formations",
column: "AlumniId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "AlumniEntityEventEntity");
migrationBuilder.DropTable(
name: "Experiences");
migrationBuilder.DropTable(
name: "Formations");
migrationBuilder.DropTable(
name: "Events");
migrationBuilder.DropTable(
name: "Alumni");
}
}
}

@ -1,217 +0,0 @@
// <auto-generated />
using System;
using Infrastructure;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace Infrastructure.Migrations
{
[DbContext(typeof(AlumniDbContext))]
partial class AlumniDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "8.0.1");
modelBuilder.Entity("AlumniEntityEventEntity", b =>
{
b.Property<string>("EventsId")
.HasColumnType("TEXT");
b.Property<string>("ParticipantsId")
.HasColumnType("TEXT");
b.HasKey("EventsId", "ParticipantsId");
b.HasIndex("ParticipantsId");
b.ToTable("AlumniEntityEventEntity");
});
modelBuilder.Entity("Infrastructure.Entities.AlumniEntity", b =>
{
b.Property<string>("Id")
.HasColumnType("TEXT");
b.Property<string>("Email")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("TEXT");
b.Property<string>("EntryYear")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("FirstName")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("TEXT");
b.Property<string>("Github")
.HasColumnType("TEXT");
b.Property<string>("LastName")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("TEXT");
b.Property<string>("Linkedin")
.HasColumnType("TEXT");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("Role")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("WebSite")
.HasColumnType("TEXT");
b.HasKey("Id");
b.ToTable("Alumni");
});
modelBuilder.Entity("Infrastructure.Entities.EventEntity", b =>
{
b.Property<string>("Id")
.HasColumnType("TEXT");
b.Property<DateTime>("Date")
.HasColumnType("TEXT");
b.Property<string>("Description")
.IsRequired()
.HasMaxLength(512)
.HasColumnType("TEXT");
b.Property<string>("Title")
.IsRequired()
.HasMaxLength(128)
.HasColumnType("TEXT");
b.Property<int>("nbPlaces")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.ToTable("Events");
});
modelBuilder.Entity("Infrastructure.Entities.ExperienceEntity", b =>
{
b.Property<string>("Id")
.HasColumnType("TEXT");
b.Property<string>("AlumniId")
.HasColumnType("TEXT");
b.Property<string>("CompanyName")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("TEXT");
b.Property<DateTime?>("EndDate")
.HasColumnType("TEXT");
b.Property<bool>("IsCurrent")
.HasColumnType("INTEGER");
b.Property<DateTime>("StartDate")
.HasColumnType("TEXT");
b.Property<string>("Title")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("AlumniId");
b.ToTable("Experiences");
});
modelBuilder.Entity("Infrastructure.Entities.FormationEntity", b =>
{
b.Property<string>("Id")
.HasColumnType("TEXT");
b.Property<string>("AlumniId")
.HasColumnType("TEXT");
b.Property<DateTime?>("EndDate")
.HasColumnType("TEXT");
b.Property<bool>("IsCurrent")
.HasColumnType("INTEGER");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("TEXT");
b.Property<string>("SchoolName")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("TEXT");
b.Property<DateTime>("StartDate")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("AlumniId");
b.ToTable("Formations");
});
modelBuilder.Entity("AlumniEntityEventEntity", b =>
{
b.HasOne("Infrastructure.Entities.EventEntity", null)
.WithMany()
.HasForeignKey("EventsId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Infrastructure.Entities.AlumniEntity", null)
.WithMany()
.HasForeignKey("ParticipantsId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Infrastructure.Entities.ExperienceEntity", b =>
{
b.HasOne("Infrastructure.Entities.AlumniEntity", "Alumni")
.WithMany("Experiences")
.HasForeignKey("AlumniId");
b.Navigation("Alumni");
});
modelBuilder.Entity("Infrastructure.Entities.FormationEntity", b =>
{
b.HasOne("Infrastructure.Entities.AlumniEntity", "Alumni")
.WithMany("Formations")
.HasForeignKey("AlumniId");
b.Navigation("Alumni");
});
modelBuilder.Entity("Infrastructure.Entities.AlumniEntity", b =>
{
b.Navigation("Experiences");
b.Navigation("Formations");
});
#pragma warning restore 612, 618
}
}
}

@ -0,0 +1,32 @@
using Infrastructure.Entities;
using Microsoft.EntityFrameworkCore;
namespace Infrastructure;
public class OptifitDbContext : DbContext
{
public virtual DbSet<User> Users { get; set; }
public OptifitDbContext()
{
}
public OptifitDbContext(DbContextOptions<OptifitDbContext> options)
: base(options)
{
}
protected override void OnConfiguring(DbContextOptionsBuilder options)
{
if (!options.IsConfigured)
{
options.UseSqlite("Data Source=InMemoryDb.db");
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().Property(a => a.Name).IsRequired();
base.OnModelCreating(modelBuilder);
}
}

@ -0,0 +1,114 @@
using System.Linq.Expressions;
using Infrastructure.Base;
using Microsoft.EntityFrameworkCore;
using Shared;
using System.Linq.Expressions;
using System.Threading.Tasks;
using System.Linq.Dynamic.Core;
namespace Infrastructure.Repositories;
public class GenericRepository<T> : IRepository<T> where T : EntityBase
{
protected readonly OptifitDbContext context;
public GenericRepository(OptifitDbContext context)
{
this.context = context;
}
public IEnumerable<T> GetAll(params Expression<Func<T, object>>[] includes)
{
IQueryable<T> query = this.context.Set<T>();
query = includes.Aggregate(query, (current, include) => current.Include(include));
return query.ToList<T>();
}
public async Task<IEnumerable<T>> GetAllAsync(Expression<Func<T, bool>>? expression = null, CancellationToken cancellationToken = default, params Expression<Func<T, object>>[] includes)
{
IQueryable<T> query = this.context.Set<T>();
query = includes.Aggregate(query, (current, include) => current.Include(include));
if (expression != null) query = query.Where(expression);
return await query.ToDynamicListAsync<T>(cancellationToken: cancellationToken);
}
public virtual async Task<T?> GetByIdAsync(object id, params Expression<Func<T, object>>[] includes)
{
IQueryable<T> query = this.context.Set<T>();
query = query.Where(entity => entity.Id.Equals(id));
query = includes.Aggregate(query, (current, include) => current.Include(include));
return await query.FirstOrDefaultAsync();
}
public async Task InsertAsync(T obj)
{
_ = await this.context.Set<T>()
.AddAsync(obj);
}
public void Update(T obj)
{
_ = this.context.Set<T>().Attach(obj);
this.context.Entry(obj).State = EntityState.Modified;
}
public void Delete(object id)
{
var existing = this.context
.Set<T>()
.Find(id);
_ = this.context.Set<T>().Remove(existing!);
}
public async Task<PaginatedResult<T>> GetPaginatedListAsync(
int pageNumber,
int pageSize,
string[]? orderBy = null,
Expression<Func<T, bool>>? expression = null,
CancellationToken cancellationToken = default,
params Expression<Func<T, object>>[] includes)
{
IQueryable<T> query = this.context.Set<T>();
query = includes.Aggregate(query, (current, include) => current.Include(include));
if (expression != null) query = query.Where(expression);
var ordering = orderBy?.Any() == true ? string.Join(",", orderBy) : null;
query = !string.IsNullOrWhiteSpace(ordering) ? query.OrderBy(ordering) : query.OrderBy(a => a.Id);
var count = await query
.AsNoTracking()
.CountAsync(cancellationToken: cancellationToken);
var items = await query
.Skip(pageNumber * pageSize)
.Take(pageSize)
.ToDynamicListAsync<T>(cancellationToken: cancellationToken);
return new PaginatedResult<T>(items, count, pageNumber, pageSize);
}
public async Task<int> CountAsync(Expression<Func<T, bool>>? expression = null, CancellationToken cancellationToken = default)
{
IQueryable<T> query = this.context.Set<T>();
if (expression != null) query = query.Where(expression);
return await query
.AsNoTracking()
.CountAsync(cancellationToken: cancellationToken);
}
public async Task<bool> ExistsAsync(Expression<Func<T, bool>> expression, CancellationToken cancellationToken = default)
{
return await this.context.Set<T>().AnyAsync(expression, cancellationToken: cancellationToken);
}
}

@ -0,0 +1,7 @@
using Infrastructure.Entities;
namespace Infrastructure.Repositories;
public interface IUserRepository : IRepository<User>
{
}

@ -0,0 +1,10 @@
using Infrastructure.Entities;
namespace Infrastructure.Repositories;
public class UserRepository : GenericRepository<User>, IUserRepository
{
public UserRepository(OptifitDbContext context) : base(context)
{
}
}

@ -3,13 +3,13 @@ using Microsoft.EntityFrameworkCore;
namespace Infrastructure.Stub;
public class StubbedContext : AlumniDbContext
public class StubbedContext : OptifitDbContext
{
public StubbedContext(DbContextOptions<AlumniDbContext> options) : base(options)
public StubbedContext(DbContextOptions<OptifitDbContext> options) : base(options)
{
}
public StubbedContext(): this(new DbContextOptionsBuilder<AlumniDbContext>()
public StubbedContext(): this(new DbContextOptionsBuilder<OptifitDbContext>()
.UseSqlite("DataSource=:memory:")
.Options)
{
@ -18,105 +18,47 @@ public class StubbedContext : AlumniDbContext
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
var eventEntities = new List<EventEntity>(
[
new EventEntity
{
Id = GenerateGuid().ToString(),
Title = "Laser Game",
Description = "Venez vous amuser et faire du networking lors d'une partie de Laser Game avec vos camarades de promo et d'anciens étudiants !",
Date = GenerateRandomDate(),
nbPlaces = GenerateRandomInt(1, 100)
},
new EventEntity
{
Id = GenerateGuid().ToString(),
Title = "Afterwork Raclette",
Description = "Venez déguster de la raclette et boire un verre lors de notre afterwork recherche de stage et alternance !",
Date = GenerateRandomDate(),
nbPlaces = GenerateRandomInt(1, 100)
},
new EventEntity
{
Id = GenerateGuid().ToString(),
Title = "Conférence : Développeur & IA ?",
Description = "Venez assister à une conférence qui vous permettra de découvrir comment l'IA doit être prise en compte dans le développement d'applications !",
Date = GenerateRandomDate(),
nbPlaces = GenerateRandomInt(1, 100)
}
]
);
var alumniEntities = new List<User>(
var users = new List<User>(
[
new User
{
Id = GenerateGuid().ToString(),
FirstName = "Test",
LastName = "Test",
Email = "test@gmail.com",
EntryYear = "2021",
Password = "1234567890",
Role = "ADMIN"
Name = "Test",
Age = GenerateRandomInt(18, 99),
Height = GenerateRandomInt(150, 200),
Weight = GenerateRandomInt(50, 150),
Sexe = GenerateRandomBool(),
Logo = GenerateRandomString(10),
NbSessionPerWeek = GenerateRandomInt(1, 7),
EGoal = GenerateRandomString(10),
ESleepLevel = GenerateRandomString(10),
ESportLevel = GenerateRandomString(10),
HashPassword = GenerateRandomString(10),
OAuthProvider = null,
OAuthId = null
},
new User
{
Id = GenerateGuid().ToString(),
FirstName = "Test2",
LastName = "Test2",
Email = "test2@gmail.com",
EntryYear = "2021",
Password = "1234567890",
Role = "USER",
}
]
);
var experienceEntities = new List<ExperienceEntity>(
[
new ExperienceEntity
{
Id = GenerateGuid().ToString(),
Title = "Data Scientist",
StartDate = GenerateRandomDate(),
CompanyName = "Michelin",
IsCurrent = GenerateRandomBool()
},
new ExperienceEntity
{
Id = GenerateGuid().ToString(),
Title = "Développeur C# .NET",
StartDate = GenerateRandomDate(),
CompanyName = "CGI",
IsCurrent = GenerateRandomBool()
}
]
);
var formationEntities = new List<FormationEntity>(
Name = "Test",
Age = GenerateRandomInt(18, 99),
Height = GenerateRandomInt(150, 200),
Weight = GenerateRandomInt(50, 150),
Sexe = GenerateRandomBool(),
Logo = GenerateRandomString(10),
NbSessionPerWeek = GenerateRandomInt(1, 7),
EGoal = GenerateRandomString(10),
ESleepLevel = GenerateRandomString(10),
ESportLevel = GenerateRandomString(10),
HashPassword = GenerateRandomString(10),
OAuthProvider = null,
OAuthId = null
[
new FormationEntity
{
Id = GenerateGuid().ToString(),
SchoolName = "IUT Clermont-Ferrand",
Name = "BUT Informatique",
StartDate = GenerateRandomDate(),
IsCurrent = GenerateRandomBool()
},
new FormationEntity
{
Id = GenerateGuid().ToString(),
SchoolName = "Isima",
Name = "Ingénieur Informatique",
StartDate = GenerateRandomDate(),
IsCurrent = GenerateRandomBool()
}
]
);
modelBuilder.Entity<ExperienceEntity>().HasData(experienceEntities);
modelBuilder.Entity<FormationEntity>().HasData(formationEntities);
modelBuilder.Entity<User>().HasData(alumniEntities);
modelBuilder.Entity<EventEntity>().HasData(eventEntities);
modelBuilder.Entity<User>().HasData(users);
}

@ -1,5 +1,5 @@
<div align = center>
<h1>SAE Alica</h1>
<h1>Optifit WebService</h1>
<h2>Entity Framework - API dotnet</h2>
</div>
@ -25,34 +25,24 @@
### Récapitulatif du Projet
Ce repot représente le rendu en API et Entity Framework, dans le cadre de notre SAe Alica.
Ce repot représente le rendu en API et Entity Framework, dans le cadre de notre SAE de 3ème année à l'IUT de Clermont-Ferrand.
<br>
En ce qui concerne la notation, notre travaille se trouve sur la branche **dev**
## Prérequis pour le projet Entity Framework
* [Visual Studio](https://visualstudio.microsoft.com/) - Environnement de développement intégré (IDE) recommandé pour les projets .NET si vous êtes sur Window
* [Rider](https://www.jetbrains.com/fr-fr/rider/) - Environnement de développement intégré (IDE) recommandé pour les projets .NET si vous êtes sur MAC
* [Code First](https://codefirst.iut.uca.fr/) - Outil de versioning
## Prérequis
## Premiers Pas
#### Warning : Le développement se faire sur la branche **dev**
1. Cloner le dépôt Git : *git clone 'https://codefirst.iut.uca.fr/git/sae.alica/API_dotnet.git'*
2. Aller dans le dossier API_dotnet : *cd API_dotnet/*
3. Changer de branche afin d'avoir la dernière version du projet : *git checkout dev*
4. Verifier bien que vous êtes sur la branche dev : *git branch*
5. Lancer le projet avec votre IDE (Rider ou Visual Studio Code)
6. Lancer la solution
7. Profiter des fonctionnalités de l'API via swagger
## Fabriqué avec
* [Visual Studio](https://visualstudio.microsoft.com/) - Environnement de développement intégré (IDE) recommandé pour les projets .NET
* [JetBrain Rider](https://www.jetbrains.com/fr-fr/rider/) - Environnement de développement intégré (IDE) recommandé pour les projets .NET
* [C#](https://learn.microsoft.com/fr-fr/dotnet/csharp/) - Documentation C#
* [Entity Framework](https://learn.microsoft.com/fr-fr/ef/) - Documentation EF
* [CodeFirst](https://codefirst.iut.uca.fr/) - Gitea
## Contributeurs
* [Vianney Jourdy](https://codefirst.iut.uca.fr/git/vianney.jourdy)
* [Tony Fages](https://codefirst.iut.uca.fr/git/tony.fages)
* [Léo TUAILLON](https://codefirst.iut.uca.fr/git/leo.tuaillon)
* [Thomas MUZARD](https://codefirst.iut.uca.fr/git/thomas.muzard)
* [Anthony Richard](https://codefirst.iut.uca.fr/git/anthony.richard)
* [Louis Laborie](https://codefirst.iut.uca.fr/git/louis.laborie)

@ -1,9 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<ActiveDebugProfile>https</ActiveDebugProfile>
<Controller_SelectedScaffolderID>MinimalApiScaffolder</Controller_SelectedScaffolderID>
<Controller_SelectedScaffolderCategoryPath>root/Common/Api</Controller_SelectedScaffolderCategoryPath>
<WebStackScaffolding_ControllerDialogWidth>650</WebStackScaffolding_ControllerDialogWidth>
</PropertyGroup>
</Project>

@ -1,45 +0,0 @@
using Microsoft.AspNetCore.Mvc;
using Server.Dto.Response;
using Asp.Versioning;
using Server.IServices;
using Shared.Criteria;
namespace Server.Controller.v1;
[ApiController]
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/alumni-restricted")]
public class AlumniRestrictedController : ControllerBase
{
private readonly ILogger<AlumniRestrictedController> _logger;
private IAlumnisService _dataServices;
public AlumniRestrictedController(ILogger<AlumniRestrictedController> logger, IAlumnisService dataServices)
{
_logger = logger;
_dataServices = dataServices;
}
[HttpGet]
[ProducesResponseType(typeof(IEnumerable<ResponseAlumniDto>), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[RequireHttps]
public async Task<IActionResult> GetAlumniRestricted([FromQuery] string? lastname, [FromQuery] int page = 1, [FromQuery] int size = 5,
[FromQuery] AlumniOrderCriteria orderCriteria = AlumniOrderCriteria.None, [FromQuery] bool ascending = true)
{
var alumni = await _dataServices.GetAlumnisRestricted(lastname, page, size, orderCriteria, ascending);
if( alumni.Count == 0) return NoContent();
return Ok(alumni.Alumnis);
}
[HttpGet("{id}")]
[ProducesResponseType(typeof(ResponseAlumniDto), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[RequireHttps]
public IActionResult GetAlumniRestrictedById(string id)
{
var alumni = _dataServices.GetAlumniRestrictedById(id);
return alumni.Result == null ? NotFound() : Ok(alumni.Result);
}
}

@ -1,56 +0,0 @@
using Microsoft.AspNetCore.Mvc;
using Server.Dto.Request;
using Server.Dto.Response;
using Asp.Versioning;
using Server.IServices;
using Shared.Criteria;
namespace Server.Controller.v1;
[ApiController]
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/[controller]")]
public class AlumnisController : ControllerBase
{
private readonly ILogger<AlumnisController> _logger;
private IAlumnisService _dataServices;
public AlumnisController(ILogger<AlumnisController> logger, IAlumnisService dataServices)
{
_logger = logger;
_dataServices = dataServices;
}
[HttpGet]
[ProducesResponseType(typeof(IEnumerable<ResponseAlumniDto>), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[RequireHttps]
public IActionResult GetAlumni([FromQuery] string? lastname, [FromQuery] int page = 1, [FromQuery] int size = 5,
[FromQuery] AlumniOrderCriteria orderCriteria = AlumniOrderCriteria.None, [FromQuery] bool ascending = true)
{
var alumni = _dataServices.GetAlumnis(lastname, page, size, orderCriteria, ascending);
return alumni.Result.Count == 0 ? NoContent() : Ok(alumni.Result.Alumnis);
}
[HttpPost()]
[ProducesResponseType(typeof(ResponseAlumniDto), StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[RequireHttps]
public IActionResult CreateAlumni([FromBody] RequestAlumniDto alumniDto)
{
var alumni = _dataServices.CreateAlumni(alumniDto);
return alumni.Result == null ? BadRequest() : CreatedAtAction(nameof(CreateAlumni), alumni);
}
[HttpGet("{id}")]
[ProducesResponseType(typeof(ResponseAlumniDto), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[RequireHttps]
public IActionResult GetAlumniById(string id)
{
var alumni = _dataServices.GetAlumniById(id);
return alumni.Result == null ? NotFound() : Ok(alumni);
}
}

@ -1,85 +0,0 @@
using Microsoft.AspNetCore.Mvc;
using Server.Dto.Request;
using Server.Dto.Response;
using Asp.Versioning;
using Server.IServices;
using Shared.Criteria;
namespace Server.Controller.v1;
[ApiController]
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/[controller]")]
public class EventsController : ControllerBase
{
private readonly ILogger<EventsController> _logger;
private readonly IEventsService _dataServices;
public EventsController(ILogger<EventsController> logger, IEventsService dataServices)
{
_logger = logger;
_dataServices = dataServices;
}
[HttpGet]
[ProducesResponseType(typeof(IEnumerable<ResponseEventDto>), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status204NoContent)]
public async Task<IActionResult> GetEvents([FromQuery] string? title, [FromQuery] int page = 1, [FromQuery] int size = 5,
[FromQuery] EventOrderCriteria criteria = EventOrderCriteria.Date, [FromQuery] bool ascending = true)
{
var result = await _dataServices.GetEvents(title, page, size, criteria, ascending);
if (result.Count == 0) return NoContent();
return Ok(result.Events);
}
[HttpGet("{id}")]
[ProducesResponseType(typeof(ResponseEventDto), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[RequireHttps]
public IActionResult GetEventById(string id)
{
var evt = _dataServices.GetEventById(id);
return evt.Result == null ? NotFound() : Ok(evt.Result);
}
[HttpPost]
[ProducesResponseType(typeof(ResponseEventDto), StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[RequireHttps]
public IActionResult CreateEvent([FromBody] RequestEventDto eventDto)
{
var evenement = _dataServices.CreateEvent(eventDto);
return evenement.Result == null ? BadRequest() : CreatedAtAction(nameof(CreateEvent), evenement.Result);
}
[HttpPut("{id}")]
[ProducesResponseType(typeof(ResponseEventDto), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[RequireHttps]
public IActionResult UpdateEvent(string id, [FromBody] RequestEventDto evenement)
{
var eventSelected = _dataServices.UpdateEvent(id, evenement);
return eventSelected == Task.FromResult<ResponseEventDto?>(null) ? BadRequest() : Ok(eventSelected.Result);
}
[HttpDelete("{id}")]
[ProducesResponseType(typeof(bool), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[RequireHttps]
public IActionResult DeleteEvent(string id)
{
return _dataServices.DeleteEvent(id).Result ? Ok() : NotFound();
}
[HttpGet("Alica/{id}")]
[ProducesResponseType(typeof(IEnumerable<ResponseEventDto>), 200)]
[RequireHttps]
public IActionResult GetEventsByAlumniId(string id)
{
//var evenement = _dataServices.GetData();
//var evenementSelected = evenement.Result.Where(x => x.AlicaId == id).ToList();
//return evenementSelected.Count() == 0 ? NoContent() : Ok(evenementSelected);
return Ok();
}
}

@ -1,90 +0,0 @@
using Microsoft.AspNetCore.Mvc;
using Server.Dto.Request;
using Server.Dto.Response;
using Asp.Versioning;
using Server.IServices;
using Shared.Criteria;
namespace Server.Controller.v1;
[ApiController]
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/[controller]")]
public class ExperiencesController : ControllerBase
{
private readonly ILogger<ExperiencesController> _logger;
private readonly IExperiencesService _dataServices;
public ExperiencesController(ILogger<ExperiencesController> logger, IExperiencesService dataServices)
{
_logger = logger;
_dataServices = dataServices;
}
[HttpGet]
[ProducesResponseType(typeof(IEnumerable<ResponseExperienceDto>), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[RequireHttps]
public async Task<IActionResult> GetExperiences([FromQuery] string? title, [FromQuery] int page = 1, [FromQuery] int size = 5,
[FromQuery] ExperienceOrderCriteria criteria = ExperienceOrderCriteria.StartDate, [FromQuery] bool ascending = true)
{
var result = await _dataServices.GetExperiences(title, page, size, criteria, ascending);
if (result.Count == 0) return NoContent();
return Ok(result.Experiences);
}
[HttpGet("{id}")]
[ProducesResponseType(typeof(ResponseExperienceDto), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[RequireHttps]
public IActionResult GetExperienceById(string id)
{
var experience = _dataServices.GetExperienceById(id);
return experience.Result == null ? NotFound() : Ok(experience.Result);
}
[HttpPost]
[ProducesResponseType(typeof(ResponseExperienceDto), StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[RequireHttps]
public IActionResult CreateExperience([FromBody] RequestExperienceDto experienceDto)
{
var experience = _dataServices.CreateExperience(experienceDto);
return experience.Result == null ? BadRequest() : CreatedAtAction(nameof(CreateExperience), experience.Result);
}
[HttpPut("{id}")]
[ProducesResponseType(typeof(ResponseExperienceDto), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[RequireHttps]
public IActionResult UpdateExperience(string id, [FromBody] RequestExperienceDto experience)
{
var experienceSelected = _dataServices.UpdateExperience(id, experience);
return experienceSelected.Result == null ? BadRequest() : Ok(experienceSelected.Result);
}
[HttpDelete("{id}")]
[ProducesResponseType(typeof(bool), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[RequireHttps]
public IActionResult DeleteExperience(string id)
{
return _dataServices.DeleteExperience(id).Result ? Ok() : NotFound();
}
[HttpGet("Alica/{id}")]
[ProducesResponseType(typeof(IEnumerable<ResponseExperienceDto>), 200)]
[RequireHttps]
public IActionResult GetExperiencesByAlumniId(string id)
{
//var experience = _dataServices.GetData();
//var experienceSelected = experience.Result.Where(x => x.AlicaId == id).ToList();
//return experienceSelected.Count() == 0 ? NoContent() : Ok(experienceSelected);
return Ok();
}
}

@ -1,86 +0,0 @@
using Microsoft.AspNetCore.Mvc;
using Server.Dto.Request;
using Server.Dto.Response;
using Asp.Versioning;
using Server.IServices;
using Shared.Criteria;
namespace Server.Controller.v1;
[ApiController]
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/[controller]")]
public class FormationsController : ControllerBase
{
private readonly ILogger<FormationsController> _logger;
private IFormationsService _dataServices;
public FormationsController(ILogger<FormationsController> logger, IFormationsService dataServices)
{
_logger = logger;
_dataServices = dataServices;
}
[HttpGet]
[ProducesResponseType(typeof(IEnumerable<ResponseFormationDto>), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[RequireHttps]
public async Task<IActionResult> GetFormations([FromQuery] string? name, [FromQuery] int page = 1, [FromQuery] int size = 5,
[FromQuery] FormationOrderCriteria criteria = FormationOrderCriteria.StartDate, [FromQuery] bool ascending = true)
{
var result = await _dataServices.GetFormations(name, page, size, criteria, ascending);
if (result.Count == 0) return NoContent();
return Ok(result.Formations);
}
[HttpGet("{id}")]
[ProducesResponseType(typeof(ResponseFormationDto), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[RequireHttps]
public IActionResult GetFormationById(string id)
{
var formation = _dataServices.GetFormationById(id);
return formation.Result == null ? NotFound() : Ok(formation.Result);
}
[HttpPost]
[ProducesResponseType(typeof(ResponseFormationDto), StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[RequireHttps]
public IActionResult CreateFormation([FromBody] RequestFormationDto experienceDto)
{
var formation = _dataServices.CreateFormation(experienceDto);
return formation.Result == null ? BadRequest() : CreatedAtAction(nameof(CreateFormation), formation.Result);
}
[HttpPut("{id}")]
[ProducesResponseType(typeof(ResponseFormationDto), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[RequireHttps]
public IActionResult UpdateFormation(string id, [FromBody] RequestFormationDto formation)
{
var formationSelected = _dataServices.UpdateFormation(id, formation);
return formationSelected.Result == null ? BadRequest() : Ok(formationSelected.Result);
}
[HttpDelete("{id}")]
[ProducesResponseType(typeof(bool), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[RequireHttps]
public IActionResult DeleteFormation(string id)
{
return _dataServices.DeleteFormation(id).Result ? Ok() : NotFound();
}
[HttpGet("Alica/{id}")]
[ProducesResponseType(typeof(IEnumerable<ResponseFormationDto>), StatusCodes.Status200OK)]
[RequireHttps]
public IActionResult GetFormationsByAlumniId(string id)
{
//var formation = _dataServices.GetData();
//var formationSelected = formation.Result.Where(x => x.AlicaId == id).ToList();
//return formationSelected.Count() == 0 ? NoContent() : Ok(formationSelected);
return Ok();
}
}

@ -0,0 +1,45 @@
using Microsoft.AspNetCore.Mvc;
using Server.Dto.Request;
using Server.Dto.Response;
using Asp.Versioning;
using Server.IServices;
namespace Server.Controller.v1;
[ApiController]
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/[controller]")]
public class UsersController : ControllerBase
{
private readonly ILogger<UsersController> _logger;
private IUsersService _dataServices;
public UsersController(ILogger<UsersController> logger, IUsersService dataServices)
{
_logger = logger;
_dataServices = dataServices;
}
[HttpGet]
[ProducesResponseType(typeof(IEnumerable<ResponseUserDto>), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[RequireHttps]
public IActionResult GetUsers([FromQuery] int pageIndex = 1, [FromQuery] int pageSize = 5, [FromQuery] bool ascending = true)
{
var users = _dataServices.GetUsers(pageIndex, pageSize, ascending);
return users.Result.TotalCount == 0 ? NoContent() : Ok(users);
}
[HttpGet("{id}")]
[ProducesResponseType(typeof(ResponseUserDto), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[RequireHttps]
public IActionResult GetAlumniById(string id)
{
var alumni = _dataServices.GetUserById(id);
return alumni.Result == null ? NotFound() : Ok(alumni);
}
}

@ -1,30 +0,0 @@
using System.ComponentModel.DataAnnotations;
namespace Server.Dto.Request;
public class RequestAlumniDto
{
[EmailAddress(ErrorMessage = "Invalid Email")]
[Required(ErrorMessage = "Email is required")]
public string Email { get; set; }
[Required(ErrorMessage = "Password is required")]
public string Password { get; set; }
[Required(ErrorMessage = "EntryYear is required")]
public string EntryYear { get; set; }
[Required(ErrorMessage = "FirstName is required")]
public string FirstName { get; set; }
[Required(ErrorMessage = "LastName is required")]
public string LastName { get; set; }
public string? LinkedinUrl { get; set; }
public string? GithubUrl { get; set; }
public string? PortfolioUrl { get; set; }
public string? ImageUrl { get; set; }
}

@ -1,23 +0,0 @@
using System.ComponentModel.DataAnnotations;
namespace Server.Dto.Request;
public class RequestEventDto
{
[Required(ErrorMessage = "AlumniId is required")]
public string AlumniId { get; set; }
[Required(ErrorMessage = "Title is required")]
public string Title { get; set; }
[Required(ErrorMessage = "Description is required")]
public string Description { get; set; }
[Required(ErrorMessage = "Date is required")]
public DateTime Date { get; set; }
[Required(ErrorMessage = "NumberOfParticipants is required")]
public int nbMaxRegistrations { get; set; }
public string? ImageUrl { get; set; }
}

@ -1,23 +0,0 @@
using System.ComponentModel.DataAnnotations;
namespace Server.Dto.Request;
public class RequestExperienceDto
{
[Required(ErrorMessage = "AlumniId is required")]
public string AlumniId { get; set; }
[Required(ErrorMessage = "Title of post is required")]
public string Title { get; set; }
[Required(ErrorMessage = "StartingDate is required")]
public DateTime StartingDate { get; set; }
public DateTime? EndingDate { get; set; }
[Required(ErrorMessage = "Company's name is required")]
public string CompanyName { get; set; }
[Required(ErrorMessage = "CurrentFormation is required")]
public bool CurrentJob { get; set; }
}

@ -1,23 +0,0 @@
using System.ComponentModel.DataAnnotations;
namespace Server.Dto.Request;
public class RequestFormationDto
{
[Required(ErrorMessage = "AlumniId is required")]
public string AlumniId { get; set; }
[Required(ErrorMessage = "Name of formation is required")]
public string Name { get; set; }
[Required(ErrorMessage = "StartingDate is required")]
public DateTime StartingDate { get; set; }
public DateTime? EndingDate { get; set; }
[Required(ErrorMessage = "School's name is required")]
public string SchoolName { get; set; }
[Required(ErrorMessage = "CurrentFormation is required")]
public bool CurrentFormation { get; set; }
}

@ -0,0 +1,9 @@
using System.ComponentModel.DataAnnotations;
namespace Server.Dto.Request;
public class RequestUserDto
{
[Required(ErrorMessage = "FirstName is required")]
public string Name { get; set; }
}

@ -1,19 +0,0 @@
using Shared.Enums;
namespace Server.Dto.Response;
public class ResponseAlumniDto
{
public string Id { get; set; }
public string Email { get; set; }
public ERole ERole { get; set; }
public string EntryYear { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string? LinkedinUrl { get; set; }
public string? GithubUrl { get; set; }
public string? PortfolioUrl { get; set; }
public string? ImageUrl { get; set; }
public IEnumerable<ResponseExperienceDto> Experiences { get; set; } = new List<ResponseExperienceDto>();
public IEnumerable<ResponseFormationDto> Formations { get; set; } = new List<ResponseFormationDto>();
}

@ -1,13 +0,0 @@
namespace Server.Dto.Response;
public class ResponseEventDto
{
public string Id { get; set; }
public string? AlumniId { get; set; }
public string Title { get; set; }
public string? ImageUrl { get; set; }
public string Description { get; set; }
public DateTime Date { get; set; }
public int nbMaxRegistrations { get; set; }
public int nbRegistrations { get; set; }
}

@ -1,12 +0,0 @@
namespace Server.Dto.Response;
public class ResponseExperienceDto
{
public string Id { get; set; }
public string? AlumniId { get; set; }
public string Title { get; set; }
public DateTime StartingDate { get; set; }
public DateTime? EndingDate { get; set; }
public string CompanyName { get; set; }
public bool CurrentJob { get; set; }
}

@ -1,12 +0,0 @@
namespace Server.Dto.Response;
public class ResponseFormationDto
{
public string Id { get; set; }
public string? AlumniId { get; set; }
public string Name { get; set; }
public DateTime StartingDate { get; set; }
public DateTime? EndingDate { get; set; }
public string SchoolName { get; set; }
public bool CurrentFormation { get; set; }
}

@ -1,10 +0,0 @@
namespace Server.Dto.Response;
public class ResponseRestrictedAlumniDto
{
public string Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string? LinkedinUrl { get; set; }
public string? ImageUrl { get; set; }
}

@ -0,0 +1,15 @@
namespace Server.Dto.Response;
public class ResponseUserDto
{
public string Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public float Height { get; set; }
public float Weight { get; set; }
public bool Sexe { get; set; }
public string? Logo { get; set; }
public int NbSessionPerWeek { get; set; }
public string? EGoal { get; set; }
public string? ESleepLevel { get; set; }
}

@ -1,17 +0,0 @@
using Server.Dto.Request;
using Server.Dto.Response;
using Shared.Criteria;
namespace Server.IServices;
public interface IAlumnisService
{
Task<(long Count, IEnumerable<ResponseRestrictedAlumniDto> Alumnis)> GetAlumnisRestricted(string? lastname, int page, int size, AlumniOrderCriteria orderCriteria = AlumniOrderCriteria.None, bool ascending = true);
Task<ResponseRestrictedAlumniDto?> GetAlumniRestrictedById(string id);
Task<ResponseAlumniDto?> GetAlumniById(string id);
Task<(long Count, IEnumerable<ResponseAlumniDto> Alumnis)> GetAlumnis
(string? lastname, int page, int size, AlumniOrderCriteria orderCriteria = AlumniOrderCriteria.None,
bool ascending = true);
Task<ResponseAlumniDto?> CreateAlumni(RequestAlumniDto alumni);
}

@ -1,18 +0,0 @@
using Server.Dto.Request;
using Server.Dto.Response;
using Shared.Criteria;
namespace Server.IServices;
public interface IEventsService
{
Task<ResponseEventDto?> GetEventById(string id);
Task<(long Count, IEnumerable<ResponseEventDto> Events)> GetEvents
(string? title, int page, int size, EventOrderCriteria orderCriteria = EventOrderCriteria.Date,
bool ascending = true);
Task<ResponseEventDto?> CreateEvent(RequestEventDto evt);
Task<ResponseEventDto?> UpdateEvent(string id, RequestEventDto evt);
Task<bool> DeleteEvent(string id);
}

@ -1,18 +0,0 @@
using Server.Dto.Request;
using Server.Dto.Response;
using Shared.Criteria;
namespace Server.IServices;
public interface IExperiencesService
{
Task<ResponseExperienceDto?> GetExperienceById(string id);
Task<(long Count, IEnumerable<ResponseExperienceDto> Experiences)> GetExperiences
(string? title, int page, int size,
ExperienceOrderCriteria orderCriteria = ExperienceOrderCriteria.EndDate, bool ascending = true);
Task<ResponseExperienceDto?> CreateExperience(RequestExperienceDto experience);
Task<ResponseExperienceDto?> UpdateExperience(string id, RequestExperienceDto experience);
Task<bool> DeleteExperience(string id);
}

@ -1,17 +0,0 @@
using Server.Dto.Request;
using Server.Dto.Response;
using Shared.Criteria;
namespace Server.IServices;
public interface IFormationsService
{
Task<ResponseFormationDto?> GetFormationById(string id);
Task<(long Count, IEnumerable<ResponseFormationDto> Formations)> GetFormations
(string? name, int page, int size, FormationOrderCriteria orderCriteria, bool ascending = true);
Task<ResponseFormationDto?> CreateFormation(RequestFormationDto formation);
Task<ResponseFormationDto?> UpdateFormation(string id, RequestFormationDto formation);
Task<bool> DeleteFormation(string id);
}

@ -0,0 +1,12 @@
using Infrastructure.Entities;
using Server.Dto.Request;
using Server.Dto.Response;
using Shared;
namespace Server.IServices;
public interface IUsersService
{
Task<ResponseUserDto?> GetUserById(string id);
Task<PaginatedResult<ResponseUserDto>> GetUsers(int page, int size, bool ascending = true);
}

@ -1,64 +0,0 @@
using Infrastructure.Entities;
using Server.Dto.Request;
using Server.Dto.Response;
using Shared.Enums;
namespace Server.Mappers;
public static class AlumnisMappers
{
public static ResponseAlumniDto ToDto(this User alumni)
{
return new ResponseAlumniDto
{
Id = alumni.Id,
Email = alumni.Email,
ERole = alumni.Role.ToERole(),
EntryYear = alumni.EntryYear,
FirstName = alumni.FirstName,
LastName = alumni.LastName,
LinkedinUrl = alumni.Linkedin,
GithubUrl = alumni.Github,
PortfolioUrl = alumni.WebSite,
Experiences = alumni.Experiences.Select(e => e.ToDto()),
Formations = alumni.Formations.Select(f => f.ToDto())
};
}
public static ResponseRestrictedAlumniDto ToDtoRestricted(this User alumni)
{
return new ResponseRestrictedAlumniDto
{
Id = alumni.Id,
FirstName = alumni.FirstName,
LastName = alumni.LastName,
LinkedinUrl = alumni.Linkedin
};
}
public static User ToEntity(this RequestAlumniDto alumni)
{
return new User
{
Email = alumni.Email,
Password = alumni.Password,
EntryYear = alumni.EntryYear,
FirstName = alumni.FirstName,
LastName = alumni.LastName,
Linkedin = alumni.LinkedinUrl,
Github = alumni.GithubUrl,
WebSite = alumni.PortfolioUrl,
Role = "USER"
};
}
public static ERole ToERole(this string role)
{
return role switch
{
"ADMIN" => ERole.ADMIN,
"MODERATOR" => ERole.MODERATOR,
"USER" => ERole.USER
};
}
}

@ -1,32 +0,0 @@
using Infrastructure.Entities;
using Server.Dto.Request;
using Server.Dto.Response;
namespace Server.Mappers;
public static class EventsMappers
{
public static ResponseEventDto ToDto(this EventEntity evt)
{
return new ResponseEventDto
{
Id = evt.Id,
Title = evt.Title,
Description = evt.Description,
Date = evt.Date,
nbMaxRegistrations = evt.nbPlaces,
nbRegistrations = evt.Participants.Count
};
}
public static EventEntity ToEntity(this RequestEventDto evt)
{
return new EventEntity
{
Title = evt.Title,
Description = evt.Description,
Date = evt.Date,
nbPlaces = evt.nbMaxRegistrations
};
}
}

@ -1,36 +0,0 @@
using Infrastructure.Entities;
using Server.Dto.Request;
using Server.Dto.Response;
namespace Server.Mappers
{
public static class ExperiencesMappers
{
public static ResponseExperienceDto ToDto(this ExperienceEntity exp)
{
return new ResponseExperienceDto
{
Id = exp.Id,
AlumniId = exp.AlumniId,
Title= exp.Title,
StartingDate = exp.StartDate,
EndingDate = exp.EndDate,
CompanyName = exp.CompanyName,
CurrentJob = exp.IsCurrent,
};
}
public static ExperienceEntity ToEntity(this RequestExperienceDto exp)
{
return new ExperienceEntity
{
AlumniId = exp.AlumniId,
Title = exp.Title,
StartDate = exp.StartingDate,
EndDate = exp.EndingDate,
CompanyName = exp.CompanyName,
IsCurrent = exp.CurrentJob,
};
}
}
}

@ -1,35 +0,0 @@
using Infrastructure.Entities;
using Server.Dto.Request;
using Server.Dto.Response;
namespace Server.Mappers
{
public static class FormationsMappers
{
public static ResponseFormationDto ToDto(this FormationEntity form)
{
return new ResponseFormationDto
{
Id = form.Id,
AlumniId = form.AlumniId,
Name = form.Name,
StartingDate = form.StartDate,
EndingDate = form.EndDate,
SchoolName = form.SchoolName,
CurrentFormation = form.IsCurrent,
};
}
public static FormationEntity ToEntity(this RequestFormationDto form)
{
return new FormationEntity
{
SchoolName = form.SchoolName,
Name = form.Name,
StartDate = form.StartingDate,
EndDate = form.EndingDate,
IsCurrent = form.CurrentFormation
};
}
}
}

@ -0,0 +1,36 @@
using Infrastructure.Entities;
using Server.Dto.Request;
using Server.Dto.Response;
using AutoMapper;
namespace Server.Mappers;
public class UsersMappers : Profile
{
public UsersMappers()
{
_ = CreateMap<User, ResponseUserDto>()
.ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.Id))
.ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.Name))
.ForMember(dest => dest.Age, opt => opt.MapFrom(src => src.Age))
.ForMember(dest => dest.Height, opt => opt.MapFrom(src => src.Height))
.ForMember(dest => dest.Weight, opt => opt.MapFrom(src => src.Weight))
.ForMember(dest => dest.Sexe, opt => opt.MapFrom(src => src.Sexe))
.ForMember(dest => dest.Logo, opt => opt.MapFrom(src => src.Logo))
.ForMember(dest => dest.NbSessionPerWeek, opt => opt.MapFrom(src => src.NbSessionPerWeek))
.ForMember(dest => dest.EGoal, opt => opt.MapFrom(src => src.EGoal))
.ForMember(dest => dest.ESleepLevel, opt => opt.MapFrom(src => src.ESleepLevel));
_ = CreateMap<RequestUserDto, User>()
.ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.Name));
//.ForMember(dest => dest.Age, opt => opt.MapFrom(src => src.Age))
//.ForMember(dest => dest.Height, opt => opt.MapFrom(src => src.Height))
//.ForMember(dest => dest.Weight, opt => opt.MapFrom(src => src.Weight))
//.ForMember(dest => dest.Sexe, opt => opt.MapFrom(src => src.Sexe))
//.ForMember(dest => dest.Logo, opt => opt.MapFrom(src => src.Logo))
//.ForMember(dest => dest.NbSessionPerWeek, opt => opt.MapFrom(src => src.NbSessionPerWeek))
//.ForMember(dest => dest.EGoal, opt => opt.MapFrom(src => src.EGoal))
//.ForMember(dest => dest.ESleepLevel, opt => opt.MapFrom(src => src.ESleepLevel));
}
}

@ -4,53 +4,57 @@ using Server.IServices;
using Asp.Versioning;
using Server.Services;
using Microsoft.OpenApi.Models;
using Infrastructure.Repositories;
using AutoMapper;
using Server.Mappers;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddScoped<IAlumnisService, AlumniService>();
builder.Services.AddScoped<IExperiencesService, ExperienceServices>();
builder.Services.AddScoped<IFormationsService, FormationServices>();
builder.Services.AddScoped<IEventsService, EventServices>();
builder.Services.AddScoped<IUsersService, UsersService>();
builder.Services.AddScoped<UserRepository>(); // Register UserRepository
builder.Services.AddControllers();
builder.Services.AddDbContext<AlumniDbContext>(options =>
builder.Services.AddDbContext<OptifitDbContext>(options =>
options.UseSqlite("Data Source=FirstTest.db"));
// Register AutoMapper
builder.Services.AddAutoMapper(typeof(UsersMappers));
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
//allow us to have lowercase urls (/alica instead of /Alica)
builder.Services.AddRouting(options => options.LowercaseUrls = true);
builder.Services.AddSwaggerGen(c =>
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Optifit API", Version = "v1" })
);
// Add API's versionning
// Add API's versioning
builder.Services.AddApiVersioning(options =>
{
{
options.DefaultApiVersion = new ApiVersion(1, 0);
options.AssumeDefaultVersionWhenUnspecified = true;
options.ReportApiVersions = true;
})
.AddApiExplorer(options =>
{
})
.AddApiExplorer(options =>
{
options.GroupNameFormat = "'v'VVV";
options.SubstituteApiVersionInUrl = true;
});
});
builder.Services.AddRouting(options => options.LowercaseUrls = true);
builder.Services.AddSwaggerGen(c =>
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Alica API First Version", Version = "v1" })
);
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Optifit API v1");
c.RoutePrefix = string.Empty; // Serve Swagger UI at the app's root
});
}
app.UseHttpsRedirection();
// app.UseAuthorization();
app.UseAuthorization();
app.MapControllers();
app.Run();

@ -1,13 +1,4 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:8364",
"sslPort": 44312
}
},
"profiles": {
"http": {
"commandName": "Project",

@ -10,6 +10,7 @@
<ItemGroup>
<PackageReference Include="Asp.Versioning.Mvc.ApiExplorer" Version="8.0.0" />
<PackageReference Include="AutoMapper" Version="13.0.1" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="8.0.1" />
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.2.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.1" />

@ -1,8 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<ActiveDebugProfile>https</ActiveDebugProfile>
<Controller_SelectedScaffolderID>ApiControllerEmptyScaffolder</Controller_SelectedScaffolderID>
<Controller_SelectedScaffolderCategoryPath>root/Common/Api</Controller_SelectedScaffolderCategoryPath>
</PropertyGroup>
</Project>

@ -1,83 +0,0 @@
using Infrastructure;
using Microsoft.EntityFrameworkCore;
using Server.Dto.Request;
using Server.Dto.Response;
using Server.IServices;
using Server.Mappers;
using Shared.Criteria;
namespace Server.Services;
public class AlumniService(AlumniDbContext context) : IAlumnisService
{
public Task<(long Count, IEnumerable<ResponseRestrictedAlumniDto> Alumnis)> GetAlumnisRestricted(string? lastname, int page, int size,
AlumniOrderCriteria orderCriteria = AlumniOrderCriteria.None, bool ascending = true)
{
var query = context.Alumni.Skip((page-1) * size).Take(size);
if (lastname != null)
{
query = context.Alumni.Where(e => e.LastName.Contains(lastname)).Skip((page-1) * size).Take(size);
}
switch (orderCriteria)
{
case AlumniOrderCriteria.Name:
query = ascending ? query.OrderBy(e => e.LastName) : query.OrderByDescending(e => e.LastName);
break;
case AlumniOrderCriteria.None:
break;
}
var count = query.LongCount();
return Task.FromResult((count, query.AsEnumerable().Select(e => e.ToDtoRestricted())));
}
public Task<ResponseRestrictedAlumniDto?> GetAlumniRestrictedById(string id)
{
var result = context.Alumni.FirstOrDefault(e => e.Id == id);
return Task.FromResult(result?.ToDtoRestricted());
}
public Task<ResponseAlumniDto?> GetAlumniById(string id)
{
var result = context.Alumni
.Include(a => a.Experiences)
.Include(a => a.Formations)
.FirstOrDefault(e => e.Id == id);
return Task.FromResult(result?.ToDto());
}
public Task<(long Count, IEnumerable<ResponseAlumniDto> Alumnis)> GetAlumnis(string? lastname, int page, int size,
AlumniOrderCriteria orderCriteria = AlumniOrderCriteria.None,
bool ascending = true)
{
var query = context.Alumni
.Include(a => a.Experiences)
.Include(a => a.Formations)
.Skip((page-1) * size)
.Take(size);
if (lastname != null)
{
query = context.Alumni.Where(e => e.LastName.Contains(lastname))
.Include(a => a.Experiences)
.Include(a => a.Formations)
.Skip((page-1) * size)
.Take(size);
}
switch (orderCriteria)
{
case AlumniOrderCriteria.Name:
query = ascending ? query.OrderBy(e => e.LastName) : query.OrderByDescending(e => e.LastName);
break;
case AlumniOrderCriteria.None:
break;
}
var count = query.LongCount();
return Task.FromResult((count, query.AsEnumerable().Select(e => e.ToDto())));
}
public Task<ResponseAlumniDto?> CreateAlumni(RequestAlumniDto alumni)
{
var result = context.Alumni.AddAsync(alumni.ToEntity());
context.SaveChangesAsync();
return Task.FromResult(result.Result?.Entity.ToDto());
}
}

@ -1,73 +0,0 @@
using Infrastructure;
using Server.Dto.Request;
using Server.Dto.Response;
using Server.IServices;
using Server.Mappers;
using Shared.Criteria;
namespace Server.Services;
/// <summary>
/// Opération CRUD des évènements
/// </summary>
/// <remarks> TODO : manque subscribe subscribers unsubscribe et récupérer les inscription d'un alumni </remarks>
public class EventServices(AlumniDbContext context) : IEventsService
{
public Task<ResponseEventDto?> GetEventById(string id)
{
var result = context.Events.FirstOrDefault(e => e.Id == id);
return Task.FromResult(result?.ToDto());
}
public Task<(long Count, IEnumerable<ResponseEventDto> Events)> GetEvents(string? title, int page, int size,
EventOrderCriteria orderCriteria = EventOrderCriteria.Date, bool ascending = true)
{
var query = context.Events.Skip((page-1) * size).Take(size);
if (title != null)
{
query = context.Events.Where(e => e.Title.Contains(title)).Skip((page-1) * size).Take(size);
}
switch (orderCriteria)
{
case EventOrderCriteria.Date:
query = ascending ? query.OrderBy(e => e.Date) : query.OrderByDescending(e => e.Date);
break;
case EventOrderCriteria.Title:
query = ascending ? query.OrderBy(e => e.Title) : query.OrderByDescending(e => e.Title);
break;
case EventOrderCriteria.NbPlaces:
query = ascending ? query.OrderBy(e => e.nbPlaces) : query.OrderByDescending(e => e.nbPlaces);
break;
}
var count = query.LongCount();
return Task.FromResult((count, query.AsEnumerable().Select(e => e.ToDto())));
}
public Task<ResponseEventDto?> CreateEvent(RequestEventDto evt)
{
var result = context.Events.AddAsync(evt.ToEntity());
context.SaveChangesAsync();
return Task.FromResult(result.Result.Entity.ToDto());
}
public Task<ResponseEventDto?> UpdateEvent(string id, RequestEventDto evt)
{
var result = context.Events.FirstOrDefault(e => e.Id == id);
if (result == null) return Task.FromResult<ResponseEventDto?>(null);
result.Title = evt.Title;
result.Description = evt.Description;
result.Date = evt.Date;
result.nbPlaces = evt.nbMaxRegistrations;
context.SaveChangesAsync();
return Task.FromResult(result.ToDto());
}
public Task<bool> DeleteEvent(string id)
{
var result = context.Events.FirstOrDefault(e => e.Id == id);
if (result == null) return Task.FromResult(false);
context.Events.Remove(result);
context.SaveChangesAsync();
return Task.FromResult(true);
}
}

@ -1,82 +0,0 @@
using Infrastructure;
using Server.Dto.Request;
using Server.Dto.Response;
using Server.IServices;
using Shared.Criteria;
using Server.Mappers;
namespace Server.Services;
public class ExperienceServices(AlumniDbContext context) : IExperiencesService
{
public Task<ResponseExperienceDto?> GetExperienceById(string id)
{
var result = context.Experiences.FirstOrDefault(exp => exp.Id == id);
return Task.FromResult(result?.ToDto());
}
public Task<(long Count, IEnumerable<ResponseExperienceDto> Experiences)> GetExperiences(string? title, int page, int size,
ExperienceOrderCriteria orderCriteria = ExperienceOrderCriteria.EndDate, bool ascending = true)
{
var query = context.Experiences
.Skip((page-1) * size)
.Take(size);
if (title != null)
{
query = context.Experiences
.Where(e => e.Title.Contains(title))
.Skip((page-1) * size)
.Take(size);
}
switch (orderCriteria)
{
case ExperienceOrderCriteria.StartDate:
query = ascending ? query.OrderBy(e => e.StartDate) : query.OrderByDescending(e => e.StartDate);
break;
case ExperienceOrderCriteria.EndDate:
query = ascending ? query.OrderBy(e => e.EndDate) : query.OrderByDescending(e => e.EndDate);
break;
case ExperienceOrderCriteria.Title:
query = ascending ? query.OrderBy(e => e.Title) : query.OrderByDescending(e => e.Title);
break;
}
var count = query.LongCount();
return Task.FromResult((count, query.AsEnumerable().Select(e => e.ToDto())));
}
public Task<ResponseExperienceDto?> CreateExperience(RequestExperienceDto experience)
{
var result = context.Experiences.AddAsync(experience.ToEntity());
var alica = context.Alumni.FirstOrDefault(a => a.Id == experience.AlumniId);
alica?.Experiences.Add(result.Result.Entity);
context.SaveChangesAsync();
return Task.FromResult(result.Result.Entity.ToDto());
}
public Task<ResponseExperienceDto?> UpdateExperience(string id, RequestExperienceDto experience)
{
var result = context.Experiences.FirstOrDefault(e => e.Id == id);
if (result == null)
{
return Task.FromResult<ResponseExperienceDto?>(null);
}
result.Title = experience.Title;
result.StartDate = experience.StartingDate;
result.EndDate = experience.EndingDate;
result.CompanyName = experience.CompanyName;
result.IsCurrent = experience.CurrentJob;
context.SaveChangesAsync();
return Task.FromResult(result.ToDto());
}
public Task<bool> DeleteExperience(string id)
{
var result = context.Experiences.FirstOrDefault(e => e.Id == id);
if (result == null)
return Task.FromResult(false);
context.Experiences.Remove(result);
context.SaveChangesAsync();
return Task.FromResult(true);
}
}

@ -1,79 +0,0 @@
using Infrastructure;
using Server.Dto.Request;
using Server.Dto.Response;
using Server.IServices;
using Shared.Criteria;
using Server.Mappers;
namespace Server.Services;
public class FormationServices(AlumniDbContext context) : IFormationsService
{
public Task<ResponseFormationDto?> GetFormationById(string id)
{
var result = context.Formations.FirstOrDefault(form => form.Id == id);
return Task.FromResult(result?.ToDto());
}
public Task<(long Count, IEnumerable<ResponseFormationDto> Formations)> GetFormations(string? name, int page, int size,
FormationOrderCriteria orderCriteria = FormationOrderCriteria.EndDate, bool ascending = true)
{
var query = context.Formations.Skip((page-1) * size).Take(size);
if (name != null)
{
query = context.Formations.Where(e => e.Name.Contains(name)).Skip((page-1) * size).Take(size);
}
switch (orderCriteria)
{
case FormationOrderCriteria.StartDate:
query = ascending ? query.OrderBy(e => e.StartDate) : query.OrderByDescending(e => e.StartDate);
break;
case FormationOrderCriteria.EndDate:
query = ascending ? query.OrderBy(e => e.EndDate) : query.OrderByDescending(e => e.EndDate);
break;
case FormationOrderCriteria.Name:
query = ascending ? query.OrderBy(e => e.Name) : query.OrderByDescending(e => e.Name);
break;
case FormationOrderCriteria.SchoolName:
query = ascending ? query.OrderBy(e => e.SchoolName) : query.OrderByDescending(e => e.SchoolName);
break;
}
var count = query.LongCount();
return Task.FromResult((count, query.AsEnumerable().Select(e => e.ToDto())));
}
public Task<ResponseFormationDto?> CreateFormation(RequestFormationDto formation)
{
var result = context.Formations.AddAsync(formation.ToEntity());
var alica = context.Alumni.FirstOrDefault(a => a.Id == formation.AlumniId);
alica?.Formations.Add(result.Result.Entity);
context.SaveChangesAsync();
return Task.FromResult(result.Result.Entity.ToDto());
}
public Task<ResponseFormationDto?> UpdateFormation(string id, RequestFormationDto formation)
{
var result = context.Formations.FirstOrDefault(e => e.Id == id);
if (result == null)
{
return Task.FromResult<ResponseFormationDto?>(null);
}
result.SchoolName = formation.SchoolName;
result.Name = formation.Name;
result.StartDate = formation.StartingDate;
result.EndDate = formation.EndingDate;
result.IsCurrent = formation.CurrentFormation;
context.SaveChangesAsync();
return Task.FromResult(result.ToDto());
}
public Task<bool> DeleteFormation(string id)
{
var result = context.Formations.FirstOrDefault(form => form.Id == id);
if (result == null) return Task.FromResult(false);
context.Formations.Remove(result);
context.SaveChangesAsync();
return Task.FromResult(true);
}
}

@ -0,0 +1,38 @@
using Infrastructure;
using Infrastructure.Repositories;
using Server.Dto.Response;
using Server.IServices;
using AutoMapper;
using Shared;
namespace Server.Services;
public class UsersService : IUsersService
{
private readonly OptifitDbContext _context;
private readonly UserRepository _userRepository;
private readonly IMapper _mapper;
public UsersService(OptifitDbContext context, UserRepository userRepository, IMapper mapper)
{
_context = context;
_userRepository = userRepository;
_mapper = mapper;
}
public async Task<ResponseUserDto?> GetUserById(string id)
{
var userEntity = await _userRepository.GetByIdAsync(id);
if (userEntity == null)
{
return null;
}
var userDto = _mapper.Map<ResponseUserDto>(userEntity);
return userDto;
}
public Task<PaginatedResult<ResponseUserDto>> GetUsers(int page, int size, bool ascending = true)
{
throw new NotImplementedException();
}
}

@ -1,7 +0,0 @@
namespace Shared.Criteria;
public enum AlumniOrderCriteria
{
Name,
None
}

@ -1,8 +0,0 @@
namespace Shared.Criteria;
public enum EventOrderCriteria
{
Title,
Date,
NbPlaces
}

@ -1,8 +0,0 @@
namespace Shared.Criteria;
public enum ExperienceOrderCriteria
{
Title,
StartDate,
EndDate
}

@ -1,10 +0,0 @@
namespace Shared.Criteria;
public enum FormationOrderCriteria
{
Name,
StartDate,
EndDate,
SchoolName,
}

@ -1,9 +0,0 @@
namespace Shared.Enums;
public enum EContract
{
CDI,
CDD,
INTERNSHIP,
APPRENTICESHIP
}

@ -1,8 +0,0 @@
namespace Shared.Enums;
public enum ELevel
{
JUNIOR,
SENIOR,
INDEFERENT
}

@ -1,8 +0,0 @@
namespace Shared.Enums;
public enum ERole
{
ADMIN,
MODERATOR,
USER
}

@ -1,9 +0,0 @@
namespace Shared.Enums;
public enum EStudies
{
BAC_2,
BAC_3,
BAC_5,
INDIFERENT
}

@ -1,44 +1,46 @@
namespace Shared;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Shared;
/// <summary>
/// Interface d'objet générique contenant les méthodes CRUD
/// Generic object interface containing CRUD methods
/// </summary>
/// <typeparam name="TObject"> Objet Générique </typeparam>
/// <typeparam name="TObject"> Generic Object </typeparam>
public interface IDataServices<TObject>
{
/// <summary>
/// Récupère toutes les données
/// Get a list of data, filtered or not, and paginated results
/// </summary>
/// <returns> un Enumerable d'objet générique </returns>
/// TODO : Ne pas passer par un tuple
public Task<IEnumerable<TObject?>> GetData();
/// <returns> An Enumerable of generic object </returns>
public Task<IEnumerable<TObject?>> GetList();
/// <summary>
/// Récupère un objet en fonction de son identifiant
/// Get an object based on its identifier
/// </summary>
/// <param name="id"> identifiant </param>
/// <returns> Un objet générique ou null si objet introuvable </returns>
/// <param name="id"> Identifier (Guid.ToString()) </param>
/// <returns> The object or null if the id is incorrect </returns>
public Task<TObject?> GetDataById(string id);
/// <summary>
/// Ajout d'un objet
/// Add an object to the database
/// </summary>
/// <param name="data"> information sur l'objet </param>
/// <returns> L'objet créé </returns>
/// <param name="data"> Object to add </param>
/// <returns> The object added </returns>
public Task<TObject> CreateData(TObject data);
/// <summary>
/// Modifie un objet en fonction de son id
/// Modify an object in the database
/// </summary>
/// <param name="data"> Information du nouvelle objet </param>
/// <param name="id"> identifiant de l'objet à modifier </param>
/// <returns> L'objet modifié ou null si id incorrect </returns>
/// <param name="data"> Object to modify </param>
/// <param name="id"> Identifier (Guid.ToString()) </param>
/// <returns> The object modified </returns>
public Task<TObject?> UpdateData(TObject data, string id);
/// <summary>
/// Supprime un objet en fonction de son identifiant
/// Delete an object from the database
/// </summary>
/// <param name="id"> identifiant </param>
/// <returns> true si réussi sinon false </returns>
public Task<bool> DeleteObjectById(string id);
/// <param name="id"> Identifier (Guid.ToString()) </param>
/// <returns> true if the object has been deleted, false otherwise </returns>
public Task<bool> DeleteById(string id);
}

@ -0,0 +1,26 @@
namespace Shared;
public class PaginatedResult<T>
{
public PaginatedResult(List<T>? data = default, int count = 0, int page = 0, int pageSize = 10)
{
Data = data;
CurrentPage = page;
PageSize = pageSize;
TotalCount = count;
}
public List<T>? Data { get; set; }
public int CurrentPage { get; set; }
public int TotalCount { get; set; }
public int PageSize { get; set; }
public int TotalPages => (int)Math.Ceiling(TotalCount / (double)PageSize);
public bool HasPreviousPage => CurrentPage > 0;
public bool HasNextPage => CurrentPage < (TotalPages - 1);
}

@ -6,4 +6,9 @@
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<Folder Include="Criteria\" />
<Folder Include="Enums\" />
</ItemGroup>
</Project>

@ -1,130 +0,0 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Moq;
using Server.Controller.v1;
using Server.Dto.Response;
using Server.IServices;
using Shared.Criteria;
namespace TestAPI.ControllerTests
{
public class AlumniControllerTest
{
private readonly Mock<ILogger<AlumnisController>> _loggerMock = new Mock<ILogger<AlumnisController>>();
private readonly Mock<IAlumnisService> _alumnisServiceMock = new Mock<IAlumnisService>();
[Fact]
public void GetAlumni_NoAlumni_ReturnsNoContent()
{
// Arrange
_alumnisServiceMock.Setup(service => service.GetAlumnis(null, 1, 5, AlumniOrderCriteria.None, true))
.ReturnsAsync((0, Enumerable.Empty<ResponseAlumniDto>()));
var controller = new AlumnisController(_loggerMock.Object, _alumnisServiceMock.Object);
// Act
var result = controller.GetAlumni(null);
// Assert
var actionResult = Assert.IsType<NoContentResult>(result);
}
[Fact]
public void GetAlumni_AlumniExists_ReturnsOk()
{
// Arrange
var alumniList = new List<ResponseAlumniDto>
{
new ResponseAlumniDto { Id = "1", FirstName = "John", LastName = "Doe" }
};
_alumnisServiceMock.Setup(service => service.GetAlumnis(null, 1, 5, AlumniOrderCriteria.None, true))
.ReturnsAsync((alumniList.Count, alumniList));
var controller = new AlumnisController(_loggerMock.Object, _alumnisServiceMock.Object);
// Act
var result = controller.GetAlumni(null);
// Assert
var actionResult = Assert.IsType<OkObjectResult>(result);
var returnValue = Assert.IsAssignableFrom<IEnumerable<ResponseAlumniDto>>(actionResult.Value);
Assert.Single(returnValue);
}
[Fact]
public void GetAlumniById_AlumniExists_ReturnsOk()
{
// Arrange
var alumniId = "1";
var alumniDto = new ResponseAlumniDto { Id = alumniId };
_alumnisServiceMock.Setup(service => service.GetAlumniById(alumniId)).ReturnsAsync(alumniDto);
var controller = new AlumnisController(_loggerMock.Object, _alumnisServiceMock.Object);
// Act
var result = controller.GetAlumniById(alumniId);
// Assert
var actionResult = Assert.IsType<OkObjectResult>(result);
var returnValue = Assert.IsType<Task<ResponseAlumniDto>>(actionResult.Value);
Assert.Equal(alumniId, returnValue.Result.Id);
}
[Fact]
public void GetAlumniById_AlumniDoesNotExist_ReturnsNotFound()
{
// Arrange
var alumniId = "1";
_alumnisServiceMock.Setup(service => service.GetAlumniById(alumniId)).ReturnsAsync((ResponseAlumniDto)null);
var controller = new AlumnisController(_loggerMock.Object, _alumnisServiceMock.Object);
// Act
var result = controller.GetAlumniById(alumniId);
// Assert
var actionResult = Assert.IsType<NotFoundResult>(result);
}
[Fact]
public void GetAlumni_ByLastName_NoAlumni_ReturnsNoContent()
{
// Arrange
var lastName = "Doe";
_alumnisServiceMock.Setup(service => service.GetAlumnis(lastName, 1, 5, AlumniOrderCriteria.None, true))
.ReturnsAsync((0, new List<ResponseAlumniDto>()));
var controller = new AlumnisController(_loggerMock.Object, _alumnisServiceMock.Object);
// Act
var result = controller.GetAlumni(lastName);
// Assert
var actionResult = Assert.IsType<NoContentResult>(result);
}
[Fact]
public void GetAlumni_ByLastName_AlumniExist_ReturnsOk()
{
// Arrange
var lastName = "Doe";
var alumniList = new List<ResponseAlumniDto>
{
new ResponseAlumniDto { Id = "1", LastName = "Doe" }
};
_alumnisServiceMock.Setup(service => service.GetAlumnis(lastName, 1, 5, AlumniOrderCriteria.None, true))
.ReturnsAsync((alumniList.Count, alumniList));
var controller = new AlumnisController(_loggerMock.Object, _alumnisServiceMock.Object);
// Act
var result = controller.GetAlumni(lastName);
// Assert
var actionResult = Assert.IsType<OkObjectResult>(result);
var returnValue = Assert.IsAssignableFrom<IEnumerable<ResponseAlumniDto>>(actionResult.Value);
Assert.Single(returnValue);
}
}
}

@ -1,98 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xunit;
using Moq;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using Server.Dto.Response;
using Server.Controller.v1;
using Server.IServices;
using Shared.Criteria;
using System.Threading.Tasks;
namespace TestAPI.ControllerTests
{
public class AlumuniRestrictedControllerTest
{
private readonly Mock<ILogger<AlumniRestrictedController>> _loggerMock = new Mock<ILogger<AlumniRestrictedController>>();
private readonly Mock<IAlumnisService> _alumnisServiceMock = new Mock<IAlumnisService>();
[Fact]
public async Task GetAlumniRestricted_NoAlumni_ReturnsNoContent()
{
// Arrange
var lastName = "Doe";
_alumnisServiceMock.Setup(service => service.GetAlumnisRestricted(lastName, 1, 5, AlumniOrderCriteria.None, true))
.ReturnsAsync((0L, new List<ResponseRestrictedAlumniDto>()));
var controller = new AlumniRestrictedController(_loggerMock.Object, _alumnisServiceMock.Object);
// Act
var result = await controller.GetAlumniRestricted(lastName);
// Assert
var actionResult = Assert.IsType<NoContentResult>(result);
}
[Fact]
public async Task GetAlumniRestricted_AlumniExist_ReturnsOk()
{
// Arrange
var lastName = "Doe";
var alumniList = new List<ResponseRestrictedAlumniDto>
{
new ResponseRestrictedAlumniDto { Id = "1", LastName = "Doe" }
};
_alumnisServiceMock.Setup(service => service.GetAlumnisRestricted(lastName, 1, 5, AlumniOrderCriteria.None, true))
.ReturnsAsync((alumniList.Count, alumniList));
var controller = new AlumniRestrictedController(_loggerMock.Object, _alumnisServiceMock.Object);
// Act
var result = await controller.GetAlumniRestricted(lastName);
// Assert
var actionResult = Assert.IsType<OkObjectResult>(result);
var returnValue = Assert.IsAssignableFrom<IEnumerable<ResponseRestrictedAlumniDto>>(actionResult.Value);
Assert.Single(returnValue);
}
[Fact]
public void GetAlumniRestrictedById_AlumniExists_ReturnsOk()
{
// Arrange
var alumniId = "1";
var alumniDto = new ResponseRestrictedAlumniDto { Id = alumniId };
_alumnisServiceMock.Setup(service => service.GetAlumniRestrictedById(alumniId)).ReturnsAsync(alumniDto);
var controller = new AlumniRestrictedController(_loggerMock.Object, _alumnisServiceMock.Object);
// Act
var result = controller.GetAlumniRestrictedById(alumniId);
// Assert
var actionResult = Assert.IsType<OkObjectResult>(result);
var returnValue = Assert.IsType<ResponseRestrictedAlumniDto>(actionResult.Value);
Assert.Equal(alumniId, returnValue.Id);
}
[Fact]
public void GetAlumniRestrictedById_AlumniDoesNotExist_ReturnsNotFound()
{
// Arrange
var alumniId = "1";
_alumnisServiceMock.Setup(service => service.GetAlumniRestrictedById(alumniId)).ReturnsAsync((ResponseRestrictedAlumniDto)null);
var controller = new AlumniRestrictedController(_loggerMock.Object, _alumnisServiceMock.Object);
// Act
var result = controller.GetAlumniRestrictedById(alumniId);
// Assert
var actionResult = Assert.IsType<NotFoundResult>(result);
}
}
}

@ -1,179 +0,0 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Moq;
using Server.Controller.v1;
using Server.Dto.Request;
using Server.Dto.Response;
using Server.IServices;
using Shared.Criteria;
namespace TestAPI.ControllerTests
{
public class EventTest
{
private readonly ILogger<EventsController> _loggerMock = Mock.Of<ILogger<EventsController>>();
private readonly Mock<IEventsService> _servicesMock = new Mock<IEventsService>();
[Fact]
public async Task GetEvents()
{
// Arrange
var expectedEvents = new List<ResponseEventDto>
{
new ResponseEventDto { Id = "1", Title = "Event 1" },
new ResponseEventDto { Id = "2", Title = "Event 2" }
};
_servicesMock.Setup(s => s.GetEvents(null, 0, 10, EventOrderCriteria.Date, true))
.ReturnsAsync((expectedEvents.Count, expectedEvents));
var eventsController = new EventsController(_loggerMock, _servicesMock.Object);
// Act
var result = await eventsController.GetEvents(null, 0, 10);
// Assert
var okResult = Assert.IsType<OkObjectResult>(result);
var eventList = Assert.IsAssignableFrom<IEnumerable<ResponseEventDto>>(okResult.Value);
Assert.Equal(expectedEvents.Count, eventList.Count());
}
[Fact]
public async Task GetEventById_ValidId()
{
// Arrange
var expectedEvent = new ResponseEventDto { Id = "1", Title = "Event 1" };
_servicesMock.Setup(s => s.GetEventById("1")).ReturnsAsync(expectedEvent);
var eventsController = new EventsController(_loggerMock, _servicesMock.Object);
// Act
var result = eventsController.GetEventById("1");
// Assert
var okResult = Assert.IsType<OkObjectResult>(result);
var eventItem = Assert.IsType<ResponseEventDto>(okResult.Value);
Assert.Equal(expectedEvent.Id, eventItem.Id);
Assert.Equal(expectedEvent.Title, eventItem.Title);
}
[Fact]
public async Task GetEventById_InvalidId()
{
// Arrange
_servicesMock.Setup(s => s.GetEventById("InvalidId")).ReturnsAsync((ResponseEventDto?)null);
var eventsController = new EventsController(_loggerMock, _servicesMock.Object);
// Act
var result = eventsController.GetEventById("InvalidId");
// Assert
Assert.IsType<NotFoundResult>(result);
}
[Fact]
public async Task CreateEvent()
{
// Arrange
var newEvent = new RequestEventDto
{
AlumniId = "A1",
Title = "New Event",
Description = "Description",
Date = DateTime.Now,
nbMaxRegistrations = 100
};
var expectedEvent = new ResponseEventDto { Id = "3", Title = "New Event" };
_servicesMock.Setup(s => s.CreateEvent(newEvent)).ReturnsAsync(expectedEvent);
var eventsController = new EventsController(_loggerMock, _servicesMock.Object);
// Act
var result = eventsController.CreateEvent(newEvent);
// Assert
var createdAtResult = Assert.IsType<CreatedAtActionResult>(result);
var createdEvent = Assert.IsType<ResponseEventDto>(createdAtResult.Value);
Assert.Equal(expectedEvent.Id, createdEvent.Id);
Assert.Equal(expectedEvent.Title, createdEvent.Title);
}
[Fact]
public async Task UpdateEvent_ValidId()
{
// Arrange
var updatedEvent = new RequestEventDto
{
Title = "Updated Event",
Description = "Updated Description",
Date = DateTime.Now.AddDays(1),
nbMaxRegistrations = 200
};
var expectedEvent = new ResponseEventDto { Id = "1", Title = "Updated Event" };
_servicesMock.Setup(s => s.UpdateEvent("1", updatedEvent)).ReturnsAsync(expectedEvent);
var eventsController = new EventsController(_loggerMock, _servicesMock.Object);
// Act
var result = eventsController.UpdateEvent("1", updatedEvent);
// Assert
var okResult = Assert.IsType<OkObjectResult>(result);
var updatedEventResult = Assert.IsType<ResponseEventDto>(okResult.Value);
Assert.Equal(expectedEvent.Id, updatedEventResult.Id);
Assert.Equal(expectedEvent.Title, updatedEventResult.Title);
}
[Fact]
public async Task UpdateEvent_InvalidId()
{
// Arrange
var updatedEvent = new RequestEventDto
{
Title = "Updated Event",
Description = "Updated Description",
Date = DateTime.Now.AddDays(1),
nbMaxRegistrations = 200
};
_servicesMock.Setup(s => s.UpdateEvent("InvalidId", updatedEvent)).ReturnsAsync((ResponseEventDto?)null);
var eventsController = new EventsController(_loggerMock, _servicesMock.Object);
// Act
var result = eventsController.UpdateEvent("InvalidId", updatedEvent);
// Assert
Assert.IsType<BadRequestResult>(result);
}
[Fact]
public async Task DeleteEvent_ValidId()
{
// Arrange
_servicesMock.Setup(s => s.DeleteEvent("1")).ReturnsAsync(true);
var eventsController = new EventsController(_loggerMock, _servicesMock.Object);
// Act
var result = eventsController.DeleteEvent("1");
// Assert
Assert.IsType<OkResult>(result);
}
[Fact]
public async Task DeleteEvent_InvalidId()
{
// Arrange
_servicesMock.Setup(s => s.DeleteEvent("InvalidId")).ReturnsAsync(false);
var eventsController = new EventsController(_loggerMock, _servicesMock.Object);
// Act
var result = eventsController.DeleteEvent("InvalidId");
// Assert
Assert.IsType<NotFoundResult>(result);
}
}
}

@ -1,186 +0,0 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Moq;
using Server.Controller.v1;
using Server.Dto.Request;
using Server.Dto.Response;
using Server.IServices;
using Shared.Criteria;
namespace TestAPI.ControllerTests
{
public class ExperienceControllerTest
{
private readonly ILogger<ExperiencesController> _loggerMock = Mock.Of<ILogger<ExperiencesController>>();
private readonly Mock<IExperiencesService> _servicesMock = new Mock<IExperiencesService>();
[Fact]
public async Task GetExperiences()
{
// Arrange
var expectedExperiences = new List<ResponseExperienceDto>
{
new ResponseExperienceDto { Id = "1", Title = "Iut" },
};
_servicesMock.Setup(s => s.GetExperiences(null, 0, 10, ExperienceOrderCriteria.StartDate, true))
.ReturnsAsync((expectedExperiences.Count, expectedExperiences));
var experiencesController = new ExperiencesController(_loggerMock, _servicesMock.Object);
// Act
var result = await experiencesController.GetExperiences(null, 0, 10);
// Assert
var okResult = Assert.IsType<OkObjectResult>(result);
var experienceList = Assert.IsAssignableFrom<IEnumerable<ResponseExperienceDto>>(okResult.Value);
Assert.Equal(expectedExperiences.Count, experienceList.Count());
}
[Fact]
public async Task GetExperienceById_ValidId()
{
// Arrange
var expectedExperience = new ResponseExperienceDto { Id = "1", Title = "Iut" };
_servicesMock.Setup(s => s.GetExperienceById("1")).ReturnsAsync(expectedExperience);
var experiencesController = new ExperiencesController(_loggerMock, _servicesMock.Object);
// Act
var result = experiencesController.GetExperienceById("1");
// Assert
var okResult = Assert.IsType<OkObjectResult>(result);
var experienceItem = Assert.IsType<ResponseExperienceDto>(okResult.Value);
Assert.Equal(expectedExperience.Id, experienceItem.Id);
Assert.Equal(expectedExperience.Title, experienceItem.Title);
}
[Fact]
public async Task GetExperienceById_InvalidId()
{
// Arrange
_servicesMock.Setup(s => s.GetExperienceById("hgfyhgyjhu")).ReturnsAsync((ResponseExperienceDto?)null);
// Act
var experiencesController = new ExperiencesController(_loggerMock, _servicesMock.Object);
var result = experiencesController.GetExperienceById("hgfyhgyjhu");
// Assert
Assert.IsType<NotFoundResult>(result);
}
[Fact]
public async Task CreateExperience()
{
// Arrange
var newExperience = new RequestExperienceDto
{
AlumniId = "A1",
Title = "Junior Dev",
StartingDate = DateTime.Now.AddYears(-2),
CompanyName = "CGI",
CurrentJob = false
};
var expectedExperience = new ResponseExperienceDto { Id = "4", Title = "Junior Dev" };
_servicesMock.Setup(s => s.CreateExperience(newExperience)).ReturnsAsync(expectedExperience);
var experiencesController = new ExperiencesController(_loggerMock, _servicesMock.Object);
// Act
var result = experiencesController.CreateExperience(newExperience);
// Assert
var createdAtResult = Assert.IsType<CreatedAtActionResult>(result);
var createdExperience = Assert.IsType<ResponseExperienceDto>(createdAtResult.Value);
Assert.Equal(expectedExperience.Id, createdExperience.Id);
Assert.Equal(expectedExperience.Title, createdExperience.Title);
}
[Fact]
public async Task UpdateExperience_ValidId()
{
// Arrange
var updatedExperience = new RequestExperienceDto
{
Title = "Update Software Developer",
StartingDate = DateTime.Now.AddYears(-2),
EndingDate = DateTime.Now,
CompanyName = "TechCo",
CurrentJob = false,
AlumniId = "A1"
};
var expectedExperience = new ResponseExperienceDto { Id = "1", Title = "Update Software Developer" };
_servicesMock.Setup(s => s.UpdateExperience("1", updatedExperience)).ReturnsAsync(expectedExperience);
var experiencesController = new ExperiencesController(_loggerMock, _servicesMock.Object);
// Act
var result = experiencesController.UpdateExperience("1", updatedExperience);
// Assert
var okResult = Assert.IsType<OkObjectResult>(result);
var updatedExperienceResult = Assert.IsType<ResponseExperienceDto>(okResult.Value);
Assert.Equal(expectedExperience.Id, updatedExperienceResult.Id);
Assert.Equal(expectedExperience.Title, updatedExperienceResult.Title);
}
[Fact]
public async Task UpdateExperience_InvalidId()
{
// Arrange
var updatedOffer = new RequestExperienceDto
{
Title = "Update Software Developer",
StartingDate = DateTime.Now.AddYears(-2),
EndingDate = DateTime.Now,
CompanyName = "TechCo",
CurrentJob = false,
AlumniId = "A1"
};
_servicesMock.Setup(s => s.UpdateExperience("InvalidId", updatedOffer)).ReturnsAsync((ResponseExperienceDto?)null);
// Act
var experiencesController = new ExperiencesController(_loggerMock, _servicesMock.Object);
var result = experiencesController.UpdateExperience("InvalidId", updatedOffer);
// Assert
var badRequestResult = Assert.IsType<BadRequestResult>(result);
}
[Fact]
public async Task DeleteExperience_ValidId()
{
// Arrange
_servicesMock.Setup(s => s.DeleteExperience("1")).ReturnsAsync(true);
var experiencesController = new ExperiencesController(_loggerMock, _servicesMock.Object);
// Act
var result = experiencesController.DeleteExperience("1");
// Assert
Assert.IsType<OkResult>(result);
}
[Fact]
public async Task DeleteExperience_InvalidId()
{
// Arrange
_servicesMock.Setup(s => s.DeleteExperience("InvalidId")).ReturnsAsync(false);
var experiencesController = new ExperiencesController(_loggerMock, _servicesMock.Object);
// Act
var result = experiencesController.DeleteExperience("InvalidId");
// Assert
Assert.IsType<NotFoundResult>(result);
}
}
}

@ -1,179 +0,0 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Moq;
using Server.Controller.v1;
using Server.Dto.Request;
using Server.Dto.Response;
using Server.IServices;
using Shared.Criteria;
namespace TestAPI.ControllerTests
{
public class FormationControllerTest
{
private readonly ILogger<FormationsController> _loggerMock = Mock.Of<ILogger<FormationsController>>();
private readonly Mock<IFormationsService> _servicesMock = new Mock<IFormationsService>();
[Fact]
public async Task GetFormations()
{
// Arrange
var expectedFormations = new List<ResponseFormationDto>
{
new ResponseFormationDto { Id = "1", Name = "Computer Science" },
new ResponseFormationDto { Id = "2", Name = "Data Science" }
};
_servicesMock.Setup(s => s.GetFormations(null, 0, 10, FormationOrderCriteria.StartDate, true))
.ReturnsAsync((expectedFormations.Count, expectedFormations));
var formationsController = new FormationsController(_loggerMock, _servicesMock.Object);
// Act
var result = await formationsController.GetFormations(null, 0, 10);
// Assert
var okResult = Assert.IsType<OkObjectResult>(result);
var formationList = Assert.IsAssignableFrom<IEnumerable<ResponseFormationDto>>(okResult.Value);
Assert.Equal(expectedFormations.Count, formationList.Count());
}
[Fact]
public async Task GetFormationById_ValidId()
{
// Arrange
var expectedFormation = new ResponseFormationDto { Id = "1", Name = "Computer Science" };
_servicesMock.Setup(s => s.GetFormationById("1")).ReturnsAsync(expectedFormation);
var formationsController = new FormationsController(_loggerMock, _servicesMock.Object);
// Act
var result = formationsController.GetFormationById("1");
// Assert
var okResult = Assert.IsType<OkObjectResult>(result);
var formationItem = Assert.IsType<ResponseFormationDto>(okResult.Value);
Assert.Equal(expectedFormation.Id, formationItem.Id);
Assert.Equal(expectedFormation.Name, formationItem.Name);
}
[Fact]
public async Task GetFormationById_InvalidId()
{
// Arrange
_servicesMock.Setup(s => s.GetFormationById("InvalidId")).ReturnsAsync((ResponseFormationDto)null);
var formationsController = new FormationsController(_loggerMock, _servicesMock.Object);
// Act
var result = formationsController.GetFormationById("InvalidId");
// Assert
Assert.IsType<NotFoundResult>(result);
}
[Fact]
public async Task CreateFormation()
{
// Arrange
var newFormation = new RequestFormationDto
{
AlumniId = "A1",
Name = "Software Engineering",
StartingDate = DateTime.Now.AddYears(-2),
SchoolName = "University XYZ",
CurrentFormation = true
};
var expectedFormation = new ResponseFormationDto { Id = "3", Name = "Software Engineering" };
_servicesMock.Setup(s => s.CreateFormation(newFormation)).ReturnsAsync(expectedFormation);
var formationsController = new FormationsController(_loggerMock, _servicesMock.Object);
// Act
var result = formationsController.CreateFormation(newFormation);
// Assert
var createdAtResult = Assert.IsType<CreatedAtActionResult>(result);
var createdFormation = Assert.IsType<ResponseFormationDto>(createdAtResult.Value);
Assert.Equal(expectedFormation.Id, createdFormation.Id);
Assert.Equal(expectedFormation.Name, createdFormation.Name);
}
[Fact]
public async Task UpdateFormation_ValidId()
{
// Arrange
var updatedFormation = new RequestFormationDto
{
Name = "Updated Data Science",
StartingDate = DateTime.Now.AddYears(-2),
SchoolName = "University XYZ",
CurrentFormation = false
};
var expectedFormation = new ResponseFormationDto { Id = "2", Name = "Updated Data Science" };
_servicesMock.Setup(s => s.UpdateFormation("2", updatedFormation)).ReturnsAsync(expectedFormation);
var formationsController = new FormationsController(_loggerMock, _servicesMock.Object);
// Act
var result = formationsController.UpdateFormation("2", updatedFormation);
// Assert
var okResult = Assert.IsType<OkObjectResult>(result);
var updatedFormationResult = Assert.IsType<ResponseFormationDto>(okResult.Value);
Assert.Equal(expectedFormation.Id, updatedFormationResult.Id);
Assert.Equal(expectedFormation.Name, updatedFormationResult.Name);
}
[Fact]
public async Task UpdateFormation_InvalidId()
{
// Arrange
var updatedFormation = new RequestFormationDto
{
Name = "Updated Data Science",
StartingDate = DateTime.Now.AddYears(-2),
SchoolName = "University XYZ",
CurrentFormation = false
};
_servicesMock.Setup(s => s.UpdateFormation("InvalidId", updatedFormation)).ReturnsAsync((ResponseFormationDto)null);
var formationsController = new FormationsController(_loggerMock, _servicesMock.Object);
// Act
var result = formationsController.UpdateFormation("InvalidId", updatedFormation);
// Assert
Assert.IsType<BadRequestResult>(result);
}
[Fact]
public async Task DeleteFormation_ValidId()
{
// Arrange
_servicesMock.Setup(s => s.DeleteFormation("1")).ReturnsAsync(true);
var formationsController = new FormationsController(_loggerMock, _servicesMock.Object);
// Act
var result = formationsController.DeleteFormation("1");
// Assert
Assert.IsType<OkResult>(result);
}
[Fact]
public async Task DeleteFormation_InvalidId()
{
// Arrange
_servicesMock.Setup(s => s.DeleteFormation("InvalidId")).ReturnsAsync(false);
var formationsController = new FormationsController(_loggerMock, _servicesMock.Object);
// Act
var result = formationsController.DeleteFormation("InvalidId");
// Assert
Assert.IsType<NotFoundResult>(result);
}
}
}

@ -1,112 +0,0 @@
using Server.Mappers;
using Server.Dto.Request;
using Infrastructure.Entities;
using Shared.Enums;
namespace TestAPI.MapperTests
{
public class AlumniMappersTests
{
[Fact]
public void ToDto_ConvertsAlumniEntityToResponseAlumniDto()
{
// Arrange
var alumniEntity = new User
{
Id = "1",
Email = "test@example.com",
Role = "USER",
EntryYear = "2020",
FirstName = "John",
LastName = "Doe",
Linkedin = "linkedin.com",
Github = "github.com",
WebSite = "portfolio.com",
Experiences = (ICollection<ExperienceEntity>)Enumerable.Empty<ExperienceEntity>(),
Formations = (ICollection<FormationEntity>)Enumerable.Empty<FormationEntity>()
};
// Act
var result = alumniEntity.ToDto();
// Assert
Assert.Equal(alumniEntity.Id, result.Id);
Assert.Equal(alumniEntity.Email, result.Email);
Assert.Equal(ERole.USER, result.ERole);
Assert.Equal(alumniEntity.EntryYear, result.EntryYear);
Assert.Equal(alumniEntity.FirstName, result.FirstName);
Assert.Equal(alumniEntity.LastName, result.LastName);
Assert.Equal(alumniEntity.Linkedin, result.LinkedinUrl);
Assert.Equal(alumniEntity.Github, result.GithubUrl);
Assert.Equal(alumniEntity.WebSite, result.PortfolioUrl);
Assert.Empty(result.Experiences);
Assert.Empty(result.Formations);
}
[Fact]
public void ToDtoRestricted_ConvertsAlumniEntityToResponseRestrictedAlumniDto()
{
// Arrange
var alumniEntity = new User
{
Id = "1",
FirstName = "John",
LastName = "Doe",
Linkedin = "linkedin.com"
};
// Act
var result = alumniEntity.ToDtoRestricted();
// Assert
Assert.Equal(alumniEntity.Id, result.Id);
Assert.Equal(alumniEntity.FirstName, result.FirstName);
Assert.Equal(alumniEntity.LastName, result.LastName);
Assert.Equal(alumniEntity.Linkedin, result.LinkedinUrl);
}
[Fact]
public void ToEntity_ConvertsRequestAlumniDtoToAlumniEntity()
{
// Arrange
var requestAlumniDto = new RequestAlumniDto
{
Email = "test@example.com",
Password = "password",
EntryYear = "2020",
FirstName = "John",
LastName = "Doe",
LinkedinUrl = "linkedin.com",
GithubUrl = "github.com",
PortfolioUrl = "portfolio.com"
};
// Act
var result = requestAlumniDto.ToEntity();
// Assert
Assert.Equal(requestAlumniDto.Email, result.Email);
Assert.Equal(requestAlumniDto.Password, result.Password);
Assert.Equal(requestAlumniDto.EntryYear, result.EntryYear);
Assert.Equal(requestAlumniDto.FirstName, result.FirstName);
Assert.Equal(requestAlumniDto.LastName, result.LastName);
Assert.Equal(requestAlumniDto.LinkedinUrl, result.Linkedin);
Assert.Equal(requestAlumniDto.GithubUrl, result.Github);
Assert.Equal(requestAlumniDto.PortfolioUrl, result.WebSite);
Assert.Equal("USER", result.Role);
}
[Theory]
[InlineData("ADMIN", ERole.ADMIN)]
[InlineData("MODERATOR", ERole.MODERATOR)]
[InlineData("USER", ERole.USER)]
public void ToERole_ConvertsStringToERole(string role, ERole expectedRole)
{
// Act
var result = role.ToERole();
// Assert
Assert.Equal(expectedRole, result);
}
}
}

@ -1,62 +0,0 @@
using Infrastructure.Entities;
using Server.Mappers;
using Server.Dto.Request;
namespace TestAPI.MapperTests
{
public class EventMappersTests
{
[Fact]
public void ToDto_ConvertsEventEntityToResponseEventDto()
{
// Arrange
var eventEntity = new EventEntity
{
Id = "1",
Title = "Test Event",
Description = "Test Description",
Date = DateTime.UtcNow,
nbPlaces = 100,
Participants = new System.Collections.Generic.List<User>
{
new User(),
new User()
}
};
// Act
var result = eventEntity.ToDto();
// Assert
Assert.Equal(eventEntity.Id, result.Id);
Assert.Equal(eventEntity.Title, result.Title);
Assert.Equal(eventEntity.Description, result.Description);
Assert.Equal(eventEntity.Date, result.Date);
Assert.Equal(eventEntity.nbPlaces, result.nbMaxRegistrations);
Assert.Equal(eventEntity.Participants.Count, result.nbRegistrations);
}
[Fact]
public void ToEntity_ConvertsRequestEventDtoToEventEntity()
{
// Arrange
var requestEventDto = new RequestEventDto
{
Title = "Test Event",
Description = "Test Description",
Date = DateTime.UtcNow,
nbMaxRegistrations = 100
};
// Act
var result = requestEventDto.ToEntity();
// Assert
Assert.Equal(requestEventDto.Title, result.Title);
Assert.Equal(requestEventDto.Description, result.Description);
Assert.Equal(requestEventDto.Date, result.Date);
Assert.Equal(requestEventDto.nbMaxRegistrations, result.nbPlaces);
}
}
}

@ -1,63 +0,0 @@
using Server.Mappers;
using Server.Dto.Request;
using Infrastructure.Entities;
namespace TestAPI.MapperTests
{
public class ExperienceMapperTests
{
[Fact]
public void ToDto_ConvertsExperienceEntityToResponseExperienceDto()
{
// Arrange
var experienceEntity = new ExperienceEntity
{
Id = "1",
AlumniId = "1",
Title = "Test Experience",
StartDate = DateTime.UtcNow,
EndDate = DateTime.UtcNow.AddYears(1),
CompanyName = "Test Company",
IsCurrent = false
};
// Act
var result = experienceEntity.ToDto();
// Assert
Assert.Equal(experienceEntity.Id, result.Id);
Assert.Equal(experienceEntity.AlumniId, result.AlumniId);
Assert.Equal(experienceEntity.Title, result.Title);
Assert.Equal(experienceEntity.StartDate, result.StartingDate);
Assert.Equal(experienceEntity.EndDate, result.EndingDate);
Assert.Equal(experienceEntity.CompanyName, result.CompanyName);
Assert.Equal(experienceEntity.IsCurrent, result.CurrentJob);
}
[Fact]
public void ToEntity_ConvertsRequestExperienceDtoToExperienceEntity()
{
// Arrange
var requestExperienceDto = new RequestExperienceDto
{
AlumniId = "1",
Title = "Test Experience",
StartingDate = DateTime.UtcNow,
EndingDate = DateTime.UtcNow.AddYears(1),
CompanyName = "Test Company",
CurrentJob = false
};
// Act
var result = requestExperienceDto.ToEntity();
// Assert
Assert.Equal(requestExperienceDto.AlumniId, result.AlumniId);
Assert.Equal(requestExperienceDto.Title, result.Title);
Assert.Equal(requestExperienceDto.StartingDate, result.StartDate);
Assert.Equal(requestExperienceDto.EndingDate, result.EndDate);
Assert.Equal(requestExperienceDto.CompanyName, result.CompanyName);
Assert.Equal(requestExperienceDto.CurrentJob, result.IsCurrent);
}
}
}

@ -1,61 +0,0 @@
using Infrastructure.Entities;
using Server.Dto.Request;
using Server.Mappers;
namespace TestAPI.MapperTests
{
public class FormationMapperTests
{
[Fact]
public void ToDto_ConvertsFormationEntityToResponseFormationDto()
{
// Arrange
var formationEntity = new FormationEntity
{
Id = "1",
AlumniId = "1",
Name = "Test Formation",
StartDate = DateTime.UtcNow,
EndDate = DateTime.UtcNow.AddYears(1),
SchoolName = "Test School",
IsCurrent = false
};
// Act
var result = formationEntity.ToDto();
// Assert
Assert.Equal(formationEntity.Id, result.Id);
Assert.Equal(formationEntity.AlumniId, result.AlumniId);
Assert.Equal(formationEntity.Name, result.Name);
Assert.Equal(formationEntity.StartDate, result.StartingDate);
Assert.Equal(formationEntity.EndDate, result.EndingDate);
Assert.Equal(formationEntity.SchoolName, result.SchoolName);
Assert.Equal(formationEntity.IsCurrent, result.CurrentFormation);
}
[Fact]
public void ToEntity_ConvertsRequestFormationDtoToFormationEntity()
{
// Arrange
var requestFormationDto = new RequestFormationDto
{
Name = "Test Formation",
StartingDate = DateTime.UtcNow,
EndingDate = DateTime.UtcNow.AddYears(1),
SchoolName = "Test School",
CurrentFormation = false
};
// Act
var result = requestFormationDto.ToEntity();
// Assert
Assert.Equal(requestFormationDto.Name, result.Name);
Assert.Equal(requestFormationDto.StartingDate, result.StartDate);
Assert.Equal(requestFormationDto.EndingDate, result.EndDate);
Assert.Equal(requestFormationDto.SchoolName, result.SchoolName);
Assert.Equal(requestFormationDto.CurrentFormation, result.IsCurrent);
}
}
}

@ -1,101 +0,0 @@
using Xunit;
using Moq;
using System.Linq;
using System.Collections.Generic;
using Infrastructure;
using Infrastructure.Entities;
using Microsoft.EntityFrameworkCore;
using Server.Dto.Request;
using Server.Services;
using Shared.Criteria;
public class AlumniServiceTests
{
private readonly Mock<AlumniDbContext> _mockContext;
private readonly AlumniService _alumniService;
public AlumniServiceTests()
{
var alumni = new List<User>
{
new User { Id = "1", LastName = "Alumni1" },
new User { Id = "2", LastName = "Alumni2" }
}.AsQueryable();
var mockSet = new Mock<DbSet<User>>();
mockSet.As<IQueryable<User>>().Setup(m => m.Provider).Returns(alumni.Provider);
mockSet.As<IQueryable<User>>().Setup(m => m.Expression).Returns(alumni.Expression);
mockSet.As<IQueryable<User>>().Setup(m => m.ElementType).Returns(alumni.ElementType);
mockSet.As<IQueryable<User>>().Setup(m => m.GetEnumerator()).Returns(alumni.GetEnumerator());
_mockContext = new Mock<AlumniDbContext>();
_mockContext.Setup(c => c.Alumni).Returns(mockSet.Object);
_alumniService = new AlumniService(_mockContext.Object);
}
[Fact]
public async Task GetAlumniById_ReturnsNull_WhenIdDoesNotExist()
{
var result = await _alumniService.GetAlumniById("3");
Assert.Null(result);
}
[Fact]
public async Task GetAlumnis_ReturnsEmpty_WhenLastNameDoesNotExist()
{
var result = await _alumniService.GetAlumnis("Alumni3", 1, 1, AlumniOrderCriteria.Name, true);
Assert.Empty(result.Alumnis);
}
[Fact]
public async Task GetAlumnisRestricted_NoMatchingLastName_ReturnsEmpty()
{
// Arrange
string lastName = "NonExistingLastName";
var page = 1;
var size = 5;
// Act
var result = await _alumniService.GetAlumnisRestricted(lastName, page, size);
// Assert
Assert.Empty(result.Alumnis);
}
[Fact]
public async Task GetAlumnisRestricted_MatchingLastName_ReturnsAlumni()
{
// Arrange
string lastName = "Alumni1";
var page = 1;
var size = 5;
// Act
var result = await _alumniService.GetAlumnisRestricted(lastName, page, size);
// Assert
Assert.NotEmpty(result.Alumnis);
Assert.Equal(1, result.Alumnis.Count());
Assert.Equal("Alumni1", result.Alumnis.First().LastName);
}
[Fact]
public async Task GetAlumnisRestricted_PaginationWorksCorrectly()
{
// Arrange
string lastName = null;
var page = 2;
var size = 1;
// Act
var result = await _alumniService.GetAlumnisRestricted(lastName, page, size);
// Assert
Assert.NotEmpty(result.Alumnis);
Assert.Single(result.Alumnis);
Assert.Equal("Alumni2", result.Alumnis.First().LastName);
}
}

@ -1,97 +0,0 @@
using Xunit;
using Moq;
using System.Linq;
using System.Collections.Generic;
using Infrastructure;
using Infrastructure.Entities;
using Microsoft.EntityFrameworkCore;
using Server.Dto.Request;
using Server.Services;
using Shared.Criteria;
public class EventServicesTests
{
private readonly Mock<AlumniDbContext> _mockContext;
private readonly EventServices _eventServices;
public EventServicesTests()
{
var events = new List<EventEntity>
{
new EventEntity { Id = "1", Title = "Event1", Description = "Description1", Date = DateTime.Now, nbPlaces = 100 },
new EventEntity { Id = "2", Title = "Event2", Description = "Description2", Date = DateTime.Now.AddDays(1), nbPlaces = 200 }
}.AsQueryable();
var mockSet = new Mock<DbSet<EventEntity>>();
mockSet.As<IQueryable<EventEntity>>().Setup(m => m.Provider).Returns(events.Provider);
mockSet.As<IQueryable<EventEntity>>().Setup(m => m.Expression).Returns(events.Expression);
mockSet.As<IQueryable<EventEntity>>().Setup(m => m.ElementType).Returns(events.ElementType);
mockSet.As<IQueryable<EventEntity>>().Setup(m => m.GetEnumerator()).Returns(events.GetEnumerator());
_mockContext = new Mock<AlumniDbContext>();
_mockContext.Setup(c => c.Events).Returns(mockSet.Object);
_eventServices = new EventServices(_mockContext.Object);
}
[Fact]
public async Task GetEventById_ReturnsEvent_WhenIdExists()
{
var result = await _eventServices.GetEventById("1");
Assert.NotNull(result);
Assert.Equal("1", result.Id);
}
[Fact]
public async Task GetEventById_ReturnsNull_WhenIdDoesNotExist()
{
var result = await _eventServices.GetEventById("3");
Assert.Null(result);
}
[Fact]
public async Task GetEvents_ReturnsEvents_WhenTitleExists()
{
var result = await _eventServices.GetEvents("Event1", 1, 1, EventOrderCriteria.Date, true);
Assert.Single(result.Events);
Assert.Equal("Event1", result.Events.First().Title);
}
[Fact]
public async Task GetEvents_ReturnsEmpty_WhenTitleDoesNotExist()
{
var result = await _eventServices.GetEvents("Event3", 1, 1, EventOrderCriteria.Date, true);
Assert.Empty(result.Events);
}
[Fact]
public async Task UpdateEvent_ReturnsUpdatedEvent_WhenIdExists()
{
var eventDto = new RequestEventDto { Title = "UpdatedEvent", Description = "UpdatedDescription", Date = DateTime.Now, nbMaxRegistrations = 150 };
var result = await _eventServices.UpdateEvent("1", eventDto);
Assert.NotNull(result);
Assert.Equal("UpdatedEvent", result.Title);
}
[Fact]
public async Task UpdateEvent_ReturnsNull_WhenIdDoesNotExist()
{
var eventDto = new RequestEventDto { Title = "UpdatedEvent", Description = "UpdatedDescription", Date = DateTime.Now, nbMaxRegistrations = 150 };
var result = await _eventServices.UpdateEvent("3", eventDto);
Assert.Null(result);
}
[Fact]
public async Task DeleteEvent_ReturnsTrue_WhenIdExists()
{
var result = await _eventServices.DeleteEvent("1");
Assert.True(result);
}
[Fact]
public async Task DeleteEvent_ReturnsFalse_WhenIdDoesNotExist()
{
var result = await _eventServices.DeleteEvent("3");
Assert.False(result);
}
}

@ -1,93 +0,0 @@
using Moq;
using Infrastructure;
using Infrastructure.Entities;
using Microsoft.EntityFrameworkCore;
using Server.Dto.Request;
using Server.Services;
public class ExperienceServicesTests
{
private readonly Mock<AlumniDbContext> _mockContext;
private readonly ExperienceServices _experienceServices;
public ExperienceServicesTests()
{
var experiences = new List<ExperienceEntity>
{
new ExperienceEntity { Id = "1", Title = "Experience1", CompanyName = "Company1", StartDate = DateTime.Now, EndDate = DateTime.Now.AddDays(30), IsCurrent = true },
new ExperienceEntity { Id = "2", Title = "Experience2", CompanyName = "Company2", StartDate = DateTime.Now, EndDate = DateTime.Now.AddDays(30), IsCurrent = false }
}.AsQueryable();
var mockSet = new Mock<DbSet<ExperienceEntity>>();
mockSet.As<IQueryable<ExperienceEntity>>().Setup(m => m.Provider).Returns(experiences.Provider);
mockSet.As<IQueryable<ExperienceEntity>>().Setup(m => m.Expression).Returns(experiences.Expression);
mockSet.As<IQueryable<ExperienceEntity>>().Setup(m => m.ElementType).Returns(experiences.ElementType);
mockSet.As<IQueryable<ExperienceEntity>>().Setup(m => m.GetEnumerator()).Returns(experiences.GetEnumerator());
_mockContext = new Mock<AlumniDbContext>();
_mockContext.Setup(c => c.Experiences).Returns(mockSet.Object);
_experienceServices = new ExperienceServices(_mockContext.Object);
}
[Fact]
public async Task GetExperienceById_ReturnsExperience_WhenIdExists()
{
var result = await _experienceServices.GetExperienceById("1");
Assert.NotNull(result);
Assert.Equal("1", result.Id);
}
[Fact]
public async Task GetExperienceById_ReturnsNull_WhenIdDoesNotExist()
{
var result = await _experienceServices.GetExperienceById("3");
Assert.Null(result);
}
[Fact]
public async Task GetExperiences_ReturnsExperiences_WhenTitleExists()
{
var result = await _experienceServices.GetExperiences("Experience1", 1, 1);
Assert.Single(result.Experiences);
Assert.Equal("Experience1", result.Experiences.First().Title);
}
[Fact]
public async Task GetExperiences_ReturnsEmpty_WhenTitleDoesNotExist()
{
var result = await _experienceServices.GetExperiences("Experience3", 1, 1);
Assert.Empty(result.Experiences);
}
[Fact]
public async Task UpdateExperience_ReturnsUpdatedExperience_WhenIdExists()
{
var experience = new RequestExperienceDto { Title = "UpdatedExperience", CompanyName = "UpdatedCompany", StartingDate = DateTime.Now, EndingDate = DateTime.Now.AddDays(30), CurrentJob = false };
var result = await _experienceServices.UpdateExperience("1", experience);
Assert.NotNull(result);
Assert.Equal("UpdatedExperience", result.Title);
}
[Fact]
public async Task UpdateExperience_ReturnsNull_WhenIdDoesNotExist()
{
var experience = new RequestExperienceDto { Title = "UpdatedExperience", CompanyName = "UpdatedCompany", StartingDate = DateTime.Now, EndingDate = DateTime.Now.AddDays(30), CurrentJob = false };
var result = await _experienceServices.UpdateExperience("3", experience);
Assert.Null(result);
}
[Fact]
public async Task DeleteExperience_ReturnsTrue_WhenIdExists()
{
var result = await _experienceServices.DeleteExperience("1");
Assert.True(result);
}
[Fact]
public async Task DeleteExperience_ReturnsFalse_WhenIdDoesNotExist()
{
var result = await _experienceServices.DeleteExperience("3");
Assert.False(result);
}
}

@ -1,143 +0,0 @@
using Moq;
using Infrastructure;
using Infrastructure.Entities;
using Microsoft.EntityFrameworkCore;
using Server.Dto.Request;
using Server.Services;
public class FormationServicesTests
{
private readonly Mock<AlumniDbContext> _mockContext;
private readonly FormationServices _formationServices;
public FormationServicesTests()
{
var formations = new List<FormationEntity>
{
new FormationEntity { Id = "1", Name = "Formation1", SchoolName = "School1", StartDate = DateTime.Now, EndDate = DateTime.Now.AddDays(30), IsCurrent = true },
new FormationEntity { Id = "2", Name = "Formation2", SchoolName = "School2", StartDate = DateTime.Now, EndDate = DateTime.Now.AddDays(30), IsCurrent = true }
}.AsQueryable();
var mockSet = new Mock<DbSet<FormationEntity>>();
mockSet.As<IQueryable<FormationEntity>>().Setup(m => m.Provider).Returns(formations.Provider);
mockSet.As<IQueryable<FormationEntity>>().Setup(m => m.Expression).Returns(formations.Expression);
mockSet.As<IQueryable<FormationEntity>>().Setup(m => m.ElementType).Returns(formations.ElementType);
mockSet.As<IQueryable<FormationEntity>>().Setup(m => m.GetEnumerator()).Returns(formations.GetEnumerator());
_mockContext = new Mock<AlumniDbContext>();
_mockContext.Setup(c => c.Formations).Returns(mockSet.Object);
_formationServices = new FormationServices(_mockContext.Object);
}
[Fact]
public async Task GetFormationById_ReturnsFormation_WhenIdExists()
{
var result = await _formationServices.GetFormationById("1");
Assert.NotNull(result);
Assert.Equal("1", result.Id);
}
[Fact]
public async Task GetFormationById_ReturnsNull_WhenIdDoesNotExist()
{
var result = await _formationServices.GetFormationById("3");
Assert.Null(result);
}
[Fact]
public async Task GetFormations_ReturnsFormations_WhenNameExists()
{
var result = await _formationServices.GetFormations("Formation1", 1, 1);
Assert.Single(result.Formations);
Assert.Equal("Formation1", result.Formations.First().Name);
}
[Fact]
public async Task GetFormations_ReturnsEmpty_WhenNameDoesNotExist()
{
var result = await _formationServices.GetFormations("Formation3", 1, 1);
Assert.Empty(result.Formations);
}
[Fact]
public async Task UpdateFormation_ReturnsUpdatedFormation_WhenIdExists()
{
var formation = new RequestFormationDto { Name = "UpdatedFormation", SchoolName = "UpdatedSchool", StartingDate = DateTime.Now, EndingDate = DateTime.Now.AddDays(30), CurrentFormation = false };
var result = await _formationServices.UpdateFormation("1", formation);
Assert.NotNull(result);
Assert.Equal("UpdatedFormation", result.Name);
}
[Fact]
public async Task UpdateFormation_ReturnsNull_WhenIdDoesNotExist()
{
var formation = new RequestFormationDto { Name = "UpdatedFormation", SchoolName = "UpdatedSchool", StartingDate = DateTime.Now, EndingDate = DateTime.Now.AddDays(30), CurrentFormation = false };
var result = await _formationServices.UpdateFormation("3", formation);
Assert.Null(result);
}
[Fact]
public async Task DeleteFormation_ReturnsTrue_WhenIdExists()
{
var result = await _formationServices.DeleteFormation("1");
Assert.True(result);
}
[Fact]
public async Task DeleteFormation_ReturnsFalse_WhenIdDoesNotExist()
{
var result = await _formationServices.DeleteFormation("3");
Assert.False(result);
}
[Fact]
public async Task GetFormations_NoName_ReturnsFormations()
{
// Arrange
string name = null;
var page = 1;
var size = 5;
// Act
var result = await _formationServices.GetFormations(name, page, size);
// Assert
Assert.NotEmpty(result.Formations);
Assert.Equal(2, result.Formations.Count());
}
[Fact]
public async Task GetFormations_MatchingName_ReturnsFilteredFormations()
{
// Arrange
string name = "Formation1";
var page = 1;
var size = 5;
// Act
var result = await _formationServices.GetFormations(name, page, size);
// Assert
Assert.Single(result.Formations);
Assert.Equal("Formation1", result.Formations.First().Name);
}
[Fact]
public async Task GetFormations_PaginationWorksCorrectly()
{
// Arrange
string name = null;
var page = 2;
var size = 1;
// Act
var result = await _formationServices.GetFormations(name, page, size);
// Assert
Assert.NotEmpty(result.Formations);
Assert.Single(result.Formations);
Assert.Equal("Formation2", result.Formations.First().Name);
}
}

@ -25,4 +25,10 @@
<Using Include="Xunit"/>
</ItemGroup>
<ItemGroup>
<Folder Include="ControllerTests\" />
<Folder Include="MapperTests\" />
<Folder Include="ServicesTests\" />
</ItemGroup>
</Project>

@ -1,93 +0,0 @@
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Server.Dto.Request;
using Server.Dto.Response;
class Program
{
static async Task Main(string[] args)
{
string baseUrl = "https://localhost:7273/api/v1/";
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(baseUrl);
// Création d'un nouvel élément
var newExperience = new RequestExperienceDto
{
AlumniId = "A1",
Title = "Junior Dev",
StartingDate = DateTime.Now.AddYears(-2),
CompanyName = "CGI",
CurrentJob = false
};
var json = JsonConvert.SerializeObject(newExperience);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PostAsync("experiences", content);
if (response.IsSuccessStatusCode)
{
var responseData = await response.Content.ReadAsStringAsync();
var createdExperience = JsonConvert.DeserializeObject<ResponseExperienceDto>(responseData);
Console.WriteLine($"Expérience créée avec succès. ID : {createdExperience.Id}");
}
else
{
Console.WriteLine($"Erreur lors de la création de l'expérience. Code : {response.StatusCode}");
}
// Lecture d'un élément par son ID
string experienceId = "123";
response = await client.GetAsync($"experiences/{experienceId}");
if (response.IsSuccessStatusCode)
{
var responseData = await response.Content.ReadAsStringAsync();
var experience = JsonConvert.DeserializeObject<ResponseExperienceDto>(responseData);
Console.WriteLine($"Expérience récupérée avec succès : {experience.Title}");
}
else
{
Console.WriteLine($"Erreur lors de la récupération de l'expérience. Code : {response.StatusCode}");
}
// Mise à jour d'un élément
var updatedExperience = new RequestExperienceDto
{
Title = "Senior Dev",
StartingDate = DateTime.Now.AddYears(-3),
CompanyName = "Microsoft",
CurrentJob = true,
AlumniId = "A1"
};
json = JsonConvert.SerializeObject(updatedExperience);
content = new StringContent(json, Encoding.UTF8, "application/json");
response = await client.PutAsync($"experiences/{experienceId}", content);
if (response.IsSuccessStatusCode)
{
var responseData = await response.Content.ReadAsStringAsync();
var experience = JsonConvert.DeserializeObject<ResponseExperienceDto>(responseData);
Console.WriteLine($"Expérience mise à jour avec succès : {experience.Title}");
}
else
{
Console.WriteLine($"Erreur lors de la mise à jour de l'expérience. Code : {response.StatusCode}");
}
// Suppression d'un élément
response = await client.DeleteAsync($"experiences/{experienceId}");
if (response.IsSuccessStatusCode)
{
Console.WriteLine("Expérience supprimée avec succès.");
}
else
{
Console.WriteLine($"Erreur lors de la suppression de l'expérience. Code : {response.StatusCode}");
}
}
}

@ -1,194 +0,0 @@
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
namespace UnitTestEF.Entities;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Infrastructure;
using Infrastructure.Entities;
[TestClass]
public class AlumniTest
{
[TestMethod]
public async Task AddAlumniTest()
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<AlumniDbContext>()
.UseSqlite(connection)
.Options;
using (var context = new AlumniDbContext(options))
{
context.Database.EnsureDeleted();
context.Database.EnsureCreated();
var alumnis = new List<User>(
[
new User
{
Id = "1",
FirstName = "Test",
LastName = "Test",
Email = "test@gmail.com",
EntryYear = "2021",
Password = "1234567890",
Role = "ADMIN"
},
new User
{
Id = "2",
FirstName = "Test2",
LastName = "Test2",
Email = "test2@gmail.com",
EntryYear = "2021",
Password = "1234567890",
Role = "USER",
}
]
);
await context.Alumni.AddRangeAsync(alumnis);
await context.SaveChangesAsync();
Assert.AreEqual(2, await context.Alumni.CountAsync());
var inBaseAlumni = await context.Alumni.FirstOrDefaultAsync(a => a.Id == "1");
Assert.IsNotNull(inBaseAlumni);
Assert.AreEqual("1", inBaseAlumni.Id);
Assert.AreEqual("Test", inBaseAlumni.FirstName);
Assert.AreEqual("Test", inBaseAlumni.LastName);
Assert.AreEqual("test@gmail.com", inBaseAlumni.Email);
Assert.AreEqual("2021", inBaseAlumni.EntryYear);
Assert.AreEqual("1234567890", inBaseAlumni.Password);
Assert.AreEqual("ADMIN", inBaseAlumni.Role);
var inBaseAlumni2 = await context.Alumni.FirstOrDefaultAsync(a => a.Id == "2");
Assert.IsNotNull(inBaseAlumni2);
Assert.AreEqual("2", inBaseAlumni2.Id);
Assert.AreEqual("Test2", inBaseAlumni2.FirstName);
Assert.AreEqual("Test2", inBaseAlumni2.LastName);
Assert.AreEqual("test2@gmail.com", inBaseAlumni2.Email);
Assert.AreEqual("2021", inBaseAlumni2.EntryYear);
Assert.AreEqual("1234567890", inBaseAlumni2.Password);
Assert.AreEqual("USER", inBaseAlumni2.Role);
}
}
[TestMethod]
public async Task DeleteAlumniTest()
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<AlumniDbContext>()
.UseSqlite(connection)
.Options;
using (var context = new AlumniDbContext(options))
{
context.Database.EnsureDeleted();
context.Database.EnsureCreated();
var alumni = new User
{
Id = "1",
FirstName = "Test",
LastName = "Test",
Email = "test@gmail.com",
EntryYear = "2021",
Password = "1234567890",
Role = "ADMIN"
};
await context.Alumni.AddAsync(alumni);
await context.SaveChangesAsync();
Assert.AreEqual(1, await context.Alumni.CountAsync());
var inBaseAlumni = await context.Alumni.FirstOrDefaultAsync(a => a.Id == "1");
Assert.IsNotNull(inBaseAlumni);
context.Alumni.Remove(alumni);
await context.SaveChangesAsync();
Assert.AreEqual(0, await context.Alumni.CountAsync());
}
}
[TestMethod]
public async Task UpdateAlumniTest()
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<AlumniDbContext>()
.UseSqlite(connection)
.Options;
using (var context = new AlumniDbContext(options))
{
context.Database.EnsureDeleted();
context.Database.EnsureCreated();
var alumni = new User
{
Id = "1",
FirstName = "Test",
LastName = "Test",
Email = "test@gmail.com",
EntryYear = "2021",
Password = "1234567890",
Role = "ADMIN"
};
await context.Alumni.AddAsync(alumni);
await context.SaveChangesAsync();
Assert.AreEqual(1, await context.Alumni.CountAsync());
var inBaseAlumni = await context.Alumni.FirstOrDefaultAsync(a => a.Id == "1");
Assert.IsNotNull(inBaseAlumni);
inBaseAlumni.FirstName = "Test2";
inBaseAlumni.LastName = "Test2";
inBaseAlumni.Email = "test2@gmail.com";
inBaseAlumni.EntryYear = "2022";
inBaseAlumni.Password = "0987654321";
inBaseAlumni.Role = "USER";
await context.SaveChangesAsync();
var alumniAfterUpdate = await context.Alumni.FirstOrDefaultAsync(a => a.Id == "1");
Assert.IsNotNull(alumniAfterUpdate);
Assert.AreEqual("1", alumniAfterUpdate.Id);
Assert.AreEqual("Test2", alumniAfterUpdate.FirstName);
Assert.AreEqual("Test2", alumniAfterUpdate.LastName);
Assert.AreEqual("test2@gmail.com", alumniAfterUpdate.Email);
Assert.AreEqual("2022", alumniAfterUpdate.EntryYear);
Assert.AreEqual("0987654321", alumniAfterUpdate.Password);
Assert.AreEqual("USER", alumniAfterUpdate.Role);
}
}
[TestMethod]
public void ToString_ReturnsCorrectFormat()
{
// Arrange
var alumni = new User
{
Id = "1",
FirstName = "Test",
LastName = "Test",
Email = "test@gmail.com",
EntryYear = "2021",
Password = "1234567890",
Role = "ADMIN",
Experiences = new List<ExperienceEntity>(),
Formations = new List<FormationEntity>(),
Events = new List<EventEntity>()
};
// Act
var result = alumni.ToString();
// Assert
var expected = "\t------------Alumni Id : 1 ------------- :\n\tFirstname : Test Lastname : Test Email : test@gmail.com Role : ADMIN\n\tExperiences : 0 \tFormations : 0 \t Events : 0";
Assert.AreEqual(expected, result);
}
}

@ -1,211 +0,0 @@
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
namespace UnitTestEF.Entities;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Infrastructure;
using Infrastructure.Entities;
[TestClass]
public class EventTest
{
[TestMethod]
public async Task AddEventTest()
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<AlumniDbContext>()
.UseSqlite(connection)
.Options;
using (var context = new AlumniDbContext(options))
{
context.Database.EnsureDeleted();
context.Database.EnsureCreated();
var newEvent = new EventEntity
{
Id = "1",
Title = "A Test Event",
Description = "A Test Description",
Date = new DateTime(2020, 9, 1),
nbPlaces = 50
};
await context.Events.AddAsync(newEvent);
await context.SaveChangesAsync();
Assert.AreEqual(1, await context.Events.CountAsync());
var inBaseEvent = await context.Events.FirstOrDefaultAsync(e => e.Id == "1");
Assert.IsNotNull(inBaseEvent);
Assert.AreEqual("1", inBaseEvent.Id);
Assert.AreEqual("A Test Event", inBaseEvent.Title);
Assert.AreEqual("A Test Description", inBaseEvent.Description);
Assert.AreEqual(new DateTime(2020, 9, 1), inBaseEvent.Date);
Assert.AreEqual(50, inBaseEvent.nbPlaces);
}
}
[TestMethod]
public async Task RemoveEventTest()
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<AlumniDbContext>()
.UseSqlite(connection)
.Options;
using (var context = new AlumniDbContext(options))
{
context.Database.EnsureDeleted();
context.Database.EnsureCreated();
var newEvent = new EventEntity
{
Id = "1",
Title = "A Test Event",
Description = "A Test Description",
Date = new DateTime(2020, 9, 1),
nbPlaces = 50
};
await context.Events.AddAsync(newEvent);
await context.SaveChangesAsync();
var inBaseEvent = await context.Events.FirstOrDefaultAsync(e => e.Id == "1");
Assert.IsNotNull(inBaseEvent);
context.Events.Remove(newEvent);
await context.SaveChangesAsync();
var eventAfterDelete = await context.Events.FirstOrDefaultAsync(e => e.Id == "1");
Assert.IsNull(eventAfterDelete);
}
}
[TestMethod]
public async Task UpdateEventTest()
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<AlumniDbContext>()
.UseSqlite(connection)
.Options;
using (var context = new AlumniDbContext(options))
{
context.Database.EnsureDeleted();
context.Database.EnsureCreated();
var newEvent = new EventEntity
{
Id = "1",
Title = "A Test Event",
Description = "A Test Description",
Date = new DateTime(2020, 9, 1),
nbPlaces = 50
};
await context.Events.AddAsync(newEvent);
await context.SaveChangesAsync();
var inBaseEvent = await context.Events.FirstOrDefaultAsync(e => e.Id == "1");
Assert.IsNotNull(inBaseEvent);
inBaseEvent.Title = "A New Title";
inBaseEvent.Description = "A New Description";
inBaseEvent.Date = new DateTime(2020, 9, 2);
inBaseEvent.nbPlaces = 100;
await context.SaveChangesAsync();
var eventAfterUpdate = await context.Events.FirstOrDefaultAsync(e => e.Id == "1");
Assert.IsNotNull(eventAfterUpdate);
Assert.AreEqual("1", eventAfterUpdate.Id);
Assert.AreEqual("A New Title", eventAfterUpdate.Title);
Assert.AreEqual("A New Description", eventAfterUpdate.Description);
Assert.AreEqual(new DateTime(2020, 9, 2), eventAfterUpdate.Date);
Assert.AreEqual(100, eventAfterUpdate.nbPlaces);
}
}
[TestMethod]
public async Task EventWithParticipantsTest()
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<AlumniDbContext>()
.UseSqlite(connection)
.Options;
using (var context = new AlumniDbContext(options))
{
context.Database.EnsureDeleted();
context.Database.EnsureCreated();
var newEvent = new EventEntity
{
Id = "1",
Title = "A Test Event",
Description = "A Test Description",
Date = new DateTime(2020, 9, 1),
nbPlaces = 50
};
await context.Events.AddAsync(newEvent);
await context.SaveChangesAsync();
var inBaseEvent = await context.Events.FirstOrDefaultAsync(e => e.Id == "1");
Assert.IsNotNull(inBaseEvent);
var participants = new List<User>(
[
new User
{
Id = "1",
FirstName = "Test",
LastName = "Test",
Email = "test@gmail.com",
EntryYear = "2021",
Password = "1234567890",
Role = "ADMIN"
},
new User
{
Id = "2",
FirstName = "Test2",
LastName = "Test2",
Email = "test2@gmail.com",
EntryYear = "2021",
Password = "1234567890",
Role = "USER",
}
]
);
foreach (var p in participants)
{
inBaseEvent.Participants.Add(p);
}
await context.SaveChangesAsync();
var eventWithParticipants = await context.Events.Include(e => e.Participants).FirstOrDefaultAsync(e => e.Id == "1");
Assert.IsNotNull(eventWithParticipants);
Assert.AreEqual(2, eventWithParticipants.Participants.Count);
foreach (var p in eventWithParticipants.Participants)
{
Assert.IsTrue(participants.Contains(p));
}
}
}
[TestMethod]
public void ToString_ReturnsCorrectFormat()
{
// Arrange
var eventEntity = new EventEntity
{
Title = "Test Event",
Description = "This is a test event",
Date = new DateTime(2022, 1, 1),
nbPlaces = 100
};
// Act
var result = eventEntity.ToString();
// Assert
var expected = "\tTitle: Test Event, Date: 01/01/2022 00:00:00, nbPlaces: 100";
Assert.AreEqual(expected, result);
}
}

@ -1,150 +0,0 @@
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
namespace UnitTestEF.Entities;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Infrastructure;
using Infrastructure.Entities;
[TestClass]
public class ExperienceTest
{
[TestMethod]
public async Task AddFormationTest()
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<AlumniDbContext>()
.UseSqlite(connection)
.Options;
using (var context = new AlumniDbContext(options))
{
context.Database.EnsureDeleted();
context.Database.EnsureCreated();
var exp = new ExperienceEntity()
{
Id = "100",
Title = "Software Engineer",
CompanyName = "CGI",
StartDate = new DateTime(2020, 9, 1),
EndDate = new DateTime(2022, 6, 1),
IsCurrent = true
};
await context.Experiences.AddAsync(exp);
await context.SaveChangesAsync();
var inBaseExp = await context.Experiences.FirstOrDefaultAsync(e => e.Id == "100");
Assert.IsNotNull(inBaseExp);
Assert.AreEqual("100", inBaseExp.Id);
Assert.AreEqual("Software Engineer", inBaseExp.Title);
Assert.AreEqual("CGI", inBaseExp.CompanyName);
Assert.AreEqual(new DateTime(2020, 9, 1), inBaseExp.StartDate);
Assert.AreEqual(new DateTime(2022, 6, 1), inBaseExp.EndDate);
Assert.IsTrue(inBaseExp.IsCurrent);
}
}
[TestMethod]
public async Task DeleteFormationTest()
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<AlumniDbContext>()
.UseSqlite(connection)
.Options;
using (var context = new AlumniDbContext(options))
{
context.Database.EnsureDeleted();
context.Database.EnsureCreated();
var exp = new ExperienceEntity()
{
Id = "100",
Title = "Software Engineer",
CompanyName = "CGI",
StartDate = new DateTime(2020, 9, 1),
EndDate = new DateTime(2022, 6, 1),
IsCurrent = true
};
await context.Experiences.AddAsync(exp);
await context.SaveChangesAsync();
var inBaseExp = await context.Experiences.FirstOrDefaultAsync(e => e.Id == "100");
Assert.IsNotNull(inBaseExp);
context.Experiences.Remove(exp);
await context.SaveChangesAsync();
var inBaseExp2 = await context.Experiences.FirstOrDefaultAsync(e => e.Id == "100");
Assert.IsNull(inBaseExp2);
}
}
[TestMethod]
public async Task UpdateFormationTest()
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<AlumniDbContext>()
.UseSqlite(connection)
.Options;
using (var context = new AlumniDbContext(options))
{
context.Database.EnsureDeleted();
context.Database.EnsureCreated();
var exp = new ExperienceEntity()
{
Id = "100",
Title = "Software Engineer",
CompanyName = "CGI",
StartDate = new DateTime(2020, 9, 1),
EndDate = new DateTime(2022, 6, 1),
IsCurrent = true
};
await context.Experiences.AddAsync(exp);
await context.SaveChangesAsync();
var inBaseExp = await context.Experiences.FirstOrDefaultAsync(e => e.Id == "100");
Assert.IsNotNull(inBaseExp);
inBaseExp.Title = "Software Engineer II";
inBaseExp.CompanyName = "CGI II";
inBaseExp.StartDate = new DateTime(2021, 9, 1);
inBaseExp.EndDate = new DateTime(2023, 6, 1);
inBaseExp.IsCurrent = false;
await context.SaveChangesAsync();
var inBaseExp2 = await context.Experiences.FirstOrDefaultAsync(e => e.Id == "100");
Assert.IsNotNull(inBaseExp2);
Assert.AreEqual("Software Engineer II", inBaseExp2.Title);
Assert.AreEqual("CGI II", inBaseExp2.CompanyName);
Assert.AreEqual(new DateTime(2021, 9, 1), inBaseExp2.StartDate);
Assert.AreEqual(new DateTime(2023, 6, 1), inBaseExp2.EndDate);
Assert.IsFalse(inBaseExp2.IsCurrent);
}
}
[TestMethod]
public void ToString_ReturnsCorrectFormat()
{
// Arrange
var experience = new ExperienceEntity
{
Id = "100",
Title = "Software Engineer",
CompanyName = "CGI",
StartDate = new DateTime(2020, 9, 1),
EndDate = new DateTime(2022, 6, 1),
IsCurrent = true
};
// Act
var result = experience.ToString();
// Assert
var expected = "\tTitle: Software Engineer, Company: CGI, Start Date: 01/09/2020, End Date: 01/06/2022, Is Current: True";
Assert.AreEqual(expected, result);
}
}

@ -1,145 +0,0 @@
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
namespace UnitTestEF.Entities;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Infrastructure;
using Infrastructure.Entities;
[TestClass]
public class FormationTest
{
[TestMethod]
public async Task AddFormationTest()
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<AlumniDbContext>()
.UseSqlite(connection)
.Options;
using (var context = new AlumniDbContext(options))
{
context.Database.EnsureDeleted();
context.Database.EnsureCreated();
var newFormation = new FormationEntity {
Id = "100",
SchoolName = "IUT",
Name = "BUT Informatique",
StartDate = new DateTime(2020, 9, 1),
EndDate = new DateTime(2022, 6, 1),
IsCurrent = true
};
await context.Formations.AddAsync(newFormation);
await context.SaveChangesAsync();
var inBaseFormation = await context.Formations.FirstOrDefaultAsync(f => f.Id == "100");
Assert.IsNotNull(inBaseFormation);
Assert.AreEqual("100", inBaseFormation.Id);
Assert.AreEqual("IUT", inBaseFormation.SchoolName);
Assert.AreEqual("BUT Informatique", inBaseFormation.Name);
Assert.AreEqual(new DateTime(2020, 9, 1), inBaseFormation.StartDate);
Assert.AreEqual(new DateTime(2022, 6, 1), inBaseFormation.EndDate);
Assert.IsTrue(inBaseFormation.IsCurrent);
}
}
[TestMethod]
public async Task DeleteFormationTest()
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<AlumniDbContext>()
.UseSqlite(connection)
.Options;
using (var context = new AlumniDbContext(options))
{
context.Database.EnsureDeleted();
context.Database.EnsureCreated();
var newFormation = new FormationEntity {
Id = "100",
SchoolName = "IUT",
Name = "BUT Informatique",
StartDate = new DateTime(2020, 9, 1),
EndDate = new DateTime(2022, 6, 1),
IsCurrent = true
};
await context.Formations.AddAsync(newFormation);
await context.SaveChangesAsync();
var inBaseFormation = await context.Formations.FirstOrDefaultAsync(f => f.Id == "100");
Assert.IsNotNull(inBaseFormation);
context.Formations.Remove(newFormation);
await context.SaveChangesAsync();
var formationAfterDelete = await context.Formations.FirstOrDefaultAsync(f => f.Id == "100");
Assert.IsNull(formationAfterDelete);
}
}
[TestMethod]
public async Task UpdateFormationTest()
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<AlumniDbContext>()
.UseSqlite(connection)
.Options;
using (var context = new AlumniDbContext(options))
{
context.Database.EnsureDeleted();
context.Database.EnsureCreated();
var newFormation = new FormationEntity {
Id = "100",
SchoolName = "IUT",
Name = "BUT Informatique",
StartDate = new DateTime(2020, 9, 1),
EndDate = new DateTime(2022, 6, 1),
IsCurrent = true
};
await context.Formations.AddAsync(newFormation);
await context.SaveChangesAsync();
var inBaseFormation = await context.Formations.FirstOrDefaultAsync(f => f.Id == "100");
Assert.IsNotNull(inBaseFormation);
inBaseFormation.SchoolName = "IUT2";
inBaseFormation.Name = "BUT Informatique2";
inBaseFormation.StartDate = new DateTime(2020, 9, 2);
inBaseFormation.EndDate = new DateTime(2022, 6, 2);
inBaseFormation.IsCurrent = false;
await context.SaveChangesAsync();
var formationAfterUpdate = await context.Formations.FirstOrDefaultAsync(f => f.Id == "100");
Assert.IsNotNull(formationAfterUpdate);
Assert.AreEqual("IUT2", formationAfterUpdate.SchoolName);
Assert.AreEqual("BUT Informatique2", formationAfterUpdate.Name);
Assert.AreEqual(new DateTime(2020, 9, 2), formationAfterUpdate.StartDate);
Assert.AreEqual(new DateTime(2022, 6, 2), formationAfterUpdate.EndDate);
Assert.IsFalse(formationAfterUpdate.IsCurrent);
}
}
[TestMethod]
public void ToString_ReturnsCorrectFormat()
{
// Arrange
var formation = new FormationEntity
{
Id = "100",
SchoolName = "IUT",
Name = "BUT Informatique",
StartDate = new DateTime(2020, 9, 1),
EndDate = new DateTime(2022, 6, 1),
IsCurrent = true
};
// Act
var result = formation.ToString();
// Assert
var expected = "\tFormation : BUT Informatique \tSchool's name : IUT";
Assert.AreEqual(expected, result);
}
}

@ -21,4 +21,8 @@
<ProjectReference Include="..\Infrastructure\Infrastructure.csproj" />
</ItemGroup>
<ItemGroup>
<Folder Include="Entities\" />
</ItemGroup>
</Project>

Loading…
Cancel
Save