Compare commits

...

98 Commits

Author SHA1 Message Date
David D'ALMEIDA de2daa5693 Mise à jour de 'EntityFramework_LoL/Sources/API_LoL_Project/Program.cs'
continuous-integration/drone/push Build is passing Details
1 year ago
David D'ALMEIDA 8f150d8db0 Mise à jour de 'EntityFramework_LoL/Sources/API_LoL_Project/Program.cs'
continuous-integration/drone/push Build is passing Details
1 year ago
David D'ALMEIDA 13bb701d1d Mise à jour de 'EntityFramework_LoL/Sources/API_LoL_Project/Dockerfile'
continuous-integration/drone/push Build is passing Details
1 year ago
David D'ALMEIDA 8d50285de5 Mise à jour de 'EntityFramework_LoL/Sources/API_LoL_Project/Dockerfile'
continuous-integration/drone/push Build is passing Details
1 year ago
David D'ALMEIDA 78290912be Mise à jour de 'EntityFramework_LoL/Sources/API_LoL_Project/Dockerfile'
continuous-integration/drone/push Build is passing Details
1 year ago
Arthur VALIN c0afc8a4a3 revert 37afa9436d
continuous-integration/drone/push Build is passing Details
2 years ago
Arthur VALIN 37afa9436d Supprimer 'EntityFramework_LoL/Sources/API_LoL_Project/Dockerfile'
continuous-integration/drone/push Build was killed Details
2 years ago
David D'ALMEIDA 1402ae1b95 Mise à jour de 'EntityFramework_LoL/Sources/API_LoL_Project/Controllers/version2/RuneController.cs'
continuous-integration/drone/push Build is passing Details
2 years ago
David D'ALMEIDA dd0d45f131 Mise à jour de 'EntityFramework_LoL/Sources/ApiMappeur/ChampionMapper.cs'
continuous-integration/drone/push Build is passing Details
2 years ago
David D'ALMEIDA 9707d2ce23 Mise à jour de 'EntityFramework_LoL/Sources/ApiMappeur/ChampionMapper.cs'
continuous-integration/drone/push Build is failing Details
2 years ago
David D'ALMEIDA 5b5fbc4e29 Mise à jour de 'EntityFramework_LoL/Sources/DTO/ChampionDTO.cs'
continuous-integration/drone/push Build is passing Details
2 years ago
David D'ALMEIDA c1dbb0c469 Mise à jour de 'EntityFramework_LoL/Sources/ApiMappeur/ImageMappeur.cs'
continuous-integration/drone/push Build is passing Details
2 years ago
David D'ALMEIDA 9a65aae7c1 Mise à jour de 'README.md'
continuous-integration/drone/push Build is passing Details
2 years ago
David D'ALMEIDA 62e10a01c5 Mise à jour de 'README.md'
continuous-integration/drone/push Build is passing Details
2 years ago
David D'ALMEIDA 043826bcaa Mise à jour de 'README.md'
continuous-integration/drone/push Build is passing Details
2 years ago
David D'ALMEIDA 9e74449ef7 Mise à jour de 'README.md'
continuous-integration/drone/push Build is passing Details
2 years ago
David D'ALMEIDA 72b88d04d4 Mise à jour de 'README.md'
continuous-integration/drone/push Build is passing Details
2 years ago
David D'ALMEIDA 80a880ebdc Mise à jour de 'README.md'
continuous-integration/drone/push Build is passing Details
2 years ago
David D'ALMEIDA c686ee9737 Mise à jour de 'README.md'
continuous-integration/drone/push Build is passing Details
2 years ago
David D'ALMEIDA 9792fb3325 Merge pull request 'fixing' (#12) from Cleaning into master
continuous-integration/drone/push Build is passing Details
2 years ago
David D'ALMEIDA 911acb9cb6 Mise à jour de 'README.md'
continuous-integration/drone/push Build is passing Details
2 years ago
David D'ALMEIDA 3c174bf47c Transférer les fichiers vers 'doc/images'
continuous-integration/drone/push Build is passing Details
2 years ago
David D'ALMEIDA 554f254a2c Mise à jour de 'README.md'
continuous-integration/drone/push Build is passing Details
2 years ago
David D'ALMEIDA 0c69cd0add fixing
continuous-integration/drone/push Build is passing Details
2 years ago
David D'ALMEIDA 93b1ec94da merging
continuous-integration/drone/push Build is passing Details
2 years ago
David D'ALMEIDA 5cf4b8b162 fix ci
continuous-integration/drone/push Build is passing Details
2 years ago
David D'ALMEIDA a0e30de9e4 cleaning -v1
continuous-integration/drone/push Build is failing Details
2 years ago
Arthur VALIN b28f68b357 Correcting bug
continuous-integration/drone/push Build is passing Details
2 years ago
Arthur VALIN 8895681c0d Merge pull request 'Doc' (#10) from Doc into master
continuous-integration/drone/push Build is passing Details
2 years ago
Arthur VALIN 2a973b3650 Mise à jour de 'README.md'
continuous-integration/drone/push Build is passing Details
2 years ago
Arthur VALIN e0cc814ca8 Mise à jour de 'README.md'
continuous-integration/drone/push Build is passing Details
2 years ago
Arthur VALIN cac0679524 Mise à jour de 'README.md'
continuous-integration/drone/push Build is passing Details
2 years ago
Arthur VALIN 991d29d53c Merge pull request 'Dave_more' (#9) from Dave_more into master
continuous-integration/drone/push Build is passing Details
2 years ago
David D'ALMEIDA d00d7dd800 add on champion for ci
continuous-integration/drone/push Build is passing Details
2 years ago
David D'ALMEIDA 9de5562e0c Mise à jour de 'README.md'
continuous-integration/drone/push Build is passing Details
2 years ago
David D'ALMEIDA f1fa313c05 Mise à jour de '.drone.yml'
continuous-integration/drone/push Build is passing Details
2 years ago
David D'ALMEIDA a8474290ba Mise à jour de '.drone.yml'
continuous-integration/drone/push Build is passing Details
2 years ago
David D'ALMEIDA 70ffad9cbb test ci
continuous-integration/drone/push Build is passing Details
2 years ago
Arthur VALIN 76eaa9e7a7 Mise à jour de 'README.md'
continuous-integration/drone/push Build is passing Details
2 years ago
Arthur VALIN abed1a36be Mise à jour de 'README.md'
continuous-integration/drone/push Build is passing Details
2 years ago
Arthur VALIN a721d6f711 Mise à jour de 'README.md'
continuous-integration/drone/push Build is passing Details
2 years ago
Arthur VALIN 52c64dc7a2 Transférer les fichiers vers 'doc/images'
continuous-integration/drone/push Build is passing Details
2 years ago
Arthur VALIN db4b182030 Mise à jour de 'README.md'
continuous-integration/drone/push Build is passing Details
2 years ago
Arthur VALIN b7d1df2fbb Mise à jour de 'README.md'
continuous-integration/drone/push Build is passing Details
2 years ago
David D'ALMEIDA fe8d292f9e Mise à jour de 'README.md'
continuous-integration/drone/push Build is passing Details
2 years ago
David D'ALMEIDA 107237ae60 Transférer les fichiers vers 'doc/images'
continuous-integration/drone/push Build is passing Details
2 years ago
David D'ALMEIDA f65b2a36fd Supprimer 'Component 1(1).png'
continuous-integration/drone/push Build is passing Details
2 years ago
David D'ALMEIDA 4110eaa5e7 doc/images
continuous-integration/drone/push Build is passing Details
2 years ago
David D'ALMEIDA 60dec6265d add lib
continuous-integration/drone/push Build is passing Details
2 years ago
David D'ALMEIDA 44e377be5e fix ci
continuous-integration/drone/push Build is failing Details
2 years ago
David D'ALMEIDA 0554f7dff5 Supprimer 'EntityFramework_LoL/Sources/ApiLib/ApiLib.csproj'
continuous-integration/drone/push Build is failing Details
2 years ago
David D'ALMEIDA eebdbe43b3 Mise à jour de 'EntityFramework_LoL/Sources/Test_Api/ChampionControllerTest.cs'
continuous-integration/drone/push Build is failing Details
2 years ago
David D'ALMEIDA 2654d4dc27 Supprimer 'EntityFramework_LoL/Sources/ApiLib/Program.cs'
continuous-integration/drone/push Build was killed Details
2 years ago
David D'ALMEIDA db44f294f0 Supprimer 'EntityFramework_LoL/Sources/ApiLib/ApiManager.cs'
continuous-integration/drone/push Build was killed Details
2 years ago
David D'ALMEIDA 5ca44d3039 Supprimer 'EntityFramework_LoL/Sources/ApiLib/ChampionsManager.cs'
continuous-integration/drone/push Build is failing Details
2 years ago
David D'ALMEIDA 06a2af01de test fixing for the CI
continuous-integration/drone/push Build is passing Details
2 years ago
David D'ALMEIDA b0802493c0 merge sucess
continuous-integration/drone/push Build is failing Details
2 years ago
Arthur VALIN 6818af2b49 Merge pull request 'Arthur_More' (#7) from Arthur_More into master
continuous-integration/drone/push Build is passing Details
2 years ago
David D'ALMEIDA 62da8b153a Mise à jour de 'README.md'
continuous-integration/drone/push Build is passing Details
2 years ago
David D'ALMEIDA 595e241164 Mise à jour de 'EntityFramework_LoL/Sources/API_LoL_Project/Controllers/Request/PageRequest.cs'
continuous-integration/drone/push Build is passing Details
2 years ago
David D'ALMEIDA 50fd3c488d Mise à jour de 'EntityFramework_LoL/Sources/API_LoL_Project/Controllers/Request/PageRequest.cs'
continuous-integration/drone/push Build is passing Details
2 years ago
Arthur VALIN a91154ff3a Adding large image to entity mappers
continuous-integration/drone/push Build is passing Details
2 years ago
David D'ALMEIDA 542732a743 Mise à jour de 'README.md'
continuous-integration/drone/push Build was killed Details
2 years ago
David D'ALMEIDA a314b8af93 Mise à jour de '.drone.yml'
continuous-integration/drone/push Build is passing Details
2 years ago
Arthur VALIN 794d5250d2 Mise à jour de 'README.md'
continuous-integration/drone/push Build was killed Details
2 years ago
Arthur VALIN d8b404bb6a Transférer les fichiers vers 'doc/images'
continuous-integration/drone/push Build is passing Details
2 years ago
Arthur VALIN 361a7fe9d5 Correcting bug
continuous-integration/drone/push Build is passing Details
2 years ago
Arthur VALIN 0dc5acc2f0 Adding includes
continuous-integration/drone/push Build is failing Details
2 years ago
Arthur VALIN 3df77d1a19 Mise à jour de 'README.md'
continuous-integration/drone/push Build is passing Details
2 years ago
Arthur VALIN 5117a26e16 Mise à jour de 'README.md'
continuous-integration/drone/push Build is passing Details
2 years ago
Arthur VALIN a8a4782085 Starting documentation
continuous-integration/drone/push Build is passing Details
2 years ago
Arthur VALIN 0668f2f44f Merge
continuous-integration/drone/push Build is passing Details
2 years ago
Arthur VALIN 9b003fa617 Adding tests on runepages
continuous-integration/drone/push Build is passing Details
2 years ago
Arthur VALIN f2c5d1ba24 Starting tests on RunePages
continuous-integration/drone/push Build is passing Details
2 years ago
Arthur VALIN 9d3ed7969a Adding more complete tests for champions
continuous-integration/drone/push Build is passing Details
2 years ago
David D'ALMEIDA 5bd1f568dc fix all
continuous-integration/drone/push Build is failing Details
2 years ago
Arthur VALIN 79b7bf3603 Adding simple tests on Runes
continuous-integration/drone/push Build is passing Details
2 years ago
Arthur VALIN aa7967839c Merge branch 'Arthur_EF_TestingInMemory' of https://codefirst.iut.uca.fr/git/arthur.valin/League-of-Legends_Project into Arthur_EF_TestingInMemory
continuous-integration/drone/push Build is passing Details
2 years ago
Arthur VALIN ac8f0dfff1 Adding Characteristics to Champion tests
2 years ago
Arthur VALIN 7d7e9a6c2f Mise à jour de '.drone.yml'
continuous-integration/drone/push Build is passing Details
2 years ago
Arthur VALIN 1ebe7b3b32 Adding Skills to Champion tests
continuous-integration/drone/push Build is passing Details
2 years ago
Arthur VALIN ba1a330726 Mise à jour de '.drone.yml'
continuous-integration/drone/push Build is passing Details
2 years ago
Arthur VALIN 8067eb21da Mise à jour de '.drone.yml'
continuous-integration/drone/push Build is passing Details
2 years ago
Arthur VALIN f2ad9c28cc Supprimer '.drone.yaml'
continuous-integration/drone/push Build is passing Details
2 years ago
Arthur VALIN 91e9449098 Mise à jour de '.drone.yml'
continuous-integration/drone/push Build is passing Details
2 years ago
Arthur VALIN 277c1cb3d4 Mise à jour de '.drone.yml'
continuous-integration/drone/push Build is passing Details
2 years ago
Arthur VALIN af379b1994 Mise à jour de '.drone.yml'
continuous-integration/drone/push Build is passing Details
2 years ago
Arthur VALIN 50e115de70 Mise à jour de '.drone.yml'
continuous-integration/drone/push Build is failing Details
2 years ago
Arthur VALIN a0822f85eb Mise à jour de '.drone.yml'
continuous-integration/drone/push Build is failing Details
2 years ago
Arthur VALIN 413ac848f4 Mise à jour de '.drone.yml'
continuous-integration/drone/push Build is failing Details
2 years ago
Arthur VALIN 06567ef8f0 CI Test
continuous-integration/drone/push Build is failing Details
2 years ago
Arthur VALIN 95249f3e99 Adding simple unit tests for SkinEntity
continuous-integration/drone/push Build is failing Details
2 years ago
Arthur VALIN cf107b961b Adding simple tests on Champion Entity
continuous-integration/drone/push Build is failing Details
2 years ago
David D'ALMEIDA 7e119a10de solving merge error
continuous-integration/drone/push Build is failing Details
2 years ago
Arthur VALIN 527c0e71f5 Merge pull request 'Arthur_ConnectionString' (#4) from Arthur_ConnectionString into master
continuous-integration/drone/push Build is failing Details
2 years ago
Arthur VALIN af54cf8375 Changing Dbcontext/Manager from Singleton to Scoped
continuous-integration/drone/push Build is failing Details
2 years ago
Arthur VALIN 8cecd77d44 Injecting connection string
continuous-integration/drone/push Build is failing Details
2 years ago
Arthur VALIN aa027cda95 Adding ConnectionStrings to AppSettings and separating EntityMappers from API
continuous-integration/drone/push Build is failing Details
2 years ago

@ -1,77 +0,0 @@
kind: pipeline
type: docker
name: default
trigger:
event:
- push
steps:
- name: build
image: mcr.microsoft.com/dotnet/sdk:6.0
volumes:
- name: docs
path: /docs
commands:
- cd EntityFramework_LoL/Sources/
- dotnet restore LeagueOfLegends.sln
- dotnet build LeagueOfLegends.sln -c Release --no-restore
- dotnet publish LeagueOfLegends.sln -c Release --no-restore -o CI_PROJECT_DIR/build/release
# docker image build
- name: docker-build-and-push
image: plugins/docker
settings:
dockerfile: EntityFramework_LoL/Sources/Dockerfile
context: EntityFramework_LoL/Sources/
registry: hub.codefirst.iut.uca.fr
repo: hub.codefirst.iut.uca.fr/git/arthur.valin/League-of-Legends_Project
username:
from_secret: SECRET_REGISTRY_USERNAME
password:
from_secret: SECRET_REGISTRY_PASSWORD
- name: tests
image: mcr.microsoft.com/dotnet/sdk:6.0
commands:
- cd EntityFramework_LoL/Sources/
- dotnet restore LeagueOfLegends.sln
- dotnet test LeagueOfLegends.sln --no-restore
depends_on: [build]
- name: code-analysis
image: hub.codefirst.iut.uca.fr/thomas.bellembois/codefirst-dronesonarplugin-dotnet6
commands:
- cd EntityFramework_LoL/Sources/
- dotnet restore LeagueOfLegends.sln
- dotnet sonarscanner begin /k:droneTemplate /d:sonar.host.url=$${PLUGIN_SONAR_HOST} /d:sonar.coverageReportPaths="coveragereport/SonarQube.xml" /d:sonar.coverage.exclusions="Tests/**" /d:sonar.login=$${PLUGIN_SONAR_TOKEN}
- dotnet build LeagueOfLegends.sln -c Release --no-restore
- dotnet test LeagueOfLegends.sln --logger trx --no-restore /p:CollectCoverage=true /p:CoverletOutputFormat=cobertura --collect "XPlat Code Coverage"
- reportgenerator -reports:"**/coverage.cobertura.xml" -reporttypes:SonarQube -targetdir:"coveragereport"
- dotnet publish LeagueOfLegends.sln -c Release --no-restore -o CI_PROJECT_DIR/build/release
- dotnet sonarscanner end /d:sonar.login=$${PLUGIN_SONAR_TOKEN}
secrets: [ SECRET_SONAR_LOGIN ]
settings:
# accessible en ligne de commande par ${PLUGIN_SONAR_HOST}
sonar_host: https://codefirst.iut.uca.fr/sonar/
# accessible en ligne de commande par ${PLUGIN_SONAR_TOKEN}
sonar_token:
from_secret: SECRET_SONAR_LOGIN
depends_on: [tests]
- name: generate-and-deploy-docs
image: hub.codefirst.iut.uca.fr/thomas.bellembois/codefirst-docdeployer
failure: ignore
volumes:
- name: docs
path: /docs
commands:
#- cd Documentation/doxygen
#- doxygen Doxyfile
- /entrypoint.sh
when:
branch:
- master
depends_on: [ build ]
volumes:
- name: docs
temp: {}

@ -21,16 +21,18 @@ steps:
- name: docker-build-and-push
image: plugins/docker
settings:
dockerfile: EntityFramework_LoL/Sources/Dockerfile
dockerfile: EntityFramework_LoL/Sources/API_LoL_Project/Dockerfile
context: EntityFramework_LoL/Sources/
registry: hub.codefirst.iut.uca.fr
repo: hub.codefirst.iut.uca.fr/git/arthur.valin/League-of-Legends_Project
repo: hub.codefirst.iut.uca.fr/arthur.valin/league-of-legends_project
username:
from_secret: SECRET_REGISTRY_USERNAME
password:
from_secret: SECRET_REGISTRY_PASSWORD
- name: tests
image: mcr.microsoft.com/dotnet/sdk:6.0
ADMINS: davidd_almeida,arthurvalin
commands:
- cd EntityFramework_LoL/Sources/
- dotnet restore LeagueOfLegends.sln
@ -54,6 +56,37 @@ steps:
- master
depends_on: [ build ]
- name: deploy-container
image: hub.codefirst.iut.uca.fr/thomas.bellembois/codefirst-dockerproxy-clientdrone:latest
environment:
IMAGENAME: hub.codefirst.iut.uca.fr/arthur.valin/league-of-legends_project:latest
CONTAINERNAME: lolcontainer
COMMAND: create
OVERWRITE: true
ADMINS: davidd_almeida,arthurvalin
depends_on: [ docker-build-and-push ]
- name: code-analysis
image: hub.codefirst.iut.uca.fr/thomas.bellembois/codefirst-dronesonarplugin-dotnet6
ADMINS: davidd_almeida,arthurvalin
commands:
- cd EntityFramework_LoL/Sources/
- dotnet restore LeagueOfLegends.sln
- dotnet sonarscanner begin /k:LOLProject /d:sonar.host.url=$${PLUGIN_SONAR_HOST} /d:sonar.coverageReportPaths="coveragereport/SonarQube.xml" /d:sonar.coverage.exclusions="Tests/**" /d:sonar.login=$${PLUGIN_SONAR_TOKEN}
- dotnet build LeagueOfLegends.sln -c Release --no-restore
- dotnet test LeagueOfLegends.sln --logger trx --no-restore /p:CollectCoverage=true /p:CoverletOutputFormat=cobertura --collect "XPlat Code Coverage"
- reportgenerator -reports:"**/coverage.cobertura.xml" -reporttypes:SonarQube -targetdir:"coveragereport"
- dotnet publish LeagueOfLegends.sln -c Release --no-restore -o CI_PROJECT_DIR/build/release
- dotnet sonarscanner end /d:sonar.login=$${PLUGIN_SONAR_TOKEN}
secrets: [ SONAR_TOKEN ]
settings:
# accessible en ligne de commande par ${PLUGIN_SONAR_HOST}
sonar_host: https://codefirst.iut.uca.fr/sonar/
# accessible en ligne de commande par ${PLUGIN_SONAR_TOKEN}
sonar_token:
from_secret: SONAR_TOKEN
depends_on: [tests]
volumes:
- name: docs
temp: {}

@ -9,20 +9,21 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning" Version="5.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning.ApiExplorer" Version="5.0.0" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.15.1" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\DTO\DTO.csproj" />
<ProjectReference Include="..\ApiMappeur\ApiMappeur.csproj" />
<ProjectReference Include="..\Business\Business.csproj" />
<ProjectReference Include="..\Entities\Entities.csproj" />
<ProjectReference Include="..\Model\Model.csproj" />
<ProjectReference Include="..\StubLib\StubLib.csproj" />
</ItemGroup>
<ItemGroup>
<Folder Include="Controllers\version2\" />
<Folder Include="Controllers\version1\" />
<Folder Include="service\" />
</ItemGroup>

@ -1,29 +1,12 @@
namespace API_LoL_Project.Controllers.Request
{
public class PageRequest
{
//max leght
public string? orderingPropertyName { get; set; } = null;
public bool? descending { get; set; } = false;
// const int maxPageSize = 50;
// public int PageNumber { get; set; } = 1;
public int index { get; set; } = 1;
public int count { get; set; } = 1;
/*
//max lentght
private int _pageSize;
public int PageSize
{
get
{
return _pageSize;
}
set
{
_pageSize = (value > maxPageSize) ? maxPageSize : value;
}
}*/
}
}
namespace API_LoL_Project.Controllers.Request
{
public class PageRequest
{
public string? orderingPropertyName { get; set; } = null;
public bool? descending { get; set; } = false;
public int index { get; set; } = 0;
public int count { get; set; } = 0;
}
}

@ -4,13 +4,13 @@ namespace API_LoL_Project.Controllers.Response
{
public class PageResponse<T>
{
public IEnumerable<LolResponce<T>> Data { get; set; }
public IEnumerable<LolResponse<T>> Data { get; set; }
public int Index { get; set; } = 1;
public int TotalCount { get; set; } = 1;
public int Count { get; set; } = 1;
public PageResponse(IEnumerable<LolResponce<T>> data, int indexRequested, int countRequested, int totalCount)
public PageResponse(IEnumerable<LolResponse<T>> data, int indexRequested, int countRequested, int totalCount)
{
this.Data = data;
this.Index = indexRequested;

@ -1,71 +0,0 @@
using DTO;
using Microsoft.AspNetCore.Mvc;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace API_LoL_Project.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class RunePageController : ControllerBase
{
/* // GET: api/<RunePageController>
[HttpGet]
public async Task<ActionResult<IEnumerable<RuneDTO>>> Get([FromQuery] Request.PageRequest request)
{
try
{
var totalcount = await runesManager.GetNbItems();
if (request.count + request.index > totalcount)
{
_logger.LogWarning("to many rows ask the max is {totalcount}", totalcount);
return BadRequest("to many rows ask the max is " + totalcount);
}
_logger.LogInformation("Executing {Action} with parameters: {Parameters}", nameof(Get), request);
var runes = await runesManager.GetItems(request.PageNumber, totalcount, request.orderingPropertyName, (request.descending == null ? false : (bool)request.descending));
IEnumerable<RuneDTO> res = runes.Select(c => c.toDTO());
if (res.Count() >= 0 || res == null)
{
_logger.LogWarning("No runes found with Id");
return BadRequest("No runes found with Id ");
}
return Ok(res);
}
catch (Exception e)
{
_logger.LogError("About get at {e.message}", DateTime.UtcNow.ToLongTimeString());
return BadRequest(e.Message);
}
}
// GET api/<RunePageController>/5
[HttpGet("{id}")]
public string Get(int id)
{
return "value";
}
// POST api/<RunePageController>
[HttpPost]
public void Post([FromBody] string value)
{
}
// PUT api/<RunePageController>/5
[HttpPut("{id}")]
public void Put(int id, [FromBody] string value)
{
}
// DELETE api/<RunePageController>/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}*/
}
}

@ -1,70 +0,0 @@
using Microsoft.AspNetCore.Mvc;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace API_LoL_Project.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class SkillController : ControllerBase
{
/* // GET: api/<SkillController>
[HttpGet]
public async Task<ActionResult<IEnumerable<RuneDTO>>> Get([FromQuery] Request.PageRequest request)
{
try
{
var totalcount = await runesManager.GetNbItems();
if (request.count + request.index > totalcount)
{
_logger.LogWarning("to many rows ask the max is {totalcount}", totalcount);
return BadRequest("to many rows ask the max is " + totalcount);
}
_logger.LogInformation("Executing {Action} with parameters: {Parameters}", nameof(Get), request);
var runes = await runesManager.GetItems(request.PageNumber, totalcount, request.orderingPropertyName, (request.descending == null ? false : (bool)request.descending));
IEnumerable<RuneDTO> res = runes.Select(c => c.toDTO());
if (res.Count() >= 0 || res == null)
{
_logger.LogWarning("No runes found with Id");
return BadRequest("No runes found with Id ");
}
return Ok(res);
}
catch (Exception e)
{
_logger.LogError("About get at {e.message}", DateTime.UtcNow.ToLongTimeString());
return BadRequest(e.Message);
}
}
// GET api/<SkillController>/5
[HttpGet("{id}")]
public string Get(int id)
{
return "value";
}
// POST api/<SkillController>
[HttpPost]
public void Post([FromBody] string value)
{
}
// PUT api/<SkillController>/5
[HttpPut("{id}")]
public void Put(int id, [FromBody] string value)
{
}
// DELETE api/<SkillController>/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}*/
}
}

@ -1,80 +0,0 @@
using DTO;
using Microsoft.AspNetCore.Mvc;
using Model;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace API_LoL_Project.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class SkinController : ControllerBase
{
/* public ISkinsManager dataManager;
private readonly ILogger<ChampionsController> _logger;
public SkinController(IDataManager dataManager, ILogger<ChampionsController> logger)
{
this.dataManager = dataManager.SkinsMgr;
this._logger = logger;
}
// GET: api/<SkinController>
[HttpGet]
public async Task<ActionResult<IEnumerable<RuneDTO>>> Get([FromQuery] Request.PageRequest request)
{
try
{
var totalcount = await dataManager.GetNbItems();
if (request.count + request.index > totalcount)
{
_logger.LogWarning("to many rows ask the max is {totalcount}", totalcount);
return BadRequest("to many rows ask the max is " + totalcount);
}
_logger.LogInformation("Executing {Action} with parameters: {Parameters}", nameof(Get), request);
var runes = await dataManager.GetItems(request.PageNumber, totalcount, request.orderingPropertyName, (request.descending == null ? false : (bool)request.descending));
IEnumerable<RuneDTO> res = runes.Select(c => c.toDTO());
if (res.Count() >= 0 || res == null)
{
_logger.LogWarning("No runes found with Id");
return BadRequest("No runes found with Id ");
}
return Ok(res);
}
catch (Exception e)
{
_logger.LogError("About get at {e.message}", DateTime.UtcNow.ToLongTimeString());
return BadRequest(e.Message);
}
}
// GET api/<SkinController>/5
[HttpGet("{id}")]
public string Get(int id)
{
return "value";
}
// POST api/<SkinController>
[HttpPost]
public void Post([FromBody] string value)
{
}
// PUT api/<SkinController>/5
[HttpPut("{id}")]
public void Put(int id, [FromBody] string value)
{
}
// DELETE api/<SkinController>/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}*/
}
}

@ -1,33 +0,0 @@
using Microsoft.AspNetCore.Mvc;
namespace API_LoL_Project.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
}
}

@ -1,5 +1,4 @@
using API_LoL_Project.Controllers.Response;
using API_LoL_Project.Mapper;
using API_LoL_Project.Middleware;
using DTO;
using Microsoft.AspNetCore.Mvc;
@ -8,31 +7,23 @@ using StubLib;
using System.Collections.Generic;
using System.Text.Json;
using System.Xml.Linq;
using ApiMappeur;
namespace API_LoL_Project.Controllers
namespace API_LoL_Project.Controllers.version1
{
/*[Route("api/v{version:apiVersion}/[controller]")]*/
[Route("api/[controller]")]
/*[ApiVersion("1.0")]*/
[Route("api/v{version:apiVersion}/[controller]")]
[ApiVersion("1.0")]
[ApiController]
public class ChampionsController : ControllerBase
{
public IChampionsManager dataManager;
private readonly ILogger<ChampionsController> _logger;
/* public ChampionsController(IChampionsManager dataManager)
{
this.dataManager = dataManager;
}*/
public ChampionsController(IDataManager dataManager, ILogger<ChampionsController> logger)
{
this.dataManager = dataManager.ChampionsMgr;
this._logger = logger;
_logger = logger;
}
// GET: api/<ChampionController>/getAllChampions
[HttpGet]
public async Task<ActionResult<PageResponse<ChampionDTO>>> Get([FromQuery] Request.PageRequest request)
@ -42,25 +33,25 @@ namespace API_LoL_Project.Controllers
var totalcount = await dataManager.GetNbItems();
if (request.count * request.index >= totalcount)
{
_logger.LogError("To many object is asked the max is {totalcount} but the request is supérior of ", totalcount);
_logger.LogError("To many object is asked the max is {totalcount} but the request is superior of ", totalcount);
return BadRequest("To many object is asked the max is : " + totalcount);
}
_logger.LogInformation("Executing {Action} with parameters: {Parameters}", nameof(Get), request); ;
var champions = await dataManager.GetItems(request.index, request.count, request.orderingPropertyName, (request.descending == null ? false : (bool)request.descending));
var champions = await dataManager.GetItems(request.index, request.count, request.orderingPropertyName, request.descending == null ? false : (bool)request.descending);
IEnumerable<ChampionDTO> res = champions.Select(c => c.ToDTO());
if (res.Count() <= 0 || res == null)
{
_logger.LogError("No chamions found the total count is {totalcount} ", totalcount);
return BadRequest("No chamions found : totalcount is : " + totalcount);
_logger.LogError("No champions found the total count is {totalcount} ", totalcount);
return BadRequest("No champions found : totalcount is : " + totalcount);
}
var respList = res.Select(r => new LolResponce<ChampionDTO>
var respList = res.Select(r => new LolResponse<ChampionDTO>
(
r,
new List<EndPointLink>
{
EndPointLink.To($"/api/[controller]/{r.Name}", "self"),
EndPointLink.To($"/api1111111111/[controller]/{r.Name}", "self"),
EndPointLink.To($"/api/[controller]/{r.Name}/{nameof(Get)}", "self"),
EndPointLink.To($"/api/[controller]/{r.Name}/{nameof(GetChampionsImage)}", "self"),
EndPointLink.To($"/api/[controller]/{r.Name}/{nameof(GetChampionsByName)}", "self"),
@ -115,6 +106,12 @@ namespace API_LoL_Project.Controllers
{
try
{
if (name == null || name == "")
{
var message = string.Format("Can not get champions image without the name (is empty)");
_logger.LogWarning(message); ;
return BadRequest(message);
}
var champion = await dataManager
.GetItemsByName(name, 0, await dataManager.GetNbItems());
_logger.LogInformation("Executing {Action} with name : {championName}", nameof(GetChampionsByName), name);
@ -140,23 +137,29 @@ namespace API_LoL_Project.Controllers
// GET api/<ChampionController>/name
[HttpGet("{name}")]
public async Task<ActionResult<LolResponce<ChampionFullDTO>>> GetChampionsByName(string name)
public async Task<ActionResult<LolResponse<ChampionFullDTO>>> GetChampionsByName(string name)
{
if (name == null || name == "")
{
var message = string.Format("Can not get champions without the name (is empty)");
_logger.LogWarning(message); ;
return BadRequest(message);
}
_logger.LogInformation("Executing {Action} with name : {championName}", nameof(GetChampionsByName), name);
try
{
var totalcount = await dataManager.GetNbItemsByName(name);
if (totalcount <= 0)
{
_logger.LogWarning("No chamions found with this name {name}", name); ;
return BadRequest("No chamions found with this name: " + name);
_logger.LogError("No chamions found with this name {name} in the dataContext", name); ;
return BadRequest("No chamions found with this name: " + name + "in the dataContext");
}
var champion = await dataManager.GetItemsByName(name, 0, totalcount);
/* IEnumerable<ChampionFullDTO> res = champion.Select(c => c.toFullDTO());//.First*/
if (champion.Count() <= 0 || champion == null)
{
_logger.LogWarning("No chamions found with {name}", name); ;
_logger.LogError($"No chamions found with {name} executing {nameof(GetChampionsByName)}"); ;
return NotFound("No chamions found with" + name);
}
ChampionFullDTO res = champion.First().toFullDTO();//.First
@ -169,7 +172,7 @@ namespace API_LoL_Project.Controllers
EndPointLink.To($"/api/[controller]/{res.Name}/", "self")
};
var response = new LolResponce<ChampionFullDTO>(res, links);
var response = new LolResponse<ChampionFullDTO>(res, links);
return Ok(response);
}
@ -183,12 +186,13 @@ namespace API_LoL_Project.Controllers
}
// POST api/<ChampionController>
// POST api/<Champ
[HttpPost]
public async Task<IActionResult> Post([FromBody] ChampionDTO value)
public async Task<IActionResult> Post([FromBody] ChampionFullDTO value)
{
try
{
// generic validation
var newChampion = value.ToModel();
await dataManager.AddItem(newChampion);
// can we check with a method
@ -225,6 +229,7 @@ namespace API_LoL_Project.Controllers
_logger.LogError("No chamions found with {name} in the dataBase", name); ;
return NotFound();
}
await dataManager.UpdateItem(champion.First(), value.ToModel());
return Ok();
}
@ -244,11 +249,12 @@ namespace API_LoL_Project.Controllers
_logger.LogInformation("Executing {Action} with name : {championName}", nameof(Delete), name);
var champion = await dataManager
.GetItemsByName(name, 0, await dataManager.GetNbItems());
if (champion != null) await dataManager.DeleteItem(champion.First());
else
{
_logger.LogWarning("No chamions found with {name}", name); ;
return NotFound();
_logger.LogError($"No chamions found with {name} cannot delete"); ;
return NotFound($"No chamions found with {name} cannot delete");
}
return Ok();
}
@ -321,11 +327,13 @@ namespace API_LoL_Project.Controllers
}
// degradation du modèle cleitn ell est dédié au cliens
[HttpGet("/count")]
// GET: api/champions/Count
[HttpGet("/count", Name = "GetChampionCount")]
public async Task<ActionResult<int>> NbChampions()
{
var nbChampions = await dataManager.GetNbItems();
return Ok(nbChampions);
return Ok(nbChampions);
}
}

@ -1,187 +1,189 @@
using DTO;
using Microsoft.AspNetCore.Mvc;
using Model;
using API_LoL_Project.Mapper;
using API_LoL_Project.Controllers.Response;
using API_LoL_Project.Middleware;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace API_LoL_Project.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class RuneController : ControllerBase
{
public IRunesManager dataManager;
// you should create a custom logger to be prety
private readonly ILogger<RuneController> _logger;
public RuneController(IDataManager dataManager, ILogger<RuneController> logger)
{
this.dataManager = dataManager.RunesMgr;
this._logger = logger;
}
// GET: api/<RuneController>
[HttpGet]
public async Task<ActionResult<IEnumerable<RuneDTO>>> GetAllRunes([FromQuery] Request.PageRequest request)
{
try
{
var totalcount = await dataManager.GetNbItems();
if (request.count * request.index >= totalcount)
{
_logger.LogError("To many object is asked the max is {totalcount} but the request is supérior of ", totalcount);
return BadRequest("To many object is asked the max is : " + totalcount);
}
_logger.LogInformation("Executing {Action} with parameters: {Parameters}", nameof(GetAllRunes), request); ;
var runes = await dataManager.GetItems(request.index, request.count, request.orderingPropertyName, (request.descending == null ? false : (bool)request.descending));
IEnumerable<RuneDTO> res = runes.Select(c => c.toDTO());
if (res.Count() <= 0 || res == null)
{
_logger.LogError("No runes found the total count is {totalcount} ", totalcount);
return BadRequest("No runes found : totalcount is : " + totalcount);
}
var respList = res.Select(r => new LolResponce<RuneDTO>
(
r,
new List<EndPointLink>
{
EndPointLink.To($"/api/[controller]/{r.Name}", "self"),
EndPointLink.To($"/api/[controller]/{r.Name}/{nameof(GetAllRunes)}", "self"),
EndPointLink.To($"/api/[controller]/{r.Name}/{nameof(GetAllRunes)}", "self"),
EndPointLink.To($"/api/[controller]/{r.Name}/{nameof(GetAllRunes)}", "self"),
EndPointLink.To($"/api/[controller]/{r.Name}/{nameof(GetAllRunes)}", "self","POST"),
EndPointLink.To($"/api/[controller]/{r.Name}/{nameof(Put)}", "self","PUT"),
}
));
var pageResponse = new PageResponse<RuneDTO>(respList, request.index, request.count, totalcount);
return Ok(pageResponse);
}
catch (Exception e)
{
_logger.LogError("Somthing goes wrong caching the Rune controller : " + e.Message);
return BadRequest(e.Message);
}
}
// GET: api/<RuneController>
/* [HttpGet]
public async Task<ActionResult<IEnumerable<RuneDTO>>> Get([FromQuery] Request.PageRequest request)
{
try
{
var totalcount = await runesManager.GetNbItems();
if (request.count + request.index > totalcount)
{
_logger.LogWarning("to many rows ask the max is {totalcount}", totalcount);
return BadRequest("to many rows ask the max is " + totalcount);
}
_logger.LogInformation("Executing {Action} with parameters: {Parameters}", nameof(Get), request);
var runes = await runesManager.GetItems(request.PageNumber, totalcount, request.orderingPropertyName, (request.descending == null ? false : (bool)request.descending));
IEnumerable<RuneDTO> res = runes.Select(c => c.toDTO());
if (res.Count() >= 0 || res == null)
{
_logger.LogWarning("No runes found with Id");
return BadRequest("No runes found with Id ");
}
return Ok(res);
}
catch (Exception e)
{
_logger.LogError("About get at {e.message}", DateTime.UtcNow.ToLongTimeString());
return BadRequest(e.Message);
}
}
*/
[HttpGet("{name}")]
public async Task<ActionResult<LolResponce<RuneDTO>>> GetRuneByName(string name)
{
try
{
var rune = await dataManager
.GetItemsByName(name, 0, await dataManager.GetNbItems());
_logger.LogInformation("Executing {Action} with name : {runeName}", nameof(GetRuneByName), name);
RuneDTO res = rune.First().toDTO();
if (res == null)
{
_logger.LogWarning("No runes found with {name}", name); ;
return NotFound();
}
var links = new List<EndPointLink>
{
EndPointLink.To($"/api/[controller]/{res.Name}", "self"),
EndPointLink.To($"/api/[controller]/{res.Name}/", "self"),
EndPointLink.To($"/api/[controller]/{res.Name}/", "self")
};
var response = new LolResponce<RuneDTO>(res, links);
return Ok(response);
}
catch (Exception e)
{
_logger.LogError("Somthing goes wrong caching the Champions controller : " + e.Message);
return BadRequest(e.Message);
}
}
/* // GET api/<RuneController>/5
[HttpGet("{id}")]
public string Get(int id)
{
try
{
var rune = await dataManager
.GetItemsByName(name, 0, await dataManager.GetNbItems());
RuneDto result = champion.First().toDTO();
return Ok(result);
}
catch (Exeption e)
{
new HttpException(400, 'Cannot get rune :' + e.message);
}
}*/
// POST api/<RuneController>
// PUT api/<RuneController>/5
[HttpPut("{id}")]
public void Put(int id, [FromBody] string value)
{
}
// DELETE api/<RuneController>/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
}
using DTO;
using Microsoft.AspNetCore.Mvc;
using Model;
using API_LoL_Project.Controllers.Response;
using API_LoL_Project.Middleware;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace API_LoL_Project.Controllers.version1
{
[Route("api/v{version:apiVersion}/[controller]")]
[ApiVersion("1.0")]
[ApiController]
public class RuneController : ControllerBase
{
public IRunesManager dataManager;
// you should create a custom logger to be prety
private readonly ILogger<RuneController> _logger;
public RuneController(IDataManager dataManager, ILogger<RuneController> logger)
{
this.dataManager = dataManager.RunesMgr;
_logger = logger;
}
/*// GET: api/<RuneController>
[HttpGet]
public async Task<ActionResult<IEnumerable<RuneDTO>>> GetAllRunes([FromQuery] Request.PageRequest request)
{
try
{
var totalcount = await dataManager.GetNbItems();
if (request.count * request.index >= totalcount)
{
_logger.LogError("To many object is asked the max is {totalcount} but the request is supérior of ", totalcount);
return BadRequest("To many object is asked the max is : " + totalcount);
}
_logger.LogInformation("Executing {Action} with parameters: {Parameters}", nameof(GetAllRunes), request); ;
var runes = await dataManager.GetItems(request.index, request.count, request.orderingPropertyName, (request.descending == null ? false : (bool)request.descending));
IEnumerable<RuneDTO> res = runes.Select(c => c.toDTO());
if (res.Count() <= 0 || res == null)
{
_logger.LogError("No runes found the total count is {totalcount} ", totalcount);
return BadRequest("No runes found : totalcount is : " + totalcount);
}
var respList = res.Select(r => new LolResponce<RuneDTO>
(
r,
new List<EndPointLink>
{
EndPointLink.To($"/api/[controller]/{r.Name}", "self"),
EndPointLink.To($"/api/[controller]/{r.Name}/{nameof(GetAllRunes)}", "self"),
EndPointLink.To($"/api/[controller]/{r.Name}/{nameof(GetAllRunes)}", "self"),
EndPointLink.To($"/api/[controller]/{r.Name}/{nameof(GetAllRunes)}", "self"),
EndPointLink.To($"/api/[controller]/{r.Name}/{nameof(GetAllRunes)}", "self","POST"),
EndPointLink.To($"/api/[controller]/{r.Name}/{nameof(Put)}", "self","PUT"),
}
));
var pageResponse = new PageResponse<RuneDTO>(respList, request.index, request.count, totalcount);
return Ok(pageResponse);
}
catch (Exception e)
{
_logger.LogError("Somthing goes wrong caching the Rune controller : " + e.Message);
return BadRequest(e.Message);
}
}
*/
// GET: api/<RuneController>
/* [HttpGet]
public async Task<ActionResult<IEnumerable<RuneDTO>>> Get([FromQuery] Request.PageRequest request)
{
try
{
var totalcount = await runesManager.GetNbItems();
if (request.count + request.index > totalcount)
{
_logger.LogWarning("to many rows ask the max is {totalcount}", totalcount);
return BadRequest("to many rows ask the max is " + totalcount);
}
_logger.LogInformation("Executing {Action} with parameters: {Parameters}", nameof(Get), request);
var runes = await runesManager.GetItems(request.PageNumber, totalcount, request.orderingPropertyName, (request.descending == null ? false : (bool)request.descending));
IEnumerable<RuneDTO> res = runes.Select(c => c.toDTO());
if (res.Count() >= 0 || res == null)
{
_logger.LogWarning("No runes found with Id");
return BadRequest("No runes found with Id ");
}
return Ok(res);
}
catch (Exception e)
{
_logger.LogError("About get at {e.message}", DateTime.UtcNow.ToLongTimeString());
return BadRequest(e.Message);
}
}
*/
/*
[HttpGet("{name}")]
public async Task<ActionResult<LolResponce<RuneDTO>>> GetRuneByName(string name)
{
try
{
var rune = await dataManager
.GetItemsByName(name, 0, await dataManager.GetNbItems());
_logger.LogInformation("Executing {Action} with name : {runeName}", nameof(GetRuneByName), name);
RuneDTO res = rune.First().toDTO();
if (res == null)
{
_logger.LogWarning("No runes found with {name}", name); ;
return NotFound();
}
var links = new List<EndPointLink>
{
EndPointLink.To($"/api/[controller]/{res.Name}", "self"),
EndPointLink.To($"/api/[controller]/{res.Name}/", "self"),
EndPointLink.To($"/api/[controller]/{res.Name}/", "self")
};
var response = new LolResponce<RuneDTO>(res, links);
return Ok(response);
}
catch (Exception e)
{
_logger.LogError("Somthing goes wrong caching the Champions controller : " + e.Message);
return BadRequest(e.Message);
}
}*/
/* // GET api/<RuneController>/5
[HttpGet("{id}")]
public string Get(int id)
{
try
{
var rune = await dataManager
.GetItemsByName(name, 0, await dataManager.GetNbItems());
RuneDto result = champion.First().toDTO();
return Ok(result);
}
catch (Exeption e)
{
new HttpException(400, 'Cannot get rune :' + e.message);
}
}*/
// POST api/<RuneController>
// PUT api/<RuneController>/5
[HttpPut("{id}")]
public void Put(int id, [FromBody] string value)
{
}
// DELETE api/<RuneController>/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
}

@ -0,0 +1,219 @@
using API_LoL_Project.Controllers.Response;
using API_LoL_Project.Middleware;
using DTO;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Hosting;
using Model;
using ApiMappeur;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace API_LoL_Project.Controllers.version1
{
[Route("api/v{version:apiVersion}/[controller]")]
[ApiVersion("1.0")]
[ApiController]
public class RunePageController : ControllerBase
{
private IRunePagesManager dataManager;
private readonly ILogger<RunePageController> _logger;
public RunePageController(IDataManager dataManager, ILogger<RunePageController> logger)
{
this.dataManager = dataManager.RunePagesMgr;
_logger = logger;
}
// GET: api/v1/<RunePageController>
[HttpGet]
public async Task<ActionResult<PageResponse<RunePageDTO>>> Get([FromQuery] Request.PageRequest request)
{
try
{
var totalcount = await dataManager.GetNbItems();
if (request.count * request.index >= totalcount)
{
_logger.LogError("To many object is asked the max is {totalcount} but the request is superior of ", totalcount);
return BadRequest("To many object is asked the max is : " + totalcount);
}
_logger.LogInformation("Executing {Action} with parameters: {Parameters}", nameof(Get), request);
var runesP = await dataManager.GetItems(request.index, request.count == 0 ? totalcount : request.count, request.orderingPropertyName, request.descending == null ? false : (bool)request.descending);
IEnumerable<RunePageDTO> res = runesP.Select(c => c.ToDto());
if (res.Count() <= 0 || res == null)
{
_logger.LogError("No RunePage found the total count is {totalcount} ", totalcount);
return BadRequest("No RunePage found : totalcount is : " + totalcount);
}
var respList = res.Select(r => new LolResponse<RunePageDTO>
(
r,
new List<EndPointLink>
{
EndPointLink.To($"/api/[controller]/{r.Name}/{nameof(GetRunePageByName)}", "self"),
EndPointLink.To($"/api/[controller]/{r.Name}/{nameof(Post)}", "self","POST"),
EndPointLink.To($"/api/[controller]/{r.Name}/{nameof(Put)}", "self","PUT"),
}
));
var pageResponse = new PageResponse<RunePageDTO>(respList, request.index, request.count, totalcount);
return Ok(pageResponse);
}
catch (Exception e)
{
_logger.LogError("Somthing goes wrong caching the RunePage controller : " + e.Message);
return BadRequest(e.Message);
}
}
[HttpGet("{name}")]
public async Task<ActionResult<IEnumerable<LolResponse<RunePageDTO>>>> GetRunePageByName(string name)
{
if (name == null || name == "")
{
var message = string.Format("Can not get Rune PAge without the name (is empty)");
_logger.LogWarning(message); ;
return BadRequest(message);
}
_logger.LogInformation("Executing {Action} with name : {runePageName}", nameof(GetRunePageByName), name);
try
{
var totalcount = await dataManager.GetNbItemsByName(name);
if (totalcount <= 0)
{
_logger.LogError("No chamions found with this name {name} in the dataContext", name); ;
return NotFound("No chamions found with this name: " + name + "in the dataContext");
}
var champion = await dataManager.GetItemsByName(name, 0, totalcount);
_logger.LogInformation($"========================= {champion} ================================================"); ;
if (champion.Count() <= 0 || champion == null)
{
_logger.LogError($"No chamions found with {name} executing {nameof(GetRunePageByName)}"); ;
return NotFound("No chamions found with" + name);
}
IEnumerable<RunePageDTO> res = champion.Select(c => c.ToDto());
/*ChampionFullDTO res = champion.First().toFullDTO();//.First*/
var respList = res.Select(r => new LolResponse<RunePageDTO>
(
r,
new List<EndPointLink>
{
EndPointLink.To($"/api/[controller]/{r.Name}/{nameof(GetRunePageByName)}", "self"),
EndPointLink.To($"/api/[controller]/{r.Name}/{nameof(Post)}", "self","POST"),
EndPointLink.To($"/api/[controller]/{r.Name}/{nameof(Put)}", "self","PUT"),
}
));
return Ok(respList);
}
catch (Exception e)
{
_logger.LogError("Somthing goes wrong caching the RunePage controller : " + e.Message);
return BadRequest("Somthing goes wrong caching the RunePage controller : " + e.Message);
}
}
[HttpPost]
public async Task<IActionResult> Post([FromBody] RunePageDTO runePage)
{
_logger.LogInformation("method {Action} - RUNEPAGE call with {item}", nameof(Post), runePage);
try
{
if (await dataManager.GetNbItemsByName(runePage.Name) == 0)
{
return CreatedAtAction(nameof(Get),
(await dataManager.AddItem(runePage.ToModel())).ToDto());
}
_logger.LogWarning($"Name : {runePage.Name} is already exist");
return BadRequest($"Name : {runePage.Name} is already exist");
}
catch (Exception error)
{
_logger.LogError(error.Message);
return BadRequest(error.Message);
}
}
[HttpPut("{name}")]
public async Task<IActionResult> Put(string name, [FromBody] RunePageDTO value)
{
try
{
_logger.LogInformation("Executing {Action} with name : {championName}", nameof(Put), name);
var champion = await dataManager
.GetItemsByName(name, 0, await dataManager.GetNbItems());
if (champion == null)
{
_logger.LogError("No chamions found with {name} in the dataBase", name); ;
return NotFound();
}
var savedUpdatedRunePage = await dataManager.UpdateItem(champion.First(), value.ToModel());
if (savedUpdatedRunePage == null)
{
_logger.LogWarning("The updated RunePage not returned {name}", name); ;
return BadRequest();
}
return Ok(savedUpdatedRunePage);
}
catch (Exception e)
{
_logger.LogError("Somthing goes wrong caching the RunePage controller : " + e.Message);
return BadRequest(e.Message);
}
}
[HttpDelete("{name}")]
public async Task<IActionResult> Delete(string name)
{
_logger.LogInformation("method {Action} - RUNEPAGE call with {name}", nameof(Delete), name);
try
{
var dtos = await dataManager.GetItemsByName(name, 0, await dataManager.GetNbItems());
if (dtos == null)
{
_logger.LogWarning("{name} was not found", name);
return NotFound($"{name} was not found");
}
await dataManager.DeleteItem(dtos.First());
return NoContent();
}
catch (Exception error)
{
_logger.LogError(error.Message);
return BadRequest(error.Message);
}
}
// GET: api/<RunePageController>/count
[HttpGet("/countRunePage", Name = "GetRunePageCount")]
public async Task<ActionResult<int>> NbRunePage()
{
_logger.LogInformation("method {Action} - RUNEPAGE call", nameof(NbRunePage));
try
{
var nbRunePage = await dataManager.GetNbItems();
return Ok(nbRunePage);
}
catch (Exception error)
{
_logger.LogError(error.Message);
return BadRequest(error.Message);
}
}
}
}

@ -0,0 +1,519 @@
using API_LoL_Project.Controllers.Response;
using API_LoL_Project.Middleware;
using DTO;
using Microsoft.AspNetCore.Mvc;
using Model;
using StubLib;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Xml.Linq;
using ApiMappeur;
using Shared;
using Microsoft.OpenApi.Extensions;
namespace API_LoL_Project.Controllers.version2
{
[Route("api/v{version:apiVersion}/[controller]")]
[ApiVersion("2.0")]
[ApiController]
public class ChampionsController : ControllerBase
{
public IChampionsManager dataManager;
private readonly ILogger<ChampionsController> _logger;
public ChampionsController(IDataManager dataManager, ILogger<ChampionsController> logger)
{
this.dataManager = dataManager.ChampionsMgr;
_logger = logger;
}
// GET: api/champions/
[HttpGet]
public async Task<ActionResult<PageResponse<ChampionDTO>>> Get([FromQuery] Request.PageRequest request)
{
try
{
var totalcount = await dataManager.GetNbItems();
if (request.count * request.index >= totalcount)
{
_logger.LogError("To many object is asked the max is {totalcount} but the request is superior of ", totalcount);
return BadRequest("To many object is asked the max is : " + totalcount);
}
_logger.LogInformation("Executing {Action} with parameters: {Parameters}", nameof(Get), request);
var champions = await dataManager.GetItems(request.index, request.count == 0 ? totalcount : (int)request.count , request.orderingPropertyName, request.descending == null ? false : (bool)request.descending);
IEnumerable<ChampionDTO> res = champions.Select(c => c.ToDTO());
if (res.Count() <= 0 || res == null)
{
_logger.LogError("No champions found the total count is {totalcount} ", totalcount);
return BadRequest("No champions found : totalcount is : " + totalcount);
}
var respList = res.Select(r => new LolResponse<ChampionDTO>
(
r,
new List<EndPointLink>
{
EndPointLink.To($"/api/[controller]/{r.Name}/{nameof(GetChampionsImage)}", "self"),
EndPointLink.To($"/api/[controller]/{r.Name}/{nameof(GetChampionsByName)}", "self"),
EndPointLink.To($"/api/[controller]/{r.Name}/{nameof(Post)}", "self","POST"),
EndPointLink.To($"/api/[controller]/{r.Name}/{nameof(Put)}", "self","PUT"),
}
));
var pageResponse = new PageResponse<ChampionDTO>(respList, request.index, request.count, totalcount);
return Ok(pageResponse);
}
catch (Exception e)
{
_logger.LogError("Somthing goes wrong caching the Champions controller : " + e.Message);
return BadRequest(e.Message);
}
}
/*// GET api/<ChampionController>/5
[HttpGet("{id}")]
public async Task<ActionResult<IEnumerable<ChampionFullDTO>>> GetChampionsById(int name)
{
try
{
var champion = await dataManager
.GetItemsByName(name, 0, await dataManager.GetNbItems());
_logger.LogInformation("Executing {Action} with name : {championName}", nameof(GetChampionsByName), name);
IEnumerable<ChampionFullDTO> res = champion.Select(c => c.toFullDTO());
if (res == null)
{
_logger.LogWarning("No chamions found with {name}", name); ;
return NotFound();
}
return Ok(res);
}
catch (Exception e)
{
return BadRequest(e.Message);
}
}*/
// GET: api/champions/image
[HttpGet("image/{name}")]
public async Task<ActionResult<ImageDTO>> GetChampionsImage(string name)
{
try
{
if (name == null || name == "")
{
var message = string.Format("Can not get champions image without the name (is empty)");
_logger.LogWarning(message + nameof(ChampionsController)); ;
return BadRequest(message);
}
var champion = await dataManager
.GetItemsByName(name, 0, await dataManager.GetNbItems());
_logger.LogInformation("Executing {Action} with name : {championName}", nameof(GetChampionsByName), name);
/* IEnumerable<ChampionFullDTO> res = champion.Select(c => c.toFullDTO());//.First*/
ChampionFullDTO res = champion.First().toFullDTO();//.First
if (res == null)
{
_logger.LogWarning("No chamions found with {name}", name); ;
return NotFound();
}
return Ok(res.LargeImage);
}
catch (Exception e)
{
return BadRequest(e.Message);
}
}
// GET api/champions/name
[HttpGet("{name}")]
public async Task<ActionResult<IEnumerable<LolResponse<ChampionFullDTO>>>> GetChampionsByName(string name)
{
if (name == null || name == "")
{
var message = string.Format("Can not get champions without the name (is empty)");
_logger.LogWarning(message); ;
return BadRequest(message);
}
_logger.LogInformation("Executing {Action} with name : {championName}", nameof(GetChampionsByName), name);
try
{
var totalcount = await dataManager.GetNbItemsByName(name);
if (totalcount <= 0)
{
_logger.LogError("No chamions found with this name {name} in the dataContext", name); ;
return NotFound("No chamions found with this name: " + name + "in the dataContext");
}
var champion = await dataManager.GetItemsByName(name, 0, totalcount);
_logger.LogInformation($"========================= {champion} ================================================"); ;
if (champion.Count() <= 0 || champion == null)
{
_logger.LogError($"No chamions found with {name} executing {nameof(GetChampionsByName)}"); ;
return NotFound("No chamions found with" + name);
}
IEnumerable<ChampionFullDTO> res = champion.Select(c => c.toFullDTO());
/*ChampionFullDTO res = champion.First().toFullDTO();//.First*/
var respList = res.Select(r => new LolResponse<ChampionFullDTO>
(
r,
new List<EndPointLink>
{
EndPointLink.To($"/api/[controller]/{r.Name}", "self"),
EndPointLink.To($"/api/[controller]/{r.Name}", "self"),
EndPointLink.To($"/api/[controller]/{r.Name}", "self","POST"),
EndPointLink.To($"/api/[controller]/{r.Name}", "self","PUT"),
EndPointLink.To($"/api/[controller]/{r.Name}/characteristic", "self"),
EndPointLink.To($"/api/[controller]/{r.Name}/characteristic", "self"),
}
));
return Ok(respList);
}
catch (Exception e)
{
_logger.LogError("Somthing goes wrong caching the Champions controller : " + e.Message);
return BadRequest("Somthing goes wrong caching the Champions controller : " + e.Message);
}
}
// POST api/champions/names
// it should be better if we get a Champions From the Model but cause the Client (MAUI one) Send Champion there is no interest to be a championDTo
/* [HttpPost]
public async Task<IActionResult> Post([FromBody] Champion value)
{
try
{
if (value == null)
{
var message = string.Format("Can not get champions image without the name (is empty)");
_logger.LogWarning(message); ;
return BadRequest(message);
}
// generic validation check if all field is good
await dataManager.AddItem(value);
// can we check with a method
//var savedChampions = await dataManager.GetItemsByName(newChampion.name, 0, await dataManager.GetNbItems())
*//*if (savedChampions.Count() >= 0 || res == null)
{
_logger.LogWarning("No chamions found ");
return BadRequest("No chamions found ");
}*//*
_logger.LogInformation("Sucessfully saved Champions : " + value.Name);
return CreatedAtAction(nameof(Get), value.ToDTO());
}
catch (Exception e)
{
_logger.LogError("Somthing goes wrong caching the Champions controller : " + e.Message);
return BadRequest(e.Message);
}
}
*/
[HttpPost]
public async Task<IActionResult> Post([FromBody] ChampionFullDTO value)
{
try
{
if (value == null)
{
var message = string.Format("Can not get champions image without the name (is empty)");
_logger.LogWarning(message); ;
return BadRequest(message);
}
/*
* cannot use this GetNbItemsByName and GetItemsByName use Contains and not equals
* var totalcount = await dataManager.GetNbItemsByName(value.Name);
if (totalcount >= 0)
{
_logger.LogError("champions found with this name {name} in the dataContext | cannot add an champions with the same Name", value.Name); ;
return BadRequest("chamions this name: " + value.Name + " already exist in the dataContext champions need to have unique name");
}*/
// generic validation check if all field is good
var newChampion = value.ToModel();
await dataManager.AddItem(newChampion);
// can we check with a method
var savedChampions = await dataManager.GetItemsByName(newChampion.Name, 0, await dataManager.GetNbItems());
if (savedChampions.Count() <= 0 || savedChampions == null)
{
_logger.LogWarning("No chamions found ");
return BadRequest("No chamions found ");
}
_logger.LogInformation("Sucessfully saved Champions : " + newChampion.Name);
return CreatedAtAction(nameof(Get), newChampion.ToDTO());
}
catch (Exception e)
{
_logger.LogError("Somthing goes wrong caching the Champions controller : " + e.Message);
return BadRequest(e.Message + e.InnerException);
}
}
// should change for id cause model implementation use filteringbyName to getItemByNAme and it use substring
// PUT api/<ChampionController>/5
[HttpPut("{name}")]
// should be champions full Dto
public async Task<IActionResult> Put(string name, [FromBody] ChampionDTO value)
{
try
{
_logger.LogInformation("Executing {Action} with name : {championName}", nameof(Put), name);
var champion = await dataManager
.GetItemsByName(name, 0, await dataManager.GetNbItems());
if (champion == null)
{
_logger.LogError("No chamions found with {name} in the dataBase", name); ;
return NotFound();
}
var savedUpdatedChampions = await dataManager.UpdateItem(champion.First(), value.ToModel());
if(savedUpdatedChampions == null)
{
_logger.LogWarning("The updated champions not returned {name}", name); ;
return BadRequest();
}
return Ok(savedUpdatedChampions);
}
catch (Exception e)
{
_logger.LogError("Somthing goes wrong caching the Champions controller : " + e.Message);
return BadRequest(e.Message);
}
}
// DELETE api/<ChampionController>/5
[HttpDelete("{name}")]
public async Task<IActionResult> Delete(string name)
{
try
{
_logger.LogInformation("Executing {Action} with name : {championName}", nameof(Delete), name);
if (string.IsNullOrEmpty(name))
{
var message = string.Format("Can not delelte champions without the name (is empty)");
_logger.LogWarning(message + nameof(ChampionsController)); ;
return BadRequest(message);
}
var totalcount = await dataManager.GetNbItemsByName(name);
if (totalcount <= 0)
{
_logger.LogError("No chamions found with this name {name} in the dataContext cannot delete", name);
return NotFound($"No chamions found with {name} cannot delete");
}
var champion = await dataManager
.GetItemsByName(name, 0, await dataManager.GetNbItems());
if (champion != null) await dataManager.DeleteItem(champion.First());
else
{
_logger.LogError($"No chamions found with {name} cannot delete"); ;
return NotFound($"No chamions found with {name} cannot delete");
}
return Ok();
}
catch (Exception e)
{
_logger.LogError("Somthing goes wrong caching the Champions controller : " + e.Message);
return BadRequest(e.Message);
}
}
/* [HttpGet]
public async Task<IActionResult> NbChampions()
{
var champions = await dataManager.GetItems(0, await dataManager.GetNbItems());
IEnumerable<ChampionDTO> res = champions.Select(c => c.toDTO());
return Ok(res);
}*/
[HttpGet("/{name}/skins")]
public async Task<ActionResult<SkinDto>> GetChampionsSkins(string name)
{
_logger.LogInformation("Executing {Action} with name : {championName}", nameof(GetChampionsSkins), name);
var champions = await dataManager.GetItemsByName(name, 0, await dataManager.GetNbItems());
if (champions == null)
{
_logger.LogWarning("No chamions found with {name}", name); ;
return NotFound();
}
//skinsDTO
IEnumerable<SkinDto> res = champions.First().Skins.Select(c => c.ToDto());
if (res == null)
{
_logger.LogWarning("No skins found for {name}", name); ;
return NotFound();
}
return Ok(res);
}
/* [HttpGet("/{name}/skills")]
public async Task<ActionResult<SkillDto>> GetChampionsSkills(string name)
{
_logger.LogInformation("Executing {Action} with name : {championName}", nameof(GetChampionsSkills), name);
var champions = await dataManager.GetItemsByName(name, 0, await dataManager.GetNbItems());
if (champions == null)
{
_logger.LogWarning("No chamions found with {name}", name); ;
return NotFound();
}
//skinsDTO
IEnumerable<SkillDto> res = champions.First().Skills.to;
if (res == null)
{
_logger.LogWarning("No skins found for {name}", name); ;
return NotFound();
}
return Ok(res);
}*/
[HttpPost("/{name}/skills")]
public async Task<ActionResult<IEnumerable<SkinDto>>> AddChampionsSkills(string name)
{
var champions = await dataManager.GetItemsByName(name, 0, await dataManager.GetNbItems());
//SkillDTO
IEnumerable<Skill> res = champions.First().Skills;
return Ok(res);
}
// degradation du modèle cleitn ell est dédié au client
// GET: api/champions/Count
[HttpGet("/count", Name = "GetChampionCount")]
public async Task<ActionResult<int>> NbChampions()
{
_logger.LogInformation("method {Action} - RUNEPAGE call", nameof(NbChampions));
try
{
var nbChampions = await dataManager.GetNbItems();
return Ok(nbChampions);
}
catch (Exception error)
{
_logger.LogError(error.Message);
return BadRequest(error.Message);
}
}
[HttpGet("count/class/{championClass}")]
public async Task<ActionResult<int>> GetChampionCountByClass(ChampionClass championClass)
{
try
{
_logger.LogInformation("Executing {Action} with parameters: {Parameters}", nameof(GetChampionCountByClass), championClass.GetDisplayName());
var count = await dataManager.GetNbItemsByClass(championClass);
return Ok(count);
}
catch (Exception e)
{
_logger.LogError("Something went wrong while fetching the count of champions by class in the controller: " + e.Message);
return BadRequest(e.Message);
}
}
[HttpGet("count/name/{substring}")]
public async Task<ActionResult<int>> GetNbItemsByName(string substring)
{
try
{
_logger.LogInformation("Executing {Action} with parameters: {Substring}", nameof(GetNbItemsByName), substring);
var count = await dataManager.GetNbItemsByName(substring);
return Ok(count);
}
catch (Exception e)
{
_logger.LogError("Something went wrong in {Action} action: {ErrorMessage}", nameof(GetNbItemsByName), e.Message);
return BadRequest(e.Message);
}
}
[HttpGet("characteristic/{characteristic}")]
public async Task<ActionResult<PageResponse<ChampionDTO>>> GetChampionByCharacteristic(string characteristic, [FromQuery] Request.PageRequest request)
{
try
{
_logger.LogInformation("Executing {Action} with parameters: {Parameters} ", nameof(GetChampionByCharacteristic), characteristic + " / " + request);
var champions = await dataManager.GetItemsByCharacteristic(characteristic, request.index, request.count == 0 ? await dataManager.GetNbItems() : (int)request.count, request.orderingPropertyName, request.descending == null ? false : (bool)request.descending);
IEnumerable<ChampionDTO> res = champions.Select(c => c.ToDTO());
if (res.Count() <= 0 || res == null)
{
_logger.LogError("No champions found for characteristic {Characteristic}", characteristic);
return BadRequest("No champions found for characteristic : " + characteristic);
}
var respList = res.Select(r => new LolResponse<ChampionDTO>
(
r,
new List<EndPointLink>
{
EndPointLink.To($"/api/[controller]/{r.Name}/{nameof(GetChampionsImage)}", "self"),
EndPointLink.To($"/api/[controller]/{r.Name}/{nameof(GetChampionsByName)}", "self"),
EndPointLink.To($"/api/[controller]/{r.Name}/{nameof(Post)}", "self","POST"),
EndPointLink.To($"/api/[controller]/{r.Name}/{nameof(Put)}", "self","PUT"),
}
));
var totalcount = await dataManager.GetNbItemsByCharacteristic(characteristic);
var pageResponse = new PageResponse<ChampionDTO>(respList, request.index, request.count, totalcount);
return Ok(pageResponse);
}
catch (Exception e)
{
_logger.LogError("Somthing goes wrong caching the Champions controller : " + e.Message);
return BadRequest(e.Message);
}
}
}
}

@ -0,0 +1,155 @@
using DTO;
using Microsoft.AspNetCore.Mvc;
using Model;
using API_LoL_Project.Controllers.Response;
using API_LoL_Project.Middleware;
using ApiMappeur;
using API_LoL_Project.Controllers.Response;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace API_LoL_Project.Controllers.version2
{
[Route("api/v{version:apiVersion}/[controller]")]
[ApiVersion("2.0")]
[ApiController]
public class RuneController : ControllerBase
{
public IRunesManager dataManager;
// you should create a custom logger to be prety
private readonly ILogger<RuneController> _logger;
public RuneController(IDataManager dataManager, ILogger<RuneController> logger)
{
this.dataManager = dataManager.RunesMgr;
_logger = logger;
}
// GET: api/rune
[HttpGet("/all")]
public async Task<ActionResult<IEnumerable<RuneDTO>>> GetAllRunes([FromQuery] Request.PageRequest request)
{
try
{
var totalcount = await dataManager.GetNbItems();
if (request.count * request.index >= totalcount)
{
_logger.LogError("To many object is asked the max is {totalcount} but the request is supérior of ", totalcount);
return BadRequest("To many object is asked the max is : " + totalcount);
}
_logger.LogInformation("Executing {Action} with parameters: {Parameters}", nameof(GetAllRunes), request); ;
var runes = await dataManager.GetItems(request.index, request.count, request.orderingPropertyName, (request.descending == null ? false : (bool)request.descending));
IEnumerable<RuneDTO> res = runes.Select(c => c.ToDTO());
if (res.Count() <= 0 || res == null)
{
_logger.LogError("No runes found the total count is {totalcount} ", totalcount);
return BadRequest("No runes found : totalcount is : " + totalcount);
}
var respList = res.Select(r => new LolResponse<RuneDTO>
(
r,
new List<EndPointLink>
{
EndPointLink.To($"/api/[controller]/{r.Name}", "self"),
EndPointLink.To($"/api/[controller]/{r.Name}/{nameof(GetAllRunes)}", "self"),
EndPointLink.To($"/api/[controller]/{r.Name}/{nameof(GetAllRunes)}", "self"),
EndPointLink.To($"/api/[controller]/{r.Name}/{nameof(GetAllRunes)}", "self"),
EndPointLink.To($"/api/[controller]/{r.Name}/{nameof(GetAllRunes)}", "self","POST"),
}
));
var pageResponse = new PageResponse<RuneDTO>(respList, request.index, request.count, totalcount);
return Ok(pageResponse);
}
catch (Exception e)
{
_logger.LogError("Somthing goes wrong caching the Rune controller : " + e.Message);
return BadRequest(e.Message);
}
}
// GET: api/<RuneController>
[HttpGet]
public async Task<ActionResult<IEnumerable<RuneDTO>>> Get([FromQuery] Request.PageRequest request)
{
try
{
var totalcount = await dataManager.GetNbItems();
if (request.count + request.index > totalcount)
{
_logger.LogWarning("to many rows ask the max is {totalcount}", totalcount);
return BadRequest("to many rows ask the max is " + totalcount);
}
_logger.LogInformation("Executing {Action} with parameters: {Parameters}", nameof(Get), request);
var runes = await dataManager.GetItems(request.index, totalcount, request.orderingPropertyName, (request.descending == null ? false : (bool)request.descending));
IEnumerable<RuneDTO> res = runes.Select(c => c.ToDTO());
if (res == null)
{
_logger.LogWarning("No runes found with Id");
return BadRequest("No runes found with Id ");
}
return Ok(res);
}
catch (Exception e)
{
_logger.LogError("About get at {e.message}", DateTime.UtcNow.ToLongTimeString());
return BadRequest(e.Message);
}
}
[HttpGet("{name}")]
public async Task<ActionResult<LolResponse<RuneDTO>>> GetRuneByName(string name)
{
try
{
var rune = await dataManager
.GetItemsByName(name, 0, await dataManager.GetNbItems());
_logger.LogInformation("Executing {Action} with name : {runeName}", nameof(GetRuneByName), name);
RuneDTO res = rune.First().ToDTO();
if (res == null)
{
_logger.LogWarning("No runes found with {name}", name); ;
return NotFound();
}
var links = new List<EndPointLink>
{
EndPointLink.To($"/api/[controller]/{res.Name}", "self"),
EndPointLink.To($"/api/[controller]/{res.Name}/", "self"),
EndPointLink.To($"/api/[controller]/{res.Name}/", "self")
};
var response = new LolResponse<RuneDTO>(res, links);
return Ok(response);
}
catch (Exception e)
{
_logger.LogError("Somthing goes wrong catching bt the Runnes controller : " + e.Message);
return BadRequest(e.Message);
}
}
}
}

@ -0,0 +1,219 @@
using API_LoL_Project.Controllers.Response;
using API_LoL_Project.Middleware;
using DTO;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Hosting;
using Model;
using ApiMappeur;
using API_LoL_Project.Middleware.Auth;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace API_LoL_Project.Controllers.version2
{
[Route("api/v{version:apiVersion}/[controller]")]
[ApiVersion("2.0")]
[ServiceFilter(typeof(AuthMiddlewareFliter))]
[ApiController]
public class RunePageController : ControllerBase
{
private IRunePagesManager dataManager;
private readonly ILogger<RunePageController> _logger;
public RunePageController(IDataManager dataManager, ILogger<RunePageController> logger)
{
this.dataManager = dataManager.RunePagesMgr;
_logger = logger;
}
// GET: api/runePage
[HttpGet]
public async Task<ActionResult<PageResponse<RunePageDTO>>> Get([FromQuery] Request.PageRequest request)
{
try
{
var totalcount = await dataManager.GetNbItems();
if (request.count * request.index >= totalcount)
{
_logger.LogError("To many object is asked the max is {totalcount} but the request is superior of ", totalcount);
return BadRequest("To many object is asked the max is : " + totalcount);
}
_logger.LogInformation("Executing {Action} with parameters: {Parameters}", nameof(Get), request);
var runesP = await dataManager.GetItems(request.index, request.count == 0 ? totalcount : request.count, request.orderingPropertyName, request.descending == null ? false : (bool)request.descending);
IEnumerable<RunePageDTO> res = runesP.Select(c => c.ToDto());
if (res.Count() <= 0 || res == null)
{
_logger.LogError("No RunePage found the total count is {totalcount} ", totalcount);
return BadRequest("No RunePage found : totalcount is : " + totalcount);
}
var respList = res.Select(r => new LolResponse<RunePageDTO>
(
r,
new List<EndPointLink>
{
EndPointLink.To($"/api/[controller]/{r.Name}/{nameof(GetRunePageByName)}", "self"),
EndPointLink.To($"/api/[controller]/{r.Name}/{nameof(Post)}", "self","POST"),
EndPointLink.To($"/api/[controller]/{r.Name}/{nameof(Put)}", "self","PUT"),
}
));
var pageResponse = new PageResponse<RunePageDTO>(respList, request.index, request.count, totalcount);
return Ok(pageResponse);
}
catch (Exception e)
{
_logger.LogError("Somthing goes wrong caching the RunePage controller : " + e.Message);
return BadRequest(e.Message);
}
}
// GET: api/<RunePageController>
[HttpGet("{name}")]
public async Task<ActionResult<IEnumerable<LolResponse<RunePageDTO>>>> GetRunePageByName(string name)
{
if (name == null || name == "")
{
var message = string.Format("Can not get Rune PAge without the name (is empty)");
_logger.LogWarning(message); ;
return BadRequest(message);
}
_logger.LogInformation("Executing {Action} with name : {runePageName}", nameof(GetRunePageByName), name);
try
{
var totalcount = await dataManager.GetNbItemsByName(name);
if (totalcount <= 0)
{
_logger.LogError("No RunePage found with this name {name} in the dataContext", name); ;
return NotFound("No RunePage found with this name: " + name + "in the dataContext");
}
var runeP = await dataManager.GetItemsByName(name, 0, totalcount);
_logger.LogInformation($"========================= {runeP} ================================================"); ;
if (runeP.Count() <= 0 || runeP == null)
{
_logger.LogError($"No RunePage found with {name} executing {nameof(GetRunePageByName)}"); ;
return NotFound("No RunePage found with" + name);
}
IEnumerable<RunePageDTO> res = runeP.Select(c => c.ToDto());
var respList = res.Select(r => new LolResponse<RunePageDTO>
(
r,
new List<EndPointLink>
{
EndPointLink.To($"/api/[controller]/{r.Name}/{nameof(GetRunePageByName)}", "self"),
EndPointLink.To($"/api/[controller]/{r.Name}/{nameof(Post)}", "self","POST"),
EndPointLink.To($"/api/[controller]/{r.Name}/{nameof(Put)}", "self","PUT"),
}
));
return Ok(respList);
}
catch (Exception e)
{
_logger.LogError("Somthing goes wrong caching the RunePage controller : " + e.Message);
return BadRequest("Somthing goes wrong caching the RunePage controller : " + e.Message);
}
}
[HttpPost]
public async Task<IActionResult> Post([FromBody] RunePageDTO runePage)
{
_logger.LogInformation("method {Action} - RunPageController with {item}", nameof(Post), runePage);
try
{
if (await dataManager.GetNbItemsByName(runePage.Name) == 0)
{
return CreatedAtAction(nameof(Get),(await dataManager.AddItem(runePage.ToModel())).ToDto());
}
_logger.LogWarning($"Name : {runePage.Name} already exist");
return BadRequest($"Name : {runePage.Name} already exist");
}
catch (Exception error)
{
_logger.LogError(error.Message);
return BadRequest(error.Message);
}
}
[HttpPut("{name}")]
public async Task<IActionResult> Put(string name, [FromBody] RunePageDTO value)
{
try
{
_logger.LogInformation("Executing {Action} with name : {RunePageName}", nameof(Put), name);
var runeP = await dataManager
.GetItemsByName(name, 0, await dataManager.GetNbItems());
if (runeP == null)
{
_logger.LogError("No RunePage found with {name} in the dataBase", name); ;
return NotFound();
}
var savedUpdatedRunePage = await dataManager.UpdateItem(runeP.First(), value.ToModel());
if (savedUpdatedRunePage == null)
{
_logger.LogWarning("The updated RunePage not returned {name}", name); ;
return BadRequest();
}
return Ok(savedUpdatedRunePage);
}
catch (Exception e)
{
_logger.LogError("Somthing goes wrong caching the RunePage controller : " + e.Message);
return BadRequest(e.Message);
}
}
[HttpDelete("{name}")]
public async Task<IActionResult> Delete(string name)
{
_logger.LogInformation("method {Action} - RUNEPAGE call with {name}", nameof(Delete), name);
try
{
var dtos = await dataManager.GetItemsByName(name, 0, await dataManager.GetNbItems());
if (dtos == null)
{
_logger.LogWarning("{name} was not found", name);
return NotFound($"{name} was not found");
}
await dataManager.DeleteItem(dtos.First());
return NoContent();
}
catch (Exception error)
{
_logger.LogError(error.Message);
return BadRequest(error.Message);
}
}
// GET: api/<RunePageController>/count
[HttpGet("/countRunePage", Name = "GetRunePageCount") ]
public async Task<ActionResult<int>> NbRunePage()
{
_logger.LogInformation("method {Action} - RUNEPAGE call", nameof(NbRunePage));
try
{
var nbRunePage = await dataManager.GetNbItems();
return Ok(nbRunePage);
}
catch (Exception error)
{
_logger.LogError(error.Message);
return BadRequest(error.Message);
}
}
}
}

@ -0,0 +1,71 @@
using Microsoft.AspNetCore.Mvc;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace API_LoL_Project.Controllers.version2
{
[Route("api/v{version:apiVersion}/[controller]")]
[ApiVersion("2.0")]
[ApiController]
public class SkillController : ControllerBase
{
/* // GET: api/<SkillController>
[HttpGet]
public async Task<ActionResult<IEnumerable<RuneDTO>>> Get([FromQuery] Request.PageRequest request)
{
try
{
var totalcount = await runesManager.GetNbItems();
if (request.count + request.index > totalcount)
{
_logger.LogWarning("to many rows ask the max is {totalcount}", totalcount);
return BadRequest("to many rows ask the max is " + totalcount);
}
_logger.LogInformation("Executing {Action} with parameters: {Parameters}", nameof(Get), request);
var runes = await runesManager.GetItems(request.PageNumber, totalcount, request.orderingPropertyName, (request.descending == null ? false : (bool)request.descending));
IEnumerable<RuneDTO> res = runes.Select(c => c.toDTO());
if (res.Count() >= 0 || res == null)
{
_logger.LogWarning("No runes found with Id");
return BadRequest("No runes found with Id ");
}
return Ok(res);
}
catch (Exception e)
{
_logger.LogError("About get at {e.message}", DateTime.UtcNow.ToLongTimeString());
return BadRequest(e.Message);
}
}
// GET api/<SkillController>/5
[HttpGet("{id}")]
public string Get(int id)
{
return "value";
}
// POST api/<SkillController>
[HttpPost]
public void Post([FromBody] string value)
{
}
// PUT api/<SkillController>/5
[HttpPut("{id}")]
public void Put(int id, [FromBody] string value)
{
}
// DELETE api/<SkillController>/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}*/
}
}

@ -0,0 +1,81 @@
using DTO;
using Microsoft.AspNetCore.Mvc;
using Model;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace API_LoL_Project.Controllers.version2
{
[Route("api/v{version:apiVersion}/[controller]")]
[ApiVersion("2.0")]
[ApiController]
public class SkinController : ControllerBase
{
/* public ISkinsManager dataManager;
private readonly ILogger<ChampionsController> _logger;
public SkinController(IDataManager dataManager, ILogger<ChampionsController> logger)
{
this.dataManager = dataManager.SkinsMgr;
this._logger = logger;
}
// GET: api/<SkinController>
[HttpGet]
public async Task<ActionResult<IEnumerable<RuneDTO>>> Get([FromQuery] Request.PageRequest request)
{
try
{
var totalcount = await dataManager.GetNbItems();
if (request.count + request.index > totalcount)
{
_logger.LogWarning("to many rows ask the max is {totalcount}", totalcount);
return BadRequest("to many rows ask the max is " + totalcount);
}
_logger.LogInformation("Executing {Action} with parameters: {Parameters}", nameof(Get), request);
var runes = await dataManager.GetItems(request.PageNumber, totalcount, request.orderingPropertyName, (request.descending == null ? false : (bool)request.descending));
IEnumerable<RuneDTO> res = runes.Select(c => c.toDTO());
if (res.Count() >= 0 || res == null)
{
_logger.LogWarning("No runes found with Id");
return BadRequest("No runes found with Id ");
}
return Ok(res);
}
catch (Exception e)
{
_logger.LogError("About get at {e.message}", DateTime.UtcNow.ToLongTimeString());
return BadRequest(e.Message);
}
}
// GET api/<SkinController>/5
[HttpGet("{id}")]
public string Get(int id)
{
return "value";
}
// POST api/<SkinController>
[HttpPost]
public void Post([FromBody] string value)
{
}
// PUT api/<SkinController>/5
[HttpPut("{id}")]
public void Put(int id, [FromBody] string value)
{
}
// DELETE api/<SkinController>/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}*/
}
}

@ -1,26 +1,27 @@
#See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging.
FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443
FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /src
COPY ["API_LoL_Project/API_LoL_Project.csproj", "API_LoL_Project/"]
COPY ["StubLib/StubLib.csproj", "StubLib/"]
COPY ["Model/Model.csproj", "Model/"]
COPY ["Shared/Shared.csproj", "Shared/"]
COPY ["DTO/DTO.csproj", "DTO/"]
RUN dotnet restore "API_LoL_Project/API_LoL_Project.csproj"
COPY . .
WORKDIR "/src/API_LoL_Project"
RUN dotnet build "API_LoL_Project.csproj" -c Release -o /app/build
FROM build AS publish
RUN dotnet publish "API_LoL_Project.csproj" -c Release -o /app/publish
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
#See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging.
FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443
FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /src
COPY ["API_LoL_Project/API_LoL_Project.csproj", "API_LoL_Project/"]
COPY ["StubLib/StubLib.csproj", "StubLib/"]
COPY ["Model/Model.csproj", "Model/"]
COPY ["Shared/Shared.csproj", "Shared/"]
COPY ["DTO/DTO.csproj", "DTO/"]
RUN dotnet restore "API_LoL_Project/API_LoL_Project.csproj"
COPY . .
WORKDIR "/src/API_LoL_Project"
RUN dotnet build "API_LoL_Project.csproj" -c Release -o /app/build
FROM build AS publish
RUN dotnet publish "API_LoL_Project.csproj" -c Release -o /app/publish
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
RUN ls -R
ENTRYPOINT ["dotnet", "API_LoL_Project.dll"]

@ -0,0 +1,20 @@
using System.Collections.ObjectModel;
using System.Text.Json.Serialization;
using System.Text.Json;
namespace API_LoL_Project.JsonConverter
{
public class ReadOnlyDictionaryConverter<TKey, TValue> : JsonConverter<ReadOnlyDictionary<TKey, TValue>>
{
public override ReadOnlyDictionary<TKey, TValue> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
Dictionary<TKey, TValue> dictionary = JsonSerializer.Deserialize<Dictionary<TKey, TValue>>(ref reader, options);
return new ReadOnlyDictionary<TKey, TValue>(dictionary);
}
public override void Write(Utf8JsonWriter writer, ReadOnlyDictionary<TKey, TValue> value, JsonSerializerOptions options)
{
JsonSerializer.Serialize(writer, value.ToDictionary(kv => kv.Key, kv => kv.Value), options);
}
}
}

@ -0,0 +1,65 @@
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.Extensions.Options;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
namespace API_LoL_Project
{
public class LolSwaggerOptions : IConfigureNamedOptions<SwaggerGenOptions>
{
private readonly IApiVersionDescriptionProvider _provider;
public LolSwaggerOptions(
IApiVersionDescriptionProvider provider)
{
_provider = provider;
}
/// <summary>
/// Configure each API discovered for Swagger Documentation
/// </summary>
/// <param name="options"></param>
public void Configure(SwaggerGenOptions options)
{
// add swagger document for every API version discovered
foreach (var description in _provider.ApiVersionDescriptions)
{
options.SwaggerDoc(
description.GroupName,
CreateVersionInfo(description));
}
}
/// <summary>
/// Configure Swagger Options. Inherited from the Interface
/// </summary>
/// <param name="name"></param>
/// <param name="options"></param>
public void Configure(string name, SwaggerGenOptions options)
{
Configure(options);
}
/// <summary>
/// Create information about the version of the API
/// </summary>
/// <param name="description"></param>
/// <returns>Information about the API</returns>
private OpenApiInfo CreateVersionInfo(
ApiVersionDescription desc)
{
var info = new OpenApiInfo()
{
Title = ".NET Core (.NET 6) Web API For Lol",
Version = desc.ApiVersion.ToString()
};
if (desc.IsDeprecated)
{
info.Description += " This API version has been deprecated. Please use one of the new APIs available from the explorer.";
}
return info;
}
}
}

@ -1,80 +0,0 @@
using DTO;
using Entities;
using Model;
namespace API_LoL_Project.Mapper
{
public static class ChampionMapper {
public static ChampionDTO ToDTO(this Champion item)
{
if (item == null)
{
var message = string.Format("Champion cannot be empty");
/*throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, message));
*/
throw new Exception(message);
}
return new ChampionDTO() {
Name = item.Name,
Bio = item.Bio
};
}
public static ChampionEntity ToEntity(this Champion item)
{
return new()
{
Name = item.Name,
Bio = item.Bio,
Icon = item.Icon,
Class = item.Class,
Image = new() { Base64 = item.Image.Base64 },
};
}
public static ChampionFullDTO toFullDTO(this Champion item)
{
if (item == null)
{
var message = string.Format("Champion with name = {} not found", item.Name);
/*throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, message));
*/
throw new Exception(message);
}
return new ChampionFullDTO()
{
Name = item.Name,
Bio = item.Bio,
Characteristics = item.Characteristics,
skills = item.Skills,
skins = item.Skins.Select(i => i.ToDto()),
LargeImage = item.Image.ToDTO()
};
}
public static Champion ToModel(this ChampionDTO dto)
{
if (dto == null)
{
var message = string.Format("Champion cannot be empty");
/*throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, message));
*/
throw new Exception(message);
}
return new(dto.Name);
}
public static Champion ToModel(this ChampionEntity entity)
{
return new(entity.Name, entity.Class, entity.Icon, entity.Image.Base64, entity.Bio);
}
}
}

@ -1,27 +0,0 @@
namespace API_LoL_Project.Mapper
{
using DTO;
using Entities;
using Model;
namespace API_LoL_Project.Mapper
{
public static class RuneMapper
{
public static RuneEntity ToEntity(this Rune item)
{
throw new NotImplementedException();
}
public static Rune ToModel(this RuneEntity entity)
{
throw new NotImplementedException();
}
}
}
}

@ -1,19 +0,0 @@
using Entities;
using Model;
namespace API_LoL_Project.Mapper
{
public static class RunePageMapper
{
public static RunePageEntity ToEntity(this RunePage item)
{
throw new NotImplementedException();
}
public static RunePage ToModel(this RunePageEntity entity)
{
throw new NotImplementedException();
}
}
}

@ -1,29 +0,0 @@
using DTO;
using Model;
namespace API_LoL_Project.Mapper
{
public static class RunesMappeur
{
public static RuneDTO toDTO(this Rune item)
{
return new RuneDTO()
{
Name = item.Name,
Family = item.Family,
};
}
public static Rune toModel(this RuneDTO dto)
{
/*if (dto == null)
{
*//* var message = string.Format("Champion with name = {} not found", dto.Name);
throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, message));*//*
}*/
return new Rune(dto.Name, dto.Family);
}
}
}

@ -0,0 +1,34 @@
using API_LoL_Project.utils;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
namespace API_LoL_Project.Middleware.Auth
{
public class AuthMiddlewareFliter : IAsyncAuthorizationFilter
{
private readonly IConfiguration _configuration;
public AuthMiddlewareFliter(IConfiguration configuration)
{
this._configuration = configuration;
}
public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
{
if (!context.HttpContext.Request.Headers.TryGetValue(AuthUtils.ApiKeyHeaderName, out var clientApiKey))
{
context.Result = new UnauthorizedObjectResult("ApiKey is missing please ask author's permission");
return;
}
var apiKey = _configuration.GetValue<string>(AuthUtils.ApiKeySectionName);
if (!apiKey.Equals(clientApiKey))
{
context.Result = new UnauthorizedObjectResult("ApiKey used is invalid");
return;
}
// If the API key is valid, allow the request to proceed.
await Task.CompletedTask;
}
}
}

@ -1,7 +0,0 @@
namespace API_LoL_Project.Middleware
{
public class HateosMiddleware
{
}
}

@ -3,13 +3,13 @@ using System.Net;
namespace API_LoL_Project.Middleware
{
public class LolResponce<T>
public class LolResponse<T>
{
public T Data { get; set; }
public List<EndPointLink> Links { get; set; } = null;
public LolResponce(T data , List<EndPointLink>? links)
public LolResponse(T data , List<EndPointLink>? links)
{
this.Data = data;
this.Links = links;

@ -1,28 +1,104 @@
using Model;
using StubLib;
using Business;
using Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.AspNetCore.Mvc.Versioning;
using Model;
using StubLib;
using API_LoL_Project;
using API_LoL_Project.JsonConverter;
using API_LoL_Project.Middleware.Auth;
using Microsoft.OpenApi.Models;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
var connectionString = builder.Configuration.GetConnectionString("LolDatabase");
builder.Services.AddDbContext<LolDbContext>(options =>
options.UseSqlite(connectionString), ServiceLifetime.Singleton);
builder.Services.AddControllers().AddJsonOptions(options =>
{
options.JsonSerializerOptions.Converters.Add(new ReadOnlyDictionaryConverter<string, int>());
});
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddSwaggerGen( cont =>
{
cont.AddSecurityDefinition("ApiKey", new Microsoft.OpenApi.Models.OpenApiSecurityScheme
{
Description = "The Key to acces to the API",
Type = SecuritySchemeType.ApiKey,
Name = "x-api-key",
In = ParameterLocation.Header,
Scheme = "ApiKeyScheme"
});
var scheme = new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "ApiKey"
},
In = ParameterLocation.Header
};
var requirement = new OpenApiSecurityRequirement
{
{
scheme, new List<string>()
}
};
cont.AddSecurityRequirement(requirement);
}
);
builder.Services.AddApiVersioning(opt =>
{
opt.DefaultApiVersion = new Microsoft.AspNetCore.Mvc.ApiVersion(1, 0);
opt.AssumeDefaultVersionWhenUnspecified = true;
opt.ReportApiVersions = true;
opt.ApiVersionReader = ApiVersionReader.Combine(new UrlSegmentApiVersionReader());
});
builder.Services.ConfigureOptions<LolSwaggerOptions>();
builder.Services.AddVersionedApiExplorer(setup =>
{
setup.GroupNameFormat = "'v'VVV";
setup.SubstituteApiVersionInUrl = true;
});
builder.Services.AddScoped<AuthMiddlewareFliter>();
builder.Services.AddSingleton<IDataManager, DbData>();
//builder.Services.AddSingleton<IDataManager, StubData>();
builder.Services.AddSingleton<IDataManager, StubData>();
var app = builder.Build();
var apiVersionDescriptionProvider = app.Services.GetRequiredService<IApiVersionDescriptionProvider>();
app?.Services?.GetService<LolDbContext>()?.Database.EnsureCreated();
// à enlever
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
app.UseSwaggerUI(options =>
{
foreach (var description in apiVersionDescriptionProvider.ApiVersionDescriptions)
{
options.SwaggerEndpoint($"/swagger/{description.GroupName}/swagger.json",
description.GroupName.ToUpperInvariant());
}
});
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();

@ -1,13 +0,0 @@
namespace API_LoL_Project
{
public class WeatherForecast
{
public DateTime Date { get; set; }
public int TemperatureC { get; set; }
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
public string? Summary { get; set; }
}
}

@ -4,5 +4,8 @@
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"ConnectionStrings": {
"LolDatabase": "Data Source=Entities.LolDatabase.db"
}
}

@ -0,0 +1,11 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"ConnectionStrings": {
"LolDatabase": "Data Source=Entities.LolDatabase.db"
}
}

@ -1,9 +1,16 @@
{
"Authentification": {
"ApiKey" : "ViveC#"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"ConnectionStrings": {
"LolDatabase": "Data Source=Entities.LolDatabase.db"
},
"AllowedHosts": "*"
}

@ -0,0 +1,10 @@
namespace API_LoL_Project.utils
{
public class AuthUtils
{
public const string ApiKeySectionName = "Authentification:ApiKey";
public const string ApiKeyHeaderName = "x-api-key";
}
}

@ -0,0 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\ApiMappeur\ApiMappeur.csproj" />
<ProjectReference Include="..\DTO\DTO.csproj" />
<ProjectReference Include="..\Model\Model.csproj" />
</ItemGroup>
</Project>

@ -0,0 +1,32 @@
using Model;
using System.Net.Http;
namespace ApiLib
{
public partial class ApiManager : IDataManager
{
protected HttpClient HttpClient { get; }
public ApiManager(HttpClient httpClient)
{
ChampionsMgr = new ChampionsManager(this);
SkinsMgr = new SkinsManager(this);
/*RunesMgr = new RunesManager(this);
RunePagesMgr = new RunePagesManager(this);*/
HttpClient = httpClient;
HttpClient.BaseAddress = new Uri("https://codefirst.iut.uca.fr/containers/arthurvalin-lolcontainer/api/v2");
}
public IChampionsManager ChampionsMgr { get; }
public ISkinsManager SkinsMgr { get; }
public IRunesManager RunesMgr { get; }
public IRunePagesManager RunePagesMgr { get; }
}
}

@ -0,0 +1,580 @@
using DTO;
using Model;
using Shared;
using System;
using System.Collections.Generic;
using System.Data.SqlTypes;
using System.Linq;
using System.Net;
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using System.Xml.Linq;
using ApiMappeur;
namespace ApiLib
{
public partial class ApiManager
{
public class ChampionsManager : IChampionsManager
{
private readonly ApiManager parent;
public ChampionsManager(ApiManager parent)
=> this.parent = parent;
private const string urlChampion = "/champions";
public async Task<Champion?> AddItem(Champion? item)
{
try
{
if (item == null) throw new ArgumentNullException("Champions is null cannot add empty");
var response = await parent.HttpClient.PostAsJsonAsync(urlChampion, item.toFullDTO());
if (response.IsSuccessStatusCode || response.StatusCode == HttpStatusCode.Created)// mayby changer to check the status code is more secure i think
{
Champion newChampion = await response.Content.ReadFromJsonAsync<Champion>();
Console.WriteLine("Champion {0} inserted", newChampion.Name);
return newChampion;
}
else
{
// Log the error status code and reason phrase
Console.WriteLine($"Failed to add item. Status code: {response.StatusCode}. Reason: {response.ReasonPhrase}");
return null;
}
}
catch (HttpRequestException ex)
{
// Log the error message from the HttpClient exception
Console.WriteLine($"Failed to add item. {ex.Message}");
return null;
}
catch (JsonException ex)
{
// Log the error message from the JSON serialization exception
Console.WriteLine($"Failed to add item. Error while serializing JSON data. {ex.Message}");
return null;
}
catch (Exception ex)
{
// Log any other exceptions that may occur
Console.WriteLine($"Failed to add item. {ex.Message}");
return null;
}
}
public async Task<bool> DeleteItem(Champion? item)
{
try
{
if (item == null) throw new ArgumentNullException("Champions is null cannot add empty");
HttpResponseMessage response = await parent.HttpClient.DeleteAsync($"champions/{item.Name}");
if (response.IsSuccessStatusCode)
{
Console.WriteLine("Champion {0} deleted", item.Name);
return true;
}
else
{
Console.WriteLine($"Failed to delete item. Status code: {response.StatusCode}. Reason: {response.ReasonPhrase}");
return false;
}
}
catch (HttpRequestException ex)
{
Console.WriteLine($"Failed to delete item. {ex.Message}");
return false;
}
catch (Exception ex)
{
Console.WriteLine($"Failed to delete item. {ex.Message}");
return false;
}
}
public async Task<IEnumerable<Champion?>> GetItems(int index, int count, string? orderingPropertyName = null, bool descending = false)
{
try
{
// should use Page request Object but to show that the api is rest
string queryString = $"?index={index}&count={count}";
if (!string.IsNullOrEmpty(orderingPropertyName))
{
queryString += $"&orderBy={orderingPropertyName}";
if (descending)
{
queryString += "&descending=true";
}
}
var response = await parent.HttpClient.GetAsync($"{urlChampion}{queryString}");
if (response.IsSuccessStatusCode)
{
IEnumerable<ChampionDTO?> champions = await response.Content.ReadFromJsonAsync<IEnumerable<ChampionDTO?>>();
Console.WriteLine(champions);
IEnumerable<Champion> res = champions.Select(c => c.ToModel());
return res;
}
else
{
Console.WriteLine($"Failed to retrieve Champions. Status code: {response.StatusCode}. Reason: {response.ReasonPhrase}");
return null;
}
}
catch (HttpRequestException ex)
{
Console.WriteLine($"Failed to retrieve Champions. {ex.Message}");
return null;
}
catch (JsonException ex)
{
Console.WriteLine($"Failed to retrieve Champions. Error while deserializing JSON data. {ex.Message}");
return null;
}
catch (Exception ex)
{
Console.WriteLine($"Failed to retrieve Champions. {ex.Message}");
return null;
}
}
public async Task<IEnumerable<Champion?>> GetItemsByCharacteristic(string charName, int index, int count, string? orderingPropertyName = null, bool descending = false)
{
try
{
HttpResponseMessage response = await parent.HttpClient.GetAsync($"{urlChampion}/characteristic/{charName}?index={index}&count={count}&orderingPropertyName={orderingPropertyName}&descending={descending}");
if (response.IsSuccessStatusCode)
{
List<ChampionDTO?> champions = await response.Content.ReadFromJsonAsync<List<ChampionDTO>>();
Console.WriteLine($"Retrieved {champions.Count} champions with characteristic {charName}");
IEnumerable<Champion> res = champions.Select(c => c.ToModel());
return res;
}
else
{
Console.WriteLine($"Failed to retrieve champions with characteristic {charName}. Status code: {response.StatusCode}. Reason: {response.ReasonPhrase}");
return null;
}
}
catch (HttpRequestException ex)
{
Console.WriteLine($"Failed to retrieve champions with characteristic {charName}. {ex.Message}");
return null;
}
catch (JsonException ex)
{
Console.WriteLine($"Failed to retrieve champions with characteristic {charName}. Error while deserializing JSON data. {ex.Message}");
return null;
}
catch (Exception ex)
{
Console.WriteLine($"Failed to retrieve champions with characteristic {charName}. {ex.Message}");
return null;
}
}
public async Task<IEnumerable<Champion?>> GetItemsByClass(ChampionClass championClass, int index, int count, string? orderingPropertyName = null, bool descending = false)
{
var queryString = new StringBuilder();
queryString.Append($"class={championClass}");
queryString.Append($"&Index={index}");
queryString.Append($"&Count={count}");
if (!string.IsNullOrEmpty(orderingPropertyName))
{
queryString.Append($"&OrderingPropertyName={orderingPropertyName}");
queryString.Append($"&Descending={descending}");
}
var uri = new UriBuilder(urlChampion)
{
Query = queryString.ToString()
}.Uri;
try
{
var response = await parent.HttpClient.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
var champions = await response.Content.ReadFromJsonAsync<IEnumerable<ChampionDTO?>>();
IEnumerable<Champion> res = champions.Select(c => c.ToModel());
return res;
}
else
{
Console.WriteLine($"Failed to retrieve items. Status code: {response.StatusCode}. Reason: {response.ReasonPhrase}");
return null;
}
}
catch (HttpRequestException ex)
{
Console.WriteLine($"Failed to retrieve items. {ex.Message}");
return null;
}
catch (JsonException ex)
{
Console.WriteLine($"Failed to retrieve items. Error while deserializing JSON data. {ex.Message}");
return null;
}
catch (Exception ex)
{
Console.WriteLine($"Failed to retrieve items. {ex.Message}");
return null;
}
}
public async Task<IEnumerable<Champion?>> GetItemsByName(string substring, int index, int count, string? orderingPropertyName = null, bool descending = false)
{
try
{
/* string queryString = $"?name={substring}&index={index}&count={count}";
if (!string.IsNullOrEmpty(orderingPropertyName))
{
queryString += $"&orderBy={orderingPropertyName}";
if (descending)
{
queryString += "&descending=true";
}
}*/
Uri uri = new Uri($"{urlChampion}/{substring}");
var response = await parent.HttpClient.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
IEnumerable<ChampionDTO> champions = await response.Content.ReadFromJsonAsync<IEnumerable<ChampionDTO>>();
Console.WriteLine(champions);
IEnumerable<Champion> res = champions.Select(c => c.ToModel());
Console.WriteLine($"Found {res.Count()} champions that match the substring '{substring}'");
return res;
}
else
{
Console.WriteLine($"Failed to retrieve items. Status code: {response.StatusCode}. Reason: {response.ReasonPhrase}");
return null;
}
}
catch (HttpRequestException ex)
{
Console.WriteLine($"Failed to retrieve items. {ex.Message}");
return null;
}
catch (JsonException ex)
{
Console.WriteLine($"Failed to retrieve items. Error while deserializing JSON data. {ex.Message}");
return null;
}
catch (Exception ex)
{
Console.WriteLine($"Failed to retrieve items. {ex.Message}");
return null;
}
}
public async Task<IEnumerable<Champion?>> GetItemsByRunePage(RunePage? runePage, int index, int count, string? orderingPropertyName = null, bool descending = false)
{
try
{
string queryString = $"?index={index}&count={count}";
if (!string.IsNullOrEmpty(orderingPropertyName))
{
queryString += $"&orderBy={orderingPropertyName}";
if (descending)
{
queryString += "&descending=true";
}
}
if (runePage != null)
{
string runePageQueryString = string.Join("&", runePage.Runes
.Where(kv => kv.Value != null)
.Select(kv => $"{kv.Key}={kv.Value.Name}"));
if (!string.IsNullOrEmpty(runePageQueryString))
{
queryString += $"&{runePageQueryString}";
}
}
Uri uri = new Uri($"{urlChampion}/runePage{queryString}");
var response = await parent.HttpClient.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
IEnumerable<Champion> champions = await response.Content.ReadFromJsonAsync<IEnumerable<Champion>>();
Console.WriteLine($"Found {champions.Count()} champions that match the Rune Page");
return champions;
}
else
{
Console.WriteLine($"Failed to retrieve items. Status code: {response.StatusCode}. Reason: {response.ReasonPhrase}");
return null;
}
}
catch (HttpRequestException ex)
{
Console.WriteLine($"Failed to retrieve items. {ex.Message}");
return null;
}
catch (JsonException ex)
{
Console.WriteLine($"Failed to retrieve items. Error while deserializing JSON data. {ex.Message}");
return null;
}
catch (Exception ex)
{
Console.WriteLine($"Failed to retrieve items. {ex.Message}");
return null;
}
}
public Task<IEnumerable<Champion?>> GetItemsBySkill(Skill? skill, int index, int count, string? orderingPropertyName = null, bool descending = false)
{
throw new NotImplementedException();
}
public Task<IEnumerable<Champion?>> GetItemsBySkill(string skill, int index, int count, string? orderingPropertyName = null, bool descending = false)
{
throw new NotImplementedException();
}
public async Task<int> GetNbItems()
{
int count = 0;
try
{
var response = await parent.HttpClient.GetAsync($"{urlChampion}/count");
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
count = int.Parse(responseBody);
}
}
catch (Exception ex)
{
// not sure about the -1 maybe sould juste log info
Console.WriteLine($"An error occurred while fetching the number of Champions: {ex.Message}");
return -1;
}
return count;
}
public async Task<int> GetNbItemsByCharacteristic(string charName)
{
int count = 0;
try
{
var response = await parent.HttpClient.GetAsync($"{urlChampion}/count/characteristic/{charName}");
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
if (!int.TryParse(responseBody, out count))
{
Console.WriteLine($"Error parsing response body {responseBody} to int");
return -1;
}
}
else
{
Console.WriteLine($"Error getting number of items by characteristic");
return -1;
}
}
catch (Exception ex)
{
// Log the error
Console.WriteLine($"Error getting number of items by characteristic {charName}: {ex.Message}");
return -1;
}
return count;
}
public async Task<int> GetNbItemsByClass(ChampionClass championClass)
{
int count = 0;
try
{
var response = await parent.HttpClient.GetAsync($"{urlChampion}/count/class/{championClass}");
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
if (!int.TryParse(responseBody, out count))
{
Console.WriteLine($"Error parsing response body {responseBody} to int");
return -1;
}
}
else
{
Console.WriteLine($"Error getting number of items by class");
return -1;
}
}
catch (Exception ex)
{
// Log the error
Console.WriteLine($"Error getting number of items by class {championClass}: {ex.Message}");
return -1;
}
return count;
}
public async Task<int> GetNbItemsByName(string substring)
{
int count = 0;
try
{
var response = await parent.HttpClient.GetAsync($"champions/count/name/{substring}");
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
if (!int.TryParse(responseBody, out count))
{
Console.WriteLine($"Error parsing response body {responseBody} to int");
return -1;
}
}
else
{
Console.WriteLine($"Error getting number of items by name");
return -1;
}
}
catch (Exception ex)
{
// Log the error
Console.WriteLine($"Error getting number of items by name {substring}: {ex.Message}");
return -1;
}
return count;
}
public async Task<int> GetNbItemsByRunePage(RunePage? runePage)
{
int count = 0;
try
{
string requestUri = $"{urlChampion}/count/runePage";
if (runePage != null)
{
string runePageQueryString = string.Join("&", runePage.Runes
.Where(kv => kv.Value != null)
.Select(kv => $"{kv.Key}={kv.Value.Name}"));
if (!string.IsNullOrEmpty(runePageQueryString))
{
requestUri += "?runePage=" + Uri.EscapeDataString(runePageQueryString);
}
}
var response = await parent.HttpClient.GetAsync(requestUri);
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
if (!int.TryParse(responseBody, out count))
{
Console.WriteLine($"Error parsing response body {responseBody} to int");
return -1;
}
}
else
{
Console.WriteLine($"Error getting number of items by rune page");
return -1;
}
}
catch (Exception ex)
{
// Log the error
Console.WriteLine($"Error getting number of items by rune page: {ex.Message}");
return -1;
}
return count;
}
public Task<int> GetNbItemsBySkill(Skill? skill)
{
throw new NotImplementedException();
}
public Task<int> GetNbItemsBySkill(string skill)
{
throw new NotImplementedException();
}
public async Task<Champion?> UpdateItem(Champion? oldItem, Champion? newItem)
{
if (oldItem == null || newItem == null || oldItem.Name != newItem.Name)
{
Console.WriteLine("Error: oldItem or newItem is null");
return null;
}
try
{
var response = await parent.HttpClient.PutAsJsonAsync($"{urlChampion}/{oldItem.Name}", newItem);
if (response.IsSuccessStatusCode)
{
var updatedChampion = await response.Content.ReadFromJsonAsync<Champion>();
return updatedChampion;
}
else
{
Console.WriteLine($"Error updating champion {oldItem.Name}");
return null;
}
}
catch (Exception ex)
{
Console.WriteLine($"Error updating champion {oldItem.Name}: {ex.Message}");
return null;
}
}
}
}
}

