diff --git a/README.md b/README.md
index 4e3fa78..6c9c0c1 100644
--- a/README.md
+++ b/README.md
@@ -70,11 +70,11 @@ L'application devrait se lancer automatiquement dans votre navigateur par défau
✅ Localisation & Globalisation (au moins deux langues) (1 point)
❌ Utilisation de la configuration (1 point)
🟨 Logs (2 point)
-❌ Propreté du code (Vous pouvez vous servir de sonarqube) (2 point)
+🟨 Propreté du code (Vous pouvez vous servir de sonarqube) (2 point)
✅ IHM (Design global, placement des boutons, ...) (2 point)
✅ Emplacement du code (Pas de code dans les vues) (2 point)
# Documentation (10 points)
✅ Le Readme (2 points)
-❌ Description du fonctionnement de la solution client (illustrutration au niveau du code) (6 points)
+✅ Description du fonctionnement de la solution client (illustrutration au niveau du code) (6 points)
✅ Merge request (2 points)
diff --git a/WF-WebAdmin/WF-WebAdmin.sln b/WF-WebAdmin/WF-WebAdmin.sln
index ae4047e..b3dcada 100644
--- a/WF-WebAdmin/WF-WebAdmin.sln
+++ b/WF-WebAdmin/WF-WebAdmin.sln
@@ -5,7 +5,7 @@ VisualStudioVersion = 17.9.34723.18
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WF-WebAdmin", "WF-WebAdmin\WF-WebAdmin.csproj", "{0E8D1007-ADDC-4103-847D-8EE48ACCDC62}"
EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UnitTestWF", "UnitTestWF\UnitTestWF.csproj", "{A4EC0EC4-7A46-4F8E-99C3-4FD32F173F2F}"
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "UnitTestWF", "UnitTestWF\UnitTestWF.csproj", "{A4EC0EC4-7A46-4F8E-99C3-4FD32F173F2F}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
diff --git a/WF-WebAdmin/WF-WebAdmin/Pages/Accueil.razor.cs b/WF-WebAdmin/WF-WebAdmin/Pages/Accueil.razor.cs
index 3117665..1f04d03 100644
--- a/WF-WebAdmin/WF-WebAdmin/Pages/Accueil.razor.cs
+++ b/WF-WebAdmin/WF-WebAdmin/Pages/Accueil.razor.cs
@@ -21,6 +21,12 @@ namespace WF_WebAdmin.Pages
[Inject]
public IStringLocalizer Localizer { get; set; }
+
+
+ ///
+ /// 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.
+ ///
protected override async Task OnInitializedAsync()
{
Dailyquote = await Http.GetFromJsonAsync($"{NavigationManager.BaseUri}fake-dataDailyQuote.json");
diff --git a/WF-WebAdmin/WF-WebAdmin/Pages/AddQuiz.razor.cs b/WF-WebAdmin/WF-WebAdmin/Pages/AddQuiz.razor.cs
index 7d11c03..172b9ff 100644
--- a/WF-WebAdmin/WF-WebAdmin/Pages/AddQuiz.razor.cs
+++ b/WF-WebAdmin/WF-WebAdmin/Pages/AddQuiz.razor.cs
@@ -26,40 +26,86 @@ namespace WF_WebAdmin.Pages
private QuizModel QuizModel = new();
+ ///
+ /// 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.
+ ///
+
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.
LoggerSaveStub.Log(Logger, LogLevel.Information, $"Création de la question {QuizModel.Question}");
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");
}
+
+
+ ///
+ /// 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.
+ ///
+ /// The selected answer that will be marked as the correct answer.
+ /// The value of the selected option, typically used for validation or additional logic.
private void OnCAwnserChange(string item, object checkedValue)
{
+ // Update the correct answer in the QuizModel with the selected answer.
QuizModel.CAnswer = item;
}
+
+ ///
+ /// Validates the provided string item.
+ /// This method is used to validate input data, but the validation logic is not yet implemented.
+ ///
+ /// The string input to be validated.
+ ///
+ /// Returns the input string as it is for now. The validation logic is yet to be implemented.
+ ///
private static string validateInformation(string item)
{
return item; // VALIDATION A FAIRE
}
- private static string validateReponse(string item)
+ ///
+ /// 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.
+ ///
+ /// The answer item (A, B, C, or D) to be validated.
+ ///
+ /// Returns the input item if valid (A, B, C, or D). If the item is invalid or null, it returns a default value ("A").
+ ///
+ 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":
@@ -71,18 +117,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)
+ catch (Exception ex)
{
- return "A"; //Default Argument
+ // In case of an exception, return a default answer ("A")
+ return "A"; // Default Argument
}
}
}
diff --git a/WF-WebAdmin/WF-WebAdmin/Pages/DeleteUser.razor.cs b/WF-WebAdmin/WF-WebAdmin/Pages/DeleteUser.razor.cs
index 5bebc2f..f132410 100644
--- a/WF-WebAdmin/WF-WebAdmin/Pages/DeleteUser.razor.cs
+++ b/WF-WebAdmin/WF-WebAdmin/Pages/DeleteUser.razor.cs
@@ -13,7 +13,7 @@ namespace WF_WebAdmin.Pages
{
[Inject]
public ILogger Logger { get; set; }
-
+
private List users;
private bool showDeletePopup = false;
@@ -42,97 +42,177 @@ namespace WF_WebAdmin.Pages
+ ///
+ /// 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).
+ ///
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);
}
+
+
+ ///
+ /// 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.
+ ///
+ /// The event arguments containing pagination details (page size and page number) and a cancellation token.
private async Task OnReadData(DataGridReadDataEventArgs 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(response.ToArray());
- page = e.Page;
+ totalItem = await userService.getNbUser(); // Get the total number of users
+ users = new List(response.ToArray()); // Store the retrieved users in the users list
+ page = e.Page; // Update the current page number
}
}
// ------- Popup remove user -------
+
+ ///
+ /// 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.
+ ///
+ /// The user to be deleted, which is passed to the method for confirmation.
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
}
+
+ ///
+ /// 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.
+ ///
+ /// The user whose information is to be modified, passed to the method for confirmation.
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
}
+
+ ///
+ /// 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.
+ ///
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
LoggerSaveStub.Log(Logger, LogLevel.Information, $"Supretion de l utilisateur : {userToDelete.Name}");
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(response.ToArray());
}
}
+
+ ///
+ /// 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.
+ ///
private async Task ModifyUser()
- {
+ {
+ // Update the selected user's information using the user service
LoggerSaveStub.Log(Logger, LogLevel.Information, $"Modification de l utilisateur : {selectedUser.Name}");
await userService.updateUser(selectedUser);
+
+ // Close the modification popup after the update is complete
ClosePopup();
}
+
+ ///
+ /// 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.
+ ///
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 -------
+ ///
+ /// 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.
+ ///
+ /// The user to be promoted to admin, passed to the method for confirmation.
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
}
+ ///
+ /// 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.
+ ///
private async Task setAdmin()
{
+ // Check if the user is not already an admin
if (!userToAdmin.IsAdmin)
- {
+ {
+ // Promote the user to admin
LoggerSaveStub.Log(Logger, LogLevel.Information, $"L utilisateur {userToAdmin.Name} a ete mis en administrateur");
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
- {
+ else
+ {
+ // Demote the user from admin to normal user
LoggerSaveStub.Log(Logger, LogLevel.Information, $"L utilisateur {userToAdmin.Name} n'est plus administrateur");
userToAdmin.IsAdmin = false;
- await userService.updateUser(userToAdmin);
- ClosePopup();
+ await userService.updateUser(userToAdmin); // Update the user status in the service
+ ClosePopup(); // Close the confirmation popup
}
}
- }
+ }
}
diff --git a/WF-WebAdmin/WF-WebAdmin/Pages/Edit.razor.cs b/WF-WebAdmin/WF-WebAdmin/Pages/Edit.razor.cs
index f04058f..0d14666 100644
--- a/WF-WebAdmin/WF-WebAdmin/Pages/Edit.razor.cs
+++ b/WF-WebAdmin/WF-WebAdmin/Pages/Edit.razor.cs
@@ -27,9 +27,19 @@ namespace WF_WebAdmin.Pages
private List src = new List();
+
+ ///
+ /// 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.
+ ///
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;
@@ -40,31 +50,51 @@ 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();
}
+ ///
+ /// 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.
+ ///
protected async void HandleValidSubmit()
{
+ // Update the properties of the selected quote (`q`) with the data from `quoteModel`.
LoggerSaveStub.Log(Logger, LogLevel.Information, $"Modification de la quote {q.Content}");
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");
}
+
+
+ ///
+ /// 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.
+ ///
+ /// The selected language ("fr" or "en") passed to the method.
+ /// The checked value (unused in this method but may be used for other purposes).
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;
- }
+ }
}
-
-
-
-
}
}
diff --git a/WF-WebAdmin/WF-WebAdmin/Pages/Error.cshtml.cs b/WF-WebAdmin/WF-WebAdmin/Pages/Error.cshtml.cs
index 49fc22c..76bb3fe 100644
--- a/WF-WebAdmin/WF-WebAdmin/Pages/Error.cshtml.cs
+++ b/WF-WebAdmin/WF-WebAdmin/Pages/Error.cshtml.cs
@@ -14,13 +14,26 @@ namespace WF_WebAdmin.Pages
private readonly ILogger _logger;
+
+ ///
+ /// Initializes a new instance of the class.
+ /// This constructor is used to inject the into the model for logging purposes.
+ ///
+ /// An instance of the used for logging error-related information.
public ErrorModel(ILogger logger)
{
_logger = logger;
}
+
+ ///
+ /// 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.
+ ///
public void OnGet()
{
+ // Retrieve the current request ID for tracing
RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
}
}
diff --git a/WF-WebAdmin/WF-WebAdmin/Pages/Login.razor b/WF-WebAdmin/WF-WebAdmin/Pages/Login.razor
index c437551..9a49df2 100644
--- a/WF-WebAdmin/WF-WebAdmin/Pages/Login.razor
+++ b/WF-WebAdmin/WF-WebAdmin/Pages/Login.razor
@@ -1,4 +1,4 @@
-@page "/Login"
+@page "/login"
@using WF_WebAdmin.Model
@using System.Globalization
diff --git a/WF-WebAdmin/WF-WebAdmin/Pages/Login.razor.cs b/WF-WebAdmin/WF-WebAdmin/Pages/Login.razor.cs
index 357106b..6043aac 100644
--- a/WF-WebAdmin/WF-WebAdmin/Pages/Login.razor.cs
+++ b/WF-WebAdmin/WF-WebAdmin/Pages/Login.razor.cs
@@ -26,45 +26,63 @@ namespace WF_WebAdmin.Pages
[Inject]
public NavigationManager NavigationManager { get; set; }
+
+ ///
+ /// 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.
+ ///
protected override async Task OnInitializedAsync()
{
+ // Fetch user login data from the specified JSON file.
usersConnexion = await Http.GetFromJsonAsync>($"{NavigationManager.BaseUri}fake-dataUserLogin.json");
-
}
+ ///
+ /// 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.
+ ///
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)
{
+ // Check if the username and password match the user credentials
if (userLogin.Name == user.Name && userLogin.Mdp == user.Mdp)
{
+ // 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";
}
}
-
}
-
}
}
}
\ No newline at end of file
diff --git a/WF-WebAdmin/WF-WebAdmin/Pages/ModifQuiz.razor.cs b/WF-WebAdmin/WF-WebAdmin/Pages/ModifQuiz.razor.cs
index 366b158..088a41c 100644
--- a/WF-WebAdmin/WF-WebAdmin/Pages/ModifQuiz.razor.cs
+++ b/WF-WebAdmin/WF-WebAdmin/Pages/ModifQuiz.razor.cs
@@ -32,62 +32,131 @@ namespace WF_WebAdmin.Pages
[Inject]
public IQuizService QuizService { get; set; }
+ ///
+ /// 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.
+ ///
+ /// The event arguments containing pagination details such as page size and page number.
private async Task OnReadData(DataGridReadDataEventArgs 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;
}
}
+ ///
+ /// 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.
+ ///
+ /// The quiz object that was clicked for editing.
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;
}
+
+ ///
+ /// 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`.
+ ///
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;
}
+
+
+ ///
+ /// 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.
+ ///
private async Task EditQuiz()
{
+ // Update the quiz in the service
LoggerSaveStub.Log(Logger, LogLevel.Information, $"Modification de la question {selectedQuiz.Question}");
await QuizService.updateQuiz(selectedQuiz);
+
+ // Clear the selected quiz after successful update
selectedQuiz = null;
+
+ // Close the popups after the edit operation
ClosePopup();
}
+
+ ///
+ /// 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.
+ ///
+ /// The quiz to be deleted.
private void OnDelete(Quiz q)
{
+ // Set the selected quiz to the one passed in
selectedQuiz = q;
+
+ // Show the delete confirmation popup
showPopupDelete = true;
}
+
+ ///
+ /// 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.
+ ///
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
LoggerSaveStub.Log(Logger, LogLevel.Information, $"Supretion de la question {selectedQuiz.Question}");
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;
}
}
}
diff --git a/WF-WebAdmin/WF-WebAdmin/Pages/ModifQuote.razor.cs b/WF-WebAdmin/WF-WebAdmin/Pages/ModifQuote.razor.cs
index 09bd6ec..373be95 100644
--- a/WF-WebAdmin/WF-WebAdmin/Pages/ModifQuote.razor.cs
+++ b/WF-WebAdmin/WF-WebAdmin/Pages/ModifQuote.razor.cs
@@ -33,19 +33,34 @@ namespace WF_WebAdmin.Pages
[Inject]
public IQuoteService QuoteService { get; set; }
+
+ ///
+ /// 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.
+ ///
+ /// The event arguments containing pagination details such as page size and page number.
private async Task OnReadData(DataGridReadDataEventArgs 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;
}
}
@@ -56,11 +71,17 @@ namespace WF_WebAdmin.Pages
selectedQuote = quote;
showEditQuote = true;
}*/
-
+
+ ///
+ /// Closes the open popups and resets any related states.
+ /// This method hides the delete confirmation popup and clears the selected quote.
+ ///
private void ClosePopup()
{
- /*showEditQuote = false;*/
+ // Hide the delete confirmation popup
showPopupDelete = false;
+
+ // Reset the selected quote to null
selectedQuote = null;
}
@@ -71,23 +92,44 @@ namespace WF_WebAdmin.Pages
ClosePopup();
}*/
+ ///
+ /// 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.
+ ///
+ /// The quote that is being deleted.
private void OnDelete(Quote q)
{
+ // Set the selected quote to the one passed in
selectedQuote = q;
+
+ // Display the delete confirmation popup
showPopupDelete = true;
}
+ ///
+ /// 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.
+ ///
private async void RemoveQuote()
{
+ // Check if a quote is selected for removal
if (selectedQuote != null)
{
+ // Remove the selected quote using the QuoteService
LoggerSaveStub.Log(Logger, LogLevel.Information, $"La quote {selectedQuote.Content} a ete suprimer");
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;
}
}
}
diff --git a/WF-WebAdmin/WF-WebAdmin/Pages/ValidQuiz.razor.cs b/WF-WebAdmin/WF-WebAdmin/Pages/ValidQuiz.razor.cs
index a63707a..a809b69 100644
--- a/WF-WebAdmin/WF-WebAdmin/Pages/ValidQuiz.razor.cs
+++ b/WF-WebAdmin/WF-WebAdmin/Pages/ValidQuiz.razor.cs
@@ -26,40 +26,74 @@ namespace WF_WebAdmin.Pages
[Inject]
public IQuizService QuizService { get; set; }
+
+ ///
+ /// 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.
+ ///
protected override async Task OnInitializedAsync()
{
+ // Fetch quizzes that need validation
quizzes = await QuizService.getQuizzesToValidate();
}
+ ///
+ /// Handles the event when the "Validate" button is clicked for a quiz.
+ /// This method calls the `ValidateQuiz` method, passing the specified quiz for validation.
+ ///
+ /// The quiz that is being validated.
private void OnValidButton(Quiz quiz)
{
+ // Call the ValidateQuiz method to validate the quiz
ValidateQuiz(quiz);
}
-
+
+ ///
+ /// 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.
+ ///
+ /// The quiz that is being validated.
private void ValidateQuiz(Quiz quiz)
{
+ // Log the validation action to the console
LoggerSaveStub.Log(Logger, LogLevel.Information, $"Quiz {quiz.Id} validated!");
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);
}
+ ///
+ /// 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.
+ ///
+ /// The quiz that is being rejected.
private void OnRejectButton(Quiz quiz)
{
+ // Call the RejectQuiz method to reject the quiz
RejectQuiz(quiz);
}
+ ///
+ /// 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.
+ ///
+ /// The quiz that is being rejected.
private void RejectQuiz(Quiz quiz)
{
+ // Log the rejection action to the console
LoggerSaveStub.Log(Logger, LogLevel.Information, $"Quiz {quiz.Id} rejected!");
Console.WriteLine($"Quiz {quiz.Id} rejected!");
+ // Remove the rejected quiz from the QuizService
QuizService.removeQuiz(quiz.Id);
}
}
diff --git a/WF-WebAdmin/WF-WebAdmin/Pages/ValidQuote.razor.cs b/WF-WebAdmin/WF-WebAdmin/Pages/ValidQuote.razor.cs
index 4c9a4b5..779e014 100644
--- a/WF-WebAdmin/WF-WebAdmin/Pages/ValidQuote.razor.cs
+++ b/WF-WebAdmin/WF-WebAdmin/Pages/ValidQuote.razor.cs
@@ -21,11 +21,17 @@ namespace WF_WebAdmin.Pages
public HttpClient Http { get; set; }
[Inject]
- public NavigationManager NavigationManager { get; set; }
-
- protected override async Task OnInitializedAsync()
- {
- quotes = await Http.GetFromJsonAsync($"{NavigationManager.BaseUri}fake-dataQuote.json");
+ public NavigationManager NavigationManager { get; set; }
+
+ ///
+ /// 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.
+ ///
+ protected override async Task OnInitializedAsync()
+ {
+ // Fetch the list of quotes from the JSON file located at the base URI
+ quotes = await Http.GetFromJsonAsync($"{NavigationManager.BaseUri}fake-dataQuote.json");
}
}
}
diff --git a/WF-WebAdmin/WF-WebAdmin/Service/QuizServiceStub.cs b/WF-WebAdmin/WF-WebAdmin/Service/QuizServiceStub.cs
index 7b6b662..f35612f 100644
--- a/WF-WebAdmin/WF-WebAdmin/Service/QuizServiceStub.cs
+++ b/WF-WebAdmin/WF-WebAdmin/Service/QuizServiceStub.cs
@@ -5,14 +5,37 @@ namespace WF_WebAdmin.Service;
public class QuizServiceStub: IQuizService
{
- private readonly string _jsonFilePath = Path.Combine(Environment.CurrentDirectory, "wwwroot", "fake_data_quiz.json");
-
- public async Task saveQuizJson(List quizzes)
- {
- var json = JsonSerializer.Serialize(quizzes, new JsonSerializerOptions { WriteIndented = true });
- await File.WriteAllTextAsync(_jsonFilePath, json);
+ private readonly string _jsonFilePath = Path.Combine(Environment.CurrentDirectory, "wwwroot", "fake_data_quiz.json");
+
+
+ ///
+ /// Asynchronously saves a list of quiz objects to a JSON file.
+ ///
+ /// A list of objects to be serialized and saved.
+ /// A task representing the asynchronous operation.
+ ///
+ /// This method serializes the list of quizzes to a well-formatted JSON string and saves it
+ /// to a specified file path. The list is serialized using
+ /// with indented formatting to make the JSON human-readable.
+ ///
+ public async Task saveQuizJson(List quizzes)
+ {
+ var json = JsonSerializer.Serialize(quizzes, new JsonSerializerOptions { WriteIndented = true });
+ await File.WriteAllTextAsync(_jsonFilePath, json);
}
+
+ ///
+ /// Asynchronously adds a new quiz to the list of quizzes and saves the updated list to a JSON file.
+ ///
+ /// The object to be added to the list of quizzes.
+ /// A task representing the asynchronous operation.
+ ///
+ /// This method retrieves the current list of quizzes using , 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 . The new quiz will have an ID
+ /// that's one greater than the highest existing ID or 1 if no quizzes exist.
+ ///
public async Task addQuiz(Quiz quiz)
{
var data = await getQuizzes();
@@ -21,32 +44,54 @@ public class QuizServiceStub: IQuizService
await saveQuizJson(data);
}
+ ///
+ /// Asynchronously updates an existing quiz in the list of quizzes and saves the updated list to a JSON file.
+ ///
+ /// The object containing the updated data.
+ /// A task representing the asynchronous operation.
+ ///
+ /// This method retrieves the current list of quizzes using , 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 .
+ /// If no quiz with the matching ID is found, no update is performed.
+ ///
public async Task updateQuiz(Quiz quiz)
{
- var data = await getQuizzes();
- var existingQuiz = data.FirstOrDefault(q => q.Id == quiz.Id);
- if (existingQuiz != null)
- {
- existingQuiz.Question = quiz.Question;
- existingQuiz.AnswerA = quiz.AnswerA;
- existingQuiz.AnswerB = quiz.AnswerB;
- existingQuiz.AnswerC = quiz.AnswerC;
- existingQuiz.AnswerD = quiz.AnswerD;
- existingQuiz.CAnswer = quiz.CAnswer;
- existingQuiz.IsValid = quiz.IsValid;
- existingQuiz.UserProposition = quiz.UserProposition;
- await saveQuizJson(data);
+ var data = await getQuizzes();
+ var existingQuiz = data.FirstOrDefault(q => q.Id == quiz.Id);
+ if (existingQuiz != null)
+ {
+ existingQuiz.Question = quiz.Question;
+ existingQuiz.AnswerA = quiz.AnswerA;
+ existingQuiz.AnswerB = quiz.AnswerB;
+ existingQuiz.AnswerC = quiz.AnswerC;
+ existingQuiz.AnswerD = quiz.AnswerD;
+ existingQuiz.CAnswer = quiz.CAnswer;
+ existingQuiz.IsValid = quiz.IsValid;
+ existingQuiz.UserProposition = quiz.UserProposition;
+ await saveQuizJson(data);
}
}
+ ///
+ /// Asynchronously removes a quiz from the list of quizzes by its ID and saves the updated list to a JSON file.
+ ///
+ /// The ID of the to be removed.
+ /// A task representing the asynchronous operation.
+ ///
+ /// This method retrieves the current list of quizzes using , 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 . If no quiz with the matching ID is found,
+ /// no changes are made.
+ ///
public async Task removeQuiz(int id)
{
- var data = await getQuizzes();
- var quiz = data.FirstOrDefault(q => q.Id == id);
- if (quiz != null)
- {
- data.Remove(quiz);
- await saveQuizJson(data);
+ var data = await getQuizzes();
+ var quiz = data.FirstOrDefault(q => q.Id == id);
+ if (quiz != null)
+ {
+ data.Remove(quiz);
+ await saveQuizJson(data);
}
}
@@ -55,27 +100,56 @@ public class QuizServiceStub: IQuizService
throw new NotImplementedException();
}
+ ///
+ /// Asynchronously retrieves the list of quizzes from a JSON file.
+ ///
+ /// A task representing the asynchronous operation, with a result containing the quizzes.
+ ///
+ /// 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 objects, and returns the list. If the deserialization is
+ /// unsuccessful or the file is empty, it returns an empty list instead.
+ ///
public async Task> getQuizzes()
{
- if (!File.Exists(_jsonFilePath))
- {
- Console.Out.WriteLine($"{_jsonFilePath} not found");
- return new List();
- }
-
- var json = await File.ReadAllTextAsync(_jsonFilePath);
+ if (!File.Exists(_jsonFilePath))
+ {
+ Console.Out.WriteLine($"{_jsonFilePath} not found");
+ return new List();
+ }
+
+ var json = await File.ReadAllTextAsync(_jsonFilePath);
return JsonSerializer.Deserialize>(json) ?? new List();
}
+ ///
+ /// Asynchronously retrieves the list of quizzes that are marked as invalid and need validation.
+ ///
+ /// A task representing the asynchronous operation, with a result containing quizzes that are not valid.
+ ///
+ /// This method retrieves the full list of quizzes using and filters it to return only those
+ /// quizzes where the property is set to false. The filtered list is then returned.
+ /// If no quizzes are invalid, an empty list will be returned.
+ ///
public async Task> getQuizzesToValidate()
{
- var quizzes = await getQuizzes();
+ var quizzes = await getQuizzes();
return quizzes.Where(quiz => quiz.IsValid == false).ToList();
}
+
+ ///
+ /// Asynchronously retrieves a specific quiz by its ID from the list of quizzes.
+ ///
+ /// The ID of the to retrieve.
+ /// A task representing the asynchronous operation, with a result containing the matching quiz, or null if not found.
+ ///
+ /// This method retrieves the full list of quizzes using 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 null.
+ ///
public async Task getQuiz(int id)
{
- var data = await getQuizzes();
+ var data = await getQuizzes();
var q = data.FirstOrDefault(p => p.Id == id);
if (q != null)
{
@@ -84,23 +158,45 @@ public class QuizServiceStub: IQuizService
return null;
}
+ ///
+ /// Asynchronously retrieves a paginated list of quizzes, returning a specific number of quizzes for the given page.
+ ///
+ /// The number of quizzes to retrieve per page.
+ /// The page number to retrieve, where the first page is 1.
+ /// A task representing the asynchronous operation, with a result containing the quizzes for the specified page.
+ ///
+ /// This method retrieves the full list of quizzes using 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.
+ ///
public async Task> 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);
}
+
+ ///
+ /// Asynchronously retrieves the total number of quizzes in the list.
+ ///
+ /// A task representing the asynchronous operation, with an result containing the total number of quizzes.
+ ///
+ /// This method retrieves the full list of quizzes using and returns the count of quizzes in the list.
+ /// It simply returns the number of quizzes available in the data source.
+ ///
public async Task getNbQuiz()
{
var data = await getQuizzes();
return data.Count;
- }
+ }
+
}
diff --git a/WF-WebAdmin/WF-WebAdmin/Service/QuoteServiceLocal.cs b/WF-WebAdmin/WF-WebAdmin/Service/QuoteServiceLocal.cs
index 4417c5b..4271681 100644
--- a/WF-WebAdmin/WF-WebAdmin/Service/QuoteServiceLocal.cs
+++ b/WF-WebAdmin/WF-WebAdmin/Service/QuoteServiceLocal.cs
@@ -10,7 +10,17 @@ namespace WF_WebAdmin.Service
-
+ ///
+ /// Asynchronously adds a new quote to the database and returns the corresponding .
+ ///
+ /// The object to be added to the database.
+ /// A task representing the asynchronous operation, with a result containing the added quote's data.
+ ///
+ /// This method converts the provided object into a using .
+ /// 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 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.
+ ///
public async Task AddQuoteAsync(Quote quote)
{
QuoteExtension extension = new QuoteExtension();
@@ -64,35 +74,72 @@ namespace WF_WebAdmin.Service
}
- public Task RemoveQuote(Quote quote)
+ ///
+ /// Asynchronously handles the removal of a quote and returns the corresponding .
+ ///
+ /// The object to be removed.
+ /// A task representing the asynchronous operation, with a result corresponding to the removed quote.
+ ///
+ /// This method takes a object, converts it into a using the
+ /// , 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.
+ ///
+ 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);
}
+
+ ///
+ /// Asynchronously validates a quote and returns the corresponding .
+ ///
+ /// The object to be validated.
+ /// A task representing the asynchronous operation, with a result corresponding to the validated quote.
+ ///
+ /// This method takes a object, converts it into a using the
+ /// , 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.
+ ///
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);
}
+
+ ///
+ /// Asynchronously updates a quote and returns the corresponding .
+ ///
+ /// The object to be updated.
+ /// A task representing the asynchronous operation, with a result corresponding to the updated quote.
+ ///
+ /// This method takes a object, converts it into a using the
+ /// , 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.
+ ///
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();
diff --git a/WF-WebAdmin/WF-WebAdmin/Service/QuoteServiceStub.cs b/WF-WebAdmin/WF-WebAdmin/Service/QuoteServiceStub.cs
index fcf6102..f4978b5 100644
--- a/WF-WebAdmin/WF-WebAdmin/Service/QuoteServiceStub.cs
+++ b/WF-WebAdmin/WF-WebAdmin/Service/QuoteServiceStub.cs
@@ -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");
+
+ ///
+ /// Asynchronously saves a list of quotes to a JSON file.
+ ///
+ /// The list of objects to be serialized and saved to the file.
+ /// A task representing the asynchronous operation of saving the quotes to the file.
+ ///
+ /// This method serializes the provided list of objects into JSON format using .
+ /// The serialized JSON is then saved to the file path specified in the field. The JSON is written
+ /// with indentation for better readability.
+ /// If the file does not already exist, it will be created.
+ ///
public async Task saveQuoteJson(List 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);
+ }
+
+
+ ///
+ /// Asynchronously adds a new quote to the list and saves it to a JSON file.
+ ///
+ /// The object to be added to the list.
+ /// A task representing the asynchronous operation of adding the quote and saving the updated list to the file.
+ ///
+ /// This method retrieves the current list of quotes using the 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 .
+ /// If the list is empty, the new quote is assigned an ID of 1.
+ ///
+ 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)
+
+ ///
+ /// Asynchronously removes a quote from the list and saves the updated list to a JSON file.
+ ///
+ /// The object to be removed from the list.
+ /// A task representing the asynchronous operation of removing the quote and saving the updated list to the file.
+ ///
+ /// This method retrieves the current list of quotes using the 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 .
+ /// If the quote is not found in the list, no action is taken.
+ ///
+ 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 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)
+ public async Task validQuote(Quote quote)
+ {
+ throw new NotImplementedException();
+ }
+
+
+ ///
+ /// Asynchronously updates the details of an existing quote and saves the updated list to a JSON file.
+ ///
+ /// The object containing the updated details of the quote.
+ /// A task representing the asynchronous operation of updating the quote and saving the updated list to the file.
+ ///
+ /// This method retrieves the current list of quotes using the 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 . If the quote with the specified `Id` is not found, no action is taken.
+ ///
+ 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)
+ ///
+ /// Asynchronously retrieves all quotes from a JSON file.
+ ///
+ /// A task representing the asynchronous operation, with a result of a list of objects.
+ ///
+ /// This method checks if the JSON file exists at the specified file path ().
+ /// 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 objects,
+ /// and returns that list. If the deserialization results in a null value, an empty list is returned.
+ ///
+ public async Task> 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();
}
- public async Task> getAllQuote()
- {
- if (!File.Exists(_jsonFilePath))
- {
- Console.Out.WriteLine($"{_jsonFilePath} not found");
- return new List();
- }
+ var json = await File.ReadAllTextAsync(_jsonFilePath);
+ return JsonSerializer.Deserialize>(json) ?? new List();
+ }
- var json = await File.ReadAllTextAsync(_jsonFilePath);
- return JsonSerializer.Deserialize>(json) ?? new List();
- }
- public async Task> getSomeQuote(int nb, int page)
+ ///
+ /// Asynchronously retrieves a subset of quotes based on the specified page number and the number of quotes per page.
+ ///
+ /// The number of quotes to retrieve per page.
+ /// The page number for pagination.
+ /// A task representing the asynchronous operation, with a result of a list of objects for the specified page.
+ ///
+ /// This method retrieves all quotes using the 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.
+ ///
+ public async Task> 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 getOnequote(int id)
+ ///
+ /// Asynchronously retrieves a single quote based on its ID.
+ ///
+ /// The unique identifier of the to be retrieved.
+ /// A task representing the asynchronous operation, with a result of the object if found, otherwise null.
+ ///
+ /// This method retrieves all quotes using the 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`.
+ ///
+ public async Task 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> reserchQuote(string reserch, List argument)
+ public async Task> reserchQuote(string reserch, List argument)
{
throw new NotImplementedException();
}
- public async Task> getAllQuoteInvalid()
- {
- var quotes = await getAllQuote();
- quotes = quotes.Where(q => q.IsValid == false).ToList();
- return quotes;
- }
- public async Task> getSomeQuoteInvalid(int nb, int page)
+ ///
+ /// Asynchronously retrieves all invalid quotes from the list.
+ ///
+ /// A task representing the asynchronous operation, with a result of a list of invalid objects.
+ ///
+ /// This method retrieves all quotes using the 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.
+ ///
+ public async Task> getAllQuoteInvalid()
+ {
+ var quotes = await getAllQuote();
+ quotes = quotes.Where(q => q.IsValid == false).ToList();
+ return quotes;
+ }
+
+
+ ///
+ /// Asynchronously retrieves a subset of invalid quotes based on the specified page number and the number of quotes per page.
+ ///
+ /// The number of invalid quotes to retrieve per page.
+ /// The page number for pagination.
+ /// A task representing the asynchronous operation, with a result of a list of invalid objects for the specified page.
+ ///
+ /// This method retrieves all invalid quotes using the 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.
+ ///
+ public async Task> 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);
+ }
+
- public async Task getNbQuote()
+ ///
+ /// Asynchronously retrieves the total number of quotes.
+ ///
+ /// A task representing the asynchronous operation, with a result of the total number of objects.
+ ///
+ /// This method retrieves all quotes using the method and returns the count of quotes.
+ /// It provides the total number of quotes currently available in the data source.
+ ///
+ public async Task getNbQuote()
+ {
+ var data = await getAllQuote();
+ return data.Count;
+ }
+
+
+ ///
+ /// Asynchronously retrieves a list of characters from a JSON file.
+ ///
+ /// A task representing the asynchronous operation, with a result of a list of objects.
+ ///
+ /// 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 objects,
+ /// and returns that list. If the deserialization results in a null value, an empty list is returned.
+ ///
+ public async Task> getChar()
+ {
+ if (!File.Exists(_char))
{
- var data = await getAllQuote();
- return data.Count;
+ Console.Out.WriteLine($"{_char} not found");
+ return new List();
}
- public async Task> getChar()
- {
- if (!File.Exists(_char))
- {
- Console.Out.WriteLine($"{_char} not found");
- return new List();
- }
+ var json = await File.ReadAllTextAsync(_char);
+ return JsonSerializer.Deserialize>(json) ?? new List();
+ }
- var json = await File.ReadAllTextAsync(_char);
- return JsonSerializer.Deserialize>(json) ?? new List();
- }
- public async Task> getSrc()
+ ///
+ /// Asynchronously retrieves a list of sources from a JSON file.
+ ///
+ /// A task representing the asynchronous operation, with a result of a list of objects.
+ ///
+ /// 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 objects,
+ /// and returns that list. If the deserialization results in a null value, an empty list is returned.
+ ///
+ public async Task> getSrc()
+ {
+ if (!File.Exists(_src))
{
- if (!File.Exists(_src))
- {
- Console.Out.WriteLine($"{_src} not found");
- return new List();
- }
-
- var json = await File.ReadAllTextAsync(_src);
- return JsonSerializer.Deserialize>(json) ?? new List();
+ Console.Out.WriteLine($"{_src} not found");
+ return new List();
}
-}
-
\ No newline at end of file
+
+ var json = await File.ReadAllTextAsync(_src);
+ return JsonSerializer.Deserialize>(json) ?? new List();
+ }
+
+}
diff --git a/WF-WebAdmin/WF-WebAdmin/Service/UserServiceStub.cs b/WF-WebAdmin/WF-WebAdmin/Service/UserServiceStub.cs
index 67cb03f..53770a3 100644
--- a/WF-WebAdmin/WF-WebAdmin/Service/UserServiceStub.cs
+++ b/WF-WebAdmin/WF-WebAdmin/Service/UserServiceStub.cs
@@ -8,12 +8,32 @@ public class UserServiceStub : IUserService
private readonly string _jsonFilePath = Path.Combine(Environment.CurrentDirectory, "wwwroot", "fake_data_users.json");
+ ///
+ /// Asynchronously saves a list of users to a JSON file.
+ ///
+ /// The list of objects to be saved to the file.
+ /// A task representing the asynchronous operation.
+ ///
+ /// This method serializes the provided list of 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.
+ ///
public async Task saveUsersJson(List users)
{
var json = JsonSerializer.Serialize(users, new JsonSerializerOptions { WriteIndented = true });
await File.WriteAllTextAsync(_jsonFilePath, json);
}
+
+ ///
+ /// Asynchronously removes a user from the list of users and saves the updated list to a JSON file.
+ ///
+ /// The object to be removed from the list.
+ /// A task representing the asynchronous operation.
+ ///
+ /// This method retrieves the list of all users using the 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 method.
+ ///
public async Task removeUser(User user)
{
var data = await getAllUser();
@@ -25,18 +45,49 @@ public class UserServiceStub : IUserService
}
}
+
+ ///
+ /// Asynchronously updates the role of a user, setting the user as an administrator.
+ ///
+ /// The object whose role is to be updated.
+ /// A task representing the asynchronous operation of updating the user's role.
+ ///
+ /// This method updates the `IsAdmin` property of the specified user to `true`, indicating that the user is an administrator.
+ /// It then calls the method to persist the updated user information.
+ ///
public Task updateRole(User user)
{
user.IsAdmin = true;
return updateUser(user);
}
+
+ ///
+ /// Asynchronously downgrades the role of a user, removing their administrator privileges.
+ ///
+ /// The object whose role is to be downgraded.
+ /// A task representing the asynchronous operation of downgrading the user's role.
+ ///
+ /// This method updates the `IsAdmin` property of the specified user to `false`, removing their administrator status.
+ /// It then calls the method to persist the updated user information.
+ ///
public Task downgradeRole(User user)
{
user.IsAdmin = false;
return updateUser(user);
}
+
+ ///
+ /// Asynchronously retrieves a list of all users from a JSON file.
+ ///
+ /// A task representing the asynchronous operation, with a result of a list of objects.
+ ///
+ /// 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 objects,
+ /// and returns that list. If the deserialization results in a null value, an empty list is returned.
+ ///
public async Task> getAllUser()
{
if (!File.Exists(_jsonFilePath))
@@ -49,6 +100,19 @@ public class UserServiceStub : IUserService
return JsonSerializer.Deserialize>(json) ?? new List();
}
+
+ ///
+ /// Asynchronously retrieves a paginated list of users from a JSON file.
+ ///
+ /// The number of users to retrieve per page.
+ /// The page number for the data to retrieve.
+ /// A task representing the asynchronous operation, with a result of a list of objects.
+ ///
+ /// This method retrieves all users using the 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.
+ ///
public async Task> getSomeUser(int nb, int page)
{
var users = await getAllUser();
@@ -59,6 +123,17 @@ public class UserServiceStub : IUserService
return users.GetRange((page - 1) * nb, nb);
}
+
+ ///
+ /// Asynchronously retrieves a single user by their ID from the JSON file.
+ ///
+ /// The ID of the user to retrieve.
+ /// A task representing the asynchronous operation, with a result of the object if found, otherwise null.
+ ///
+ /// This method retrieves all users using the 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.
+ ///
public async Task getOneUser(int id)
{
var data = await getAllUser();
@@ -70,28 +145,47 @@ public class UserServiceStub : IUserService
return null;
}
+
public Task> reserchUsers(string reserch, List args)
{
throw new NotImplementedException();
}
+ ///
+ /// Asynchronously retrieves the total number of users from the JSON file.
+ ///
+ /// A task representing the asynchronous operation, with a result of the total number of users.
+ ///
+ /// This method retrieves all users using the method and returns the count of users in the list.
+ ///
public async Task getNbUser()
{
var data = await getAllUser();
return data.Count;
}
+
+ ///
+ /// Asynchronously updates the details of a user in the JSON file.
+ ///
+ /// The object containing the updated user details.
+ /// A task representing the asynchronous operation of updating the user.
+ ///
+ /// This method retrieves all users using the 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 method.
+ ///
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);
+ }
}
}
\ No newline at end of file
diff --git a/WF-WebAdmin/WF-WebAdmin/Shared/CultureSelector.razor b/WF-WebAdmin/WF-WebAdmin/Shared/CultureSelector.razor
index 44d3c10..7a48e2b 100644
--- a/WF-WebAdmin/WF-WebAdmin/Shared/CultureSelector.razor
+++ b/WF-WebAdmin/WF-WebAdmin/Shared/CultureSelector.razor
@@ -21,6 +21,16 @@
new CultureInfo("fr-FR")
};
+ ///
+ /// Gets or sets the current culture for the application, triggering a navigation to set the culture cookie when changed.
+ ///
+ ///
+ /// The getter retrieves the current culture of the application using .
+ /// 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.
+ ///
private CultureInfo Culture
{
get => CultureInfo.CurrentCulture;
@@ -40,4 +50,5 @@
this.NavigationManager.NavigateTo("/Culture/SetCulture" + query, forceLoad: true);
}
}
+
}
\ No newline at end of file
diff --git a/WF-WebAdmin/WF-WebAdmin/Shared/MainLayout.razor b/WF-WebAdmin/WF-WebAdmin/Shared/MainLayout.razor
index e129354..db2f3e3 100644
--- a/WF-WebAdmin/WF-WebAdmin/Shared/MainLayout.razor
+++ b/WF-WebAdmin/WF-WebAdmin/Shared/MainLayout.razor
@@ -5,9 +5,9 @@
WF-WebAdmin
-