Compare commits

...

118 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
David D'ALMEIDA 9bc670215e count endpoints
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
David D'ALMEIDA d416ae2183 ctrl mostly good
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
David D'ALMEIDA 4a12988b66 merge resoled
continuous-integration/drone/push Build is failing Details
2 years ago
David D'ALMEIDA f7b85e8e5d Merge pull request 'Arthur_EF_Business' (#2) from Arthur_EF_Business into master
2 years ago
David D'ALMEIDA bc808d9264 update
continuous-integration/drone/push Build is failing Details
2 years ago
David D'ALMEIDA 9a38019c38 newww
continuous-integration/drone/push Build is failing Details
2 years ago
David D'ALMEIDA a1369a8d36 Merge branch 'Dave_test' of https://codefirst.iut.uca.fr/git/arthur.valin/League-of-Legends_Project into Dave_test
2 years ago
David D'ALMEIDA 47ade9ad3b next
2 years ago
David D'ALMEIDA f34951672d add
2 years ago
David D'ALMEIDA cbb4e95f57 Merge pull request 'Arthur_EF' (#1) from Arthur_EF into master
2 years ago
David D'ALMEIDA fed5e75530 Mise à jour de '.drone.yml'
continuous-integration/drone/push Build is failing Details
2 years ago
David D'ALMEIDA 206ed6b0f1 Mise à jour de '.drone.yaml'
2 years ago
David D'ALMEIDA fa8b0ce448 Ajouter '.drone.yaml'
2 years ago
David D'ALMEIDA c876900f53 update
2 years ago
David D'ALMEIDA c057f8132c Mise à jour de '.drone.yaml'
2 years ago
David D'ALMEIDA 179397ce86 Mise à jour de '.drone.yaml'
2 years ago
David D'ALMEIDA aa34c7f84b Mise à jour de '.drone.yaml'
2 years ago
David D'ALMEIDA 85603523a6 Ajouter '.drone.yaml'
2 years ago
David D'ALMEIDA 1f0ee639ac new things
2 years ago
David D'ALMEIDA 2681d13de7 create branch
2 years ago

@ -0,0 +1,92 @@
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/API_LoL_Project/Dockerfile
context: EntityFramework_LoL/Sources/
registry: hub.codefirst.iut.uca.fr
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
- dotnet test LeagueOfLegends.sln --no-restore
depends_on: [build]
- 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 ]
- 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: {}

Binary file not shown.

Binary file not shown.

@ -0,0 +1,25 @@
**/.classpath
**/.dockerignore
**/.env
**/.git
**/.gitignore
**/.project
**/.settings
**/.toolstarget
**/.vs
**/.vscode
**/*.*proj.user
**/*.dbmdl
**/*.jfm
**/azds.yaml
**/bin
**/charts
**/docker-compose*
**/Dockerfile*
**/node_modules
**/npm-debug.log
**/obj
**/secrets.dev.yaml
**/values.dev.yaml
LICENSE
README.md

@ -4,17 +4,27 @@
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<UserSecretsId>c1310bab-6367-419f-9338-2a73d29996c3</UserSecretsId>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
</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="service\" />
</ItemGroup>
</Project>

@ -1,67 +0,0 @@
using API_LoL_Project.Mapper;
using DTO;
using Microsoft.AspNetCore.Mvc;
using Model;
using StubLib;
using System.Xml.Linq;
// 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 ChampionsController : ControllerBase
{
IChampionsManager dataManager = new StubData().ChampionsMgr;
// GET: api/<ChampionController>
[HttpGet]
public async Task<IActionResult> Get()
{
var champions = await dataManager.GetItems(0, await dataManager.GetNbItems());
return Ok(new { result = champions.Select(c => c.ToDTO())});
}
// GET api/<ChampionController>/5
[HttpGet("{name}")]
public async Task<IActionResult> Get(string name)
{
var champion = await dataManager
.GetItemsByName(name, 0, await dataManager.GetNbItems());
return Ok(new { result = champion.First().ToDTO() });
}
// POST api/<ChampionController>
[HttpPost]
public async Task<IActionResult> Post([FromBody] ChampionDTO value)
{
await dataManager.AddItem(value.ToModel());
return Ok();
}
// PUT api/<ChampionController>/5
[HttpPut("{name}")]
public async Task<IActionResult> Put(string name, [FromBody] ChampionDTO value)
{
var champion = await dataManager
.GetItemsByName(name, 0, await dataManager.GetNbItems());
await dataManager.UpdateItem(champion.First(), value.ToModel());
return Ok();
}
// DELETE api/<ChampionController>/5
[HttpDelete("{name}")]
public async Task<IActionResult> Delete(string name)
{
var champion = await dataManager
.GetItemsByName(name, 0, await dataManager.GetNbItems());
await dataManager.DeleteItem(champion.First());
return Ok();
}
}
}

