Compare commits

..

1 Commits

Author SHA1 Message Date
David D'ALMEIDA 95c05e60a7 push
continuous-integration/drone/push Build is failing Details
2 years ago

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

@ -9,21 +9,19 @@
</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="..\ApiMappeur\ApiMappeur.csproj" />
<ProjectReference Include="..\Business\Business.csproj" />
<ProjectReference Include="..\Entities\Entities.csproj" />
<ProjectReference Include="..\DTO\DTO.csproj" />
<ProjectReference Include="..\Model\Model.csproj" />
<ProjectReference Include="..\StubLib\StubLib.csproj" />
</ItemGroup>
<ItemGroup>
<Folder Include="Controllers\v2\" />
<Folder Include="Controllers\v1\" />
<Folder Include="service\" />
</ItemGroup>

@ -0,0 +1,221 @@
using API_LoL_Project.Mapper;
using API_LoL_Project.Middleware;
using DTO;
using Microsoft.AspNetCore.Mvc;
using Model;
using StubLib;
using System.Text.Json;
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/v{version:apiVersion}/[controller]")]*/
[Route("api/[controller]")]
/*[ApiVersion("1.0")]*/
[ApiController]
public class ChampionsController : ControllerBase
{
public IChampionsManager dataManager;
private readonly ILogger<ChampionsController> _logger;
/* public ChampionsController(IChampionsManager dataManager)
{
this.dataManager = dataManager;
}*/
public ChampionsController(IDataManager dataManager, ILogger<ChampionsController> logger)
{
this.dataManager = dataManager.ChampionsMgr;
this._logger = logger;
}
// GET: api/<ChampionController>
[HttpGet]
public async Task<ActionResult<IEnumerable<ChampionDTO>>> Get([FromQuery] Request.PageRequest request)
{
try
{
var totalcount = await dataManager.GetNbItems();
if (request.count + request.index > totalcount)
{
_logger.LogWarning("No chamions found");
return BadRequest("No chamions found");
}
_logger.LogInformation("Executing {Action} with parameters: {Parameters}", nameof(Get), request);;
var champions = await dataManager.GetItems(request.PageNumber, totalcount, request.orderingPropertyName, (request.descending == null ? false : (bool)request.descending));
IEnumerable<ChampionDTO> res = champions.Select(c => c.toDTO());
if (res.Count() >= 0 || res == null)
{
_logger.LogWarning("No chamions found ");
return BadRequest("No chamions found ");
}
return Ok(res);
}
catch (Exception e)
{
_logger.LogError("");
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>/5
[HttpGet("{name}")]
public async Task<ActionResult<IEnumerable<ChampionFullDTO>>> GetChampionsByName(string 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);
}
}
// POST api/<ChampionController>
[HttpPost]
public async Task<IActionResult> Post([FromBody] ChampionDTO value)
{
try
{
var newChampion = value.toModel();
await dataManager.AddItem(newChampion);
return CreatedAtAction(nameof(Get), newChampion) ;
}
catch (Exception e)
{
return BadRequest(e.Message);
}
}
// PUT api/<ChampionController>/5
[HttpPut("{name}")]
public async Task<IActionResult> Put(string name, [FromBody] ChampionDTO value)
{
try
{
var champion = await dataManager
.GetItemsByName(name, 0, await dataManager.GetNbItems());
await dataManager.UpdateItem(champion.First(), value.toModel());
return Ok();
}
catch(Exception e)
{
return BadRequest(e.Message);
}
}
// DELETE api/<ChampionController>/5
[HttpDelete("{name}")]
public async Task<IActionResult> Delete(string name)
{
try
{
var champion = await dataManager
.GetItemsByName(name, 0, await dataManager.GetNbItems());
if (champion != null) await dataManager.DeleteItem(champion.First());
else
{
return NotFound();
}
return Ok();
}
catch (Exception e)
{
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<Skin>> GetChampionsSkins(string name)
{
var champions = await dataManager.GetItemsByName(name, 0, await dataManager.GetNbItems());
//skinsDTO
IEnumerable<Skin> res = champions.First().Skins;
return Ok(res);
}
[HttpGet("/{name}/skills")]
public async Task<ActionResult<Skin>> GetChampionsSkills(string name)
{
var champions = await dataManager.GetItemsByName(name, 0, await dataManager.GetNbItems());
//SkillDTO
IEnumerable<Skill> res = champions.First().Skills;
return Ok(res);
}
/*[HttpGet("/{name}/skins")]
public async Task<ActionResult<Skill> NbChampions()
{
var champions = await dataManager.GetItems(0, await dataManager.GetNbItems());
IEnumerable<ChampionDTO> res = champions.Select(c => c.toDTO());
return Ok(res);
}*/
}
}

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

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

@ -1,22 +1,7 @@
using API_LoL_Project.Middleware;
namespace API_LoL_Project.Controllers.Response
namespace API_LoL_Project.Controllers.Response
{
public class PageResponse<T>
public class PageResponse
{
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;
}
}
}

