Changed program.cs for versioning in the swagger, also fixed uniqueness issues and created 3 versions of the ChampionController
continuous-integration/drone/push Build is passing Details

Logs_Version_Filtrage_Pagination
Emre KARTAL 2 years ago
parent c88eac1354
commit 074892b3a7

@ -9,6 +9,8 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <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.EntityFrameworkCore.SqlServer" Version="7.0.2" /> <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.2" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.15.1" /> <PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.15.1" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" /> <PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />

@ -0,0 +1,73 @@
using ApiLol.Mapper;
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 ApiLol.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class SkinsController : ControllerBase
{
private readonly IDataManager _manager;
private readonly ILogger<SkinsController> _logger;
public SkinsController(IDataManager dataManager, ILogger<SkinsController> logger)
{
_logger = logger;
this._manager = dataManager;
}
// GET: api/<SkinsController>
[HttpGet]
public async Task<IActionResult> Get([FromQuery] PageRequest pageRequest)
{
try
{
int nbTotal = await _manager.ChampionsMgr.GetNbItems();
if (pageRequest.count + pageRequest.index > nbTotal)
{
_logger.LogWarning($"too many, maximum {nbTotal}");
return BadRequest($"Champion limit exceed, max {nbTotal}");
}
_logger.LogInformation($"method Get call");
IEnumerable<SkinDtoC> dtos = (await _manager.SkinsMgr.GetItems(pageRequest.index, pageRequest.count))
.Select(x => x.ToDtoC());
return Ok(dtos);
}
catch (Exception e)
{
return BadRequest(e.Message);
}
}
// GET api/<SkinsController>/5
[HttpGet("{name}")]
public async Task<IActionResult> Get(string name)
{
return Ok();
}
// POST api/<SkinsController>
[HttpPost]
public async void Post([FromBody] string value)
{
}
// PUT api/<SkinsController>/5
[HttpPut("{name}")]
public async void Put(int id, [FromBody] string value)
{
}
// DELETE api/<SkinsController>/5
[HttpDelete("{name}")]
public async void Delete(string name)
{
}
}
}

@ -0,0 +1,84 @@
using ApiLol.Mapper;
using DTO;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using Model;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace ApiLol.Controllers.v1
{
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/[controller]")]
[ApiController]
public class ChampionsController : ControllerBase
{
private readonly IDataManager _manager;
private readonly ILogger<ChampionsController> _logger;
public ChampionsController(IDataManager dataManager, ILogger<ChampionsController> logger)
{
_logger = logger;
this._manager = dataManager;
}
// GET: api/<ValuesController>
[HttpGet]
public async Task<IActionResult> Get([FromQuery] PageRequest pageRequest)
{
int nbTotal = await _manager.ChampionsMgr.GetNbItems();
_logger.LogInformation($"method Get call");
IEnumerable<ChampionDto> dtos = (await _manager.ChampionsMgr.GetItems(pageRequest.index, pageRequest.count))
.Select(x => x.ToDto());
return Ok(dtos);
}
// GET api/<ValuesController>/5
[HttpGet("{name}")]
public async Task<IActionResult> Get(string name)
{
_logger.LogInformation($"method GetByName call with {name}");
var dtos = (await _manager.ChampionsMgr.GetItemsByName(name, 0, await _manager.ChampionsMgr.GetNbItems()))
.Select(x => x.ToDto());
return Ok(dtos);
}
// POST api/<ValuesController>
[HttpPost]
public async Task<IActionResult> Post([FromBody] ChampionDto champion)
{
_logger.LogInformation($"method Post call");
return CreatedAtAction(nameof(Get),
(await _manager.ChampionsMgr.AddItem(champion.ToModel())).ToDto());
}
// PUT api/<ValuesController>/5
[HttpPut("{name}")]
public async Task<IActionResult> Put(string name, [FromBody] ChampionDto champion)
{
_logger.LogInformation($"method Put call with {name}");
var dtos = (await _manager.ChampionsMgr.GetItemsByName(name, 0, await _manager.ChampionsMgr.GetNbItems()));
return Ok(await _manager.ChampionsMgr.UpdateItem(dtos.First(), champion.ToModel()));
}
// DELETE api/<ValuesController>/5
[HttpDelete("{name}")]
public async Task<IActionResult> Delete(string name)
{
_logger.LogInformation($"method Delete call with {name}");
var dtos = (await _manager.ChampionsMgr.GetItemsByName(name, 0, await _manager.ChampionsMgr.GetNbItems()));
return Ok(await _manager.ChampionsMgr.DeleteItem(dtos.First()));
}
}
}

