feat : Players and a bit of fix everywhere

pull/38/head
Jade VAN BRABANDT 1 year ago
parent 992c403b21
commit 03191d5cee

@ -7,38 +7,33 @@
</PropertyGroup>
<ItemGroup>
<Compile Remove="Pages\Player\**" />
<Content Remove="Pages\Player\**" />
<EmbeddedResource Remove="Pages\Player\**" />
<None Remove="Pages\Player\**" />
<Content Remove="Pages\_Layout.cshtml" />
</ItemGroup>
<ItemGroup>
<Content Remove="Pages\_Layout.cshtml" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Blazored.LocalStorage" Version="4.4.0" />
<PackageReference Include="Blazored.Modal" Version="7.1.0" />
<PackageReference Include="Blazored.Modal" Version="7.1.0" />
<PackageReference Include="Blazorise.Bootstrap" Version="1.4.0" />
<PackageReference Include="Blazorise.DataGrid" Version="1.4.0" />
<PackageReference Include="Blazorise.Icons.FontAwesome" Version="1.4.0" />
<PackageReference Include="ChoETL.JSON.NETStandard" Version="1.2.1.64" />
<PackageReference Include="ChoETL.NETStandard" Version="1.2.1.64" />
<PackageReference Include="System.Net.Http" Version="4.3.4" />
<PackageReference Include="System.Text.RegularExpressions" Version="4.3.1" />
</ItemGroup>
<ItemGroup>
<UpToDateCheckInput Remove="Pages\_Layout.cshtml" />
</ItemGroup>
<ItemGroup>
<_ContentIncludedByDefault Remove="Pages\_Layout.cshtml" />
</ItemGroup>
<ItemGroup>
<None Include="Pages\_Layout.cshtml" />
<PackageReference Include="ChoETL.JSON.NETStandard" Version="1.2.1.64" />
<PackageReference Include="ChoETL.NETStandard" Version="1.2.1.64" />
<PackageReference Include="System.Net.Http" Version="4.3.4" />
<PackageReference Include="System.Text.RegularExpressions" Version="4.3.1" />
</ItemGroup>
<ItemGroup>
<UpToDateCheckInput Remove="Pages\_Layout.cshtml" />
</ItemGroup>
<ItemGroup>
<_ContentIncludedByDefault Remove="Pages\_Layout.cshtml" />
</ItemGroup>
<ItemGroup>
<None Include="Pages\_Layout.cshtml" />
</ItemGroup>
</Project>

@ -4,10 +4,10 @@ using System.Security.Cryptography;
namespace Blazor.Models;
public class AdministratorsModel : PasswordHasher<string>
public class AdministratorModel : PasswordHasher<string>
{
public int Id { get; set; }
public string Username { get; set; }
public string hashedPassword { get; set; }
public string HashedPassword { get; set; }
}

@ -5,21 +5,7 @@ namespace Blazor.Models;
public class PlayerModel
{
public int Id { get; private set; }
public string Nickname { get; private set; }
public int Id { get; set; }
public string Nickname { get; set; }
public string HashedPassword { get; set; }
private byte[] salt = RandomNumberGenerator.GetBytes(128 / 8); // for password hash
public PlayerModel(int id, string nickname, string password)
{
Id = id;
Nickname = nickname;
//hash password
HashedPassword = Convert.ToBase64String(KeyDerivation.Pbkdf2(
password: password!,
salt: salt,
prf: KeyDerivationPrf.HMACSHA256,
iterationCount: 100000,
numBytesRequested: 256 / 8)
);
}
}