@ -0,0 +1,156 @@
using DTO;
using Microsoft.AspNetCore.Mvc;
using Model;
using API_LoL_Project.Mapper;
using System.Xml.Linq;
using System;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace API_LoL_Project.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class RuneController : ControllerBase
{
/*public IRunesManager runesManager;
// you should create a custom logger to be prety
private readonly ILogger<RuneController> _logger;
public RuneController(IDataManager dataManager, ILogger<RuneController> logger)
{
this.runesManager = dataManager.RunesMgr;
this._logger = logger;
}
*//*// GET: api/<RuneController>
[HttpGet]
public async Task<IEnumerable<RuneDTO>> Get()
{
try
{
var runes = await runesManager.GetItems(0, await runesManager.GetNbItems());
IEnumerable<RuneDTO> res = runes.Select(c => c.toDTO());
return Ok(res);
}
catch (Exception e)
{
_logger.LogInformation("About get at {e.message}", DateTime.UtcNow.ToLongTimeString());
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);
}
}
*//* // GET api/<RuneController>/5
[HttpGet("{id}")]
public string GetRuneById(int id)
{
try
{
var rune = await runesManager.GetItemsByName
.(name, 0, await dataManager.GetNbItems());
RuneDto result = champion.First().toDTO();
return Ok(result);
}
}*//*
// GET api/<RuneController>/5
[HttpGet("{name}")]
public async string GetByRuneName(string name)
{
try
{
var rune = await runesManager
.GetItemsByName(name, 0, await runesManager.GetNbItems());
_logger.LogInformation("Executing {Action} with name : {championName}", nameof(GetByRuneName), name);
RuneDTO res = rune.First().toFullDTO();
if (res == null)
{
_logger.LogWarning("No rune found with {name}", name); ;
return NotFound();
}
return Ok(res);
}
catch (Exception e)
{
return BadRequest(e.Message);
}
}
// POST api/<RuneController>
[HttpPost]
public void Post([FromBody] string value)
{
try
{
await dataManager.AddItem(value.toModel());
return Ok();
}
catch ()
{
new HttpException(400, 'Cannot create rune')
}
}
// 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,70 @@
using Microsoft.AspNetCore.Mvc;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace API_LoL_Project.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class RunePageController : ControllerBase
{
// GET: api/<RunePageController>
/*[HttpGet]
public async Task<ActionResult<IEnumerable<RuneDTO>>> Get([FromQuery] Request.PageRequest request)
{
try
{
var totalcount = await runesManager.GetNbItems();
if (request.count + request.index > totalcount)
{
_logger.LogWarning("to many rows ask the max is {totalcount}", totalcount);
return BadRequest("to many rows ask the max is " + totalcount);
}
_logger.LogInformation("Executing {Action} with parameters: {Parameters}", nameof(Get), request);
var runes = await runesManager.GetItems(request.PageNumber, totalcount, request.orderingPropertyName, (request.descending == null ? false : (bool)request.descending));
IEnumerable<RuneDTO> res = runes.Select(c => c.toDTO());
if (res.Count() >= 0 || res == null)
{
_logger.LogWarning("No runes found with Id");
return BadRequest("No runes found with Id ");
}
return Ok(res);
}
catch (Exception e)
{
_logger.LogError("About get at {e.message}", DateTime.UtcNow.ToLongTimeString());
return BadRequest(e.Message);
}
}
// GET api/<RunePageController>/5
[HttpGet("{id}")]
public string Get(int id)
{
return "value";
}
// POST api/<RunePageController>
[HttpPost]
public void Post([FromBody] string value)
{
}
// PUT api/<RunePageController>/5
[HttpPut("{id}")]
public void Put(int id, [FromBody] string value)
{
}
// DELETE api/<RunePageController>/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}*/
}
}

@ -0,0 +1,84 @@
using DTO;
using Microsoft.AspNetCore.Mvc;
using Model;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace API_LoL_Project.Controllers
{
/*[Route("api/[controller]")]
[ApiController]
public class SkinController : ControllerBase
{
public ISkinsManager dataManager;
private readonly ILogger<ChampionsController> _logger;
*//* public ChampionsController(IChampionsManager dataManager)
{
this.dataManager = dataManager;
}*//*
public SkinController(IDataManager dataManager, ILogger<ChampionsController> logger)
{
this.dataManager = dataManager.SkinsMgr;
this._logger = logger;
}
// GET: api/<SkinController>
[HttpGet]
public async Task<ActionResult<IEnumerable<SkinDto>>> 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 skin = await dataManager.GetItems(request.PageNumber, totalcount, request.orderingPropertyName, (request.descending == null ? false : (bool)request.descending));
IEnumerable<SkinDto> res = skin.Select(c => c.toDTO());
if (res.Count() >= 0 || res == null)
{
_logger.LogWarning("No skin founds");
return BadRequest("No skin founds");
}
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,33 @@
using Microsoft.AspNetCore.Mvc;
namespace API_LoL_Project.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
}
}

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

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

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

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

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

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

@ -1,71 +0,0 @@
using Microsoft.AspNetCore.Mvc;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace API_LoL_Project.Controllers.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)
{
}*/
}
}

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