@ -1,179 +1,205 @@
using ApiLol.Mapper; using ApiLol.Mapper;
using DTO; using DTO;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens; using Microsoft.IdentityModel.Tokens;
using Model; using Model;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 // For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace ApiLol.Controllers namespace ApiLol.Controllers.v2
{ {
[Route("api/[controller]")] [ApiVersion("2.0")]
[ApiController] [ApiVersion("3.0")]
public class ChampionsController : ControllerBase [Route("api/v{version:apiVersion}/[controller]")]
{ [ApiController]
private readonly IDataManager _manager; public class ChampionsController : ControllerBase
public readonly ILogger<ChampionsController> _logger; {
public ChampionsController(IDataManager dataManager, ILogger<ChampionsController> logger) private readonly IDataManager _manager;
{ private readonly ILogger<ChampionsController> _logger;
_logger = logger; public ChampionsController(IDataManager dataManager, ILogger<ChampionsController> logger)
this._manager = dataManager; {
} _logger = logger;
this._manager = dataManager;
// GET: api/<ValuesController> }
[HttpGet]
public async Task<IActionResult> Get([FromQuery] PageRequest pageRequest) // GET: api/<ValuesController>
{ [HttpGet]
try public async Task<IActionResult> Get([FromQuery] PageRequest pageRequest)
{ {
int nbTotal = await _manager.ChampionsMgr.GetNbItems(); try
if (pageRequest.count + pageRequest.index > nbTotal) {
{ int nbTotal = await _manager.ChampionsMgr.GetNbItems();
_logger.LogWarning($"too many, maximum {nbTotal}"); if (pageRequest.count * pageRequest.index >= nbTotal)
return BadRequest($"Champion limit exceed, max {nbTotal}"); {
} _logger.LogWarning($"too many, maximum {nbTotal}");
return BadRequest($"Champion limit exceed, max {nbTotal}");
_logger.LogInformation($"method Get call"); }
IEnumerable<ChampionDto> dtos = (await _manager.ChampionsMgr.GetItems(pageRequest.index, pageRequest.count))
.Select(x => x.ToDto()); _logger.LogInformation($"method Get call");
return Ok(dtos); IEnumerable<ChampionDto> dtos = (await _manager.ChampionsMgr.GetItems(pageRequest.index, pageRequest.count))
} .Select(x => x.ToDto());
catch (Exception e) return Ok(dtos);
{ }
return BadRequest(e.Message); catch (Exception e)
{
} return BadRequest(e.Message);
} }
}
// GET api/<ValuesController>/5
[HttpGet("{name}")] // GET: api/<ValuesController>
public async Task<IActionResult> Get(string name) [HttpGet, MapToApiVersion("3.0")]
{ public async Task<IActionResult> GetV3([FromQuery] PageRequest pageRequest)
try {
{ try
_logger.LogInformation($"method GetByName call with {name}"); {
var dtos = (await _manager.ChampionsMgr.GetItemsByName(name, 0, await _manager.ChampionsMgr.GetNbItems())) int nbTotal = await _manager.ChampionsMgr.GetNbItems();
.Select(x => x.ToDto()); if (pageRequest == null)
if (dtos.IsNullOrEmpty()) {
{ pageRequest.index = 0;
_logger.LogWarning($"{name} was not found"); pageRequest.count = nbTotal;
return NotFound(); }
} else if (pageRequest.count * pageRequest.index >= nbTotal)
return Ok(dtos); {
} _logger.LogWarning($"too many, maximum {nbTotal}");
catch (Exception e) return BadRequest($"Champion limit exceed, max {nbTotal}");
{ }
return BadRequest(e.Message);
_logger.LogInformation($"method Get call");
} IEnumerable<ChampionDto> dtos = (await _manager.ChampionsMgr.GetItems(pageRequest.index, pageRequest.count))
} .Select(x => x.ToDto());
return Ok(dtos);
// POST api/<ValuesController> }
[HttpPost] catch (Exception e)
public async Task<IActionResult> Post([FromBody] ChampionDto champion) {
{ return BadRequest(e.Message);
try }
{ }
_logger.LogInformation($"method Post call");
var dtos = (await _manager.ChampionsMgr.GetItemsByName(champion.Name, 0, await _manager.ChampionsMgr.GetNbItems())); // GET api/<ValuesController>/5
if (!dtos.IsNullOrEmpty()) [HttpGet("{name}")]
{ public async Task<IActionResult> Get(string name)
return BadRequest("Name is already exist"); {
} try
return CreatedAtAction(nameof(Get), {
(await _manager.ChampionsMgr.AddItem(champion.ToModel())).ToDto()); _logger.LogInformation($"method GetByName call with {name}");
} var dtos = (await _manager.ChampionsMgr.GetItemsByName(name, 0, await _manager.ChampionsMgr.GetNbItems()))
catch (Exception e) .Select(x => x.ToDto());
{ if (dtos.IsNullOrEmpty())
return BadRequest(e.Message); {
_logger.LogWarning($"{name} was not found");
} return NotFound();
} }
return Ok(dtos);
// PUT api/<ValuesController>/5 }
[HttpPut("{name}")] catch (Exception e)
public async Task<IActionResult> Put(string name, [FromBody] ChampionDto champion) {
{ return BadRequest(e.Message);
try }
{ }
_logger.LogInformation($"method Put call with {name}");
var dtos = (await _manager.ChampionsMgr.GetItemsByName(name, 0, await _manager.ChampionsMgr.GetNbItems())); // POST api/<ValuesController>
if (dtos.IsNullOrEmpty()) [HttpPost]
{ public async Task<IActionResult> Post([FromBody] ChampionDto champion)
return BadRequest("Name not exist"); {
} try
// Checks if the new name exists {
if (name != champion.Name) _logger.LogInformation($"method Post call");
{ var dtos = (await _manager.ChampionsMgr.GetItemsByName(champion.Name, 0, await _manager.ChampionsMgr.GetNbItems()));
var dtos2 = (await _manager.ChampionsMgr.GetItemsByName(champion.Name, 0, await _manager.ChampionsMgr.GetNbItems())); if (!dtos.IsNullOrEmpty())
if (!dtos.IsNullOrEmpty()) {
{ return BadRequest("Name is already exist");
return BadRequest("Name is already exist"); }
} return CreatedAtAction(nameof(Get),
} (await _manager.ChampionsMgr.AddItem(champion.ToModel())).ToDto());
return Ok(await _manager.ChampionsMgr.UpdateItem(dtos.First(), champion.ToModel())); }
} catch (Exception e)
catch (Exception e) {
{ return BadRequest(e.Message);
return BadRequest(e.Message); }
}
}
} // PUT api/<ValuesController>/5
[HttpPut("{name}")]
[HttpGet("/{name}/skins")] public async Task<IActionResult> Put(string name, [FromBody] ChampionDto champion)
public async Task<ActionResult<Skin>> GetChampionsSkins(string name) {
{ try
try {
{ _logger.LogInformation($"method Put call with {name}");
var champions = await _manager.ChampionsMgr.GetItemsByName(name, 0, await _manager.ChampionsMgr.GetNbItems()); var dtos = (await _manager.ChampionsMgr.GetItemsByName(name, 0, await _manager.ChampionsMgr.GetNbItems()));
//skinsDTO if (dtos.IsNullOrEmpty())
IEnumerable<SkinDto> res = champions.First().Skins.Select(e => e.ToDto()); {
return NotFound("Name not exist");
return Ok(res); }
} // Checks if the new name exists
catch (Exception e) if (name != champion.Name)
{ {
return BadRequest(e.Message); var dtos2 = (await _manager.ChampionsMgr.GetItemsByName(champion.Name, 0, await _manager.ChampionsMgr.GetNbItems()));
if (dtos.IsNullOrEmpty() || dtos2.Count() > 0)
} {
} return BadRequest("Name is already exist");
}
[HttpGet("/{name}/skills")] }
public async Task<ActionResult<Skin>> GetChampionsSkills(string name) return Ok(await _manager.ChampionsMgr.UpdateItem(dtos.First(), champion.ToModel()));
{ }
try catch (Exception e)
{ {
var champions = await _manager.ChampionsMgr.GetItemsByName(name, 0, await _manager.ChampionsMgr.GetNbItems()); return BadRequest(e.Message);
//SkillDTO }
IEnumerable<SkillDto> res = champions.First().Skills.Select(e => e.ToDto()); }
return Ok(res); [HttpGet("/{name}/skins")]
} public async Task<ActionResult<SkinDto>> GetChampionsSkins(string name)
catch (Exception e) {
{ try
return BadRequest(e.Message); {
} var champions = await _manager.ChampionsMgr.GetItemsByName(name, 0, await _manager.ChampionsMgr.GetNbItems());
} //skinsDTO
IEnumerable<SkinDto> res = champions.First().Skins.Select(e => e.ToDto());
// DELETE api/<ValuesController>/5
[HttpDelete("{name}")] return Ok(res);
public async Task<IActionResult> Delete(string name) }
{ catch (Exception e)
try {
{ return BadRequest(e.Message);
_logger.LogInformation($"method Delete call with {name}"); }
var dtos = (await _manager.ChampionsMgr.GetItemsByName(name, 0, await _manager.ChampionsMgr.GetNbItems())); }
if (dtos.IsNullOrEmpty())
{ [HttpGet("/{name}/skills")]
_logger.LogWarning($"{name} was not found"); public async Task<ActionResult<SkillDto>> GetChampionsSkills(string name)
return BadRequest(); {
} try
return Ok(await _manager.ChampionsMgr.DeleteItem(dtos.First())); {
} var champions = await _manager.ChampionsMgr.GetItemsByName(name, 0, await _manager.ChampionsMgr.GetNbItems());
catch (Exception e) //SkillDTO
{ IEnumerable<SkillDto> res = champions.First().Skills.Select(e => e.ToDto());
return BadRequest(e.Message);
} return Ok(res);
} }
} catch (Exception e)
{
return BadRequest(e.Message);
}
}
// DELETE api/<ValuesController>/5
[HttpDelete("{name}")]
public async Task<IActionResult> Delete(string name)
{
try
{
_logger.LogInformation($"method Delete call with {name}");
var dtos = (await _manager.ChampionsMgr.GetItemsByName(name, 0, await _manager.ChampionsMgr.GetNbItems()));
if (dtos.IsNullOrEmpty())
{
_logger.LogWarning($"{name} was not found");
return BadRequest();
}
return Ok(await _manager.ChampionsMgr.DeleteItem(dtos.First()));
}
catch (Exception e)
{
return BadRequest(e.Message);
}
}
}
} }

@ -17,9 +17,23 @@ namespace ApiLol.Mapper
}; };
} }
public static SkinDtoC ToDtoC(this Skin skin)
{
return new SkinDtoC()
{
Name = skin.Name,
Description = skin.Description,
Icon = skin.Icon,
Image = skin.Image.ToDto(),
Price = skin.Price,
ChampionName = skin.Champion.Name
};
}
public static Skin ToModel(this SkinDto skinDto) public static Skin ToModel(this SkinDto skinDto)
{ {
return new Skin(skinDto.Name, null, skinDto.Price, skinDto.Icon, skinDto.Image.Base64, skinDto.Description); return new Skin(skinDto.Name, null, skinDto.Price, skinDto.Icon, skinDto.Image.Base64, skinDto.Description);
} }
} }
} }

