Docummentation #30

Merged
leni.beaulaton merged 4 commits from Docummentation into master 3 months ago

@ -18,6 +18,12 @@ namespace WF_WebAdmin.Pages
[Inject]
public IStringLocalizer<Accueil> Localizer { get; set; }
/// <summary>
/// This method is called during the initialization of the Blazor component.
/// It is asynchronous and is used to load data or perform actions before the component is rendered.
/// </summary>
protected override async Task OnInitializedAsync()
{
Dailyquote = await Http.GetFromJsonAsync<Quote[]>($"{NavigationManager.BaseUri}fake-dataDailyQuote.json");

@ -22,40 +22,85 @@ namespace WF_WebAdmin.Pages
private QuizModel QuizModel = new();
/// <summary>
/// Handles the valid submission of a quiz form.
/// This method is triggered when the form is successfully validated and the user submits the quiz data.
/// It retrieves the current quiz count, increments it, and then adds a new quiz entry to the quiz service.
/// Finally, it navigates to the "modifquiz" page.
/// </summary>
private async void HandleValidSubmit()
{
// Declare a variable to hold the ID of the new quiz.
int id;
// Get the current number of quizzes from the quiz service.
id = await quizService.getNbQuiz();
// Increment the quiz ID for the new quiz.
id++;
// Create a new quiz and add it using the quiz service.
await quizService.addQuiz(new Quiz(
id,
validateInformation(QuizModel.Question),
validateInformation(QuizModel.AnswerA),
validateInformation(QuizModel.AnswerB),
validateInformation(QuizModel.AnswerC),
validateInformation(QuizModel.AnswerD),
validateReponse(QuizModel.CAnswer)
id, // New quiz ID
validateInformation(QuizModel.Question), // Validated question
validateInformation(QuizModel.AnswerA), // Validated answer A
validateInformation(QuizModel.AnswerB), // Validated answer B
validateInformation(QuizModel.AnswerC), // Validated answer C
validateInformation(QuizModel.AnswerD), // Validated answer D
validateReponse(QuizModel.CAnswer) // Validated correct answer
));
// Navigate to the "modifquiz" page after adding the quiz.
NavigationManager.NavigateTo("modifquiz");
}
/// <summary>
/// Handles the change of the correct answer for the quiz.
/// This method is triggered when the user selects or changes the correct answer for the quiz question.
/// It updates the QuizModel's Correct Answer property with the selected answer.
/// </summary>
/// <param name="item">The selected answer that will be marked as the correct answer.</param>
/// <param name="checkedValue">The value of the selected option, typically used for validation or additional logic.</param>
private void OnCAwnserChange(string item, object checkedValue)
{
// Update the correct answer in the QuizModel with the selected answer.
QuizModel.CAnswer = item;
}
/// <summary>
/// Validates the provided string item.
/// This method is used to validate input data, but the validation logic is not yet implemented.
/// </summary>
/// <param name="item">The string input to be validated.</param>
/// <returns>
/// Returns the input string as it is for now. The validation logic is yet to be implemented.
/// </returns>
private static string validateInformation(string item)
{
return item; // VALIDATION A FAIRE
}
/// <summary>
/// Validates the provided answer item (A, B, C, or D) for the quiz.
/// This method ensures that the input corresponds to one of the allowed values for the correct answer.
/// If the input is invalid or null, it throws an exception and returns a default value ("A") in case of error.
/// </summary>
/// <param name="item">The answer item (A, B, C, or D) to be validated.</param>
/// <returns>
/// Returns the input item if valid (A, B, C, or D). If the item is invalid or null, it returns a default value ("A").
/// </returns>
private static string validateReponse(string item)
{
try
{
// Check if the item is not null or empty
if (!string.IsNullOrEmpty(item))
{
// Validate that the item is one of the allowed values: A, B, C, or D
switch (item)
{
case "A":
@ -67,18 +112,23 @@ namespace WF_WebAdmin.Pages
case "D":
break;
default:
throw new InvalidDataException("Invalid item (validateReponse) : item must be A,B,C or D " + item + "give.");
// Throw exception if the item is not one of the allowed answers
throw new InvalidDataException("Invalid item (validateReponse) : item must be A,B,C or D " + item + " given.");
}
}
else
{
// Throw exception if the item is null or empty
throw new ArgumentNullException("Invalid item (validateReponse): null given.");
}
// Return the validated item
return item;
}
catch (Exception ex)
{
return "A"; //Default Argument
// In case of an exception, return a default answer ("A")
return "A"; // Default Argument
}
}
}

@ -38,91 +38,171 @@ namespace WF_WebAdmin.Pages
/// <summary>
/// This method is called when the component is initialized.
/// It is an asynchronous method that retrieves a list of users from the user service.
/// The method fetches a subset of users with a specified maximum value and page number (1 in this case).
/// </summary>
protected override async Task OnInitializedAsync()
{
// Retrieve a list of users using the user service. The number of users and page number are specified.
// MaxValue determines how many users to retrieve, and '1' refers to the first page of results.
users = await userService.getSomeUser(MaxValue, 1);
}
/// <summary>
/// Handles the event when data is read in the data grid.
/// This method is triggered during pagination or when data is loaded into the grid.
/// It asynchronously fetches a page of users based on the requested page size and page number,
/// and updates the list of users and total item count if the operation is not cancelled.
/// </summary>
/// <param name="e">The event arguments containing pagination details (page size and page number) and a cancellation token.</param>
private async Task OnReadData(DataGridReadDataEventArgs<User> e)
{
// If the cancellation token is requested, exit the method without processing the request.
if (e.CancellationToken.IsCancellationRequested)
{
return;
}
// Fetch a page of users from the user service using the page size and page number provided by the event arguments.
var response = await userService.getSomeUser(e.PageSize, e.Page);
// If the operation is not cancelled, update the total number of users and the list of users.
if (!e.CancellationToken.IsCancellationRequested)
{
totalItem = await userService.getNbUser();
users = new List<User>(response.ToArray());
page = e.Page;
totalItem = await userService.getNbUser(); // Get the total number of users
users = new List<User>(response.ToArray()); // Store the retrieved users in the users list
page = e.Page; // Update the current page number
}
}
// ------- Popup remove user -------
/// <summary>
/// Displays a confirmation popup to confirm the deletion of a user.
/// This method is triggered when the user intends to delete a user,
/// and it sets the user to be deleted and shows the confirmation popup.
/// </summary>
/// <param name="user">The user to be deleted, which is passed to the method for confirmation.</param>
private void ShowConfirmation(User user)
{
userToDelete = user;
showPopupDelete = true;
// Set the user to be deleted and show the confirmation popup.
userToDelete = user; // Store the user to be deleted in a variable
showPopupDelete = true; // Display the confirmation popup
}
/// <summary>
/// Displays a confirmation popup for modifying a user's information.
/// This method is triggered when the user intends to modify a specific user's data,
/// and it sets the selected user and shows the modification confirmation popup.
/// </summary>
/// <param name="user">The user whose information is to be modified, passed to the method for confirmation.</param>
private void ShowModifyConfirmation(User user)
{
// Afficher la modale et mémoriser l'utilisateur à supprimer
selectedUser = user;
showModifyPopup = true;
// Set the selected user and show the modification confirmation popup.
selectedUser = user; // Store the user to be modified
showModifyPopup = true; // Display the confirmation popup for modification
}
/// <summary>
/// Removes the specified user from the system.
/// This method is triggered when the user confirms the deletion of a user.
/// It calls the user service to remove the user, closes the confirmation popup,
/// and then refreshes the list of users by fetching the updated data.
/// </summary>
private async Task RemoveUser()
{
// Check if there is a user to delete
if (userToDelete != null)
{
// Remove the selected user from the system using the user service
await userService.removeUser(userToDelete);
// Close the confirmation popup after the deletion
ClosePopup();
// Refresh the list of users by fetching the updated data from the user service
var response = await userService.getSomeUser(MaxValue, page);
// Update the users list with the latest data
users = new List<User>(response.ToArray());
}
}
/// <summary>
/// Modifies the selected user's information.
/// This method is triggered when the user confirms the modification of a user's details.
/// It calls the user service to update the user's information and then closes the modification popup.
/// </summary>
private async Task ModifyUser()
{
// Update the selected user's information using the user service
await userService.updateUser(selectedUser);
// Close the modification popup after the update is complete
ClosePopup();
}
/// <summary>
/// Closes all open popups in the UI by setting their visibility flags to false.
/// This method is typically called after an action (like deleting or modifying a user)
/// to hide any active popups and reset the UI state.
/// </summary>
private void ClosePopup()
{
showDeletePopup = false;
showModifyPopup = false;
showPopupDelete = false;
showPopupAdmin = false;
// Set all popup visibility flags to false to hide the popups
showDeletePopup = false; // Close the delete confirmation popup
showModifyPopup = false; // Close the modify confirmation popup
showPopupDelete = false; // Close any additional delete popups
showPopupAdmin = false; // Close the admin-related popup (if any)
}
// ------- Popup admin -------
/// <summary>
/// Displays a confirmation popup to confirm the promotion of a user to admin status.
/// This method is triggered when the user intends to promote a specific user to admin.
/// It sets the selected user to be promoted and shows the confirmation popup for admin promotion.
/// </summary>
/// <param name="user">The user to be promoted to admin, passed to the method for confirmation.</param>
private void ShowConfirmationAdmin(User user)
{
userToAdmin = user;
showPopupAdmin = true;
// Set the user to be promoted to admin and show the confirmation popup.
userToAdmin = user; // Store the user to be promoted
showPopupAdmin = true; // Display the confirmation popup for admin promotion
}
/// <summary>
/// Toggles the admin status of the selected user.
/// This method checks the current admin status of the user, and if the user is not an admin,
/// it promotes them to admin. If the user is already an admin, it demotes them.
/// After the change, the user's information is updated, and the confirmation popup is closed.
/// </summary>
private async Task setAdmin()
{
// Check if the user is not already an admin
if (!userToAdmin.IsAdmin)
{
// Promote the user to admin
userToAdmin.IsAdmin = true;
await userService.updateUser(userToAdmin);
ClosePopup();
await userService.updateUser(userToAdmin); // Update the user status in the service
ClosePopup(); // Close the confirmation popup
}
else
{
// Demote the user from admin to normal user
userToAdmin.IsAdmin = false;
await userService.updateUser(userToAdmin);
ClosePopup();
await userService.updateUser(userToAdmin); // Update the user status in the service
ClosePopup(); // Close the confirmation popup
}
}