@ -0,0 +1,12 @@
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;
}
}

@ -0,0 +1,22 @@
namespace API_LoL_Project.Controllers.Response
{
public class EndPointLink
{
public string Href { get; set; }
public string Rel { get; set; }
public string Method { get; set; }
public EndPointLink()
{
}
public EndPointLink(string href, string rel, string method)
{
Href = href;
Rel = rel;
Method = method;
}
public static EndPointLink To(string href, string rel = "self", string method = "GET")
{
return new EndPointLink { Href = href, Rel = rel, Method = method };
}
}
}

@ -0,0 +1,22 @@
using API_LoL_Project.Middleware;
namespace API_LoL_Project.Controllers.Response
{
public class PageResponse<T>
{
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<LolResponse<T>> data, int indexRequested, int countRequested, int totalCount)
{
this.Data = data;
this.Index = indexRequested;
this.TotalCount = totalCount;
this.Count = countRequested;
}
}
}

@ -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();
}
}
}

@ -0,0 +1,341 @@
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.Text.Json;
using System.Xml.Linq;
using ApiMappeur;
namespace API_LoL_Project.Controllers.version1
{
[Route("api/v{version:apiVersion}/[controller]")]
[ApiVersion("1.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/<ChampionController>/getAllChampions
[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, 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($"/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"),
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/<ChampionController>/LargeImage
[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); ;
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/<ChampionController>/name
[HttpGet("{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.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.LogError($"No chamions found with {name} executing {nameof(GetChampionsByName)}"); ;
return NotFound("No chamions found with" + name);
}
ChampionFullDTO res = champion.First().toFullDTO();//.First
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<ChampionFullDTO>(res, links);
return Ok(response);
}
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/<Champ
[HttpPost]
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
//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 : " + newChampion.Name);
return CreatedAtAction(nameof(Get), newChampion);
}
catch (Exception e)
{
_logger.LogError("Somthing goes wrong caching the Champions controller : " + e.Message);
return BadRequest(e.Message);
}
}
// should change for id cause model implementation use filteringbyName to getItemByNAme and it use substring
// PUT api/<ChampionController>/5
[HttpPut("{name}")]
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();
}
await dataManager.UpdateItem(champion.First(), value.ToModel());
return Ok();
}
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);
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 cliens
// GET: api/champions/Count
[HttpGet("/count", Name = "GetChampionCount")]
public async Task<ActionResult<int>> NbChampions()
{
var nbChampions = await dataManager.GetNbItems();
return Ok(nbChampions);
}
}
}

@ -0,0 +1,189 @@
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)
{
}*/
}
}

@ -0,0 +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 .
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,40 +0,0 @@
using DTO;
using Entities;
using Model;
namespace API_LoL_Project.Mapper
{
public static class ChampionMapper {
public static ChampionDTO ToDTO(this Champion item)
{
return new() {
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 Champion ToModel(this ChampionDTO dto)
{
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,23 +0,0 @@
using DTO;
using Entities;
using Model;
namespace API_LoL_Project.Mapper
{
public static class SkinMapper
{
public static SkinEntity ToEntity(this Skin item)
{
throw new NotImplementedException();
}
public static Skin ToModel(this SkinEntity entity)
{
throw new NotImplementedException();
}
}
}
}

@ -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;
}
}
}

@ -0,0 +1,6 @@
namespace API_LoL_Project.Middleware
{
public class ExceptionMiddleware
{
}
}

@ -0,0 +1,33 @@
using Microsoft.AspNetCore.Http.Headers;
using System.Net;
namespace API_LoL_Project.Middleware
{
public class HttpExeption : Exception
{
public HttpStatusCode StatusCode { get; set; }
public String Message { get; set; }
public HttpExeption(HttpStatusCode statusCode, string message ="") : base(message)
{
this.StatusCode = statusCode;
this.Message = message;
}
/*void AddHeaders(this HttpRequestMessage message, RequestHeaders headers)
{
var headerParameters = headers.Parameters.Where(x => !KnownHeaders.IsContentHeader(x.Name!));
headerParameters.ForEach(x => AddHeader(x, message.Headers));
}
void AddHeader(Parameter parameter, HttpHeaders httpHeaders)
{
var parameterStringValue = parameter.Value!.ToString();
httpHeaders.Remove(parameter.Name!);
httpHeaders.TryAddWithoutValidation(parameter.Name!, parameterStringValue);
}*/
}
}

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

@ -0,0 +1,8 @@
namespace API_LoL_Project.Middleware
{
public class Validator
{
}
}

@ -1,25 +1,107 @@
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>();
var app = builder.Build();
var apiVersionDescriptionProvider = app.Services.GetRequiredService<IApiVersionDescriptionProvider>();
app?.Services?.GetService<LolDbContext>()?.Database.EnsureCreated();
// 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();
app.Run();

@ -1,4 +1,4 @@
{
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
@ -11,13 +11,13 @@
"profiles": {
"API_LoL_Project": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "https://localhost:7041;http://localhost:5233",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"applicationUrl": "https://localhost:7041;http://localhost:5233",
"dotnetRunMessages": true
},
"IIS Express": {
"commandName": "IISExpress",
@ -26,6 +26,13 @@
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"Docker": {
"commandName": "Docker",
"launchBrowser": true,
"launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}/swagger",
"publishAllPorts": true,
"useSSL": true
}
}
}

@ -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);
}
}
}