@ -0,0 +1,367 @@
using Model;
using Shared;
using System.Diagnostics;
using System.Collections.Immutable;
using static System.Console;
namespace ApiLib
{
static class Program
{
static IDataManager dataManager = null!;
static async Task Main(string[] args)
{
try
{
dataManager = new ApiManager(new HttpClient());
var datat = dataManager.ChampionsMgr.GetItemsByName("dave", 0, 0);
WriteLine(datat);
await DisplayMainMenu();
Console.ReadLine();
}
catch (Exception ex)
{
Debug.WriteLine(ex, "Stopped program because of exception");
throw;
}
}
public static async Task DisplayMainMenu()
{
Dictionary<int, string> choices = new Dictionary<int, string>()
{
[1] = "1- Manage Champions",
[2] = "2- Manage Skins",
[3] = "3- Manage Runes",
[4] = "4- Manage Rune Pages",
[99] = "99- Quit"
};
while (true)
{
int input = DisplayAMenu(choices);
switch (input)
{
case 1:
await DisplayChampionsMenu();
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 99:
WriteLine("Bye bye!");
return;
default:
break;
}
}
}
private static int DisplayAMenu(Dictionary<int, string> choices)
{
int input = -1;
while (true)
{
WriteLine("What is your choice?");
WriteLine("--------------------");
foreach (var choice in choices.OrderBy(kvp => kvp.Key).Select(kvp => kvp.Value))
{
WriteLine(choice);
}
if (!int.TryParse(ReadLine(), out input) || input == -1)
{
WriteLine("I do not understand what your choice is. Please try again.");
continue;
}
break;
}
WriteLine($"You have chosen: {choices[input]}");
WriteLine();
return input;
}
public static async Task DisplayChampionsMenu()
{
Dictionary<int, string> choices = new Dictionary<int, string>()
{
[0] = "0- Get number of champions",
[1] = "1- Get champions",
[2] = "2- Find champions by name",
[3] = "3- Find champions by characteristic",
[4] = "4- Find champions by class",
[5] = "5- Find champions by skill",
[6] = "6- Add new champion",
[7] = "7- Delete a champion",
[8] = "8- Update a champion",
};
int input = DisplayAMenu(choices);
switch (input)
{
case 0:
int nb = await dataManager.ChampionsMgr.GetNbItems();
WriteLine($"There are {nb} champions");
WriteLine("**********************");
break;
case 1:
{
int index = ReadAnInt("Please enter the page index");
int count = ReadAnInt("Please enter the number of elements to display");
WriteLine($"{count} champions of page {index + 1}");
var champions = await dataManager.ChampionsMgr.GetItems(index, count, nameof(Champion.Name));
foreach (var champion in champions)
{
WriteLine($"\t{champion}");
}
WriteLine("**********************");
}
break;
case 2:
{
string substring = ReadAString("Please enter the substring to look for in the name of a champion");
int index = ReadAnInt("Please enter the page index");
int count = ReadAnInt("Please enter the number of elements to display");
var champions = await dataManager.ChampionsMgr.GetItemsByName(substring, index, count, nameof(Champion.Name));
foreach (var champion in champions)
{
WriteLine($"\t{champion}");
}
WriteLine("**********************");
}
break;
case 3:
{
string substring = ReadAString("Please enter the substring to look for in the characteristics of champions");
int index = ReadAnInt("Please enter the page index");
int count = ReadAnInt("Please enter the number of elements to display");
var champions = await dataManager.ChampionsMgr.GetItemsByCharacteristic(substring, index, count, nameof(Champion.Name));
foreach (var champion in champions)
{
WriteLine($"\t{champion}");
}
WriteLine("**********************");
}
break;
case 4:
{
ChampionClass championClass = ReadAnEnum<ChampionClass>($"Please enter the champion class (possible values are: {Enum.GetNames<ChampionClass>().Aggregate("", (name, chaine) => $"{chaine} {name}")}):");
int index = ReadAnInt("Please enter the page index");
int count = ReadAnInt("Please enter the number of elements to display");
var champions = await dataManager.ChampionsMgr.GetItemsByClass(championClass, index, count, nameof(Champion.Name));
foreach (var champion in champions)
{
WriteLine($"\t{champion}");
}
WriteLine("**********************");
}
break;
case 5:
{
string substring = ReadAString("Please enter the substring to look for in the skills of champions");
int index = ReadAnInt("Please enter the page index");
int count = ReadAnInt("Please enter the number of elements to display");
var champions = await dataManager.ChampionsMgr.GetItemsBySkill(substring, index, count, nameof(Champion.Name));
foreach (var champion in champions)
{
WriteLine($"\t{champion}");
}
WriteLine("**********************");
}
break;
case 6:
{
WriteLine("You are going to create a new champion.");
string name = ReadAString("Please enter the champion name:");
ChampionClass championClass = ReadAnEnum<ChampionClass>($"Please enter the champion class (possible values are: {Enum.GetNames<ChampionClass>().Aggregate("", (name, chaine) => $"{chaine} {name}")}):");
string bio = ReadAString("Please enter the champion bio:");
Champion champion = new Champion(name, championClass, bio: bio);
DisplayCreationChampionMenu(champion);
_ = await dataManager.ChampionsMgr.AddItem(champion);
}
break;
case 7:
{
WriteLine("You are going to delete a champion.");
string name = ReadAString("Please enter the champion name:");
var somechampions = await dataManager.ChampionsMgr.GetItemsByName(name, 0, 10, nameof(Champion.Name));
var someChampionNames = somechampions.Select(c => c!.Name);
var someChampionNamesAsOneString = someChampionNames.Aggregate("", (name, chaine) => $"{chaine} {name}");
string champName = ReadAStringAmongPossibleValues($"Who do you want to delete among these champions? (type \"Cancel\" to ... cancel) {someChampionNamesAsOneString}",
someChampionNames.ToArray());
if (champName != "Cancel")
{
await dataManager.ChampionsMgr.DeleteItem(somechampions.Single(c => c!.Name == champName));
}
}
break;
case 8:
{
WriteLine("You are going to update a champion.");
string name = ReadAString("Please enter the champion name:");
var somechampions = await dataManager.ChampionsMgr.GetItemsByName(name, 0, 10, nameof(Champion.Name));
var someChampionNames = somechampions.Select(c => c!.Name);
var someChampionNamesAsOneString = someChampionNames.Aggregate("", (name, chaine) => $"{chaine} {name}");
string champName = ReadAStringAmongPossibleValues($"Who do you want to update among these champions? (type \"Cancel\" to ... cancel) {someChampionNamesAsOneString}",
someChampionNames.ToArray());
if (champName == "Cancel") break;
ChampionClass championClass = ReadAnEnum<ChampionClass>($"Please enter the champion class (possible values are: {Enum.GetNames<ChampionClass>().Aggregate("", (name, chaine) => $"{chaine} {name}")}):");
string bio = ReadAString("Please enter the champion bio:");
Champion champion = new Champion(champName, championClass, bio: bio);
DisplayCreationChampionMenu(champion);
await dataManager.ChampionsMgr.UpdateItem(somechampions.Single(c => c!.Name == champName), champion);
}
break;
default:
break;
}
}
public static void DisplayCreationChampionMenu(Champion champion)
{
Dictionary<int, string> choices = new Dictionary<int, string>()
{
[1] = "1- Add a skill",
[2] = "2- Add a skin",
[3] = "3- Add a characteristic",
[99] = "99- Finish"
};
while (true)
{
int input = DisplayAMenu(choices);
switch (input)
{
case 1:
string skillName = ReadAString("Please enter the skill name:");
SkillType skillType = ReadAnEnum<SkillType>($"Please enter the skill type (possible values are: {Enum.GetNames<SkillType>().Aggregate("", (name, chaine) => $"{chaine} {name}")}):");
string skillDescription = ReadAString("Please enter the skill description:");
Skill skill = new Skill(skillName, skillType, skillDescription);
champion.AddSkill(skill);
break;
case 2:
string skinName = ReadAString("Please enter the skin name:");
string skinDescription = ReadAString("Please enter the skin description:");
float skinPrice = ReadAFloat("Please enter the price of this skin:");
Skin skin = new Skin(skinName, champion, skinPrice, description: skinDescription);
break;
case 3:
string characteristic = ReadAString("Please enter the characteristic:");
int value = ReadAnInt("Please enter the value associated to this characteristic:");
champion.AddCharacteristics(Tuple.Create(characteristic, value));
break;
case 99:
return;
default:
break;
}
}
}
private static int ReadAnInt(string message)
{
while (true)
{
WriteLine(message);
if (!int.TryParse(ReadLine(), out int result))
{
continue;
}
return result;
}
}
private static float ReadAFloat(string message)
{
while (true)
{
WriteLine(message);
if (!float.TryParse(ReadLine(), out float result))
{
continue;
}
return result;
}
}
private static string ReadAString(string message)
{
while (true)
{
WriteLine(message);
string? line = ReadLine();
if (line == null)
{
continue;
}
return line!;
}
}
private static TEnum ReadAnEnum<TEnum>(string message) where TEnum : struct
{
while (true)
{
WriteLine(message);
if (!Enum.TryParse<TEnum>(ReadLine(), out TEnum result))
{
continue;
}
return result;
}
}
private static string ReadAStringAmongPossibleValues(string message, params string[] possibleValues)
{
while (true)
{
WriteLine(message);
string? result = ReadLine();
if (result == null) continue;
if (result != "Cancel" && !possibleValues.Contains(result!)) continue;
return result!;
}
}
}
}
// Get all champions
/*var champions = await championClient.ChampionsMgr.
Console.WriteLine("All champions:");
foreach (var champion in champions)
{
Console.WriteLine($"{champion.Name} ({champion.Bio})");
}
*/
/*// Add a new champion
var newChampion = new ChampionDto { Name = "Akali", Role = "Assassin" };
championClient.Add(newChampion);
// Delete a champion
var championToDelete = champions.FirstOrDefault(c => c.Name == "Riven");
if (championToDelete != null)
{
championClient.Delete(championToDelete);
Console.WriteLine($"{championToDelete.Name} deleted.");
}
// Update a champion
var championToUpdate = champions.FirstOrDefault(c => c.Name == "Ashe");
if (championToUpdate != null)
{
championToUpdate.Role = "Marksman";
championClient.Update(championToUpdate);
Console.WriteLine($"{championToUpdate.Name} updated.");
}
*/