@ -23,9 +23,19 @@ namespace WF_WebAdmin.Pages
private List<Source> src = new List<Source>();
/// <summary>
/// Asynchronously initializes the component by loading data related to a quote.
/// This method fetches a specific quote based on the provided ID and populates the `quoteModel`
/// with the quote's content, language, character, source, and other associated data.
/// It also loads additional data such as character and source information for the quote.
/// </summary>
protected override async Task OnInitializedAsync()
{
// Fetch the quote data based on the provided ID.
q = await quoteService.getOnequote(Id);
// Populate the quoteModel with the data from the retrieved quote.
quoteModel.Content = q.Content;
quoteModel.Langue = q.Langue;
quoteModel.Charac = q.Charac;
@ -36,30 +46,50 @@ namespace WF_WebAdmin.Pages
quoteModel.DateSrc = q.DateSrc;
quoteModel.UserProposition = q.UserProposition;
quoteModel.IsValid = q.IsValid;
// Fetch additional data related to the quote, such as character and source.
charac = await quoteService.getChar();
src = await quoteService.getSrc();
}
/// <summary>
/// Handles the submission of a valid form for updating a quote.
/// This method takes the data from `quoteModel`, updates the selected quote (`q`) with the new values,
/// and then calls the `quoteService.updateQuote` method to persist the changes.
/// After updating, it navigates to the "modifquote" page.
/// </summary>
protected async void HandleValidSubmit()
{
// Update the properties of the selected quote (`q`) with the data from `quoteModel`.
q.Content = quoteModel.Content;
q.Langue = quoteModel.Langue;
q.TitleSrc = quoteModel.TitleSrc;
q.Charac = quoteModel.Charac;
// Call the quote service to update the quote in the data source.
await quoteService.updateQuote(q);
// Navigate to the "modifquote" page after updating the quote.
NavigationManager.NavigateTo("modifquote");
}
/// <summary>
/// Handles the language change event for the quote.
/// This method updates the `Langue` property of the `quoteModel` based on the selected language (`item`).
/// It only accepts "fr" (French) or "en" (English) as valid language options.
/// </summary>
/// <param name="item">The selected language ("fr" or "en") passed to the method.</param>
/// <param name="checkedValue">The checked value (unused in this method but may be used for other purposes).</param>
private void OnlangChange(string item, object checkedValue)
{
if(item == "fr" || item == "en")
// Check if the selected language is either "fr" or "en"
if (item == "fr" || item == "en")
{
// Update the Langue property of the quoteModel with the selected language
quoteModel.Langue = item;
}
}
}
}

@ -14,13 +14,26 @@ namespace WF_WebAdmin.Pages
private readonly ILogger<ErrorModel> _logger;
/// <summary>
/// Initializes a new instance of the <see cref="ErrorModel"/> class.
/// This constructor is used to inject the <see cref="ILogger{ErrorModel}"/> into the model for logging purposes.
/// </summary>
/// <param name="logger">An instance of the <see cref="ILogger{ErrorModel}"/> used for logging error-related information.</param>
public ErrorModel(ILogger<ErrorModel> logger)
{
_logger = logger;
}
/// <summary>
/// Handles the GET request for the page or endpoint.
/// This method retrieves the request ID for tracing purposes, using the `Activity.Current?.Id`
/// if it's available, or the `HttpContext.TraceIdentifier` as a fallback if no current activity ID is present.
/// </summary>
public void OnGet()
{
// Retrieve the current request ID for tracing
RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
}
}

@ -26,45 +26,63 @@ namespace WF_WebAdmin.Pages
[Inject]
public NavigationManager NavigationManager { get; set; }
/// <summary>
/// Asynchronously initializes the component by loading user login data.
/// This method retrieves a list of user login information from a JSON file located at the specified URI
/// and populates the `usersConnexion` list with the data.
/// </summary>
protected override async Task OnInitializedAsync()
{
// Fetch user login data from the specified JSON file.
usersConnexion = await Http.GetFromJsonAsync<List<UserLogin>>($"{NavigationManager.BaseUri}fake-dataUserLogin.json");
}
/// <summary>
/// Validates the login credentials of the user.
/// This method checks if the provided username and password match any user in the `usersConnexion` list.
/// If the credentials are correct and the user is an admin, it stores the user details and navigates to the home page.
/// If the credentials are incorrect, an error message is set for display.
/// </summary>
public void validlogin()
{
// Check if both the username and password are provided
if (!string.IsNullOrEmpty(userLogin.Name) || !string.IsNullOrEmpty(userLogin.Mdp))
{
// Loop through the list of connected users to find a match
foreach (var user in usersConnexion)
{
if(userLogin.Name == user.Name && userLogin.Mdp == user.Mdp)
// Check if the username and password match the user credentials
if (userLogin.Name == user.Name && userLogin.Mdp == user.Mdp)
{
if(user.IsAdmin)
// Check if the user is an admin
if (user.IsAdmin)
{
// If the user is an admin, store their information and navigate to the home page
uLogin.Id = userLogin.Id;
uLogin.Name = user.Name;
uLogin.Image = user.Image;
// Redirect to the homepage
NavigationManager.NavigateTo(NavigationManager.BaseUri + "accueil");
return;
}
else
{
// If the user is not an admin, display an error message
ErrorConnexion = "Connexion échouée, le nom ou le mot de passe sont incorrectes";
}
}
else
{
// If credentials do not match, set the error message
ErrorConnexion = "Connexion échouée, le nom ou le mot de passe sont incorrectes";
}
}
}
}
}
}

