merge sucess
continuous-integration/drone/push Build is failing Details

Dave_more
David D'ALMEIDA 2 years ago
parent 6818af2b49
commit b0802493c0

@ -9,13 +9,15 @@
</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="..\DTO\DTO.csproj" />
<ProjectReference Include="..\Entities\Entities.csproj" />
<ProjectReference Include="..\Model\Model.csproj" />
<ProjectReference Include="..\StubLib\StubLib.csproj" />

@ -1,189 +0,0 @@
using API_LoL_Project.Mapper;
using API_LoL_Project.Middleware;
using DTO;
using Microsoft.AspNetCore.Mvc;
using Model;
using StubLib;
using System.Xml.Linq;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace API_LoL_Project.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ChampionsController : ControllerBase
{
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 with Id");
return BadRequest("No chamions found with Id ");
}
_logger.LogInformation("Executing {Action} with parameters: {Parameters}", nameof(Get), request);;
var champions = await dataManager.GetItems(request.index, request.count, request.orderingPropertyName, request.descending);
IEnumerable<ChampionDTO> res = champions.Select(c => c.ToDTO());
if (res.Count() <= 0 || res == null)
{
_logger.LogWarning("No chamions found with Id");
return BadRequest("No chamions found with Id ");
}
return Ok(res);
}
catch (Exception e)
{
return BadRequest(e.Message);
}
}
// GET api/<ChampionController>/5
[HttpGet("{name}")]
public async Task<ActionResult<ChampionDTO>> GetChampionsByName(string name)
{
try
{
var champion = await dataManager
.GetItemsByName(name, 0, await dataManager.GetNbItems());
_logger.LogInformation("Executing {Action} with name : {championName}", nameof(GetChampionsByName), name);
ChampionDTO res = champion.First().ToDTO();
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);
}*/
}
}

@ -3,8 +3,10 @@
public class PageRequest
{
public string? orderingPropertyName { get; set; } = null;
public bool descending { get; set; } = false;
public int index { get; set; } = 1;
public bool? descending { get; set; } = false;
public int index { get; set; } = 0;
public int count { get; set; } = 1;
}
}

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

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

@ -2,6 +2,8 @@
using Microsoft.AspNetCore.Mvc;
using Model;
using API_LoL_Project.Mapper;
using API_LoL_Project.Controllers.Response;
using API_LoL_Project.Middleware;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
@ -10,111 +12,166 @@ namespace API_LoL_Project.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class RuneController : ControllerBase
{
/*public IRunesManager runesManager;
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.runesManager = dataManager.RunesMgr;
this.dataManager = dataManager.RunesMgr;
this._logger = logger;
}
*//*// GET: api/<RuneController>
/*// GET: api/<RuneController>
[HttpGet]
public async Task<IEnumerable<RuneDTO>> Get()
public async Task<ActionResult<IEnumerable<RuneDTO>>> GetAllRunes([FromQuery] Request.PageRequest request)
{
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)
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.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(Get), request);
var runes = await runesManager.GetItems(request.PageNumber, totalcount, request.orderingPropertyName,(request.descending == null ? false : (bool)request.descending));
_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)
if (res.Count() <= 0 || res == null)
{
_logger.LogWarning("No runes found with Id");
return BadRequest("No runes found with Id ");
_logger.LogError("No runes found the total count is {totalcount} ", totalcount);
return BadRequest("No runes found : totalcount is : " + totalcount);
}
return Ok(res);
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("About get at {e.message}", DateTime.UtcNow.ToLongTimeString());
_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);
// 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)
{
}
catch (Exception e)
{
new HttpException(400, 'Cannot get rune :' + e.message);
}
_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)
{
// 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')
}
new HttpException(400, 'Cannot get rune :' + e.message);
}
}
}*/
// POST api/<RuneController>
// PUT api/<RuneController>/5
[HttpPut("{id}")]
@ -127,6 +184,6 @@ namespace API_LoL_Project.Controllers
[HttpDelete("{id}")]
public void Delete(int id)
{
}*/
}
}
}

