feat : page questions
continuous-integration/drone/push Build is passing Details

pull/38/head
Maxence GUITARD 1 year ago
parent 987bc11c9b
commit a1b99f9cb7

@ -2,7 +2,7 @@
using Blazor.Services; using Blazor.Services;
using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components;
namespace Blazor.Pages namespace Blazor.Pages.Admins
{ {
public partial class EditAdministrator public partial class EditAdministrator
{ {

@ -1,47 +1,29 @@
@page "/questions" @page "/questions"
@using Blazor.Data @using Blazor.ViewClasses;
@inject WeatherForecastService ForecastService @using Blazorise.DataGrid
@using Blazored.Modal;
<h3>Chapters</h3>
<PageTitle>Weather forecast</PageTitle> <div>
<NavLink class="btn btn-primary" href="addChapter" Match="NavLinkMatch.All">
<i class="fa fa-plus"></i> Ajouter
</NavLink>
</div>
<h1>Weather forecast</h1> <DataGrid TItem="Question"
Data="@questions"
ReadData="@OnReadData"
TotalItems="@totalQuestion"
PageSize="10"
ShowPager
Responsive>
<DataGridColumn TItem="Question" Field="@nameof(Question.Id)" Caption="#" />
<DataGridColumn TItem="Question" Field="@nameof(Question.Content)" Caption="Display content" />
<p>This component demonstrates fetching data from a service.</p> <DataGridColumn TItem="Question" Field="@nameof(Question.Id)" Caption="Action">
<DisplayTemplate>
@if (forecasts == null) <a href="editQuestion/@(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>
<p><em>Loading...</em></p> </DisplayTemplate>
} </DataGridColumn>
else </DataGrid>
{
<table class="table">
<thead>
<tr>
<th>Date</th>
<th>Temp. (C)</th>
<th>Temp. (F)</th>
<th>Summary</th>
</tr>
</thead>
<tbody>
@foreach (var forecast in forecasts)
{
<tr>
<td>@forecast.Date.ToShortDateString()</td>
<td>@forecast.TemperatureC</td>
<td>@forecast.TemperatureF</td>
<td>@forecast.Summary</td>
</tr>
}
</tbody>
</table>
}
@code {
private WeatherForecast[]? forecasts;
protected override async Task OnInitializedAsync()
{
forecasts = await ForecastService.GetForecastAsync(DateOnly.FromDateTime(DateTime.Now));
}
}

@ -1,6 +1,178 @@
namespace Blazor.Pages.Questions; 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;
namespace Blazor.Pages.Questions;
public partial class Questions public partial class Questions
{ {
public List<Question> questions;
private int totalQuestion;
[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(Question.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("questions", true);
}
protected override async Task OnAfterRenderAsync(bool firstRender)
{
// Do not treat this action if is not the first render
if (!firstRender)
{
return;
}
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 (we load the data sync for initialize the data before load the OnReadData method)
var originalData = Http.GetFromJsonAsync<Question[]>($"https://trusting-panini.87-106-126-109.plesk.page/api/chapters").Result;
await LocalStorage.SetItemAsync("data", originalData);
}
}
private async Task OnReadData(DataGridReadDataEventArgs<Question> e)
{
if (e.CancellationToken.IsCancellationRequested)
{
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<Question[]>($"https://trusting-panini.87-106-126-109.plesk.page/api/chapters").Result;
if (!e.CancellationToken.IsCancellationRequested)
{
totalQuestion = (await LocalStorage.GetItemAsync<List<Question>>("data")).Count;
questions = new List<Question>(response); // an actual data for the current page
}
}
private async void Export()
{
StringBuilder sb = new StringBuilder();
HttpResponseMessage response = await Http.GetAsync("https://trusting-panini.87-106-126-109.plesk.page/api/chapters");
var json = await response.Content.ReadAsStringAsync();
using (var jsonFile = ChoJSONReader.LoadText(json))
{
using (var csvFile = new ChoCSVWriter(sb).WithFirstLineHeader())
{
csvFile.Write(jsonFile);
}
}
var sentFile = new MemoryStream(Encoding.UTF32.GetBytes(sb.ToString()));
using (var streamRef = new DotNetStreamReference(stream: sentFile))
{
await IJSRuntime.InvokeVoidAsync("downloadFileFromStream", "data.csv", streamRef);
}
}
private async Task SingleUpload(InputFileChangeEventArgs e)
{
using (MemoryStream ms = new MemoryStream())
{
await e.File.OpenReadStream().CopyToAsync(ms);
var bytes = ms.ToArray();
string s = Encoding.UTF8.GetString(bytes);
char[] invalidChars = { '1', '2', '3', '4', '5', '6', '7', '8', '9', '\r', '\n', ',', ' ' };
List<string> filteredStrings = new List<string>();
StringBuilder filteredString = new StringBuilder();
foreach (var c in s)
{
if (!invalidChars.Contains(c))
{
filteredString.Append(c);
}
else
{
if (filteredString.Length > 0)
{
filteredStrings.Add(filteredString.ToString());
filteredString.Clear();
}
}
}
if (filteredString.Length > 0)
{
filteredStrings.Add(filteredString.ToString());
}
foreach (var filteredStr in filteredStrings)
{
var formData = new List<KeyValuePair<string, string>>();
formData.Add(new KeyValuePair<string, string>("name", filteredStr));
var formContent = new FormUrlEncodedContent(formData);
string apiUri = "https://trusting-panini.87-106-126-109.plesk.page/api/add/chapters";
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();
}
}
}
}
}
} }

@ -98,8 +98,6 @@ namespace Blazor.Services
await _localStorage.SetItemAsync("data", currentData); await _localStorage.SetItemAsync("data", currentData);
} }
public async Task<int> Count() public async Task<int> Count()
{ {
// Load data from the local storage // Load data from the local storage
@ -137,10 +135,10 @@ namespace Blazor.Services
// Get the current data // Get the current data
var currentData = await _localStorage.GetItemAsync<List<Administrator>>("data"); var currentData = await _localStorage.GetItemAsync<List<Administrator>>("data");
// Get the chapter int the list // Get the admin int the list
var admin = currentData.FirstOrDefault(w => w.Id == id); var admin = currentData.FirstOrDefault(w => w.Id == id);
// Check if chapter exist // Check if admin exist
if (admin == null) if (admin == null)
{ {
throw new Exception($"Unable to found the item with ID: {id}"); throw new Exception($"Unable to found the item with ID: {id}");
@ -171,7 +169,6 @@ namespace Blazor.Services
await _localStorage.SetItemAsync("data", currentData); await _localStorage.SetItemAsync("data", currentData);
} }
public async Task Add(AdministratorsModel model) public async Task Add(AdministratorsModel model)
{ {
// Get the current data // Get the current data
@ -180,7 +177,7 @@ namespace Blazor.Services
// Simulate the Id // Simulate the Id
model.Id = currentData.Max(s => s.Id) + 1; model.Id = currentData.Max(s => s.Id) + 1;
// Add the chapter to the current data // Add the admin to the current data
currentData.Add(new Administrator currentData.Add(new Administrator
{ {
Id = model.Id, Id = model.Id,
@ -224,5 +221,98 @@ namespace Blazor.Services
return (await _localStorage.GetItemAsync<Administrator[]>("data")).Skip((currentPage - 1) * pageSize).Take(pageSize).ToList(); 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();
}
} }
} }

@ -24,6 +24,15 @@ namespace Blazor.Services
Task<int> CountAdmin(); Task<int> CountAdmin();
Task<List<Administrator>> ListAdmin(int currentPage, int pageSize); Task<List<Administrator>> ListAdmin(int currentPage, int pageSize);
//Task Add(QuestionsModel model);
//Task Update(int id, QuestionsModel model);
Task<Question> GetQuestionById(int id);
Task<int> CountQuestion();
Task<List<Question>> ListQuestion(int currentPage, int pageSize);
Task Delete(int id); Task Delete(int id);
} }

Loading…
Cancel
Save