@ -0,0 +1,201 @@
using Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Json;
using System.Net;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using DTO;
using ApiMappeur;
namespace ApiLib
{
public partial class ApiManager
{
public class SkinsManager : ISkinsManager
{
private readonly ApiManager parent;
public SkinsManager(ApiManager parent)
=> this.parent = parent;
public async Task<Skin?> AddItem(Skin? item)
{
try
{
if (item == null) throw new ArgumentNullException("Skin is null cannot add empty");
var response = await parent.HttpClient.PostAsJsonAsync("/skins", item);
if (response.IsSuccessStatusCode || response.StatusCode == HttpStatusCode.Created)
{
Skin newSkin = await response.Content.ReadFromJsonAsync<Skin>();
Console.WriteLine("Skin {0} inserted", newSkin.Name);
return newSkin;
}
else
{
Console.WriteLine($"Failed to add item. Status code: {response.StatusCode}. Reason: {response.ReasonPhrase}");
return null;
}
}
catch (HttpRequestException ex)
{
Console.WriteLine($"Failed to add item. {ex.Message}");
return null;
}
catch (JsonException ex)
{
Console.WriteLine($"Failed to add item. Error while serializing JSON data. {ex.Message}");
return null;
}
catch (Exception ex)
{
Console.WriteLine($"Failed to add item. {ex.Message}");
return null;
}
}
public async Task<bool> DeleteItem(Skin? item)
{
try
{
if (item == null) throw new ArgumentNullException("Skin is null cannot delete empty");
var response = await parent.HttpClient.DeleteAsync($"/skins/{item.Name}");
if (response.IsSuccessStatusCode)
{
Console.WriteLine("Skin {0} deleted", item.Name);
return true;
}
else
{
Console.WriteLine($"Failed to delete item. Status code: {response.StatusCode}. Reason: {response.ReasonPhrase}");
return false;
}
}
catch (HttpRequestException ex)
{
Console.WriteLine($"Failed to delete item. {ex.Message}");
return false;
}
catch (Exception ex)
{
Console.WriteLine($"Failed to delete item. {ex.Message}");
return false;
}
}
public async Task<IEnumerable<Skin?>> GetItems(int index, int count, string? orderingPropertyName = null, bool descending = false)
{
try
{
string uri = $"/skins?index={index}&count={count}";
if (!string.IsNullOrEmpty(orderingPropertyName))
{
uri += $"&orderingPropertyName={orderingPropertyName}&descending={descending}";
}
var response = await parent.HttpClient.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
IEnumerable<Skin> skins = await response.Content.ReadFromJsonAsync<IEnumerable<Skin>>();
return skins;
}
else
{
Console.WriteLine($"Failed to get items. Status code: {response.StatusCode}. Reason: {response.ReasonPhrase}");
return Enumerable.Empty<Skin>();
}
}
catch (HttpRequestException ex)
{
Console.WriteLine($"Failed to get items. {ex.Message}");
return Enumerable.Empty<Skin>();
}
catch (Exception ex)
{
Console.WriteLine($"Failed to get items. {ex.Message}");
return Enumerable.Empty<Skin>();
}
}
public async Task<IEnumerable<Skin?>> GetItemsByChampion(Champion? champion, int index, int count, string? orderingPropertyName = null, bool descending = false)
{
try
{
if (champion == null) throw new ArgumentNullException(nameof(champion), "Champion is null");
// Build the query string with the specified parameters
string queryString = $"?champion={champion.Name}&index={index}&count={count}";
if (!string.IsNullOrEmpty(orderingPropertyName)) queryString += $"&orderingPropertyName={orderingPropertyName}&descending={descending}";
var response = await parent.HttpClient.GetAsync($"/skins{queryString}");
if (response.IsSuccessStatusCode)
{
IEnumerable<SkinDto> skins = await response.Content.ReadFromJsonAsync<IEnumerable<SkinDto>>();
IEnumerable<Skin> res = skins.Select(s => s.ToModel());
return res;
}
else
{
// Log the error status code and reason phrase
Console.WriteLine($"Failed to get items by champion. Status code: {response.StatusCode}. Reason: {response.ReasonPhrase}");
return null;
}
}
catch (HttpRequestException ex)
{
// Log the error message from the HttpClient exception
Console.WriteLine($"Failed to get items by champion. {ex.Message}");
return null;
}
catch (JsonException ex)
{
// Log the error message from the JSON serialization exception
Console.WriteLine($"Failed to get items by champion. Error while deserializing JSON data. {ex.Message}");
return null;
}
catch (Exception ex)
{
// Log any other exceptions that may occur
Console.WriteLine($"Failed to get items by champion. {ex.Message}");
return null;
}
}
public Task<IEnumerable<Skin?>> GetItemsByName(string substring, int index, int count, string? orderingPropertyName = null, bool descending = false)
{
throw new NotImplementedException();
}
public Task<int> GetNbItems()
{
throw new NotImplementedException();
}
public Task<int> GetNbItemsByChampion(Champion? champion)
{
throw new NotImplementedException();
}
public Task<int> GetNbItemsByName(string substring)
{
throw new NotImplementedException();
}
public Task<Skin?> UpdateItem(Skin? oldItem, Skin? newItem)
{
throw new NotImplementedException();
}
}
}
}