@ -9,7 +9,7 @@ namespace API_LoL_Project.Controllers
[ApiController]
public class RunePageController : ControllerBase
{
/* // GET: api/<RunePageController>
/* // GET: api/<RunePageController>
[HttpGet]
public async Task<ActionResult<IEnumerable<RuneDTO>>> Get([FromQuery] Request.PageRequest request)
{

@ -1,4 +1,6 @@
using Microsoft.AspNetCore.Mvc;
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
@ -8,13 +10,21 @@ namespace API_LoL_Project.Controllers
[ApiController]
public class SkinController : ControllerBase
{
/* // GET: api/<SkinController>
/* 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 runesManager.GetNbItems();
var totalcount = await dataManager.GetNbItems();
if (request.count + request.index > totalcount)
{
_logger.LogWarning("to many rows ask the max is {totalcount}", totalcount);
@ -23,7 +33,7 @@ namespace API_LoL_Project.Controllers
_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));
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)
{

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

@ -0,0 +1,339 @@
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
[HttpGet("/count")]
public async Task<ActionResult<int>> NbChampions()
{
var nbChampions = await dataManager.GetNbItems();
return Ok(nbChampions);
}
}
}

@ -0,0 +1,399 @@
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;
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, 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<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);
_logger.LogError($"========================= {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}/{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"),
}
));
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);
}
// 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);
}
}
// 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);
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 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
[HttpGet("/count")]
public async Task<ActionResult<int>> NbChampions()
{
var nbChampions = await dataManager.GetNbItems();
return Ok(nbChampions);
}
}
}

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

@ -0,0 +1,65 @@
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.Extensions.Options;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
namespace API_LoL_Project
{
public class LolSwaggerOptions : IConfigureNamedOptions<SwaggerGenOptions>
{
private readonly IApiVersionDescriptionProvider _provider;
public LolSwaggerOptions(
IApiVersionDescriptionProvider provider)
{
_provider = provider;
}
/// <summary>
/// Configure each API discovered for Swagger Documentation
/// </summary>
/// <param name="options"></param>
public void Configure(SwaggerGenOptions options)
{
// add swagger document for every API version discovered
foreach (var description in _provider.ApiVersionDescriptions)
{
options.SwaggerDoc(
description.GroupName,
CreateVersionInfo(description));
}
}
/// <summary>
/// Configure Swagger Options. Inherited from the Interface
/// </summary>
/// <param name="name"></param>
/// <param name="options"></param>
public void Configure(string name, SwaggerGenOptions options)
{
Configure(options);
}
/// <summary>
/// Create information about the version of the API
/// </summary>
/// <param name="description"></param>
/// <returns>Information about the API</returns>
private OpenApiInfo CreateVersionInfo(
ApiVersionDescription desc)
{
var info = new OpenApiInfo()
{
Title = ".NET Core (.NET 6) Web API",
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;
}
}
}

@ -6,20 +6,6 @@ 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 ChampionEntity ToEntity(this Champion item)
{
return new()
@ -31,27 +17,7 @@ namespace API_LoL_Project.Mapper
Image = new() { Base64 = item.Image.Base64 },
};
}
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,
skills = item.Skills,
skins = item.Skins,
LargeImage = item.Image.Base64
};
}
public static Champion ToModel(this ChampionDTO dto)
{
if (dto == null)

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

@ -1,8 +1,13 @@
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;
var builder = WebApplication.CreateBuilder(args);
@ -10,14 +15,33 @@ var connectionString = builder.Configuration.GetConnectionString("LolDatabase");
builder.Services.AddDbContext<LolDbContext>(options =>
options.UseSqlite(connectionString), ServiceLifetime.Singleton);
builder.Services.AddControllers();
builder.Services.AddControllers().AddJsonOptions(options =>
{
options.JsonSerializerOptions.Converters.Add(new ReadOnlyDictionaryConverter<string, int>());
});
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
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.AddSingleton<IDataManager, DbData>();
//builder.Services.AddSingleton<IDataManager, StubData>();
var app = builder.Build();
var apiVersionDescriptionProvider = app.Services.GetRequiredService<IApiVersionDescriptionProvider>();
app?.Services?.GetService<LolDbContext>()?.Database.EnsureCreated();
@ -25,7 +49,15 @@ app?.Services?.GetService<LolDbContext>()?.Database.EnsureCreated();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
/* app.UseSwaggerUI();*/
app.UseSwaggerUI(options =>
{
foreach (var description in apiVersionDescriptionProvider.ApiVersionDescriptions)
{
options.SwaggerEndpoint($"/swagger/{description.GroupName}/swagger.json",
description.GroupName.ToUpperInvariant());
}
});
}
app.UseHttpsRedirection();

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

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

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

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

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