@ -1,6 +1,6 @@
namespace Blazor.Models;
public class QuestionsModel
public class QuestionModel
{
public int Id { get; private set; }
public string Content { get; set; }
@ -9,7 +9,7 @@ public class QuestionsModel
public int Difficulty { get; set; }
public int NbFails { get; private set; }
public QuestionsModel(int id, string content, int idChapter, int difficulty, int nbFails, int? idAnswerGood = null)
public QuestionModel(int id, string content, int idChapter, int difficulty, int nbFails, int? idAnswerGood = null)
{
Id = id;
Content = content;

@ -3,18 +3,18 @@
<h3>AddAdministrators</h3>
<EditForm Model="@administratorsModel" OnValidSubmit="@HandleValidSubmit">
<EditForm Model="@administratorModel" OnValidSubmit="@HandleValidSubmit">
<DataAnnotationsValidator />
<ValidationSummary />
<p>
<label for="username">
Username:
<InputText id="username" @bind-Value="administratorsModel.Username" />
<InputText id="username" @bind-Value="administratorModel.Username" />
</label>
<label for="hashedPassword">
Password:
<InputText id="hashedPassword" @bind-Value="administratorsModel.hashedPassword" />
<InputText id="hashedPassword" @bind-Value="administratorModel.HashedPassword" />
</label>
</p>

@ -6,9 +6,9 @@ using Blazor.Services;
namespace Blazor.Pages.Admins
{
public partial class AddAdministrators
public partial class AddAdministrator
{
private AdministratorsModel administratorsModel = new();
private AdministratorModel administratorModel = new();
[Inject]
public IDataService DataService { get; set; }
@ -19,7 +19,7 @@ namespace Blazor.Pages.Admins
private async void HandleValidSubmit()
{
await DataService.Add(administratorsModel);
await DataService.Add(administratorModel);
NavigationManager.NavigateTo("administrators");
}

@ -5,7 +5,7 @@
<h3>Administrators</h3>
<div>
<NavLink class="btn btn-primary" href="addAdministrators" Match="NavLinkMatch.All">
<NavLink class="btn btn-primary" href="addAdministrator" Match="NavLinkMatch.All">
<i class="fa fa-plus"></i> Ajouter
</NavLink>
</div>
@ -26,3 +26,4 @@
</DataGridColumn>
</DataGrid>
<script src="Pages/Administrators.razor.js"></script>

@ -61,13 +61,13 @@ public partial class Administrators
return;
}
var currentData = await LocalStorage.GetItemAsync<AdministratorsModel[]>("data");
var currentData = await LocalStorage.GetItemAsync<AdministratorModel[]>("data");
// Check if data exist in the local storage
if (currentData == null)
{
// this code add in the local storage the fake data (we load the data sync for initialize the data before load the OnReadData method)
var originalData = Http.GetFromJsonAsync<AdministratorsModel[]>($"trusting-panini.87-106-126-109.plesk.page/api/chapters").Result;
var originalData = Http.GetFromJsonAsync<AdministratorModel[]>($"trusting-panini.87-106-126-109.plesk.page/api/chapters").Result;
await LocalStorage.SetItemAsync("data", originalData);
}
}

@ -2,18 +2,18 @@
<h3>EditAdministrator</h3>
<EditForm Model="@administratorsModel" OnValidSubmit="@HandleValidSubmit">
<EditForm Model="@administratorModel" OnValidSubmit="@HandleValidSubmit">
<DataAnnotationsValidator />
<ValidationSummary />
<p>
<label for="username">
Username:
<InputText id="username" @bind-Value="administratorsModel.Username" />
<InputText id="username" @bind-Value="administratorModel.Username" />
</label>
<label for="hashedPassword">
Password:
<InputText id="hashedPassword" @bind-Value="administratorsModel.hashedPassword" />
<InputText id="hashedPassword" @bind-Value="administratorModel.HashedPassword" />
</label>
</p>

@ -10,7 +10,7 @@ namespace Blazor.Pages.Admins
[Parameter]
public int Id { get; set; }
private AdministratorsModel administratorsModel = new();
private AdministratorModel administratorModel = new();
[Inject]
public IDataService DataService { get; set; }
@ -26,7 +26,7 @@ namespace Blazor.Pages.Admins
var administrator = await DataService.GetAdminById(Id);
// Set the model with the admin
administratorsModel = new AdministratorsModel
administratorModel = new AdministratorModel
{
Id = administrator.Id,
Username = administrator.Username
@ -35,7 +35,7 @@ namespace Blazor.Pages.Admins
private async void HandleValidSubmit()
{
await DataService.Update(Id, administratorsModel);
await DataService.Update(Id, administratorModel);
NavigationManager.NavigateTo("administrators");
}

@ -73,8 +73,6 @@ public partial class Chapters
return;
}
// When you use a real API, we use this follow code
//var response = await Http.GetFromJsonAsync<ChaptersModel[]>( $"https://trusting-panini.87-106-126-109.plesk.page/api/chapters?page={e.Page}&pageSize={e.PageSize}" );
var response = Http.GetFromJsonAsync<Chapter[]>($"https://trusting-panini.87-106-126-109.plesk.page/api/chapters").Result;
if (!e.CancellationToken.IsCancellationRequested)

@ -1,40 +1,40 @@
using Blazor.Models;
using Blazor.Services;
using Microsoft.AspNetCore.Components;
namespace Blazor.Pages.Chapters;
public partial class EditChapter
{
[Parameter]
public int Id { get; set; }
private ChapterModel chapterModel = new();
[Inject]
public IDataService DataService { get; set; }
[Inject]
public NavigationManager NavigationManager { get; set; }
[Inject]
public IWebHostEnvironment WebHostEnvironment { get; set; }
protected override async Task OnInitializedAsync()
{
var chapter = await DataService.GetById(Id);
// Set the model with the chapter
chapterModel = new ChapterModel
{
Id = chapter.Id,
Name = chapter.Name
};
}
private async void HandleValidSubmit()
{
await DataService.Update(Id, chapterModel);
using Blazor.Models;
using Blazor.Services;
using Microsoft.AspNetCore.Components;
namespace Blazor.Pages.Chapters;
public partial class EditChapter
{
[Parameter]
public int Id { get; set; }
private ChapterModel chapterModel = new();
[Inject]
public IDataService DataService { get; set; }
[Inject]
public NavigationManager NavigationManager { get; set; }
[Inject]
public IWebHostEnvironment WebHostEnvironment { get; set; }
protected override async Task OnInitializedAsync()
{
var chapter = await DataService.GetById(Id);
// Set the model with the chapter
chapterModel = new ChapterModel
{
Id = chapter.Id,
Name = chapter.Name
};
}
private async void HandleValidSubmit()
{
await DataService.Update(Id, chapterModel);
var formData = new List<KeyValuePair<string, string>>();
formData.Add(new KeyValuePair<string, string>("name", chapterModel.Name));
@ -55,7 +55,7 @@ public partial class EditChapter
{
var errorResponse = await response.Content.ReadAsStringAsync();
}
}
NavigationManager.NavigateTo("chapters");
}
}
}
NavigationManager.NavigateTo("chapters");
}
}