@ -1,3 +1,5 @@
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.AspNetCore.Mvc.Versioning;
using Model; using Model;
using StubLib; using StubLib;
@ -9,14 +11,41 @@ builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer(); builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(); 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(),
new HeaderApiVersionReader("x-api-version"),
new MediaTypeApiVersionReader("x-api-version"));
});
// Add ApiExplorer to discover versions
builder.Services.AddVersionedApiExplorer(setup =>
{
setup.GroupNameFormat = "'v'VVV";
setup.SubstituteApiVersionInUrl = true;
});
builder.Services.AddSingleton<IDataManager, StubData>(); builder.Services.AddSingleton<IDataManager, StubData>();
var app = builder.Build(); var app = builder.Build();
// Configure the HTTP request pipeline. // Configure the HTTP request pipeline.
app.UseSwagger(); var apiVersionDescriptionProvider = app.Services.GetRequiredService<IApiVersionDescriptionProvider>();
app.UseSwaggerUI();
// Configure the HTTP request pipeline.
app.UseSwagger();
app.UseSwaggerUI(options =>
{
foreach (var description in apiVersionDescriptionProvider.ApiVersionDescriptions)
{
options.SwaggerEndpoint($"/swagger/{description.GroupName}/swagger.json",
description.GroupName.ToUpperInvariant());
}
});
app.UseHttpsRedirection(); app.UseHttpsRedirection();