@ -28,60 +28,129 @@ namespace WF_WebAdmin.Pages
[Inject]
public IQuizService QuizService { get; set; }
/// <summary>
/// Handles the data reading event for a data grid, fetching quiz data based on the specified page and page size.
/// This method makes an asynchronous call to retrieve a specific page of quizzes and updates the `quiz` list and pagination details.
/// If the cancellation token is requested, it exits early without making further calls or updates.
/// </summary>
/// <param name="e">The event arguments containing pagination details such as page size and page number.</param>
private async Task OnReadData(DataGridReadDataEventArgs<Quiz> e)
{
// Check if the cancellation token has been requested
if (e.CancellationToken.IsCancellationRequested)
{
return;
}
// Fetch the quiz data for the specified page and page size
var response = await QuizService.getSommeQuiz(e.PageSize, e.Page);
// If cancellation hasn't been requested, process the data
if (!e.CancellationToken.IsCancellationRequested)
{
// Get the total number of quizzes for pagination purposes
totalItem = await QuizService.getNbQuiz();
// Update the quiz data for the current page
quiz = response.ToArray();
// Update the current page number
page = e.Page;
}
}
/// <summary>
/// Handles the event when the "Edit" button is clicked for a quiz.
/// This method checks if a valid quiz is passed. If so, it sets the `selectedQuiz` to the clicked quiz and shows the quiz edit modal.
/// </summary>
/// <param name="quiz">The quiz object that was clicked for editing.</param>
private void OnEditButtonClicked(Quiz quiz)
{
// If the quiz is null, return early
if (quiz == null) return;
// Set the selected quiz to the one clicked by the user
selectedQuiz = quiz;
// Show the modal or UI for editing the quiz
showEditQuiz = true;
}
/// <summary>
/// Closes the open popups and resets any related states.
/// This method hides the quiz edit popup, the delete confirmation popup, and resets the selected quiz to `null`.
/// </summary>
private void ClosePopup()
{
// Hide the edit quiz popup
showEditQuiz = false;
// Hide the delete confirmation popup
showPopupDelete = false;
// Reset the selected quiz to null
selectedQuiz = null;
}
/// <summary>
/// Edits the selected quiz by updating it in the quiz service.
/// This method asynchronously sends the updated quiz data to the service for persistence.
/// After updating the quiz, it clears the selected quiz and closes any open popups.
/// </summary>
private async Task EditQuiz()
{
// Update the quiz in the service
await QuizService.updateQuiz(selectedQuiz);
// Clear the selected quiz after successful update
selectedQuiz = null;
// Close the popups after the edit operation
ClosePopup();
}
/// <summary>
/// Handles the event when the delete action is triggered for a quiz.
/// This method sets the selected quiz to the one passed as a parameter and shows the delete confirmation popup.
/// </summary>
/// <param name="q">The quiz to be deleted.</param>
private void OnDelete(Quiz q)
{
// Set the selected quiz to the one passed in
selectedQuiz = q;
// Show the delete confirmation popup
showPopupDelete = true;
}
/// <summary>
/// Removes the selected quiz from the quiz service and updates the quiz list.
/// This method first checks if a quiz is selected, and if so, it deletes the quiz by calling the service.
/// After removal, it clears the `selectedQuiz`, updates the quiz list, and closes the delete confirmation popup.
/// </summary>
private async void RemoveQuote()
{
// Check if a quiz is selected for deletion
if (selectedQuiz != null)
{
// Remove the selected quiz from the service by its ID
await QuizService.removeQuiz(selectedQuiz.Id);
// Clear the selected quiz after successful removal
selectedQuiz = null;
// Update the quiz list by fetching the latest data
var response = await QuizService.getSommeQuiz(MaxValue, page);
quiz = response.ToArray();
}
showPopupDelete= false;
// Close the delete confirmation popup
showPopupDelete = false;
}
}
}

@ -28,19 +28,34 @@ namespace WF_WebAdmin.Pages
[Inject]
public IQuoteService QuoteService { get; set; }
/// <summary>
/// Handles the data reading event for a data grid, fetching quote data based on the specified page and page size.
/// This method makes an asynchronous call to retrieve a specific page of quotes and updates the `quotes` list and pagination details.
/// If the cancellation token is requested, it exits early without making further calls or updates.
/// </summary>
/// <param name="e">The event arguments containing pagination details such as page size and page number.</param>
private async Task OnReadData(DataGridReadDataEventArgs<Quote> e)
{
// Check if the cancellation token has been requested
if (e.CancellationToken.IsCancellationRequested)
{
return;
}
// Fetch the quote data for the specified page and page size
var response = await QuoteService.getSomeQuote(e.PageSize, e.Page);
// If cancellation hasn't been requested, process the data
if (!e.CancellationToken.IsCancellationRequested)
{
// Get the total number of quotes for pagination purposes
totalItem = await QuoteService.getNbQuote();
// Update the quotes data for the current page
quotes = response.ToArray();
// Update the current page number
page = e.Page;
}
}
@ -52,10 +67,16 @@ namespace WF_WebAdmin.Pages
showEditQuote = true;
}*/
/// <summary>
/// Closes the open popups and resets any related states.
/// This method hides the delete confirmation popup and clears the selected quote.
/// </summary>
private void ClosePopup()
{
/*showEditQuote = false;*/
// Hide the delete confirmation popup
showPopupDelete = false;
// Reset the selected quote to null
selectedQuote = null;
}
@ -66,22 +87,43 @@ namespace WF_WebAdmin.Pages
ClosePopup();
}*/
/// <summary>
/// Handles the event when the delete action is triggered for a quote.
/// This method sets the selected quote to the one passed as a parameter and displays the delete confirmation popup.
/// </summary>
/// <param name="q">The quote that is being deleted.</param>
private void OnDelete(Quote q)
{
// Set the selected quote to the one passed in
selectedQuote = q;
// Display the delete confirmation popup
showPopupDelete = true;
}
/// <summary>
/// Removes the selected quote by calling the remove service and updates the quote list.
/// This method checks if a quote is selected. If so, it removes the quote using the `QuoteService`, clears the selected quote,
/// and fetches the updated list of quotes. It also closes the delete confirmation popup after the operation.
/// </summary>
private async void RemoveQuote()
{
// Check if a quote is selected for removal
if (selectedQuote != null)
{
// Remove the selected quote using the QuoteService
await QuoteService.removeQuote(selectedQuote);
selectedQuote= null;
// Clear the selected quote after removal
selectedQuote = null;
// Update the quotes list by fetching the latest quotes data
var response = await QuoteService.getSomeQuote(MaxValue, page);
quotes = response.ToArray();
}
showPopupDelete= false;
// Close the delete confirmation popup
showPopupDelete = false;
}
}
}