@ -0,0 +1,23 @@
using DTO;
using Model;
namespace ApiMappeur
{
public static class ImageMappeur
{
public static ImageDTO ToDTO(this LargeImage item)
{
if (item == null)
{
var message = string.Format("Image cannot be empty");
/*throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, message));
*/
}
return new ImageDTO()
{
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;
}
}
}

@ -0,0 +1,37 @@
using DTO;
using Entities;
using Model;
namespace ApiMappeur
{
public static class SkinMapper
{
public static Skin ToModel(this SkinEntity entity)
{
throw new NotImplementedException();
}
public static SkinDto ToDto(this Skin item)
{
return new SkinDto()
{
Name = item.Name,
LargeImage = item.Image.ToDTO(),
Description = item.Description,
Icon = item.Icon,
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());
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());
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,15 +15,22 @@ 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());
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());
@ -56,10 +58,14 @@ namespace Business
}
public async Task<int> GetNbItemsByChampion(Champion? champion)
{
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; }

@ -22,7 +22,7 @@ namespace Business
: temp.OrderBy(item => prop.GetValue(item));
}
}
return temp.Skip(index * count).Take(count)
return temp.Skip(index * count).Take(count);
}
}
}

@ -1,8 +1,47 @@
namespace DTO
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 ChampionClass Class { get; set; }
}
public class ChampionFullDTO
{
[JsonPropertyName("characteristics")]
public ReadOnlyDictionary<string, int> Characteristics { get; set; }
[JsonPropertyName("name")]
public string Name { get; set; }
[JsonPropertyName("bio")]
public string Bio { get; set; }
[JsonPropertyName("class")]
public ChampionClass Class { get; set; }
[JsonPropertyName("icon")]
public string Icon { get; set; }
[JsonPropertyName("largeImage")]
public ImageDTO LargeImage { get; set; }
[JsonPropertyName("skins")]
public IEnumerable<SkinDto> Skins { get; set; }
[JsonPropertyName("skills")]
public IEnumerable<Skill> Skills { get; set; }
}
}

@ -6,4 +6,8 @@
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Model\Model.csproj" />
</ItemGroup>
</Project>

@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DTO
{
public class ImageDTO
{
public string base64 { get; set; }
}
}

@ -0,0 +1,23 @@
using Model;
using Shared;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DTO
{
public class RuneDTO
{
public string Name { get; set; }
public string Description { get; set; }
public RuneFamily Family { get; set; }
public string Icon { get; set; }
public LargeImage Image { 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; }
}
}

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DTO
{
public class SkillDto
{
/* 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
{
}
}

@ -0,0 +1,32 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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,130 +16,31 @@ 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)
{
if (!optionsBuilder.IsConfigured) {
Console.WriteLine("!IsConfigured...");
optionsBuilder.UseSqlite($"Data Source=Entities.Champions.db");
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
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,13 +17,25 @@ 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}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Business", "Business\Business.csproj", "{A447B0BE-62AE-4F66-B887-D1F3D46B0DB3}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Test_Api", "Test_Api\Test_Api.csproj", "{C35C38F6-5774-4562-BD00-C81BCE13A260}"
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
@ -51,18 +63,38 @@ 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
{C463E2E1-237A-4339-A4C4-6EA3BE7002AE}.Release|Any CPU.Build.0 = Release|Any CPU
{C35C38F6-5774-4562-BD00-C81BCE13A260}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C35C38F6-5774-4562-BD00-C81BCE13A260}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C35C38F6-5774-4562-BD00-C81BCE13A260}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C35C38F6-5774-4562-BD00-C81BCE13A260}.Release|Any CPU.Build.0 = Release|Any CPU
{A447B0BE-62AE-4F66-B887-D1F3D46B0DB3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{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
@ -72,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"
}
}
}

@ -16,6 +16,7 @@ namespace StubLib
new Champion("Alistar", ChampionClass.Tank),
};
public class ChampionsManager : IChampionsManager
{
private readonly StubData parent;

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

Loading…
Cancel
Save