@ -23,12 +23,12 @@ namespace Client
var url = $"{ApiChampions}?index={index}&count={count}"; var url = $"{ApiChampions}?index={index}&count={count}";
return await _httpClient.GetFromJsonAsync<IEnumerable<ChampionDto>>(url); return await _httpClient.GetFromJsonAsync<IEnumerable<ChampionDto>>(url);
} }
public async void Add(ChampionDto champion) /* public async void Add(ChampionDto champion)
{ {
await _httpClient.PostAsJsonAsync<ChampionDto>(ApiChampions, champion); await _httpClient.PostAsJsonAsync<ChampionDto>(ApiChampions, champion);
} }*/
public async void Delete(ChampionDto champion) /* public async void Delete(ChampionDto champion)
{ {
await _httpClient.DeleteAsync(champion.Name); await _httpClient.DeleteAsync(champion.Name);
} }
@ -36,7 +36,7 @@ namespace Client
public async void Update(ChampionDto champion) public async void Update(ChampionDto champion)
{ {
await _httpClient.PutAsJsonAsync<ChampionDto>(ApiChampions, champion); await _httpClient.PutAsJsonAsync<ChampionDto>(ApiChampions, champion);
} }*/
} }
} }

@ -1,4 +1,5 @@
using System; using DTO.enums;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
@ -10,6 +11,8 @@ namespace DTO
{ {
public string Name { get; set; } public string Name { get; set; }
public string Description { get; set; } public string Description { get; set; }
public RuneFamilyDto Family { get; set; }
public LargeImageDto Image { get; set; }
} }
} }

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

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DTO.enums
{
public enum RuneFamilyDto
{
Unknown,
Precision,
Domination
}
}

@ -84,7 +84,7 @@ namespace StubLib
.Select(tuple => tuple.Item1) .Select(tuple => tuple.Item1)
.Skip(index*count).Take(count)); .Skip(index*count).Take(count));
private Func<Champion, string, bool> filterByName = (champ, substring) => champ.Name.Contains(substring, StringComparison.InvariantCultureIgnoreCase); private Func<Champion, string, bool> filterByName = (champ, substring) => champ.Name.Equals(substring, StringComparison.InvariantCultureIgnoreCase);
public Task<int> GetNbItemsByName(string substring) public Task<int> GetNbItemsByName(string substring)
=> parent.champions.GetNbItemsWithFilter(champ => filterByName(champ, substring)); => parent.champions.GetNbItemsWithFilter(champ => filterByName(champ, substring));

@ -1,4 +1,5 @@
using ApiLol.Controllers; using ApiLol.Controllers;
using ApiLol.Controllers.v2;
using DTO; using DTO;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
@ -50,7 +51,6 @@ namespace ApiTests
Icon = "", Icon = "",
Image = new LargeImageDto() { Base64 = "" }, Image = new LargeImageDto() { Base64 = "" },
Skins = new List<SkinDto>() Skins = new List<SkinDto>()
}; };
//Act //Act

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