@ -22,36 +22,70 @@ namespace WF_WebAdmin.Pages
[Inject]
public IQuizService QuizService { get; set; }
/// <summary>
/// Initializes the component asynchronously by fetching the quizzes that need validation.
/// This method retrieves a list of quizzes from the `QuizService` that are pending validation when the component is initialized.
/// </summary>
protected override async Task OnInitializedAsync()
{
// Fetch quizzes that need validation
quizzes = await QuizService.getQuizzesToValidate();
}
/// <summary>
/// Handles the event when the "Validate" button is clicked for a quiz.
/// This method calls the `ValidateQuiz` method, passing the specified quiz for validation.
/// </summary>
/// <param name="quiz">The quiz that is being validated.</param>
private void OnValidButton(Quiz quiz)
{
// Call the ValidateQuiz method to validate the quiz
ValidateQuiz(quiz);
}
/// <summary>
/// Validates the specified quiz by setting its `IsValid` property to true and updating its state in the service.
/// This method logs a message to the console indicating the quiz has been validated, then updates the quiz's validation status.
/// It then calls the `QuizService.updateQuiz` method to persist the changes.
/// </summary>
/// <param name="quiz">The quiz that is being validated.</param>
private void ValidateQuiz(Quiz quiz)
{
// Log the validation action to the console
Console.WriteLine($"Quiz {quiz.Id} validated!");
// Create a new quiz instance (or modify the existing one)
Quiz newQuiz = quiz;
newQuiz.IsValid = true;
// Mis à jour de l'état du quiz
// Update the quiz state in the QuizService
QuizService.updateQuiz(quiz);
}
/// <summary>
/// Handles the event when the "Reject" button is clicked for a quiz.
/// This method calls the `RejectQuiz` method, passing the specified quiz to be rejected.
/// </summary>
/// <param name="quiz">The quiz that is being rejected.</param>
private void OnRejectButton(Quiz quiz)
{
// Call the RejectQuiz method to reject the quiz
RejectQuiz(quiz);
}
/// <summary>
/// Rejects the specified quiz by logging a rejection message and removing it from the QuizService.
/// This method logs a message to the console indicating the quiz has been rejected, and then calls the `QuizService.removeQuiz`
/// method to remove the quiz from the system.
/// </summary>
/// <param name="quiz">The quiz that is being rejected.</param>
private void RejectQuiz(Quiz quiz)
{
// Log the rejection action to the console
Console.WriteLine($"Quiz {quiz.Id} rejected!");
// Remove the rejected quiz from the QuizService
QuizService.removeQuiz(quiz.Id);
}
}

@ -23,8 +23,14 @@ namespace WF_WebAdmin.Pages
[Inject]
public NavigationManager NavigationManager { get; set; }
/// <summary>
/// Initializes the component asynchronously by fetching a list of quotes from a JSON file.
/// This method makes an asynchronous HTTP request to retrieve an array of `Quote` objects from a specified JSON file
/// located at the base URI, and then assigns the result to the `quotes` variable.
/// </summary>
protected override async Task OnInitializedAsync()
{
// Fetch the list of quotes from the JSON file located at the base URI
quotes = await Http.GetFromJsonAsync<Quote[]>($"{NavigationManager.BaseUri}fake-dataQuote.json");
}
}

@ -7,12 +7,35 @@ public class QuizServiceStub: IQuizService
{
private readonly string _jsonFilePath = Path.Combine(Environment.CurrentDirectory, "wwwroot", "fake_data_quiz.json");
/// <summary>
/// Asynchronously saves a list of quiz objects to a JSON file.
/// </summary>
/// <param name="quizzes">A list of <see cref="Quiz"/> objects to be serialized and saved.</param>
/// <returns>A task representing the asynchronous operation.</returns>
/// <remarks>
/// This method serializes the list of quizzes to a well-formatted JSON string and saves it
/// to a specified file path. The <paramref name="quizzes"/> list is serialized using
/// <see cref="JsonSerializer"/> with indented formatting to make the JSON human-readable.
/// </remarks>
public async Task saveQuizJson(List<Quiz> quizzes)
{
var json = JsonSerializer.Serialize(quizzes, new JsonSerializerOptions { WriteIndented = true });
await File.WriteAllTextAsync(_jsonFilePath, json);
}
/// <summary>
/// Asynchronously adds a new quiz to the list of quizzes and saves the updated list to a JSON file.
/// </summary>
/// <param name="quiz">The <see cref="Quiz"/> object to be added to the list of quizzes.</param>
/// <returns>A task representing the asynchronous operation.</returns>
/// <remarks>
/// This method retrieves the current list of quizzes using <see cref="getQuizzes"/>, assigns a unique ID to the
/// new quiz (based on the highest existing ID), and adds the new quiz to the list. Afterward, the updated list
/// of quizzes is saved back to the JSON file using <see cref="saveQuizJson"/>. The new quiz will have an ID
/// that's one greater than the highest existing ID or 1 if no quizzes exist.
/// </remarks>
public async Task addQuiz(Quiz quiz)
{
var data = await getQuizzes();
@ -21,6 +44,17 @@ public class QuizServiceStub: IQuizService
await saveQuizJson(data);
}
/// <summary>
/// Asynchronously updates an existing quiz in the list of quizzes and saves the updated list to a JSON file.
/// </summary>
/// <param name="quiz">The <see cref="Quiz"/> object containing the updated data.</param>
/// <returns>A task representing the asynchronous operation.</returns>
/// <remarks>
/// This method retrieves the current list of quizzes using <see cref="getQuizzes"/>, searches for the quiz
/// with the same ID as the one provided, and updates its properties with the new values from the given quiz object.
/// If the quiz is found, the updated list is saved back to the JSON file using <see cref="saveQuizJson"/>.
/// If no quiz with the matching ID is found, no update is performed.
/// </remarks>
public async Task updateQuiz(Quiz quiz)
{
var data = await getQuizzes();
@ -39,6 +73,17 @@ public class QuizServiceStub: IQuizService
}
}
/// <summary>
/// Asynchronously removes a quiz from the list of quizzes by its ID and saves the updated list to a JSON file.
/// </summary>
/// <param name="id">The ID of the <see cref="Quiz"/> to be removed.</param>
/// <returns>A task representing the asynchronous operation.</returns>
/// <remarks>
/// This method retrieves the current list of quizzes using <see cref="getQuizzes"/>, searches for the quiz
/// with the specified ID, and removes it from the list if found. After removal, the updated list of quizzes is
/// saved back to the JSON file using <see cref="saveQuizJson"/>. If no quiz with the matching ID is found,
/// no changes are made.
/// </remarks>
public async Task removeQuiz(int id)
{
var data = await getQuizzes();
@ -55,6 +100,16 @@ public class QuizServiceStub: IQuizService
throw new NotImplementedException();
}
/// <summary>
/// Asynchronously retrieves the list of quizzes from a JSON file.
/// </summary>
/// <returns>A task representing the asynchronous operation, with a <see cref="List{Quiz}"/> result containing the quizzes.</returns>
/// <remarks>
/// This method checks if the JSON file exists at the specified file path. If the file does not exist, it logs a
/// message to the console and returns an empty list of quizzes. If the file exists, it reads the JSON content,
/// deserializes it into a list of <see cref="Quiz"/> objects, and returns the list. If the deserialization is
/// unsuccessful or the file is empty, it returns an empty list instead.
/// </remarks>
public async Task<List<Quiz>> getQuizzes()
{
if (!File.Exists(_jsonFilePath))
@ -67,12 +122,31 @@ public class QuizServiceStub: IQuizService
return JsonSerializer.Deserialize<List<Quiz>>(json) ?? new List<Quiz>();
}
/// <summary>
/// Asynchronously retrieves the list of quizzes that are marked as invalid and need validation.
/// </summary>
/// <returns>A task representing the asynchronous operation, with a <see cref="List{Quiz}"/> result containing quizzes that are not valid.</returns>
/// <remarks>
/// This method retrieves the full list of quizzes using <see cref="getQuizzes"/> and filters it to return only those
/// quizzes where the <see cref="Quiz.IsValid"/> property is set to <c>false</c>. The filtered list is then returned.
/// If no quizzes are invalid, an empty list will be returned.
/// </remarks>
public async Task<List<Quiz>> getQuizzesToValidate()
{
var quizzes = await getQuizzes();
return quizzes.Where(quiz => quiz.IsValid == false).ToList();
}
/// <summary>
/// Asynchronously retrieves a specific quiz by its ID from the list of quizzes.
/// </summary>
/// <param name="id">The ID of the <see cref="Quiz"/> to retrieve.</param>
/// <returns>A task representing the asynchronous operation, with a <see cref="Quiz"/> result containing the matching quiz, or <c>null</c> if not found.</returns>
/// <remarks>
/// This method retrieves the full list of quizzes using <see cref="getQuizzes"/> and searches for a quiz with
/// the specified ID. If a quiz with the matching ID is found, it is returned; otherwise, the method returns <c>null</c>.
/// </remarks>
public async Task<Quiz> getQuiz(int id)
{
var data = await getQuizzes();
@ -84,23 +158,45 @@ public class QuizServiceStub: IQuizService
return null;
}
/// <summary>
/// Asynchronously retrieves a paginated list of quizzes, returning a specific number of quizzes for the given page.
/// </summary>
/// <param name="nb">The number of quizzes to retrieve per page.</param>
/// <param name="page">The page number to retrieve, where the first page is 1.</param>
/// <returns>A task representing the asynchronous operation, with a <see cref="List{Quiz}"/> result containing the quizzes for the specified page.</returns>
/// <remarks>
/// This method retrieves the full list of quizzes using <see cref="getQuizzes"/> and returns a subset of quizzes based
/// on the specified page number and the number of quizzes per page. If the requested page exceeds the available quizzes,
/// the method returns the last page with the remaining quizzes. If the number of quizzes requested per page exceeds the
/// total number of quizzes, the method will return all quizzes available.
/// </remarks>
public async Task<List<Quiz>> getSommeQuiz(int nb, int page)
{
var data = await getQuizzes();
if ((page - 1) * nb + nb > data.Count())
{
if(nb > data.Count())
if (nb > data.Count())
{
return data.GetRange(0, data.Count()-1);
return data.GetRange(0, data.Count() - 1);
}
return data.GetRange(data.Count() - nb, nb);
}
return data.GetRange((page - 1) * nb, nb);
}
/// <summary>
/// Asynchronously retrieves the total number of quizzes in the list.
/// </summary>
/// <returns>A task representing the asynchronous operation, with an <see cref="int"/> result containing the total number of quizzes.</returns>
/// <remarks>
/// This method retrieves the full list of quizzes using <see cref="getQuizzes"/> and returns the count of quizzes in the list.
/// It simply returns the number of quizzes available in the data source.
/// </remarks>
public async Task<int> getNbQuiz()
{
var data = await getQuizzes();
return data.Count;
}
}