@ -1,27 +1,26 @@
#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
#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 .
ENTRYPOINT ["dotnet", "API_LoL_Project.dll"]

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

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

@ -0,0 +1,58 @@
using DTO;
using Model;
namespace API_LoL_Project.Mapper
{
public static class ChampionMapper
{
public static ChampionDTO toDTO(this Champion item)
{
if (item == null)
{
var message = string.Format("Champion with name = {} nhhoddt found", item.Name);
/*throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, message));
*/
}
return new ChampionDTO() {
Name = item.Name,
Bio = item.Bio
};
}
public static ChampionFullDTO toFullDTO(this Champion item)
{
if (item == null)
{
var message = string.Format("Champion with name = {} nhhoddt found", item.Name);
/*throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, message));
*/
}
return new ChampionFullDTO()
{
Name = item.Name,
Bio = item.Bio,
Characteristics = item.Characteristics,
skills = item.Skills,
skins = item.Skins,
LargeImage = item.Image
};
}
public static Champion toModel(this ChampionDTO dto)
{
if (dto == null)
{
var message = string.Format("Champion with name = {} nhhoddt found", dto.Name);
/*throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, message));
*/}
return new Champion(dto.Name);
}
}
}

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

@ -0,0 +1,6 @@
namespace API_LoL_Project.Mapper
{
public class SkinsMappeur
{
}
}

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

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

@ -1,104 +1,28 @@
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;
using Model;
using StubLib;
var builder = WebApplication.CreateBuilder(args);
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>());
});
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen( cont =>
{
cont.AddSecurityDefinition("ApiKey", new Microsoft.OpenApi.Models.OpenApiSecurityScheme
{
Description = "The Key to acces to the API",
Type = SecuritySchemeType.ApiKey,
Name = "x-api-key",
In = ParameterLocation.Header,
Scheme = "ApiKeyScheme"
});
var scheme = new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "ApiKey"
},
In = ParameterLocation.Header
};
var requirement = new OpenApiSecurityRequirement
{
{
scheme, new List<string>()
}
};
cont.AddSecurityRequirement(requirement);
}
);
builder.Services.AddApiVersioning(opt =>
{
opt.DefaultApiVersion = new Microsoft.AspNetCore.Mvc.ApiVersion(1, 0);
opt.AssumeDefaultVersionWhenUnspecified = true;
opt.ReportApiVersions = true;
opt.ApiVersionReader = ApiVersionReader.Combine(new UrlSegmentApiVersionReader());
});
builder.Services.ConfigureOptions<LolSwaggerOptions>();
builder.Services.AddVersionedApiExplorer(setup =>
{
setup.GroupNameFormat = "'v'VVV";
setup.SubstituteApiVersionInUrl = true;
});
builder.Services.AddScoped<AuthMiddlewareFliter>();
builder.Services.AddSingleton<IDataManager, DbData>();
//builder.Services.AddSingleton<IDataManager, StubData>();
builder.Services.AddSwaggerGen();
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(options =>
{
foreach (var description in apiVersionDescriptionProvider.ApiVersionDescriptions)
{
options.SwaggerEndpoint($"/swagger/{description.GroupName}/swagger.json",
description.GroupName.ToUpperInvariant());
}
});
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();

@ -0,0 +1,13 @@
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,8 +4,5 @@
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"ConnectionStrings": {
"LolDatabase": "Data Source=Entities.LolDatabase.db"
}
}

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

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

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

@ -1,16 +0,0 @@
<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>

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

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

@ -1,367 +0,0 @@
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.");
}
*/

@ -1,201 +0,0 @@
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();
}
}
}
}

@ -1,19 +0,0 @@
<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>

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

@ -1,23 +0,0 @@
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 ?? ""
};
}
}
}

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

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

@ -1,37 +0,0 @@
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 ?? "");
}
}
}

@ -1,15 +0,0 @@
<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="..\EntityMappers\EntityMappers.csproj" />
<ProjectReference Include="..\Model\Model.csproj" />
</ItemGroup>
</Project>