@ -0,0 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<Folder Include="Mapper\" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\DTO\DTO.csproj" />
<ProjectReference Include="..\Entities\Entities.csproj" />
<ProjectReference Include="..\Model\Model.csproj" />
</ItemGroup>
</Project>

@ -0,0 +1,113 @@
using DTO;
using Entities;
using Model;
namespace ApiMappeur
{
public static class ChampionMapper
{
public static ChampionDTO ToDTO(this Champion item)
{
return new ChampionDTO()
{
Icon = item.Icon,
Name = item.Name,
Bio = item.Bio,
Class = item.Class
};
}
public static ChampionEntity ToEntity(this Champion item)
{
return new()
{
Name = item.Name,
Bio = item.Bio,
Icon = item.Icon,
Class = item.Class,
Image = new() { Base64 = item.Image.Base64 },
};
}
public static ChampionFullDTO toFullDTO(this Champion item)
{
if (item == null)
{
var message = string.Format("Champion is null cannot null it");
throw new Exception(message);
}
return new ChampionFullDTO()
{
Name = item.Name,
Characteristics = item.Characteristics,
Bio = item.Bio,
Skills = item.Skills,
Class = item.Class,
Skins = item.Skins.Select(i => i.ToDto()),
LargeImage = item.Image.ToDTO(),
Icon = item.Icon,
};
}
public static Champion ToModel(this ChampionFullDTO dto)
{
if (dto == null)
{
var message = string.Format("Champion cannot be empty");
throw new Exception(message);
}
var champion = new Champion(dto.Name, dto.Class, dto.Icon,dto?.LargeImage?.base64 ?? "", dto.Bio);
champion.AddCharacteristics(dto.Characteristics?.Select(kv => Tuple.Create(kv.Key, kv.Value)).ToArray() ?? Array.Empty<Tuple<string, int>>());
if (dto.Skills != null)
{
foreach (var skill in dto.Skills)
{
champion.AddSkill(skill);
}
}
/* if (dto.Skins != null)
{
foreach (var skinDto in dto.Skins)
{
var skin = new Skin(skinDto.Name, dto.ToModel());
champion.AddSkin(skin);
}
}*/
return champion;
}
public static Champion ToModel(this ChampionDTO dto)
{
if (dto == null)
{
var message = string.Format("Champion cannot be empty");
/*throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, message));
*/
throw new Exception(message);
}
return new Champion(dto.Name, dto.Class, dto.Icon)
{
Bio = dto.Bio
};
}
public static Champion ToModel(this ChampionEntity entity)
{
return new(entity.Name, entity.Class, entity.Icon, entity.Image.Base64, entity.Bio);
}
}
}