@ -10,7 +10,17 @@ namespace WF_WebAdmin.Service
/// <summary>
/// Asynchronously adds a new quote to the database and returns the corresponding <see cref="QuoteDTO"/>.
/// </summary>
/// <param name="quote">The <see cref="Quote"/> object to be added to the database.</param>
/// <returns>A task representing the asynchronous operation, with a <see cref="QuoteDTO"/> result containing the added quote's data.</returns>
/// <remarks>
/// This method converts the provided <see cref="Quote"/> object into a <see cref="QuoteDTO"/> using <see cref="QuoteExtension"/>.
/// It then inserts the quote into the PostgreSQL database using a parameterized SQL query with the help of Npgsql.
/// After successfully inserting the quote, the corresponding <see cref="QuoteDTO"/> is returned to the caller.
/// Error handling is in place to catch any issues during the database insertion process, with the exception message logged in case of failure.
/// </remarks>
public async Task<QuoteDTO> AddQuoteAsync(Quote quote)
{
QuoteExtension extension = new QuoteExtension();
@ -64,35 +74,72 @@ namespace WF_WebAdmin.Service
}
public Task RemoveQuote(Quote quote)
/// <summary>
/// Asynchronously handles the removal of a quote and returns the corresponding <see cref="QuoteDTO"/>.
/// </summary>
/// <param name="quote">The <see cref="Quote"/> object to be removed.</param>
/// <returns>A task representing the asynchronous operation, with a <see cref="QuoteDTO"/> result corresponding to the removed quote.</returns>
/// <remarks>
/// This method takes a <see cref="Quote"/> object, converts it into a <see cref="QuoteDTO"/> using the
/// <see cref="QuoteExtension"/>, and then returns the DTO. Note that while this function is named `RemoveQuote`,
/// it currently only converts the quote to a DTO and does not actually perform any database removal operation.
/// You may need to implement additional logic to remove the quote from the database.
/// </remarks>
public Task RemoveQuote(Quote quote)
{
QuoteExtension extension = new QuoteExtension();
QuoteDTO quoteDTO = extension.QuoteToDTO(quote);
// Return the DTO as the result of this asynchronous operation (though no removal logic is currently implemented)
return Task.FromResult(quoteDTO);
}
/// <summary>
/// Asynchronously validates a quote and returns the corresponding <see cref="QuoteDTO"/>.
/// </summary>
/// <param name="quote">The <see cref="Quote"/> object to be validated.</param>
/// <returns>A task representing the asynchronous operation, with a <see cref="QuoteDTO"/> result corresponding to the validated quote.</returns>
/// <remarks>
/// This method takes a <see cref="Quote"/> object, converts it into a <see cref="QuoteDTO"/> using the
/// <see cref="QuoteExtension"/>, and returns the DTO. The method is named `validQuote`, but currently, it only
/// converts the quote into a DTO and does not perform any actual validation logic.
/// If you intend to validate the quote (e.g., updating its status in a database), you will need to implement
/// the actual validation logic separately.
/// </remarks>
public Task validQuote(Quote quote)
{
QuoteExtension extension = new QuoteExtension();
QuoteDTO quoteDTO = extension.QuoteToDTO(quote);
// Return the DTO as the result of this asynchronous operation (though no validation logic is currently implemented)
return Task.FromResult(quoteDTO);
}
/// <summary>
/// Asynchronously updates a quote and returns the corresponding <see cref="QuoteDTO"/>.
/// </summary>
/// <param name="quote">The <see cref="Quote"/> object to be updated.</param>
/// <returns>A task representing the asynchronous operation, with a <see cref="QuoteDTO"/> result corresponding to the updated quote.</returns>
/// <remarks>
/// This method takes a <see cref="Quote"/> object, converts it into a <see cref="QuoteDTO"/> using the
/// <see cref="QuoteExtension"/>, and returns the DTO. The method is named `updateQuote`, but currently, it only
/// converts the quote into a DTO and does not perform any actual update logic.
/// If you intend to update the quote (e.g., modifying the quote in a database or data source),
/// you will need to implement the actual update logic separately.
/// </remarks>
public Task updateQuote(Quote quote)
{
QuoteExtension extension = new QuoteExtension();
QuoteDTO quoteDTO = extension.QuoteToDTO(quote);
// Return the DTO as the result of this asynchronous operation (though no update logic is currently implemented)
return Task.FromResult(quoteDTO);
}
public Task addQuote(Quote quote)
{
throw new NotImplementedException();

@ -9,143 +9,285 @@ namespace WF_WebAdmin.Service;
private readonly string _char = Path.Combine(Environment.CurrentDirectory, "wwwroot", "fake-dataCaracter.json");
private readonly string _src = Path.Combine(Environment.CurrentDirectory, "wwwroot", "fake-dataSource.json");
/// <summary>
/// Asynchronously saves a list of quotes to a JSON file.
/// </summary>
/// <param name="quotes">The list of <see cref="Quote"/> objects to be serialized and saved to the file.</param>
/// <returns>A task representing the asynchronous operation of saving the quotes to the file.</returns>
/// <remarks>
/// This method serializes the provided list of <see cref="Quote"/> objects into JSON format using <see cref="JsonSerializer"/>.
/// The serialized JSON is then saved to the file path specified in the <see cref="_jsonFilePath"/> field. The JSON is written
/// with indentation for better readability.
/// If the file does not already exist, it will be created.
/// </remarks>
public async Task saveQuoteJson(List<Quote> quotes)
{
var json = JsonSerializer.Serialize(quotes, new JsonSerializerOptions { WriteIndented = true });
await File.WriteAllTextAsync(_jsonFilePath, json);
}
{
var json = JsonSerializer.Serialize(quotes, new JsonSerializerOptions { WriteIndented = true });
await File.WriteAllTextAsync(_jsonFilePath, json);
}
/// <summary>
/// Asynchronously adds a new quote to the list and saves it to a JSON file.
/// </summary>
/// <param name="quote">The <see cref="Quote"/> object to be added to the list.</param>
/// <returns>A task representing the asynchronous operation of adding the quote and saving the updated list to the file.</returns>
/// <remarks>
/// This method retrieves the current list of quotes using the <see cref="getAllQuote"/> method, assigns a new ID to the
/// provided quote (incremented from the maximum existing ID), and adds the quote to the list. After updating the list,
/// the method saves the updated list back to the JSON file using <see cref="saveQuoteJson"/>.
/// If the list is empty, the new quote is assigned an ID of 1.
/// </remarks>
public async Task addQuote(Quote quote)
{
var data = await getAllQuote();
quote.Id = data.Count > 0 ? data.Max(p => p.Id) + 1 : 1;
data.Add(quote);
await saveQuoteJson(data);
}
public async Task addQuote(Quote quote)
/// <summary>
/// Asynchronously removes a quote from the list and saves the updated list to a JSON file.
/// </summary>
/// <param name="quote">The <see cref="Quote"/> object to be removed from the list.</param>
/// <returns>A task representing the asynchronous operation of removing the quote and saving the updated list to the file.</returns>
/// <remarks>
/// This method retrieves the current list of quotes using the <see cref="getAllQuote"/> method.
/// It searches for the provided quote by its `Id` and, if found, removes it from the list.
/// After removing the quote, the method saves the updated list back to the JSON file using <see cref="saveQuoteJson"/>.
/// If the quote is not found in the list, no action is taken.
/// </remarks>
public async Task removeQuote(Quote quote)
{
var data = await getAllQuote();
var q = data.FirstOrDefault(p => p.Id == quote.Id);
if (q != null)
{
var data = await getAllQuote();
quote.Id = data.Count > 0 ? data.Max(p => p.Id) + 1 : 1;
data.Add(quote);
data.Remove(q);
await saveQuoteJson(data);
}
}
public async Task validQuote(Quote quote)
{
throw new NotImplementedException();
}
public async Task removeQuote(Quote quote)
{
var data = await getAllQuote();
var q = data.FirstOrDefault(p => p.Id == quote.Id);
if (q != null)
{
data.Remove(q);
await saveQuoteJson(data);
}
}
public async Task validQuote(Quote quote)
/// <summary>
/// Asynchronously updates the details of an existing quote and saves the updated list to a JSON file.
/// </summary>
/// <param name="quote">The <see cref="Quote"/> object containing the updated details of the quote.</param>
/// <returns>A task representing the asynchronous operation of updating the quote and saving the updated list to the file.</returns>
/// <remarks>
/// This method retrieves the current list of quotes using the <see cref="getAllQuote"/> method.
/// It searches for the quote with the provided `Id` and, if found, updates its properties (e.g., content, character, image path, etc.)
/// with the values from the provided `quote` object. After updating the quote, the method saves the updated list back to the JSON file
/// using <see cref="saveQuoteJson"/>. If the quote with the specified `Id` is not found, no action is taken.
/// </remarks>
public async Task updateQuote(Quote quote)
{
var data = await getAllQuote();
var q = data.FirstOrDefault(p => p.Id == quote.Id);
if (q != null)
{
throw new NotImplementedException();
q.Content = quote.Content;
q.Charac = quote.Charac;
q.ImgPath = quote.ImgPath;
q.TitleSrc = quote.TitleSrc;
q.DateSrc = quote.DateSrc;
q.Langue = quote.Langue;
await saveQuoteJson(data);
}
}
public async Task updateQuote(Quote quote)
/// <summary>
/// Asynchronously retrieves all quotes from a JSON file.
/// </summary>
/// <returns>A task representing the asynchronous operation, with a result of a list of <see cref="Quote"/> objects.</returns>
/// <remarks>
/// This method checks if the JSON file exists at the specified file path (<see cref="_jsonFilePath"/>).
/// If the file does not exist, it logs a message and returns an empty list of quotes.
/// If the file exists, it reads the JSON content, deserializes it into a list of <see cref="Quote"/> objects,
/// and returns that list. If the deserialization results in a null value, an empty list is returned.
/// </remarks>
public async Task<List<Quote>> getAllQuote()
{
if (!File.Exists(_jsonFilePath))
{
var data = await getAllQuote();
var q = data.FirstOrDefault(p => p.Id == quote.Id);
if (q != null)
{
q.Content = quote.Content;
q.Charac = quote.Charac;
q.ImgPath = quote.ImgPath;
q.TitleSrc = quote.TitleSrc;
q.DateSrc = quote.DateSrc;
q.Langue = quote.Langue;
await saveQuoteJson(data);
}
Console.Out.WriteLine($"{_jsonFilePath} not found");
return new List<Quote>();
}
public async Task<List<Quote>> getAllQuote()
{
if (!File.Exists(_jsonFilePath))
{
Console.Out.WriteLine($"{_jsonFilePath} not found");
return new List<Quote>();
}
var json = await File.ReadAllTextAsync(_jsonFilePath);
return JsonSerializer.Deserialize<List<Quote>>(json) ?? new List<Quote>();
}
var json = await File.ReadAllTextAsync(_jsonFilePath);
return JsonSerializer.Deserialize<List<Quote>>(json) ?? new List<Quote>();
}
public async Task<List<Quote>> getSomeQuote(int nb, int page)
/// <summary>
/// Asynchronously retrieves a subset of quotes based on the specified page number and the number of quotes per page.
/// </summary>
/// <param name="nb">The number of quotes to retrieve per page.</param>
/// <param name="page">The page number for pagination.</param>
/// <returns>A task representing the asynchronous operation, with a result of a list of <see cref="Quote"/> objects for the specified page.</returns>
/// <remarks>
/// This method retrieves all quotes using the <see cref="getAllQuote"/> method and then calculates the range of quotes
/// to be returned based on the provided `nb` (number of quotes per page) and `page` (the page number). It ensures that
/// the returned subset does not exceed the total number of quotes available.
///
/// If the calculated range is larger than the available quotes, it returns a subset of quotes from the end of the list.
/// If the requested page number exceeds the total number of pages, the method will return the last available page of quotes.
/// </remarks>
public async Task<List<Quote>> getSomeQuote(int nb, int page)
{
var quotes = await getAllQuote();
if ((page - 1) * nb + nb > quotes.Count())
{
var quotes = await getAllQuote();
if((page - 1) * nb + nb > quotes.Count())
if (nb > quotes.Count())
{
if (nb > quotes.Count())
{
return quotes.GetRange(0, quotes.Count());
}
return quotes.GetRange(quotes.Count()-nb, nb);
return quotes.GetRange(0, quotes.Count());
}
return quotes.GetRange((page - 1) * nb, nb);
return quotes.GetRange(quotes.Count() - nb, nb);
}
return quotes.GetRange((page - 1) * nb, nb);
}
public async Task<Quote> getOnequote(int id)
/// <summary>
/// Asynchronously retrieves a single quote based on its ID.
/// </summary>
/// <param name="id">The unique identifier of the <see cref="Quote"/> to be retrieved.</param>
/// <returns>A task representing the asynchronous operation, with a result of the <see cref="Quote"/> object if found, otherwise null.</returns>
/// <remarks>
/// This method retrieves all quotes using the <see cref="getAllQuote"/> method and searches for the quote that matches the provided `id`.
/// If a matching quote is found, it returns that quote; otherwise, it returns `null`.
/// </remarks>
public async Task<Quote> getOnequote(int id)
{
var data = await getAllQuote();
var q = data.FirstOrDefault(p => p.Id == id);
if (q != null)
{
var data = await getAllQuote();
var q = data.FirstOrDefault(p => p.Id == id);
if (q != null)
{
return q;
}
return null;
return q;
}
return null;
}
public async Task<List<Quote>> reserchQuote(string reserch, List<string> argument)
public async Task<List<Quote>> reserchQuote(string reserch, List<string> argument)
{
throw new NotImplementedException();
}
public async Task<List<Quote>> getAllQuoteInvalid()
{
var quotes = await getAllQuote();
quotes = quotes.Where(q => q.IsValid == false).ToList();
return quotes;
}
public async Task<List<Quote>> getSomeQuoteInvalid(int nb, int page)
/// <summary>
/// Asynchronously retrieves all invalid quotes from the list.
/// </summary>
/// <returns>A task representing the asynchronous operation, with a result of a list of invalid <see cref="Quote"/> objects.</returns>
/// <remarks>
/// This method retrieves all quotes using the <see cref="getAllQuote"/> method and filters them by the `IsValid` property.
/// It returns only those quotes where `IsValid` is set to `false`.
/// If no invalid quotes are found, an empty list is returned.
/// </remarks>
public async Task<List<Quote>> getAllQuoteInvalid()
{
var quotes = await getAllQuote();
quotes = quotes.Where(q => q.IsValid == false).ToList();
return quotes;
}
/// <summary>
/// Asynchronously retrieves a subset of invalid quotes based on the specified page number and the number of quotes per page.
/// </summary>
/// <param name="nb">The number of invalid quotes to retrieve per page.</param>
/// <param name="page">The page number for pagination.</param>
/// <returns>A task representing the asynchronous operation, with a result of a list of invalid <see cref="Quote"/> objects for the specified page.</returns>
/// <remarks>
/// This method retrieves all invalid quotes using the <see cref="getAllQuoteInvalid"/> method and then calculates the range of invalid quotes
/// to be returned based on the provided `nb` (number of quotes per page) and `page` (the page number). It ensures that
/// the returned subset does not exceed the total number of invalid quotes available.
///
/// If the calculated range is larger than the available invalid quotes, it returns a subset of quotes from the end of the list.
/// If the requested page number exceeds the total number of pages, the method will return the last available page of invalid quotes.
/// </remarks>
public async Task<List<Quote>> getSomeQuoteInvalid(int nb, int page)
{
var quotes = await getAllQuoteInvalid();
if ((page - 1) * nb + nb > quotes.Count())
{
var quotes = await getAllQuoteInvalid();
if ((page - 1) * nb + nb > quotes.Count())
if (nb > quotes.Count())
{
if (nb > quotes.Count())
{
return quotes.GetRange(0, quotes.Count());
}
return quotes.GetRange(quotes.Count() - nb, nb);
return quotes.GetRange(0, quotes.Count());
}
return quotes.GetRange((page - 1) * nb, nb);
return quotes.GetRange(quotes.Count() - nb, nb);
}
return quotes.GetRange((page - 1) * nb, nb);
}
/// <summary>
/// Asynchronously retrieves the total number of quotes.
/// </summary>
/// <returns>A task representing the asynchronous operation, with a result of the total number of <see cref="Quote"/> objects.</returns>
/// <remarks>
/// This method retrieves all quotes using the <see cref="getAllQuote"/> method and returns the count of quotes.
/// It provides the total number of quotes currently available in the data source.
/// </remarks>
public async Task<int> getNbQuote()
{
var data = await getAllQuote();
return data.Count;
}
public async Task<int> getNbQuote()
/// <summary>
/// Asynchronously retrieves a list of characters from a JSON file.
/// </summary>
/// <returns>A task representing the asynchronous operation, with a result of a list of <see cref="Character"/> objects.</returns>
/// <remarks>
/// This method checks if the JSON file containing character data exists at the specified file path (`_char`).
/// If the file does not exist, it logs a message to the console and returns an empty list of characters.
/// If the file exists, it reads the JSON content, deserializes it into a list of <see cref="Character"/> objects,
/// and returns that list. If the deserialization results in a null value, an empty list is returned.
/// </remarks>
public async Task<List<Character>> getChar()
{
if (!File.Exists(_char))
{
var data = await getAllQuote();
return data.Count;
Console.Out.WriteLine($"{_char} not found");
return new List<Character>();
}
public async Task<List<Character>> getChar()
{
if (!File.Exists(_char))
{
Console.Out.WriteLine($"{_char} not found");
return new List<Character>();
}
var json = await File.ReadAllTextAsync(_char);
return JsonSerializer.Deserialize<List<Character>>(json) ?? new List<Character>();
}
var json = await File.ReadAllTextAsync(_char);
return JsonSerializer.Deserialize<List<Character>>(json) ?? new List<Character>();
}
public async Task<List<Source>> getSrc()
/// <summary>
/// Asynchronously retrieves a list of sources from a JSON file.
/// </summary>
/// <returns>A task representing the asynchronous operation, with a result of a list of <see cref="Source"/> objects.</returns>
/// <remarks>
/// This method checks if the JSON file containing source data exists at the specified file path (`_src`).
/// If the file does not exist, it logs a message to the console and returns an empty list of sources.
/// If the file exists, it reads the JSON content, deserializes it into a list of <see cref="Source"/> objects,
/// and returns that list. If the deserialization results in a null value, an empty list is returned.
/// </remarks>
public async Task<List<Source>> getSrc()
{
if (!File.Exists(_src))
{
if (!File.Exists(_src))
{
Console.Out.WriteLine($"{_src} not found");
return new List<Source>();
}
var json = await File.ReadAllTextAsync(_src);
return JsonSerializer.Deserialize<List<Source>>(json) ?? new List<Source>();
Console.Out.WriteLine($"{_src} not found");
return new List<Source>();
}
}
var json = await File.ReadAllTextAsync(_src);
return JsonSerializer.Deserialize<List<Source>>(json) ?? new List<Source>();
}
}