@ -0,0 +1,23 @@
@page "/addPlayer"
@using Blazor.Models
<h3>Add Player</h3>
<EditForm Model="@playerModel" OnValidSubmit="@HandleValidSubmit">
<DataAnnotationsValidator />
<ValidationSummary />
<p>
<label for="nickname">
Nickname:
<InputText id="nickname" @bind-Value="playerModel.Nickname" />
</label>
<label for="hashedPassword">
Password:
<InputText id="hashedPassword" @bind-Value="playerModel.HashedPassword" />
</label>
</p>
<button type="submit">Submit</button>
</EditForm>

@ -0,0 +1,45 @@
using Microsoft.AspNetCore.Components;
using Blazor.Models;
using Blazor.Services;
namespace Blazor.Pages.Players
{
public partial class AddPlayer
{
private PlayerModel playerModel = new();
[Inject]
public IDataService DataService { get; set; }
[Inject]
public NavigationManager NavigationManager { get; set; }
private async void HandleValidSubmit()
{
await DataService.Add(playerModel);
var formData = new List<KeyValuePair<string, string>>();
formData.Add(new KeyValuePair<string, string>("nickname", playerModel.Nickname));
formData.Add(new KeyValuePair<string, string>("password", playerModel.HashedPassword));
var formContent = new FormUrlEncodedContent(formData);
string apiUri = "https://trusting-panini.87-106-126-109.plesk.page/api/add/players/"+playerModel.Id;
using (var httpClient = new HttpClient())
{
var response = await httpClient.PostAsync(apiUri, formContent);
if (response.IsSuccessStatusCode)
{
var responseBody = await response.Content.ReadAsStringAsync();
}
else
{
var errorResponse = await response.Content.ReadAsStringAsync();
}
}
NavigationManager.NavigateTo("players");
}
}
}

@ -0,0 +1,21 @@
@page "/editPlayer/{Id:int}"
<h3>Edit Player</h3>
<EditForm Model="@playerModel" OnValidSubmit="@HandleValidSubmit">
<DataAnnotationsValidator />
<ValidationSummary />
<p>
<label for="nickname">
Nickname:
<InputText id="nickname" @bind-Value="playerModel.Nickname" />
</label>
<label for="hashedPassword">
Password:
<InputText id="hashedPassword" @bind-Value="playerModel.HashedPassword" />
</label>
</p>
<button type="submit">Submit</button>
</EditForm>

@ -0,0 +1,64 @@
using Blazor.Models;
using Blazor.Services;
using ChoETL;
using Microsoft.AspNetCore.Components;
namespace Blazor.Pages.Players
{
public partial class EditPlayer
{
[Parameter]
public int Id { get; set; }
private PlayerModel playerModel = new();
[Inject]
public IDataService DataService { get; set; }
[Inject]
public NavigationManager NavigationManager { get; set; }
[Inject]
public IWebHostEnvironment WebHostEnvironment { get; set; }
protected override async Task OnInitializedAsync()
{
var player = await DataService.GetPlayerById(Id);
// Set the model with the admin
playerModel = new PlayerModel
{
Id = player.Id,
Nickname = player.Nickname
};
}
private async void HandleValidSubmit()
{
await DataService.Update(Id, playerModel);
var formData = new List<KeyValuePair<string, string>>();
formData.Add(new KeyValuePair<string, string>("nickname", playerModel.Nickname));
formData.Add(new KeyValuePair<string, string>("password", playerModel.HashedPassword));
var formContent = new FormUrlEncodedContent(formData);
string apiUri = "https://trusting-panini.87-106-126-109.plesk.page/api/update/"+playerModel.Id;
using (var httpClient = new HttpClient())
{
var response = await httpClient.PostAsync(apiUri, formContent);
if (response.IsSuccessStatusCode)
{
var responseBody = await response.Content.ReadAsStringAsync();
}
else
{
var errorResponse = await response.Content.ReadAsStringAsync();
}
}
NavigationManager.NavigateTo("players");
}
}
}