@ -1,7 +1,7 @@
using DTO;
using Model;
namespace API_LoL_Project.Mapper
namespace ApiMappeur
{
public static class ImageMappeur
{
@ -15,7 +15,7 @@ namespace API_LoL_Project.Mapper
}
return new ImageDTO()
{
base64 = item.Base64
base64 = item?.Base64 ?? ""
};
}

@ -0,0 +1,37 @@
 using DTO;
using Model;
using System.Text;
using Rune = Model.Rune;
namespace ApiMappeur
{
public static class RuneMapper
{
public static RuneDTO ToDTO(this Rune item)
{
return new RuneDTO
{
Name = item.Name,
Description = item.Description,
Family = item.Family,
Icon = item.Icon,
Image = item.Image
};
}
public static Rune ToModel(this RuneDTO dto)
{
/*if (dto == null)
{
*//* var message = string.Format("Champion with name = {} not found", dto.Name);
throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, message));*//*
}*/
return new Rune(dto.Name, dto.Family, dto.Icon, dto.Image.Base64, dto.Description);
}
}
}

@ -0,0 +1,77 @@
using DTO;
using Shared;
using Rune = Model.Rune;
using Model;
namespace ApiMappeur
{
/* public static class RunePageMappeur
{
public static RunePageDTO ToDto(this RunePage runePage)
{
var runePageDTO = new RunePageDTO
{
Name = runePage.Name,
Runes = new Dictionary<Category, RuneDTO>()
};
foreach (var runeCategory in Enum.GetValues(typeof(Category)).Cast<Category>())
{
var rune = runePage[runeCategory];
if (rune != null)
{
runePageDTO.Runes[runeCategory] = rune.ToDTO();
}
}
return runePageDTO;
}
public static RunePage ToModel(this RunePageDTO runePageDto)
{
var entity = new RunePage(runePageDto.Name);
foreach (var kvp in runePageDto.Runes)
{
var category = kvp.Key;
var runeDTO = kvp.Value;
var rune = new Rune(runeDTO.Name, runeDTO.Family, runeDTO.Icon, runeDTO.Image.Base64, runeDTO.Description);
entity[category] = rune;
}
return entity;}
}*/
public static class RunePageMappeur
{
public static RunePageDTO ToDto(this RunePage runePage)
{
return new RunePageDTO()
{
Name = runePage.Name,
Runes = runePage.Runes.ToDictionary(c => c.Key.ToString(), r => r.Value.ToDTO())
};
}
public static RunePage ToModel(this RunePageDTO runePageDto)
{
Category category;
Dictionary<Category, Rune> runDico = runePageDto.Runes.ToDictionary(
r => (Category)Enum.Parse(typeof(Category), r.Key),
r => r.Value.ToModel()
);
var runePage = new RunePage(runePageDto.Name);
foreach (var rune in runePageDto.Runes)
{
if (!Enum.TryParse<Category>(rune.Key, true, out category))
{
continue;
}
runePage[category] = rune.Value.ToModel();
}
return runePage;
}
}
}

@ -2,14 +2,10 @@
using Entities;
using Model;
namespace API_LoL_Project.Mapper
namespace ApiMappeur
{
public static class SkinMapper
{
public static SkinEntity ToEntity(this Skin item)
{
throw new NotImplementedException();
}
public static Skin ToModel(this SkinEntity entity)
@ -22,12 +18,19 @@ namespace API_LoL_Project.Mapper
return new SkinDto()
{
Name = item.Name,
LargeImage = item.Image.ToDTO(),
Description = item.Description,
Icon = item.Icon,
Price = item.Price
Price = item.Price,
};
}
public static Skin ToModel(this SkinDto item)
{
var image = item?.LargeImage?.base64 ?? "";
return new(item?.Name ?? "", null, item?.Price ?? -1, image, item?.Description ?? "");
}
}
}

@ -7,8 +7,8 @@
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\API_LoL_Project\API_LoL_Project.csproj" />
<ProjectReference Include="..\Entities\Entities.csproj" />
<ProjectReference Include="..\EntityMappers\EntityMappers.csproj" />
<ProjectReference Include="..\Model\Model.csproj" />
</ItemGroup>