@ -1,146 +0,0 @@
using EntityMapper;
using Microsoft.EntityFrameworkCore;
using Model;
using Shared;
using System.Diagnostics;
namespace Business
{
public partial class DbData
{
public class ChampionsManager : IChampionsManager
{
private readonly DbData parent;
public ChampionsManager(DbData parent)
=> this.parent = parent;
public async Task<Champion?> AddItem(Champion? item)
{
await parent.DbContext.champions.AddAsync(item.ToEntity(parent.DbContext));
parent.DbContext.SaveChanges();
return item;
}
public async Task<bool> DeleteItem(Champion? item)
{
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)
{
Console.WriteLine("GET");
return parent.DbContext.champions.Include("Skills").Include("Characteristics").GetItemsWithFilterAndOrdering(
c => true,
index, count,
orderingPropertyName, descending).Select(c => c.ToModel());
}
public async Task<IEnumerable<Champion?>> GetItemsByCharacteristic(string charName, int index, int count, string? orderingPropertyName = null, bool descending = false)
{
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());
}
public async Task<IEnumerable<Champion?>> GetItemsByClass(ChampionClass championClass, int index, int count, string? orderingPropertyName = null, bool descending = false)
{
return parent.DbContext.champions.Include("Skills").Include("Characteristics").GetItemsWithFilterAndOrdering(
c => c.Class.Equals(championClass),
index, count,
orderingPropertyName, descending).Select(c => c.ToModel());
}
public async Task<IEnumerable<Champion?>> GetItemsByName(string substring, int index, int count, string? orderingPropertyName = null, bool descending = false)
{
return parent.DbContext.champions.Include("Skills").Include("Characteristics").GetItemsWithFilterAndOrdering(
c => c.Name.Contains(substring),
index, count,
orderingPropertyName, descending).Select(c => c.ToModel());
}
public async Task<IEnumerable<Champion?>> GetItemsByRunePage(RunePage? runePage, int index, int count, string? orderingPropertyName = null, bool descending = false)
{
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());
}
public async Task<IEnumerable<Champion?>> GetItemsBySkill(Skill? skill, int index, int count, string? orderingPropertyName = null, bool descending = false)
{
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());
}
public async Task<IEnumerable<Champion?>> GetItemsBySkill(string skill, int index, int count, string? orderingPropertyName = null, bool descending = false)
{
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());
}
public async Task<int> GetNbItems()
{
return parent.DbContext.champions.Count();
}
public async Task<int> GetNbItemsByCharacteristic(string charName)
{
return parent.DbContext.champions.Where(c => c.Characteristics.Any(ch => ch.Name.Equals(charName))).Count();
}
public async Task<int> GetNbItemsByClass(ChampionClass championClass)
{
return parent.DbContext.champions.Where(c => c.Class.Equals(championClass))
.Count();
}
public async Task<int> GetNbItemsByName(string substring)
{
return parent.DbContext.champions.Where(c => c.Name.Contains(substring))
.Count();
}
public async Task<int> GetNbItemsByRunePage(RunePage? runePage)
{
return parent.DbContext.champions.Where(c => c.runepages.Any(rp => rp.Equals(runePage.ToEntity(parent.DbContext)))).Count();
}
public async Task<int> GetNbItemsBySkill(Skill? skill)
{
return parent.DbContext.champions.Where(c => skill != null && c.Skills.Any(s => s.Name.Equals(skill.Name)))
.Count();
}
public async Task<int> GetNbItemsBySkill(string skill)
{
return parent.DbContext.champions.Where(c => skill != null && c.Skills.Any(s => s.Name.Equals(skill)))
.Count();
}
public async Task<Champion?> UpdateItem(Champion? oldItem, Champion? newItem)
{
var toUpdate = parent.DbContext.champions.Find(oldItem.Name);
toUpdate = newItem.ToEntity(parent.DbContext);
parent.DbContext.SaveChanges();
return newItem;
}
}
}
}