@ -0,0 +1,30 @@
@page "/players"
@using Blazor.ViewClasses;
@using Blazorise.DataGrid
@using Blazored.Modal;
<h3>Joueurs</h3>
<div>
<NavLink class="btn btn-primary" href="addPlayer" Match="NavLinkMatch.All">
<i class="fa fa-plus"></i> Ajouter
</NavLink>
</div>
<DataGrid TItem="Player"
Data="@players"
ReadData="@OnReadData"
TotalItems="@totalPlayer"
PageSize="10"
ShowPager
Responsive>
<DataGridColumn TItem="Player" Field="@nameof(Player.Id)" Caption="#" />
<DataGridColumn TItem="Player" Field="@nameof(Player.Nickname)" Caption="Username" />
<DataGridColumn TItem="Player" Field="@nameof(Player.Id)" Caption="Action">
<DisplayTemplate>
<a href="editPlayer/@(context.Id)" class="btn btn-primary"><i class="fa fa-edit"></i> Editer</a>
<button type="button" class="btn btn-primary" @onclick="() => OnDelete(context.Id)"><i class="fa fa-trash"></i> Supprimer</button>
</DisplayTemplate>
</DataGridColumn>
</DataGrid>
<script src="Pages/Players.razor.js"></script>

@ -0,0 +1,94 @@
using Blazored.LocalStorage;
using Blazor.Services;
using Blazored.Modal.Services;
using Blazor.ViewClasses;
using System.Text;
using Microsoft.JSInterop;
using Microsoft.AspNetCore.Components;
using Blazorise.DataGrid;
using ChoETL;
using Microsoft.AspNetCore.Components.Forms;
using Blazor.Modals;
using Blazored.Modal;
using Blazor.Pages.Admins;
using Blazor.Pages.Chapters;
namespace Blazor.Pages.Players;
public partial class Players
{
public List<Player> players;
private int totalPlayer;
[Inject]
public NavigationManager NavigationManager { get; set; }
[CascadingParameter]
public IModalService Modal { get; set; }
[Inject]
public IDataService DataService { get; set; }
public IWebHostEnvironment WebHostEnvironment { get; set; }
[Inject]
public HttpClient Http { get; set; }
[Inject]
public ILocalStorageService LocalStorage { get; set; }
[Inject]
public IJSRuntime IJSRuntime { get; set; }
private async void OnDelete(int id)
{
var parameters = new ModalParameters();
parameters.Add(nameof(Player.Id), id);
var modal = Modal.Show<DeleteConfirmation>("Delete Confirmation", parameters);
var result = modal.Result;
if (result.IsCanceled)
{
return;
}
await DataService.Delete(id);
// Reload the page
NavigationManager.NavigateTo("Players", true);
}
//protected override async Task OnAfterRenderAsync(bool firstRender)
//{
// // Do not treat this action if is not the first render
// if (!firstRender)
// {
// return;
// }
//}
private async Task OnReadData(DataGridReadDataEventArgs<Player> e)
{
if (e.CancellationToken.IsCancellationRequested)
{
return;
}
var response = Http.GetFromJsonAsync<Player[]>($"https://trusting-panini.87-106-126-109.plesk.page/api/players").Result;
if (!e.CancellationToken.IsCancellationRequested)
{
players = new List<Player>(response); // an actual data for the current page
totalPlayer = players.Count;
var currentData = await LocalStorage.GetItemAsync<Player[]>("data");
if (currentData == null || currentData.Length != players.Count)
{
var originalData = Http.GetFromJsonAsync<Player[]>($"https://trusting-panini.87-106-126-109.plesk.page/api/players").Result;
await LocalStorage.SetItemAsync("data", originalData);
}
}
}
}