@ -1,7 +1,8 @@
using API_LoL_Project.Mapper;
using EntityMapper;
using Microsoft.EntityFrameworkCore;
using Model;
using Shared;
using System.Data.SqlTypes;
using System.Diagnostics;
namespace Business
{
@ -16,19 +17,27 @@ namespace Business
public async Task<Champion?> AddItem(Champion? item)
{
await parent.DbContext.champions.AddAsync(item.ToEntity());
await parent.DbContext.champions.AddAsync(item.ToEntity(parent.DbContext));
parent.DbContext.SaveChanges();
return item;
}
public async Task<bool> DeleteItem(Champion? item)
{
parent.DbContext.champions.Remove(item.ToEntity());
return true;
var toDelete = parent.DbContext.champions.Find(item.Name);
if (toDelete!=null)
{
parent.DbContext.champions.Remove(toDelete);
parent.DbContext.SaveChanges();
return true;
}
return false;
}
public async Task<IEnumerable<Champion?>> GetItems(int index, int count, string? orderingPropertyName = null, bool descending = false)
{
return parent.DbContext.champions.GetItemsWithFilterAndOrdering(
Console.WriteLine("GET");
return parent.DbContext.champions.Include("Skills").Include("Characteristics").GetItemsWithFilterAndOrdering(
c => true,
index, count,
orderingPropertyName, descending).Select(c => c.ToModel());
@ -37,7 +46,7 @@ namespace Business
public async Task<IEnumerable<Champion?>> GetItemsByCharacteristic(string charName, int index, int count, string? orderingPropertyName = null, bool descending = false)
{
return parent.DbContext.champions.GetItemsWithFilterAndOrdering(
return parent.DbContext.champions.Include("Skills").Include("Characteristics").GetItemsWithFilterAndOrdering(
c => c.Characteristics.Any(ch => ch.Name.Equals(charName)),
index, count,
orderingPropertyName, descending).Select(c => c.ToModel());
@ -45,7 +54,7 @@ namespace Business
public async Task<IEnumerable<Champion?>> GetItemsByClass(ChampionClass championClass, int index, int count, string? orderingPropertyName = null, bool descending = false)
{
return parent.DbContext.champions.GetItemsWithFilterAndOrdering(
return parent.DbContext.champions.Include("Skills").Include("Characteristics").GetItemsWithFilterAndOrdering(
c => c.Class.Equals(championClass),
index, count,
orderingPropertyName, descending).Select(c => c.ToModel());
@ -53,7 +62,7 @@ namespace Business
public async Task<IEnumerable<Champion?>> GetItemsByName(string substring, int index, int count, string? orderingPropertyName = null, bool descending = false)
{
return parent.DbContext.champions.GetItemsWithFilterAndOrdering(
return parent.DbContext.champions.Include("Skills").Include("Characteristics").GetItemsWithFilterAndOrdering(
c => c.Name.Contains(substring),
index, count,
orderingPropertyName, descending).Select(c => c.ToModel());
@ -62,8 +71,8 @@ namespace Business
public async Task<IEnumerable<Champion?>> GetItemsByRunePage(RunePage? runePage, int index, int count, string? orderingPropertyName = null, bool descending = false)
{
return parent.DbContext.champions.GetItemsWithFilterAndOrdering(
c => c.runepages.Any(rp => rp.Equals(runePage.ToEntity())),
return parent.DbContext.champions.Include("Skills").Include("Characteristics").Include("runepages").GetItemsWithFilterAndOrdering(
c => c.runepages.Any(rp => rp.Equals(runePage.ToEntity(parent.DbContext))),
index, count,
orderingPropertyName, descending).Select(c => c.ToModel());
@ -71,7 +80,7 @@ namespace Business
public async Task<IEnumerable<Champion?>> GetItemsBySkill(Skill? skill, int index, int count, string? orderingPropertyName = null, bool descending = false)
{
return parent.DbContext.champions.GetItemsWithFilterAndOrdering(
return parent.DbContext.champions.Include("Skills").Include("Characteristics").GetItemsWithFilterAndOrdering(
c => skill != null && c.Skills.Any(s => s.Name.Equals(skill.Name)),
index, count,
orderingPropertyName, descending).Select(c => c.ToModel());
@ -79,7 +88,7 @@ namespace Business
public async Task<IEnumerable<Champion?>> GetItemsBySkill(string skill, int index, int count, string? orderingPropertyName = null, bool descending = false)
{
return parent.DbContext.champions.GetItemsWithFilterAndOrdering(
return parent.DbContext.champions.Include("Skills").Include("Characteristics").Include("Skills").GetItemsWithFilterAndOrdering(
c => skill != null && c.Skills.Any(s => s.Name.Equals(skill)),
index, count,
orderingPropertyName, descending).Select(c => c.ToModel());
@ -109,7 +118,7 @@ namespace Business
public async Task<int> GetNbItemsByRunePage(RunePage? runePage)
{
return parent.DbContext.champions.Where(c => c.runepages.Any(rp => rp.Equals(runePage.ToEntity()))).Count();
return parent.DbContext.champions.Where(c => c.runepages.Any(rp => rp.Equals(runePage.ToEntity(parent.DbContext)))).Count();
}
@ -127,8 +136,9 @@ namespace Business
public async Task<Champion?> UpdateItem(Champion? oldItem, Champion? newItem)
{
parent.DbContext.champions.Remove(oldItem.ToEntity());
parent.DbContext.champions.Add(newItem.ToEntity());
var toUpdate = parent.DbContext.champions.Find(oldItem.Name);
toUpdate = newItem.ToEntity(parent.DbContext);
parent.DbContext.SaveChanges();
return newItem;
}
}

@ -1,7 +1,7 @@
using API_LoL_Project.Mapper;
using Entities;
using EntityMapper;
using Microsoft.EntityFrameworkCore;
using Model;
using System.Data.SqlTypes;
using System.Linq;
namespace Business
{
@ -16,46 +16,53 @@ namespace Business
public async Task<RunePage?> AddItem(RunePage? item)
{
await parent.DbContext.runepages.AddAsync(item.ToEntity());
await parent.DbContext.runepages.AddAsync(item.ToEntity(parent.DbContext));
parent.DbContext.SaveChanges();
return item;
}
public async Task<bool> DeleteItem(RunePage? item)
{
parent.DbContext.runepages.Remove(item.ToEntity());
return true;
var toDelete = parent.DbContext.runepages.Find(item.Name);
if (toDelete != null)
{
parent.DbContext.runepages.Remove(toDelete);
parent.DbContext.SaveChanges();
return true;
}
return false;
}
public async Task<IEnumerable<RunePage?>> GetItems(int index, int count, string? orderingPropertyName = null, bool descending = false)
{
return parent.DbContext.runepages.GetItemsWithFilterAndOrdering(
return parent.DbContext.runepages.Include("entries").GetItemsWithFilterAndOrdering(
rp => true,
index, count,
orderingPropertyName, descending).Select(rp => rp.ToModel());
orderingPropertyName, descending).Select(rp => rp.ToModel(parent.DbContext));
}
public async Task<IEnumerable<RunePage?>> GetItemsByChampion(Champion? champion, int index, int count, string? orderingPropertyName = null, bool descending = false)
{
return parent.DbContext.runepages.GetItemsWithFilterAndOrdering(
return parent.DbContext.runepages.Include("champions").GetItemsWithFilterAndOrdering(
rp => rp.champions.Any(c => c.Name.Equals(champion.Name)),
index, count,
orderingPropertyName, descending).Select(rp => rp.ToModel());
orderingPropertyName, descending).Select(rp => rp.ToModel(parent.DbContext));
}
public async Task<IEnumerable<RunePage?>> GetItemsByName(string substring, int index, int count, string? orderingPropertyName = null, bool descending = false)
{
return parent.DbContext.runepages.GetItemsWithFilterAndOrdering(
return parent.DbContext.runepages.Include("entries").GetItemsWithFilterAndOrdering(
rp => rp.Name.Contains(substring),
index, count,
orderingPropertyName, descending).Select(rp => rp.ToModel());
orderingPropertyName, descending).Select(rp => rp.ToModel(parent.DbContext));
}
public async Task<IEnumerable<RunePage?>> GetItemsByRune(Rune? rune, int index, int count, string? orderingPropertyName = null, bool descending = false)
{
return parent.DbContext.runepages.GetItemsWithFilterAndOrdering(
rp => rp.runes.Any(r => r.Name.Equals(rune.Name)),
return parent.DbContext.runepages.Include("entries").GetItemsWithFilterAndOrdering(
rp => rp.entries.Any(r => r.RuneName.Equals(rune.Name)),
index, count,
orderingPropertyName, descending).Select(rp => rp.ToModel());
orderingPropertyName, descending).Select(rp => rp.ToModel(parent.DbContext));
}
public async Task<int> GetNbItems()
@ -77,14 +84,23 @@ namespace Business
public async Task<int> GetNbItemsByRune(Model.Rune? rune)
{
return parent.DbContext.runepages.Where(rp => rp.runes.Any(r => r.Name.Equals(rune.Name))).Count();
return parent.DbContext.runepages.Where(rp => rp.entries.Any(r => r.RuneName.Equals(rune.Name))).Count();
}
public async Task<RunePage?> UpdateItem(RunePage? oldItem, RunePage? newItem)
{
parent.DbContext.runepages.Remove(oldItem.ToEntity());
parent.DbContext.runepages.Add(newItem.ToEntity());
var toUpdate = parent.DbContext.runepages.Include("entries")
.Where(x => x.Name.Equals(newItem.Name)).First();
toUpdate.entries = newItem.Runes.Select(r => new RunePageRuneEntity()
{
category = r.Key,
rune = r.Value.ToEntity(parent.DbContext),
}).ToList();
parent.DbContext.SaveChanges();
return newItem;
}
}
}

@ -1,5 +1,5 @@
using API_LoL_Project.Mapper;
using API_LoL_Project.Mapper.API_LoL_Project.Mapper;
using EntityMapper;
using Microsoft.EntityFrameworkCore;
using Model;
using Shared;
@ -15,14 +15,21 @@ namespace Business
=> this.parent = parent;
public async Task<Rune?> AddItem(Rune? item)
{
await parent.DbContext.runes.AddAsync(item.ToEntity());
await parent.DbContext.runes.AddAsync(item.ToEntity(parent.DbContext));
parent.DbContext.SaveChanges();
return item;
}
public async Task<bool> DeleteItem(Rune? item)
{
parent.DbContext.runes.Remove(item.ToEntity());
return true;
var toDelete = parent.DbContext.runes.Find(item?.Name);
if (toDelete != null)
{
parent.DbContext.runes.Remove(item?.ToEntity(parent.DbContext));
parent.DbContext.SaveChanges();
return true;
}
return false;
}
public async Task<IEnumerable<Rune?>> GetItems(int index, int count, string? orderingPropertyName = null, bool descending = false)
@ -66,8 +73,11 @@ namespace Business
public async Task<Rune?> UpdateItem(Rune? oldItem, Rune? newItem)
{
parent.DbContext.runes.Remove(oldItem.ToEntity());
parent.DbContext.runes.Add(newItem.ToEntity());
var toUpdate = parent.DbContext.runes.Find(oldItem.Name);
toUpdate.Description = newItem.Description;
toUpdate.RuneFamily = newItem.Family;
parent.DbContext.SaveChanges();
return newItem;
}
}

@ -1,7 +1,6 @@
using API_LoL_Project.Mapper;
using API_LoL_Project.Mapper.API_LoL_Project.Mapper;
using EntityMapper;
using Microsoft.EntityFrameworkCore;
using Model;
using System.Data.SqlTypes;
namespace Business
{
@ -16,35 +15,38 @@ namespace Business
public async Task<Skin?> AddItem(Skin? item)
{
await parent.DbContext.skins.AddAsync(item.ToEntity());
await parent.DbContext.skins.AddAsync(item.ToEntity(parent.DbContext));
parent.DbContext.SaveChanges();
return item;
}
public async Task<bool> DeleteItem(Skin? item)
{
parent.DbContext.skins.Remove(item.ToEntity());
var toDelete = parent.DbContext.skins.Find(item.Name);
parent.DbContext.skins.Remove(toDelete);
parent.DbContext.SaveChanges();
return true;
}
public async Task<IEnumerable<Skin?>> GetItems(int index, int count, string? orderingPropertyName = null, bool descending = false)
{
return parent.DbContext.skins.GetItemsWithFilterAndOrdering(
return parent.DbContext.skins.Include("Champion").GetItemsWithFilterAndOrdering(
s => true,
index, count,
orderingPropertyName, descending).Select(s => s.ToModel());
orderingPropertyName, descending).Select(s => s?.ToModel());
}
public async Task<IEnumerable<Skin?>> GetItemsByChampion(Champion? champion, int index, int count, string? orderingPropertyName = null, bool descending = false)
{
return parent.DbContext.skins.GetItemsWithFilterAndOrdering(
s => s.Champion.Name.Equals(champion.Name),
return parent.DbContext.skins.Include("Champion").GetItemsWithFilterAndOrdering(
s => s.Champion.Name.Equals(champion?.Name),
index, count,
orderingPropertyName, descending).Select(s => s.ToModel());
orderingPropertyName, descending).Select(s => s?.ToModel());
}
public async Task<IEnumerable<Skin?>> GetItemsByName(string substring, int index, int count, string? orderingPropertyName = null, bool descending = false)
{
return parent.DbContext.skins.GetItemsWithFilterAndOrdering(
return parent.DbContext.skins.Include("Champion").GetItemsWithFilterAndOrdering(
s => s.Name.Contains(substring),
index, count,
orderingPropertyName, descending).Select(s => s.ToModel());
@ -57,8 +59,12 @@ namespace Business
public async Task<int> GetNbItemsByChampion(Champion? champion)
{
return parent.DbContext.skins.Where(s => s.Champion.Name.Equals(champion.Name))
.Count();
if (champion != null)
{
return parent.DbContext.skins.Where(s => s.Champion.Name.Equals(champion.Name))
.Count();
}
return 0;
}
public async Task<int> GetNbItemsByName(string substring)
@ -69,10 +75,11 @@ namespace Business
public async Task<Skin?> UpdateItem(Skin? oldItem, Skin? newItem)
{
parent.DbContext.skins.Remove(oldItem.ToEntity());
parent.DbContext.skins.Add(newItem.ToEntity());
var toUpdate = parent.DbContext.skins.Find(oldItem.Name);
toUpdate.Champion = parent.DbContext.champions.Find(newItem.Champion.Name);
return newItem;
}
}
}
}

@ -6,7 +6,6 @@ namespace Business
{
public partial class DbData : IDataManager
{
public DbData(LolDbContext dbContext)
{
DbContext = dbContext;
@ -15,6 +14,7 @@ namespace Business
RunesMgr = new RunesManager(this);
RunePagesMgr = new RunePagesManager(this);
}
protected LolDbContext DbContext{ get; }
public IChampionsManager ChampionsMgr { get; }

@ -1,31 +1,47 @@
using Model;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;
using Model;
using Shared;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;
using System.Text.Json.Serialization;
using static System.Net.Mime.MediaTypeNames;
namespace DTO
{
public class ChampionDTO
{
public string Name { get; set; }
public string Bio { get; set; }
public string Icon { get; set; }
/*public string Icon { get; set; }
*/
public string Bio { get; set; }
public string Icon { get; set; }
public ChampionClass Class { get; set; }
}
public class ChampionFullDTO
{
/*[Required(ErrorMessage = "Name is required")]
[StringLength(60, ErrorMessage = "Name can't be longer than 60 characters")]*/
[JsonPropertyName("characteristics")]
public ReadOnlyDictionary<string, int> Characteristics { get; set; }
[JsonPropertyName("name")]
public string Name { get; set; }
[JsonPropertyName("bio")]
public string Bio { get; set; }
public ReadOnlyDictionary<string, int> Characteristics { get; set; }
[JsonPropertyName("class")]
public ChampionClass Class { get; set; }
[JsonPropertyName("icon")]
public string Icon { get; set; }
[JsonPropertyName("largeImage")]
public ImageDTO LargeImage { get; set; }
public IEnumerable<SkinDto> skins { get; set; }
public IEnumerable<Skill> skills { get; set; }
[JsonPropertyName("skins")]
public IEnumerable<SkinDto> Skins { get; set; }
[JsonPropertyName("skills")]
public IEnumerable<Skill> Skills { get; set; }
}
}

@ -0,0 +1,15 @@
using Shared;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DTO
{
public class RunePageDTO
{
public string Name { get; set; }
public Dictionary<string, RuneDTO> Runes { get; set; }
}
}

@ -8,7 +8,9 @@ namespace DTO
{
public class SkillDto
{
public string Name { get; set; }
/* public SkillDtoType type { get; set; }
*/ public string Name { get; set; }
public string Description { get; set; }
}
}

@ -0,0 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DTO
{
public class SkillDtoType
{
}
}

@ -8,10 +8,25 @@ namespace DTO
{
public class SkinDto
{
/* public string Champion { get; set; }
*/ public string Name { get; set; }
public string Description { get; set; }
public string Icon { get; set; }
public float Price { get; set; }
public ImageDTO LargeImage { get; set; }
}
public class SkinFullDto
{
public string Champion { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Icon { get; set; }
public float Price { get; set; }
public ImageDTO LargeImage { get; set; }
}
}

@ -13,7 +13,8 @@ namespace Entities
[Required]
[MaxLength(500)]
public string Bio { get; set; }
public string? Icon { get; set; }
public string Icon { get; set; }
[Required]
public ChampionClass Class { get; set;}
public virtual ICollection<SkillEntity> Skills { get; set; }

@ -1,4 +1,5 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Shared;
using System.Reflection.Metadata;
using System.Security.Claims;
@ -15,11 +16,15 @@ namespace Entities
public DbSet<RuneEntity> runes { get; set; }
public DbSet<RunePageEntity> runepages { get; set; }
public DbSet<LargeImageEntity> largeimages { get; set; }
public DbSet<RunePageRuneEntity> runepagerunes { get; set; }
public LolDbContext(DbContextOptions configuration) : base(configuration){}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite($"Data Source=Entities.Champions.db");
if (!optionsBuilder.IsConfigured) {
Console.WriteLine("!IsConfigured...");
optionsBuilder.UseSqlite($"Data Source=Entities.Champions.db");
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
@ -27,118 +32,15 @@ namespace Entities
modelBuilder.Entity<LargeImageEntity>().Property(e => e.Id).ValueGeneratedOnAdd();
modelBuilder.Entity<CharacteristicEntity>().HasKey(c => new { c.Name, c.ChampionForeignKey });
modelBuilder.Entity<RunePageRuneEntity>().HasKey(c => new { c.RunePageName, c.RuneName });
modelBuilder.Entity<RunePageEntity>().Property(e => e.Id).ValueGeneratedOnAdd();
modelBuilder.Entity<RunePageEntity>()
.HasMany(x => x.runes)
.WithMany(x => x.runepages)
.UsingEntity<RunePageRuneEntity>();
//modelBuilder.Entity<RunePageEntity>().Property(e => e.Id).ValueGeneratedOnAdd();
modelBuilder.Entity<ChampionEntity>()
.HasMany(x => x.runepages)
.WithMany(x => x.champions);
modelBuilder.Entity<LargeImageEntity>().HasData(new List<LargeImageEntity>()
{
new()
{
Id = Guid.NewGuid(),
Base64 = "aaa"
}
});
modelBuilder.Entity<ChampionEntity>().HasData(new List<ChampionEntity>() {
new()
{
Name = "Dave",
Bio = "Le meilleur Jazzman de France",
Class = ChampionClass.Fighter,
},
new()
{
Name = "Armure",
Bio = "Solide",
Class = ChampionClass.Tank,
}
});
modelBuilder.Entity<CharacteristicEntity>().HasData(new List<CharacteristicEntity>() {
new()
{
Name = "Force",
Value = 50,
ChampionForeignKey = "Dave",
},
new()
{
Name = "Défense",
Value = 75,
ChampionForeignKey = "Armure",
}
});
modelBuilder.Entity<SkinEntity>().HasData(new List<SkinEntity>() {
new SkinEntity
{
Name = "Dave de glace",
Description = "Enneigé",
Icon = "aaa",
ChampionForeignKey = "Dave",
Price=7.99F
},
new SkinEntity
{
Name = "Armure Fullspeed",
Description = "Deja vu",
Icon = "aaa",
ChampionForeignKey = "Armure",
Price=9.99F
},
});
modelBuilder.Entity<SkillEntity>().HasData(new List<SkillEntity>() {
new()
{
Name = "Boule de feu",
Description = "Fire!",
SkillType = SkillType.Basic
},
new()
{
Name = "White Star",
Description = "Random damage",
SkillType = SkillType.Ultimate
}
});
modelBuilder.Entity<RunePageEntity>().HasData(new List<RunePageEntity>()
{
new()
{
Id = Guid.NewGuid(),
Name="Runepage_1"
}
});
modelBuilder.Entity<RuneEntity>().HasData(new List<RuneEntity>() {
new()
{
Name = "Bullseye",
Description = "Steady shot",
RuneFamily = RuneFamily.Precision
},
new()
{
Name = "Alkatraz",
Description = "Lock effect",
RuneFamily = RuneFamily.Domination
}
});
}
}
internal record NewRecord(string Name, string Item);
}

@ -0,0 +1,121 @@
using Microsoft.EntityFrameworkCore;
using Shared;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Entities
{
internal class LolDbContextWithStub : LolDbContext
{
public LolDbContextWithStub(DbContextOptions configuration) : base(configuration)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<LargeImageEntity>().HasData(new List<LargeImageEntity>()
{
new()
{
Id = Guid.NewGuid(),
Base64 = "aaa"
}
});
modelBuilder.Entity<ChampionEntity>().HasData(new List<ChampionEntity>() {
new()
{
Name = "Dave",
Bio = "Le meilleur Jazzman de France",
Class = ChampionClass.Fighter,
},
new()
{
Name = "Armure",
Bio = "Solide",
Class = ChampionClass.Tank,
}
});
modelBuilder.Entity<CharacteristicEntity>().HasData(new List<CharacteristicEntity>() {
new()
{
Name = "Force",
Value = 50,
ChampionForeignKey = "Dave",
},
new()
{
Name = "Défense",
Value = 75,
ChampionForeignKey = "Armure",
}
});
modelBuilder.Entity<SkinEntity>().HasData(new List<SkinEntity>() {
new SkinEntity
{
Name = "Dave de glace",
Description = "Enneigé",
Icon = "aaa",
ChampionForeignKey = "Dave",
Price=7.99F
},
new SkinEntity
{
Name = "Armure Fullspeed",
Description = "Deja vu",
Icon = "aaa",
ChampionForeignKey = "Armure",
Price=9.99F
},
});
modelBuilder.Entity<SkillEntity>().HasData(new List<SkillEntity>() {
new()
{
Name = "Boule de feu",
Description = "Fire!",
SkillType = SkillType.Basic
},
new()
{
Name = "White Star",
Description = "Random damage",
SkillType = SkillType.Ultimate
}
});
modelBuilder.Entity<RunePageEntity>().HasData(new List<RunePageEntity>()
{
new()
{
//Id = Guid.NewGuid(),
Name="Runepage_1"
}
});
modelBuilder.Entity<RuneEntity>().HasData(new List<RuneEntity>() {
new()
{
Name = "Bullseye",
Description = "Steady shot",
RuneFamily = RuneFamily.Precision
},
new()
{
Name = "Alkatraz",
Description = "Lock effect",
RuneFamily = RuneFamily.Domination
}
});
}
}
}

@ -1,411 +0,0 @@
// <auto-generated />
using System;
using Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace Entities.Migrations
{
[DbContext(typeof(LolDbContext))]
[Migration("20230301162639_myFirstMigration")]
partial class myFirstMigration
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "7.0.2");
modelBuilder.Entity("ChampionEntityRunePageEntity", b =>
{
b.Property<string>("championsName")
.HasColumnType("TEXT");
b.Property<Guid>("runepagesId")
.HasColumnType("TEXT");
b.HasKey("championsName", "runepagesId");
b.HasIndex("runepagesId");
b.ToTable("ChampionEntityRunePageEntity");
});
modelBuilder.Entity("ChampionEntitySkillEntity", b =>
{
b.Property<string>("ChampionsName")
.HasColumnType("TEXT");
b.Property<string>("SkillsName")
.HasColumnType("TEXT");
b.HasKey("ChampionsName", "SkillsName");
b.HasIndex("SkillsName");
b.ToTable("ChampionEntitySkillEntity");
});
modelBuilder.Entity("Entities.ChampionEntity", b =>
{
b.Property<string>("Name")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.Property<string>("Bio")
.IsRequired()
.HasMaxLength(500)
.HasColumnType("TEXT");
b.Property<int>("Class")
.HasColumnType("INTEGER");
b.Property<string>("Icon")
.HasColumnType("TEXT");
b.Property<Guid?>("ImageId")
.HasColumnType("TEXT");
b.HasKey("Name");
b.HasIndex("ImageId");
b.ToTable("champions");
b.HasData(
new
{
Name = "Dave",
Bio = "Le meilleur Jazzman de France",
Class = 2
},
new
{
Name = "Armure",
Bio = "Solide",
Class = 6
});
});
modelBuilder.Entity("Entities.CharacteristicEntity", b =>
{
b.Property<string>("Name")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.Property<string>("ChampionForeignKey")
.HasColumnType("TEXT");
b.Property<int>("Value")
.HasColumnType("INTEGER");
b.HasKey("Name", "ChampionForeignKey");
b.HasIndex("ChampionForeignKey");
b.ToTable("characteristics");
b.HasData(
new
{
Name = "Force",
ChampionForeignKey = "Dave",
Value = 50
},
new
{
Name = "Défense",
ChampionForeignKey = "Armure",
Value = 75
});
});
modelBuilder.Entity("Entities.LargeImageEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("Base64")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("Id");
b.ToTable("largeimages");
b.HasData(
new
{
Id = new Guid("d3a490c6-fb49-475a-9134-47c2de9888d2"),
Base64 = "aaa"
});
});
modelBuilder.Entity("Entities.RuneEntity", b =>
{
b.Property<string>("Name")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.Property<string>("Description")
.IsRequired()
.HasMaxLength(500)
.HasColumnType("TEXT");
b.Property<Guid?>("ImageId")
.HasColumnType("TEXT");
b.Property<int>("RuneFamily")
.HasColumnType("INTEGER");
b.HasKey("Name");
b.HasIndex("ImageId");
b.ToTable("runes");
b.HasData(
new
{
Name = "Bullseye",
Description = "Steady shot",
RuneFamily = 1
},
new
{
Name = "Alkatraz",
Description = "Lock effect",
RuneFamily = 2
});
});
modelBuilder.Entity("Entities.RunePageEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(256)
.HasColumnType("TEXT");
b.HasKey("Id");
b.ToTable("runepages");
b.HasData(
new
{
Id = new Guid("4ea04d4f-0a64-4d28-8d74-4499dbc541f2"),
Name = "Runepage_1"
});
});
modelBuilder.Entity("Entities.RunePageRuneEntity", b =>
{
b.Property<Guid>("runepagesId")
.HasColumnType("TEXT");
b.Property<string>("runesName")
.HasColumnType("TEXT");
b.Property<int>("Category")
.HasColumnType("INTEGER");
b.HasKey("runepagesId", "runesName");
b.HasIndex("runesName");
b.ToTable("RunePageRuneEntity");
});
modelBuilder.Entity("Entities.SkillEntity", b =>
{
b.Property<string>("Name")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.Property<string>("Description")
.IsRequired()
.HasMaxLength(500)
.HasColumnType("TEXT");
b.Property<int>("SkillType")
.HasColumnType("INTEGER");
b.HasKey("Name");
b.ToTable("skills");
b.HasData(
new
{
Name = "Boule de feu",
Description = "Fire!",
SkillType = 1
},
new
{
Name = "White Star",
Description = "Random damage",
SkillType = 3
});
});
modelBuilder.Entity("Entities.SkinEntity", b =>
{
b.Property<string>("Name")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.Property<string>("ChampionForeignKey")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("Description")
.IsRequired()
.HasMaxLength(500)
.HasColumnType("TEXT");
b.Property<string>("Icon")
.IsRequired()
.HasColumnType("TEXT");
b.Property<Guid?>("ImageId")
.HasColumnType("TEXT");
b.Property<float>("Price")
.HasColumnType("REAL");
b.HasKey("Name");
b.HasIndex("ChampionForeignKey");
b.HasIndex("ImageId");
b.ToTable("skins");
b.HasData(
new
{
Name = "Dave de glace",
ChampionForeignKey = "Dave",
Description = "Enneigé",
Icon = "aaa",
Price = 7.99f
},
new
{
Name = "Armure Fullspeed",
ChampionForeignKey = "Armure",
Description = "Deja vu",
Icon = "aaa",
Price = 9.99f
});
});
modelBuilder.Entity("ChampionEntityRunePageEntity", b =>
{
b.HasOne("Entities.ChampionEntity", null)
.WithMany()
.HasForeignKey("championsName")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Entities.RunePageEntity", null)
.WithMany()
.HasForeignKey("runepagesId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("ChampionEntitySkillEntity", b =>
{
b.HasOne("Entities.ChampionEntity", null)
.WithMany()
.HasForeignKey("ChampionsName")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Entities.SkillEntity", null)
.WithMany()
.HasForeignKey("SkillsName")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Entities.ChampionEntity", b =>
{
b.HasOne("Entities.LargeImageEntity", "Image")
.WithMany()
.HasForeignKey("ImageId");
b.Navigation("Image");
});
modelBuilder.Entity("Entities.CharacteristicEntity", b =>
{
b.HasOne("Entities.ChampionEntity", "Champion")
.WithMany("Characteristics")
.HasForeignKey("ChampionForeignKey")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Champion");
});
modelBuilder.Entity("Entities.RuneEntity", b =>
{
b.HasOne("Entities.LargeImageEntity", "Image")
.WithMany()
.HasForeignKey("ImageId");
b.Navigation("Image");
});
modelBuilder.Entity("Entities.RunePageRuneEntity", b =>
{
b.HasOne("Entities.RunePageEntity", null)
.WithMany()
.HasForeignKey("runepagesId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Entities.RuneEntity", null)
.WithMany()
.HasForeignKey("runesName")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Entities.SkinEntity", b =>
{
b.HasOne("Entities.ChampionEntity", "Champion")
.WithMany()
.HasForeignKey("ChampionForeignKey")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Entities.LargeImageEntity", "Image")
.WithMany()
.HasForeignKey("ImageId");
b.Navigation("Champion");
b.Navigation("Image");
});
modelBuilder.Entity("Entities.ChampionEntity", b =>
{
b.Navigation("Characteristics");
});
#pragma warning restore 612, 618
}
}
}

@ -1,341 +0,0 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
#pragma warning disable CA1814 // Prefer jagged arrays over multidimensional
namespace Entities.Migrations
{
/// <inheritdoc />
public partial class myFirstMigration : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "largeimages",
columns: table => new
{
Id = table.Column<Guid>(type: "TEXT", nullable: false),
Base64 = table.Column<string>(type: "TEXT", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_largeimages", x => x.Id);
});
migrationBuilder.CreateTable(
name: "runepages",
columns: table => new
{
Id = table.Column<Guid>(type: "TEXT", nullable: false),
Name = table.Column<string>(type: "TEXT", maxLength: 256, nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_runepages", x => x.Id);
});
migrationBuilder.CreateTable(
name: "skills",
columns: table => new
{
Name = table.Column<string>(type: "TEXT", maxLength: 256, nullable: false),
Description = table.Column<string>(type: "TEXT", maxLength: 500, nullable: false),
SkillType = table.Column<int>(type: "INTEGER", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_skills", x => x.Name);
});
migrationBuilder.CreateTable(
name: "champions",
columns: table => new
{
Name = table.Column<string>(type: "TEXT", maxLength: 256, nullable: false),
Bio = table.Column<string>(type: "TEXT", maxLength: 500, nullable: false),
Icon = table.Column<string>(type: "TEXT", nullable: true),
Class = table.Column<int>(type: "INTEGER", nullable: false),
ImageId = table.Column<Guid>(type: "TEXT", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_champions", x => x.Name);
table.ForeignKey(
name: "FK_champions_largeimages_ImageId",
column: x => x.ImageId,
principalTable: "largeimages",
principalColumn: "Id");
});
migrationBuilder.CreateTable(
name: "runes",
columns: table => new
{
Name = table.Column<string>(type: "TEXT", maxLength: 256, nullable: false),
Description = table.Column<string>(type: "TEXT", maxLength: 500, nullable: false),
RuneFamily = table.Column<int>(type: "INTEGER", nullable: false),
ImageId = table.Column<Guid>(type: "TEXT", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_runes", x => x.Name);
table.ForeignKey(
name: "FK_runes_largeimages_ImageId",
column: x => x.ImageId,
principalTable: "largeimages",
principalColumn: "Id");
});
migrationBuilder.CreateTable(
name: "ChampionEntityRunePageEntity",
columns: table => new
{
championsName = table.Column<string>(type: "TEXT", nullable: false),
runepagesId = table.Column<Guid>(type: "TEXT", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_ChampionEntityRunePageEntity", x => new { x.championsName, x.runepagesId });
table.ForeignKey(
name: "FK_ChampionEntityRunePageEntity_champions_championsName",
column: x => x.championsName,
principalTable: "champions",
principalColumn: "Name",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_ChampionEntityRunePageEntity_runepages_runepagesId",
column: x => x.runepagesId,
principalTable: "runepages",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "ChampionEntitySkillEntity",
columns: table => new
{
ChampionsName = table.Column<string>(type: "TEXT", nullable: false),
SkillsName = table.Column<string>(type: "TEXT", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_ChampionEntitySkillEntity", x => new { x.ChampionsName, x.SkillsName });
table.ForeignKey(
name: "FK_ChampionEntitySkillEntity_champions_ChampionsName",
column: x => x.ChampionsName,
principalTable: "champions",
principalColumn: "Name",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_ChampionEntitySkillEntity_skills_SkillsName",
column: x => x.SkillsName,
principalTable: "skills",
principalColumn: "Name",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "characteristics",
columns: table => new
{
Name = table.Column<string>(type: "TEXT", maxLength: 256, nullable: false),
ChampionForeignKey = table.Column<string>(type: "TEXT", nullable: false),
Value = table.Column<int>(type: "INTEGER", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_characteristics", x => new { x.Name, x.ChampionForeignKey });
table.ForeignKey(
name: "FK_characteristics_champions_ChampionForeignKey",
column: x => x.ChampionForeignKey,
principalTable: "champions",
principalColumn: "Name",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "skins",
columns: table => new
{
Name = table.Column<string>(type: "TEXT", maxLength: 256, nullable: false),
Description = table.Column<string>(type: "TEXT", maxLength: 500, nullable: false),
Icon = table.Column<string>(type: "TEXT", nullable: false),
Price = table.Column<float>(type: "REAL", nullable: false),
ChampionForeignKey = table.Column<string>(type: "TEXT", nullable: false),
ImageId = table.Column<Guid>(type: "TEXT", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_skins", x => x.Name);
table.ForeignKey(
name: "FK_skins_champions_ChampionForeignKey",
column: x => x.ChampionForeignKey,
principalTable: "champions",
principalColumn: "Name",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_skins_largeimages_ImageId",
column: x => x.ImageId,
principalTable: "largeimages",
principalColumn: "Id");
});
migrationBuilder.CreateTable(
name: "RunePageRuneEntity",
columns: table => new
{
runepagesId = table.Column<Guid>(type: "TEXT", nullable: false),
runesName = table.Column<string>(type: "TEXT", nullable: false),
Category = table.Column<int>(type: "INTEGER", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_RunePageRuneEntity", x => new { x.runepagesId, x.runesName });
table.ForeignKey(
name: "FK_RunePageRuneEntity_runepages_runepagesId",
column: x => x.runepagesId,
principalTable: "runepages",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_RunePageRuneEntity_runes_runesName",
column: x => x.runesName,
principalTable: "runes",
principalColumn: "Name",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.InsertData(
table: "champions",
columns: new[] { "Name", "Bio", "Class", "Icon", "ImageId" },
values: new object[,]
{
{ "Armure", "Solide", 6, null, null },
{ "Dave", "Le meilleur Jazzman de France", 2, null, null }
});
migrationBuilder.InsertData(
table: "largeimages",
columns: new[] { "Id", "Base64" },
values: new object[] { new Guid("d3a490c6-fb49-475a-9134-47c2de9888d2"), "aaa" });
migrationBuilder.InsertData(
table: "runepages",
columns: new[] { "Id", "Name" },
values: new object[] { new Guid("4ea04d4f-0a64-4d28-8d74-4499dbc541f2"), "Runepage_1" });
migrationBuilder.InsertData(
table: "runes",
columns: new[] { "Name", "Description", "ImageId", "RuneFamily" },
values: new object[,]
{
{ "Alkatraz", "Lock effect", null, 2 },
{ "Bullseye", "Steady shot", null, 1 }
});
migrationBuilder.InsertData(
table: "skills",
columns: new[] { "Name", "Description", "SkillType" },
values: new object[,]
{
{ "Boule de feu", "Fire!", 1 },
{ "White Star", "Random damage", 3 }
});
migrationBuilder.InsertData(
table: "characteristics",
columns: new[] { "ChampionForeignKey", "Name", "Value" },
values: new object[,]
{
{ "Armure", "Défense", 75 },
{ "Dave", "Force", 50 }
});
migrationBuilder.InsertData(
table: "skins",
columns: new[] { "Name", "ChampionForeignKey", "Description", "Icon", "ImageId", "Price" },
values: new object[,]
{
{ "Armure Fullspeed", "Armure", "Deja vu", "aaa", null, 9.99f },
{ "Dave de glace", "Dave", "Enneigé", "aaa", null, 7.99f }
});
migrationBuilder.CreateIndex(
name: "IX_ChampionEntityRunePageEntity_runepagesId",
table: "ChampionEntityRunePageEntity",
column: "runepagesId");
migrationBuilder.CreateIndex(
name: "IX_ChampionEntitySkillEntity_SkillsName",
table: "ChampionEntitySkillEntity",
column: "SkillsName");
migrationBuilder.CreateIndex(
name: "IX_champions_ImageId",
table: "champions",
column: "ImageId");
migrationBuilder.CreateIndex(
name: "IX_characteristics_ChampionForeignKey",
table: "characteristics",
column: "ChampionForeignKey");
migrationBuilder.CreateIndex(
name: "IX_RunePageRuneEntity_runesName",
table: "RunePageRuneEntity",
column: "runesName");
migrationBuilder.CreateIndex(
name: "IX_runes_ImageId",
table: "runes",
column: "ImageId");
migrationBuilder.CreateIndex(
name: "IX_skins_ChampionForeignKey",
table: "skins",
column: "ChampionForeignKey");
migrationBuilder.CreateIndex(
name: "IX_skins_ImageId",
table: "skins",
column: "ImageId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "ChampionEntityRunePageEntity");
migrationBuilder.DropTable(
name: "ChampionEntitySkillEntity");
migrationBuilder.DropTable(
name: "characteristics");
migrationBuilder.DropTable(
name: "RunePageRuneEntity");
migrationBuilder.DropTable(
name: "skins");
migrationBuilder.DropTable(
name: "skills");
migrationBuilder.DropTable(
name: "runepages");
migrationBuilder.DropTable(
name: "runes");
migrationBuilder.DropTable(
name: "champions");
migrationBuilder.DropTable(
name: "largeimages");
}
}
}

@ -1,408 +0,0 @@
// <auto-generated />
using System;
using Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace Entities.Migrations
{
[DbContext(typeof(LolDbContext))]
partial class LolDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "7.0.2");
modelBuilder.Entity("ChampionEntityRunePageEntity", b =>
{
b.Property<string>("championsName")
.HasColumnType("TEXT");
b.Property<Guid>("runepagesId")
.HasColumnType("TEXT");
b.HasKey("championsName", "runepagesId");
b.HasIndex("runepagesId");
b.ToTable("ChampionEntityRunePageEntity");
});
modelBuilder.Entity("ChampionEntitySkillEntity", b =>
{
b.Property<string>("ChampionsName")
.HasColumnType("TEXT");
b.Property<string>("SkillsName")
.HasColumnType("TEXT");
b.HasKey("ChampionsName", "SkillsName");
b.HasIndex("SkillsName");
b.ToTable("ChampionEntitySkillEntity");
});
modelBuilder.Entity("Entities.ChampionEntity", b =>
{
b.Property<string>("Name")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.Property<string>("Bio")
.IsRequired()
.HasMaxLength(500)
.HasColumnType("TEXT");
b.Property<int>("Class")
.HasColumnType("INTEGER");
b.Property<string>("Icon")
.HasColumnType("TEXT");
b.Property<Guid?>("ImageId")
.HasColumnType("TEXT");
b.HasKey("Name");
b.HasIndex("ImageId");
b.ToTable("champions");
b.HasData(
new
{
Name = "Dave",
Bio = "Le meilleur Jazzman de France",
Class = 2
},
new
{
Name = "Armure",
Bio = "Solide",
Class = 6
});
});
modelBuilder.Entity("Entities.CharacteristicEntity", b =>
{
b.Property<string>("Name")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.Property<string>("ChampionForeignKey")
.HasColumnType("TEXT");
b.Property<int>("Value")
.HasColumnType("INTEGER");
b.HasKey("Name", "ChampionForeignKey");
b.HasIndex("ChampionForeignKey");
b.ToTable("characteristics");
b.HasData(
new
{
Name = "Force",
ChampionForeignKey = "Dave",
Value = 50
},
new
{
Name = "Défense",
ChampionForeignKey = "Armure",
Value = 75
});
});
modelBuilder.Entity("Entities.LargeImageEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("Base64")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("Id");
b.ToTable("largeimages");
b.HasData(
new
{
Id = new Guid("d3a490c6-fb49-475a-9134-47c2de9888d2"),
Base64 = "aaa"
});
});
modelBuilder.Entity("Entities.RuneEntity", b =>
{
b.Property<string>("Name")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.Property<string>("Description")
.IsRequired()
.HasMaxLength(500)
.HasColumnType("TEXT");
b.Property<Guid?>("ImageId")
.HasColumnType("TEXT");
b.Property<int>("RuneFamily")
.HasColumnType("INTEGER");
b.HasKey("Name");
b.HasIndex("ImageId");
b.ToTable("runes");
b.HasData(
new
{
Name = "Bullseye",
Description = "Steady shot",
RuneFamily = 1
},
new
{
Name = "Alkatraz",
Description = "Lock effect",
RuneFamily = 2
});
});
modelBuilder.Entity("Entities.RunePageEntity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(256)
.HasColumnType("TEXT");
b.HasKey("Id");
b.ToTable("runepages");
b.HasData(
new
{
Id = new Guid("4ea04d4f-0a64-4d28-8d74-4499dbc541f2"),
Name = "Runepage_1"
});
});
modelBuilder.Entity("Entities.RunePageRuneEntity", b =>
{
b.Property<Guid>("runepagesId")
.HasColumnType("TEXT");
b.Property<string>("runesName")
.HasColumnType("TEXT");
b.Property<int>("Category")
.HasColumnType("INTEGER");
b.HasKey("runepagesId", "runesName");
b.HasIndex("runesName");
b.ToTable("RunePageRuneEntity");
});
modelBuilder.Entity("Entities.SkillEntity", b =>
{
b.Property<string>("Name")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.Property<string>("Description")
.IsRequired()
.HasMaxLength(500)
.HasColumnType("TEXT");
b.Property<int>("SkillType")
.HasColumnType("INTEGER");
b.HasKey("Name");
b.ToTable("skills");
b.HasData(
new
{
Name = "Boule de feu",
Description = "Fire!",
SkillType = 1
},
new
{
Name = "White Star",
Description = "Random damage",
SkillType = 3
});
});
modelBuilder.Entity("Entities.SkinEntity", b =>
{
b.Property<string>("Name")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.Property<string>("ChampionForeignKey")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("Description")
.IsRequired()
.HasMaxLength(500)
.HasColumnType("TEXT");
b.Property<string>("Icon")
.IsRequired()
.HasColumnType("TEXT");
b.Property<Guid?>("ImageId")
.HasColumnType("TEXT");
b.Property<float>("Price")
.HasColumnType("REAL");
b.HasKey("Name");
b.HasIndex("ChampionForeignKey");
b.HasIndex("ImageId");
b.ToTable("skins");
b.HasData(
new
{
Name = "Dave de glace",
ChampionForeignKey = "Dave",
Description = "Enneigé",
Icon = "aaa",
Price = 7.99f
},
new
{
Name = "Armure Fullspeed",
ChampionForeignKey = "Armure",
Description = "Deja vu",
Icon = "aaa",
Price = 9.99f
});
});
modelBuilder.Entity("ChampionEntityRunePageEntity", b =>
{
b.HasOne("Entities.ChampionEntity", null)
.WithMany()
.HasForeignKey("championsName")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Entities.RunePageEntity", null)
.WithMany()
.HasForeignKey("runepagesId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("ChampionEntitySkillEntity", b =>
{
b.HasOne("Entities.ChampionEntity", null)
.WithMany()
.HasForeignKey("ChampionsName")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Entities.SkillEntity", null)
.WithMany()
.HasForeignKey("SkillsName")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Entities.ChampionEntity", b =>
{
b.HasOne("Entities.LargeImageEntity", "Image")
.WithMany()
.HasForeignKey("ImageId");
b.Navigation("Image");
});
modelBuilder.Entity("Entities.CharacteristicEntity", b =>
{
b.HasOne("Entities.ChampionEntity", "Champion")
.WithMany("Characteristics")
.HasForeignKey("ChampionForeignKey")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Champion");
});
modelBuilder.Entity("Entities.RuneEntity", b =>
{
b.HasOne("Entities.LargeImageEntity", "Image")
.WithMany()
.HasForeignKey("ImageId");
b.Navigation("Image");
});
modelBuilder.Entity("Entities.RunePageRuneEntity", b =>
{
b.HasOne("Entities.RunePageEntity", null)
.WithMany()
.HasForeignKey("runepagesId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Entities.RuneEntity", null)
.WithMany()
.HasForeignKey("runesName")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Entities.SkinEntity", b =>
{
b.HasOne("Entities.ChampionEntity", "Champion")
.WithMany()
.HasForeignKey("ChampionForeignKey")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Entities.LargeImageEntity", "Image")
.WithMany()
.HasForeignKey("ImageId");
b.Navigation("Champion");
b.Navigation("Image");
});
modelBuilder.Entity("Entities.ChampionEntity", b =>
{
b.Navigation("Characteristics");
});
#pragma warning restore 612, 618
}
}
}

@ -7,7 +7,7 @@ ChampionEntity imri = new()
Bio = "Fou Furieux",
Class = ChampionClass.Assassin
};
using (var context = new LolDbContext())
using (var context = new LolDbContext(null))
{
// Crée des nounours et les insère dans la base
Console.WriteLine("Creates and inserts new Champion");

@ -19,9 +19,11 @@ namespace Entities
[MaxLength(500)]
public string Description { get; set; }
public string Icon { get; set; }
[Required]
public RuneFamily RuneFamily { get; set; }
public ICollection<RunePageEntity>? runepages { get; set; }
public ICollection<RunePageRuneEntity>? runepages { get; set; }
public Guid? ImageId { get; set; }

@ -11,14 +11,10 @@ namespace Entities
public class RunePageEntity
{
[Key]
public Guid Id { get; set; }
[MaxLength(256)]
public string Name { get; set; }
public ICollection<RuneEntity> runes { get; set; }
public ICollection<RunePageRuneEntity> entries { get; set; }
public ICollection<ChampionEntity> champions { get; set; }
}
}

@ -1,14 +1,20 @@
using Shared;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Entities
{
public class RunePageRuneEntity
{
public Category Category { get; set; }
public Category category { get; set; }
[ForeignKey("RuneName")]
public RuneEntity rune { get; set; }
public string RuneName { get; set; }
[ForeignKey("RunePageName")]
public RunePageEntity runepage { get; set; }
public string RunePageName { get; set; }
}
}

@ -1,19 +0,0 @@
using EntityFramework.Entities;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EntityFramework.DbContexts
{
internal class ChampionDbContext : DbContext
{
public DbSet<ChampionEntity> champions { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite($"Data Source=EntityFramework.Champions.db");
}
}
}

@ -1,17 +0,0 @@
using System.ComponentModel.DataAnnotations;
namespace EntityFramework.Entities
{
internal class ChampionEntity
{
[Key]
[MaxLength(256)]
public string Name { get; set; }
[Required]
[MaxLength(500)]
public string Bio { get; set; }
[Required]
public string Icon { get; set; }
}
}

@ -1,44 +0,0 @@
// <auto-generated />
using EntityFramework.DbContexts;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace EntityFramework.Migrations
{
[DbContext(typeof(ChampionDbContext))]
[Migration("20230201154310_migr")]
partial class migr
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "7.0.2");
modelBuilder.Entity("EntityFramework.Entities.ChampionEntity", b =>
{
b.Property<string>("Name")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.Property<string>("Bio")
.IsRequired()
.HasMaxLength(500)
.HasColumnType("TEXT");
b.Property<string>("Icon")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("Name");
b.ToTable("champions");
});
#pragma warning restore 612, 618
}
}
}

@ -1,34 +0,0 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace EntityFramework.Migrations
{
/// <inheritdoc />
public partial class migr : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "champions",
columns: table => new
{
Name = table.Column<string>(type: "TEXT", maxLength: 256, nullable: false),
Bio = table.Column<string>(type: "TEXT", maxLength: 500, nullable: false),
Icon = table.Column<string>(type: "TEXT", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_champions", x => x.Name);
});
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "champions");
}
}
}

@ -1,44 +0,0 @@
// <auto-generated />
using EntityFramework.DbContexts;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace EntityFramework.Migrations
{
[DbContext(typeof(ChampionDbContext))]
[Migration("20230209124258_myFirstMigration")]
partial class myFirstMigration
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "7.0.2");
modelBuilder.Entity("EntityFramework.Entities.ChampionEntity", b =>
{
b.Property<string>("Name")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.Property<string>("Bio")
.IsRequired()
.HasMaxLength(500)
.HasColumnType("TEXT");
b.Property<string>("Icon")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("Name");
b.ToTable("champions");
});
#pragma warning restore 612, 618
}
}
}

@ -1,22 +0,0 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace EntityFramework.Migrations
{
/// <inheritdoc />
public partial class myFirstMigration : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
}
}
}

@ -1,41 +0,0 @@
// <auto-generated />
using EntityFramework.DbContexts;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace EntityFramework.Migrations
{
[DbContext(typeof(ChampionDbContext))]
partial class ChampionDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "7.0.2");
modelBuilder.Entity("EntityFramework.Entities.ChampionEntity", b =>
{
b.Property<string>("Name")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.Property<string>("Bio")
.IsRequired()
.HasMaxLength(500)
.HasColumnType("TEXT");
b.Property<string>("Icon")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("Name");
b.ToTable("champions");
});
#pragma warning restore 612, 618
}
}
}

@ -1,17 +0,0 @@
using EntityFramework.DbContexts;
using EntityFramework.Entities;
using Model;
ChampionEntity dave = new ChampionEntity()
{
Name = "Dave",
Bio = "Le meilleur Jazzman de France",
Icon = "aaa"
};
using (var context = new ChampionDbContext())
{
// Crée des nounours et les insère dans la base
Console.WriteLine("Creates and inserts new Champion");
context.Add(dave);
context.SaveChanges();
}

@ -0,0 +1,41 @@
using Entities;
using EntityMappers;
using Model;
namespace EntityMapper
{
public static class ChampionMapper {
public static ChampionEntity ToEntity(this Champion item, LolDbContext context)
{
ChampionEntity? championEntity = context.champions.Find(item.Name);
if (championEntity == null)
{
championEntity = new()
{
Name = item.Name,
Bio = item.Bio,
Icon = item.Icon,
Class = item.Class,
Image = new() { Base64 = item.Image.Base64 },
};
championEntity.Skills = item.Skills.Select(x => x.ToEntity(championEntity, context)).ToList();
championEntity.Characteristics = item.Characteristics.Select(x => x.ToEntity(championEntity, context)).ToList();
}
return championEntity;
}
public static Champion ToModel(this ChampionEntity entity)
{
var image = entity?.Image?.Base64 ?? "";
var champion = new Champion(entity?.Name ?? "", entity?.Class??Shared.ChampionClass.Unknown, entity?.Icon??"", image , entity?.Bio??"");
if(entity.Skills!=null) foreach(var s in entity.Skills){champion.AddSkill(s.ToModel());}
if (entity.Characteristics != null) foreach (var c in entity.Characteristics){champion.AddCharacteristics(c.ToModel()); }
return champion;
}
}
}

@ -0,0 +1,33 @@
using Entities;
using Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EntityMappers
{
public static class CharacteristicMapper
{
public static CharacteristicEntity ToEntity(this KeyValuePair<string, int> item, ChampionEntity champion, LolDbContext context)
{
var characteristicEntity = context.characteristics.Find(item.Key, champion.Name);
if (characteristicEntity == null)
{
return new()
{
Name = item.Key,
Value = item.Value,
ChampionForeignKey = champion.Name
};
}
return characteristicEntity;
}
public static Tuple<string, int> ToModel(this CharacteristicEntity entity)
=> new(entity.Name, entity.Value);
}
}

@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Entities\Entities.csproj" />
<ProjectReference Include="..\Model\Model.csproj" />
</ItemGroup>
</Project>

@ -0,0 +1,35 @@
using Entities;
using Model;
using System.Reflection.Metadata.Ecma335;
namespace EntityMapper
{
public static class RuneMapper
{
public static RuneEntity ToEntity(this Rune item, LolDbContext context)
{
RuneEntity? runeEntity = context.runes.Find(item.Name);
if (runeEntity == null) {
return new()
{
Name = item.Name,
Description = item.Description,
RuneFamily = item.Family,
Icon = item.Icon,
Image = new() { Base64 = item.Image.Base64 },
};
}
return runeEntity;
}
public static Rune ToModel(this RuneEntity entity)
{
var image = entity?.Image?.Base64 ?? "";
return new Rune(entity?.Name ?? "", entity?.RuneFamily??Shared.RuneFamily.Unknown, entity?.Icon ?? "", image, entity?.Description??"");
}
}
}

@ -0,0 +1,48 @@
using Entities;
using Model;
using Shared;
namespace EntityMapper
{
public static class RunePageMapper
{
public static RunePageEntity ToEntity(this RunePage item, LolDbContext context)
{
RunePageEntity? runePageEntity = context.runepages.Find(item.Name);
if (runePageEntity == null)
{
runePageEntity = new()
{
Name = item.Name,
};
runePageEntity.entries = new List<RunePageRuneEntity>();
foreach (var r in item.Runes)
{
runePageEntity.entries.Add(new RunePageRuneEntity()
{
category = r.Key,
rune = r.Value.ToEntity(context),
});
}
}
return runePageEntity;
}
public static RunePage ToModel(this RunePageEntity entity, LolDbContext context)
{
RunePage runePage = new(entity.Name);
if(entity.entries!= null)
{
foreach(var r in entity.entries)
{
var rune = context.runes.Find(r.RuneName);
if(rune!=null) runePage[r.category] = rune.ToModel();
};
}
return runePage;
}
}
}

@ -0,0 +1,33 @@
using Entities;
using Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EntityMappers
{
public static class SkillMapper
{
public static SkillEntity ToEntity(this Skill item, ChampionEntity champion, LolDbContext context)
{
var skillEntity = context.skills.Find(item.Name);
if (skillEntity == null) {
return new()
{
Name = item.Name,
Description = item.Description,
SkillType = item.Type,
Champions = new List<ChampionEntity>() { champion }
};
}
skillEntity!.Champions?.Add(champion);
return skillEntity;
}
public static Skill ToModel(this SkillEntity entity)
=> new(entity.Name, entity.SkillType,entity.Description);
}
}

@ -0,0 +1,31 @@
using Entities;
using Microsoft.EntityFrameworkCore;
using Model;
namespace EntityMapper
{
public static class SkinMapper
{
public static SkinEntity ToEntity(this Skin item, LolDbContext? context = null)
{
return new()
{
Name = item.Name,
Champion = context?.champions.Find(item.Champion.Name) ?? item.Champion.ToEntity(context),
ChampionForeignKey = item.Champion.Name,
Description = item.Description,
Icon = item.Icon,
Image = new() { Base64 = item.Image.Base64 },
Price = item.Price
};
}
public static Skin ToModel(this SkinEntity entity)
{
var image = entity?.Image?.Base64 ?? "";
return new(entity?.Name ?? "", entity?.Champion?.ToModel()??new(""), entity?.Price??-1, image, entity?.Description??"");
}
}
}

@ -17,8 +17,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "StubLib", "StubLib\StubLib.
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "API_LoL_Project", "API_LoL_Project\API_LoL_Project.csproj", "{4EDC93E0-35B8-4EF1-9318-24F7A606BA97}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DTO", "DTO\DTO.csproj", "{7F6A519E-98F8-429E-B34F-9B0D20075CFB}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Entity Framework", "Entity Framework", "{BC2FFCA4-3801-433F-A83E-B55345F3B31E}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Entities", "Entities\Entities.csproj", "{C463E2E1-237A-4339-A4C4-6EA3BE7002AE}"
@ -27,6 +25,18 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Test_Api", "Test_Api\Test_A
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Business", "Business\Business.csproj", "{A447B0BE-62AE-4F66-B887-D1F3D46B0DB3}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EntityMappers", "EntityMappers\EntityMappers.csproj", "{3A70A719-4F42-4CC3-846A-53437F3B4CC5}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tests", "Tests", "{4008CA21-360B-4C39-8AC3-6E5B02552E22}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestEF", "TestEF\TestEF.csproj", "{059B4A61-E9D5-4C00-8178-C8714D781FBC}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ApiLib", "ApiLib\ApiLib.csproj", "{3D3CBA61-0C8E-4B22-9CAA-66845E1D6C96}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ApiMappeur", "ApiMappeur\ApiMappeur.csproj", "{709010E2-F36C-4FD9-91D3-D3806EE28B88}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DTO", "DTO\DTO.csproj", "{CA27B501-E120-4551-ABAE-BCE1B85B7455}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -53,10 +63,6 @@ Global
{4EDC93E0-35B8-4EF1-9318-24F7A606BA97}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4EDC93E0-35B8-4EF1-9318-24F7A606BA97}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4EDC93E0-35B8-4EF1-9318-24F7A606BA97}.Release|Any CPU.Build.0 = Release|Any CPU
{7F6A519E-98F8-429E-B34F-9B0D20075CFB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7F6A519E-98F8-429E-B34F-9B0D20075CFB}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7F6A519E-98F8-429E-B34F-9B0D20075CFB}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7F6A519E-98F8-429E-B34F-9B0D20075CFB}.Release|Any CPU.Build.0 = Release|Any CPU
{C463E2E1-237A-4339-A4C4-6EA3BE7002AE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C463E2E1-237A-4339-A4C4-6EA3BE7002AE}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C463E2E1-237A-4339-A4C4-6EA3BE7002AE}.Release|Any CPU.ActiveCfg = Release|Any CPU
@ -69,6 +75,26 @@ Global
{A447B0BE-62AE-4F66-B887-D1F3D46B0DB3}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A447B0BE-62AE-4F66-B887-D1F3D46B0DB3}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A447B0BE-62AE-4F66-B887-D1F3D46B0DB3}.Release|Any CPU.Build.0 = Release|Any CPU
{3A70A719-4F42-4CC3-846A-53437F3B4CC5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3A70A719-4F42-4CC3-846A-53437F3B4CC5}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3A70A719-4F42-4CC3-846A-53437F3B4CC5}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3A70A719-4F42-4CC3-846A-53437F3B4CC5}.Release|Any CPU.Build.0 = Release|Any CPU
{059B4A61-E9D5-4C00-8178-C8714D781FBC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{059B4A61-E9D5-4C00-8178-C8714D781FBC}.Debug|Any CPU.Build.0 = Debug|Any CPU
{059B4A61-E9D5-4C00-8178-C8714D781FBC}.Release|Any CPU.ActiveCfg = Release|Any CPU
{059B4A61-E9D5-4C00-8178-C8714D781FBC}.Release|Any CPU.Build.0 = Release|Any CPU
{3D3CBA61-0C8E-4B22-9CAA-66845E1D6C96}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3D3CBA61-0C8E-4B22-9CAA-66845E1D6C96}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3D3CBA61-0C8E-4B22-9CAA-66845E1D6C96}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3D3CBA61-0C8E-4B22-9CAA-66845E1D6C96}.Release|Any CPU.Build.0 = Release|Any CPU
{709010E2-F36C-4FD9-91D3-D3806EE28B88}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{709010E2-F36C-4FD9-91D3-D3806EE28B88}.Debug|Any CPU.Build.0 = Debug|Any CPU
{709010E2-F36C-4FD9-91D3-D3806EE28B88}.Release|Any CPU.ActiveCfg = Release|Any CPU
{709010E2-F36C-4FD9-91D3-D3806EE28B88}.Release|Any CPU.Build.0 = Release|Any CPU
{CA27B501-E120-4551-ABAE-BCE1B85B7455}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{CA27B501-E120-4551-ABAE-BCE1B85B7455}.Debug|Any CPU.Build.0 = Debug|Any CPU
{CA27B501-E120-4551-ABAE-BCE1B85B7455}.Release|Any CPU.ActiveCfg = Release|Any CPU
{CA27B501-E120-4551-ABAE-BCE1B85B7455}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@ -78,6 +104,9 @@ Global
{B01D7EF2-2D64-409A-A29A-61FB7BB7A9DB} = {2C607793-B163-4731-A4D1-AFE8A7C4C170}
{C463E2E1-237A-4339-A4C4-6EA3BE7002AE} = {BC2FFCA4-3801-433F-A83E-B55345F3B31E}
{A447B0BE-62AE-4F66-B887-D1F3D46B0DB3} = {BC2FFCA4-3801-433F-A83E-B55345F3B31E}
{3A70A719-4F42-4CC3-846A-53437F3B4CC5} = {BC2FFCA4-3801-433F-A83E-B55345F3B31E}
{4008CA21-360B-4C39-8AC3-6E5B02552E22} = {BC2FFCA4-3801-433F-A83E-B55345F3B31E}
{059B4A61-E9D5-4C00-8178-C8714D781FBC} = {4008CA21-360B-4C39-8AC3-6E5B02552E22}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {92F3083D-793F-4552-8A9A-0AD6534159C9}

@ -63,7 +63,7 @@ public class Champion : IEquatable<Champion>
public ImmutableHashSet<Skill> Skills => skills.ToImmutableHashSet();
private HashSet<Skill> skills = new HashSet<Skill>();
internal bool AddSkin(Skin skin)
public bool AddSkin(Skin skin)
{
if (skins.Contains(skin))
return false;

@ -0,0 +1,7 @@
{
"profiles": {
"Model": {
"commandName": "Project"
}
}
}

@ -15,8 +15,9 @@ namespace StubLib
new Champion("Bard", ChampionClass.Support),
new Champion("Alistar", ChampionClass.Tank),
};
public class ChampionsManager : IChampionsManager
public class ChampionsManager : IChampionsManager
{
private readonly StubData parent;

@ -29,7 +29,5 @@ public partial class StubData : IDataManager
championsAndRunePages.Add(Tuple.Create(champions[0], runePages[0]));
}
}