@ -8,12 +8,32 @@ public class UserServiceStub : IUserService
private readonly string _jsonFilePath = Path.Combine(Environment.CurrentDirectory, "wwwroot", "fake_data_users.json");
/// <summary>
/// Asynchronously saves a list of users to a JSON file.
/// </summary>
/// <param name="users">The list of <see cref="User"/> objects to be saved to the file.</param>
/// <returns>A task representing the asynchronous operation.</returns>
/// <remarks>
/// This method serializes the provided list of <see cref="User"/> objects into a JSON format using the `JsonSerializer`.
/// It then writes the serialized JSON string to the file specified by the `_jsonFilePath`. The JSON is written with indentation for readability.
/// </remarks>
public async Task saveUsersJson(List<User> users)
{
var json = JsonSerializer.Serialize(users, new JsonSerializerOptions { WriteIndented = true });
await File.WriteAllTextAsync(_jsonFilePath, json);
}
/// <summary>
/// Asynchronously removes a user from the list of users and saves the updated list to a JSON file.
/// </summary>
/// <param name="user">The <see cref="User"/> object to be removed from the list.</param>
/// <returns>A task representing the asynchronous operation.</returns>
/// <remarks>
/// This method retrieves the list of all users using the <see cref="getAllUser"/> method,
/// then searches for the specified user by their `Id`. If a matching user is found,
/// they are removed from the list, and the updated list is saved back to the JSON file using the <see cref="saveUsersJson"/> method.
/// </remarks>
public async Task removeUser(User user)
{
var data = await getAllUser();
@ -25,18 +45,49 @@ public class UserServiceStub : IUserService
}
}
/// <summary>
/// Asynchronously updates the role of a user, setting the user as an administrator.
/// </summary>
/// <param name="user">The <see cref="User"/> object whose role is to be updated.</param>
/// <returns>A task representing the asynchronous operation of updating the user's role.</returns>
/// <remarks>
/// This method updates the `IsAdmin` property of the specified user to `true`, indicating that the user is an administrator.
/// It then calls the <see cref="updateUser"/> method to persist the updated user information.
/// </remarks>
public Task updateRole(User user)
{
user.IsAdmin = true;
return updateUser(user);
}
/// <summary>
/// Asynchronously downgrades the role of a user, removing their administrator privileges.
/// </summary>
/// <param name="user">The <see cref="User"/> object whose role is to be downgraded.</param>
/// <returns>A task representing the asynchronous operation of downgrading the user's role.</returns>
/// <remarks>
/// This method updates the `IsAdmin` property of the specified user to `false`, removing their administrator status.
/// It then calls the <see cref="updateUser"/> method to persist the updated user information.
/// </remarks>
public Task downgradeRole(User user)
{
user.IsAdmin = false;
return updateUser(user);
}
/// <summary>
/// Asynchronously retrieves a list of all users from a JSON file.
/// </summary>
/// <returns>A task representing the asynchronous operation, with a result of a list of <see cref="User"/> objects.</returns>
/// <remarks>
/// This method checks if the JSON file containing user data exists at the specified file path (`_jsonFilePath`).
/// If the file does not exist, it logs a message to the console and returns an empty list of users.
/// If the file exists, it reads the JSON content, deserializes it into a list of <see cref="User"/> objects,
/// and returns that list. If the deserialization results in a null value, an empty list is returned.
/// </remarks>
public async Task<List<User>> getAllUser()
{
if (!File.Exists(_jsonFilePath))
@ -49,6 +100,19 @@ public class UserServiceStub : IUserService
return JsonSerializer.Deserialize<List<User>>(json) ?? new List<User>();
}
/// <summary>
/// Asynchronously retrieves a paginated list of users from a JSON file.
/// </summary>
/// <param name="nb">The number of users to retrieve per page.</param>
/// <param name="page">The page number for the data to retrieve.</param>
/// <returns>A task representing the asynchronous operation, with a result of a list of <see cref="User"/> objects.</returns>
/// <remarks>
/// This method retrieves all users using the <see cref="getAllUser"/> method, then calculates the range of users to return
/// based on the specified page number and the number of users per page (`nb`).
/// It returns the corresponding subset of users for the given page. If the page exceeds the available number of users,
/// it returns the last `nb` users available.
/// </remarks>
public async Task<List<User>> getSomeUser(int nb, int page)
{
var users = await getAllUser();
@ -59,6 +123,17 @@ public class UserServiceStub : IUserService
return users.GetRange((page - 1) * nb, nb);
}
/// <summary>
/// Asynchronously retrieves a single user by their ID from the JSON file.
/// </summary>
/// <param name="id">The ID of the user to retrieve.</param>
/// <returns>A task representing the asynchronous operation, with a result of the <see cref="User"/> object if found, otherwise null.</returns>
/// <remarks>
/// This method retrieves all users using the <see cref="getAllUser"/> method,
/// then searches for the user with the specified `id`. If a user with the given ID is found,
/// the user is returned. Otherwise, it returns null.
/// </remarks>
public async Task<User> getOneUser(int id)
{
var data = await getAllUser();
@ -70,28 +145,47 @@ public class UserServiceStub : IUserService
return null;
}
public Task<List<User>> reserchUsers(string reserch, List<string> args)
{
throw new NotImplementedException();
}
/// <summary>
/// Asynchronously retrieves the total number of users from the JSON file.
/// </summary>
/// <returns>A task representing the asynchronous operation, with a result of the total number of users.</returns>
/// <remarks>
/// This method retrieves all users using the <see cref="getAllUser"/> method and returns the count of users in the list.
/// </remarks>
public async Task<int> getNbUser()
{
var data = await getAllUser();
return data.Count;
}
/// <summary>
/// Asynchronously updates the details of a user in the JSON file.
/// </summary>
/// <param name="user">The <see cref="User"/> object containing the updated user details.</param>
/// <returns>A task representing the asynchronous operation of updating the user.</returns>
/// <remarks>
/// This method retrieves all users using the <see cref="getAllUser"/> method, then searches for the user with the specified ID.
/// If a user with the given ID is found, it updates their details (Name, Email, Image, IsAdmin) based on the provided `user` object.
/// After updating the user, the modified list of users is saved back to the JSON file using the <see cref="saveUsersJson"/> method.
/// </remarks>
public async Task updateUser(User user)
{
var data = await getAllUser();
var person = data.FirstOrDefault(p => p.Id == user.Id);
if (person != null)
{
person.Name = user.Name;
person.Email = user.Email;
person.Image = user.Image;
person.IsAdmin = user.IsAdmin;
await saveUsersJson(data);
}
var data = await getAllUser();
var person = data.FirstOrDefault(p => p.Id == user.Id);
if (person != null)
{
person.Name = user.Name;
person.Email = user.Email;
person.Image = user.Image;
person.IsAdmin = user.IsAdmin;
await saveUsersJson(data);
}
}
}

@ -21,6 +21,16 @@
new CultureInfo("fr-FR")
};
/// <summary>
/// Gets or sets the current culture for the application, triggering a navigation to set the culture cookie when changed.
/// </summary>
/// <remarks>
/// The getter retrieves the current culture of the application using <see cref="CultureInfo.CurrentCulture"/>.
/// The setter checks if the current UI culture matches the provided value. If they are the same, no action is taken.
/// If the cultures differ, it constructs a query string that includes the new culture and a redirect URI,
/// and then navigates to a "/Culture/SetCulture" endpoint to set the culture cookie.
/// The user is redirected to the same page with the new culture applied after the redirect.
/// </remarks>
private CultureInfo Culture
{
get => CultureInfo.CurrentCulture;
@ -40,4 +50,5 @@
this.NavigationManager.NavigateTo("/Culture/SetCulture" + query, forceLoad: true);
}
}
}

@ -7,7 +7,7 @@
"AnswerC": "do officia",
"AnswerD": "ut nostrud",
"CAnswer": "C",
"IsValid": false,
"IsValid": true,
"UserProposition": "Brooks Martinez"
},
{

Loading…
Cancel
Save