@ -1,319 +1,415 @@
using Blazor.Models;
using Blazor.ViewClasses;
using Blazored.LocalStorage;
using Microsoft.AspNetCore.Components;
namespace Blazor.Services
{
public class DataLocalService : IDataService
{
private readonly HttpClient _http;
private readonly ILocalStorageService _localStorage;
private readonly NavigationManager _navigationManager;
private readonly IWebHostEnvironment _webHostEnvironment;
public DataLocalService(
ILocalStorageService localStorage,
HttpClient http,
IWebHostEnvironment webHostEnvironment,
NavigationManager navigationManager)
{
_localStorage = localStorage;
_http = http;
_webHostEnvironment = webHostEnvironment;
_navigationManager = navigationManager;
}
public async Task<Chapter> GetById(int id)
{
// Get the current data
var currentData = await _localStorage.GetItemAsync<List<Chapter>>("data");
// Get the chapter int the list
var chapter = currentData.FirstOrDefault(w => w.Id == id);
// Check if chapter exist
if (chapter == null)
{
throw new Exception($"Unable to found the item with ID: {id}");
}
return chapter;
}
public async Task Update(int id, ChapterModel model)
{
// Get the current data
var currentData = await _localStorage.GetItemAsync<List<Chapter>>("data");
// Get the chapter int the list
var chapter = currentData.FirstOrDefault(w => w.Id == id);
// Check if chapter exist
if (chapter == null)
{
throw new Exception($"Unable to found the item with ID: {id}");
}
// Modify the content of the chapter
chapter.Name = model.Name;
// Save the data
await _localStorage.SetItemAsync("data", currentData);
}
public async Task Add(ChapterModel model)
{
// Get the current data
var currentData = await _localStorage.GetItemAsync<List<Chapter>>("data");
// Simulate the Id
model.Id = currentData.Max(s => s.Id) + 1;
// Add the chapter to the current data
currentData.Add(new Chapter
{
Id = model.Id,
Name = model.Name
});
// Save the data
await _localStorage.SetItemAsync("data", currentData);
}
public async Task Delete(int id)
{
// Get the current data
//var currentData = await _localStorage.GetItemAsync<List<Chapter>>("data");
var currentData = _http.GetFromJsonAsync<List<Chapter>>($"https://trusting-panini.87-106-126-109.plesk.page/api/chapters").Result;
// Get the chapter int the list
var chapter = currentData.FirstOrDefault(w => w.Id == id);
// Delete chapter in
currentData.Remove(chapter);
// Save the data
await _localStorage.SetItemAsync("data", currentData);
}
public async Task<int> Count()
{
// Load data from the local storage
var currentData = await _localStorage.GetItemAsync<Chapter[]>("data");
// Check if data exist in the local storage
if (currentData == null)
{
// this code add in the local storage the fake data
var originalData = await _http.GetFromJsonAsync<Chapter[]>($"{_navigationManager.BaseUri}fake-data.json");
await _localStorage.SetItemAsync("data", originalData);
}
return (await _localStorage.GetItemAsync<Chapter[]>("data")).Length;
}
public async Task<List<Chapter>> List(int currentPage, int pageSize)
{
// Load data from the local storage
var currentData = await _localStorage.GetItemAsync<Chapter[]>("data");
// Check if data exist in the local storage
if (currentData == null)
{
// this code add in the local storage the fake data
var originalData = await _http.GetFromJsonAsync<Chapter[]>($"{_navigationManager.BaseUri}fake-data.json");
await _localStorage.SetItemAsync("data", originalData);
}
return (await _localStorage.GetItemAsync<Chapter[]>("data")).Skip((currentPage - 1) * pageSize).Take(pageSize).ToList();
}
public async Task<Administrator> GetAdminById(int id)
{
// Get the current data
var currentData = await _localStorage.GetItemAsync<List<Administrator>>("data");
// Get the admin int the list
var admin = currentData.FirstOrDefault(w => w.Id == id);
// Check if admin exist
if (admin == null)
{
throw new Exception($"Unable to found the item with ID: {id}");
}
return admin;
}
public async Task Update(int id, AdministratorsModel model)
{
// Get the current data
var currentData = await _localStorage.GetItemAsync<List<Administrator>>("data");
// Get the admin int the list
var admin = currentData.FirstOrDefault(w => w.Id == id);
// Check if admin exist
if (admin == null)
{
throw new Exception($"Unable to found the item with ID: {id}");
}
// Modify the content of the adminnistrator
admin.Username = model.Username;
admin.hashedPassword = model.hashedPassword;
// Save the data
await _localStorage.SetItemAsync("data", currentData);
}
public async Task Add(AdministratorsModel model)
{
// Get the current data
var currentData = await _localStorage.GetItemAsync<List<Administrator>>("data");
// Simulate the Id
model.Id = currentData.Max(s => s.Id) + 1;
// Add the admin to the current data
currentData.Add(new Administrator
{
Id = model.Id,
Username = model.Username,
hashedPassword = model.hashedPassword
});
// Save the data
await _localStorage.SetItemAsync("data", currentData);
}
public async Task<int> CountAdmin()
{
// Load data from the local storage
var currentData = await _localStorage.GetItemAsync<Administrator[]>("data");
// Check if data exist in the local storage
if (currentData == null)
{
// this code add in the local storage the fake data
var originalData = await _http.GetFromJsonAsync<Administrator[]>($"{_navigationManager.BaseUri}fake-administrator.json");
await _localStorage.SetItemAsync("data", originalData);
}
return (await _localStorage.GetItemAsync<Administrator[]>("data")).Length;
}
public async Task<List<Administrator>> ListAdmin(int currentPage, int pageSize)
{
// Load data from the local storage
var currentData = await _localStorage.GetItemAsync<Administrator[]>("data");
// Check if data exist in the local storage
if (currentData == null)
{
// this code add in the local storage the fake data
var originalData = await _http.GetFromJsonAsync<Administrator[]>($"{_navigationManager.BaseUri}fake-administrator.json");
await _localStorage.SetItemAsync("data", originalData);
}
return (await _localStorage.GetItemAsync<Administrator[]>("data")).Skip((currentPage - 1) * pageSize).Take(pageSize).ToList();
}
public async Task<Question> GetQuestionById(int id)
{
// Get the current data
var currentData = await _localStorage.GetItemAsync<List<Question>>("data");
// Get the question int the list
var question = currentData.FirstOrDefault(w => w.Id == id);
// Check if question exist
if (question == null)
{
throw new Exception($"Unable to found the item with ID: {id}");
}
return question;
}
//public async Task Update(int id, QuestionsModel model)
//{
// // Get the current data
// var currentData = await _localStorage.GetItemAsync<List<Question>>("data");
// // Get the admin int the list
// var question = currentData.FirstOrDefault(w => w.Id == id);
// // Check if admin exist
// if (question == null)
// {
// throw new Exception($"Unable to found the item with ID: {id}");
// }
// // Modify the content of the adminnistrator
// question.Username = model.Username;
// question.hashedPassword = model.hashedPassword;
// // Save the data
// await _localStorage.SetItemAsync("data", currentData);
//}
//public async Task Add(QuestionsModel model)
//{
// // Get the current data
// var currentData = await _localStorage.GetItemAsync<List<Question>>("data");
// // Simulate the Id
// model.Id = currentData.Max(s => s.Id) + 1;
// // Add the admin to the current data
// currentData.Add(new Question
// {
// Id = model.Id,
// Username = model.Username,
// hashedPassword = model.hashedPassword
// });
// // Save the data
// await _localStorage.SetItemAsync("data", currentData);
//}
public async Task<int> CountQuestion()
{
// Load data from the local storage
var currentData = await _localStorage.GetItemAsync<Question[]>("data");
// Check if data exist in the local storage
if (currentData == null)
{
// this code add in the local storage the fake data
var originalData = await _http.GetFromJsonAsync<Question[]>($"{_navigationManager.BaseUri}fake-question.json");
await _localStorage.SetItemAsync("data", originalData);
}
return (await _localStorage.GetItemAsync<Question[]>("data")).Length;
}
public async Task<List<Question>> ListQuestion(int currentPage, int pageSize)
{
// Load data from the local storage
var currentData = await _localStorage.GetItemAsync<Question[]>("data");
// Check if data exist in the local storage
if (currentData == null)
{
// this code add in the local storage the fake data
var originalData = await _http.GetFromJsonAsync<Question[]>($"{_navigationManager.BaseUri}fake-question.json");
await _localStorage.SetItemAsync("data", originalData);
}
return (await _localStorage.GetItemAsync<Question[]>("data")).Skip((currentPage - 1) * pageSize).Take(pageSize).ToList();
}
}
}
using Blazor.Models;
using Blazor.ViewClasses;
using Blazored.LocalStorage;
using Microsoft.AspNetCore.Components;
using static System.Net.WebRequestMethods;
namespace Blazor.Services
{
public class DataLocalService : IDataService
{
private readonly HttpClient _http;
private readonly ILocalStorageService _localStorage;
private readonly NavigationManager _navigationManager;
private readonly IWebHostEnvironment _webHostEnvironment;
public DataLocalService(
ILocalStorageService localStorage,
HttpClient http,
IWebHostEnvironment webHostEnvironment,
NavigationManager navigationManager)
{
_localStorage = localStorage;
_http = http;
_webHostEnvironment = webHostEnvironment;
_navigationManager = navigationManager;
}
public async Task<Chapter> GetById(int id)
{
// Get the current data
var currentData = await _localStorage.GetItemAsync<List<Chapter>>("data");
// Get the chapter int the list
var chapter = currentData.FirstOrDefault(w => w.Id == id);
// Check if chapter exist
if (chapter == null)
{
throw new Exception($"Unable to found the item with ID: {id}");
}
return chapter;
}
public async Task Update(int id, ChapterModel model)
{
// Get the current data
var currentData = await _localStorage.GetItemAsync<List<Chapter>>("data");
// Get the chapter int the list
var chapter = currentData.FirstOrDefault(w => w.Id == id);
// Check if chapter exist
if (chapter == null)
{
throw new Exception($"Unable to found the item with ID: {id}");
}
// Modify the content of the chapter
chapter.Name = model.Name;
// Save the data
await _localStorage.SetItemAsync("data", currentData);
}
public async Task Add(ChapterModel model)
{
// Get the current data
var currentData = await _localStorage.GetItemAsync<List<Chapter>>("data");
// Simulate the Id
model.Id = currentData.Max(s => s.Id) + 1;
// Add the chapter to the current data
currentData.Add(new Chapter
{
Id = model.Id,
Name = model.Name
});
// Save the data
await _localStorage.SetItemAsync("data", currentData);
}
public async Task Delete(int id)
{
// Get the current data
//var currentData = await _localStorage.GetItemAsync<List<Chapter>>("data");
var currentData = _http.GetFromJsonAsync<List<Chapter>>($"https://trusting-panini.87-106-126-109.plesk.page/api/chapters").Result;
// Get the chapter int the list
var chapter = currentData.FirstOrDefault(w => w.Id == id);
// Delete chapter in
currentData.Remove(chapter);
// Save the data
await _localStorage.SetItemAsync("data", currentData);
}
public async Task<int> Count()
{
// Load data from the local storage
var currentData = await _localStorage.GetItemAsync<Chapter[]>("data");
// Check if data exist in the local storage
if (currentData == null)
{
// this code add in the local storage the fake data
var originalData = await _http.GetFromJsonAsync<Chapter[]>($"{_navigationManager.BaseUri}fake-data.json");
await _localStorage.SetItemAsync("data", originalData);
}
return (await _localStorage.GetItemAsync<Chapter[]>("data")).Length;
}
public async Task<List<Chapter>> List(int currentPage, int pageSize)
{
// Load data from the local storage
var currentData = await _localStorage.GetItemAsync<Chapter[]>("data");
// Check if data exist in the local storage
if (currentData == null)
{
// this code add in the local storage the fake data
var originalData = await _http.GetFromJsonAsync<Chapter[]>($"{_navigationManager.BaseUri}fake-data.json");
await _localStorage.SetItemAsync("data", originalData);
}
return (await _localStorage.GetItemAsync<Chapter[]>("data")).Skip((currentPage - 1) * pageSize).Take(pageSize).ToList();
}
public async Task<Administrator> GetAdminById(int id)
{
// Get the current data
var currentData = await _localStorage.GetItemAsync<List<Administrator>>("data");
// Get the admin int the list
var admin = currentData.FirstOrDefault(w => w.Id == id);
// Check if admin exist
if (admin == null)
{
throw new Exception($"Unable to found the item with ID: {id}");
}
return admin;
}
public async Task Update(int id, AdministratorModel model)
{
// Get the current data
var currentData = await _localStorage.GetItemAsync<List<Administrator>>("data");
// Get the admin int the list
var admin = currentData.FirstOrDefault(w => w.Id == id);
// Check if admin exist
if (admin == null)
{
throw new Exception($"Unable to found the item with ID: {id}");
}
// Modify the content of the adminnistrator
admin.Username = model.Username;
admin.HashedPassword = model.HashedPassword;
// Save the data
await _localStorage.SetItemAsync("data", currentData);
}
public async Task Add(AdministratorModel model)
{
// Get the current data
var currentData = await _localStorage.GetItemAsync<List<Administrator>>("data");
// Simulate the Id
model.Id = currentData.Max(s => s.Id) + 1;
// Add the admin to the current data
currentData.Add(new Administrator
{
Id = model.Id,
Username = model.Username,
HashedPassword = model.HashedPassword
});
// Save the data
await _localStorage.SetItemAsync("data", currentData);
}
public async Task<int> CountAdmin()
{
// Load data from the local storage
var currentData = await _localStorage.GetItemAsync<Administrator[]>("data");
// Check if data exist in the local storage
if (currentData == null)
{
// this code add in the local storage the fake data
var originalData = await _http.GetFromJsonAsync<Administrator[]>($"{_navigationManager.BaseUri}fake-administrator.json");
await _localStorage.SetItemAsync("data", originalData);
}
return (await _localStorage.GetItemAsync<Administrator[]>("data")).Length;
}
public async Task<List<Administrator>> ListAdmin(int currentPage, int pageSize)
{
// Load data from the local storage
var currentData = await _localStorage.GetItemAsync<Administrator[]>("data");
// Check if data exist in the local storage
if (currentData == null)
{
// this code add in the local storage the fake data
var originalData = await _http.GetFromJsonAsync<Administrator[]>($"{_navigationManager.BaseUri}fake-administrator.json");
await _localStorage.SetItemAsync("data", originalData);
}
return (await _localStorage.GetItemAsync<Administrator[]>("data")).Skip((currentPage - 1) * pageSize).Take(pageSize).ToList();
}
public async Task<Question> GetQuestionById(int id)
{
// Get the current data
var currentData = await _localStorage.GetItemAsync<List<Question>>("data");
// Get the question int the list
var question = currentData.FirstOrDefault(w => w.Id == id);
// Check if question exist
if (question == null)
{
throw new Exception($"Unable to found the item with ID: {id}");
}
return question;
}
//public async Task Update(int id, QuestionsModel model)
//{
// // Get the current data
// var currentData = await _localStorage.GetItemAsync<List<Question>>("data");
// // Get the admin int the list
// var question = currentData.FirstOrDefault(w => w.Id == id);
// // Check if admin exist
// if (question == null)
// {
// throw new Exception($"Unable to found the item with ID: {id}");
// }
// // Modify the content of the adminnistrator
// question.Username = model.Username;
// question.HashedPassword = model.HashedPassword;
// // Save the data
// await _localStorage.SetItemAsync("data", currentData);
//}
//public async Task Add(QuestionsModel model)
//{
// // Get the current data
// var currentData = await _localStorage.GetItemAsync<List<Question>>("data");
// // Simulate the Id
// model.Id = currentData.Max(s => s.Id) + 1;
// // Add the admin to the current data
// currentData.Add(new Question
// {
// Id = model.Id,
// Username = model.Username,
// HashedPassword = model.HashedPassword
// });
// // Save the data
// await _localStorage.SetItemAsync("data", currentData);
//}
public async Task<int> CountQuestion()
{
// Load data from the local storage
var currentData = await _localStorage.GetItemAsync<Question[]>("data");
// Check if data exist in the local storage
if (currentData == null)
{
// this code add in the local storage the fake data
var originalData = await _http.GetFromJsonAsync<Question[]>($"{_navigationManager.BaseUri}fake-question.json");
await _localStorage.SetItemAsync("data", originalData);
}
return (await _localStorage.GetItemAsync<Question[]>("data")).Length;
}
public async Task<List<Question>> ListQuestion(int currentPage, int pageSize)
{
// Load data from the local storage
var currentData = await _localStorage.GetItemAsync<Question[]>("data");
// Check if data exist in the local storage
if (currentData == null)
{
// this code add in the local storage the fake data
var originalData = await _http.GetFromJsonAsync<Question[]>($"{_navigationManager.BaseUri}fake-question.json");
await _localStorage.SetItemAsync("data", originalData);
}
return (await _localStorage.GetItemAsync<Question[]>("data")).Skip((currentPage - 1) * pageSize).Take(pageSize).ToList();
}
public async Task<Player> GetPlayerById(int id)
{
// Get the current data
var currentData = await _localStorage.GetItemAsync<List<Player>>("data");
// Get the player in the list
var player = currentData.FirstOrDefault(w => w.Id == id);
// Check if player exist
if (player == null)
{
throw new Exception($"Unable to found the item with ID: {id}");
}
return player;
}
public async Task Update(int id, PlayerModel model)
{
// Get the current data
var currentData = await _localStorage.GetItemAsync<List<Player>>("data");
// Get the admin int the list
var player = currentData.FirstOrDefault(w => w.Id == id);
// Check if admin exist
if (player == null)
{
throw new Exception($"Unable to found the item with ID: {id}");
}
// Modify the content of the adminnistrator
player.Nickname = model.Nickname;
player.HashedPassword = model.HashedPassword;
// Save the data
await _localStorage.SetItemAsync("data", currentData);
}
public async Task Add(PlayerModel model)
{
// Get the current data
var currentData = await _localStorage.GetItemAsync<List<Player>>("data");
// Simulate the Id
model.Id = currentData.Max(s => s.Id) + 1;
// Add the admin to the current data
currentData.Add(new Player
{
Id = model.Id,
Nickname = model.Nickname,
HashedPassword = model.HashedPassword
});
// Save the data
await _localStorage.SetItemAsync("data", currentData);
}
public async Task<int> CountPlayer()
{
// Load data from the local storage
var currentData = await _localStorage.GetItemAsync<Player[]>("data");
// Check if data exist in the local storage
if (currentData == null)
{
// this code add in the local storage the fake data
var originalData = await _http.GetFromJsonAsync<Player[]>($"{_navigationManager.BaseUri}fake-administrator.json");
await _localStorage.SetItemAsync("data", originalData);
}
return (await _localStorage.GetItemAsync<Player[]>("data")).Length;
}
public async Task<List<Player>> ListPlayer(int currentPage, int pageSize)
{
// Load data from the local storage
var currentData = await _localStorage.GetItemAsync<Player[]>("data");
// Check if data exist in the local storage
if (currentData == null)
{
// this code add in the local storage the fake data
var originalData = await _http.GetFromJsonAsync<Player[]>($"{_navigationManager.BaseUri}fake-administrator.json");
await _localStorage.SetItemAsync("data", originalData);
}
return (await _localStorage.GetItemAsync<Player[]>("data")).Skip((currentPage - 1) * pageSize).Take(pageSize).ToList();
}
}
}