@ -0,0 +1,197 @@
using Business;
using Entities;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Model;
using Shared;
using Xunit.Abstractions;
namespace TestEF
{
public class TestChampions
{
[Fact]
public async void Test_Add()
{
//connection must be opened to use In-memory database
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<LolDbContext>()
.UseSqlite(connection)
.Options;
using (var context = new LolDbContext(options))
{
var manager = new DbData(context).ChampionsMgr;
context.Database.EnsureCreated();
Champion batman = new("Batman", ChampionClass.Assassin, "icon_1", "image_1", "L'ombre de la nuit");
batman.AddSkill(new("Bat-signal", SkillType.Basic, "Envoie le signal"));
batman.AddCharacteristics(new[] {
Tuple.Create("Force", 150),
Tuple.Create("Agilité", 500)
});
Champion endeavor = new("Endeavor", ChampionClass.Tank, "icon_2", "image_2", "Feu brûlant énernel");
endeavor.AddSkill(new("Final flames", SkillType.Ultimate, "Dernière flamme d'un héro"));
endeavor.AddCharacteristics(new[] {
Tuple.Create("Force", 200),
Tuple.Create("Défense", 300),
Tuple.Create("Alter", 800)
});
Champion escanor = new("Escanor", ChampionClass.Fighter, "icon_3", "image_3", "1, 2, 3, Soleil");
escanor.AddSkill(new("Croissance solaire", SkillType.Passive, "Le soleil rends plus fort !"));
escanor.AddCharacteristics(new[] {
Tuple.Create("Force", 500),
Tuple.Create("Défense", 500)
});
await manager.AddItem(batman);
await manager.AddItem(endeavor);
await manager.AddItem(escanor);
}
//uses another instance of the context to do the tests
using (var context = new LolDbContext(options))
{
var manager = new DbData(context).ChampionsMgr;
context.Database.EnsureCreated();
var nbItems = await manager.GetNbItems();
Assert.Equal(3, nbItems);
var items = await manager.GetItemsByName("Batman", 0, nbItems);
Assert.Equal("Batman", items.First().Name);
Assert.Equal(2, await manager.GetNbItemsByName("E"));
items = await manager.GetItemsBySkill("Croissance solaire", 0, nbItems);
Assert.Equal("Escanor", items.First().Name);
items = await manager.GetItemsBySkill(new Skill("Final flames", SkillType.Ultimate, "Dernière flamme d'un héro"),
0, nbItems);
Assert.Equal("Endeavor", items.First().Name);
items = await manager.GetItemsByCharacteristic("Alter", 0, nbItems);
Assert.Equal("Endeavor", items.First().Name);
Assert.Equal(2, await manager.GetNbItemsByCharacteristic("Défense"));
}
}
[Fact]
public async void Test_Update()
{
//connection must be opened to use In-memory database
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<LolDbContext>()
.UseSqlite(connection)
.Options;
//prepares the database with one instance of the context
using (var context = new LolDbContext(options))
{
var manager = new DbData(context).ChampionsMgr;
context.Database.EnsureCreated();
Champion batman = new("Batman", ChampionClass.Assassin, "icon_1", "image_1", "L'ombre de la nuit");
Champion endeavor = new("Endeavor", ChampionClass.Tank, "icon_2", "image_2", "Feu brûlant énernel");
Champion escanor = new("Escanor", ChampionClass.Fighter, "icon_3", "image_3", "1, 2, 3, Soleil");
await manager.AddItem(batman);
await manager.AddItem(endeavor);
await manager.AddItem(escanor);
}
//uses another instance of the context to do the tests
using (var context = new LolDbContext(options))
{
var manager = new DbData(context).ChampionsMgr;
context.Database.EnsureCreated();
var items = await manager.GetItemsByName("E", 0, 3);
Assert.Equal(2, items.Count());
var escanor = context.champions.Where(n => n.Name.Contains("Esc")).First();
escanor.Class = ChampionClass.Tank;
context.SaveChanges();
items = await manager.GetItemsByClass(ChampionClass.Tank, 0, 3);
Assert.Contains("Escanor", items.Select(x => x.Name));
Assert.Equal(2, await manager.GetNbItemsByClass(ChampionClass.Tank));
}
}
[Fact]
public async void Test_Delete()
{
//connection must be opened to use In-memory database
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<LolDbContext>()
.UseSqlite(connection)
.Options;
//prepares the database with one instance of the context
using (var context = new LolDbContext(options))
{
var manager = new DbData(context).ChampionsMgr;
context.Database.EnsureCreated();
Champion batman = new("Batman", ChampionClass.Assassin, "icon_1", "image_1", "L'ombre de la nuit");
batman.AddSkill(new("Charge", SkillType.Basic, "Coup de base"));
batman.AddSkill(new("Double Saut", SkillType.Basic, ""));
Champion endeavor = new("Endeavor", ChampionClass.Tank, "icon_2", "image_2", "Feu brûlant énernel");
endeavor.AddSkill(new("Charge", SkillType.Basic, "Coup de base"));
Champion escanor = new("Escanor", ChampionClass.Fighter, "icon_3", "image_3", "1, 2, 3, Soleil");
escanor.AddSkill(new("Charge", SkillType.Basic, "Coup de base"));
batman.AddSkill(new("Double Saut", SkillType.Basic, ""));
await manager.AddItem(batman);
await manager.AddItem(endeavor);
await manager.AddItem(escanor);
}
//uses another instance of the context to do the tests
using (var context = new LolDbContext(options))
{
var manager = new DbData(context).ChampionsMgr;
context.Database.EnsureCreated();
var endeavor = (await manager.GetItemsByName("Endeavor", 0, 3)).First();
var itemsByName = await manager.DeleteItem(endeavor);
Assert.Equal(2, await manager.GetNbItems());
var items = await manager.GetItems(0, await manager.GetNbItems());
Assert.DoesNotContain("Endeavor", items.Select(x => x.Name));
Assert.Equal(1, await manager.GetNbItemsBySkill(new Skill("Double Saut", SkillType.Basic, "")));
Assert.Equal(2, await manager.GetNbItemsBySkill("Charge"));
}
}
}
}

@ -1,29 +1,31 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<StartWorkingDirectory>$(MSBuildProjectDirectory)</StartWorkingDirectory>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="7.0.2">
<PrivateAssets>all</PrivateAssets>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="7.0.3" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.3.2" />
<PackageReference Include="xunit" Version="2.4.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.5">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="7.0.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="7.0.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.2">
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="coverlet.collector" Version="3.1.2">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Business\Business.csproj" />
<ProjectReference Include="..\Entities\Entities.csproj" />
<ProjectReference Include="..\Model\Model.csproj" />
</ItemGroup>