@ -1,107 +0,0 @@
using Entities;
using EntityMapper;
using Microsoft.EntityFrameworkCore;
using Model;
namespace Business
{
public partial class DbData
{
public class RunePagesManager : IRunePagesManager
{
private readonly DbData parent;
public RunePagesManager(DbData parent)
=> this.parent = parent;
public async Task<RunePage?> AddItem(RunePage? item)
{
await parent.DbContext.runepages.AddAsync(item.ToEntity(parent.DbContext));
parent.DbContext.SaveChanges();
return item;
}
public async Task<bool> DeleteItem(RunePage? item)
{
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.Include("entries").GetItemsWithFilterAndOrdering(
rp => true,
index, count,
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.Include("champions").GetItemsWithFilterAndOrdering(
rp => rp.champions.Any(c => c.Name.Equals(champion.Name)),
index, count,
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.Include("entries").GetItemsWithFilterAndOrdering(
rp => rp.Name.Contains(substring),
index, count,
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.Include("entries").GetItemsWithFilterAndOrdering(
rp => rp.entries.Any(r => r.RuneName.Equals(rune.Name)),
index, count,
orderingPropertyName, descending).Select(rp => rp.ToModel(parent.DbContext));
}
public async Task<int> GetNbItems()
{
return parent.DbContext.runepages.Count();
}
public async Task<int> GetNbItemsByChampion(Champion? champion)
{
return parent.DbContext.runepages.Where(rp => rp.champions.Any(c => c.Name.Equals(champion.Name))).Count();
}
public async Task<int> GetNbItemsByName(string substring)
{
return parent.DbContext.runepages.Where(rp => rp.Name.Contains(substring)).Count();
}
public async Task<int> GetNbItemsByRune(Model.Rune? rune)
{
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)
{
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,85 +0,0 @@
using EntityMapper;
using Microsoft.EntityFrameworkCore;
using Model;
using Shared;
namespace Business
{
public partial class DbData
{
public class RunesManager : IRunesManager
{
private readonly DbData parent;
public RunesManager(DbData parent)
=> this.parent = parent;
public async Task<Rune?> AddItem(Rune? item)
{
await parent.DbContext.runes.AddAsync(item.ToEntity(parent.DbContext));
parent.DbContext.SaveChanges();
return item;
}
public async Task<bool> DeleteItem(Rune? item)
{
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)
{
return parent.DbContext.runes.GetItemsWithFilterAndOrdering(
r => true,
index, count,
orderingPropertyName, descending).Select(r => r.ToModel());
}
public async Task<IEnumerable<Rune?>> GetItemsByFamily(RuneFamily family, int index, int count, string? orderingPropertyName = null, bool descending = false)
{
return parent.DbContext.runes.GetItemsWithFilterAndOrdering(
r => r.RuneFamily.Equals(family),
index, count,
orderingPropertyName, descending).Select(r => r.ToModel());
}
public async Task<IEnumerable<Rune?>> GetItemsByName(string substring, int index, int count, string? orderingPropertyName = null, bool descending = false)
{
return parent.DbContext.runes.GetItemsWithFilterAndOrdering(
r => r.Name.Contains(substring),
index, count,
orderingPropertyName, descending).Select(r => r.ToModel());
}
public async Task<int> GetNbItems()
{
return parent.DbContext.runes.Count();
}
public async Task<int> GetNbItemsByFamily(RuneFamily family)
{
return parent.DbContext.runes.Where(r => r.RuneFamily.Equals(family)).Count();
}
public async Task<int> GetNbItemsByName(string substring)
{
return parent.DbContext.runes.Where(r => r.Name.Contains(substring)).Count();
}
public async Task<Rune?> UpdateItem(Rune? oldItem, Rune? newItem)
{
var toUpdate = parent.DbContext.runes.Find(oldItem.Name);
toUpdate.Description = newItem.Description;
toUpdate.RuneFamily = newItem.Family;
parent.DbContext.SaveChanges();
return newItem;
}
}
}
}

@ -1,85 +0,0 @@
using EntityMapper;
using Microsoft.EntityFrameworkCore;
using Model;
namespace Business
{
public partial class DbData
{
public class SkinsManager : ISkinsManager
{
private readonly DbData parent;
public SkinsManager(DbData parent)
=> this.parent = parent;
public async Task<Skin?> AddItem(Skin? item)
{
await parent.DbContext.skins.AddAsync(item.ToEntity(parent.DbContext));
parent.DbContext.SaveChanges();
return item;
}
public async Task<bool> DeleteItem(Skin? item)
{
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.Include("Champion").GetItemsWithFilterAndOrdering(
s => true,
index, count,
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.Include("Champion").GetItemsWithFilterAndOrdering(
s => s.Champion.Name.Equals(champion?.Name),
index, count,
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.Include("Champion").GetItemsWithFilterAndOrdering(
s => s.Name.Contains(substring),
index, count,
orderingPropertyName, descending).Select(s => s.ToModel());
}
public async Task<int> GetNbItems()
{
return parent.DbContext.skins.Count();
}
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)
{
return parent.DbContext.skins.Where(s => s.Name.Contains(substring))
.Count();
}
public async Task<Skin?> UpdateItem(Skin? oldItem, Skin? newItem)
{
var toUpdate = parent.DbContext.skins.Find(oldItem.Name);
toUpdate.Champion = parent.DbContext.champions.Find(newItem.Champion.Name);
return newItem;
}
}
}
}

@ -1,28 +0,0 @@
using Entities;
using Microsoft.EntityFrameworkCore;
using Model;
namespace Business
{
public partial class DbData : IDataManager
{
public DbData(LolDbContext dbContext)
{
DbContext = dbContext;
ChampionsMgr = new ChampionsManager(this);
SkinsMgr = new SkinsManager(this);
RunesMgr = new RunesManager(this);
RunePagesMgr = new RunePagesManager(this);
}
protected LolDbContext DbContext{ get; }
public IChampionsManager ChampionsMgr { get; }
public ISkinsManager SkinsMgr { get; }
public IRunesManager RunesMgr { get; }
public IRunePagesManager RunePagesMgr { get; }
}
}

@ -1,28 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Business
{
static class Extensions
{
internal static IEnumerable<T?> GetItemsWithFilterAndOrdering<T>(this IEnumerable<T> collection,
Func<T, bool> filter, int index, int count, string? orderingPropertyName = null, bool descending = false)
{
IEnumerable<T> temp = collection;
temp = temp.Where(item => filter(item));
if (orderingPropertyName != null)
{
var prop = typeof(T).GetProperty(orderingPropertyName!);
if (prop != null)
{
temp = descending ? temp.OrderByDescending(item => prop.GetValue(item))
: temp.OrderBy(item => prop.GetValue(item));
}
}
return temp.Skip(index * count).Take(count);
}
}
}

@ -1,47 +1,25 @@
using Model;
using Shared;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;
using System.Text.Json.Serialization;
using static System.Net.Mime.MediaTypeNames;
using Model;
using System.Collections.ObjectModel;
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 string Bio { get; set; }
public string Icon { get; set; }
/*public string Icon { 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; }
public ReadOnlyDictionary<string, int> Characteristics { get; set; }
public LargeImage LargeImage { 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; }
public IEnumerable<Skin> skins { get; set; }
public IEnumerable<Skill> skills { get; set; }
[JsonPropertyName("skills")]
public IEnumerable<Skill> Skills { get; set; }
}
}

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

@ -1,5 +1,4 @@
using Model;
using Shared;
using System;
using System.Collections.Generic;
using System.Linq;
@ -14,9 +13,9 @@ namespace DTO
public string Description { get; set; }
public RuneFamily Family { get; set; }
public RuneFamily Family { get; set; }
public string Icon { get; set; }
public string Icon { get; set; }
public LargeImage Image { get; set; }
}

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

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

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

@ -8,25 +8,10 @@ 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; }
}
}

@ -1,28 +0,0 @@
using Shared;
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Entities
{
public class ChampionEntity
{
[Key]
[MaxLength(256)]
public string Name { get; set; }
[Required]
[MaxLength(500)]
public string Bio { get; set; }
public string Icon { get; set; }
[Required]
public ChampionClass Class { get; set;}
public virtual ICollection<SkillEntity> Skills { get; set; }
public virtual ICollection<CharacteristicEntity> Characteristics { get; set; }
public ICollection<RunePageEntity> runepages { get; set; }
public Guid? ImageId { get; set; }
[ForeignKey("ImageId")]
public LargeImageEntity? Image { get; set; }
}
}

@ -1,26 +0,0 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Entities
{
public class CharacteristicEntity
{
[Key]
[MaxLength(256)]
public string Name { get; set; }
[Required]
public int Value { get; set; }
[Required]
public string ChampionForeignKey { get; set; }
[ForeignKey("ChampionForeignKey")]
public ChampionEntity Champion { get; set; }
}
}

@ -1,28 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<StartWorkingDirectory>$(MSBuildProjectDirectory)</StartWorkingDirectory>
<OutputType>Exe</OutputType>
</PropertyGroup>
<ItemGroup>
<Compile Remove="Programme.cs" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="7.0.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.2">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Shared\Shared.csproj" />
</ItemGroup>
</Project>

@ -1,19 +0,0 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Entities
{
public class LargeImageEntity
{
[Key]
public Guid Id { get; set; }
[Required]
public string Base64 { get; set; }
}
}

@ -1,46 +0,0 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Shared;
using System.Reflection.Metadata;
using System.Security.Claims;
using System.Xml.Linq;
namespace Entities
{
public class LolDbContext : DbContext
{
public DbSet<SkinEntity> skins { get; set; }
public DbSet<ChampionEntity> champions { get; set; }
public DbSet<CharacteristicEntity> characteristics { get; set; }
public DbSet<SkillEntity> skills { get; set; }
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<ChampionEntity>()
.HasMany(x => x.runepages)
.WithMany(x => x.champions);
}
}
internal record NewRecord(string Name, string Item);
}

@ -1,121 +0,0 @@
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,16 +0,0 @@
using Entities;
using Shared;
ChampionEntity imri = new()
{
Name = "Imri Cartel",
Bio = "Fou Furieux",
Class = ChampionClass.Assassin
};
using (var context = new LolDbContext(null))
{
// Crée des nounours et les insère dans la base
Console.WriteLine("Creates and inserts new Champion");
context.Add(imri);
context.SaveChanges();
}

@ -1,34 +0,0 @@
using Shared;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Entities
{
public class RuneEntity
{
[Key]
[MaxLength(256)]
public string Name { get; set; }
[Required]
[MaxLength(500)]
public string Description { get; set; }
public string Icon { get; set; }
[Required]
public RuneFamily RuneFamily { get; set; }
public ICollection<RunePageRuneEntity>? runepages { get; set; }
public Guid? ImageId { get; set; }
[ForeignKey("ImageId")]
public LargeImageEntity? Image { get; set; }
}
}

@ -1,20 +0,0 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Entities
{
public class RunePageEntity
{
[Key]
[MaxLength(256)]
public string Name { get; set; }
public ICollection<RunePageRuneEntity> entries { get; set; }
public ICollection<ChampionEntity> champions { get; set; }
}
}

@ -1,20 +0,0 @@
using Shared;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Entities
{
public class RunePageRuneEntity
{
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,29 +0,0 @@
using Shared;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Entities
{
public class SkillEntity
{
[Key]
[MaxLength(256)]
public string Name { get; set; }
[Required]
[MaxLength(500)]
public string Description { get; set; }
[Required]
public SkillType SkillType { get; set; }
public virtual ICollection<ChampionEntity>? Champions { get; set; }
}
}

@ -1,37 +0,0 @@
using Shared;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Entities
{
public class SkinEntity
{
[Key]
[MaxLength(256)]
public string Name { get; set; }
[Required]
[MaxLength(500)]
public string Description { get; set; }
[Required]
public string Icon { get; set; }
[Required]
public float Price { get; set; }
[Required]
public string ChampionForeignKey { get; set; }
[ForeignKey("ChampionForeignKey")]
public ChampionEntity Champion { get; set; }
public Guid? ImageId { get; set; }
[ForeignKey("ImageId")]
public LargeImageEntity? Image { get; set; }
}
}

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

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

@ -1,14 +0,0 @@
<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>

@ -1,35 +0,0 @@
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??"");
}
}
}

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

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

@ -1,31 +0,0 @@
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??"");
}
}
}

@ -1,114 +1,70 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.4.33205.214
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Model", "Model\Model.csproj", "{2960F9BA-49DE-494D-92E3-CE5A794BA1A9}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tests", "Tests", "{C76D0C23-1FFA-4963-93CD-E12BD643F030}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ConsoleTests", "Tests\ConsoleTests\ConsoleTests.csproj", "{1889FA6E-B7C6-416E-8628-9449FB9070B9}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Shared", "Shared\Shared.csproj", "{3B720C0C-53FE-4642-A2DB-87FD8634CD74}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Stub", "Stub", "{2C607793-B163-4731-A4D1-AFE8A7C4C170}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "StubLib", "StubLib\StubLib.csproj", "{B01D7EF2-2D64-409A-A29A-61FB7BB7A9DB}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "API_LoL_Project", "API_LoL_Project\API_LoL_Project.csproj", "{4EDC93E0-35B8-4EF1-9318-24F7A606BA97}"
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("{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
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{2960F9BA-49DE-494D-92E3-CE5A794BA1A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{2960F9BA-49DE-494D-92E3-CE5A794BA1A9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2960F9BA-49DE-494D-92E3-CE5A794BA1A9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2960F9BA-49DE-494D-92E3-CE5A794BA1A9}.Release|Any CPU.Build.0 = Release|Any CPU
{1889FA6E-B7C6-416E-8628-9449FB9070B9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1889FA6E-B7C6-416E-8628-9449FB9070B9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1889FA6E-B7C6-416E-8628-9449FB9070B9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1889FA6E-B7C6-416E-8628-9449FB9070B9}.Release|Any CPU.Build.0 = Release|Any CPU
{3B720C0C-53FE-4642-A2DB-87FD8634CD74}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3B720C0C-53FE-4642-A2DB-87FD8634CD74}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3B720C0C-53FE-4642-A2DB-87FD8634CD74}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3B720C0C-53FE-4642-A2DB-87FD8634CD74}.Release|Any CPU.Build.0 = Release|Any CPU
{B01D7EF2-2D64-409A-A29A-61FB7BB7A9DB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B01D7EF2-2D64-409A-A29A-61FB7BB7A9DB}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B01D7EF2-2D64-409A-A29A-61FB7BB7A9DB}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B01D7EF2-2D64-409A-A29A-61FB7BB7A9DB}.Release|Any CPU.Build.0 = Release|Any CPU
{4EDC93E0-35B8-4EF1-9318-24F7A606BA97}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{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
{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
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{1889FA6E-B7C6-416E-8628-9449FB9070B9} = {C76D0C23-1FFA-4963-93CD-E12BD643F030}
{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}
EndGlobalSection
EndGlobal

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.4.33205.214
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Model", "Model\Model.csproj", "{2960F9BA-49DE-494D-92E3-CE5A794BA1A9}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tests", "Tests", "{C76D0C23-1FFA-4963-93CD-E12BD643F030}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ConsoleTests", "Tests\ConsoleTests\ConsoleTests.csproj", "{1889FA6E-B7C6-416E-8628-9449FB9070B9}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Shared", "Shared\Shared.csproj", "{3B720C0C-53FE-4642-A2DB-87FD8634CD74}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Stub", "Stub", "{2C607793-B163-4731-A4D1-AFE8A7C4C170}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "StubLib", "StubLib\StubLib.csproj", "{B01D7EF2-2D64-409A-A29A-61FB7BB7A9DB}"
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("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Test_Api", "Test_Api\Test_Api.csproj", "{C35C38F6-5774-4562-BD00-C81BCE13A260}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{2960F9BA-49DE-494D-92E3-CE5A794BA1A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{2960F9BA-49DE-494D-92E3-CE5A794BA1A9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2960F9BA-49DE-494D-92E3-CE5A794BA1A9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2960F9BA-49DE-494D-92E3-CE5A794BA1A9}.Release|Any CPU.Build.0 = Release|Any CPU
{1889FA6E-B7C6-416E-8628-9449FB9070B9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1889FA6E-B7C6-416E-8628-9449FB9070B9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1889FA6E-B7C6-416E-8628-9449FB9070B9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1889FA6E-B7C6-416E-8628-9449FB9070B9}.Release|Any CPU.Build.0 = Release|Any CPU
{3B720C0C-53FE-4642-A2DB-87FD8634CD74}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3B720C0C-53FE-4642-A2DB-87FD8634CD74}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3B720C0C-53FE-4642-A2DB-87FD8634CD74}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3B720C0C-53FE-4642-A2DB-87FD8634CD74}.Release|Any CPU.Build.0 = Release|Any CPU
{B01D7EF2-2D64-409A-A29A-61FB7BB7A9DB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B01D7EF2-2D64-409A-A29A-61FB7BB7A9DB}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B01D7EF2-2D64-409A-A29A-61FB7BB7A9DB}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B01D7EF2-2D64-409A-A29A-61FB7BB7A9DB}.Release|Any CPU.Build.0 = Release|Any CPU
{4EDC93E0-35B8-4EF1-9318-24F7A606BA97}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{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
{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
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{1889FA6E-B7C6-416E-8628-9449FB9070B9} = {C76D0C23-1FFA-4963-93CD-E12BD643F030}
{B01D7EF2-2D64-409A-A29A-61FB7BB7A9DB} = {2C607793-B163-4731-A4D1-AFE8A7C4C170}
{C35C38F6-5774-4562-BD00-C81BCE13A260} = {C76D0C23-1FFA-4963-93CD-E12BD643F030}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {92F3083D-793F-4552-8A9A-0AD6534159C9}
EndGlobalSection
EndGlobal

@ -1,5 +1,4 @@
using Shared;
using System.Collections.Immutable;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.Numerics;
using System.Text;
@ -63,7 +62,7 @@ public class Champion : IEquatable<Champion>
public ImmutableHashSet<Skill> Skills => skills.ToImmutableHashSet();
private HashSet<Skill> skills = new HashSet<Skill>();
public bool AddSkin(Skin skin)
internal bool AddSkin(Skin skin)
{
if (skins.Contains(skin))
return false;

@ -9,6 +9,9 @@
<ItemGroup>
<None Remove="enums\" />
</ItemGroup>
<ItemGroup>
<Folder Include="enums\" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Shared\Shared.csproj" />
</ItemGroup>

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

@ -1,4 +1,4 @@
using Shared;
using System;
namespace Model
{

@ -1,5 +1,8 @@
namespace Shared
using System;
namespace Model
{
public partial class RunePage
{
public enum Category
{
Major,
@ -9,5 +12,6 @@
OtherMinor1,
OtherMinor2
}
}
}

@ -1,4 +1,4 @@
using Shared;
using System;
using System.Collections.ObjectModel;
namespace Model

@ -1,4 +1,4 @@
using Shared;
using System;
namespace Model
{

@ -1,4 +1,5 @@
namespace Shared
using System;
namespace Model
{
public enum ChampionClass
{

@ -1,4 +1,5 @@
namespace Shared
using System;
namespace Model
{
public enum RuneFamily
{

@ -1,4 +1,5 @@
namespace Shared
using System;
namespace Model
{
public enum SkillType
{

@ -1,15 +0,0 @@
using Entities;
ChampionEntity dave = new()
{
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();
}

@ -1,15 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<StartWorkingDirectory>$(MSBuildProjectDirectory)</StartWorkingDirectory>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Entities\Entities.csproj" />
</ItemGroup>
</Project>

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

@ -1,6 +1,5 @@
using System;
using Model;
using Shared;
namespace StubLib
{
@ -11,12 +10,12 @@ namespace StubLib
private void InitRunePages()
{
var runePage1 = new RunePage("rune page 1");
runePage1[Category.Major] = runes[0];
runePage1[Category.Minor1] = runes[1];
runePage1[Category.Minor2] = runes[2];
runePage1[Category.Minor3] = runes[3];
runePage1[Category.OtherMinor1] = runes[4];
runePage1[Category.OtherMinor2] = runes[5];
runePage1[RunePage.Category.Major] = runes[0];
runePage1[RunePage.Category.Minor1] = runes[1];
runePage1[RunePage.Category.Minor2] = runes[2];
runePage1[RunePage.Category.Minor3] = runes[3];
runePage1[RunePage.Category.OtherMinor1] = runes[4];
runePage1[RunePage.Category.OtherMinor2] = runes[5];
runePages.Add(runePage1);
}

@ -1,6 +1,5 @@
using System;
using Model;
using Shared;
namespace StubLib
{

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

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

@ -1,32 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="7.0.3" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.3.2" />
<PackageReference Include="xunit" Version="2.4.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.5">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="coverlet.collector" Version="3.1.2">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Business\Business.csproj" />
<ProjectReference Include="..\Entities\Entities.csproj" />
<ProjectReference Include="..\Model\Model.csproj" />
</ItemGroup>
</Project>

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

Loading…
Cancel
Save