@ -15,9 +15,9 @@ namespace Blazor.Services
Task Update(int id, ChapterModel model);
Task Add(AdministratorsModel model);
Task Add(AdministratorModel model);
Task Update(int id, AdministratorsModel model);
Task Update(int id, AdministratorModel model);
Task<Administrator> GetAdminById(int id);
@ -33,7 +33,16 @@ namespace Blazor.Services
Task<int> CountQuestion();
Task<List<Question>> ListQuestion(int currentPage, int pageSize);
Task Delete(int id);
Task Delete(int id);
Task Add(PlayerModel model);
Task Update(int id, PlayerModel model);
Task<Player> GetPlayerById(int id);
Task<int> CountPlayer();
Task<List<Player>> ListPlayer(int currentPage, int pageSize);
}
}

@ -29,6 +29,11 @@
<span class="oi oi-plus" aria-hidden="true"></span> Questions
</NavLink>
</div>
<div class="nav-item px-3">
<NavLink class="nav-link" href="players">
<span class="oi oi-plus" aria-hidden="true"></span> Players
</NavLink>
</div>
</nav>
</div>

@ -4,6 +4,6 @@ public class Administrator
{
public int Id { get; set; }
public string Username { get; set; }
public string hashedPassword { get; set; }
public string HashedPassword { get; set; }
}

@ -2,15 +2,8 @@
public class Player
{
public int Id { get; private set; }
public string Nickname { get; private set; }
public int Id { get; set; }
public string Nickname { get; set; }
public string HashedPassword { get; set; }
public Player(int id, string nickname, string hashedPassword)
{
Id = id;
Nickname = nickname;
HashedPassword = hashedPassword;
}
}

Loading…
Cancel
Save