@ -0,0 +1,284 @@
using Business;
using Entities;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Model;
using Shared;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestEF
{
public class TestRunePage
{
[Fact]
public async void Test_Add()
{
//connection must be opened to use In-memory database
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<LolDbContext>()
.UseSqlite(connection)
.Options;
using (var context = new LolDbContext(options))
{
var manager = new DbData(context).RunePagesMgr;
var runeManager = new DbData(context).RunesMgr;
var championManager = new DbData(context).ChampionsMgr;
context.Database.EnsureCreated();
Model.Rune rune1 = new("Sanglante", RuneFamily.Domination);
Model.Rune rune2 = new("Oeil de l'esprit", RuneFamily.Precision);
Model.Rune rune3 = new("Concrétisation", RuneFamily.Unknown);
Model.Rune rune4 = new("The moon", RuneFamily.Unknown);
Model.Rune rune5 = new("Radiance", RuneFamily.Domination);
Model.Rune rune6 = new("Bullseye", RuneFamily.Precision);
RunePage runepage1 = new("Damages");
runepage1[Category.Major] = rune1;
runepage1[Category.Minor1] = rune2;
runepage1[Category.Minor2] = rune5;
RunePage runepage2 = new("Hawk");
runepage2[Category.Major] = rune6;
runepage2[Category.Minor1] = rune2;
RunePage runepage3 = new("Juggler");
runepage3[Category.Major] = rune5;
runepage3[Category.Minor1] = rune3;
runepage3[Category.Minor2] = rune2;
await runeManager.AddItem(rune1);
await runeManager.AddItem(rune2);
await runeManager.AddItem(rune3);
await runeManager.AddItem(rune4);
await runeManager.AddItem(rune5);
await runeManager.AddItem(rune6);
await manager.AddItem(runepage1);
await manager.AddItem(runepage2);
await manager.AddItem(runepage3);
Champion batman = new("Batman", ChampionClass.Assassin, "icon_1", "image_1", "L'ombre de la nuit");
Champion endeavor = new("Endeavor", ChampionClass.Tank, "icon_2", "image_2", "Feu brûlant énernel");
Champion escanor = new("Escanor", ChampionClass.Fighter, "icon_3", "image_3", "1, 2, 3, Soleil");
await championManager.AddItem(batman);
await championManager.AddItem(endeavor);
await championManager.AddItem(escanor);
var runepage_entities = context.runepages;
var champion_entities = context.champions;
var damages = runepage_entities.Find("Damages");
var hawk = runepage_entities.Find("Hawk");
var juggler = runepage_entities.Find("Juggler");
champion_entities.Find("Batman")!.runepages = new List<RunePageEntity>() { hawk, juggler };
champion_entities.Find("Endeavor")!.runepages = new List<RunePageEntity>() { damages };
champion_entities.Find("Escanor")!.runepages = new List<RunePageEntity>() { damages };
context.SaveChanges();
}
//uses another instance of the context to do the tests
using (var context = new LolDbContext(options))
{
var manager = new DbData(context).RunePagesMgr;
var championManager = new DbData(context).ChampionsMgr;
context.Database.EnsureCreated();
Model.Rune rune5 = new("Radiance", RuneFamily.Domination);
Model.Rune rune1 = new("Sanglante", RuneFamily.Domination);
Champion batman = new("Batman", ChampionClass.Assassin, "icon_1", "image_1", "L'ombre de la nuit");
Champion endeavor = new("Endeavor", ChampionClass.Tank, "icon_2", "image_2", "Feu brûlant énernel");
var nbItems = await manager.GetNbItems();
Assert.Equal(3, nbItems);
var items = await manager.GetItemsByName("Ha", 0, nbItems);
Assert.Equal("Hawk", items.First().Name);
Assert.Equal(2, await manager.GetNbItemsByName("a"));
Assert.Equal(1, await manager.GetNbItemsByRune(rune5));
items = await manager.GetItemsByRune(rune1, 0, nbItems);
Assert.Equal("Damages", items.First().Name);
Assert.Equal(2, await manager.GetNbItemsByChampion(batman));
Assert.Equal("Damages", (await manager.GetItemsByChampion(endeavor, 0, 3)).First()!.Name);
Assert.Equal(2, await championManager.GetNbItemsByRunePage(new("Damages")));
Assert.Equal("Batman", (await championManager.GetItemsByRunePage(new("Juggler"), 0, 3)).First()!.Name);
}
}
[Fact]
public async void Test_Update()
{
//connection must be opened to use In-memory database
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<LolDbContext>()
.UseSqlite(connection)
.Options;
using (var context = new LolDbContext(options))
{
var manager = new DbData(context).RunePagesMgr;
var runeManager = new DbData(context).RunesMgr;
context.Database.EnsureCreated();
Model.Rune rune1 = new("Sanglante", RuneFamily.Domination);
Model.Rune rune2 = new("Oeil de l'esprit", RuneFamily.Precision);
Model.Rune rune3 = new("Concrétisation", RuneFamily.Unknown);
Model.Rune rune4 = new("The moon", RuneFamily.Unknown);
Model.Rune rune5 = new("Radiance", RuneFamily.Domination);
Model.Rune rune6 = new("Bullseye", RuneFamily.Precision);
RunePage runepage1 = new("Damages");
runepage1[Category.Major] = rune1;
runepage1[Category.Minor1] = rune2;
runepage1[Category.Minor2] = rune5;
RunePage runepage2 = new("Hawk");
runepage2[Category.Major] = rune6;
runepage2[Category.Minor1] = rune2;
RunePage runepage3 = new("Juggler");
runepage3[Category.Major] = rune5;
runepage3[Category.Minor1] = rune3;
runepage3[Category.Minor2] = rune2;
await runeManager.AddItem(rune1);
await runeManager.AddItem(rune2);
await runeManager.AddItem(rune3);
await runeManager.AddItem(rune4);
await runeManager.AddItem(rune5);
await runeManager.AddItem(rune6);
await manager.AddItem(runepage1);
await manager.AddItem(runepage2);
await manager.AddItem(runepage3);
}
//uses another instance of the context to do the tests
using (var context = new LolDbContext(options))
{
var manager = new DbData(context).RunePagesMgr;
Model.Rune rune1 = new("Sanglante", RuneFamily.Domination);
Model.Rune rune6 = new("Bullseye", RuneFamily.Precision);
context.Database.EnsureCreated();
Assert.Equal(1, await manager.GetNbItemsByRune(rune1));
Assert.Equal(1, await manager.GetNbItemsByRune(rune6));
RunePage after = new("Hawk");
after[Category.Major] = rune1;
await manager.UpdateItem(new("Hawk"), after);
Assert.Equal(2, await manager.GetNbItemsByRune(rune1));
Assert.Equal(0, await manager.GetNbItemsByRune(rune6));
context.SaveChanges();
}
}
[Fact]
public async void Test_Delete()
{
//connection must be opened to use In-memory database
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<LolDbContext>()
.UseSqlite(connection)
.Options;
//prepares the database with one instance of the context
using (var context = new LolDbContext(options))
{
var manager = new DbData(context).RunePagesMgr;
var runeManager = new DbData(context).RunesMgr;
context.Database.EnsureCreated();
Model.Rune rune1 = new("Sanglante", RuneFamily.Domination);
Model.Rune rune2 = new("Oeil de l'esprit", RuneFamily.Precision);
Model.Rune rune3 = new("Concrétisation", RuneFamily.Unknown);
Model.Rune rune4 = new("The moon", RuneFamily.Unknown);
Model.Rune rune5 = new("Radiance", RuneFamily.Domination);
Model.Rune rune6 = new("Bullseye", RuneFamily.Precision);
RunePage runepage1 = new("Damages");
runepage1[Category.Major] = rune1;
runepage1[Category.Minor1] = rune2;
runepage1[Category.Minor2] = rune5;
RunePage runepage2 = new("Hawk");
runepage2[Category.Major] = rune6;
runepage2[Category.Minor1] = rune2;
RunePage runepage3 = new("Juggler");
runepage3[Category.Major] = rune5;
runepage3[Category.Minor1] = rune3;
runepage3[Category.Minor2] = rune2;
await runeManager.AddItem(rune1);
await runeManager.AddItem(rune2);
await runeManager.AddItem(rune3);
await runeManager.AddItem(rune4);
await runeManager.AddItem(rune5);
await runeManager.AddItem(rune6);
await manager.AddItem(runepage1);
await manager.AddItem(runepage2);
await manager.AddItem(runepage3);
}
//uses another instance of the context to do the tests
using (var context = new LolDbContext(options))
{
var manager = new DbData(context).RunePagesMgr;
Model.Rune rune2 = new("Oeil de l'esprit", RuneFamily.Precision);
context.Database.EnsureCreated();
Assert.Equal(3, await manager.GetNbItems());
await manager.DeleteItem(new("Juggler"));
Assert.Equal(2, await manager.GetNbItems());
Assert.Equal(1, await manager.GetNbItemsByName("e"));
Assert.Equal(1, await manager.GetNbItemsByRune(rune2));
}
}
}
}

@ -0,0 +1,160 @@
using Business;
using Entities;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Model;
using Shared;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestEF
{
public class TestRunes
{
[Fact]
public async void Test_Add()
{
//connection must be opened to use In-memory database
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<LolDbContext>()
.UseSqlite(connection)
.Options;
using (var context = new LolDbContext(options))
{
var manager = new DbData(context).RunesMgr;
context.Database.EnsureCreated();
Model.Rune rune1 = new("Sanglante", RuneFamily.Domination);
Model.Rune rune2 = new("Oeil de l'esprit", RuneFamily.Precision);
Model.Rune rune3 = new("Concrétisation", RuneFamily.Unknown);
await manager.AddItem(rune1);
await manager.AddItem(rune2);
await manager.AddItem(rune3);
}
//uses another instance of the context to do the tests
using (var context = new LolDbContext(options))
{
var manager = new DbData(context).RunesMgr;
context.Database.EnsureCreated();
var nbItems = await manager.GetNbItems();
Assert.Equal(3, nbItems);
var items = await manager.GetItemsByName("Sanglante", 0, nbItems);
Assert.Equal("Sanglante", items.First().Name);
Assert.Equal(1, await manager.GetNbItemsByName("Concrétisation"));
items = await manager.GetItemsByFamily(RuneFamily.Precision, 0, nbItems);
Assert.Equal("Oeil de l'esprit", items.First().Name);
Assert.Equal(1, await manager.GetNbItemsByFamily(RuneFamily.Unknown));
}
}
[Fact]
public async void Test_Update()
{
//connection must be opened to use In-memory database
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<LolDbContext>()
.UseSqlite(connection)
.Options;
using (var context = new LolDbContext(options))
{
var manager = new DbData(context).RunesMgr;
context.Database.EnsureCreated();
Model.Rune rune1 = new("Sanglante", RuneFamily.Domination);
Model.Rune rune2 = new("Oeil de l'esprit", RuneFamily.Precision);
Model.Rune rune3 = new("Concrétisation", RuneFamily.Unknown);
await manager.AddItem(rune1);
await manager.AddItem(rune2);
await manager.AddItem(rune3);
}
//uses another instance of the context to do the tests
using (var context = new LolDbContext(options))
{
var manager = new DbData(context).RunesMgr;
context.Database.EnsureCreated();
Assert.Equal(1, await manager.GetNbItemsByFamily(RuneFamily.Precision));
Model.Rune before = new("Concrétisation", RuneFamily.Unknown);
Model.Rune after = new("Concrétisation", RuneFamily.Precision);
await manager.UpdateItem(before, after);
Assert.Equal(2, await manager.GetNbItemsByFamily(RuneFamily.Precision));
context.SaveChanges();
}
}
[Fact]
public async void Test_Delete()
{
//connection must be opened to use In-memory database
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<LolDbContext>()
.UseSqlite(connection)
.Options;
//prepares the database with one instance of the context
using (var context = new LolDbContext(options))
{
var manager = new DbData(context).RunesMgr;
context.Database.EnsureCreated();
Model.Rune rune1 = new("Sanglante", RuneFamily.Domination);
Model.Rune rune2 = new("Oeil de l'esprit", RuneFamily.Precision);
Model.Rune rune3 = new("Concrétisation", RuneFamily.Unknown);
await manager.AddItem(rune1);
await manager.AddItem(rune2);
await manager.AddItem(rune3);
}
//uses another instance of the context to do the tests
using (var context = new LolDbContext(options))
{
var manager = new DbData(context).RunesMgr;
context.Database.EnsureCreated();
Assert.Equal(3, await manager.GetNbItems());
await manager.DeleteItem(new("Concrétisation", RuneFamily.Unknown));
Assert.Equal(2, await manager.GetNbItems());
Assert.Equal(0, await manager.GetNbItemsByName("Concrétisation"));
}
}
}
}

@ -0,0 +1,187 @@
using Business;
using Entities;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Model;
using Shared;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestEF
{
public class TestSkins
{
[Fact]
public async void Test_Add()
{
//connection must be opened to use In-memory database
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<LolDbContext>()
.UseSqlite(connection)
.Options;
using (var context = new LolDbContext(options))
{
var manager = new DbData(context).SkinsMgr;
var championManager = new DbData(context).ChampionsMgr;
context.Database.EnsureCreated();
Champion batman = new("Batman", ChampionClass.Assassin);
Champion endeavor = new("Endeavor", ChampionClass.Tank);
await championManager.AddItem(batman);
await championManager.AddItem(endeavor);
Skin batman_skin_1 = new("Batman de glace", batman);
Skin batman_skin_2 = new("Batman gold", batman);
Skin batman_skin_3 = new("L'homme araignée", batman);
Skin endeavor_skin_1 = new("L'abominable Endeavor", endeavor);
await manager.AddItem(batman_skin_1);
await manager.AddItem(batman_skin_2);
await manager.AddItem(batman_skin_3);
await manager.AddItem(endeavor_skin_1);
}
//uses another instance of the context to do the tests
using (var context = new LolDbContext(options))
{
var manager = new DbData(context).SkinsMgr;
context.Database.EnsureCreated();
var nbItems = await manager.GetNbItems();
Assert.Equal(4, nbItems);
Assert.Equal(4, (await manager.GetItems(0, nbItems)).Count());
var items = await manager.GetItemsByName("Batman", 0, nbItems);
Assert.Equal(2, items.Count());
Champion batman = new("Batman", ChampionClass.Assassin);
items = await manager.GetItemsByChampion(batman, 0, nbItems);
Assert.Equal(3, items.Count());
}
}
[Fact]
public async void Test_Update()
{
//connection must be opened to use In-memory database
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<LolDbContext>()
.UseSqlite(connection)
.Options;
using (var context = new LolDbContext(options))
{
var manager = new DbData(context).SkinsMgr;
var championManager = new DbData(context).ChampionsMgr;
context.Database.EnsureCreated();
Champion batman = new("Batman", ChampionClass.Assassin);
Champion endeavor = new("Endeavor", ChampionClass.Tank);
await championManager.AddItem(batman);
await championManager.AddItem(endeavor);
Skin batman_skin_1 = new("Batman de glace", batman);
Skin batman_skin_2 = new("Batman gold", batman);
Skin batman_skin_3 = new("L'homme araignée", batman);
Skin endeavor_skin_1 = new("L'abominable Endeavor", endeavor);
await manager.AddItem(batman_skin_1);
await manager.AddItem(batman_skin_2);
await manager.AddItem(batman_skin_3);
await manager.AddItem(endeavor_skin_1);
}
//uses another instance of the context to do the tests
using (var context = new LolDbContext(options))
{
var manager = new DbData(context).SkinsMgr;
context.Database.EnsureCreated();
Champion batman = new("Batman", ChampionClass.Assassin);
Champion endeavor = new("Endeavor", ChampionClass.Tank);
var itemsByName = await manager.GetItemsByChampion(batman, 0, 4);
Assert.Equal(3, itemsByName.Count());
Skin batman_skin = new("L'homme araignée", batman);
Skin endeavor_skin = new("L'homme araignée", endeavor);
await manager.UpdateItem(batman_skin, endeavor_skin);
itemsByName = await manager.GetItemsByChampion(batman, 0, 4);
Assert.Equal(2, itemsByName.Count());
context.SaveChanges();
}
}
[Fact]
public async void Test_Delete()
{
//connection must be opened to use In-memory database
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<LolDbContext>()
.UseSqlite(connection)
.Options;
//prepares the database with one instance of the context
using (var context = new LolDbContext(options))
{
var manager = new DbData(context).SkinsMgr;
var championManager = new DbData(context).ChampionsMgr;
context.Database.EnsureCreated();
Champion batman = new("Batman", ChampionClass.Assassin);
Champion endeavor = new("Endeavor", ChampionClass.Tank);
await championManager.AddItem(batman);
await championManager.AddItem(endeavor);
Skin batman_skin_1 = new("Batman de glace", batman);
Skin batman_skin_2 = new("Batman gold", batman);
Skin batman_skin_3 = new("L'homme araignée", batman);
Skin endeavor_skin_1 = new("L'abominable Endeavor", endeavor);
await manager.AddItem(batman_skin_1);
await manager.AddItem(batman_skin_2);
await manager.AddItem(batman_skin_3);
await manager.AddItem(endeavor_skin_1);
}
//uses another instance of the context to do the tests
using (var context = new LolDbContext(options))
{
var manager = new DbData(context).SkinsMgr;
context.Database.EnsureCreated();
await manager.DeleteItem((await manager.GetItemsByName("L'", 0, 4)).First());
await manager.DeleteItem((await manager.GetItemsByName("L'", 0, 3)).First());
Assert.Equal(2, await manager.GetNbItems());
Assert.Equal(2, await manager.GetNbItemsByName("Batman"));
Champion batman = new("Batman", ChampionClass.Assassin);
Assert.Equal(2, await manager.GetNbItemsByChampion(batman));
}
}
}
}

@ -1,46 +1,399 @@
using API_LoL_Project.Controllers;
using DTO;
using Microsoft.AspNetCore.Mvc;
using Model;
using StubLib;
using System.Net;
namespace Test_Api
{
[TestClass]
public class ChampionControllerTest
{
public readonly ChampionsController championCtrl;
public readonly IDataManager stubMgr;
public ChampionControllerTest()
{
var stubMgr = new StubData();
championCtrl = new ChampionsController(stubMgr);
}
[TestMethod]
public async Task TestGetChampions()
{
var getResult = await championCtrl.Get();
Console.WriteLine(getResult);
var objectRes = getResult as OkObjectResult;
Assert.AreEqual(200, objectRes.StatusCode);
Assert.IsNotNull(objectRes);
var champions = objectRes?.Value as IEnumerable<ChampionDTO>;
Assert.IsNotNull(champions);
/*
Assert.AreEqual(champions.Count(), await stubMgr.ChampionsMgr.GetNbItems());*/
}
}
using API_LoL_Project.Controllers;
using API_LoL_Project.Controllers.Request;
using API_LoL_Project.Controllers.Response;
using API_LoL_Project.Controllers.version2;
using API_LoL_Project.Middleware;
using DTO;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Model;
using Shared;
using StubLib;
using System.Collections.ObjectModel;
using System.Net;
using System.Xml.Linq;
namespace Test_Api
{
[TestClass]
public class ChampionControllerTest
{
public readonly ChampionsController championCtrl;
private readonly ILogger<ChampionsController> logger = new NullLogger<ChampionsController>();
public readonly IDataManager stubMgr;
public ChampionControllerTest()
{
stubMgr = new StubData();
championCtrl = new ChampionsController(stubMgr, logger);
}
[TestMethod]
public async Task TestGetSuccesChampions()
{
var totalcountTest = await stubMgr.ChampionsMgr.GetNbItems();
// Arrange
var request = new PageRequest
{
index = 0,
count = 10,
orderingPropertyName = "Name",
descending = false
};
// Create some test data
var champions = new List<Champion>
{
new Champion("Brand", ChampionClass.Mage),
new Champion("Caitlyn", ChampionClass.Marksman),
new Champion("Cassiopeia", ChampionClass.Mage)
};
foreach (var c in champions)
{
await stubMgr.ChampionsMgr.AddItem(c);
}
// Act
var getResult = await championCtrl.Get(request);
// Assert
Assert.IsInstanceOfType(getResult.Result, typeof(OkObjectResult));
var objectRes = getResult.Result as OkObjectResult;
Assert.AreEqual(200, objectRes.StatusCode);
Assert.IsNotNull(objectRes);
var pageResponse = objectRes.Value as PageResponse<ChampionDTO>;
Assert.IsNotNull(pageResponse);
Assert.IsInstanceOfType(pageResponse, typeof(PageResponse<ChampionDTO>));
Assert.AreEqual(totalcountTest + champions.Count, pageResponse.TotalCount);
Assert.AreEqual(totalcountTest + champions.Count, pageResponse.Data.Count());
var endpoints = pageResponse.Data.Select(r => r.Links);
foreach (var endpointList in endpoints)
{
Assert.AreEqual(4, endpointList.Count());
Assert.IsTrue(endpointList.Any(e => e.Href.Contains("/api/[controller]/")));
}
var championsDTO = pageResponse.Data.Select(r => r.Data);
foreach (var c in championsDTO)
{
Assert.IsInstanceOfType(c, typeof(ChampionDTO));
}
}
[TestMethod]
public async Task TestGetChampions_When_Count_Index_Too_High()
{
var totalcountTest = await stubMgr.ChampionsMgr.GetNbItems();
var request = new PageRequest
{
index = 999,
count = 9,
orderingPropertyName = "Name",
descending = false
};
// Act
var getResult = await championCtrl.Get(request);
// Assert
var badRequestResult = getResult.Result as BadRequestObjectResult;
Assert.IsNotNull(badRequestResult);
Assert.AreEqual($"To many object is asked the max is : {totalcountTest}", badRequestResult.Value);
}
[TestMethod]
public async Task TestGetBadRequest_WhenNoChampionsFound()
{
// need to be empty
List<Champion> champions = new()
{
new Champion("Akali", ChampionClass.Assassin),
new Champion("Aatrox", ChampionClass.Fighter),
new Champion("Ahri", ChampionClass.Mage),
new Champion("Akshan", ChampionClass.Marksman),
new Champion("Bard", ChampionClass.Support),
new Champion("Alistar", ChampionClass.Tank),
};
foreach(var c in champions)
{
stubMgr.ChampionsMgr.DeleteItem(c);
}
var request = new PageRequest
{
index = 0,
count = 10,
orderingPropertyName = "Name",
descending = false
};
// Act
var getResult = await championCtrl.Get(request);
Console.WriteLine(getResult);
// Assert
var badRequestResult = getResult.Result as BadRequestObjectResult;
Assert.IsNotNull(badRequestResult);
Assert.AreEqual("To many object is asked the max is : 0", badRequestResult.Value);
}
[TestMethod]
public async Task TestGetChampionByName_ExistingName()
{
// Arrange
var championName = "lopalinda";
var champion = new Champion(championName, ChampionClass.Assassin);
await stubMgr.ChampionsMgr.AddItem(champion);
// Act
var getResult = await championCtrl.GetChampionsByName(championName);
// Assert
/* Assert.IsInstanceOfType(getResult, typeof(OkObjectResult));
var objectRes = getResult.Result as OkObjectResult;
Assert.AreEqual(200, objectRes.StatusCode);
Assert.IsInstanceOfType(okResult.Value, typeof(IEnumerable<LolResponse<ChampionFullDTO>>));
Assert.IsNotNull(objectRes);*/
Assert.IsInstanceOfType(getResult.Result, typeof(OkObjectResult));
var okResult = getResult.Result as OkObjectResult;
Assert.IsInstanceOfType(okResult.Value, typeof(IEnumerable<LolResponse<ChampionFullDTO>>));
var responseList = okResult.Value as IEnumerable<LolResponse<ChampionFullDTO>>;
Assert.AreEqual(1, responseList.Count());
var response = responseList.First();
Assert.AreEqual(champion.Name, response.Data.Name);
}
[TestMethod]
public async Task TestGetChampionsByName_ReturnsBadRequest_WhenNameIsEmpty()
{
// Arrange
var name = "";
// Act
var result = await championCtrl.GetChampionsByName(name);
// Assert
Assert.IsInstanceOfType(result.Result, typeof(BadRequestObjectResult));
var badRequestResult = result.Result as BadRequestObjectResult;
Assert.AreEqual("Can not get champions without the name (is empty)", badRequestResult.Value);
}
[TestMethod]
public async Task TestGetChampionsByName_ReturnsBadRequest_WhenNoChampionsFound()
{
// Arrange
var name = "NonExistentChampionName";
// Act
var result = await championCtrl.GetChampionsByName(name);
// Assert
Assert.IsInstanceOfType(result.Result, typeof(NotFoundObjectResult));
var badRequestResult = result.Result as NotFoundObjectResult;
Assert.AreEqual("No chamions found with this name: NonExistentChampionNamein the dataContext", badRequestResult.Value);
}
/*[TestMethod]
public async Task TestPostChampionsSucess()
{
var championName = "bhbhb";
var expectedChampion = new ChampionFullDTO()
{
Characteristics = new ReadOnlyDictionary<string, int>(new Dictionary<string, int>() {
{ "health", 500 },
{ "attack damage", 60 },
{ "ability power", 0 }
}),
Name = championName,
Bio = "Garen is a strong and noble warrior, the pride of Demacia.",
Class = ChampionClass.Fighter,
Icon = "https://example.com/garen-icon.png",
LargeImage = new ImageDTO() { base64 = "xyz" },
Skins = new List<SkinDto>() {
new SkinDto() {
Name = "Classic Garen",
Description = "The default skin for Garen.",
Icon = "https://example.com/garen-classic-icon.png",
Price = 1350,
LargeImage = new ImageDTO() { base64 = "xyz" }
},
new SkinDto() {
Name = "God-King Garen",
Description = "Garen as a divine being.",
Icon = "https://example.com/garen-god-king-icon.png",
Price = 1820,
LargeImage = new ImageDTO() { base64 = "xyz" }
}
},
Skills = new List<Skill>() {
new Skill("Decisive Strike", SkillType.Basic, "Garen's next attack strikes a vital area of his foe, dealing bonus damage and silencing them."),
new Skill("Courage", SkillType.Basic, "Garen passively increases his armor and magic resistance by killing enemies. He may also activate this ability to gain additional defensive statistics."),
new Skill("Judgment", SkillType.Basic, "Garen rapidly spins his sword around his body, dealing physical damage to nearby enemies and reducing the duration of all incoming crowd control effects."),
new Skill("Demacian Justice", SkillType.Ultimate, "Garen calls upon the might of Demacia to deal a finishing blow to an enemy champion, dealing massive damage based on their missing health.")
}
};
var rep = await championCtrl.Post(expectedChampion);
Assert.AreEqual(200, objectRes.StatusCode);
Assert.IsNotNull(objectRes);
var champions = objectRes?.Value as IEnumerable<ChampionDTO>;
Assert.IsNotNull(champions);
}
*/
[TestMethod]
public async Task TestPost_ReturnsCreatedAndSavedChampion()
{
// Arrange
var expectedChampion = new ChampionFullDTO()
{
Characteristics = new ReadOnlyDictionary<string, int>(new Dictionary<string, int>() {
{ "health", 500 },
{ "attack damage", 60 },
{ "ability power", 0 }
}),
Name = "iuhbbhs",
Bio = "Garen is a strong and noble warrior, the pride of Demacia.",
Class = ChampionClass.Fighter,
Icon = "https://example.com/garen-icon.png",
LargeImage = new ImageDTO() { base64 = "xyz" },
Skins = new List<SkinDto>() {
new SkinDto() {
Name = "Classic Garen",
Description = "The default skin for Garen.",
Icon = "https://example.com/garen-classic-icon.png",
Price = 1350,
LargeImage = new ImageDTO() { base64 = "xyz" }
},
new SkinDto() {
Name = "God-King Garen",
Description = "Garen as a divine being.",
Icon = "https://example.com/garen-god-king-icon.png",
Price = 1820,
LargeImage = new ImageDTO() { base64 = "xyz" }
}
},
Skills = new List<Skill>() {
new Skill("Decisive Strike", SkillType.Basic, "Garen's next attack strikes a vital area of his foe, dealing bonus damage and silencing them."),
new Skill("Courage", SkillType.Basic, "Garen passively increases his armor and magic resistance by killing enemies. He may also activate this ability to gain additional defensive statistics."),
new Skill("Judgment", SkillType.Basic, "Garen rapidly spins his sword around his body, dealing physical damage to nearby enemies and reducing the duration of all incoming crowd control effects."),
new Skill("Demacian Justice", SkillType.Ultimate, "Garen calls upon the might of Demacia to deal a finishing blow to an enemy champion, dealing massive damage based on their missing health.")
}
};
// Act
var postResult = await championCtrl.Post(expectedChampion);
// Assert
Assert.IsInstanceOfType(postResult, typeof(CreatedAtActionResult));
var objectRes = postResult as CreatedAtActionResult;
Assert.AreEqual(201, objectRes.StatusCode);
Assert.IsNotNull(objectRes);
Assert.AreEqual(nameof(championCtrl.Get), objectRes.ActionName);
var createdChampion = objectRes.Value as ChampionDTO;
Assert.IsNotNull(createdChampion);
Assert.AreEqual(expectedChampion.Name, createdChampion.Name);
Assert.AreEqual(expectedChampion.Class, createdChampion.Class);
}
[TestMethod]
public async Task TestPutChampion()
{
// Arrange
var championName = "kakarot";
var updatedChampion = new ChampionDTO
{
Name = championName,
Class = ChampionClass.Mage,
Icon = "dsodm",
Bio = "totto",
};
await stubMgr.ChampionsMgr.AddItem(new Champion(championName, ChampionClass.Assassin));
// Act
var result = await championCtrl.Put(championName, updatedChampion);
// Assert
Assert.IsInstanceOfType(result, typeof(OkObjectResult));
var champion = await stubMgr.ChampionsMgr.GetItemsByName(championName, 0, 1);
Assert.AreEqual(updatedChampion.Name, champion.First().Name);
Assert.AreEqual(updatedChampion.Class, champion.First().Class);
Assert.AreEqual(updatedChampion.Bio, champion.First().Bio);
}
[TestMethod]
public async Task TestDeleteChampion()
{
// Arrange
var championToDelete = new Champion("Yasuo", ChampionClass.Fighter);
await stubMgr.ChampionsMgr.AddItem(championToDelete);
// Act
var result = await championCtrl.Delete(championToDelete.Name);
// Assert
Assert.IsInstanceOfType(result, typeof(OkResult));
Assert.AreEqual(200, (result as OkResult).StatusCode);
var championsAfterDelete = await stubMgr.ChampionsMgr.GetItems(0, await stubMgr.ChampionsMgr.GetNbItems());
Assert.IsFalse(championsAfterDelete.Any(c => c.Name == championToDelete.Name));
}
[TestMethod]
public async Task TestDeleteChampionWithInvalidName()
{
// Arrange
var invalidName = "Invalid Name";
// Act
var result = await championCtrl.Delete(invalidName);
// Assert
Assert.IsInstanceOfType(result, typeof(NotFoundObjectResult));
Assert.AreEqual(404, (result as NotFoundObjectResult).StatusCode);
Assert.AreEqual($"No chamions found with {invalidName} cannot delete", (result as NotFoundObjectResult).Value);
}
[TestMethod]
public async Task TestDeleteChampionWithEmptyName()
{
// Arrange
var emptyName = string.Empty;
// Act
var result = await championCtrl.Delete(emptyName);
// Assert
Assert.IsInstanceOfType(result, typeof(BadRequestObjectResult));
Assert.AreEqual(400, (result as BadRequestObjectResult).StatusCode);
Assert.AreEqual("Can not delelte champions without the name (is empty)", (result as BadRequestObjectResult).Value);
}
}
}

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save