@ -0,0 +1,31 @@
 using DTO;
using Model;
namespace API_LoL_Project.Mapper
{
public static class RuneMapper
{
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,10 @@
using Entities;
using Model;
namespace ApiMappeur
{
public static class RunePageMapper
{
}
}

@ -0,0 +1,30 @@
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,
Description = item.Description,
Icon = item.Icon,
Price = item.Price
};
}
}
}

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

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

@ -14,9 +14,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; }
}

@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DTO
{
public class SkillDto
{
public string Name { get; set; }
public string Description { get; set; }
}
}

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DTO
{
public class SkinDto
{
public string Name { get; set; }
public string Description { get; set; }
public string Icon { get; set; }
public float Price { get; set; }
}
}

@ -17,8 +17,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "StubLib", "StubLib\StubLib.
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "API_LoL_Project", "API_LoL_Project\API_LoL_Project.csproj", "{4EDC93E0-35B8-4EF1-9318-24F7A606BA97}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DTO", "DTO\DTO.csproj", "{7F6A519E-98F8-429E-B34F-9B0D20075CFB}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Entity Framework", "Entity Framework", "{BC2FFCA4-3801-433F-A83E-B55345F3B31E}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Entities", "Entities\Entities.csproj", "{C463E2E1-237A-4339-A4C4-6EA3BE7002AE}"
@ -26,13 +24,18 @@ 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}"
<<<<<<< HEAD
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EntityMappers", "EntityMappers\EntityMappers.csproj", "{3A70A719-4F42-4CC3-846A-53437F3B4CC5}"
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("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestEF", "TestEF\TestEF.csproj", "{059B4A61-E9D5-4C00-8178-C8714D781FBC}"
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
@ -60,10 +63,6 @@ Global
{4EDC93E0-35B8-4EF1-9318-24F7A606BA97}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4EDC93E0-35B8-4EF1-9318-24F7A606BA97}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4EDC93E0-35B8-4EF1-9318-24F7A606BA97}.Release|Any CPU.Build.0 = Release|Any CPU
{7F6A519E-98F8-429E-B34F-9B0D20075CFB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7F6A519E-98F8-429E-B34F-9B0D20075CFB}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7F6A519E-98F8-429E-B34F-9B0D20075CFB}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7F6A519E-98F8-429E-B34F-9B0D20075CFB}.Release|Any CPU.Build.0 = Release|Any CPU
{C463E2E1-237A-4339-A4C4-6EA3BE7002AE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C463E2E1-237A-4339-A4C4-6EA3BE7002AE}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C463E2E1-237A-4339-A4C4-6EA3BE7002AE}.Release|Any CPU.ActiveCfg = Release|Any CPU
@ -84,6 +83,18 @@ Global
{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

@ -1,7 +1,12 @@
using API_LoL_Project.Controllers;
using API_LoL_Project.Controllers.Request;
using API_LoL_Project.Controllers.Response;
using API_LoL_Project.Controllers.version2;
using DTO;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Model;
using StubLib;
using System.Net;
@ -11,38 +16,183 @@ namespace Test_Api
[TestClass]
public class ChampionControllerTest
{
public readonly ChampionsController championCtrl;
public ChampionsController championCtrl;
private readonly ILogger<ChampionsController> logger = new NullLogger<ChampionsController>();
public readonly IDataManager stubMgr;
public ChampionControllerTest(ILogger<ChampionsController> logger)
public ChampionControllerTest()
{
var stubMgr = new StubData();
championCtrl = new ChampionsController(stubMgr, logger);
}
/*
[TestMethod]
public async Task TestGetChampions()
{
/* var getResult = await championCtrl.Get();
Console.WriteLine(getResult);
var objectRes = getResult as OkObjectResult;
var request = new PageRequest
{
index = 0,
count = 10,
orderingPropertyName = "Name",
descending = false
};
var totalcountTest = await stubMgr.ChampionsMgr.GetNbItems();
// Act
var getResult = await championCtrl.Get(request);
// Assert
Assert.IsInstanceOfType(getResult, typeof(OkObjectResult));
var objectRes = getResult.Result as OkObjectResult;
Assert.AreEqual(200, objectRes.StatusCode);
Assert.IsNotNull(objectRes);
var champions = objectRes?.Value as IEnumerable<ChampionDTO>;
Assert.IsNotNull(champions);*/
Assert.IsNotNull(champions);
/*
Assert.AreEqual(champions.Count(), await stubMgr.ChampionsMgr.GetNbItems());*/
Assert.IsInstanceOfType(objectRes.Value, typeof(PageResponse<ChampionDTO>));
var pageResponse = objectRes.Value as PageResponse<ChampionDTO>;
Assert.AreEqual(totalcountTest, pageResponse.TotalCount);
Assert.AreEqual(totalcountTest, pageResponse.Data.Count());
*//* Assert.AreEqual(1, pageResponse.Data[.Data.Id);
*//* Assert.AreEqual("Champion1", pageResponse.Items[0].Data.Name);
*//* Assert.AreEqual(2, pageResponse.Items[1].Data.Id);
*//* Assert.AreEqual("Champion2", pageResponse.Items[1].Data.Name);
*/
/*
Assert.AreEqual(champions.Count(), await stubMgr.ChampionsMgr.GetNbItems());*//*
}
[TestMethod]
public async Task TestGetChampions_When_Count_Index_Too_High()
{
var totalcountTest = await stubMgr.ChampionsMgr.GetNbItems();
var request = new PageRequest
{
index = 999,
count = 9,
orderingPropertyName = "Name",
descending = false
};
// Act
var getResult = await championCtrl.Get(request);
// Assert
var badRequestResult = getResult.Result as BadRequestObjectResult;
Assert.IsNotNull(badRequestResult);
Assert.AreEqual("To many object is asked the max is : {totalcountTest}", badRequestResult.Value);
}
[TestMethod]
public async Task TestGetBadRequest_WhenNoChampionsFound()
{
///var totalcountTest = await stubMgr.ChampionsMgr.GetNbItems();
// need to be empty
var request = new PageRequest
{
index = 0,
count = 10,
orderingPropertyName = "Name",
descending = false
};
// Act
var getResult = await championCtrl.Get(request);
Console.WriteLine(getResult);
// Assert
var badRequestResult = getResult.Result as BadRequestObjectResult;
Assert.IsNotNull(badRequestResult);
Assert.AreEqual("No chamions found : totalcount is : 0", badRequestResult.Value);
}
*/
/*
[TestMethod]
public async Task TestPostChampions()
{
var getResult = await championCtrl.Get();
Console.WriteLine(getResult);
var objectRes = getResult as OkObjectResult;
Assert.AreEqual(200, objectRes.StatusCode);
Assert.IsNotNull(objectRes);
var champions = objectRes?.Value as IEnumerable<ChampionDTO>;
Assert.IsNotNull(champions);
}
[TestMethod]
public async Task TestUpdateChampions()
{
var getResult = await championCtrl.Get();
Console.WriteLine(getResult);
var objectRes = getResult as OkObjectResult;
Assert.AreEqual(200, objectRes.StatusCode);
Assert.IsNotNull(objectRes);
var champions = objectRes?.Value as IEnumerable<ChampionDTO>;
Assert.IsNotNull(champions);
}
[TestMethod]
public async Task TestDeleteChampions()
{
var getResult = await championCtrl.Get();
Console.WriteLine(getResult);
var objectRes = getResult as OkObjectResult;
Assert.AreEqual(200, objectRes.StatusCode);
Assert.IsNotNull(objectRes);
var champions = objectRes?.Value as IEnumerable<ChampionDTO>;
Assert.IsNotNull(champions);
}
*/
}
}

@ -17,7 +17,6 @@
<ItemGroup>
<ProjectReference Include="..\API_LoL_Project\API_LoL_Project.csproj" />
<ProjectReference Include="..\DTO\DTO.csproj" />
<ProjectReference Include="..\Model\Model.csproj" />
<ProjectReference Include="..\StubLib\StubLib.csproj" />
</ItemGroup>

Loading…
Cancel
Save