From 47d874f7179be1c0ef70264baa59764fc9184ce0 Mon Sep 17 00:00:00 2001 From: Alex Berezhnykh Date: Mon, 14 Nov 2022 05:37:19 +0300 Subject: [PATCH 01/14] wip --- .../Controllers/AccountController.cs | 219 +++-- .../Controllers/AggregationController.cs | 57 +- .../Controllers/CourseGroupsController.cs | 163 ++-- .../Controllers/CoursesController.cs | 241 +++--- .../Controllers/HomeworksController.cs | 81 +- .../Controllers/NotificationsController.cs | 61 +- .../Controllers/SolutionsController.cs | 285 ++++--- .../Controllers/StatisticsController.cs | 55 +- .../Controllers/SystemController.cs | 99 ++- .../Controllers/TasksController.cs | 83 +- .../ForbiddenExceptionFilter.cs | 15 +- .../HwProj.APIGateway.API.csproj | 7 +- .../Models/CoursePreviewView.cs | 19 +- .../Models/Solutions/SolutionPreviewView.cs | 35 +- .../Models/Solutions/UserTaskSolutions.cs | 13 +- .../Models/StatisticsCourseMatesModel.cs | 17 +- .../Models/SystemInfo.cs | 13 +- .../Models/Tasks/TaskDeadlineView.cs | 17 +- .../Models/UserDataDto.cs | 15 +- .../HwProj.APIGateway.API/Program.cs | 27 +- .../HwProj.APIGateway.API/Startup.cs | 75 +- .../HwProj.AuthService.API/AppSettings.cs | 19 +- .../ApplicationProfile.cs | 19 +- .../Controllers/AccountController.cs | 255 +++--- .../Controllers/SystemController.cs | 17 +- .../Events/AdminRegisterEvent.cs | 13 +- .../Events/InviteLecturerEvent.cs | 13 +- .../Events/RegisterEvent.cs | 33 +- .../Events/StudentRegisterEvent.cs | 13 +- .../Extensions/IdentityResultExtensions.cs | 47 +- .../HwProj.AuthService.API.csproj | 10 +- .../Models/IdentityContext.cs | 15 +- .../Models/IdentityResults.cs | 31 +- .../HwProj.AuthService.API/Program.cs | 21 +- .../HwProj.AuthService.API/RoleInitializer.cs | 59 +- .../Services/AccountService.cs | 333 ++++---- .../Services/AuthTokenService.cs | 69 +- .../Services/IAccountService.cs | 23 +- .../Services/IAuthTokenService.cs | 11 +- .../Services/IUserManager.cs | 33 +- .../Services/ProxyUserManager.cs | 113 ++- .../HwProj.AuthService.API/Startup.cs | 143 ++-- .../AuthServiceClient.cs | 303 ++++--- .../ConfigurationExtensions.cs | 15 +- .../HwProj.AuthService.Client.csproj | 9 +- .../IAuthServiceClient.cs | 33 +- .../AuthServiceTests.cs | 771 +++++++++--------- ...HwProj.AuthService.IntegrationTests.csproj | 3 +- .../HwProj.Exceptions/ForbiddenException.cs | 19 +- .../HwProj.Exceptions.csproj | 4 +- .../HwProj.HttpUtils/HwProj.HttpUtils.csproj | 4 +- .../HwProjJsonSerializerSettings.cs | 29 +- .../HwProj.HttpUtils/JsonConvertExtensions.cs | 13 +- .../HwProj.HttpUtils/RequestHeaderBuilder.cs | 11 +- .../HwProj.HttpUtils/RequestUrlBuilder.cs | 65 +- .../AuthService/DTO/AccountDataDTO.cs | 45 +- .../AuthService/DTO/EditDataDTO.cs | 19 +- .../AuthService/DTO/RegisterDataDTO.cs | 23 +- .../AuthService/DTO/TokenCredentials.cs | 11 +- .../ViewModels/ChangeEmailViewModel.cs | 15 +- .../AuthService/ViewModels/DeleteViewModel.cs | 15 +- .../ViewModels/EditAccountViewModel.cs | 33 +- .../ViewModels/EditExternalViewModel.cs | 19 +- .../ViewModels/InviteLecturerViewModel.cs | 15 +- .../AuthService/ViewModels/LoginViewModel.cs | 23 +- .../ViewModels/RegisterViewModel.cs | 42 +- .../AuthService/ViewModels/User.cs | 23 +- .../CoursesService/DTO/TaslDeadlineDTO.cs | 21 +- .../DTO/UserGroupDescription.cs | 19 +- .../ViewModels/CourseMateViewModel.cs | 13 +- .../ViewModels/CourseViewModels.cs | 111 ++- .../ViewModels/GroupMateViewModel.cs | 11 +- .../ViewModels/GroupViewModel.cs | 55 +- .../ViewModels/HomeworkTaskViewModels.cs | 67 +- .../ViewModels/HomeworkViewModels.cs | 37 +- HwProj.Common/HwProj.Models/DateTimeUtils.cs | 11 +- .../HwProj.Models/HwProj.Models.csproj | 9 +- .../CategorizedNotifications.cs | 15 +- .../NotificationsService/Notification.cs | 27 +- .../NotificationCategoryState.cs | 15 +- .../NotificationFilter.cs | 21 +- .../NotificationViewModel.cs | 23 +- HwProj.Common/HwProj.Models/Result/Result.cs | 87 +- HwProj.Common/HwProj.Models/Roles/Roles.cs | 17 +- .../SolutionsService/Solution.cs | 31 +- .../SolutionsService/SolutionPreviewDTO.cs | 17 +- .../SolutionsService/SolutionState.cs | 11 +- .../SolutionsService/SolutionViewModel.cs | 23 +- .../StatisticsCourseHomeworksModel.cs | 13 +- .../StatisticsCourseMatesDTO.cs | 13 +- .../StatisticsCourseSolutionsModel.cs | 29 +- .../StatisticsCourseTasksModel.cs | 13 +- .../HwProj.Repositories/CrudRepository.cs | 57 +- .../HwProj.Repositories.csproj | 9 +- .../HwProj.Repositories/ICrudRepository.cs | 17 +- HwProj.Common/HwProj.Repositories/IEntity.cs | 13 +- .../IReadOnlyRepository.cs | 21 +- .../HwProj.Repositories/ReadOnlyRepository.cs | 53 +- .../Authorization/AuthExtensions.cs | 57 +- .../Authorization/AuthorizationKey.cs | 13 +- .../Configuration/ConnectionString.cs | 19 +- .../Middleware/NoApiGatewayMiddleware.cs | 29 +- .../Configuration/StartupExtensions.cs | 217 +++-- .../HwProj.Utils/HwProj.Utils.csproj | 31 +- .../HwProj.CourseWorkService.API.csproj | 6 +- .../ApplicationProfile.cs | 85 +- .../Controllers/CourseGroupsController.cs | 151 ++-- .../Controllers/CoursesController.cs | 299 ++++--- .../Controllers/HomeworksController.cs | 89 +- .../Controllers/SystemController.cs | 17 +- .../Controllers/TasksController.cs | 105 ++- .../Events/LecturerAcceptToCourseEvent.cs | 17 +- .../Events/LecturerInvitedToCourseEvent.cs | 17 +- .../Events/LecturerRejectToCourseEvent.cs | 17 +- .../Events/NewCourseMateEvent.cs | 17 +- .../Events/NewHomeworkEvent.cs | 21 +- .../Events/NewHomeworkTaskEvent.cs | 29 +- .../Events/UpdateHomeworkEvent.cs | 21 +- .../Events/UpdateSolutionMaxRatingEvent.cs | 25 +- .../Events/UpdateTaskMaxRatingEvent.cs | 25 +- .../Filters/CourseMentorOnlyAttribute.cs | 37 +- .../HwProj.CoursesService.API.csproj | 13 +- .../Models/Course.cs | 29 +- .../Models/CourseContext.cs | 39 +- .../Models/CourseMate.cs | 19 +- .../HwProj.CoursesService.API/Models/Group.cs | 21 +- .../Models/GroupMate.cs | 17 +- .../Models/Homework.cs | 21 +- .../Models/HomeworkTask.cs | 29 +- .../Models/TaskModel.cs | 17 +- .../HwProj.CoursesService.API/Program.cs | 21 +- .../Repositories/CourseMatesRepository.cs | 11 +- .../Repositories/CoursesRepository.cs | 47 +- .../Groups/GroupMatesRepository.cs | 13 +- .../Repositories/Groups/GroupsRepository.cs | 49 +- .../Groups/IGroupMatesRepository.cs | 9 +- .../Repositories/Groups/IGroupsRepository.cs | 13 +- .../Groups/ITaskModelsRepository.cs | 9 +- .../Groups/TaskModelsRepository.cs | 13 +- .../Repositories/HomeworksRepository.cs | 43 +- .../Repositories/ICourseMatesRepository.cs | 7 +- .../Repositories/ICoursesRepository.cs | 13 +- .../Repositories/IHomeworksRepository.cs | 15 +- .../Repositories/ITasksRepository.cs | 9 +- .../Repositories/TasksRepository.cs | 13 +- .../Services/CoursesService.cs | 379 +++++---- .../Services/GroupsService.cs | 185 +++-- .../Services/HomeworksService.cs | 87 +- .../Services/ICoursesService.cs | 33 +- .../Services/IGroupsService.cs | 27 +- .../Services/IHomeworksService.cs | 17 +- .../Services/ITasksService.cs | 17 +- .../Services/TasksService.cs | 109 ++- .../HwProj.CoursesService.API/Startup.cs | 77 +- .../ConfigurationExtensions.cs | 15 +- .../CoursesServiceClient.cs | 663 ++++++++------- .../HwProj.CoursesService.Client.csproj | 7 +- .../ICoursesServiceClient.cs | 69 +- .../CoursesServiceTests.cs | 15 +- .../GroupsServiceTests.cs | 523 ++++++------ .../HwProj.CoursesService.Tests.csproj | 6 +- .../HwProj.EventBus.Client/Event.cs | 35 +- .../HwProj.EventBus.Client.csproj | 13 +- .../Implementations/DefaultConnection.cs | 95 ++- .../Implementations/EventBusRabbitMQ.cs | 220 +++-- .../Implementations/EventBusSubscriber.cs | 33 +- .../Interfaces/IDefaultConnection.cs | 15 +- .../Interfaces/IEventBus.cs | 25 +- .../Interfaces/IEventHandler.cs | 23 +- .../HwProj.EventBus.Tests.csproj | 3 +- .../HwProj.EventBus.Tests/OtherTestHandler.cs | 35 +- .../HwProj.EventBus.Tests/TestEvent.cs | 21 +- .../HwProj.EventBus.Tests/TestEventBus.cs | 31 +- .../HwProj.EventBus.Tests/TestHandler.cs | 25 +- .../AutomapperProfile.cs | 11 +- .../Controllers/NotificationsController.cs | 67 +- .../Controllers/SystemController.cs | 17 +- .../InviteLecturerEventHandler.cs | 47 +- .../LecturerAcceptToCourseEventHandler.cs | 67 +- .../LecturerInvitedToCourseEventHandler.cs | 59 +- .../LecturerRejectToCourseEventHandler.cs | 67 +- .../EventHandlers/NewCourseMateHandler.cs | 87 +- .../EventHandlers/NewHomeworkEventHandler.cs | 75 +- .../NewHomeworkTaskEventHandler.cs | 85 +- .../EventHandlers/RateEventHandler.cs | 69 +- .../EventHandlers/RegisterEventHandler.cs | 49 +- .../StudentPassTaskEventHandler.cs | 75 +- .../UpdateHomeworkEventHandler.cs | 71 +- .../HwProj.NotificationsService.API.csproj | 11 +- .../Models/NotificationsContext.cs | 17 +- .../Program.cs | 21 +- .../Repositories/INotificationsRepository.cs | 15 +- .../Repositories/NotificationsRepository.cs | 47 +- .../Services/EmailService.cs | 73 +- .../Services/IEmailService.cs | 9 +- .../Services/NotificationsDomain.cs | 39 +- .../Startup.cs | 99 ++- .../ConfigurationExtensions.cs | 15 +- .../HwProj.NotificationsService.Client.csproj | 5 +- .../INotificationsServiceClient.cs | 17 +- .../NotificationsServiceClient.cs | 79 +- .../HwProj.NotificationsService.Tests.csproj | 10 +- .../NotificationsServiceTests.cs | 15 +- .../AutomapperProfile.cs | 13 +- .../Controllers/SolutionsController.cs | 291 ++++--- .../Controllers/SystemController.cs | 17 +- .../Domains/SolutionsStatsDomain.cs | 57 +- .../Events/RateEvent.cs | 21 +- .../Events/StudentPassTaskEvent.cs | 29 +- .../HwProj.SolutionsService.API.csproj | 11 +- .../Models/SolutionsContext.cs | 19 +- .../Models/StatisticsAggregateModel.cs | 15 +- .../HwProj.SolutionsService.API/Program.cs | 21 +- .../Repositories/ISolutionsRepository.cs | 15 +- .../Repositories/SolutionsRepository.cs | 87 +- .../Services/ISolutionsService.cs | 27 +- .../Services/SolutionsService.cs | 183 +++-- .../HwProj.SolutionsService.API/Startup.cs | 49 +- .../ConfigurationExtensions.cs | 15 +- .../HwProj.SolutionsService.Client.csproj | 6 +- .../ISolutionsServiceClient.cs | 37 +- .../SolutionsServiceClient.cs | 289 ++++--- ...j.SolutionsService.IntegrationTests.csproj | 2 +- .../SolutionsServiceTests.cs | 611 +++++++------- HwProj.sln | 9 - 225 files changed, 6419 insertions(+), 6688 deletions(-) diff --git a/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/AccountController.cs b/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/AccountController.cs index 7886595ab..48f18993e 100644 --- a/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/AccountController.cs +++ b/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/AccountController.cs @@ -14,135 +14,134 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; -namespace HwProj.APIGateway.API.Controllers -{ - [Route("api/[controller]")] - [ApiController] - public class AccountController : AggregationController - { - private readonly ICoursesServiceClient _coursesClient; - private readonly ISolutionsServiceClient _solutionsServiceClient; +namespace HwProj.APIGateway.API.Controllers; - public AccountController( - IAuthServiceClient authClient, - ICoursesServiceClient coursesClient, - ISolutionsServiceClient solutionsServiceClient) : base(authClient) - { - _coursesClient = coursesClient; - _solutionsServiceClient = solutionsServiceClient; - } +[Route("api/[controller]")] +[ApiController] +public class AccountController : AggregationController +{ + private readonly ICoursesServiceClient _coursesClient; + private readonly ISolutionsServiceClient _solutionsServiceClient; - [HttpGet("getUserData/{userId}")] - [ProducesResponseType(typeof(AccountDataDto), (int)HttpStatusCode.OK)] - public async Task GetUserDataById(string userId) - { - var result = await AuthServiceClient.GetAccountData(userId); - return result == null - ? NotFound() as IActionResult - : Ok(result); - } + public AccountController( + IAuthServiceClient authClient, + ICoursesServiceClient coursesClient, + ISolutionsServiceClient solutionsServiceClient) : base(authClient) + { + _coursesClient = coursesClient; + _solutionsServiceClient = solutionsServiceClient; + } - //TODO: separate for mentor and student - [HttpGet("getUserData")] - [Authorize] - [ProducesResponseType(typeof(UserDataDto), (int)HttpStatusCode.OK)] - public async Task GetUserData() - { - var getAccountDataTask = AuthServiceClient.GetAccountData(UserId); - var getCoursesTask = _coursesClient.GetAllUserCourses(); + [HttpGet("getUserData/{userId}")] + [ProducesResponseType(typeof(AccountDataDto), (int)HttpStatusCode.OK)] + public async Task GetUserDataById(string userId) + { + var result = await AuthServiceClient.GetAccountData(userId); + return result == null + ? NotFound() + : Ok(result); + } - await Task.WhenAll(getAccountDataTask, getCoursesTask); + //TODO: separate for mentor and student + [HttpGet("getUserData")] + [Authorize] + [ProducesResponseType(typeof(UserDataDto), (int)HttpStatusCode.OK)] + public async Task GetUserData() + { + var getAccountDataTask = AuthServiceClient.GetAccountData(UserId); + var getCoursesTask = _coursesClient.GetAllUserCourses(); - var courses = GetCoursePreviews(getCoursesTask.Result); + await Task.WhenAll(getAccountDataTask, getCoursesTask); - if (User.IsInRole(Roles.LecturerRole)) - { - return Ok(new UserDataDto - { - UserData = getAccountDataTask.Result, - Courses = await courses, - TaskDeadlines = Array.Empty() - }); - } - - var taskDeadlines = await _coursesClient.GetTaskDeadlines(); - var taskIds = taskDeadlines.Select(t => t.TaskId).ToArray(); - var solutions = await _solutionsServiceClient.GetLastTaskSolutions(taskIds, UserId); - var taskDeadlinesInfo = taskDeadlines.Select((d, i) => new TaskDeadlineView - { - Deadline = d, - SolutionState = solutions[i]?.State, - Rating = solutions[i]?.Rating, - MaxRating = taskDeadlines[i].MaxRating - }).ToArray(); + var courses = GetCoursePreviews(getCoursesTask.Result); - var aggregatedResult = new UserDataDto + if (User.IsInRole(Roles.LecturerRole)) + { + return Ok(new UserDataDto { UserData = getAccountDataTask.Result, Courses = await courses, - TaskDeadlines = taskDeadlinesInfo - }; - return Ok(aggregatedResult); + TaskDeadlines = Array.Empty() + }); } - [HttpPost("register")] - [ProducesResponseType(typeof(Result), (int)HttpStatusCode.OK)] - public async Task Register(RegisterViewModel model) + var taskDeadlines = await _coursesClient.GetTaskDeadlines(); + var taskIds = taskDeadlines.Select(t => t.TaskId).ToArray(); + var solutions = await _solutionsServiceClient.GetLastTaskSolutions(taskIds, UserId); + var taskDeadlinesInfo = taskDeadlines.Select((d, i) => new TaskDeadlineView { - var result = await AuthServiceClient.Register(model); - return Ok(result); - } + Deadline = d, + SolutionState = solutions[i]?.State, + Rating = solutions[i]?.Rating, + MaxRating = taskDeadlines[i].MaxRating + }).ToArray(); - [HttpPost("login")] - [ProducesResponseType(typeof(Result), (int)HttpStatusCode.OK)] - public async Task Login(LoginViewModel model) + var aggregatedResult = new UserDataDto { - var tokenMeta = await AuthServiceClient.Login(model).ConfigureAwait(false); - return Ok(tokenMeta); - } + UserData = getAccountDataTask.Result, + Courses = await courses, + TaskDeadlines = taskDeadlinesInfo + }; + return Ok(aggregatedResult); + } - [HttpPut("edit")] - [Authorize] - [ProducesResponseType(typeof(Result), (int)HttpStatusCode.OK)] - public async Task Edit(EditAccountViewModel model) - { - var result = await AuthServiceClient.Edit(model, UserId); - return Ok(result); - } + [HttpPost("register")] + [ProducesResponseType(typeof(Result), (int)HttpStatusCode.OK)] + public async Task Register(RegisterViewModel model) + { + var result = await AuthServiceClient.Register(model); + return Ok(result); + } - [HttpPost("inviteNewLecturer")] - [Authorize(Roles = Roles.LecturerRole)] - [ProducesResponseType(typeof(Result), (int)HttpStatusCode.OK)] - public async Task InviteNewLecturer(InviteLecturerViewModel model) - { - var result = await AuthServiceClient.InviteNewLecturer(model).ConfigureAwait(false); - return Ok(result); - } + [HttpPost("login")] + [ProducesResponseType(typeof(Result), (int)HttpStatusCode.OK)] + public async Task Login(LoginViewModel model) + { + var tokenMeta = await AuthServiceClient.Login(model).ConfigureAwait(false); + return Ok(tokenMeta); + } - [HttpPost("google")] - [ProducesResponseType(typeof(Result), (int)HttpStatusCode.OK)] - public async Task LoginByGoogle(string tokenId) - { - var tokenMeta = await AuthServiceClient.LoginByGoogle(tokenId).ConfigureAwait(false); - return Ok(tokenMeta); - } + [HttpPut("edit")] + [Authorize] + [ProducesResponseType(typeof(Result), (int)HttpStatusCode.OK)] + public async Task Edit(EditAccountViewModel model) + { + var result = await AuthServiceClient.Edit(model, UserId); + return Ok(result); + } - [HttpPut("editExternal")] - [Authorize] - [ProducesResponseType(typeof(Result), (int)HttpStatusCode.OK)] - public async Task EditExternal(EditExternalViewModel model) - { - var result = await AuthServiceClient.EditExternal(model, UserId); - return Ok(result); - } + [HttpPost("inviteNewLecturer")] + [Authorize(Roles = Roles.LecturerRole)] + [ProducesResponseType(typeof(Result), (int)HttpStatusCode.OK)] + public async Task InviteNewLecturer(InviteLecturerViewModel model) + { + var result = await AuthServiceClient.InviteNewLecturer(model).ConfigureAwait(false); + return Ok(result); + } - [HttpGet("getAllStudents")] - [Authorize(Roles = Roles.LecturerRole)] - [ProducesResponseType(typeof(AccountDataDto[]), (int)HttpStatusCode.OK)] - public async Task GetAllStudents() - { - var result = await AuthServiceClient.GetAllStudents(); - return Ok(result); - } + [HttpPost("google")] + [ProducesResponseType(typeof(Result), (int)HttpStatusCode.OK)] + public async Task LoginByGoogle(string tokenId) + { + var tokenMeta = await AuthServiceClient.LoginByGoogle(tokenId).ConfigureAwait(false); + return Ok(tokenMeta); + } + + [HttpPut("editExternal")] + [Authorize] + [ProducesResponseType(typeof(Result), (int)HttpStatusCode.OK)] + public async Task EditExternal(EditExternalViewModel model) + { + var result = await AuthServiceClient.EditExternal(model, UserId); + return Ok(result); + } + + [HttpGet("getAllStudents")] + [Authorize(Roles = Roles.LecturerRole)] + [ProducesResponseType(typeof(AccountDataDto[]), (int)HttpStatusCode.OK)] + public async Task GetAllStudents() + { + var result = await AuthServiceClient.GetAllStudents(); + return Ok(result); } } diff --git a/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/AggregationController.cs b/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/AggregationController.cs index c484313e4..105a76f03 100644 --- a/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/AggregationController.cs +++ b/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/AggregationController.cs @@ -5,39 +5,38 @@ using HwProj.Models.CoursesService.ViewModels; using Microsoft.AspNetCore.Mvc; -namespace HwProj.APIGateway.API.Controllers +namespace HwProj.APIGateway.API.Controllers; + +public class AggregationController : ControllerBase { - public class AggregationController : ControllerBase - { - protected readonly IAuthServiceClient AuthServiceClient; + protected readonly IAuthServiceClient AuthServiceClient; - protected AggregationController(IAuthServiceClient authServiceClient) - { - AuthServiceClient = authServiceClient; - } + protected AggregationController(IAuthServiceClient authServiceClient) + { + AuthServiceClient = authServiceClient; + } - protected string? UserId => - Request.HttpContext.User.Claims - .FirstOrDefault(claim => claim.Type.ToString() == "_id") - ?.Value; + protected string? UserId => + Request.HttpContext.User.Claims + .FirstOrDefault(claim => claim.Type.ToString() == "_id") + ?.Value; - protected async Task GetCoursePreviews(CoursePreview[] courses) - { - var getMentorsTasks = courses.Select(t => AuthServiceClient.GetAccountsData(t.MentorIds)).ToList(); - await Task.WhenAll(getMentorsTasks); - var mentorDTOs = getMentorsTasks.Select(t => t.Result); + protected async Task GetCoursePreviews(CoursePreview[] courses) + { + var getMentorsTasks = courses.Select(t => AuthServiceClient.GetAccountsData(t.MentorIds)).ToList(); + await Task.WhenAll(getMentorsTasks); + var mentorDTOs = getMentorsTasks.Select(t => t.Result); - var result = courses.Zip(mentorDTOs, (course, mentors) => - new CoursePreviewView - { - Id = course.Id, - Name = course.Name, - GroupName = course.GroupName, - IsCompleted = course.IsCompleted, - Mentors = mentors.Where(t => t != null).ToArray() - }).ToArray(); + var result = courses.Zip(mentorDTOs, (course, mentors) => + new CoursePreviewView + { + Id = course.Id, + Name = course.Name, + GroupName = course.GroupName, + IsCompleted = course.IsCompleted, + Mentors = mentors.Where(t => t != null).ToArray() + }).ToArray(); - return result; - } + return result; } -} +} \ No newline at end of file diff --git a/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/CourseGroupsController.cs b/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/CourseGroupsController.cs index 7e1672ee6..1aebf1161 100644 --- a/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/CourseGroupsController.cs +++ b/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/CourseGroupsController.cs @@ -6,97 +6,96 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; -namespace HwProj.APIGateway.API.Controllers +namespace HwProj.APIGateway.API.Controllers; + +[Route("api/[controller]")] +[ApiController] +public class CourseGroupsController : AggregationController { - [Route("api/[controller]")] - [ApiController] - public class CourseGroupsController : AggregationController - { - private readonly ICoursesServiceClient _coursesClient; + private readonly ICoursesServiceClient _coursesClient; - public CourseGroupsController(ICoursesServiceClient coursesClient) : base(null) - { - _coursesClient = coursesClient; - } + public CourseGroupsController(ICoursesServiceClient coursesClient) : base(null) + { + _coursesClient = coursesClient; + } - [HttpGet("{courseId}/getAll")] - [ProducesResponseType(typeof(GroupViewModel[]), (int)HttpStatusCode.OK)] - public async Task GetAllCourseGroups(long courseId) - { - var result = await _coursesClient.GetAllCourseGroups(courseId); - return result == null - ? NotFound() as IActionResult - : Ok(result); - } + [HttpGet("{courseId}/getAll")] + [ProducesResponseType(typeof(GroupViewModel[]), (int)HttpStatusCode.OK)] + public async Task GetAllCourseGroups(long courseId) + { + var result = await _coursesClient.GetAllCourseGroups(courseId); + return result == null + ? NotFound() + : Ok(result); + } - [HttpPost("{courseId}/create")] - [Authorize(Roles = Roles.LecturerRole)] - [ProducesResponseType(typeof(long), (int)HttpStatusCode.OK)] - public async Task CreateCourseGroup(CreateGroupViewModel model, long courseId) - { - var result = await _coursesClient.CreateCourseGroup(model, courseId); - return Ok(result); - } + [HttpPost("{courseId}/create")] + [Authorize(Roles = Roles.LecturerRole)] + [ProducesResponseType(typeof(long), (int)HttpStatusCode.OK)] + public async Task CreateCourseGroup(CreateGroupViewModel model, long courseId) + { + var result = await _coursesClient.CreateCourseGroup(model, courseId); + return Ok(result); + } - [HttpDelete("{courseId}/delete/{groupId}")] - [Authorize(Roles = Roles.LecturerRole)] - public async Task DeleteCourseGroup(long courseId, long groupId) - { - await _coursesClient.DeleteCourseGroup(courseId, groupId); - return Ok(); - } + [HttpDelete("{courseId}/delete/{groupId}")] + [Authorize(Roles = Roles.LecturerRole)] + public async Task DeleteCourseGroup(long courseId, long groupId) + { + await _coursesClient.DeleteCourseGroup(courseId, groupId); + return Ok(); + } - [HttpPost("{courseId}/update/{groupId}")] - [Authorize(Roles = Roles.LecturerRole)] - public async Task UpdateCourseGroup(UpdateGroupViewModel model, long courseId, long groupId) - { - await _coursesClient.UpdateCourseGroup(model, courseId, groupId); - return Ok(); - } + [HttpPost("{courseId}/update/{groupId}")] + [Authorize(Roles = Roles.LecturerRole)] + public async Task UpdateCourseGroup(UpdateGroupViewModel model, long courseId, long groupId) + { + await _coursesClient.UpdateCourseGroup(model, courseId, groupId); + return Ok(); + } - [HttpGet("{courseId}/get")] - [Authorize] - [ProducesResponseType(typeof(GroupViewModel), (int)HttpStatusCode.OK)] - public async Task GetCourseGroupsById(long courseId) - { - var result = await _coursesClient.GetCourseGroupsById(courseId, UserId); - return result == null - ? NotFound() as IActionResult - : Ok(result); - } + [HttpGet("{courseId}/get")] + [Authorize] + [ProducesResponseType(typeof(GroupViewModel), (int)HttpStatusCode.OK)] + public async Task GetCourseGroupsById(long courseId) + { + var result = await _coursesClient.GetCourseGroupsById(courseId, UserId); + return result == null + ? NotFound() + : Ok(result); + } - [HttpPost("{courseId}/addStudentInGroup/{groupId}")] - [Authorize(Roles = Roles.LecturerRole)] - public async Task AddStudentInGroup(long courseId, long groupId, [FromQuery] string userId) - { - await _coursesClient.AddStudentInGroup(courseId, groupId, userId); - return Ok(); - } + [HttpPost("{courseId}/addStudentInGroup/{groupId}")] + [Authorize(Roles = Roles.LecturerRole)] + public async Task AddStudentInGroup(long courseId, long groupId, [FromQuery] string userId) + { + await _coursesClient.AddStudentInGroup(courseId, groupId, userId); + return Ok(); + } - [HttpPost("{courseId}/removeStudentFromGroup/{groupId}")] - [Authorize(Roles = Roles.LecturerRole)] - public async Task RemoveStudentFromGroup(long courseId, long groupId, [FromQuery] string userId) - { - await _coursesClient.RemoveStudentFromGroup(courseId, groupId, userId); - return Ok(); - } + [HttpPost("{courseId}/removeStudentFromGroup/{groupId}")] + [Authorize(Roles = Roles.LecturerRole)] + public async Task RemoveStudentFromGroup(long courseId, long groupId, [FromQuery] string userId) + { + await _coursesClient.RemoveStudentFromGroup(courseId, groupId, userId); + return Ok(); + } - [HttpGet("get/{groupId}")] - [ProducesResponseType(typeof(GroupViewModel), (int)HttpStatusCode.OK)] - public async Task GetGroup(long groupId) - { - var result = await _coursesClient.GetGroupById(groupId); - return result == null - ? NotFound() as IActionResult - : Ok(result); - } + [HttpGet("get/{groupId}")] + [ProducesResponseType(typeof(GroupViewModel), (int)HttpStatusCode.OK)] + public async Task GetGroup(long groupId) + { + var result = await _coursesClient.GetGroupById(groupId); + return result == null + ? NotFound() + : Ok(result); + } - [HttpGet("getTasks/{groupId}")] - [ProducesResponseType(typeof(long[]), (int)HttpStatusCode.OK)] - public async Task GetGroupTasks(long groupId) - { - var result = await _coursesClient.GetGroupTasks(groupId); - return Ok(result); - } + [HttpGet("getTasks/{groupId}")] + [ProducesResponseType(typeof(long[]), (int)HttpStatusCode.OK)] + public async Task GetGroupTasks(long groupId) + { + var result = await _coursesClient.GetGroupTasks(groupId); + return Ok(result); } -} +} \ No newline at end of file diff --git a/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/CoursesController.cs b/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/CoursesController.cs index 5b83b747e..ddeae9d32 100644 --- a/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/CoursesController.cs +++ b/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/CoursesController.cs @@ -11,142 +11,141 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; -namespace HwProj.APIGateway.API.Controllers +namespace HwProj.APIGateway.API.Controllers; + +[Route("api/[controller]")] +[ApiController] +public class CoursesController : AggregationController { - [Route("api/[controller]")] - [ApiController] - public class CoursesController : AggregationController + private readonly ICoursesServiceClient _coursesClient; + + public CoursesController(ICoursesServiceClient coursesClient, IAuthServiceClient authServiceClient) : base( + authServiceClient) { - private readonly ICoursesServiceClient _coursesClient; + _coursesClient = coursesClient; + } - public CoursesController(ICoursesServiceClient coursesClient, IAuthServiceClient authServiceClient) : base( - authServiceClient) - { - _coursesClient = coursesClient; - } + [HttpGet] + [Authorize] + public async Task GetAllCourses() + { + var courses = await _coursesClient.GetAllCourses(); + var result = await GetCoursePreviews(courses); + return result; + } - [HttpGet] - [Authorize] - public async Task GetAllCourses() - { - var courses = await _coursesClient.GetAllCourses(); - var result = await GetCoursePreviews(courses); - return result; - } + [HttpGet("{courseId}")] + [ProducesResponseType(typeof(CourseViewModel), (int)HttpStatusCode.OK)] + public async Task GetCourseData(long courseId) + { + var course = await _coursesClient.GetCourseById(courseId, UserId); + if (course == null) return NotFound(); - [HttpGet("{courseId}")] - [ProducesResponseType(typeof(CourseViewModel), (int)HttpStatusCode.OK)] - public async Task GetCourseData(long courseId) - { - var course = await _coursesClient.GetCourseById(courseId, UserId); - if (course == null) return NotFound(); - - var studentIds = course.CourseMates.Select(t => t.StudentId).ToArray(); - var getStudentsTask = AuthServiceClient.GetAccountsData(studentIds); - var getMentorsTask = AuthServiceClient.GetAccountsData(course.MentorIds); - - await Task.WhenAll(getStudentsTask, getMentorsTask); - - var students = getStudentsTask.Result; - - var acceptedStudents = new List(); - var newStudents = new List(); - for (var i = 0; i < students.Length; i++) - { - if (!(students[i] is { } student)) continue; - if (course.CourseMates[i].IsAccepted) acceptedStudents.Add(student); - else newStudents.Add(student); - } - - var result = new CourseViewModel - { - Id = courseId, - Name = course.Name, - GroupName = course.GroupName, - Mentors = getMentorsTask.Result.Where(t => t != null).ToArray(), - AcceptedStudents = acceptedStudents.ToArray(), - NewStudents = newStudents.ToArray(), - Homeworks = course.Homeworks, - IsCompleted = course.IsCompleted, - IsOpen = course.IsOpen, - }; - - return Ok(result); - } + var studentIds = course.CourseMates.Select(t => t.StudentId).ToArray(); + var getStudentsTask = AuthServiceClient.GetAccountsData(studentIds); + var getMentorsTask = AuthServiceClient.GetAccountsData(course.MentorIds); - [HttpDelete("{courseId}")] - [Authorize(Roles = Roles.LecturerRole)] - public async Task DeleteCourse(long courseId) - { - await _coursesClient.DeleteCourse(courseId); - return Ok(); - } + await Task.WhenAll(getStudentsTask, getMentorsTask); - [HttpPost("create")] - [Authorize(Roles = Roles.LecturerRole)] - [ProducesResponseType(typeof(long), (int)HttpStatusCode.OK)] - public async Task CreateCourse(CreateCourseViewModel model) - { - var result = await _coursesClient.CreateCourse(model, UserId); - return Ok(result); - } + var students = getStudentsTask.Result; - [HttpPost("update/{courseId}")] - [Authorize(Roles = Roles.LecturerRole)] - public async Task UpdateCourse(UpdateCourseViewModel model, long courseId) + var acceptedStudents = new List(); + var newStudents = new List(); + for (var i = 0; i < students.Length; i++) { - await _coursesClient.UpdateCourse(model, courseId); - return Ok(); + if (!(students[i] is { } student)) continue; + if (course.CourseMates[i].IsAccepted) acceptedStudents.Add(student); + else newStudents.Add(student); } - [HttpPost("signInCourse/{courseId}")] - [Authorize] - public async Task SignInCourse(long courseId) + var result = new CourseViewModel { - await _coursesClient.SignInCourse(courseId, UserId); - return Ok(); - } + Id = courseId, + Name = course.Name, + GroupName = course.GroupName, + Mentors = getMentorsTask.Result.Where(t => t != null).ToArray(), + AcceptedStudents = acceptedStudents.ToArray(), + NewStudents = newStudents.ToArray(), + Homeworks = course.Homeworks, + IsCompleted = course.IsCompleted, + IsOpen = course.IsOpen, + }; + + return Ok(result); + } - [HttpPost("acceptStudent/{courseId}/{studentId}")] - [Authorize(Roles = Roles.LecturerRole)] - public async Task AcceptStudent(long courseId, string studentId) - { - await _coursesClient.AcceptStudent(courseId, studentId); - return Ok(); - } + [HttpDelete("{courseId}")] + [Authorize(Roles = Roles.LecturerRole)] + public async Task DeleteCourse(long courseId) + { + await _coursesClient.DeleteCourse(courseId); + return Ok(); + } - [HttpPost("rejectStudent/{courseId}/{studentId}")] - [Authorize(Roles = Roles.LecturerRole)] - public async Task RejectStudent(long courseId, string studentId) - { - await _coursesClient.RejectStudent(courseId, studentId); - return Ok(); - } + [HttpPost("create")] + [Authorize(Roles = Roles.LecturerRole)] + [ProducesResponseType(typeof(long), (int)HttpStatusCode.OK)] + public async Task CreateCourse(CreateCourseViewModel model) + { + var result = await _coursesClient.CreateCourse(model, UserId); + return Ok(result); + } - [HttpGet("userCourses")] - [Authorize] - public async Task GetAllUserCourses() - { - var userCourses = await _coursesClient.GetAllUserCourses(); - var result = await GetCoursePreviews(userCourses); - return result; - } + [HttpPost("update/{courseId}")] + [Authorize(Roles = Roles.LecturerRole)] + public async Task UpdateCourse(UpdateCourseViewModel model, long courseId) + { + await _coursesClient.UpdateCourse(model, courseId); + return Ok(); + } - [HttpGet("acceptLecturer/{courseId}/{lecturerEmail}")] - [Authorize(Roles = Roles.LecturerRole)] - public async Task AcceptLecturer(long courseId, string lecturerEmail) - { - await _coursesClient.AcceptLecturer(courseId, lecturerEmail); - return Ok(); - } + [HttpPost("signInCourse/{courseId}")] + [Authorize] + public async Task SignInCourse(long courseId) + { + await _coursesClient.SignInCourse(courseId, UserId); + return Ok(); + } - [HttpGet("getLecturersAvailableForCourse/{courseId}")] - [Authorize(Roles = Roles.LecturerRole)] - [ProducesResponseType(typeof(AccountDataDto[]), (int)HttpStatusCode.OK)] - public async Task GetLecturersAvailableForCourse(long courseId) - { - var result = await _coursesClient.GetLecturersAvailableForCourse(courseId); - return Ok(result.Value); - } + [HttpPost("acceptStudent/{courseId}/{studentId}")] + [Authorize(Roles = Roles.LecturerRole)] + public async Task AcceptStudent(long courseId, string studentId) + { + await _coursesClient.AcceptStudent(courseId, studentId); + return Ok(); + } + + [HttpPost("rejectStudent/{courseId}/{studentId}")] + [Authorize(Roles = Roles.LecturerRole)] + public async Task RejectStudent(long courseId, string studentId) + { + await _coursesClient.RejectStudent(courseId, studentId); + return Ok(); + } + + [HttpGet("userCourses")] + [Authorize] + public async Task GetAllUserCourses() + { + var userCourses = await _coursesClient.GetAllUserCourses(); + var result = await GetCoursePreviews(userCourses); + return result; + } + + [HttpGet("acceptLecturer/{courseId}/{lecturerEmail}")] + [Authorize(Roles = Roles.LecturerRole)] + public async Task AcceptLecturer(long courseId, string lecturerEmail) + { + await _coursesClient.AcceptLecturer(courseId, lecturerEmail); + return Ok(); + } + + [HttpGet("getLecturersAvailableForCourse/{courseId}")] + [Authorize(Roles = Roles.LecturerRole)] + [ProducesResponseType(typeof(AccountDataDto[]), (int)HttpStatusCode.OK)] + public async Task GetLecturersAvailableForCourse(long courseId) + { + var result = await _coursesClient.GetLecturersAvailableForCourse(courseId); + return Ok(result.Value); } -} +} \ No newline at end of file diff --git a/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/HomeworksController.cs b/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/HomeworksController.cs index 2a7d271af..49c1244bf 100644 --- a/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/HomeworksController.cs +++ b/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/HomeworksController.cs @@ -6,51 +6,50 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; -namespace HwProj.APIGateway.API.Controllers +namespace HwProj.APIGateway.API.Controllers; + +[Route("api/[controller]")] +[ApiController] +public class HomeworksController : ControllerBase { - [Route("api/[controller]")] - [ApiController] - public class HomeworksController : ControllerBase - { - private readonly ICoursesServiceClient _coursesClient; + private readonly ICoursesServiceClient _coursesClient; - public HomeworksController(ICoursesServiceClient coursesClient) - { - _coursesClient = coursesClient; - } + public HomeworksController(ICoursesServiceClient coursesClient) + { + _coursesClient = coursesClient; + } - [HttpGet("get/{homeworkId}")] - [Authorize] - [ProducesResponseType(typeof(HomeworkViewModel), (int)HttpStatusCode.OK)] - public async Task GetHomework(long homeworkId) - { - var result = await _coursesClient.GetHomework(homeworkId); - return Ok(result); - } + [HttpGet("get/{homeworkId}")] + [Authorize] + [ProducesResponseType(typeof(HomeworkViewModel), (int)HttpStatusCode.OK)] + public async Task GetHomework(long homeworkId) + { + var result = await _coursesClient.GetHomework(homeworkId); + return Ok(result); + } - [HttpPost("{courseId}/add")] - [Authorize(Roles = Roles.LecturerRole)] - [ProducesResponseType(typeof(long), (int)HttpStatusCode.OK)] - public async Task AddHomework(CreateHomeworkViewModel homeworkViewModel, long courseId) - { - var result = await _coursesClient.AddHomeworkToCourse(homeworkViewModel, courseId); - return Ok(result.Value); - } + [HttpPost("{courseId}/add")] + [Authorize(Roles = Roles.LecturerRole)] + [ProducesResponseType(typeof(long), (int)HttpStatusCode.OK)] + public async Task AddHomework(CreateHomeworkViewModel homeworkViewModel, long courseId) + { + var result = await _coursesClient.AddHomeworkToCourse(homeworkViewModel, courseId); + return Ok(result.Value); + } - [HttpDelete("delete/{homeworkId}")] - [Authorize(Roles = Roles.LecturerRole)] - public async Task DeleteHomework(long homeworkId) - { - await _coursesClient.DeleteHomework(homeworkId); - return Ok(); - } + [HttpDelete("delete/{homeworkId}")] + [Authorize(Roles = Roles.LecturerRole)] + public async Task DeleteHomework(long homeworkId) + { + await _coursesClient.DeleteHomework(homeworkId); + return Ok(); + } - [HttpPut("update/{homeworkId}")] - [Authorize(Roles = Roles.LecturerRole)] - public async Task UpdateHomework(CreateHomeworkViewModel homeworkViewModel, long homeworkId) - { - await _coursesClient.UpdateHomework(homeworkViewModel, homeworkId); - return Ok(); - } + [HttpPut("update/{homeworkId}")] + [Authorize(Roles = Roles.LecturerRole)] + public async Task UpdateHomework(CreateHomeworkViewModel homeworkViewModel, long homeworkId) + { + await _coursesClient.UpdateHomework(homeworkViewModel, homeworkId); + return Ok(); } -} +} \ No newline at end of file diff --git a/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/NotificationsController.cs b/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/NotificationsController.cs index 01bab40a8..f19357f40 100644 --- a/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/NotificationsController.cs +++ b/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/NotificationsController.cs @@ -5,40 +5,39 @@ using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; -namespace HwProj.APIGateway.API.Controllers +namespace HwProj.APIGateway.API.Controllers; + +[Route("api/[controller]")] +[Authorize] +[ApiController] +public class NotificationsController : AggregationController { - [Route("api/[controller]")] - [Authorize] - [ApiController] - public class NotificationsController : AggregationController - { - private readonly INotificationsServiceClient _notificationsClient; + private readonly INotificationsServiceClient _notificationsClient; - public NotificationsController(INotificationsServiceClient notificationsClient) : base(null) - { - _notificationsClient = notificationsClient; - } + public NotificationsController(INotificationsServiceClient notificationsClient) : base(null) + { + _notificationsClient = notificationsClient; + } - [HttpGet("getNewNotificationsCount")] - public async Task GetNewNotificationsCount() - { - var count = await _notificationsClient.GetNewNotificationsCount(UserId); - return count; - } + [HttpGet("getNewNotificationsCount")] + public async Task GetNewNotificationsCount() + { + var count = await _notificationsClient.GetNewNotificationsCount(UserId); + return count; + } - [HttpGet("get")] - [ProducesResponseType(typeof(CategorizedNotifications[]), (int)HttpStatusCode.OK)] - public async Task Get() - { - var result = await _notificationsClient.Get(UserId); - return Ok(result); - } + [HttpGet("get")] + [ProducesResponseType(typeof(CategorizedNotifications[]), (int)HttpStatusCode.OK)] + public async Task Get() + { + var result = await _notificationsClient.Get(UserId); + return Ok(result); + } - [HttpPut("markAsSeen")] - public async Task MarkAsSeen([FromBody] long[] notificationIds) - { - await _notificationsClient.MarkAsSeen(UserId, notificationIds); - return Ok(); - } + [HttpPut("markAsSeen")] + public async Task MarkAsSeen([FromBody] long[] notificationIds) + { + await _notificationsClient.MarkAsSeen(UserId, notificationIds); + return Ok(); } -} +} \ No newline at end of file diff --git a/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/SolutionsController.cs b/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/SolutionsController.cs index 5aa505dcf..984337fef 100644 --- a/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/SolutionsController.cs +++ b/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/SolutionsController.cs @@ -13,170 +13,169 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; -namespace HwProj.APIGateway.API.Controllers -{ - [Route("api/[controller]")] - [ApiController] - [ForbiddenExceptionFilter] - public class SolutionsController : AggregationController - { - private readonly ISolutionsServiceClient _solutionsClient; - private readonly ICoursesServiceClient _coursesServiceClient; +namespace HwProj.APIGateway.API.Controllers; - public SolutionsController(ISolutionsServiceClient solutionsClient, IAuthServiceClient authServiceClient, - ICoursesServiceClient coursesServiceClient) : - base(authServiceClient) - { - _solutionsClient = solutionsClient; - _coursesServiceClient = coursesServiceClient; - } +[Route("api/[controller]")] +[ApiController] +[ForbiddenExceptionFilter] +public class SolutionsController : AggregationController +{ + private readonly ISolutionsServiceClient _solutionsClient; + private readonly ICoursesServiceClient _coursesServiceClient; - [HttpGet] - [ProducesResponseType(typeof(Solution[]), (int)HttpStatusCode.OK)] - public async Task GetAllSolutions() - { - var result = await _solutionsClient.GetAllSolutions(); - return Ok(result); - } + public SolutionsController(ISolutionsServiceClient solutionsClient, IAuthServiceClient authServiceClient, + ICoursesServiceClient coursesServiceClient) : + base(authServiceClient) + { + _solutionsClient = solutionsClient; + _coursesServiceClient = coursesServiceClient; + } - [HttpGet("{solutionId}")] - [ProducesResponseType(typeof(Solution), (int)HttpStatusCode.OK)] - public async Task GetSolutionById(long solutionId) - { - var result = await _solutionsClient.GetSolutionById(solutionId); - return result == null - ? NotFound() as IActionResult - : Ok(result); - } + [HttpGet] + [ProducesResponseType(typeof(Solution[]), (int)HttpStatusCode.OK)] + public async Task GetAllSolutions() + { + var result = await _solutionsClient.GetAllSolutions(); + return Ok(result); + } - [HttpGet("taskSolution/{taskId}/{studentId}")] - [Authorize] - public async Task GetStudentSolution(long taskId, string studentId) - { - var getSolutionsTask = _solutionsClient.GetUserSolutions(taskId, studentId); - var getUserTask = AuthServiceClient.GetAccountData(studentId); + [HttpGet("{solutionId}")] + [ProducesResponseType(typeof(Solution), (int)HttpStatusCode.OK)] + public async Task GetSolutionById(long solutionId) + { + var result = await _solutionsClient.GetSolutionById(solutionId); + return result == null + ? NotFound() + : Ok(result); + } - await Task.WhenAll(getSolutionsTask, getUserTask); + [HttpGet("taskSolution/{taskId}/{studentId}")] + [Authorize] + public async Task GetStudentSolution(long taskId, string studentId) + { + var getSolutionsTask = _solutionsClient.GetUserSolutions(taskId, studentId); + var getUserTask = AuthServiceClient.GetAccountData(studentId); - var result = new UserTaskSolutions - { - User = getUserTask.Result, - Solutions = getSolutionsTask.Result, - }; - return result; - } + await Task.WhenAll(getSolutionsTask, getUserTask); - [HttpPost("{taskId}")] - [Authorize] - [ProducesResponseType(typeof(long), (int)HttpStatusCode.OK)] - public async Task PostSolution(SolutionViewModel model, long taskId) + var result = new UserTaskSolutions { - model.StudentId = UserId; - var result = await _solutionsClient.PostSolution(model, taskId); - return Ok(result); - } + User = getUserTask.Result, + Solutions = getSolutionsTask.Result, + }; + return result; + } - [HttpPost("rateSolution/{solutionId}/{newRating}")] - [Authorize(Roles = Roles.LecturerRole)] - public async Task RateSolution(long solutionId, int newRating, - [FromQuery] string lecturerComment) - { - await _solutionsClient.RateSolution(solutionId, newRating, lecturerComment, UserId); - return Ok(); - } + [HttpPost("{taskId}")] + [Authorize] + [ProducesResponseType(typeof(long), (int)HttpStatusCode.OK)] + public async Task PostSolution(SolutionViewModel model, long taskId) + { + model.StudentId = UserId; + var result = await _solutionsClient.PostSolution(model, taskId); + return Ok(result); + } - [HttpPost("markSolutionFinal/{solutionId}")] - [Authorize(Roles = Roles.LecturerRole)] - public async Task MarkSolution(long solutionId) - { - await _solutionsClient.MarkSolution(solutionId); - return Ok(); - } + [HttpPost("rateSolution/{solutionId}/{newRating}")] + [Authorize(Roles = Roles.LecturerRole)] + public async Task RateSolution(long solutionId, int newRating, + [FromQuery] string lecturerComment) + { + await _solutionsClient.RateSolution(solutionId, newRating, lecturerComment, UserId); + return Ok(); + } - [HttpDelete("delete/{solutionId}")] - [Authorize(Roles = Roles.LecturerRole)] - public async Task DeleteSolution(long solutionId) - { - await _solutionsClient.DeleteSolution(solutionId); - return Ok(); - } + [HttpPost("markSolutionFinal/{solutionId}")] + [Authorize(Roles = Roles.LecturerRole)] + public async Task MarkSolution(long solutionId) + { + await _solutionsClient.MarkSolution(solutionId); + return Ok(); + } - [HttpPost("{groupId}/{taskId}")] - [Authorize] - [ProducesResponseType(typeof(long), (int)HttpStatusCode.OK)] - public async Task PostGroupSolution(SolutionViewModel model, long taskId, long groupId) - { - var result = await _solutionsClient.PostGroupSolution(model, taskId, groupId); - return Ok(result); - } + [HttpDelete("delete/{solutionId}")] + [Authorize(Roles = Roles.LecturerRole)] + public async Task DeleteSolution(long solutionId) + { + await _solutionsClient.DeleteSolution(solutionId); + return Ok(); + } - [HttpGet("{groupId}/taskSolutions/{taskId}")] - [Authorize] - [ProducesResponseType(typeof(Solution[]), (int)HttpStatusCode.OK)] - public async Task GetGroupSolutions(long groupId, long taskId) - { - var result = await _solutionsClient.GetTaskSolutions(groupId, taskId); - return result == null - ? NotFound() as IActionResult - : Ok(result); - } + [HttpPost("{groupId}/{taskId}")] + [Authorize] + [ProducesResponseType(typeof(long), (int)HttpStatusCode.OK)] + public async Task PostGroupSolution(SolutionViewModel model, long taskId, long groupId) + { + var result = await _solutionsClient.PostGroupSolution(model, taskId, groupId); + return Ok(result); + } - [HttpGet("unratedSolutions")] - [Authorize(Roles = Roles.LecturerRole)] - public async Task GetUnratedSolutions(long? taskId) - { - var mentorCourses = await _coursesServiceClient.GetAllUserCourses(); - var tasks = FilterTasks(mentorCourses, taskId).ToDictionary(t => t.taskId, t => t.data); + [HttpGet("{groupId}/taskSolutions/{taskId}")] + [Authorize] + [ProducesResponseType(typeof(Solution[]), (int)HttpStatusCode.OK)] + public async Task GetGroupSolutions(long groupId, long taskId) + { + var result = await _solutionsClient.GetTaskSolutions(groupId, taskId); + return result == null + ? NotFound() + : Ok(result); + } - var taskIds = tasks.Select(t => t.Key).ToArray(); - var solutions = await _solutionsClient.GetAllUnratedSolutionsForTasks(taskIds); + [HttpGet("unratedSolutions")] + [Authorize(Roles = Roles.LecturerRole)] + public async Task GetUnratedSolutions(long? taskId) + { + var mentorCourses = await _coursesServiceClient.GetAllUserCourses(); + var tasks = FilterTasks(mentorCourses, taskId).ToDictionary(t => t.taskId, t => t.data); - var studentIds = solutions.Select(t => t.StudentId).Distinct().ToArray(); - var accountsData = await AuthServiceClient.GetAccountsData(studentIds); + var taskIds = tasks.Select(t => t.Key).ToArray(); + var solutions = await _solutionsClient.GetAllUnratedSolutionsForTasks(taskIds); - var unratedSolutions = solutions - .Join(accountsData, s => s.StudentId, s => s.UserId, (solution, account) => - { - var (course, homeworkTitle, task) = tasks[solution.TaskId]; - return new SolutionPreviewView - { - Student = account, - CourseTitle = $"{course.Name} / {course.GroupName}", - CourseId = course.Id, - HomeworkTitle = homeworkTitle, - TaskTitle = task.Title, - TaskId = task.Id, - PublicationDate = solution.PublicationDate, - IsFirstTry = solution.IsFirstTry, - SentAfterDeadline = solution.IsFirstTry && task.DeadlineDate != null && - solution.PublicationDate > task.DeadlineDate - }; - }) - .ToArray(); - - return new UnratedSolutionPreviews - { - UnratedSolutions = unratedSolutions, - }; - } + var studentIds = solutions.Select(t => t.StudentId).Distinct().ToArray(); + var accountsData = await AuthServiceClient.GetAccountsData(studentIds); - private static IEnumerable<(long taskId, - (CourseDTO course, string homeworkTitle, HomeworkTaskViewModel task) data)> - FilterTasks(CourseDTO[] courses, long? taskId) - { - foreach (var course in courses) - foreach (var homework in course.Homeworks) - foreach (var task in homework.Tasks) + var unratedSolutions = solutions + .Join(accountsData, s => s.StudentId, s => s.UserId, (solution, account) => { - if (taskId is { } id && task.Id == id) + var (course, homeworkTitle, task) = tasks[solution.TaskId]; + return new SolutionPreviewView { - yield return (task.Id, (course, homework.Title, task)); - yield break; - } + Student = account, + CourseTitle = $"{course.Name} / {course.GroupName}", + CourseId = course.Id, + HomeworkTitle = homeworkTitle, + TaskTitle = task.Title, + TaskId = task.Id, + PublicationDate = solution.PublicationDate, + IsFirstTry = solution.IsFirstTry, + SentAfterDeadline = solution.IsFirstTry && task.DeadlineDate != null && + solution.PublicationDate > task.DeadlineDate + }; + }) + .ToArray(); + + return new UnratedSolutionPreviews + { + UnratedSolutions = unratedSolutions, + }; + } - if (!taskId.HasValue) - yield return (task.Id, (course, homework.Title, task)); + private static IEnumerable<(long taskId, + (CourseDTO course, string homeworkTitle, HomeworkTaskViewModel task) data)> + FilterTasks(CourseDTO[] courses, long? taskId) + { + foreach (var course in courses) + foreach (var homework in course.Homeworks) + foreach (var task in homework.Tasks) + { + if (taskId is { } id && task.Id == id) + { + yield return (task.Id, (course, homework.Title, task)); + yield break; } + + if (!taskId.HasValue) + yield return (task.Id, (course, homework.Title, task)); } } -} +} \ No newline at end of file diff --git a/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/StatisticsController.cs b/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/StatisticsController.cs index 77d2a1945..84786faa3 100644 --- a/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/StatisticsController.cs +++ b/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/StatisticsController.cs @@ -6,39 +6,38 @@ using HwProj.SolutionsService.Client; using Microsoft.AspNetCore.Mvc; -namespace HwProj.APIGateway.API.Controllers +namespace HwProj.APIGateway.API.Controllers; + +[Route("api/[controller]")] +[ApiController] +public class StatisticsController : AggregationController { - [Route("api/[controller]")] - [ApiController] - public class StatisticsController : AggregationController - { - private readonly ISolutionsServiceClient _solutionClient; + private readonly ISolutionsServiceClient _solutionClient; - public StatisticsController(ISolutionsServiceClient solutionClient, IAuthServiceClient authServiceClient) : - base(authServiceClient) - { - _solutionClient = solutionClient; - } + public StatisticsController(ISolutionsServiceClient solutionClient, IAuthServiceClient authServiceClient) : + base(authServiceClient) + { + _solutionClient = solutionClient; + } - [HttpGet("{courseId}")] - [ProducesResponseType(typeof(StatisticsCourseMatesModel[]), (int)HttpStatusCode.OK)] - public async Task GetCourseStatistics(long courseId) - { - var statistics = await _solutionClient.GetCourseStatistics(courseId, UserId); - if (statistics == null) return Forbid(); + [HttpGet("{courseId}")] + [ProducesResponseType(typeof(StatisticsCourseMatesModel[]), (int)HttpStatusCode.OK)] + public async Task GetCourseStatistics(long courseId) + { + var statistics = await _solutionClient.GetCourseStatistics(courseId, UserId); + if (statistics == null) return Forbid(); - var studentIds = statistics.Select(t => t.StudentId).ToArray(); - var students = await AuthServiceClient.GetAccountsData(studentIds); + var studentIds = statistics.Select(t => t.StudentId).ToArray(); + var students = await AuthServiceClient.GetAccountsData(studentIds); - var result = statistics.Zip(students, (stats, student) => new StatisticsCourseMatesModel - { - Id = student.UserId, - Name = student.Name, - Surname = student.Surname, - Homeworks = stats.Homeworks - }).OrderBy(t => t.Surname).ThenBy(t => t.Name); + var result = statistics.Zip(students, (stats, student) => new StatisticsCourseMatesModel + { + Id = student.UserId, + Name = student.Name, + Surname = student.Surname, + Homeworks = stats.Homeworks + }).OrderBy(t => t.Surname).ThenBy(t => t.Name); - return Ok(result); - } + return Ok(result); } } diff --git a/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/SystemController.cs b/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/SystemController.cs index 61fb17326..a1b64115f 100644 --- a/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/SystemController.cs +++ b/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/SystemController.cs @@ -6,60 +6,59 @@ using HwProj.SolutionsService.Client; using Microsoft.AspNetCore.Mvc; -namespace HwProj.APIGateway.API.Controllers +namespace HwProj.APIGateway.API.Controllers; + +[Route("api/[controller]")] +[ApiController] +public class SystemController : AggregationController { - [Route("api/[controller]")] - [ApiController] - public class SystemController : AggregationController - { - private readonly ICoursesServiceClient _coursesServiceClient; - private readonly INotificationsServiceClient _notificationsServiceClient; - private readonly ISolutionsServiceClient _solutionsServiceClient; + private readonly ICoursesServiceClient _coursesServiceClient; + private readonly INotificationsServiceClient _notificationsServiceClient; + private readonly ISolutionsServiceClient _solutionsServiceClient; - public SystemController( - IAuthServiceClient authServiceClient, - ICoursesServiceClient coursesServiceClient, - INotificationsServiceClient notificationsServiceClient, - ISolutionsServiceClient solutionsServiceClient) : base(authServiceClient) - { - _coursesServiceClient = coursesServiceClient; - _notificationsServiceClient = notificationsServiceClient; - _solutionsServiceClient = solutionsServiceClient; - } + public SystemController( + IAuthServiceClient authServiceClient, + ICoursesServiceClient coursesServiceClient, + INotificationsServiceClient notificationsServiceClient, + ISolutionsServiceClient solutionsServiceClient) : base(authServiceClient) + { + _coursesServiceClient = coursesServiceClient; + _notificationsServiceClient = notificationsServiceClient; + _solutionsServiceClient = solutionsServiceClient; + } - [HttpGet("status")] - public async Task Status() - { - var authPing = AuthServiceClient.Ping(); - var coursesPing = _coursesServiceClient.Ping(); - var notificationsPing = _notificationsServiceClient.Ping(); - var solutionsPing = _solutionsServiceClient.Ping(); + [HttpGet("status")] + public async Task Status() + { + var authPing = AuthServiceClient.Ping(); + var coursesPing = _coursesServiceClient.Ping(); + var notificationsPing = _notificationsServiceClient.Ping(); + var solutionsPing = _solutionsServiceClient.Ping(); - await Task.WhenAll(authPing, coursesPing, notificationsPing, solutionsPing); + await Task.WhenAll(authPing, coursesPing, notificationsPing, solutionsPing); - return new[] + return new[] + { + new SystemInfo + { + Service = "Auth Service", + IsAvailable = authPing.Result + }, + new SystemInfo + { + Service = "Courses Service", + IsAvailable = coursesPing.Result + }, + new SystemInfo + { + Service = "Notifications Service", + IsAvailable = notificationsPing.Result + }, + new SystemInfo { - new SystemInfo - { - Service = "Auth Service", - IsAvailable = authPing.Result - }, - new SystemInfo - { - Service = "Courses Service", - IsAvailable = coursesPing.Result - }, - new SystemInfo - { - Service = "Notifications Service", - IsAvailable = notificationsPing.Result - }, - new SystemInfo - { - Service = "Solutions Service", - IsAvailable = solutionsPing.Result - }, - }; - } + Service = "Solutions Service", + IsAvailable = solutionsPing.Result + }, + }; } -} +} \ No newline at end of file diff --git a/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/TasksController.cs b/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/TasksController.cs index b057a2b05..d46ce7340 100644 --- a/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/TasksController.cs +++ b/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/TasksController.cs @@ -6,52 +6,51 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; -namespace HwProj.APIGateway.API.Controllers +namespace HwProj.APIGateway.API.Controllers; + +[Route("api/[controller]")] +[ApiController] +public class TasksController : ControllerBase { - [Route("api/[controller]")] - [ApiController] - public class TasksController : ControllerBase - { - private readonly ICoursesServiceClient _coursesClient; + private readonly ICoursesServiceClient _coursesClient; - public TasksController(ICoursesServiceClient coursesClient) - { - _coursesClient = coursesClient; - } + public TasksController(ICoursesServiceClient coursesClient) + { + _coursesClient = coursesClient; + } - [HttpGet("get/{taskId}")] - [ProducesResponseType(typeof(HomeworkTaskViewModel), (int)HttpStatusCode.OK)] - public async Task GetTask(long taskId) - { - var result = await _coursesClient.GetTask(taskId); - return result == null - ? NotFound() as IActionResult - : Ok(result); - } + [HttpGet("get/{taskId}")] + [ProducesResponseType(typeof(HomeworkTaskViewModel), (int)HttpStatusCode.OK)] + public async Task GetTask(long taskId) + { + var result = await _coursesClient.GetTask(taskId); + return result == null + ? NotFound() + : Ok(result); + } - [HttpPost("add/{homeworkId}")] - [Authorize(Roles = Roles.LecturerRole)] - [ProducesResponseType(typeof(long), (int)HttpStatusCode.OK)] - public async Task AddTask(CreateTaskViewModel taskViewModel, long homeworkId) - { - var result = await _coursesClient.AddTask(taskViewModel, homeworkId); - return Ok(result.Value); - } + [HttpPost("add/{homeworkId}")] + [Authorize(Roles = Roles.LecturerRole)] + [ProducesResponseType(typeof(long), (int)HttpStatusCode.OK)] + public async Task AddTask(CreateTaskViewModel taskViewModel, long homeworkId) + { + var result = await _coursesClient.AddTask(taskViewModel, homeworkId); + return Ok(result.Value); + } - [HttpDelete("delete/{taskId}")] - [Authorize(Roles = Roles.LecturerRole)] - public async Task DeleteTask(long taskId) - { - await _coursesClient.DeleteTask(taskId); - return Ok(); - } + [HttpDelete("delete/{taskId}")] + [Authorize(Roles = Roles.LecturerRole)] + public async Task DeleteTask(long taskId) + { + await _coursesClient.DeleteTask(taskId); + return Ok(); + } - [HttpPut("update/{taskId}")] - [Authorize(Roles = Roles.LecturerRole)] - public async Task UpdateTask(CreateTaskViewModel taskViewModel, long taskId) - { - await _coursesClient.UpdateTask(taskViewModel, taskId); - return Ok(); - } + [HttpPut("update/{taskId}")] + [Authorize(Roles = Roles.LecturerRole)] + public async Task UpdateTask(CreateTaskViewModel taskViewModel, long taskId) + { + await _coursesClient.UpdateTask(taskViewModel, taskId); + return Ok(); } -} +} \ No newline at end of file diff --git a/HwProj.APIGateway/HwProj.APIGateway.API/ExceptionFilters/ForbiddenExceptionFilter.cs b/HwProj.APIGateway/HwProj.APIGateway.API/ExceptionFilters/ForbiddenExceptionFilter.cs index 677cbaa64..74bfcf015 100644 --- a/HwProj.APIGateway/HwProj.APIGateway.API/ExceptionFilters/ForbiddenExceptionFilter.cs +++ b/HwProj.APIGateway/HwProj.APIGateway.API/ExceptionFilters/ForbiddenExceptionFilter.cs @@ -3,17 +3,16 @@ using HwProj.Exceptions; -namespace HwProj.APIGateway.API.ExceptionFilters +namespace HwProj.APIGateway.API.ExceptionFilters; + +public class ForbiddenExceptionFilter : Attribute, IExceptionFilter { - public class ForbiddenExceptionFilter : Attribute, IExceptionFilter + public void OnException(ExceptionContext context) { - public void OnException(ExceptionContext context) + if (context.Exception is ForbiddenException) { - if (context.Exception is ForbiddenException) - { - context.ExceptionHandled = true; - context.HttpContext.Response.StatusCode = 403; - } + context.ExceptionHandled = true; + context.HttpContext.Response.StatusCode = 403; } } } \ No newline at end of file diff --git a/HwProj.APIGateway/HwProj.APIGateway.API/HwProj.APIGateway.API.csproj b/HwProj.APIGateway/HwProj.APIGateway.API/HwProj.APIGateway.API.csproj index 29e5d8b3c..b2442e0ba 100644 --- a/HwProj.APIGateway/HwProj.APIGateway.API/HwProj.APIGateway.API.csproj +++ b/HwProj.APIGateway/HwProj.APIGateway.API/HwProj.APIGateway.API.csproj @@ -1,7 +1,7 @@  - netcoreapp2.2 + net6.0 ..\..\docker-compose.dcproj Linux ..\.. @@ -10,10 +10,7 @@ - - - - + diff --git a/HwProj.APIGateway/HwProj.APIGateway.API/Models/CoursePreviewView.cs b/HwProj.APIGateway/HwProj.APIGateway.API/Models/CoursePreviewView.cs index 7103dda92..3162b24ae 100644 --- a/HwProj.APIGateway/HwProj.APIGateway.API/Models/CoursePreviewView.cs +++ b/HwProj.APIGateway/HwProj.APIGateway.API/Models/CoursePreviewView.cs @@ -1,13 +1,12 @@ using HwProj.Models.AuthService.DTO; -namespace HwProj.APIGateway.API.Models +namespace HwProj.APIGateway.API.Models; + +public class CoursePreviewView { - public class CoursePreviewView - { - public long Id { get; set; } - public string Name { get; set; } - public string GroupName { get; set; } - public bool IsCompleted { get; set; } - public AccountDataDto[] Mentors { get; set; } - } -} + public long Id { get; set; } + public string Name { get; set; } + public string GroupName { get; set; } + public bool IsCompleted { get; set; } + public AccountDataDto[] Mentors { get; set; } +} \ No newline at end of file diff --git a/HwProj.APIGateway/HwProj.APIGateway.API/Models/Solutions/SolutionPreviewView.cs b/HwProj.APIGateway/HwProj.APIGateway.API/Models/Solutions/SolutionPreviewView.cs index 8c7087709..3c50a3071 100644 --- a/HwProj.APIGateway/HwProj.APIGateway.API/Models/Solutions/SolutionPreviewView.cs +++ b/HwProj.APIGateway/HwProj.APIGateway.API/Models/Solutions/SolutionPreviewView.cs @@ -1,23 +1,22 @@ using System; using HwProj.Models.AuthService.DTO; -namespace HwProj.APIGateway.API.Models.Solutions -{ - public class SolutionPreviewView - { - public AccountDataDto Student { get; set; } - public string CourseTitle { get; set; } - public long CourseId { get; set; } - public string HomeworkTitle { get; set; } - public string TaskTitle { get; set; } - public long TaskId { get; set; } - public DateTime PublicationDate { get; set; } - public bool IsFirstTry { get; set; } - public bool SentAfterDeadline { get; set; } - } +namespace HwProj.APIGateway.API.Models.Solutions; - public class UnratedSolutionPreviews - { - public SolutionPreviewView[] UnratedSolutions { get; set; } - } +public class SolutionPreviewView +{ + public AccountDataDto Student { get; set; } + public string CourseTitle { get; set; } + public long CourseId { get; set; } + public string HomeworkTitle { get; set; } + public string TaskTitle { get; set; } + public long TaskId { get; set; } + public DateTime PublicationDate { get; set; } + public bool IsFirstTry { get; set; } + public bool SentAfterDeadline { get; set; } } + +public class UnratedSolutionPreviews +{ + public SolutionPreviewView[] UnratedSolutions { get; set; } +} \ No newline at end of file diff --git a/HwProj.APIGateway/HwProj.APIGateway.API/Models/Solutions/UserTaskSolutions.cs b/HwProj.APIGateway/HwProj.APIGateway.API/Models/Solutions/UserTaskSolutions.cs index 86d69a26e..bc5973ddf 100644 --- a/HwProj.APIGateway/HwProj.APIGateway.API/Models/Solutions/UserTaskSolutions.cs +++ b/HwProj.APIGateway/HwProj.APIGateway.API/Models/Solutions/UserTaskSolutions.cs @@ -1,11 +1,10 @@ using HwProj.Models.AuthService.DTO; using HwProj.Models.SolutionsService; -namespace HwProj.APIGateway.API.Models.Solutions +namespace HwProj.APIGateway.API.Models.Solutions; + +public class UserTaskSolutions { - public class UserTaskSolutions - { - public Solution[] Solutions { get; set; } - public AccountDataDto User { get; set; } - } -} + public Solution[] Solutions { get; set; } + public AccountDataDto User { get; set; } +} \ No newline at end of file diff --git a/HwProj.APIGateway/HwProj.APIGateway.API/Models/StatisticsCourseMatesModel.cs b/HwProj.APIGateway/HwProj.APIGateway.API/Models/StatisticsCourseMatesModel.cs index 386ec0d83..2a7a68283 100644 --- a/HwProj.APIGateway/HwProj.APIGateway.API/Models/StatisticsCourseMatesModel.cs +++ b/HwProj.APIGateway/HwProj.APIGateway.API/Models/StatisticsCourseMatesModel.cs @@ -1,13 +1,12 @@ using System.Collections.Generic; using HwProj.Models.StatisticsService; -namespace HwProj.APIGateway.API.Models +namespace HwProj.APIGateway.API.Models; + +public class StatisticsCourseMatesModel { - public class StatisticsCourseMatesModel - { - public string Id { get; set; } - public string Name { get; set; } - public string Surname { get; set; } - public List Homeworks { get; set; } = new List(); - } -} + public string Id { get; set; } + public string Name { get; set; } + public string Surname { get; set; } + public List Homeworks { get; set; } = new(); +} \ No newline at end of file diff --git a/HwProj.APIGateway/HwProj.APIGateway.API/Models/SystemInfo.cs b/HwProj.APIGateway/HwProj.APIGateway.API/Models/SystemInfo.cs index 56c142588..1463cc6d0 100644 --- a/HwProj.APIGateway/HwProj.APIGateway.API/Models/SystemInfo.cs +++ b/HwProj.APIGateway/HwProj.APIGateway.API/Models/SystemInfo.cs @@ -1,8 +1,7 @@ -namespace HwProj.APIGateway.API.Models +namespace HwProj.APIGateway.API.Models; + +public class SystemInfo { - public class SystemInfo - { - public string Service { get; set; } - public bool IsAvailable { get; set; } - } -} + public string Service { get; set; } + public bool IsAvailable { get; set; } +} \ No newline at end of file diff --git a/HwProj.APIGateway/HwProj.APIGateway.API/Models/Tasks/TaskDeadlineView.cs b/HwProj.APIGateway/HwProj.APIGateway.API/Models/Tasks/TaskDeadlineView.cs index f45a58bd3..ef71107b5 100644 --- a/HwProj.APIGateway/HwProj.APIGateway.API/Models/Tasks/TaskDeadlineView.cs +++ b/HwProj.APIGateway/HwProj.APIGateway.API/Models/Tasks/TaskDeadlineView.cs @@ -1,13 +1,12 @@ using HwProj.Models.CoursesService.DTO; using HwProj.Models.SolutionsService; -namespace HwProj.APIGateway.API.Models.Tasks +namespace HwProj.APIGateway.API.Models.Tasks; + +public class TaskDeadlineView { - public class TaskDeadlineView - { - public TaskDeadlineDto Deadline { get; set; } - public SolutionState? SolutionState { get; set; } - public long? Rating { get; set; } - public long MaxRating { get; set; } - } -} + public TaskDeadlineDto Deadline { get; set; } + public SolutionState? SolutionState { get; set; } + public long? Rating { get; set; } + public long MaxRating { get; set; } +} \ No newline at end of file diff --git a/HwProj.APIGateway/HwProj.APIGateway.API/Models/UserDataDto.cs b/HwProj.APIGateway/HwProj.APIGateway.API/Models/UserDataDto.cs index 50aaff051..5cc1d2d2b 100644 --- a/HwProj.APIGateway/HwProj.APIGateway.API/Models/UserDataDto.cs +++ b/HwProj.APIGateway/HwProj.APIGateway.API/Models/UserDataDto.cs @@ -1,12 +1,11 @@ using HwProj.APIGateway.API.Models.Tasks; using HwProj.Models.AuthService.DTO; -namespace HwProj.APIGateway.API.Models +namespace HwProj.APIGateway.API.Models; + +public class UserDataDto { - public class UserDataDto - { - public AccountDataDto UserData { get; set; } - public CoursePreviewView[] Courses { get; set; } - public TaskDeadlineView[] TaskDeadlines { get; set; } - } -} + public AccountDataDto UserData { get; set; } + public CoursePreviewView[] Courses { get; set; } + public TaskDeadlineView[] TaskDeadlines { get; set; } +} \ No newline at end of file diff --git a/HwProj.APIGateway/HwProj.APIGateway.API/Program.cs b/HwProj.APIGateway/HwProj.APIGateway.API/Program.cs index 9378edd4d..f165e74bf 100644 --- a/HwProj.APIGateway/HwProj.APIGateway.API/Program.cs +++ b/HwProj.APIGateway/HwProj.APIGateway.API/Program.cs @@ -2,21 +2,20 @@ using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; -namespace HwProj.APIGateway.API +namespace HwProj.APIGateway.API; + +public static class Program { - public static class Program + public static void Main(string[] args) { - public static void Main(string[] args) - { - WebHost.CreateDefaultBuilder(args) - .UseStartup() - .ConfigureAppConfiguration((hostingContext, config) => - { - config.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath) - .AddEnvironmentVariables(); - }) - .Build() - .Run(); - } + WebHost.CreateDefaultBuilder(args) + .UseStartup() + .ConfigureAppConfiguration((hostingContext, config) => + { + config.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath) + .AddEnvironmentVariables(); + }) + .Build() + .Run(); } } diff --git a/HwProj.APIGateway/HwProj.APIGateway.API/Startup.cs b/HwProj.APIGateway/HwProj.APIGateway.API/Startup.cs index 81455dec1..ea6c395e6 100644 --- a/HwProj.APIGateway/HwProj.APIGateway.API/Startup.cs +++ b/HwProj.APIGateway/HwProj.APIGateway.API/Startup.cs @@ -10,50 +10,49 @@ using Microsoft.IdentityModel.Tokens; using HwProj.Utils.Authorization; -namespace HwProj.APIGateway.API +namespace HwProj.APIGateway.API; + +public class Startup { - public class Startup + public Startup(IConfiguration configuration) { - public Startup(IConfiguration configuration) - { - Configuration = configuration; - } + Configuration = configuration; + } - public IConfiguration Configuration { get; } + public IConfiguration Configuration { get; } - public void ConfigureServices(IServiceCollection services) - { - services.ConfigureHwProjServices("API Gateway"); + public void ConfigureServices(IServiceCollection services) + { + services.ConfigureHwProjServices("API Gateway"); - const string authenticationProviderKey = "GatewayKey"; + const string authenticationProviderKey = "GatewayKey"; - services.AddAuthentication() - .AddJwtBearer(authenticationProviderKey, x => + services.AddAuthentication() + .AddJwtBearer(authenticationProviderKey, x => + { + x.RequireHttpsMetadata = false; + x.TokenValidationParameters = new TokenValidationParameters { - x.RequireHttpsMetadata = false; - x.TokenValidationParameters = new TokenValidationParameters - { - ValidIssuer = "AuthService", - ValidateIssuer = true, - ValidateAudience = false, - ValidateLifetime = true, - IssuerSigningKey = AuthorizationKey.SecurityKey, - ValidateIssuerSigningKey = true - }; - }); - - services.AddHttpClient(); - services.AddHttpContextAccessor(); - - services.AddAuthServiceClient(); - services.AddCoursesServiceClient(); - services.AddSolutionServiceClient(); - services.AddNotificationsServiceClient(); - } - - public void Configure(IApplicationBuilder app, IHostingEnvironment env) - { - app.ConfigureHwProj(env, "API Gateway"); - } + ValidIssuer = "AuthService", + ValidateIssuer = true, + ValidateAudience = false, + ValidateLifetime = true, + IssuerSigningKey = AuthorizationKey.SecurityKey, + ValidateIssuerSigningKey = true + }; + }); + + services.AddHttpClient(); + services.AddHttpContextAccessor(); + + services.AddAuthServiceClient(); + services.AddCoursesServiceClient(); + services.AddSolutionServiceClient(); + services.AddNotificationsServiceClient(); + } + + public void Configure(IApplicationBuilder app, IWebHostEnvironment env) + { + app.ConfigureHwProj(env, "API Gateway"); } } diff --git a/HwProj.AuthService/HwProj.AuthService.API/AppSettings.cs b/HwProj.AuthService/HwProj.AuthService.API/AppSettings.cs index 2865a8e7a..6300da4f9 100644 --- a/HwProj.AuthService/HwProj.AuthService.API/AppSettings.cs +++ b/HwProj.AuthService/HwProj.AuthService.API/AppSettings.cs @@ -1,12 +1,11 @@ -namespace HwProj.AuthService.API +namespace HwProj.AuthService.API; + +public class AppSettings { - public class AppSettings - { - public string SecurityKey { get; set; } - public string ApiName { get; set; } - public string ClientIdGitHub { get; set; } - public string ClientSecretGitHub { get; set; } - public double ExpireInForToken { get; set; } - public double ExpireInForResponse { get; set; } - } + public string SecurityKey { get; set; } + public string ApiName { get; set; } + public string ClientIdGitHub { get; set; } + public string ClientSecretGitHub { get; set; } + public double ExpireInForToken { get; set; } + public double ExpireInForResponse { get; set; } } \ No newline at end of file diff --git a/HwProj.AuthService/HwProj.AuthService.API/ApplicationProfile.cs b/HwProj.AuthService/HwProj.AuthService.API/ApplicationProfile.cs index fd607c4a2..eb32a8f82 100644 --- a/HwProj.AuthService/HwProj.AuthService.API/ApplicationProfile.cs +++ b/HwProj.AuthService/HwProj.AuthService.API/ApplicationProfile.cs @@ -2,16 +2,15 @@ using HwProj.Models.AuthService.DTO; using HwProj.Models.AuthService.ViewModels; -namespace HwProj.AuthService.API +namespace HwProj.AuthService.API; + +public class ApplicationProfile : Profile { - public class ApplicationProfile : Profile + public ApplicationProfile() { - public ApplicationProfile() - { - CreateMap(); - CreateMap(); - CreateMap(); - CreateMap(); - } + CreateMap(); + CreateMap(); + CreateMap(); + CreateMap(); } -} +} \ No newline at end of file diff --git a/HwProj.AuthService/HwProj.AuthService.API/Controllers/AccountController.cs b/HwProj.AuthService/HwProj.AuthService.API/Controllers/AccountController.cs index b3ece17c5..9dc2b38e8 100644 --- a/HwProj.AuthService/HwProj.AuthService.API/Controllers/AccountController.cs +++ b/HwProj.AuthService/HwProj.AuthService.API/Controllers/AccountController.cs @@ -10,135 +10,134 @@ using Google.Apis.Auth; using HwProj.Models.Roles; -namespace HwProj.AuthService.API.Controllers +namespace HwProj.AuthService.API.Controllers; + +[Route("api/account")] +[ApiController] +public class AccountController : ControllerBase { - [Route("api/account")] - [ApiController] - public class AccountController : ControllerBase + private readonly IAccountService _accountService; + private readonly IUserManager _userManager; + private readonly IMapper _mapper; + + public AccountController(IAccountService accountService, IUserManager userManager, IMapper mapper) + { + _accountService = accountService; + _userManager = userManager; + _mapper = mapper; + } + + [HttpGet("getUserData/{userId}")] + [ProducesResponseType(typeof(AccountDataDto), (int)HttpStatusCode.OK)] + public async Task GetUserDataById(string userId) + { + var accountData = await _accountService.GetAccountDataAsync(userId).ConfigureAwait(false); + + return accountData != null + ? Ok(accountData) + : NotFound(); + } + + [HttpGet("getUsersData")] + public async Task GetUsersData([FromBody] string[] userIds) + { + var getAccountsDataTasks = userIds.Select(_accountService.GetAccountDataAsync).ToList(); + await Task.WhenAll(getAccountsDataTasks); + + return getAccountsDataTasks.Select(t => t.Result).ToArray(); + } + + [HttpPost("register")] + [ProducesResponseType(typeof(Result), (int)HttpStatusCode.OK)] + public async Task Register([FromBody] RegisterViewModel model) + { + var newModel = _mapper.Map(model); + var result = await _accountService.RegisterUserAsync(newModel).ConfigureAwait(false); + return Ok(result); + } + + [HttpPost("login")] + [ProducesResponseType(typeof(Result), (int)HttpStatusCode.OK)] + public async Task Login([FromBody] LoginViewModel model) + { + var tokenMeta = await _accountService.LoginUserAsync(model).ConfigureAwait(false); + return Ok(tokenMeta); + } + + [HttpPut("edit/{userId}")] + [ProducesResponseType(typeof(Result), (int)HttpStatusCode.OK)] + public async Task Edit([FromBody] EditAccountViewModel model, string userId) + { + var newModel = _mapper.Map(model); + var result = await _accountService.EditAccountAsync(userId, newModel).ConfigureAwait(false); + return Ok(result); + } + + [HttpPost("inviteNewLecturer")] + [ProducesResponseType(typeof(Result), (int)HttpStatusCode.OK)] + public async Task InviteNewLecturer(InviteLecturerViewModel model) + { + var result = await _accountService.InviteNewLecturer(model.Email).ConfigureAwait(false); + return Ok(result); + } + + [HttpPost("google/{tokenId}")] + [ProducesResponseType(typeof(Result), (int)HttpStatusCode.OK)] + public async Task GoogleRegister(string tokenId) + { + var payload = + await GoogleJsonWebSignature.ValidateAsync(tokenId, new GoogleJsonWebSignature.ValidationSettings()); + var result = await _accountService.LoginUserByGoogleAsync(payload).ConfigureAwait(false); + return Ok(result); + } + + [HttpPut("editExternal/{userId}")] + [ProducesResponseType(typeof(Result), (int)HttpStatusCode.OK)] + public async Task EditExternal([FromBody] EditExternalViewModel model, string userId) + { + var newModel = _mapper.Map(model); + var result = await _accountService.EditAccountAsync(userId, newModel).ConfigureAwait(false); + return Ok(result); + } + + + [HttpGet("findByEmail/{email}")] + [ProducesResponseType(typeof(User), (int)HttpStatusCode.OK)] + public async Task FindByEmail(string email) { - private readonly IAccountService _accountService; - private readonly IUserManager _userManager; - private readonly IMapper _mapper; - - public AccountController(IAccountService accountService, IUserManager userManager, IMapper mapper) - { - _accountService = accountService; - _userManager = userManager; - _mapper = mapper; - } - - [HttpGet("getUserData/{userId}")] - [ProducesResponseType(typeof(AccountDataDto), (int)HttpStatusCode.OK)] - public async Task GetUserDataById(string userId) - { - var accountData = await _accountService.GetAccountDataAsync(userId).ConfigureAwait(false); - - return accountData != null - ? Ok(accountData) as IActionResult - : NotFound(); - } - - [HttpGet("getUsersData")] - public async Task GetUsersData([FromBody] string[] userIds) - { - var getAccountsDataTasks = userIds.Select(_accountService.GetAccountDataAsync).ToList(); - await Task.WhenAll(getAccountsDataTasks); - - return getAccountsDataTasks.Select(t => t.Result).ToArray(); - } - - [HttpPost("register")] - [ProducesResponseType(typeof(Result), (int)HttpStatusCode.OK)] - public async Task Register([FromBody] RegisterViewModel model) - { - var newModel = _mapper.Map(model); - var result = await _accountService.RegisterUserAsync(newModel).ConfigureAwait(false); - return Ok(result); - } - - [HttpPost("login")] - [ProducesResponseType(typeof(Result), (int)HttpStatusCode.OK)] - public async Task Login([FromBody] LoginViewModel model) - { - var tokenMeta = await _accountService.LoginUserAsync(model).ConfigureAwait(false); - return Ok(tokenMeta); - } - - [HttpPut("edit/{userId}")] - [ProducesResponseType(typeof(Result), (int)HttpStatusCode.OK)] - public async Task Edit([FromBody] EditAccountViewModel model, string userId) - { - var newModel = _mapper.Map(model); - var result = await _accountService.EditAccountAsync(userId, newModel).ConfigureAwait(false); - return Ok(result); - } - - [HttpPost("inviteNewLecturer")] - [ProducesResponseType(typeof(Result), (int)HttpStatusCode.OK)] - public async Task InviteNewLecturer(InviteLecturerViewModel model) - { - var result = await _accountService.InviteNewLecturer(model.Email).ConfigureAwait(false); - return Ok(result); - } - - [HttpPost("google/{tokenId}")] - [ProducesResponseType(typeof(Result), (int)HttpStatusCode.OK)] - public async Task GoogleRegister(string tokenId) - { - var payload = - await GoogleJsonWebSignature.ValidateAsync(tokenId, new GoogleJsonWebSignature.ValidationSettings()); - var result = await _accountService.LoginUserByGoogleAsync(payload).ConfigureAwait(false); - return Ok(result); - } - - [HttpPut("editExternal/{userId}")] - [ProducesResponseType(typeof(Result), (int)HttpStatusCode.OK)] - public async Task EditExternal([FromBody] EditExternalViewModel model, string userId) - { - var newModel = _mapper.Map(model); - var result = await _accountService.EditAccountAsync(userId, newModel).ConfigureAwait(false); - return Ok(result); - } - - - [HttpGet("findByEmail/{email}")] - [ProducesResponseType(typeof(User), (int)HttpStatusCode.OK)] - public async Task FindByEmail(string email) - { - var user = await _userManager.FindByEmailAsync(email); - return Ok(user); - } - - [HttpGet("getRole")] - [ProducesResponseType(typeof(string), (int)HttpStatusCode.OK)] - public async Task GetRolesAsync([FromBody] User user) - { - var roles = await _userManager.GetRolesAsync(user); - return Ok(roles[0]); - } - - [HttpGet("getAllStudents")] - [ProducesResponseType(typeof(AccountDataDto[]), (int)HttpStatusCode.OK)] - public async Task GetAllStudents() - { - var allStudents = await _accountService.GetUsersInRole(Roles.StudentRole); - var result = allStudents - .Select(u => - new AccountDataDto(u.Id, u.Name, u.Surname, u.Email, Roles.StudentRole, u.IsExternalAuth, - u.MiddleName)) - .ToArray(); - - return Ok(result); - } - - [HttpGet("getAllLecturers")] - [ProducesResponseType(typeof(User[]), (int)HttpStatusCode.OK)] - public async Task GetAllLecturers() - { - var allLecturers = await _accountService.GetUsersInRole(Roles.LecturerRole); - var result = allLecturers.ToArray(); - - return Ok(result); - } + var user = await _userManager.FindByEmailAsync(email); + return Ok(user); + } + + [HttpGet("getRole")] + [ProducesResponseType(typeof(string), (int)HttpStatusCode.OK)] + public async Task GetRolesAsync([FromBody] User user) + { + var roles = await _userManager.GetRolesAsync(user); + return Ok(roles[0]); + } + + [HttpGet("getAllStudents")] + [ProducesResponseType(typeof(AccountDataDto[]), (int)HttpStatusCode.OK)] + public async Task GetAllStudents() + { + var allStudents = await _accountService.GetUsersInRole(Roles.StudentRole); + var result = allStudents + .Select(u => + new AccountDataDto(u.Id, u.Name, u.Surname, u.Email, Roles.StudentRole, u.IsExternalAuth, + u.MiddleName)) + .ToArray(); + + return Ok(result); + } + + [HttpGet("getAllLecturers")] + [ProducesResponseType(typeof(User[]), (int)HttpStatusCode.OK)] + public async Task GetAllLecturers() + { + var allLecturers = await _accountService.GetUsersInRole(Roles.LecturerRole); + var result = allLecturers.ToArray(); + + return Ok(result); } } diff --git a/HwProj.AuthService/HwProj.AuthService.API/Controllers/SystemController.cs b/HwProj.AuthService/HwProj.AuthService.API/Controllers/SystemController.cs index 13d72610a..62107115e 100644 --- a/HwProj.AuthService/HwProj.AuthService.API/Controllers/SystemController.cs +++ b/HwProj.AuthService/HwProj.AuthService.API/Controllers/SystemController.cs @@ -1,12 +1,11 @@ using Microsoft.AspNetCore.Mvc; -namespace HwProj.AuthService.API.Controllers +namespace HwProj.AuthService.API.Controllers; + +[Route("api/[controller]")] +[ApiController] +public class SystemController : ControllerBase { - [Route("api/[controller]")] - [ApiController] - public class SystemController : ControllerBase - { - [HttpGet("status")] - public IActionResult Status() => Ok(); - } -} + [HttpGet("status")] + public IActionResult Status() => Ok(); +} \ No newline at end of file diff --git a/HwProj.AuthService/HwProj.AuthService.API/Events/AdminRegisterEvent.cs b/HwProj.AuthService/HwProj.AuthService.API/Events/AdminRegisterEvent.cs index 09fc75942..2d389784d 100644 --- a/HwProj.AuthService/HwProj.AuthService.API/Events/AdminRegisterEvent.cs +++ b/HwProj.AuthService/HwProj.AuthService.API/Events/AdminRegisterEvent.cs @@ -1,11 +1,10 @@ -namespace HwProj.AuthService.API.Events +namespace HwProj.AuthService.API.Events; + +public class AdminRegisterEvent : RegisterEvent { - public class AdminRegisterEvent : RegisterEvent + public AdminRegisterEvent(string userId, string email, string name, string surname = "", string middleName = "") + : base(userId, email, name, surname, middleName) { - public AdminRegisterEvent(string userId, string email, string name, string surname = "", string middleName = "") - : base(userId, email, name, surname, middleName) - { - } } -} +} \ No newline at end of file diff --git a/HwProj.AuthService/HwProj.AuthService.API/Events/InviteLecturerEvent.cs b/HwProj.AuthService/HwProj.AuthService.API/Events/InviteLecturerEvent.cs index 345d6cc40..f277436eb 100644 --- a/HwProj.AuthService/HwProj.AuthService.API/Events/InviteLecturerEvent.cs +++ b/HwProj.AuthService/HwProj.AuthService.API/Events/InviteLecturerEvent.cs @@ -1,10 +1,9 @@ using HwProj.EventBus.Client; -namespace HwProj.AuthService.API.Events +namespace HwProj.AuthService.API.Events; + +public class InviteLecturerEvent : Event { - public class InviteLecturerEvent : Event - { - public string UserId { get; set; } - public string UserEmail { get; set; } - } -} + public string UserId { get; set; } + public string UserEmail { get; set; } +} \ No newline at end of file diff --git a/HwProj.AuthService/HwProj.AuthService.API/Events/RegisterEvent.cs b/HwProj.AuthService/HwProj.AuthService.API/Events/RegisterEvent.cs index c2625e5ba..a4ae1e98b 100644 --- a/HwProj.AuthService/HwProj.AuthService.API/Events/RegisterEvent.cs +++ b/HwProj.AuthService/HwProj.AuthService.API/Events/RegisterEvent.cs @@ -1,22 +1,21 @@ using HwProj.EventBus.Client; -namespace HwProj.AuthService.API.Events +namespace HwProj.AuthService.API.Events; + +public abstract class RegisterEvent : Event { - public abstract class RegisterEvent : Event - { - public string UserId { get; set; } - public string Name { get; set; } - public string Surname { get; set; } - public string MiddleName { get; set; } - public string Email { get; set; } + public string UserId { get; set; } + public string Name { get; set; } + public string Surname { get; set; } + public string MiddleName { get; set; } + public string Email { get; set; } - protected RegisterEvent(string userId, string email, string name, string surname = "", string middleName = "") - { - UserId = userId; - Name = name; - Surname = surname; - MiddleName = middleName; - Email = email; - } + protected RegisterEvent(string userId, string email, string name, string surname = "", string middleName = "") + { + UserId = userId; + Name = name; + Surname = surname; + MiddleName = middleName; + Email = email; } -} +} \ No newline at end of file diff --git a/HwProj.AuthService/HwProj.AuthService.API/Events/StudentRegisterEvent.cs b/HwProj.AuthService/HwProj.AuthService.API/Events/StudentRegisterEvent.cs index 5c894d2b8..e276404d2 100644 --- a/HwProj.AuthService/HwProj.AuthService.API/Events/StudentRegisterEvent.cs +++ b/HwProj.AuthService/HwProj.AuthService.API/Events/StudentRegisterEvent.cs @@ -1,11 +1,10 @@ -namespace HwProj.AuthService.API.Events +namespace HwProj.AuthService.API.Events; + +public class StudentRegisterEvent : RegisterEvent { - public class StudentRegisterEvent : RegisterEvent + public StudentRegisterEvent(string userId, string email, string name, string surname = "", string middleName = "") + : base(userId, email, name, surname, middleName) { - public StudentRegisterEvent(string userId, string email, string name, string surname = "", string middleName = "") - : base(userId, email, name, surname, middleName) - { - } } -} +} \ No newline at end of file diff --git a/HwProj.AuthService/HwProj.AuthService.API/Extensions/IdentityResultExtensions.cs b/HwProj.AuthService/HwProj.AuthService.API/Extensions/IdentityResultExtensions.cs index f51da37ab..3bacb9b7d 100644 --- a/HwProj.AuthService/HwProj.AuthService.API/Extensions/IdentityResultExtensions.cs +++ b/HwProj.AuthService/HwProj.AuthService.API/Extensions/IdentityResultExtensions.cs @@ -2,37 +2,36 @@ using System.Threading.Tasks; using Microsoft.AspNetCore.Identity; -namespace HwProj.AuthService.API.Extensions +namespace HwProj.AuthService.API.Extensions; + +public static class IdentityResultExtensions { - public static class IdentityResultExtensions + public static async Task Then(this Task task, + Func> continuation) { - public static async Task Then(this Task task, - Func> continuation) + var result = await task.ConfigureAwait(false); + return result.Succeeded + ? await continuation().ConfigureAwait(false) + : result; + } + + public static string TryGetIdentityError(this SignInResult result) + { + if (result.IsLockedOut) { - var result = await task.ConfigureAwait(false); - return result.Succeeded - ? await continuation().ConfigureAwait(false) - : result; + return nameof(result.IsLockedOut); } - public static string TryGetIdentityError(this SignInResult result) + if (result.IsNotAllowed) { - if (result.IsLockedOut) - { - return nameof(result.IsLockedOut); - } - - if (result.IsNotAllowed) - { - return nameof(result.IsNotAllowed); - } + return nameof(result.IsNotAllowed); + } - if (result.RequiresTwoFactor) - { - return nameof(result.RequiresTwoFactor); - } - - return "Неправильный логин или пароль"; + if (result.RequiresTwoFactor) + { + return nameof(result.RequiresTwoFactor); } + + return "Неправильный логин или пароль"; } } \ No newline at end of file diff --git a/HwProj.AuthService/HwProj.AuthService.API/HwProj.AuthService.API.csproj b/HwProj.AuthService/HwProj.AuthService.API/HwProj.AuthService.API.csproj index 1a272c31b..e0b845020 100644 --- a/HwProj.AuthService/HwProj.AuthService.API/HwProj.AuthService.API.csproj +++ b/HwProj.AuthService/HwProj.AuthService.API/HwProj.AuthService.API.csproj @@ -1,7 +1,7 @@  - netcoreapp2.2 + net6.0 Linux ..\..\docker-compose.dcproj ..\.. @@ -12,13 +12,11 @@ - - - + @@ -28,8 +26,4 @@ - - - - diff --git a/HwProj.AuthService/HwProj.AuthService.API/Models/IdentityContext.cs b/HwProj.AuthService/HwProj.AuthService.API/Models/IdentityContext.cs index 6f35c9636..ceb4def99 100644 --- a/HwProj.AuthService/HwProj.AuthService.API/Models/IdentityContext.cs +++ b/HwProj.AuthService/HwProj.AuthService.API/Models/IdentityContext.cs @@ -2,14 +2,13 @@ using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; -namespace HwProj.AuthService.API.Models +namespace HwProj.AuthService.API.Models; + +public sealed class IdentityContext : IdentityDbContext { - public sealed class IdentityContext : IdentityDbContext + public IdentityContext(DbContextOptions options) + : base(options) { - public IdentityContext(DbContextOptions options) - : base(options) - { - Database.EnsureCreated(); - } + Database.EnsureCreated(); } -} +} \ No newline at end of file diff --git a/HwProj.AuthService/HwProj.AuthService.API/Models/IdentityResults.cs b/HwProj.AuthService/HwProj.AuthService.API/Models/IdentityResults.cs index 77a7dbe30..f5effa3b7 100644 --- a/HwProj.AuthService/HwProj.AuthService.API/Models/IdentityResults.cs +++ b/HwProj.AuthService/HwProj.AuthService.API/Models/IdentityResults.cs @@ -1,21 +1,20 @@ using Microsoft.AspNetCore.Identity; -namespace HwProj.AuthService.API.Models -{ - public static class IdentityResults - { - public static IdentityResult UserNotFound => IdentityResult.Failed(IdentityErrors.UserNotFound); - public static IdentityResult WrongPassword => IdentityResult.Failed(IdentityErrors.WrongPassword); +namespace HwProj.AuthService.API.Models; - public static IdentityResult UserExists => - IdentityResult.Failed(new IdentityError { Description = "User exists" }); - } +public static class IdentityResults +{ + public static IdentityResult UserNotFound => IdentityResult.Failed(IdentityErrors.UserNotFound); + public static IdentityResult WrongPassword => IdentityResult.Failed(IdentityErrors.WrongPassword); - public static class IdentityErrors - { - public static IdentityError EmailNotConfirmed => new IdentityError { Description = "Email not confirmed" }; - public static IdentityError UserNotFound => new IdentityError { Description = "User not found" }; - public static IdentityError WrongPassword => new IdentityError { Description = "Wrong login or password" }; - public static IdentityError PasswordTooShort => new IdentityError { Description = "Пароль должен содержать не менее 6 символов" }; - } + public static IdentityResult UserExists => + IdentityResult.Failed(new IdentityError { Description = "User exists" }); } + +public static class IdentityErrors +{ + public static IdentityError EmailNotConfirmed => new() { Description = "Email not confirmed" }; + public static IdentityError UserNotFound => new() { Description = "User not found" }; + public static IdentityError WrongPassword => new() { Description = "Wrong login or password" }; + public static IdentityError PasswordTooShort => new() { Description = "Пароль должен содержать не менее 6 символов" }; +} \ No newline at end of file diff --git a/HwProj.AuthService/HwProj.AuthService.API/Program.cs b/HwProj.AuthService/HwProj.AuthService.API/Program.cs index d0443a9a6..096d32001 100644 --- a/HwProj.AuthService/HwProj.AuthService.API/Program.cs +++ b/HwProj.AuthService/HwProj.AuthService.API/Program.cs @@ -1,17 +1,16 @@ using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; -namespace HwProj.AuthService.API +namespace HwProj.AuthService.API; + +public class Program { - public class Program + public static void Main(string[] args) { - public static void Main(string[] args) - { - CreateWebHostBuilder(args).Build().Run(); - } - - public static IWebHostBuilder CreateWebHostBuilder(string[] args) => - WebHost.CreateDefaultBuilder(args) - .UseStartup(); + CreateWebHostBuilder(args).Build().Run(); } -} + + public static IWebHostBuilder CreateWebHostBuilder(string[] args) => + WebHost.CreateDefaultBuilder(args) + .UseStartup(); +} \ No newline at end of file diff --git a/HwProj.AuthService/HwProj.AuthService.API/RoleInitializer.cs b/HwProj.AuthService/HwProj.AuthService.API/RoleInitializer.cs index f3bcd0143..e68847872 100644 --- a/HwProj.AuthService/HwProj.AuthService.API/RoleInitializer.cs +++ b/HwProj.AuthService/HwProj.AuthService.API/RoleInitializer.cs @@ -5,44 +5,43 @@ using HwProj.Models.Roles; using HwProj.Models.AuthService.ViewModels; -namespace HwProj.AuthService.API +namespace HwProj.AuthService.API; + +public class RoleInitializer { - public class RoleInitializer + public static async Task InitializeAsync(UserManager userManager, RoleManager roleManager, IEventBus eventBus) { - public static async Task InitializeAsync(UserManager userManager, RoleManager roleManager, IEventBus eventBus) + if(await roleManager.FindByNameAsync(Roles.LecturerRole) == null) { - if(await roleManager.FindByNameAsync(Roles.LecturerRole) == null) - { - await roleManager.CreateAsync(Roles.Lecturer); - } + await roleManager.CreateAsync(Roles.Lecturer); + } - if (await roleManager.FindByNameAsync(Roles.StudentRole) == null) - { - await roleManager.CreateAsync(Roles.Student); - } + if (await roleManager.FindByNameAsync(Roles.StudentRole) == null) + { + await roleManager.CreateAsync(Roles.Student); + } - const string email = "admin@gmail.com"; - const string password = "Admin@1234"; + const string email = "admin@gmail.com"; + const string password = "Admin@1234"; - if (await userManager.FindByEmailAsync(email) == null) - { - var admin = new User { - Email = email, - Name = "Admin", - UserName = "Admin" - }; + if (await userManager.FindByEmailAsync(email) == null) + { + var admin = new User { + Email = email, + Name = "Admin", + UserName = "Admin" + }; - var result = await userManager.CreateAsync(admin, password); + var result = await userManager.CreateAsync(admin, password); - if (result.Succeeded) - { - await userManager.AddToRoleAsync(admin, Roles.LecturerRole); //TODO: dangerous - admin.EmailConfirmed = true; - await userManager.UpdateAsync(admin); - var @event = new AdminRegisterEvent(admin.Id, admin.Email, admin.Name); - eventBus.Publish(@event); - } + if (result.Succeeded) + { + await userManager.AddToRoleAsync(admin, Roles.LecturerRole); //TODO: dangerous + admin.EmailConfirmed = true; + await userManager.UpdateAsync(admin); + var @event = new AdminRegisterEvent(admin.Id, admin.Email, admin.Name); + eventBus.Publish(@event); } } } -} +} \ No newline at end of file diff --git a/HwProj.AuthService/HwProj.AuthService.API/Services/AccountService.cs b/HwProj.AuthService/HwProj.AuthService.API/Services/AccountService.cs index b60ad7ef5..d309cc2b3 100644 --- a/HwProj.AuthService/HwProj.AuthService.API/Services/AccountService.cs +++ b/HwProj.AuthService/HwProj.AuthService.API/Services/AccountService.cs @@ -12,228 +12,227 @@ using HwProj.Models.AuthService.ViewModels; using HwProj.Models.Result; -namespace HwProj.AuthService.API.Services +namespace HwProj.AuthService.API.Services; + +public class AccountService : IAccountService { - public class AccountService : IAccountService + private readonly IUserManager _userManager; + private readonly SignInManager _signInManager; + private readonly IAuthTokenService _tokenService; + private readonly IEventBus _eventBus; + private readonly IMapper _mapper; + + public AccountService(IUserManager userManager, + SignInManager signInManager, + IAuthTokenService authTokenService, + IEventBus eventBus, + IMapper mapper) { - private readonly IUserManager _userManager; - private readonly SignInManager _signInManager; - private readonly IAuthTokenService _tokenService; - private readonly IEventBus _eventBus; - private readonly IMapper _mapper; + _userManager = userManager; + _signInManager = signInManager; + _tokenService = authTokenService; + _eventBus = eventBus; + _mapper = mapper; + } - public AccountService(IUserManager userManager, - SignInManager signInManager, - IAuthTokenService authTokenService, - IEventBus eventBus, - IMapper mapper) + public async Task GetAccountDataAsync(string userId) + { + var user = await _userManager.FindByIdAsync(userId).ConfigureAwait(false); + if (user == null) { - _userManager = userManager; - _signInManager = signInManager; - _tokenService = authTokenService; - _eventBus = eventBus; - _mapper = mapper; + return null; } - public async Task GetAccountDataAsync(string userId) - { - var user = await _userManager.FindByIdAsync(userId).ConfigureAwait(false); - if (user == null) - { - return null; - } + var userRoles = await _userManager.GetRolesAsync(user).ConfigureAwait(false); + var userRole = userRoles.FirstOrDefault() ?? Roles.StudentRole; + return new AccountDataDto(user.Id, user.Name, user.Surname, user.Email, userRole, user.IsExternalAuth, + user.MiddleName); + } - var userRoles = await _userManager.GetRolesAsync(user).ConfigureAwait(false); - var userRole = userRoles.FirstOrDefault() ?? Roles.StudentRole; - return new AccountDataDto(user.Id, user.Name, user.Surname, user.Email, userRole, user.IsExternalAuth, - user.MiddleName); + public async Task EditAccountAsync(string id, EditDataDTO model) + { + var user = await _userManager.FindByIdAsync(id).ConfigureAwait(false); + if (user == null) + { + return Result.Failed("Пользователь не найден"); } - public async Task EditAccountAsync(string id, EditDataDTO model) + if (!user.IsExternalAuth && !await _userManager.CheckPasswordAsync(user, model.CurrentPassword)) { - var user = await _userManager.FindByIdAsync(id).ConfigureAwait(false); - if (user == null) - { - return Result.Failed("Пользователь не найден"); - } + return Result.Failed("Неправильный логин или пароль"); + } - if (!user.IsExternalAuth && !await _userManager.CheckPasswordAsync(user, model.CurrentPassword)) - { - return Result.Failed("Неправильный логин или пароль"); - } + var result = user.IsExternalAuth + ? await ChangeUserNameTask(user, model) + : await ChangeUserNameTask(user, model).Then(() => ChangePasswordAsync(user, model)); - var result = user.IsExternalAuth - ? await ChangeUserNameTask(user, model) - : await ChangeUserNameTask(user, model).Then(() => ChangePasswordAsync(user, model)); + if (result.Succeeded) + { + return Result.Success(); + } - if (result.Succeeded) - { - return Result.Success(); - } + return Result.Failed(); + } - return Result.Failed(); + public async Task> LoginUserAsync(LoginViewModel model) + { + if (await _userManager.FindByEmailAsync(model.Email).ConfigureAwait(false) + is var user && user == null) + { + return Result.Failed("Пользователь не найден"); } - public async Task> LoginUserAsync(LoginViewModel model) + var result = await _signInManager.PasswordSignInAsync( + user, + model.Password, + model.RememberMe, + false).ConfigureAwait(false); + + if (!result.Succeeded) { - if (await _userManager.FindByEmailAsync(model.Email).ConfigureAwait(false) - is var user && user == null) - { - return Result.Failed("Пользователь не найден"); - } + return Result.Failed(result.TryGetIdentityError()); + } - var result = await _signInManager.PasswordSignInAsync( - user, - model.Password, - model.RememberMe, - false).ConfigureAwait(false); + var token = await _tokenService.GetTokenAsync(user).ConfigureAwait(false); + return Result.Success(token); + } - if (!result.Succeeded) + public async Task> LoginUserByGoogleAsync(GoogleJsonWebSignature.Payload payload) + { + if (await _userManager.FindByEmailAsync(payload.Email).ConfigureAwait(false) + is var user && user == null) + { + var userModel = new RegisterDataDTO() { - return Result.Failed(result.TryGetIdentityError()); - } + Email = payload.Email, + Name = payload.GivenName, + Surname = payload.FamilyName, + IsExternalAuth = true + }; - var token = await _tokenService.GetTokenAsync(user).ConfigureAwait(false); - return Result.Success(token); + return await RegisterUserAsync(userModel); } - public async Task> LoginUserByGoogleAsync(GoogleJsonWebSignature.Payload payload) - { - if (await _userManager.FindByEmailAsync(payload.Email).ConfigureAwait(false) - is var user && user == null) - { - var userModel = new RegisterDataDTO() - { - Email = payload.Email, - Name = payload.GivenName, - Surname = payload.FamilyName, - IsExternalAuth = true - }; - - return await RegisterUserAsync(userModel); - } + return await GetToken(user); + } - return await GetToken(user); + public async Task> RegisterUserAsync(RegisterDataDTO model) + { + if (await _userManager.FindByEmailAsync(model.Email) != null) + { + return Result.Failed("Пользователь уже зарегистрирован"); } - public async Task> RegisterUserAsync(RegisterDataDTO model) + if (!model.IsExternalAuth && model.Password.Length < 6) { - if (await _userManager.FindByEmailAsync(model.Email) != null) - { - return Result.Failed("Пользователь уже зарегистрирован"); - } - - if (!model.IsExternalAuth && model.Password.Length < 6) - { - return Result.Failed("Пароль должен содержать не менее 6 символов"); - } - - var user = _mapper.Map(model); - user.UserName = user.Email.Split('@')[0]; + return Result.Failed("Пароль должен содержать не менее 6 символов"); + } - var createUserTask = model.IsExternalAuth - ? _userManager.CreateAsync(user) - : _userManager.CreateAsync(user, model.Password); + var user = _mapper.Map(model); + user.UserName = user.Email.Split('@')[0]; - if (!model.IsExternalAuth && createUserTask.Result.Succeeded && - !await _userManager.CheckPasswordAsync(user, model.PasswordConfirm)) - { - return Result.Failed("Пароли не совпадают"); - } + var createUserTask = model.IsExternalAuth + ? _userManager.CreateAsync(user) + : _userManager.CreateAsync(user, model.Password); - var result = await createUserTask - .Then(() => _userManager.AddToRoleAsync(user, Roles.StudentRole)) - .Then(() => - { - user.EmailConfirmed = true; - return _userManager.UpdateAsync(user); - }); + if (!model.IsExternalAuth && createUserTask.Result.Succeeded && + !await _userManager.CheckPasswordAsync(user, model.PasswordConfirm)) + { + return Result.Failed("Пароли не совпадают"); + } - if (result.Succeeded) + var result = await createUserTask + .Then(() => _userManager.AddToRoleAsync(user, Roles.StudentRole)) + .Then(() => { - var newUser = await _userManager.FindByEmailAsync(model.Email).ConfigureAwait(false); - var registerEvent = new StudentRegisterEvent(newUser.Id, newUser.Email, newUser.Name, - newUser.Surname, newUser.MiddleName); - _eventBus.Publish(registerEvent); - - if (!model.IsExternalAuth) - { - await SignIn(user, model.Password); - } - - return await GetToken(user); - } - - return Result.Failed(result.Errors.Select(errors => errors.Description).ToArray()); - } + user.EmailConfirmed = true; + return _userManager.UpdateAsync(user); + }); - public async Task InviteNewLecturer(string emailOfInvitedUser) + if (result.Succeeded) { - var invitedUser = await _userManager.FindByEmailAsync(emailOfInvitedUser).ConfigureAwait(false); + var newUser = await _userManager.FindByEmailAsync(model.Email).ConfigureAwait(false); + var registerEvent = new StudentRegisterEvent(newUser.Id, newUser.Email, newUser.Name, + newUser.Surname, newUser.MiddleName); + _eventBus.Publish(registerEvent); - if (invitedUser == null) + if (!model.IsExternalAuth) { - return Result.Failed("Пользователь не найден"); + await SignIn(user, model.Password); } - var result = await _userManager.AddToRoleAsync(invitedUser, Roles.LecturerRole) - .Then(() => _userManager.RemoveFromRoleAsync(invitedUser, Roles.StudentRole)).ConfigureAwait(false); + return await GetToken(user); + } - if (result.Succeeded) - { - var inviteEvent = new InviteLecturerEvent - { - UserId = invitedUser.Id, - UserEmail = invitedUser.Email - }; - _eventBus.Publish(inviteEvent); - return Result.Success(); - } + return Result.Failed(result.Errors.Select(errors => errors.Description).ToArray()); + } - return Result.Failed("Пользователь уже является преподавателем"); - } + public async Task InviteNewLecturer(string emailOfInvitedUser) + { + var invitedUser = await _userManager.FindByEmailAsync(emailOfInvitedUser).ConfigureAwait(false); - public async Task> GetUsersInRole(string role) + if (invitedUser == null) { - return await _userManager.GetUsersInRoleAsync(role); + return Result.Failed("Пользователь не найден"); } - private Task ChangeUserNameTask(User user, EditDataDTO model) - { - if (!string.IsNullOrWhiteSpace(model.Name)) - { - user.Name = model.Name; - } + var result = await _userManager.AddToRoleAsync(invitedUser, Roles.LecturerRole) + .Then(() => _userManager.RemoveFromRoleAsync(invitedUser, Roles.StudentRole)).ConfigureAwait(false); - if (!string.IsNullOrWhiteSpace(model.Name)) + if (result.Succeeded) + { + var inviteEvent = new InviteLecturerEvent { - user.Surname = model.Surname; - } + UserId = invitedUser.Id, + UserEmail = invitedUser.Email + }; + _eventBus.Publish(inviteEvent); + return Result.Success(); + } - if (!string.IsNullOrWhiteSpace(model.Name)) - { - user.MiddleName = model.MiddleName; - } + return Result.Failed("Пользователь уже является преподавателем"); + } - return _userManager.UpdateAsync(user); - } + public async Task> GetUsersInRole(string role) + { + return await _userManager.GetUsersInRoleAsync(role); + } - private Task ChangePasswordAsync(User user, EditDataDTO model) + private Task ChangeUserNameTask(User user, EditDataDTO model) + { + if (!string.IsNullOrWhiteSpace(model.Name)) { - return !string.IsNullOrWhiteSpace(model.NewPassword) - ? _userManager.ChangePasswordAsync(user, model.CurrentPassword, model.NewPassword) - : Task.FromResult(IdentityResult.Success); + user.Name = model.Name; } - private async Task SignIn(User user, string password) + if (!string.IsNullOrWhiteSpace(model.Name)) { - await _signInManager.PasswordSignInAsync(user, password, false, false) - .ConfigureAwait(false); + user.Surname = model.Surname; } - private async Task> GetToken(User user) + if (!string.IsNullOrWhiteSpace(model.Name)) { - return Result.Success(await _tokenService.GetTokenAsync(user).ConfigureAwait(false)); + user.MiddleName = model.MiddleName; } + + return _userManager.UpdateAsync(user); + } + + private Task ChangePasswordAsync(User user, EditDataDTO model) + { + return !string.IsNullOrWhiteSpace(model.NewPassword) + ? _userManager.ChangePasswordAsync(user, model.CurrentPassword, model.NewPassword) + : Task.FromResult(IdentityResult.Success); + } + + private async Task SignIn(User user, string password) + { + await _signInManager.PasswordSignInAsync(user, password, false, false) + .ConfigureAwait(false); + } + + private async Task> GetToken(User user) + { + return Result.Success(await _tokenService.GetTokenAsync(user).ConfigureAwait(false)); } -} +} \ No newline at end of file diff --git a/HwProj.AuthService/HwProj.AuthService.API/Services/AuthTokenService.cs b/HwProj.AuthService/HwProj.AuthService.API/Services/AuthTokenService.cs index cd7d9e778..e48a7ff5f 100644 --- a/HwProj.AuthService/HwProj.AuthService.API/Services/AuthTokenService.cs +++ b/HwProj.AuthService/HwProj.AuthService.API/Services/AuthTokenService.cs @@ -11,45 +11,44 @@ using HwProj.Models.AuthService.DTO; using HwProj.Models.AuthService.ViewModels; -namespace HwProj.AuthService.API.Services +namespace HwProj.AuthService.API.Services; + +public class AuthTokenService : IAuthTokenService { - public class AuthTokenService : IAuthTokenService + private readonly UserManager _userManager; + private readonly IConfigurationSection _configuration; + + public AuthTokenService(UserManager userManager, IConfiguration configuration) { - private readonly UserManager _userManager; - private readonly IConfigurationSection _configuration; + _userManager = userManager; + _configuration = configuration.GetSection("AppSettings"); + } - public AuthTokenService(UserManager userManager, IConfiguration configuration) - { - _userManager = userManager; - _configuration = configuration.GetSection("AppSettings"); - } + public async Task GetTokenAsync(User user) + { + var securityKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_configuration["SecurityKey"])); + var timeNow = DateTime.UtcNow; - public async Task GetTokenAsync(User user) - { - var securityKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_configuration["SecurityKey"])); - var timeNow = DateTime.UtcNow; - - var userRoles = await _userManager.GetRolesAsync(user).ConfigureAwait(false); - - var token = new JwtSecurityToken( - issuer: _configuration["ApiName"], - notBefore: timeNow, - expires: timeNow.AddMinutes(int.Parse(_configuration["ExpiresIn"])), - claims: new[] - { - new Claim("_userName", user.UserName), - new Claim("_id", user.Id), - new Claim(ClaimTypes.Email, user.Email), - new Claim(ClaimTypes.Role, userRoles.FirstOrDefault() ?? Roles.StudentRole) - }, - signingCredentials: new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256)); - - var tokenCredentials = new TokenCredentials + var userRoles = await _userManager.GetRolesAsync(user).ConfigureAwait(false); + + var token = new JwtSecurityToken( + issuer: _configuration["ApiName"], + notBefore: timeNow, + expires: timeNow.AddMinutes(int.Parse(_configuration["ExpiresIn"])), + claims: new[] { - AccessToken = new JwtSecurityTokenHandler().WriteToken(token) - }; + new Claim("_userName", user.UserName), + new Claim("_id", user.Id), + new Claim(ClaimTypes.Email, user.Email), + new Claim(ClaimTypes.Role, userRoles.FirstOrDefault() ?? Roles.StudentRole) + }, + signingCredentials: new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256)); + + var tokenCredentials = new TokenCredentials + { + AccessToken = new JwtSecurityTokenHandler().WriteToken(token) + }; - return tokenCredentials; - } + return tokenCredentials; } -} +} \ No newline at end of file diff --git a/HwProj.AuthService/HwProj.AuthService.API/Services/IAccountService.cs b/HwProj.AuthService/HwProj.AuthService.API/Services/IAccountService.cs index 183e5524e..1f5737dad 100644 --- a/HwProj.AuthService/HwProj.AuthService.API/Services/IAccountService.cs +++ b/HwProj.AuthService/HwProj.AuthService.API/Services/IAccountService.cs @@ -5,16 +5,15 @@ using HwProj.Models.AuthService.ViewModels; using HwProj.Models.Result; -namespace HwProj.AuthService.API.Services +namespace HwProj.AuthService.API.Services; + +public interface IAccountService { - public interface IAccountService - { - Task GetAccountDataAsync(string userId); - Task> RegisterUserAsync(RegisterDataDTO model); - Task EditAccountAsync(string accountId, EditDataDTO model); - Task> LoginUserAsync(LoginViewModel model); - Task> LoginUserByGoogleAsync(GoogleJsonWebSignature.Payload payload); - Task InviteNewLecturer(string emailOfInvitedUser); - Task> GetUsersInRole(string role); - } -} + Task GetAccountDataAsync(string userId); + Task> RegisterUserAsync(RegisterDataDTO model); + Task EditAccountAsync(string accountId, EditDataDTO model); + Task> LoginUserAsync(LoginViewModel model); + Task> LoginUserByGoogleAsync(GoogleJsonWebSignature.Payload payload); + Task InviteNewLecturer(string emailOfInvitedUser); + Task> GetUsersInRole(string role); +} \ No newline at end of file diff --git a/HwProj.AuthService/HwProj.AuthService.API/Services/IAuthTokenService.cs b/HwProj.AuthService/HwProj.AuthService.API/Services/IAuthTokenService.cs index ee0caef99..48f8873cb 100644 --- a/HwProj.AuthService/HwProj.AuthService.API/Services/IAuthTokenService.cs +++ b/HwProj.AuthService/HwProj.AuthService.API/Services/IAuthTokenService.cs @@ -2,10 +2,9 @@ using HwProj.Models.AuthService.ViewModels; using System.Threading.Tasks; -namespace HwProj.AuthService.API.Services +namespace HwProj.AuthService.API.Services; + +public interface IAuthTokenService { - public interface IAuthTokenService - { - Task GetTokenAsync(User user); - } -} + Task GetTokenAsync(User user); +} \ No newline at end of file diff --git a/HwProj.AuthService/HwProj.AuthService.API/Services/IUserManager.cs b/HwProj.AuthService/HwProj.AuthService.API/Services/IUserManager.cs index 9ce9db520..13fe057dc 100644 --- a/HwProj.AuthService/HwProj.AuthService.API/Services/IUserManager.cs +++ b/HwProj.AuthService/HwProj.AuthService.API/Services/IUserManager.cs @@ -3,21 +3,20 @@ using HwProj.Models.AuthService.ViewModels; using Microsoft.AspNetCore.Identity; -namespace HwProj.AuthService.API.Services +namespace HwProj.AuthService.API.Services; + +public interface IUserManager { - public interface IUserManager - { - Task CreateAsync(User user); - Task CreateAsync(User user, string password); - Task FindByIdAsync(string id); - Task FindByEmailAsync(string email); - Task UpdateAsync(User user); - Task AddToRoleAsync(User user, string role); - Task RemoveFromRoleAsync(User user, string role); - Task> GetRolesAsync(User user); - Task IsEmailConfirmedAsync(User user); - Task CheckPasswordAsync(User user, string password); - Task ChangePasswordAsync(User user, string currentPassword, string newPassword); - Task> GetUsersInRoleAsync(string role); - } -} + Task CreateAsync(User user); + Task CreateAsync(User user, string password); + Task FindByIdAsync(string id); + Task FindByEmailAsync(string email); + Task UpdateAsync(User user); + Task AddToRoleAsync(User user, string role); + Task RemoveFromRoleAsync(User user, string role); + Task> GetRolesAsync(User user); + Task IsEmailConfirmedAsync(User user); + Task CheckPasswordAsync(User user, string password); + Task ChangePasswordAsync(User user, string currentPassword, string newPassword); + Task> GetUsersInRoleAsync(string role); +} \ No newline at end of file diff --git a/HwProj.AuthService/HwProj.AuthService.API/Services/ProxyUserManager.cs b/HwProj.AuthService/HwProj.AuthService.API/Services/ProxyUserManager.cs index 533b149cb..7ff2b7ed9 100644 --- a/HwProj.AuthService/HwProj.AuthService.API/Services/ProxyUserManager.cs +++ b/HwProj.AuthService/HwProj.AuthService.API/Services/ProxyUserManager.cs @@ -3,75 +3,74 @@ using HwProj.Models.AuthService.ViewModels; using Microsoft.AspNetCore.Identity; -namespace HwProj.AuthService.API.Services +namespace HwProj.AuthService.API.Services; + +public class ProxyUserManager : IUserManager { - public class ProxyUserManager : IUserManager - { - private readonly UserManager _aspUserManager; + private readonly UserManager _aspUserManager; - public ProxyUserManager(UserManager aspUserManager) - { - _aspUserManager = aspUserManager; - } + public ProxyUserManager(UserManager aspUserManager) + { + _aspUserManager = aspUserManager; + } - public Task CreateAsync(User user) - { - return _aspUserManager.CreateAsync(user); - } + public Task CreateAsync(User user) + { + return _aspUserManager.CreateAsync(user); + } - public Task CreateAsync(User user, string password) - { - return _aspUserManager.CreateAsync(user, password); - } + public Task CreateAsync(User user, string password) + { + return _aspUserManager.CreateAsync(user, password); + } - public Task FindByIdAsync(string id) - { - return _aspUserManager.FindByIdAsync(id); - } + public Task FindByIdAsync(string id) + { + return _aspUserManager.FindByIdAsync(id); + } - public Task FindByEmailAsync(string email) - { - return _aspUserManager.FindByEmailAsync(email); - } + public Task FindByEmailAsync(string email) + { + return _aspUserManager.FindByEmailAsync(email); + } - public Task UpdateAsync(User user) - { - return _aspUserManager.UpdateAsync(user); - } + public Task UpdateAsync(User user) + { + return _aspUserManager.UpdateAsync(user); + } - public Task AddToRoleAsync(User user, string role) - { - return _aspUserManager.AddToRoleAsync(user, role); - } + public Task AddToRoleAsync(User user, string role) + { + return _aspUserManager.AddToRoleAsync(user, role); + } - public Task RemoveFromRoleAsync(User user, string role) - { - return _aspUserManager.RemoveFromRoleAsync(user, role); - } + public Task RemoveFromRoleAsync(User user, string role) + { + return _aspUserManager.RemoveFromRoleAsync(user, role); + } - public Task> GetRolesAsync(User user) - { - return _aspUserManager.GetRolesAsync(user); - } + public Task> GetRolesAsync(User user) + { + return _aspUserManager.GetRolesAsync(user); + } - public Task IsEmailConfirmedAsync(User user) - { - return _aspUserManager.IsEmailConfirmedAsync(user); - } + public Task IsEmailConfirmedAsync(User user) + { + return _aspUserManager.IsEmailConfirmedAsync(user); + } - public Task CheckPasswordAsync(User user, string password) - { - return _aspUserManager.CheckPasswordAsync(user, password); - } + public Task CheckPasswordAsync(User user, string password) + { + return _aspUserManager.CheckPasswordAsync(user, password); + } - public Task ChangePasswordAsync(User user, string currentPassword, string newPassword) - { - return _aspUserManager.ChangePasswordAsync(user, currentPassword, newPassword); - } + public Task ChangePasswordAsync(User user, string currentPassword, string newPassword) + { + return _aspUserManager.ChangePasswordAsync(user, currentPassword, newPassword); + } - public Task> GetUsersInRoleAsync(string role) - { - return _aspUserManager.GetUsersInRoleAsync(role); - } + public Task> GetUsersInRoleAsync(string role) + { + return _aspUserManager.GetUsersInRoleAsync(role); } -} +} \ No newline at end of file diff --git a/HwProj.AuthService/HwProj.AuthService.API/Startup.cs b/HwProj.AuthService/HwProj.AuthService.API/Startup.cs index d04e63c87..6df22fa4c 100644 --- a/HwProj.AuthService/HwProj.AuthService.API/Startup.cs +++ b/HwProj.AuthService/HwProj.AuthService.API/Startup.cs @@ -12,94 +12,93 @@ using HwProj.Utils.Configuration; using HwProj.Utils.Authorization; using HwProj.Models.AuthService.ViewModels; +using Microsoft.Extensions.Hosting; -namespace HwProj.AuthService.API +namespace HwProj.AuthService.API; + +public class Startup { - public class Startup + public Startup(IConfiguration configuration) { - public Startup(IConfiguration configuration) - { - Configuration = configuration; - } + Configuration = configuration; + } - public IConfiguration Configuration { get; } + public IConfiguration Configuration { get; } - public void ConfigureServices(IServiceCollection services) - { - services.ConfigureHwProjServices("AuthService API"); + public void ConfigureServices(IServiceCollection services) + { + services.ConfigureHwProjServices("AuthService API"); - //var appSettingsSection = Configuration.GetSection("AppSettings"); - //services.Configure(appSettingsSection); - - services.AddAuthentication(options => - { - options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; - //options.DefaultChallengeScheme = GoogleDefaults.AuthenticationScheme; - }) - .AddJwtBearer(x => - { - x.RequireHttpsMetadata = false; //TODO: dev env setting - x.TokenValidationParameters = new TokenValidationParameters - { - ValidIssuer = "AuthService", - ValidateIssuer = true, - ValidateAudience = false, - ValidateLifetime = true, - IssuerSigningKey = AuthorizationKey.SecurityKey, - ValidateIssuerSigningKey = true - }; - }) - /*.AddCookie() - .AddGoogle(options => + //var appSettingsSection = Configuration.GetSection("AppSettings"); + //services.Configure(appSettingsSection); + + services.AddAuthentication(options => + { + options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; + //options.DefaultChallengeScheme = GoogleDefaults.AuthenticationScheme; + }) + .AddJwtBearer(x => + { + x.RequireHttpsMetadata = false; //TODO: dev env setting + x.TokenValidationParameters = new TokenValidationParameters { - IConfigurationSection googleAuthNSection = - Configuration.GetSection("Authentication:Google"); + ValidIssuer = "AuthService", + ValidateIssuer = true, + ValidateAudience = false, + ValidateLifetime = true, + IssuerSigningKey = AuthorizationKey.SecurityKey, + ValidateIssuerSigningKey = true + }; + }) + /*.AddCookie() + .AddGoogle(options => + { + IConfigurationSection googleAuthNSection = + Configuration.GetSection("Authentication:Google"); - options.ClientId = googleAuthNSection["ClientId"]; - options.ClientSecret = googleAuthNSection["ClientSecret"]; - })*/; + options.ClientId = googleAuthNSection["ClientId"]; + options.ClientSecret = googleAuthNSection["ClientSecret"]; + })*/; - var connectionString = ConnectionString.GetConnectionString(Configuration); - services.AddDbContext(options => - options.UseSqlServer(connectionString)); + var connectionString = ConnectionString.GetConnectionString(Configuration); + services.AddDbContext(options => + options.UseSqlServer(connectionString)); - services.AddIdentity(opts => - { - opts.User.RequireUniqueEmail = true; - opts.Password.RequiredLength = 6; - opts.Password.RequireNonAlphanumeric = false; - opts.Password.RequireLowercase = false; - opts.Password.RequireUppercase = false; - opts.Password.RequireDigit = false; - }) - .AddEntityFrameworkStores() - .AddUserManager>() - .AddRoleManager>() - .AddDefaultTokenProviders(); + services.AddIdentity(opts => + { + opts.User.RequireUniqueEmail = true; + opts.Password.RequiredLength = 6; + opts.Password.RequireNonAlphanumeric = false; + opts.Password.RequireLowercase = false; + opts.Password.RequireUppercase = false; + opts.Password.RequireDigit = false; + }) + .AddEntityFrameworkStores() + .AddUserManager>() + .AddRoleManager>() + .AddDefaultTokenProviders(); - services.AddEventBus(Configuration); + services.AddEventBus(Configuration); - services.AddScoped() - .AddScoped() - .AddScoped(); - } + services.AddScoped() + .AddScoped() + .AddScoped(); + } - public void Configure(IApplicationBuilder app, IHostingEnvironment env) - { - app.ConfigureHwProj(env, "AuthService API"); + public void Configure(IApplicationBuilder app, IWebHostEnvironment env) + { + app.ConfigureHwProj(env, "AuthService API"); - using (var scope = app.ApplicationServices.CreateScope()) - { - var userManager = scope.ServiceProvider.GetService(typeof(UserManager)) as UserManager; + using var scope = app.ApplicationServices.CreateScope(); + var userManager = scope.ServiceProvider.GetService(typeof(UserManager)) as UserManager; - var rolesManager = scope.ServiceProvider.GetService(typeof(RoleManager)) as RoleManager; - var eventBus = scope.ServiceProvider.GetService(); + var rolesManager = + scope.ServiceProvider.GetService(typeof(RoleManager)) as RoleManager; + var eventBus = scope.ServiceProvider.GetService(); - if (env.IsDevelopment()) - { - RoleInitializer.InitializeAsync(userManager, rolesManager, eventBus).Wait(); - } - } + if (env.IsDevelopment()) + { + RoleInitializer.InitializeAsync(userManager, rolesManager, eventBus).Wait(); } } } diff --git a/HwProj.AuthService/HwProj.AuthService.Client/AuthServiceClient.cs b/HwProj.AuthService/HwProj.AuthService.Client/AuthServiceClient.cs index c551ec42f..4a50b5de5 100644 --- a/HwProj.AuthService/HwProj.AuthService.Client/AuthServiceClient.cs +++ b/HwProj.AuthService/HwProj.AuthService.Client/AuthServiceClient.cs @@ -9,183 +9,182 @@ using HwProj.Models.Result; using Microsoft.Extensions.Configuration; -namespace HwProj.AuthService.Client +namespace HwProj.AuthService.Client; + +public class AuthServiceClient : IAuthServiceClient { - public class AuthServiceClient : IAuthServiceClient - { - private readonly HttpClient _httpClient; - private readonly Uri _authServiceUri; + private readonly HttpClient _httpClient; + private readonly Uri _authServiceUri; - public AuthServiceClient(IHttpClientFactory clientFactory, IConfiguration configuration) - { - _httpClient = clientFactory.CreateClient(); - _authServiceUri = new Uri(configuration.GetSection("Services")["Auth"]); - } + public AuthServiceClient(IHttpClientFactory clientFactory, IConfiguration configuration) + { + _httpClient = clientFactory.CreateClient(); + _authServiceUri = new Uri(configuration.GetSection("Services")["Auth"]); + } - public async Task GetAccountData(string userId) - { - using var httpRequest = new HttpRequestMessage( - HttpMethod.Get, - _authServiceUri + $"api/account/getUserData/{userId}"); + public async Task GetAccountData(string userId) + { + using var httpRequest = new HttpRequestMessage( + HttpMethod.Get, + _authServiceUri + $"api/account/getUserData/{userId}"); - var response = await _httpClient.SendAsync(httpRequest); - return await response.DeserializeAsync().ConfigureAwait(false); - } + var response = await _httpClient.SendAsync(httpRequest); + return await response.DeserializeAsync().ConfigureAwait(false); + } - public async Task GetAccountsData(string[] userIds) + public async Task GetAccountsData(string[] userIds) + { + using var httpRequest = new HttpRequestMessage( + HttpMethod.Get, + _authServiceUri + "api/account/getUsersData") { - using var httpRequest = new HttpRequestMessage( - HttpMethod.Get, - _authServiceUri + "api/account/getUsersData") - { - Content = new StringContent( - JsonConvert.SerializeObject(userIds), - Encoding.UTF8, - "application/json") - }; - - var response = await _httpClient.SendAsync(httpRequest); - return await response.DeserializeAsync(); - } + Content = new StringContent( + JsonConvert.SerializeObject(userIds), + Encoding.UTF8, + "application/json") + }; + + var response = await _httpClient.SendAsync(httpRequest); + return await response.DeserializeAsync(); + } - public async Task> Register(RegisterViewModel model) + public async Task> Register(RegisterViewModel model) + { + using var httpRequest = new HttpRequestMessage( + HttpMethod.Post, + _authServiceUri + "api/account/register") { - using var httpRequest = new HttpRequestMessage( - HttpMethod.Post, - _authServiceUri + "api/account/register") - { - Content = new StringContent( - JsonConvert.SerializeObject(model), - Encoding.UTF8, - "application/json") - }; - - var response = await _httpClient.SendAsync(httpRequest); - return await response.DeserializeAsync>(); - } + Content = new StringContent( + JsonConvert.SerializeObject(model), + Encoding.UTF8, + "application/json") + }; + + var response = await _httpClient.SendAsync(httpRequest); + return await response.DeserializeAsync>(); + } - public async Task> Login(LoginViewModel model) + public async Task> Login(LoginViewModel model) + { + using var httpRequest = new HttpRequestMessage( + HttpMethod.Post, + _authServiceUri + "api/account/login") { - using var httpRequest = new HttpRequestMessage( - HttpMethod.Post, - _authServiceUri + "api/account/login") - { - Content = new StringContent( - JsonConvert.SerializeObject(model), - Encoding.UTF8, - "application/json") - }; - - var response = await _httpClient.SendAsync(httpRequest); - return await response.DeserializeAsync>(); - } + Content = new StringContent( + JsonConvert.SerializeObject(model), + Encoding.UTF8, + "application/json") + }; + + var response = await _httpClient.SendAsync(httpRequest); + return await response.DeserializeAsync>(); + } - public async Task Edit(EditAccountViewModel model, string userId) + public async Task Edit(EditAccountViewModel model, string userId) + { + using var httpRequest = new HttpRequestMessage( + HttpMethod.Put, + _authServiceUri + $"api/account/edit/{userId}") { - using var httpRequest = new HttpRequestMessage( - HttpMethod.Put, - _authServiceUri + $"api/account/edit/{userId}") - { - Content = new StringContent( - JsonConvert.SerializeObject(model), - Encoding.UTF8, - "application/json") - }; - - var response = await _httpClient.SendAsync(httpRequest); - return await response.DeserializeAsync(); - } + Content = new StringContent( + JsonConvert.SerializeObject(model), + Encoding.UTF8, + "application/json") + }; + + var response = await _httpClient.SendAsync(httpRequest); + return await response.DeserializeAsync(); + } - public async Task InviteNewLecturer(InviteLecturerViewModel model) + public async Task InviteNewLecturer(InviteLecturerViewModel model) + { + using var httpRequest = new HttpRequestMessage( + HttpMethod.Post, + _authServiceUri + "api/account/inviteNewLecturer") { - using var httpRequest = new HttpRequestMessage( - HttpMethod.Post, - _authServiceUri + "api/account/inviteNewLecturer") - { - Content = new StringContent( - JsonConvert.SerializeObject(model), - Encoding.UTF8, - "application/json") - }; - - var response = await _httpClient.SendAsync(httpRequest); - return await response.DeserializeAsync(); - } + Content = new StringContent( + JsonConvert.SerializeObject(model), + Encoding.UTF8, + "application/json") + }; + + var response = await _httpClient.SendAsync(httpRequest); + return await response.DeserializeAsync(); + } - public async Task> LoginByGoogle(string tokenId) - { - using var httpRequest = new HttpRequestMessage( - HttpMethod.Post, - _authServiceUri + $"api/account/google/{tokenId}"); + public async Task> LoginByGoogle(string tokenId) + { + using var httpRequest = new HttpRequestMessage( + HttpMethod.Post, + _authServiceUri + $"api/account/google/{tokenId}"); - var response = await _httpClient.SendAsync(httpRequest); - return await response.DeserializeAsync>(); - ; - } + var response = await _httpClient.SendAsync(httpRequest); + return await response.DeserializeAsync>(); + ; + } - public async Task EditExternal(EditExternalViewModel model, string userId) + public async Task EditExternal(EditExternalViewModel model, string userId) + { + using var httpRequest = new HttpRequestMessage( + HttpMethod.Put, + _authServiceUri + $"api/account/editExternal/{userId}") { - using var httpRequest = new HttpRequestMessage( - HttpMethod.Put, - _authServiceUri + $"api/account/editExternal/{userId}") - { - Content = new StringContent( - JsonConvert.SerializeObject(model), - Encoding.UTF8, - "application/json") - }; - var response = await _httpClient.SendAsync(httpRequest); - return await response.DeserializeAsync(); - } + Content = new StringContent( + JsonConvert.SerializeObject(model), + Encoding.UTF8, + "application/json") + }; + var response = await _httpClient.SendAsync(httpRequest); + return await response.DeserializeAsync(); + } - public async Task FindByEmailAsync(string email) + public async Task FindByEmailAsync(string email) + { + using var httpRequest = new HttpRequestMessage( + HttpMethod.Get, + _authServiceUri + $"api/account/findByEmail/{email}") { - using var httpRequest = new HttpRequestMessage( - HttpMethod.Get, - _authServiceUri + $"api/account/findByEmail/{email}") - { - Content = new StringContent( - JsonConvert.SerializeObject(email), - Encoding.UTF8, - "application/json") - }; - - var response = await _httpClient.SendAsync(httpRequest); - var user = await response.DeserializeAsync(); - return user?.Id; - } + Content = new StringContent( + JsonConvert.SerializeObject(email), + Encoding.UTF8, + "application/json") + }; + + var response = await _httpClient.SendAsync(httpRequest); + var user = await response.DeserializeAsync(); + return user?.Id; + } - public async Task GetAllStudents() - { - using var httpRequest = new HttpRequestMessage( - HttpMethod.Get, - _authServiceUri + "api/account/getAllStudents"); + public async Task GetAllStudents() + { + using var httpRequest = new HttpRequestMessage( + HttpMethod.Get, + _authServiceUri + "api/account/getAllStudents"); - var response = await _httpClient.SendAsync(httpRequest); - return await response.DeserializeAsync().ConfigureAwait(false); - } + var response = await _httpClient.SendAsync(httpRequest); + return await response.DeserializeAsync().ConfigureAwait(false); + } - public async Task GetAllLecturers() - { - using var httpRequest = new HttpRequestMessage( - HttpMethod.Get, - _authServiceUri + "api/account/getAllLecturers"); + public async Task GetAllLecturers() + { + using var httpRequest = new HttpRequestMessage( + HttpMethod.Get, + _authServiceUri + "api/account/getAllLecturers"); - var response = await _httpClient.SendAsync(httpRequest); - return await response.DeserializeAsync().ConfigureAwait(false); - } + var response = await _httpClient.SendAsync(httpRequest); + return await response.DeserializeAsync().ConfigureAwait(false); + } - public async Task Ping() + public async Task Ping() + { + try + { + await _httpClient.GetAsync(_authServiceUri + "api/system/ping"); + return true; + } + catch { - try - { - await _httpClient.GetAsync(_authServiceUri + "api/system/ping"); - return true; - } - catch - { - return false; - } + return false; } } -} +} \ No newline at end of file diff --git a/HwProj.AuthService/HwProj.AuthService.Client/ConfigurationExtensions.cs b/HwProj.AuthService/HwProj.AuthService.Client/ConfigurationExtensions.cs index 822fe24d8..a446990eb 100644 --- a/HwProj.AuthService/HwProj.AuthService.Client/ConfigurationExtensions.cs +++ b/HwProj.AuthService/HwProj.AuthService.Client/ConfigurationExtensions.cs @@ -1,13 +1,12 @@ using Microsoft.Extensions.DependencyInjection; -namespace HwProj.AuthService.Client +namespace HwProj.AuthService.Client; + +public static class ConfigurationExtensions { - public static class ConfigurationExtensions + public static IServiceCollection AddAuthServiceClient(this IServiceCollection services) { - public static IServiceCollection AddAuthServiceClient(this IServiceCollection services) - { - services.AddScoped(); - return services; - } + services.AddScoped(); + return services; } -} +} \ No newline at end of file diff --git a/HwProj.AuthService/HwProj.AuthService.Client/HwProj.AuthService.Client.csproj b/HwProj.AuthService/HwProj.AuthService.Client/HwProj.AuthService.Client.csproj index f83f7fc5a..e3c2850c2 100644 --- a/HwProj.AuthService/HwProj.AuthService.Client/HwProj.AuthService.Client.csproj +++ b/HwProj.AuthService/HwProj.AuthService.Client/HwProj.AuthService.Client.csproj @@ -2,7 +2,7 @@ Library - netcoreapp2.2 + net6.0 $(CSharpLanguageVersion) @@ -10,13 +10,12 @@ - - + + - - + diff --git a/HwProj.AuthService/HwProj.AuthService.Client/IAuthServiceClient.cs b/HwProj.AuthService/HwProj.AuthService.Client/IAuthServiceClient.cs index 9f995eac5..04ca22cbc 100644 --- a/HwProj.AuthService/HwProj.AuthService.Client/IAuthServiceClient.cs +++ b/HwProj.AuthService/HwProj.AuthService.Client/IAuthServiceClient.cs @@ -3,21 +3,20 @@ using System.Threading.Tasks; using HwProj.Models.Result; -namespace HwProj.AuthService.Client +namespace HwProj.AuthService.Client; + +public interface IAuthServiceClient { - public interface IAuthServiceClient - { - Task GetAccountData(string userId); - Task GetAccountsData(string[] userId); - Task> Register(RegisterViewModel model); - Task> Login(LoginViewModel model); - Task Edit(EditAccountViewModel model, string userId); - Task InviteNewLecturer(InviteLecturerViewModel model); - Task> LoginByGoogle(string tokenId); - Task EditExternal(EditExternalViewModel model, string userId); - Task FindByEmailAsync(string email); - Task GetAllStudents(); - Task GetAllLecturers(); - Task Ping(); - } -} + Task GetAccountData(string userId); + Task GetAccountsData(string[] userId); + Task> Register(RegisterViewModel model); + Task> Login(LoginViewModel model); + Task Edit(EditAccountViewModel model, string userId); + Task InviteNewLecturer(InviteLecturerViewModel model); + Task> LoginByGoogle(string tokenId); + Task EditExternal(EditExternalViewModel model, string userId); + Task FindByEmailAsync(string email); + Task GetAllStudents(); + Task GetAllLecturers(); + Task Ping(); +} \ No newline at end of file diff --git a/HwProj.AuthService/HwProj.AuthService.IntegrationTests/AuthServiceTests.cs b/HwProj.AuthService/HwProj.AuthService.IntegrationTests/AuthServiceTests.cs index f532661f3..bec02adbe 100644 --- a/HwProj.AuthService/HwProj.AuthService.IntegrationTests/AuthServiceTests.cs +++ b/HwProj.AuthService/HwProj.AuthService.IntegrationTests/AuthServiceTests.cs @@ -20,481 +20,480 @@ using HwProj.Models.Roles; using HwProj.Utils.Authorization; -namespace HwProj.AuthService.IntegrationTests +namespace HwProj.AuthService.IntegrationTests; + +public class Tests { - public class Tests + private Claim[] ValidateToken(Result resultData) { - private Claim[] ValidateToken(Result resultData) - { - const string secret = "this is a string used for encrypt and decrypt token"; - var key = Encoding.ASCII.GetBytes(secret); - var handler = new JwtSecurityTokenHandler(); - var validations = new TokenValidationParameters - { - ValidIssuer = "AuthService", - ValidateIssuer = true, - ValidateAudience = false, - ValidateLifetime = true, - IssuerSigningKey = AuthorizationKey.SecurityKey, - ValidateIssuerSigningKey = true - }; - var claims = handler.ValidateToken(resultData.Value.AccessToken, validations, out var tokenSecure); - - return claims.Claims.ToArray(); - } - - private AuthServiceClient CreateAuthServiceClient() + const string secret = "this is a string used for encrypt and decrypt token"; + var key = Encoding.ASCII.GetBytes(secret); + var handler = new JwtSecurityTokenHandler(); + var validations = new TokenValidationParameters { - var mockIConfiguration = new Mock(); - mockIConfiguration - .Setup(x => x.GetSection("Services")["Auth"]) - .Returns("http://localhost:5001"); + ValidIssuer = "AuthService", + ValidateIssuer = true, + ValidateAudience = false, + ValidateLifetime = true, + IssuerSigningKey = AuthorizationKey.SecurityKey, + ValidateIssuerSigningKey = true + }; + var claims = handler.ValidateToken(resultData.Value.AccessToken, validations, out var tokenSecure); + + return claims.Claims.ToArray(); + } - var mockClientFactory = new Mock(); - mockClientFactory - .Setup(x => x.CreateClient(Options.DefaultName)) - .Returns(new HttpClient()); + private AuthServiceClient CreateAuthServiceClient() + { + var mockIConfiguration = new Mock(); + mockIConfiguration + .Setup(x => x.GetSection("Services")["Auth"]) + .Returns("http://localhost:5001"); - return new AuthServiceClient(mockClientFactory.Object, mockIConfiguration.Object); - } + var mockClientFactory = new Mock(); + mockClientFactory + .Setup(x => x.CreateClient(Options.DefaultName)) + .Returns(new HttpClient()); - private static RegisterViewModel GenerateRegisterViewModel() - { - var password = new Fixture().Create(); - - var fixture = new Fixture().Build() - .With(x => x.Email, new Fixture().Create().Address) - .With(x => x.Password, password) - .With(x => x.PasswordConfirm, password); - - return fixture.Create(); - } - - private static LoginViewModel GenerateLoginViewModel(RegisterViewModel model) - => new LoginViewModel - { - Email = model.Email, - Password = model.Password, - RememberMe = false - }; - - private static EditAccountViewModel GenerateEditViewModel(RegisterViewModel model) - => new EditAccountViewModel - { - Name = model.Name, - Surname = model.Surname, - MiddleName = model.MiddleName, - CurrentPassword = model.Password, - NewPassword = new Fixture().Create() - }; - - private static EditAccountViewModel GenerateEditAccountViewModel(RegisterViewModel model) - => new EditAccountViewModel - { - Name = new Fixture().Create(), - Surname = new Fixture().Create(), - MiddleName = new Fixture().Create(), - CurrentPassword = model.Password, - NewPassword = model.Password - }; - - private static InviteLecturerViewModel GenerateInviteNewLecturerViewModel(RegisterViewModel model) - => new InviteLecturerViewModel - { - Email = model.Email - }; - - private static AccountDataDto GenerateAccountDataDto(RegisterViewModel model) - => new AccountDataDto(Guid.NewGuid().ToString(), model.Name, - model.Surname, - model.Email, - "Student", - false, - model.MiddleName); - - private static User GenerateUser(RegisterViewModel model) - => new User - { - Name = model.Name, - Surname = model.Surname, - MiddleName = model.MiddleName, - IsExternalAuth = false - }; - - private IAuthServiceClient _authServiceClient; - - [SetUp] - public void SetUp() + return new AuthServiceClient(mockClientFactory.Object, mockIConfiguration.Object); + } + + private static RegisterViewModel GenerateRegisterViewModel() + { + var password = new Fixture().Create(); + + var fixture = new Fixture().Build() + .With(x => x.Email, new Fixture().Create().Address) + .With(x => x.Password, password) + .With(x => x.PasswordConfirm, password); + + return fixture.Create(); + } + + private static LoginViewModel GenerateLoginViewModel(RegisterViewModel model) + => new LoginViewModel { - _authServiceClient = CreateAuthServiceClient(); - } + Email = model.Email, + Password = model.Password, + RememberMe = false + }; - [Test] - public async Task TestRegisterUser() + private static EditAccountViewModel GenerateEditViewModel(RegisterViewModel model) + => new EditAccountViewModel + { + Name = model.Name, + Surname = model.Surname, + MiddleName = model.MiddleName, + CurrentPassword = model.Password, + NewPassword = new Fixture().Create() + }; + + private static EditAccountViewModel GenerateEditAccountViewModel(RegisterViewModel model) + => new EditAccountViewModel + { + Name = new Fixture().Create(), + Surname = new Fixture().Create(), + MiddleName = new Fixture().Create(), + CurrentPassword = model.Password, + NewPassword = model.Password + }; + + private static InviteLecturerViewModel GenerateInviteNewLecturerViewModel(RegisterViewModel model) + => new InviteLecturerViewModel { - var userData = GenerateRegisterViewModel(); - var registerResult = await _authServiceClient.Register(userData); + Email = model.Email + }; + + private static AccountDataDto GenerateAccountDataDto(RegisterViewModel model) + => new AccountDataDto(Guid.NewGuid().ToString(), model.Name, + model.Surname, + model.Email, + "Student", + false, + model.MiddleName); + + private static User GenerateUser(RegisterViewModel model) + => new User + { + Name = model.Name, + Surname = model.Surname, + MiddleName = model.MiddleName, + IsExternalAuth = false + }; - registerResult.Succeeded.Should().BeTrue(); - registerResult.Errors.Should().BeNullOrEmpty(); - registerResult.Value.AccessToken.Should().NotBeNullOrEmpty(); + private IAuthServiceClient _authServiceClient; - var userId = await _authServiceClient.FindByEmailAsync(userData.Email); - var resultData = await _authServiceClient.GetAccountData(userId); + [SetUp] + public void SetUp() + { + _authServiceClient = CreateAuthServiceClient(); + } - resultData.Should().BeEquivalentTo(userData, options => - options.ExcludingMissingMembers()); - resultData.Role.Should().Be(Roles.StudentRole); - } + [Test] + public async Task TestRegisterUser() + { + var userData = GenerateRegisterViewModel(); + var registerResult = await _authServiceClient.Register(userData); - [Test] - public async Task UserAlreadyExistRegisterTest() - { - var userData = GenerateRegisterViewModel(); - var registerResult = await _authServiceClient.Register(userData); + registerResult.Succeeded.Should().BeTrue(); + registerResult.Errors.Should().BeNullOrEmpty(); + registerResult.Value.AccessToken.Should().NotBeNullOrEmpty(); - registerResult.Succeeded.Should().BeTrue(); - registerResult.Errors.Should().BeNullOrEmpty(); - registerResult.Value.AccessToken.Should().NotBeNullOrEmpty(); + var userId = await _authServiceClient.FindByEmailAsync(userData.Email); + var resultData = await _authServiceClient.GetAccountData(userId); - var secondRegisterResult = await _authServiceClient.Register(userData); + resultData.Should().BeEquivalentTo(userData, options => + options.ExcludingMissingMembers()); + resultData.Role.Should().Be(Roles.StudentRole); + } - secondRegisterResult.Succeeded.Should().BeFalse(); - secondRegisterResult.Errors.Should() - .BeEquivalentTo("Пользователь уже зарегистрирован"); + [Test] + public async Task UserAlreadyExistRegisterTest() + { + var userData = GenerateRegisterViewModel(); + var registerResult = await _authServiceClient.Register(userData); - secondRegisterResult.Value.Should().BeNull(); - } + registerResult.Succeeded.Should().BeTrue(); + registerResult.Errors.Should().BeNullOrEmpty(); + registerResult.Value.AccessToken.Should().NotBeNullOrEmpty(); - [Test] - public async Task WrongLengthPasswordRegisterTest() - { - var userData = GenerateRegisterViewModel(); - userData.Password = userData.Password.Substring(0, 5); - var registerResult = await _authServiceClient.Register(userData); - - registerResult.Succeeded.Should().BeFalse(); - registerResult.Errors.Should() - .BeEquivalentTo("Пароль должен содержать не менее 6 символов"); - registerResult.Value.Should().BeNull(); - } - - [Test] - public async Task PasswordsDoNotMatchRegisterTest() - { - var userData = GenerateRegisterViewModel(); - userData.PasswordConfirm = new Fixture().Create().Address; - var registerResult = await _authServiceClient.Register(userData); - - registerResult.Succeeded.Should().BeFalse(); - registerResult.Errors.Should() - .BeEquivalentTo("Пароли не совпадают"); - registerResult.Value.Should().BeNull(); - } - - [Test] - public async Task TestLoginUser() - { - var userData = GenerateRegisterViewModel(); - await _authServiceClient.Register(userData); + var secondRegisterResult = await _authServiceClient.Register(userData); - var loginData = GenerateLoginViewModel(userData); - var resultData = await _authServiceClient.Login(loginData); + secondRegisterResult.Succeeded.Should().BeFalse(); + secondRegisterResult.Errors.Should() + .BeEquivalentTo("Пользователь уже зарегистрирован"); - resultData.Succeeded.Should().BeTrue(); - resultData.Errors.Should().BeNullOrEmpty(); - resultData.Value.AccessToken.Should().NotBeNullOrEmpty(); + secondRegisterResult.Value.Should().BeNull(); + } - var claims = ValidateToken(resultData); - var userId = await _authServiceClient.FindByEmailAsync(userData.Email); + [Test] + public async Task WrongLengthPasswordRegisterTest() + { + var userData = GenerateRegisterViewModel(); + userData.Password = userData.Password.Substring(0, 5); + var registerResult = await _authServiceClient.Register(userData); + + registerResult.Succeeded.Should().BeFalse(); + registerResult.Errors.Should() + .BeEquivalentTo("Пароль должен содержать не менее 6 символов"); + registerResult.Value.Should().BeNull(); + } - claims[1].Value.Should().Be(userId); - claims[2].Value.Should().Be(userData.Email); - claims[3].Value.Should().Be(Roles.StudentRole); - } + [Test] + public async Task PasswordsDoNotMatchRegisterTest() + { + var userData = GenerateRegisterViewModel(); + userData.PasswordConfirm = new Fixture().Create().Address; + var registerResult = await _authServiceClient.Register(userData); + + registerResult.Succeeded.Should().BeFalse(); + registerResult.Errors.Should() + .BeEquivalentTo("Пароли не совпадают"); + registerResult.Value.Should().BeNull(); + } - [Test] - public async Task UserIsNotExistLoginTest() - { - var userData = GenerateRegisterViewModel(); - var loginData = GenerateLoginViewModel(userData); + [Test] + public async Task TestLoginUser() + { + var userData = GenerateRegisterViewModel(); + await _authServiceClient.Register(userData); - var loginResult = await _authServiceClient.Login(loginData); + var loginData = GenerateLoginViewModel(userData); + var resultData = await _authServiceClient.Login(loginData); - loginResult.Succeeded.Should().BeFalse(); - loginResult.Errors.Should() - .BeEquivalentTo("Пользователь не найден"); - loginResult.Value.Should().BeNull(); - } + resultData.Succeeded.Should().BeTrue(); + resultData.Errors.Should().BeNullOrEmpty(); + resultData.Value.AccessToken.Should().NotBeNullOrEmpty(); - [Test] - public async Task WrongPasswordLoginTest() - { - var userData = GenerateRegisterViewModel(); - await _authServiceClient.Register(userData); + var claims = ValidateToken(resultData); + var userId = await _authServiceClient.FindByEmailAsync(userData.Email); - var loginData = GenerateLoginViewModel(userData); - loginData.Password = new Fixture().Create(); - var resultData = await _authServiceClient.Login(loginData); + claims[1].Value.Should().Be(userId); + claims[2].Value.Should().Be(userData.Email); + claims[3].Value.Should().Be(Roles.StudentRole); + } - resultData.Succeeded.Should().BeFalse(); - resultData.Errors.Should() - .BeEquivalentTo("Неправильный логин или пароль"); - resultData.Value.Should().BeNull(); - } + [Test] + public async Task UserIsNotExistLoginTest() + { + var userData = GenerateRegisterViewModel(); + var loginData = GenerateLoginViewModel(userData); - [Test] - public async Task WrongEmailLoginTest() - { - var userData = GenerateRegisterViewModel(); - await _authServiceClient.Register(userData); + var loginResult = await _authServiceClient.Login(loginData); - var loginData = GenerateLoginViewModel(userData); - loginData.Email = new Fixture().Create().Address; - var resultData = await _authServiceClient.Login(loginData); + loginResult.Succeeded.Should().BeFalse(); + loginResult.Errors.Should() + .BeEquivalentTo("Пользователь не найден"); + loginResult.Value.Should().BeNull(); + } - resultData.Succeeded.Should().BeFalse(); - resultData.Errors.Should() - .BeEquivalentTo("Пользователь не найден"); - resultData.Value.Should().BeNull(); - } + [Test] + public async Task WrongPasswordLoginTest() + { + var userData = GenerateRegisterViewModel(); + await _authServiceClient.Register(userData); - [Test] - public async Task TestEditAccountData() - { - var userData = GenerateRegisterViewModel(); - await _authServiceClient.Register(userData); + var loginData = GenerateLoginViewModel(userData); + loginData.Password = new Fixture().Create(); + var resultData = await _authServiceClient.Login(loginData); - var editData = GenerateEditAccountViewModel(userData); - var userId = await _authServiceClient.FindByEmailAsync(userData.Email); - var result = await _authServiceClient.Edit(editData, userId); + resultData.Succeeded.Should().BeFalse(); + resultData.Errors.Should() + .BeEquivalentTo("Неправильный логин или пароль"); + resultData.Value.Should().BeNull(); + } - result.Succeeded.Should().BeTrue(); - result.Errors.Should().BeNullOrEmpty(); + [Test] + public async Task WrongEmailLoginTest() + { + var userData = GenerateRegisterViewModel(); + await _authServiceClient.Register(userData); - var resultData = await _authServiceClient.GetAccountData(userId); + var loginData = GenerateLoginViewModel(userData); + loginData.Email = new Fixture().Create().Address; + var resultData = await _authServiceClient.Login(loginData); - resultData.Should().BeEquivalentTo(editData, options => - options.ExcludingMissingMembers()); - } + resultData.Succeeded.Should().BeFalse(); + resultData.Errors.Should() + .BeEquivalentTo("Пользователь не найден"); + resultData.Value.Should().BeNull(); + } - [Test] - public async Task TestEditPassword() - { - var userData = GenerateRegisterViewModel(); - await _authServiceClient.Register(userData); + [Test] + public async Task TestEditAccountData() + { + var userData = GenerateRegisterViewModel(); + await _authServiceClient.Register(userData); - var editData = GenerateEditViewModel(userData); - var userId = await _authServiceClient.FindByEmailAsync(userData.Email); - var resultData = await _authServiceClient.Edit(editData, userId); + var editData = GenerateEditAccountViewModel(userData); + var userId = await _authServiceClient.FindByEmailAsync(userData.Email); + var result = await _authServiceClient.Edit(editData, userId); - resultData.Succeeded.Should().BeTrue(); - resultData.Errors.Should().BeNullOrEmpty(); + result.Succeeded.Should().BeTrue(); + result.Errors.Should().BeNullOrEmpty(); - var loginData = GenerateLoginViewModel(userData); - var failedResult = await _authServiceClient.Login(loginData); + var resultData = await _authServiceClient.GetAccountData(userId); - failedResult.Succeeded.Should().BeFalse(); - failedResult.Errors.Should() - .BeEquivalentTo("Неправильный логин или пароль"); + resultData.Should().BeEquivalentTo(editData, options => + options.ExcludingMissingMembers()); + } - loginData.Password = editData.NewPassword; - var result = await _authServiceClient.Login(loginData); + [Test] + public async Task TestEditPassword() + { + var userData = GenerateRegisterViewModel(); + await _authServiceClient.Register(userData); - result.Succeeded.Should().BeTrue(); - result.Errors.Should().BeNullOrEmpty(); - } + var editData = GenerateEditViewModel(userData); + var userId = await _authServiceClient.FindByEmailAsync(userData.Email); + var resultData = await _authServiceClient.Edit(editData, userId); - [Test] - public async Task EditAccountDataForUserThatDoesNotExistTest() - { - var userData = GenerateRegisterViewModel(); - var editData = GenerateEditAccountViewModel(userData); - var userId = new Fixture().Create(); + resultData.Succeeded.Should().BeTrue(); + resultData.Errors.Should().BeNullOrEmpty(); - var result = await _authServiceClient.Edit(editData, userId); + var loginData = GenerateLoginViewModel(userData); + var failedResult = await _authServiceClient.Login(loginData); - result.Succeeded.Should().BeFalse(); - result.Errors.Should() - .BeEquivalentTo("Пользователь не найден"); - } + failedResult.Succeeded.Should().BeFalse(); + failedResult.Errors.Should() + .BeEquivalentTo("Неправильный логин или пароль"); - [Test] - public async Task EditAccountDataForUserWithWrongCurrentPasswordTest() - { - var userData = GenerateRegisterViewModel(); - await _authServiceClient.Register(userData); - var editData = GenerateEditAccountViewModel(userData); - editData.CurrentPassword = new Fixture().Create(); - var userId = await _authServiceClient.FindByEmailAsync(userData.Email); + loginData.Password = editData.NewPassword; + var result = await _authServiceClient.Login(loginData); - var result = await _authServiceClient.Edit(editData, userId); + result.Succeeded.Should().BeTrue(); + result.Errors.Should().BeNullOrEmpty(); + } - result.Succeeded.Should().BeFalse(); - result.Errors.Should() - .BeEquivalentTo("Неправильный логин или пароль"); - } + [Test] + public async Task EditAccountDataForUserThatDoesNotExistTest() + { + var userData = GenerateRegisterViewModel(); + var editData = GenerateEditAccountViewModel(userData); + var userId = new Fixture().Create(); - [Test] - public async Task TestInviteNewLecturer() - { - var userData = GenerateRegisterViewModel(); - await _authServiceClient.Register(userData); + var result = await _authServiceClient.Edit(editData, userId); - var inviteLecturerData = GenerateInviteNewLecturerViewModel(userData); - var resultData = await _authServiceClient.InviteNewLecturer(inviteLecturerData); + result.Succeeded.Should().BeFalse(); + result.Errors.Should() + .BeEquivalentTo("Пользователь не найден"); + } - resultData.Succeeded.Should().BeTrue(); - resultData.Errors.Should().BeNullOrEmpty(); + [Test] + public async Task EditAccountDataForUserWithWrongCurrentPasswordTest() + { + var userData = GenerateRegisterViewModel(); + await _authServiceClient.Register(userData); + var editData = GenerateEditAccountViewModel(userData); + editData.CurrentPassword = new Fixture().Create(); + var userId = await _authServiceClient.FindByEmailAsync(userData.Email); - var userId = await _authServiceClient.FindByEmailAsync(userData.Email); - var newUserData = await _authServiceClient.GetAccountData(userId); + var result = await _authServiceClient.Edit(editData, userId); - newUserData.Role.Should().Be(Roles.LecturerRole); - } + result.Succeeded.Should().BeFalse(); + result.Errors.Should() + .BeEquivalentTo("Неправильный логин или пароль"); + } - [Test] - public async Task TestInviteNewLecturerForUserThatDoesNotExist() - { - var userData = GenerateRegisterViewModel(); - var inviteLecturerData = GenerateInviteNewLecturerViewModel(userData); + [Test] + public async Task TestInviteNewLecturer() + { + var userData = GenerateRegisterViewModel(); + await _authServiceClient.Register(userData); - var resultData = await _authServiceClient.InviteNewLecturer(inviteLecturerData); + var inviteLecturerData = GenerateInviteNewLecturerViewModel(userData); + var resultData = await _authServiceClient.InviteNewLecturer(inviteLecturerData); - resultData.Succeeded.Should().BeFalse(); - resultData.Errors.Should() - .BeEquivalentTo("Пользователь не найден"); - } + resultData.Succeeded.Should().BeTrue(); + resultData.Errors.Should().BeNullOrEmpty(); - [Test] - public async Task TestInviteNewLecturerForUserThatAlreadyLecturer() - { - var userData = GenerateRegisterViewModel(); - await _authServiceClient.Register(userData); + var userId = await _authServiceClient.FindByEmailAsync(userData.Email); + var newUserData = await _authServiceClient.GetAccountData(userId); - var inviteLecturerData = GenerateInviteNewLecturerViewModel(userData); - var resultData = await _authServiceClient.InviteNewLecturer(inviteLecturerData); + newUserData.Role.Should().Be(Roles.LecturerRole); + } - resultData.Succeeded.Should().BeTrue(); - resultData.Errors.Should().BeNullOrEmpty(); + [Test] + public async Task TestInviteNewLecturerForUserThatDoesNotExist() + { + var userData = GenerateRegisterViewModel(); + var inviteLecturerData = GenerateInviteNewLecturerViewModel(userData); - var result = await _authServiceClient.InviteNewLecturer(inviteLecturerData); + var resultData = await _authServiceClient.InviteNewLecturer(inviteLecturerData); - result.Succeeded.Should().BeFalse(); - result.Errors.Should() - .BeEquivalentTo("Пользователь уже является преподавателем"); - } + resultData.Succeeded.Should().BeFalse(); + resultData.Errors.Should() + .BeEquivalentTo("Пользователь не найден"); + } - [Test] - public async Task TestFindByEmail() - { - var userData = GenerateRegisterViewModel(); - await _authServiceClient.Register(userData); + [Test] + public async Task TestInviteNewLecturerForUserThatAlreadyLecturer() + { + var userData = GenerateRegisterViewModel(); + await _authServiceClient.Register(userData); - var userId = await _authServiceClient.FindByEmailAsync(userData.Email); + var inviteLecturerData = GenerateInviteNewLecturerViewModel(userData); + var resultData = await _authServiceClient.InviteNewLecturer(inviteLecturerData); - userId.Should().NotBeNullOrEmpty(); - } + resultData.Succeeded.Should().BeTrue(); + resultData.Errors.Should().BeNullOrEmpty(); - [Test] - public async Task TestFindByEmailForUserThatDoesNotExist() - { - var userData = GenerateRegisterViewModel(); + var result = await _authServiceClient.InviteNewLecturer(inviteLecturerData); - var userId = await _authServiceClient.FindByEmailAsync(userData.Email); + result.Succeeded.Should().BeFalse(); + result.Errors.Should() + .BeEquivalentTo("Пользователь уже является преподавателем"); + } - userId.Should().BeNullOrEmpty(); - } + [Test] + public async Task TestFindByEmail() + { + var userData = GenerateRegisterViewModel(); + await _authServiceClient.Register(userData); - [Test] - public async Task TestGetAllStudents() - { - var firstUser = GenerateRegisterViewModel(); - var secondUser = GenerateRegisterViewModel(); + var userId = await _authServiceClient.FindByEmailAsync(userData.Email); - var firstResult = await _authServiceClient.Register(firstUser); - var secondResult = await _authServiceClient.Register(secondUser); + userId.Should().NotBeNullOrEmpty(); + } - firstResult.Succeeded.Should().BeTrue(); - secondResult.Succeeded.Should().BeTrue(); + [Test] + public async Task TestFindByEmailForUserThatDoesNotExist() + { + var userData = GenerateRegisterViewModel(); - var allStudents = await _authServiceClient.GetAllStudents(); + var userId = await _authServiceClient.FindByEmailAsync(userData.Email); - allStudents.Should().ContainEquivalentOf(firstUser, options => - options.ExcludingMissingMembers()); - allStudents.Should().ContainEquivalentOf(secondUser, options => - options.ExcludingMissingMembers()); + userId.Should().BeNullOrEmpty(); + } - var firstLecturerData = GenerateInviteNewLecturerViewModel(firstUser); - var secondLecturerData = GenerateInviteNewLecturerViewModel(secondUser); - var firstLecturer = await _authServiceClient.InviteNewLecturer(firstLecturerData); - var secondLecturer = await _authServiceClient.InviteNewLecturer(secondLecturerData); + [Test] + public async Task TestGetAllStudents() + { + var firstUser = GenerateRegisterViewModel(); + var secondUser = GenerateRegisterViewModel(); - firstLecturer.Succeeded.Should().BeTrue(); - secondLecturer.Succeeded.Should().BeTrue(); + var firstResult = await _authServiceClient.Register(firstUser); + var secondResult = await _authServiceClient.Register(secondUser); - var newStudents = await _authServiceClient.GetAllStudents(); + firstResult.Succeeded.Should().BeTrue(); + secondResult.Succeeded.Should().BeTrue(); - newStudents.Should().NotContainEquivalentOf(firstUser, options => - options.ExcludingMissingMembers()); - newStudents.Should().NotContainEquivalentOf(secondUser, options => - options.ExcludingMissingMembers()); - } + var allStudents = await _authServiceClient.GetAllStudents(); - [Test] - public async Task TestGetAllLecturers() - { - var firstUser = GenerateRegisterViewModel(); - var secondUser = GenerateRegisterViewModel(); + allStudents.Should().ContainEquivalentOf(firstUser, options => + options.ExcludingMissingMembers()); + allStudents.Should().ContainEquivalentOf(secondUser, options => + options.ExcludingMissingMembers()); - var firstResult = await _authServiceClient.Register(firstUser); - var secondResult = await _authServiceClient.Register(secondUser); + var firstLecturerData = GenerateInviteNewLecturerViewModel(firstUser); + var secondLecturerData = GenerateInviteNewLecturerViewModel(secondUser); + var firstLecturer = await _authServiceClient.InviteNewLecturer(firstLecturerData); + var secondLecturer = await _authServiceClient.InviteNewLecturer(secondLecturerData); - firstResult.Succeeded.Should().BeTrue(); - secondResult.Succeeded.Should().BeTrue(); + firstLecturer.Succeeded.Should().BeTrue(); + secondLecturer.Succeeded.Should().BeTrue(); - var allLecturers = await _authServiceClient.GetAllLecturers(); + var newStudents = await _authServiceClient.GetAllStudents(); - allLecturers.Should().NotContainEquivalentOf(firstUser, options => - options.ExcludingMissingMembers()); - allLecturers.Should().NotContainEquivalentOf(secondUser, options => - options.ExcludingMissingMembers()); + newStudents.Should().NotContainEquivalentOf(firstUser, options => + options.ExcludingMissingMembers()); + newStudents.Should().NotContainEquivalentOf(secondUser, options => + options.ExcludingMissingMembers()); + } - var firstLecturerData = GenerateInviteNewLecturerViewModel(firstUser); - var secondLecturerData = GenerateInviteNewLecturerViewModel(secondUser); - var firstLecturer = await _authServiceClient.InviteNewLecturer(firstLecturerData); - var secondLecturer = await _authServiceClient.InviteNewLecturer(secondLecturerData); + [Test] + public async Task TestGetAllLecturers() + { + var firstUser = GenerateRegisterViewModel(); + var secondUser = GenerateRegisterViewModel(); - firstLecturer.Succeeded.Should().BeTrue(); - secondLecturer.Succeeded.Should().BeTrue(); + var firstResult = await _authServiceClient.Register(firstUser); + var secondResult = await _authServiceClient.Register(secondUser); - var newLecturers = await _authServiceClient.GetAllLecturers(); + firstResult.Succeeded.Should().BeTrue(); + secondResult.Succeeded.Should().BeTrue(); - newLecturers.Should().ContainEquivalentOf(firstUser, options => - options.ExcludingMissingMembers()); - newLecturers.Should().ContainEquivalentOf(secondUser, options => - options.ExcludingMissingMembers()); - } + var allLecturers = await _authServiceClient.GetAllLecturers(); - [Test] - public async Task TestGetAccountData() - { - var userData = GenerateRegisterViewModel(); - await _authServiceClient.Register(userData); + allLecturers.Should().NotContainEquivalentOf(firstUser, options => + options.ExcludingMissingMembers()); + allLecturers.Should().NotContainEquivalentOf(secondUser, options => + options.ExcludingMissingMembers()); - var userId = await _authServiceClient.FindByEmailAsync(userData.Email); - var resultData = await _authServiceClient.GetAccountData(userId); + var firstLecturerData = GenerateInviteNewLecturerViewModel(firstUser); + var secondLecturerData = GenerateInviteNewLecturerViewModel(secondUser); + var firstLecturer = await _authServiceClient.InviteNewLecturer(firstLecturerData); + var secondLecturer = await _authServiceClient.InviteNewLecturer(secondLecturerData); - resultData.Should().BeEquivalentTo(userData, options => - options.ExcludingMissingMembers()); - } + firstLecturer.Succeeded.Should().BeTrue(); + secondLecturer.Succeeded.Should().BeTrue(); - [Test] - public async Task TestGetAccountDataForUserThatDoesNotExist() - { - var resultData = await _authServiceClient.GetAccountData(new Fixture().Create()); + var newLecturers = await _authServiceClient.GetAllLecturers(); + + newLecturers.Should().ContainEquivalentOf(firstUser, options => + options.ExcludingMissingMembers()); + newLecturers.Should().ContainEquivalentOf(secondUser, options => + options.ExcludingMissingMembers()); + } + + [Test] + public async Task TestGetAccountData() + { + var userData = GenerateRegisterViewModel(); + await _authServiceClient.Register(userData); + + var userId = await _authServiceClient.FindByEmailAsync(userData.Email); + var resultData = await _authServiceClient.GetAccountData(userId); + + resultData.Should().BeEquivalentTo(userData, options => + options.ExcludingMissingMembers()); + } + + [Test] + public async Task TestGetAccountDataForUserThatDoesNotExist() + { + var resultData = await _authServiceClient.GetAccountData(new Fixture().Create()); - resultData.Should().BeNull(); - } + resultData.Should().BeNull(); } -} +} \ No newline at end of file diff --git a/HwProj.AuthService/HwProj.AuthService.IntegrationTests/HwProj.AuthService.IntegrationTests.csproj b/HwProj.AuthService/HwProj.AuthService.IntegrationTests/HwProj.AuthService.IntegrationTests.csproj index c36c33c3b..53d295526 100644 --- a/HwProj.AuthService/HwProj.AuthService.IntegrationTests/HwProj.AuthService.IntegrationTests.csproj +++ b/HwProj.AuthService/HwProj.AuthService.IntegrationTests/HwProj.AuthService.IntegrationTests.csproj @@ -1,7 +1,7 @@ - netcoreapp2.2 + net6.0 false @@ -20,6 +20,7 @@ + diff --git a/HwProj.Common/HwProj.Exceptions/ForbiddenException.cs b/HwProj.Common/HwProj.Exceptions/ForbiddenException.cs index b89f9b539..e97cf8f1f 100644 --- a/HwProj.Common/HwProj.Exceptions/ForbiddenException.cs +++ b/HwProj.Common/HwProj.Exceptions/ForbiddenException.cs @@ -1,13 +1,12 @@ using System; -namespace HwProj.Exceptions +namespace HwProj.Exceptions; + +public class ForbiddenException : Exception { - public class ForbiddenException : Exception - { - public ForbiddenException() : base() { } - public ForbiddenException(string message) : base(message) { } - public ForbiddenException(string message, Exception inner) : base(message, inner) { } - protected ForbiddenException(System.Runtime.Serialization.SerializationInfo info, - System.Runtime.Serialization.StreamingContext context) : base(info, context) { } - } -} \ No newline at end of file + public ForbiddenException() { } + public ForbiddenException(string message) : base(message) { } + public ForbiddenException(string message, Exception inner) : base(message, inner) { } + protected ForbiddenException(System.Runtime.Serialization.SerializationInfo info, + System.Runtime.Serialization.StreamingContext context) : base(info, context) { } +} diff --git a/HwProj.Common/HwProj.Exceptions/HwProj.Exceptions.csproj b/HwProj.Common/HwProj.Exceptions/HwProj.Exceptions.csproj index 054441486..019975c7d 100644 --- a/HwProj.Common/HwProj.Exceptions/HwProj.Exceptions.csproj +++ b/HwProj.Common/HwProj.Exceptions/HwProj.Exceptions.csproj @@ -1,9 +1,9 @@ - netcoreapp2.2 + net6.0 $(CSharpLanguageVersion) $(NullableReferenceTypes) - \ No newline at end of file + diff --git a/HwProj.Common/HwProj.HttpUtils/HwProj.HttpUtils.csproj b/HwProj.Common/HwProj.HttpUtils/HwProj.HttpUtils.csproj index 92a4822f2..73a2d16e2 100644 --- a/HwProj.Common/HwProj.HttpUtils/HwProj.HttpUtils.csproj +++ b/HwProj.Common/HwProj.HttpUtils/HwProj.HttpUtils.csproj @@ -1,14 +1,14 @@  - netcoreapp2.2 + net6.0 $(CSharpLanguageVersion) $(NullableReferenceTypes) - + diff --git a/HwProj.Common/HwProj.HttpUtils/HwProjJsonSerializerSettings.cs b/HwProj.Common/HwProj.HttpUtils/HwProjJsonSerializerSettings.cs index 63b6e44b4..832cfaffa 100644 --- a/HwProj.Common/HwProj.HttpUtils/HwProjJsonSerializerSettings.cs +++ b/HwProj.Common/HwProj.HttpUtils/HwProjJsonSerializerSettings.cs @@ -2,23 +2,22 @@ using Newtonsoft.Json.Converters; using Newtonsoft.Json.Serialization; -namespace HwProj.HttpUtils +namespace HwProj.HttpUtils; + +public class HwProjJsonSerializerSettings { - public class HwProjJsonSerializerSettings + static HwProjJsonSerializerSettings() { - static HwProjJsonSerializerSettings() + Settings = new JsonSerializerSettings { - Settings = new JsonSerializerSettings() + ContractResolver = new CamelCasePropertyNamesContractResolver(), + NullValueHandling = NullValueHandling.Ignore, + Converters = new JsonConverter[] { - ContractResolver = new CamelCasePropertyNamesContractResolver(), - NullValueHandling = NullValueHandling.Ignore, - Converters = new JsonConverter[] - { - new StringEnumConverter(new CamelCaseNamingStrategy()), - } - }; - } - - public static JsonSerializerSettings Settings { get; } + new StringEnumConverter(new CamelCaseNamingStrategy()), + } + }; } -} \ No newline at end of file + + public static JsonSerializerSettings Settings { get; } +} diff --git a/HwProj.Common/HwProj.HttpUtils/JsonConvertExtensions.cs b/HwProj.Common/HwProj.HttpUtils/JsonConvertExtensions.cs index 6fdfc7c22..294e18abc 100644 --- a/HwProj.Common/HwProj.HttpUtils/JsonConvertExtensions.cs +++ b/HwProj.Common/HwProj.HttpUtils/JsonConvertExtensions.cs @@ -2,14 +2,13 @@ using System.Threading.Tasks; using Newtonsoft.Json; -namespace HwProj.HttpUtils +namespace HwProj.HttpUtils; + +public static class JsonConvertExtensions { - public static class JsonConvertExtensions + public static async Task DeserializeAsync(this HttpResponseMessage response) { - public static async Task DeserializeAsync(this HttpResponseMessage response) - { - var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false); - return JsonConvert.DeserializeObject(content, HwProjJsonSerializerSettings.Settings); - } + var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false); + return JsonConvert.DeserializeObject(content, HwProjJsonSerializerSettings.Settings); } } \ No newline at end of file diff --git a/HwProj.Common/HwProj.HttpUtils/RequestHeaderBuilder.cs b/HwProj.Common/HwProj.HttpUtils/RequestHeaderBuilder.cs index d0996e85e..5f8183550 100644 --- a/HwProj.Common/HwProj.HttpUtils/RequestHeaderBuilder.cs +++ b/HwProj.Common/HwProj.HttpUtils/RequestHeaderBuilder.cs @@ -1,13 +1,12 @@ using System.Net.Http; using Microsoft.AspNetCore.Http; -namespace HwProj.HttpUtils +namespace HwProj.HttpUtils; + +public static class RequestHeaderBuilder { - public static class RequestHeaderBuilder + public static void AddUserId(this HttpRequestMessage request, IHttpContextAccessor httpContextAccessor) { - public static void AddUserId(this HttpRequestMessage request, IHttpContextAccessor httpContextAccessor) - { - request.Headers.Add("UserId", httpContextAccessor.HttpContext.User.FindFirst("_id").Value); - } + request.Headers.Add("UserId", httpContextAccessor.HttpContext.User.FindFirst("_id").Value); } } diff --git a/HwProj.Common/HwProj.HttpUtils/RequestUrlBuilder.cs b/HwProj.Common/HwProj.HttpUtils/RequestUrlBuilder.cs index acb4dc26b..e01b52126 100644 --- a/HwProj.Common/HwProj.HttpUtils/RequestUrlBuilder.cs +++ b/HwProj.Common/HwProj.HttpUtils/RequestUrlBuilder.cs @@ -1,47 +1,46 @@ using System; using System.Text; -namespace HwProj.HttpUtils +namespace HwProj.HttpUtils; + +public class RequestUrlBuilder { - public class RequestUrlBuilder + private readonly StringBuilder _uriBuilder = new(); + private bool _withQuery; + + public RequestUrlBuilder(Uri baseUri) { - private readonly StringBuilder _uriBuilder = new StringBuilder(); - private bool _withQuery; + _uriBuilder.Append(baseUri.AbsolutePath); + } - public RequestUrlBuilder(Uri baseUri) - { - _uriBuilder.Append(baseUri.AbsolutePath); - } + public RequestUrlBuilder AppendToPath(string value) + { + _uriBuilder.Append($"/{value}"); + return this; + } - public RequestUrlBuilder AppendToPath(string value) - { - _uriBuilder.Append($"/{value}"); - return this; - } + public RequestUrlBuilder AppendToPath(T value) + { + _uriBuilder.Append($"/{value}"); + return this; + } - public RequestUrlBuilder AppendToPath(T value) + public RequestUrlBuilder AppendToQuery(string argName, string value) + { + if (_withQuery) { - _uriBuilder.Append($"/{value}"); - return this; + _uriBuilder.Append($"&{argName}={value}"); } - - public RequestUrlBuilder AppendToQuery(string argName, string value) + else { - if (_withQuery) - { - _uriBuilder.Append($"&{argName}={value}"); - } - else - { - _uriBuilder.Append($"?{argName}={value}"); - _withQuery = true; - } - return this; + _uriBuilder.Append($"?{argName}={value}"); + _withQuery = true; } + return this; + } - public string Build() - { - return _uriBuilder.ToString(); - } + public string Build() + { + return _uriBuilder.ToString(); } -} \ No newline at end of file +} diff --git a/HwProj.Common/HwProj.Models/AuthService/DTO/AccountDataDTO.cs b/HwProj.Common/HwProj.Models/AuthService/DTO/AccountDataDTO.cs index 1b121af8a..d819ef650 100644 --- a/HwProj.Common/HwProj.Models/AuthService/DTO/AccountDataDTO.cs +++ b/HwProj.Common/HwProj.Models/AuthService/DTO/AccountDataDTO.cs @@ -1,26 +1,25 @@ -namespace HwProj.Models.AuthService.DTO +namespace HwProj.Models.AuthService.DTO; + +public class AccountDataDto { - public class AccountDataDto - { - public string UserId { get; set; } - public string Name { get; set; } - public string Surname { get; set; } - public string MiddleName { get; set; } - public string Email { get; } - public string Role { get; } - public bool IsExternalAuth { get; } + public string UserId { get; set; } + public string Name { get; set; } + public string Surname { get; set; } + public string MiddleName { get; set; } + public string Email { get; } + public string Role { get; } + public bool IsExternalAuth { get; } - public AccountDataDto(string userId, string name, string surname, string email, string role, - bool isExternalAuth, - string middleName = "") - { - UserId = userId; - Name = name; - Surname = surname; - MiddleName = middleName; - Email = email; - Role = role; - IsExternalAuth = isExternalAuth; - } + public AccountDataDto(string userId, string name, string surname, string email, string role, + bool isExternalAuth, + string middleName = "") + { + UserId = userId; + Name = name; + Surname = surname; + MiddleName = middleName; + Email = email; + Role = role; + IsExternalAuth = isExternalAuth; } -} +} \ No newline at end of file diff --git a/HwProj.Common/HwProj.Models/AuthService/DTO/EditDataDTO.cs b/HwProj.Common/HwProj.Models/AuthService/DTO/EditDataDTO.cs index c4f70f7c8..127304d46 100644 --- a/HwProj.Common/HwProj.Models/AuthService/DTO/EditDataDTO.cs +++ b/HwProj.Common/HwProj.Models/AuthService/DTO/EditDataDTO.cs @@ -1,11 +1,10 @@ -namespace HwProj.Models.AuthService.DTO +namespace HwProj.Models.AuthService.DTO; + +public class EditDataDTO { - public class EditDataDTO - { - public string Name { get; set; } - public string Surname { get; set; } - public string MiddleName { get; set; } - public string CurrentPassword { get; set; } - public string NewPassword { get; set; } - } -} + public string Name { get; set; } + public string Surname { get; set; } + public string MiddleName { get; set; } + public string CurrentPassword { get; set; } + public string NewPassword { get; set; } +} \ No newline at end of file diff --git a/HwProj.Common/HwProj.Models/AuthService/DTO/RegisterDataDTO.cs b/HwProj.Common/HwProj.Models/AuthService/DTO/RegisterDataDTO.cs index cf6a9d217..d2df895c5 100644 --- a/HwProj.Common/HwProj.Models/AuthService/DTO/RegisterDataDTO.cs +++ b/HwProj.Common/HwProj.Models/AuthService/DTO/RegisterDataDTO.cs @@ -1,13 +1,12 @@ -namespace HwProj.Models.AuthService.DTO +namespace HwProj.Models.AuthService.DTO; + +public class RegisterDataDTO { - public class RegisterDataDTO - { - public string Name { get; set; } - public string Surname { get; set; } - public string MiddleName { get; set; } - public string Email { get; set; } - public string Password { get; set; } - public string PasswordConfirm { get; set; } - public bool IsExternalAuth { get; set; } - } -} + public string Name { get; set; } + public string Surname { get; set; } + public string MiddleName { get; set; } + public string Email { get; set; } + public string Password { get; set; } + public string PasswordConfirm { get; set; } + public bool IsExternalAuth { get; set; } +} \ No newline at end of file diff --git a/HwProj.Common/HwProj.Models/AuthService/DTO/TokenCredentials.cs b/HwProj.Common/HwProj.Models/AuthService/DTO/TokenCredentials.cs index 8d0d8ad7f..75bb93110 100644 --- a/HwProj.Common/HwProj.Models/AuthService/DTO/TokenCredentials.cs +++ b/HwProj.Common/HwProj.Models/AuthService/DTO/TokenCredentials.cs @@ -1,7 +1,6 @@ -namespace HwProj.Models.AuthService.DTO +namespace HwProj.Models.AuthService.DTO; + +public class TokenCredentials { - public class TokenCredentials - { - public string AccessToken { get; set; } - } -} + public string AccessToken { get; set; } +} \ No newline at end of file diff --git a/HwProj.Common/HwProj.Models/AuthService/ViewModels/ChangeEmailViewModel.cs b/HwProj.Common/HwProj.Models/AuthService/ViewModels/ChangeEmailViewModel.cs index 69fa82f99..e3813a2fd 100644 --- a/HwProj.Common/HwProj.Models/AuthService/ViewModels/ChangeEmailViewModel.cs +++ b/HwProj.Common/HwProj.Models/AuthService/ViewModels/ChangeEmailViewModel.cs @@ -1,11 +1,10 @@ using System.ComponentModel.DataAnnotations; -namespace HwProj.Models.AuthService.ViewModels +namespace HwProj.Models.AuthService.ViewModels; + +public class ChangeEmailViewModel { - public class ChangeEmailViewModel - { - [Required] - [EmailAddress] - public string NewEmail { get; set; } - } -} + [Required] + [EmailAddress] + public string NewEmail { get; set; } +} \ No newline at end of file diff --git a/HwProj.Common/HwProj.Models/AuthService/ViewModels/DeleteViewModel.cs b/HwProj.Common/HwProj.Models/AuthService/ViewModels/DeleteViewModel.cs index ae41d4ea2..773a5b1ff 100644 --- a/HwProj.Common/HwProj.Models/AuthService/ViewModels/DeleteViewModel.cs +++ b/HwProj.Common/HwProj.Models/AuthService/ViewModels/DeleteViewModel.cs @@ -1,11 +1,10 @@ using System.ComponentModel.DataAnnotations; -namespace HwProj.Models.AuthService.ViewModels +namespace HwProj.Models.AuthService.ViewModels; + +public class DeleteViewModel { - public class DeleteViewModel - { - [Required] - [DataType(DataType.Password)] - public string Password { get; set; } - } -} + [Required] + [DataType(DataType.Password)] + public string Password { get; set; } +} \ No newline at end of file diff --git a/HwProj.Common/HwProj.Models/AuthService/ViewModels/EditAccountViewModel.cs b/HwProj.Common/HwProj.Models/AuthService/ViewModels/EditAccountViewModel.cs index fc879723b..a41ddcff8 100644 --- a/HwProj.Common/HwProj.Models/AuthService/ViewModels/EditAccountViewModel.cs +++ b/HwProj.Common/HwProj.Models/AuthService/ViewModels/EditAccountViewModel.cs @@ -1,24 +1,23 @@ using System.ComponentModel.DataAnnotations; -namespace HwProj.Models.AuthService.ViewModels +namespace HwProj.Models.AuthService.ViewModels; + +public class EditAccountViewModel { - public class EditAccountViewModel - { - [Required] - public string Name { get; set; } + [Required] + public string Name { get; set; } - [Required] - public string Surname { get; set; } + [Required] + public string Surname { get; set; } - public string MiddleName { get; set; } + public string MiddleName { get; set; } - [Required] - [DataType(DataType.Password)] - public string CurrentPassword { get; set; } + [Required] + [DataType(DataType.Password)] + public string CurrentPassword { get; set; } - [Required] - [DataType(DataType.Password)] - [StringLength(100, ErrorMessage = "Пароль должен содержать не менее 6 символов", MinimumLength = 6)] - public string NewPassword { get; set; } - } -} + [Required] + [DataType(DataType.Password)] + [StringLength(100, ErrorMessage = "Пароль должен содержать не менее 6 символов", MinimumLength = 6)] + public string NewPassword { get; set; } +} \ No newline at end of file diff --git a/HwProj.Common/HwProj.Models/AuthService/ViewModels/EditExternalViewModel.cs b/HwProj.Common/HwProj.Models/AuthService/ViewModels/EditExternalViewModel.cs index d762e2db3..4161d924e 100644 --- a/HwProj.Common/HwProj.Models/AuthService/ViewModels/EditExternalViewModel.cs +++ b/HwProj.Common/HwProj.Models/AuthService/ViewModels/EditExternalViewModel.cs @@ -1,15 +1,14 @@ using System.ComponentModel.DataAnnotations; -namespace HwProj.Models.AuthService.ViewModels +namespace HwProj.Models.AuthService.ViewModels; + +public class EditExternalViewModel { - public class EditExternalViewModel - { - [Required] - public string Name { get; set; } + [Required] + public string Name { get; set; } - [Required] - public string Surname { get; set; } + [Required] + public string Surname { get; set; } - public string MiddleName { get; set; } - } -} + public string MiddleName { get; set; } +} \ No newline at end of file diff --git a/HwProj.Common/HwProj.Models/AuthService/ViewModels/InviteLecturerViewModel.cs b/HwProj.Common/HwProj.Models/AuthService/ViewModels/InviteLecturerViewModel.cs index 0d29c81e8..640390e17 100644 --- a/HwProj.Common/HwProj.Models/AuthService/ViewModels/InviteLecturerViewModel.cs +++ b/HwProj.Common/HwProj.Models/AuthService/ViewModels/InviteLecturerViewModel.cs @@ -1,11 +1,10 @@ using System.ComponentModel.DataAnnotations; -namespace HwProj.Models.AuthService.ViewModels +namespace HwProj.Models.AuthService.ViewModels; + +public class InviteLecturerViewModel { - public class InviteLecturerViewModel - { - [Required] - [EmailAddress] - public string Email { get; set; } - } -} + [Required] + [EmailAddress] + public string Email { get; set; } +} \ No newline at end of file diff --git a/HwProj.Common/HwProj.Models/AuthService/ViewModels/LoginViewModel.cs b/HwProj.Common/HwProj.Models/AuthService/ViewModels/LoginViewModel.cs index 8db70d128..f6dd412dd 100644 --- a/HwProj.Common/HwProj.Models/AuthService/ViewModels/LoginViewModel.cs +++ b/HwProj.Common/HwProj.Models/AuthService/ViewModels/LoginViewModel.cs @@ -1,18 +1,17 @@ using System.ComponentModel.DataAnnotations; -namespace HwProj.Models.AuthService.ViewModels +namespace HwProj.Models.AuthService.ViewModels; + +public class LoginViewModel { - public class LoginViewModel - { - [Required] - [DataType(DataType.EmailAddress)] - public string Email { get; set; } + [Required] + [DataType(DataType.EmailAddress)] + public string Email { get; set; } - [Required] - [DataType(DataType.Password)] - public string Password { get; set; } + [Required] + [DataType(DataType.Password)] + public string Password { get; set; } - [Required] - public bool RememberMe { get; set; } - } + [Required] + public bool RememberMe { get; set; } } diff --git a/HwProj.Common/HwProj.Models/AuthService/ViewModels/RegisterViewModel.cs b/HwProj.Common/HwProj.Models/AuthService/ViewModels/RegisterViewModel.cs index 82208ee90..68ce37afd 100644 --- a/HwProj.Common/HwProj.Models/AuthService/ViewModels/RegisterViewModel.cs +++ b/HwProj.Common/HwProj.Models/AuthService/ViewModels/RegisterViewModel.cs @@ -1,32 +1,26 @@ using System.ComponentModel.DataAnnotations; -using Microsoft.AspNetCore.Mvc.ModelBinding.Validation; -namespace HwProj.Models.AuthService.ViewModels +namespace HwProj.Models.AuthService.ViewModels; + +public class RegisterViewModel { - public class RegisterViewModel - { - [Required] - public string Name { get; set; } + [Required] public string Name { get; set; } - [Required] - public string Surname { get; set; } + [Required] public string Surname { get; set; } - public string MiddleName { get; set; } + public string MiddleName { get; set; } - [Required] - [DataType(DataType.EmailAddress)] - public string Email { get; set; } + [Required] + [DataType(DataType.EmailAddress)] + public string Email { get; set; } - [ValidateNever] - [Required] - [DataType(DataType.Password)] - //[StringLength(100, ErrorMessage = "Пароль должен содержать не менее 6 символов", MinimumLength = 6)] - public string Password { get; set; } + [Required] + [DataType(DataType.Password)] + //[StringLength(100, ErrorMessage = "Пароль должен содержать не менее 6 символов", MinimumLength = 6)] + public string Password { get; set; } - [ValidateNever] - [Required] - [DataType(DataType.Password)] - //[Compare("Password", ErrorMessage = "Пароли не совпадают")] - public string PasswordConfirm { get; set; } - } -} \ No newline at end of file + [Required] + [DataType(DataType.Password)] + [Compare("Password", ErrorMessage = "Пароли не совпадают")] + public string PasswordConfirm { get; set; } +} diff --git a/HwProj.Common/HwProj.Models/AuthService/ViewModels/User.cs b/HwProj.Common/HwProj.Models/AuthService/ViewModels/User.cs index b2975e353..49a6f8a27 100644 --- a/HwProj.Common/HwProj.Models/AuthService/ViewModels/User.cs +++ b/HwProj.Common/HwProj.Models/AuthService/ViewModels/User.cs @@ -1,21 +1,20 @@ using Microsoft.AspNetCore.Identity; -namespace HwProj.Models.AuthService.ViewModels +namespace HwProj.Models.AuthService.ViewModels; + +public class User : IdentityUser { - public class User : IdentityUser - { - public string GitHubId { get; set; } + public string GitHubId { get; set; } - public string Name { get; set; } + public string Name { get; set; } - public string Surname { get; set; } + public string Surname { get; set; } - public string MiddleName { get; set; } + public string MiddleName { get; set; } - public bool IsExternalAuth { get; set; } + public bool IsExternalAuth { get; set; } - public User() - { - } + public User() + { } -} +} \ No newline at end of file diff --git a/HwProj.Common/HwProj.Models/CoursesService/DTO/TaslDeadlineDTO.cs b/HwProj.Common/HwProj.Models/CoursesService/DTO/TaslDeadlineDTO.cs index dcaad54ef..9f83c2208 100644 --- a/HwProj.Common/HwProj.Models/CoursesService/DTO/TaslDeadlineDTO.cs +++ b/HwProj.Common/HwProj.Models/CoursesService/DTO/TaslDeadlineDTO.cs @@ -1,14 +1,13 @@ using System; -namespace HwProj.Models.CoursesService.DTO +namespace HwProj.Models.CoursesService.DTO; + +public class TaskDeadlineDto { - public class TaskDeadlineDto - { - public long TaskId { get; set; } - public string TaskTitle { get; set; } - public string CourseTitle { get; set; } - public long MaxRating { get; set; } - public DateTime PublicationDate { get; set; } - public DateTime DeadlineDate { get; set; } - } -} + public long TaskId { get; set; } + public string TaskTitle { get; set; } + public string CourseTitle { get; set; } + public long MaxRating { get; set; } + public DateTime PublicationDate { get; set; } + public DateTime DeadlineDate { get; set; } +} \ No newline at end of file diff --git a/HwProj.Common/HwProj.Models/CoursesService/DTO/UserGroupDescription.cs b/HwProj.Common/HwProj.Models/CoursesService/DTO/UserGroupDescription.cs index bacd9633b..fe586104a 100644 --- a/HwProj.Common/HwProj.Models/CoursesService/DTO/UserGroupDescription.cs +++ b/HwProj.Common/HwProj.Models/CoursesService/DTO/UserGroupDescription.cs @@ -1,18 +1,17 @@ using System.Collections.Generic; using HwProj.Models.CoursesService.ViewModels; -namespace HwProj.Models.CoursesService.DTO +namespace HwProj.Models.CoursesService.DTO; + +public class UserGroupDescription { - public class UserGroupDescription - { - public long Id { get; set; } + public long Id { get; set; } - public long CourseId { get; set; } + public long CourseId { get; set; } - public string Name { get; set; } + public string Name { get; set; } - public List Tasks { get; set; } = new List(); + public List Tasks { get; set; } = new(); - public List GroupMates { get; set; } = new List(); - } -} + public List GroupMates { get; set; } = new(); +} \ No newline at end of file diff --git a/HwProj.Common/HwProj.Models/CoursesService/ViewModels/CourseMateViewModel.cs b/HwProj.Common/HwProj.Models/CoursesService/ViewModels/CourseMateViewModel.cs index 9d28b4b26..ad5881866 100644 --- a/HwProj.Common/HwProj.Models/CoursesService/ViewModels/CourseMateViewModel.cs +++ b/HwProj.Common/HwProj.Models/CoursesService/ViewModels/CourseMateViewModel.cs @@ -1,8 +1,7 @@ -namespace HwProj.Models.CoursesService.ViewModels +namespace HwProj.Models.CoursesService.ViewModels; + +public class CourseMateViewModel { - public class CourseMateViewModel - { - public string StudentId { get; set; } - public bool IsAccepted { get; set; } - } -} + public string StudentId { get; set; } + public bool IsAccepted { get; set; } +} \ No newline at end of file diff --git a/HwProj.Common/HwProj.Models/CoursesService/ViewModels/CourseViewModels.cs b/HwProj.Common/HwProj.Models/CoursesService/ViewModels/CourseViewModels.cs index 3d0010956..ab27ad1a2 100644 --- a/HwProj.Common/HwProj.Models/CoursesService/ViewModels/CourseViewModels.cs +++ b/HwProj.Common/HwProj.Models/CoursesService/ViewModels/CourseViewModels.cs @@ -1,61 +1,60 @@ using System.ComponentModel.DataAnnotations; using HwProj.Models.AuthService.DTO; -namespace HwProj.Models.CoursesService.ViewModels +namespace HwProj.Models.CoursesService.ViewModels; + +public class CreateCourseViewModel { - public class CreateCourseViewModel - { - [Required] - [RegularExpression(@"^\S+.*", ErrorMessage = "Name shouldn't start with white spaces.")] - public string Name { get; set; } - - public string GroupName { get; set; } - - [Required] public bool IsOpen { get; set; } - } - - public class UpdateCourseViewModel - { - [Required] - [RegularExpression(@"^\S+.*", ErrorMessage = "Name shouldn't start with white spaces.")] - public string Name { get; set; } - - public string GroupName { get; set; } - - [Required] public bool IsOpen { get; set; } - - public bool IsCompleted { get; set; } - } - - public class CourseDTO : CoursePreview - { - public bool IsOpen { get; set; } - public string InviteCode { get; set; } - public CourseMateViewModel[] CourseMates { get; set; } - public HomeworkViewModel[] Homeworks { get; set; } - } - - public class CourseViewModel - { - public long Id { get; set; } - public string Name { get; set; } - public string GroupName { get; set; } - public bool IsOpen { get; set; } - public bool IsCompleted { get; set; } - - public AccountDataDto[] Mentors { get; set; } - public AccountDataDto[] AcceptedStudents { get; set; } - public AccountDataDto[] NewStudents { get; set; } - public HomeworkViewModel[] Homeworks { get; set; } - } - - // Модель для списка всех курсов - public class CoursePreview - { - public long Id { get; set; } - public string Name { get; set; } - public string GroupName { get; set; } - public bool IsCompleted { get; set; } - public string[] MentorIds { get; set; } - } + [Required] + [RegularExpression(@"^\S+.*", ErrorMessage = "Name shouldn't start with white spaces.")] + public string Name { get; set; } + + public string GroupName { get; set; } + + [Required] public bool IsOpen { get; set; } +} + +public class UpdateCourseViewModel +{ + [Required] + [RegularExpression(@"^\S+.*", ErrorMessage = "Name shouldn't start with white spaces.")] + public string Name { get; set; } + + public string GroupName { get; set; } + + [Required] public bool IsOpen { get; set; } + + public bool IsCompleted { get; set; } } + +public class CourseDTO : CoursePreview +{ + public bool IsOpen { get; set; } + public string InviteCode { get; set; } + public CourseMateViewModel[] CourseMates { get; set; } + public HomeworkViewModel[] Homeworks { get; set; } +} + +public class CourseViewModel +{ + public long Id { get; set; } + public string Name { get; set; } + public string GroupName { get; set; } + public bool IsOpen { get; set; } + public bool IsCompleted { get; set; } + + public AccountDataDto[] Mentors { get; set; } + public AccountDataDto[] AcceptedStudents { get; set; } + public AccountDataDto[] NewStudents { get; set; } + public HomeworkViewModel[] Homeworks { get; set; } +} + +// Модель для списка всех курсов +public class CoursePreview +{ + public long Id { get; set; } + public string Name { get; set; } + public string GroupName { get; set; } + public bool IsCompleted { get; set; } + public string[] MentorIds { get; set; } +} \ No newline at end of file diff --git a/HwProj.Common/HwProj.Models/CoursesService/ViewModels/GroupMateViewModel.cs b/HwProj.Common/HwProj.Models/CoursesService/ViewModels/GroupMateViewModel.cs index cade2fde1..bfce6302c 100644 --- a/HwProj.Common/HwProj.Models/CoursesService/ViewModels/GroupMateViewModel.cs +++ b/HwProj.Common/HwProj.Models/CoursesService/ViewModels/GroupMateViewModel.cs @@ -1,7 +1,6 @@ -namespace HwProj.Models.CoursesService.ViewModels +namespace HwProj.Models.CoursesService.ViewModels; + +public class GroupMateViewModel { - public class GroupMateViewModel - { - public string StudentId { get; set; } - } -} + public string StudentId { get; set; } +} \ No newline at end of file diff --git a/HwProj.Common/HwProj.Models/CoursesService/ViewModels/GroupViewModel.cs b/HwProj.Common/HwProj.Models/CoursesService/ViewModels/GroupViewModel.cs index 928c450ff..2f8763e0c 100644 --- a/HwProj.Common/HwProj.Models/CoursesService/ViewModels/GroupViewModel.cs +++ b/HwProj.Common/HwProj.Models/CoursesService/ViewModels/GroupViewModel.cs @@ -1,43 +1,42 @@ using System.Collections.Generic; using System.ComponentModel.DataAnnotations; -namespace HwProj.Models.CoursesService.ViewModels +namespace HwProj.Models.CoursesService.ViewModels; + +public class GroupViewModel { - public class GroupViewModel - { - public long Id { get; set; } + public long Id { get; set; } - public long CourseId { get; set; } + public long CourseId { get; set; } - public string Name { get; set; } + public string Name { get; set; } - public List Tasks { get; set; } = new List(); + public List Tasks { get; set; } = new(); - public List GroupMates { get; set; } = new List(); - } + public List GroupMates { get; set; } = new(); +} - public class CreateGroupViewModel - { - [Required] - [RegularExpression(@"^\S+.*", ErrorMessage = "Name shouldn't start with white spaces.")] - public string Name { get; set; } +public class CreateGroupViewModel +{ + [Required] + [RegularExpression(@"^\S+.*", ErrorMessage = "Name shouldn't start with white spaces.")] + public string Name { get; set; } - [Required] public List GroupMates { get; set; } = new List(); + [Required] public List GroupMates { get; set; } = new(); - [Required] - public long CourseId { get; set; } + [Required] + public long CourseId { get; set; } - [Required] - public List Tasks { get; set; } = new List(); - } + [Required] + public List Tasks { get; set; } = new(); +} - public class UpdateGroupViewModel - { - [RegularExpression(@"^\S+.*", ErrorMessage = "Name shouldn't start with white spaces.")] - public string Name { get; set; } +public class UpdateGroupViewModel +{ + [RegularExpression(@"^\S+.*", ErrorMessage = "Name shouldn't start with white spaces.")] + public string Name { get; set; } - public List Tasks { get; set; } = new List(); + public List Tasks { get; set; } = new(); - public List GroupMates { get; set; } - } -} + public List GroupMates { get; set; } +} \ No newline at end of file diff --git a/HwProj.Common/HwProj.Models/CoursesService/ViewModels/HomeworkTaskViewModels.cs b/HwProj.Common/HwProj.Models/CoursesService/ViewModels/HomeworkTaskViewModels.cs index 3535f5b10..81c66b8de 100644 --- a/HwProj.Common/HwProj.Models/CoursesService/ViewModels/HomeworkTaskViewModels.cs +++ b/HwProj.Common/HwProj.Models/CoursesService/ViewModels/HomeworkTaskViewModels.cs @@ -2,59 +2,58 @@ using System.ComponentModel.DataAnnotations; using Newtonsoft.Json; -namespace HwProj.Models.CoursesService.ViewModels +namespace HwProj.Models.CoursesService.ViewModels; + +public class HomeworkTaskViewModel { - public class HomeworkTaskViewModel - { - public long Id { get; set; } + public long Id { get; set; } - public string Title { get; set; } + public string Title { get; set; } - public string Description { get; set; } + public string Description { get; set; } - public int MaxRating { get; set; } + public int MaxRating { get; set; } - public bool HasDeadline { get; set; } + public bool HasDeadline { get; set; } - public DateTime? DeadlineDate { get; set; } + public DateTime? DeadlineDate { get; set; } - public bool IsDeadlineStrict { get; set; } + public bool IsDeadlineStrict { get; set; } - [JsonProperty] public bool CanSendSolution => !IsDeadlineStrict || DateTimeUtils.GetMoscowNow() <= DeadlineDate; + [JsonProperty] public bool CanSendSolution => !IsDeadlineStrict || DateTimeUtils.GetMoscowNow() <= DeadlineDate; - public DateTime PublicationDate { get; set; } + public DateTime PublicationDate { get; set; } - public long HomeworkId { get; set; } + public long HomeworkId { get; set; } - public bool IsDeferred { get; set; } - } + public bool IsDeferred { get; set; } +} - public class CreateTaskViewModel - { - [Required] - [RegularExpression(@"^\S+.*", ErrorMessage = "Name shouldn't start with white spaces.")] - public string Title { get; set; } +public class CreateTaskViewModel +{ + [Required] + [RegularExpression(@"^\S+.*", ErrorMessage = "Name shouldn't start with white spaces.")] + public string Title { get; set; } - public string Description { get; set; } + public string Description { get; set; } - public bool HasDeadline { get; set; } + public bool HasDeadline { get; set; } - public DateTime? DeadlineDate { get; set; } + public DateTime? DeadlineDate { get; set; } - public bool IsDeadlineStrict { get; set; } + public bool IsDeadlineStrict { get; set; } - public DateTime PublicationDate { get; set; } + public DateTime PublicationDate { get; set; } - [Required] public int MaxRating { get; set; } + [Required] public int MaxRating { get; set; } - public void InitializeDeadline() + public void InitializeDeadline() + { + if (!HasDeadline || DeadlineDate == null) { - if (!HasDeadline || DeadlineDate == null) - { - IsDeadlineStrict = false; - HasDeadline = false; - DeadlineDate = null; - } + IsDeadlineStrict = false; + HasDeadline = false; + DeadlineDate = null; } } -} +} \ No newline at end of file diff --git a/HwProj.Common/HwProj.Models/CoursesService/ViewModels/HomeworkViewModels.cs b/HwProj.Common/HwProj.Models/CoursesService/ViewModels/HomeworkViewModels.cs index 442cf5f5e..5eaa33343 100644 --- a/HwProj.Common/HwProj.Models/CoursesService/ViewModels/HomeworkViewModels.cs +++ b/HwProj.Common/HwProj.Models/CoursesService/ViewModels/HomeworkViewModels.cs @@ -2,31 +2,30 @@ using System.Collections.Generic; using System.ComponentModel.DataAnnotations; -namespace HwProj.Models.CoursesService.ViewModels +namespace HwProj.Models.CoursesService.ViewModels; + +public class CreateHomeworkViewModel { - public class CreateHomeworkViewModel - { - [Required] - [RegularExpression(@"^\S+.*", ErrorMessage = "Name shouldn't start with white spaces.")] - public string Title { get; set; } + [Required] + [RegularExpression(@"^\S+.*", ErrorMessage = "Name shouldn't start with white spaces.")] + public string Title { get; set; } - public string Description { get; set; } + public string Description { get; set; } - public List Tasks { get; set; } = new List(); - } + public List Tasks { get; set; } = new(); +} - public class HomeworkViewModel - { - public long Id { get; set; } +public class HomeworkViewModel +{ + public long Id { get; set; } - public string Title { get; set; } + public string Title { get; set; } - public string Description { get; set; } + public string Description { get; set; } - public DateTime Date { get; set; } + public DateTime Date { get; set; } - public long CourseId { get; set; } + public long CourseId { get; set; } - public List Tasks { get; set; } = new List(); - } -} + public List Tasks { get; set; } = new(); +} \ No newline at end of file diff --git a/HwProj.Common/HwProj.Models/DateTimeUtils.cs b/HwProj.Common/HwProj.Models/DateTimeUtils.cs index 341ae4be6..26ec837ee 100644 --- a/HwProj.Common/HwProj.Models/DateTimeUtils.cs +++ b/HwProj.Common/HwProj.Models/DateTimeUtils.cs @@ -1,9 +1,8 @@ using System; -namespace HwProj.Models +namespace HwProj.Models; + +public static class DateTimeUtils { - public static class DateTimeUtils - { - public static DateTime GetMoscowNow() => DateTime.UtcNow.AddHours(3); - } -} + public static DateTime GetMoscowNow() => DateTime.UtcNow.AddHours(3); +} \ No newline at end of file diff --git a/HwProj.Common/HwProj.Models/HwProj.Models.csproj b/HwProj.Common/HwProj.Models/HwProj.Models.csproj index 0ec3918d8..1ff494e0d 100644 --- a/HwProj.Common/HwProj.Models/HwProj.Models.csproj +++ b/HwProj.Common/HwProj.Models/HwProj.Models.csproj @@ -1,16 +1,15 @@  - netcoreapp2.2 + net6.0 $(CSharpLanguageVersion) $(NullableReferenceTypes) - - - - + + + diff --git a/HwProj.Common/HwProj.Models/NotificationsService/CategorizedNotifications.cs b/HwProj.Common/HwProj.Models/NotificationsService/CategorizedNotifications.cs index 391535b5d..536be819f 100644 --- a/HwProj.Common/HwProj.Models/NotificationsService/CategorizedNotifications.cs +++ b/HwProj.Common/HwProj.Models/NotificationsService/CategorizedNotifications.cs @@ -1,9 +1,8 @@ -namespace HwProj.Models.NotificationsService +namespace HwProj.Models.NotificationsService; + +public class CategorizedNotifications { - public class CategorizedNotifications - { - public CategoryState Category { get; set; } - public NotificationViewModel[] SeenNotifications { get; set; } - public NotificationViewModel[] NotSeenNotifications { get; set; } - } -} + public CategoryState Category { get; set; } + public NotificationViewModel[] SeenNotifications { get; set; } + public NotificationViewModel[] NotSeenNotifications { get; set; } +} \ No newline at end of file diff --git a/HwProj.Common/HwProj.Models/NotificationsService/Notification.cs b/HwProj.Common/HwProj.Models/NotificationsService/Notification.cs index 61d20235d..297e71c12 100644 --- a/HwProj.Common/HwProj.Models/NotificationsService/Notification.cs +++ b/HwProj.Common/HwProj.Models/NotificationsService/Notification.cs @@ -2,20 +2,19 @@ using System.ComponentModel.DataAnnotations; using HwProj.Repositories; -namespace HwProj.Models.NotificationsService +namespace HwProj.Models.NotificationsService; + +public class Notification : IEntity { - public class Notification : IEntity - { - [Key] public long Id { get; set; } + [Key] public long Id { get; set; } - public string Sender { get; set; } + public string Sender { get; set; } - //навесить индекс - public string Owner { get; set; } - public CategoryState Category { get; set; } - public string Body { get; set; } - public bool HasSeen { get; set; } - //TODO: выставлять автоматически - public DateTime Date { get ; set; } - } -} + //навесить индекс + public string Owner { get; set; } + public CategoryState Category { get; set; } + public string Body { get; set; } + public bool HasSeen { get; set; } + //TODO: выставлять автоматически + public DateTime Date { get ; set; } +} \ No newline at end of file diff --git a/HwProj.Common/HwProj.Models/NotificationsService/NotificationCategoryState.cs b/HwProj.Common/HwProj.Models/NotificationsService/NotificationCategoryState.cs index af6d354f8..fc25d00a0 100644 --- a/HwProj.Common/HwProj.Models/NotificationsService/NotificationCategoryState.cs +++ b/HwProj.Common/HwProj.Models/NotificationsService/NotificationCategoryState.cs @@ -1,10 +1,9 @@ -namespace HwProj.Models.NotificationsService +namespace HwProj.Models.NotificationsService; + +public enum CategoryState { - public enum CategoryState - { - None, - Profile, - Courses, - Homeworks - } + None, + Profile, + Courses, + Homeworks } \ No newline at end of file diff --git a/HwProj.Common/HwProj.Models/NotificationsService/NotificationFilter.cs b/HwProj.Common/HwProj.Models/NotificationsService/NotificationFilter.cs index e34016d2f..261dca9f0 100644 --- a/HwProj.Common/HwProj.Models/NotificationsService/NotificationFilter.cs +++ b/HwProj.Common/HwProj.Models/NotificationsService/NotificationFilter.cs @@ -1,15 +1,14 @@ using System; -namespace HwProj.Models.NotificationsService +namespace HwProj.Models.NotificationsService; + +public class NotificationFilter { - public class NotificationFilter - { - public string Sender { get; set; } - public CategoryState Category { get; set; } - public int? MaxCount { get; set; } - public int? Offset { get; set; } - public int? LastNotificationsId { get; set; } - public bool? HasSeen { get; set; } - public DateTime? LastDate { get; set; } - } + public string Sender { get; set; } + public CategoryState Category { get; set; } + public int? MaxCount { get; set; } + public int? Offset { get; set; } + public int? LastNotificationsId { get; set; } + public bool? HasSeen { get; set; } + public DateTime? LastDate { get; set; } } \ No newline at end of file diff --git a/HwProj.Common/HwProj.Models/NotificationsService/NotificationViewModel.cs b/HwProj.Common/HwProj.Models/NotificationsService/NotificationViewModel.cs index 912f0d0e8..9db0dfea4 100644 --- a/HwProj.Common/HwProj.Models/NotificationsService/NotificationViewModel.cs +++ b/HwProj.Common/HwProj.Models/NotificationsService/NotificationViewModel.cs @@ -1,18 +1,17 @@ using System; -namespace HwProj.Models.NotificationsService +namespace HwProj.Models.NotificationsService; + +public class NotificationViewModel { - public class NotificationViewModel - { - public long Id { get; set; } - public string Sender { get; set; } - public string Owner { get; set; } - public CategoryState Category { get; set; } - public string Body { get; set; } + public long Id { get; set; } + public string Sender { get; set; } + public string Owner { get; set; } + public CategoryState Category { get; set; } + public string Body { get; set; } - public bool HasSeen { get; set; } + public bool HasSeen { get; set; } - // dd.mm.yy hh:mm - public DateTime Date { get; set; } - } + // dd.mm.yy hh:mm + public DateTime Date { get; set; } } \ No newline at end of file diff --git a/HwProj.Common/HwProj.Models/Result/Result.cs b/HwProj.Common/HwProj.Models/Result/Result.cs index 4f3e7ed28..799e69012 100644 --- a/HwProj.Common/HwProj.Models/Result/Result.cs +++ b/HwProj.Common/HwProj.Models/Result/Result.cs @@ -1,52 +1,51 @@ using Newtonsoft.Json; -namespace HwProj.Models.Result +namespace HwProj.Models.Result; + +public sealed class Result { - public sealed class Result + public T Value { get; } + public bool Succeeded { get; } + public string[] Errors { get; } + + [JsonConstructor] + private Result(T value, bool succeeded, string[] errors) { - public T Value { get; } - public bool Succeeded { get; } - public string[] Errors { get; } - - [JsonConstructor] - private Result(T value, bool succeeded, string[] errors) - { - Succeeded = succeeded; - Value = value; - Errors = errors; - } - - public static Result Success(T value) - { - return new Result(value, true, null); - } - - public static Result Failed(params string[] errors) - { - return new Result(default, false, errors); - } + Succeeded = succeeded; + Value = value; + Errors = errors; } - - public sealed class Result + + public static Result Success(T value) { - public bool Succeeded { get; } - public string[] Errors { get; } - - [JsonConstructor] - private Result(bool succeeded, string[] errors) - { - Succeeded = succeeded; - Errors = errors; - } - - public static Result Success() - { - return new Result(true, null); - } - - public static Result Failed(params string[] errors) - { - return new Result(false, errors); - } + return new Result(value, true, null); + } + + public static Result Failed(params string[] errors) + { + return new Result(default, false, errors); } } + +public sealed class Result +{ + public bool Succeeded { get; } + public string[] Errors { get; } + + [JsonConstructor] + private Result(bool succeeded, string[] errors) + { + Succeeded = succeeded; + Errors = errors; + } + + public static Result Success() + { + return new Result(true, null); + } + + public static Result Failed(params string[] errors) + { + return new Result(false, errors); + } +} \ No newline at end of file diff --git a/HwProj.Common/HwProj.Models/Roles/Roles.cs b/HwProj.Common/HwProj.Models/Roles/Roles.cs index 97ef1d521..40afedc59 100644 --- a/HwProj.Common/HwProj.Models/Roles/Roles.cs +++ b/HwProj.Common/HwProj.Models/Roles/Roles.cs @@ -1,12 +1,11 @@ using Microsoft.AspNetCore.Identity; -namespace HwProj.Models.Roles +namespace HwProj.Models.Roles; + +public static class Roles { - public static class Roles - { - public static IdentityRole Lecturer = new IdentityRole("Lecturer"); - public static IdentityRole Student = new IdentityRole("Student"); - public const string LecturerRole = "Lecturer"; - public const string StudentRole = "Student"; - } -} + public static IdentityRole Lecturer = new("Lecturer"); + public static IdentityRole Student = new("Student"); + public const string LecturerRole = "Lecturer"; + public const string StudentRole = "Student"; +} \ No newline at end of file diff --git a/HwProj.Common/HwProj.Models/SolutionsService/Solution.cs b/HwProj.Common/HwProj.Models/SolutionsService/Solution.cs index 9783a04e3..a9973018f 100644 --- a/HwProj.Common/HwProj.Models/SolutionsService/Solution.cs +++ b/HwProj.Common/HwProj.Models/SolutionsService/Solution.cs @@ -3,29 +3,28 @@ using Newtonsoft.Json.Converters; using System; -namespace HwProj.Models.SolutionsService +namespace HwProj.Models.SolutionsService; + +public class Solution : IEntity { - public class Solution : IEntity - { - public long Id { get; set; } + public long Id { get; set; } - public string GithubUrl { get; set; } + public string GithubUrl { get; set; } - public string Comment { get; set; } + public string Comment { get; set; } - [JsonConverter(typeof(StringEnumConverter))] - public SolutionState State { get; set; } + [JsonConverter(typeof(StringEnumConverter))] + public SolutionState State { get; set; } - public int Rating { get; set; } + public int Rating { get; set; } - public string StudentId { get; set; } + public string StudentId { get; set; } - public long? GroupId { get; set; } + public long? GroupId { get; set; } - public long TaskId { get; set; } + public long TaskId { get; set; } - public DateTime PublicationDate { get; set; } + public DateTime PublicationDate { get; set; } - public string LecturerComment { get; set; } - } -} + public string LecturerComment { get; set; } +} \ No newline at end of file diff --git a/HwProj.Common/HwProj.Models/SolutionsService/SolutionPreviewDTO.cs b/HwProj.Common/HwProj.Models/SolutionsService/SolutionPreviewDTO.cs index f4f2ec548..7f609ce4f 100644 --- a/HwProj.Common/HwProj.Models/SolutionsService/SolutionPreviewDTO.cs +++ b/HwProj.Common/HwProj.Models/SolutionsService/SolutionPreviewDTO.cs @@ -1,14 +1,13 @@ using System; -namespace HwProj.Models.SolutionsService +namespace HwProj.Models.SolutionsService; + +public class SolutionPreviewDto { - public class SolutionPreviewDto - { - public string StudentId { get; set; } + public string StudentId { get; set; } - public long TaskId { get; set; } + public long TaskId { get; set; } - public DateTime PublicationDate { get; set; } - public bool IsFirstTry { get; set; } - } -} + public DateTime PublicationDate { get; set; } + public bool IsFirstTry { get; set; } +} \ No newline at end of file diff --git a/HwProj.Common/HwProj.Models/SolutionsService/SolutionState.cs b/HwProj.Common/HwProj.Models/SolutionsService/SolutionState.cs index 133b0b236..2fe77ca4c 100644 --- a/HwProj.Common/HwProj.Models/SolutionsService/SolutionState.cs +++ b/HwProj.Common/HwProj.Models/SolutionsService/SolutionState.cs @@ -1,7 +1,6 @@ -namespace HwProj.Models.SolutionsService +namespace HwProj.Models.SolutionsService; + +public enum SolutionState { - public enum SolutionState - { - Posted, Rated, Final - } -} + Posted, Rated, Final +} \ No newline at end of file diff --git a/HwProj.Common/HwProj.Models/SolutionsService/SolutionViewModel.cs b/HwProj.Common/HwProj.Models/SolutionsService/SolutionViewModel.cs index d93441f6e..7577e29e1 100644 --- a/HwProj.Common/HwProj.Models/SolutionsService/SolutionViewModel.cs +++ b/HwProj.Common/HwProj.Models/SolutionsService/SolutionViewModel.cs @@ -1,20 +1,19 @@ using System.ComponentModel.DataAnnotations; using System; -namespace HwProj.Models.SolutionsService +namespace HwProj.Models.SolutionsService; + +public class SolutionViewModel { - public class SolutionViewModel - { - [Required] - [RegularExpression(@"^\S+.*", ErrorMessage = "Name shouldn't start with white spaces.")] - public string GithubUrl { get; set; } + [Required] + [RegularExpression(@"^\S+.*", ErrorMessage = "Name shouldn't start with white spaces.")] + public string GithubUrl { get; set; } - public string Comment { get; set; } + public string Comment { get; set; } - public string StudentId { get; set; } + public string StudentId { get; set; } - public DateTime PublicationDate { get; set; } + public DateTime PublicationDate { get; set; } - public string LecturerComment { get; set; } - } -} + public string LecturerComment { get; set; } +} \ No newline at end of file diff --git a/HwProj.Common/HwProj.Models/StatisticsService/StatisticsCourseHomeworksModel.cs b/HwProj.Common/HwProj.Models/StatisticsService/StatisticsCourseHomeworksModel.cs index 4223bda42..3a8f0091c 100644 --- a/HwProj.Common/HwProj.Models/StatisticsService/StatisticsCourseHomeworksModel.cs +++ b/HwProj.Common/HwProj.Models/StatisticsService/StatisticsCourseHomeworksModel.cs @@ -1,10 +1,9 @@ using System.Collections.Generic; -namespace HwProj.Models.StatisticsService +namespace HwProj.Models.StatisticsService; + +public class StatisticsCourseHomeworksModel { - public class StatisticsCourseHomeworksModel - { - public long? Id; - public List Tasks { get; set; } = new List(); - } -} + public long? Id; + public List Tasks { get; set; } = new(); +} \ No newline at end of file diff --git a/HwProj.Common/HwProj.Models/StatisticsService/StatisticsCourseMatesDTO.cs b/HwProj.Common/HwProj.Models/StatisticsService/StatisticsCourseMatesDTO.cs index 716f70db3..5190ad0cd 100644 --- a/HwProj.Common/HwProj.Models/StatisticsService/StatisticsCourseMatesDTO.cs +++ b/HwProj.Common/HwProj.Models/StatisticsService/StatisticsCourseMatesDTO.cs @@ -1,10 +1,9 @@ using System.Collections.Generic; -namespace HwProj.Models.StatisticsService +namespace HwProj.Models.StatisticsService; + +public class StatisticsCourseMatesDto { - public class StatisticsCourseMatesDto - { - public string StudentId { get; set; } - public List Homeworks { get; set; } - } -} + public string StudentId { get; set; } + public List Homeworks { get; set; } +} \ No newline at end of file diff --git a/HwProj.Common/HwProj.Models/StatisticsService/StatisticsCourseSolutionsModel.cs b/HwProj.Common/HwProj.Models/StatisticsService/StatisticsCourseSolutionsModel.cs index 3fc188fe6..0884a07db 100644 --- a/HwProj.Common/HwProj.Models/StatisticsService/StatisticsCourseSolutionsModel.cs +++ b/HwProj.Common/HwProj.Models/StatisticsService/StatisticsCourseSolutionsModel.cs @@ -1,22 +1,21 @@ using HwProj.Models.SolutionsService; -namespace HwProj.Models.StatisticsService +namespace HwProj.Models.StatisticsService; + +public class StatisticsCourseSolutionsModel { - public class StatisticsCourseSolutionsModel + public StatisticsCourseSolutionsModel(Solution? model) { - public StatisticsCourseSolutionsModel(Solution? model) + if (model != null) { - if (model != null) - { - Id = model.Id; - State = model.State; - Rating = model.Rating; - } - + Id = model.Id; + State = model.State; + Rating = model.Rating; } - - public long? Id { get; set; } - public SolutionState? State { get; set; } - public int? Rating { get; set; } + } -} + + public long? Id { get; set; } + public SolutionState? State { get; set; } + public int? Rating { get; set; } +} \ No newline at end of file diff --git a/HwProj.Common/HwProj.Models/StatisticsService/StatisticsCourseTasksModel.cs b/HwProj.Common/HwProj.Models/StatisticsService/StatisticsCourseTasksModel.cs index e59f340ae..ad700e58b 100644 --- a/HwProj.Common/HwProj.Models/StatisticsService/StatisticsCourseTasksModel.cs +++ b/HwProj.Common/HwProj.Models/StatisticsService/StatisticsCourseTasksModel.cs @@ -1,10 +1,9 @@ using System.Collections.Generic; -namespace HwProj.Models.StatisticsService +namespace HwProj.Models.StatisticsService; + +public class StatisticsCourseTasksModel { - public class StatisticsCourseTasksModel - { - public long? Id { get; set; } - public List Solution { get; set; } = new List(); - } -} + public long? Id { get; set; } + public List Solution { get; set; } = new(); +} \ No newline at end of file diff --git a/HwProj.Common/HwProj.Repositories/CrudRepository.cs b/HwProj.Common/HwProj.Repositories/CrudRepository.cs index efcf06ca8..aa7a778cb 100644 --- a/HwProj.Common/HwProj.Repositories/CrudRepository.cs +++ b/HwProj.Common/HwProj.Repositories/CrudRepository.cs @@ -5,38 +5,37 @@ using Microsoft.EntityFrameworkCore; using Z.EntityFramework.Plus; -namespace HwProj.Repositories +namespace HwProj.Repositories; + +public class CrudRepository : ReadOnlyRepository, ICrudRepository + where TEntity : class, IEntity, new() + where TKey : IEquatable { - public class CrudRepository : ReadOnlyRepository, ICrudRepository - where TEntity : class, IEntity, new() - where TKey : IEquatable + public CrudRepository(DbContext context) + : base(context) { - public CrudRepository(DbContext context) - : base(context) - { - } + } - public async Task AddAsync(TEntity item) - { - await Context.AddAsync(item).ConfigureAwait(false); - await Context.SaveChangesAsync().ConfigureAwait(false); - return item.Id; - } + public async Task AddAsync(TEntity item) + { + await Context.AddAsync(item).ConfigureAwait(false); + await Context.SaveChangesAsync().ConfigureAwait(false); + return item.Id; + } - public async Task DeleteAsync(TKey id) - { - await Context.Set() - .Where(entity => entity.Id.Equals(id)) - .DeleteAsync() - .ConfigureAwait(false); - } + public async Task DeleteAsync(TKey id) + { + await Context.Set() + .Where(entity => entity.Id.Equals(id)) + .DeleteAsync() + .ConfigureAwait(false); + } - public async Task UpdateAsync(TKey id, Expression> updateFactory) - { - await Context.Set() - .Where(entity => entity.Id.Equals(id)) - .UpdateAsync(updateFactory) - .ConfigureAwait(false); - } + public async Task UpdateAsync(TKey id, Expression> updateFactory) + { + await Context.Set() + .Where(entity => entity.Id.Equals(id)) + .UpdateAsync(updateFactory) + .ConfigureAwait(false); } -} +} \ No newline at end of file diff --git a/HwProj.Common/HwProj.Repositories/HwProj.Repositories.csproj b/HwProj.Common/HwProj.Repositories/HwProj.Repositories.csproj index 7c840a1cf..d2f985328 100644 --- a/HwProj.Common/HwProj.Repositories/HwProj.Repositories.csproj +++ b/HwProj.Common/HwProj.Repositories/HwProj.Repositories.csproj @@ -1,11 +1,12 @@  - netcoreapp2.1 + net6.0 $(CSharpLanguageVersion) $(NullableReferenceTypes) - - + + + - \ No newline at end of file + diff --git a/HwProj.Common/HwProj.Repositories/ICrudRepository.cs b/HwProj.Common/HwProj.Repositories/ICrudRepository.cs index 5ab5b219c..811c16e12 100644 --- a/HwProj.Common/HwProj.Repositories/ICrudRepository.cs +++ b/HwProj.Common/HwProj.Repositories/ICrudRepository.cs @@ -2,14 +2,13 @@ using System.Linq.Expressions; using System.Threading.Tasks; -namespace HwProj.Repositories +namespace HwProj.Repositories; + +public interface ICrudRepository : IReadOnlyRepository + where TEntity : IEntity + where TKey : IEquatable { - public interface ICrudRepository : IReadOnlyRepository - where TEntity : IEntity - where TKey : IEquatable - { - Task AddAsync(TEntity item); - Task DeleteAsync(TKey id); - Task UpdateAsync(TKey id, Expression> updateFactory); - } + Task AddAsync(TEntity item); + Task DeleteAsync(TKey id); + Task UpdateAsync(TKey id, Expression> updateFactory); } \ No newline at end of file diff --git a/HwProj.Common/HwProj.Repositories/IEntity.cs b/HwProj.Common/HwProj.Repositories/IEntity.cs index 3a9ebbad0..f2e864ad8 100644 --- a/HwProj.Common/HwProj.Repositories/IEntity.cs +++ b/HwProj.Common/HwProj.Repositories/IEntity.cs @@ -1,10 +1,9 @@ using System; -namespace HwProj.Repositories +namespace HwProj.Repositories; + +public interface IEntity + where TKey : IEquatable { - public interface IEntity - where TKey : IEquatable - { - TKey Id { get; set; } - } -} + TKey Id { get; set; } +} \ No newline at end of file diff --git a/HwProj.Common/HwProj.Repositories/IReadOnlyRepository.cs b/HwProj.Common/HwProj.Repositories/IReadOnlyRepository.cs index f9b556e78..187b56b00 100644 --- a/HwProj.Common/HwProj.Repositories/IReadOnlyRepository.cs +++ b/HwProj.Common/HwProj.Repositories/IReadOnlyRepository.cs @@ -3,15 +3,14 @@ using System.Linq.Expressions; using System.Threading.Tasks; -namespace HwProj.Repositories +namespace HwProj.Repositories; + +public interface IReadOnlyRepository + where TEntity : IEntity + where TKey : IEquatable { - public interface IReadOnlyRepository - where TEntity : IEntity - where TKey : IEquatable - { - IQueryable GetAll(); - IQueryable FindAll(Expression> predicate); - Task GetAsync(TKey id); - Task FindAsync(Expression> predicate); - } -} + IQueryable GetAll(); + IQueryable FindAll(Expression> predicate); + Task GetAsync(TKey id); + Task FindAsync(Expression> predicate); +} \ No newline at end of file diff --git a/HwProj.Common/HwProj.Repositories/ReadOnlyRepository.cs b/HwProj.Common/HwProj.Repositories/ReadOnlyRepository.cs index 4e0b9a4ad..010893a3c 100644 --- a/HwProj.Common/HwProj.Repositories/ReadOnlyRepository.cs +++ b/HwProj.Common/HwProj.Repositories/ReadOnlyRepository.cs @@ -4,37 +4,36 @@ using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; -namespace HwProj.Repositories +namespace HwProj.Repositories; + +public class ReadOnlyRepository : IReadOnlyRepository + where TEntity : class, IEntity, new() + where TKey : IEquatable { - public class ReadOnlyRepository : IReadOnlyRepository - where TEntity : class, IEntity, new() - where TKey : IEquatable - { - protected readonly DbContext Context; + protected readonly DbContext Context; - public ReadOnlyRepository(DbContext context) - { - Context = context; - } + public ReadOnlyRepository(DbContext context) + { + Context = context; + } - public IQueryable GetAll() - { - return Context.Set().AsNoTracking(); - } + public IQueryable GetAll() + { + return Context.Set().AsNoTracking(); + } - public IQueryable FindAll(Expression> predicate) - { - return Context.Set().AsNoTracking().Where(predicate); - } + public IQueryable FindAll(Expression> predicate) + { + return Context.Set().AsNoTracking().Where(predicate); + } - public async Task GetAsync(TKey id) - { - return await Context.FindAsync(id).ConfigureAwait(false); - } + public async Task GetAsync(TKey id) + { + return await Context.FindAsync(id).ConfigureAwait(false); + } - public async Task FindAsync(Expression> predicate) - { - return await Context.Set().AsNoTracking().FirstOrDefaultAsync(predicate).ConfigureAwait(false); - } + public async Task FindAsync(Expression> predicate) + { + return await Context.Set().AsNoTracking().FirstOrDefaultAsync(predicate).ConfigureAwait(false); } -} +} \ No newline at end of file diff --git a/HwProj.Common/HwProj.Utils/Authorization/AuthExtensions.cs b/HwProj.Common/HwProj.Utils/Authorization/AuthExtensions.cs index f8fa936e6..15a4a368d 100644 --- a/HwProj.Common/HwProj.Utils/Authorization/AuthExtensions.cs +++ b/HwProj.Common/HwProj.Utils/Authorization/AuthExtensions.cs @@ -3,38 +3,37 @@ using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Primitives; -namespace HwProj.Utils.Authorization +namespace HwProj.Utils.Authorization; + +public static class AuthExtensions { - public static class AuthExtensions - { - public static string? GetUserIdFromHeader(this HttpRequest request) => - request.Headers.TryGetValue("UserId", out var id) ? id.FirstOrDefault() : null; + public static string? GetUserIdFromHeader(this HttpRequest request) => + request.Headers.TryGetValue("UserId", out var id) ? id.FirstOrDefault() : null; - public static string GetUserName(this HttpRequest request) - { - return request.Query.First(x => x.Key == "_userName").Value.ToString(); - } + public static string GetUserName(this HttpRequest request) + { + return request.Query.First(x => x.Key == "_userName").Value.ToString(); + } - public static string GetUserRole(this HttpRequest request) - { - var claimRole = "http://schemas.microsoft.com/ws/2008/06/identity/claims/role"; - var role = request.HttpContext.User.Claims.FirstOrDefault(claim => claim.Type.ToString() == claimRole); - return role == null - ? null - : role.Value; - } + public static string GetUserRole(this HttpRequest request) + { + var claimRole = "http://schemas.microsoft.com/ws/2008/06/identity/claims/role"; + var role = request.HttpContext.User.Claims.FirstOrDefault(claim => claim.Type.ToString() == claimRole); + return role == null + ? null + : role.Value; + } - public static bool IsLecturer(this string role) - { - return role == Roles.LecturerRole; - } + public static bool IsLecturer(this string role) + { + return role == Roles.LecturerRole; + } - public static string GetMentorId(this HttpRequest request) - { - request.HttpContext.Request.Headers.TryGetValue("UserId", out var userId); - return StringValues.IsNullOrEmpty(userId) - ? null - : userId.ToString(); - } + public static string GetMentorId(this HttpRequest request) + { + request.HttpContext.Request.Headers.TryGetValue("UserId", out var userId); + return StringValues.IsNullOrEmpty(userId) + ? null + : userId.ToString(); } -} +} \ No newline at end of file diff --git a/HwProj.Common/HwProj.Utils/Authorization/AuthorizationKey.cs b/HwProj.Common/HwProj.Utils/Authorization/AuthorizationKey.cs index 390c6d553..1255f34f6 100644 --- a/HwProj.Common/HwProj.Utils/Authorization/AuthorizationKey.cs +++ b/HwProj.Common/HwProj.Utils/Authorization/AuthorizationKey.cs @@ -1,11 +1,10 @@ using Microsoft.IdentityModel.Tokens; using System.Text; -namespace HwProj.Utils.Authorization +namespace HwProj.Utils.Authorization; + +public static class AuthorizationKey { - public static class AuthorizationKey - { - private const string _key = "U8_.wpvk93fPWG new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_key)); - } -} + private const string _key = "U8_.wpvk93fPWG new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_key)); +} \ No newline at end of file diff --git a/HwProj.Common/HwProj.Utils/Configuration/ConnectionString.cs b/HwProj.Common/HwProj.Utils/Configuration/ConnectionString.cs index 2c0ea9135..01e4e44e3 100644 --- a/HwProj.Common/HwProj.Utils/Configuration/ConnectionString.cs +++ b/HwProj.Common/HwProj.Utils/Configuration/ConnectionString.cs @@ -2,18 +2,17 @@ using Microsoft.Extensions.Configuration; using IConfiguration = Microsoft.Extensions.Configuration.IConfiguration; -namespace HwProj.Utils.Configuration +namespace HwProj.Utils.Configuration; + +public static class ConnectionString { - public static class ConnectionString + public static string GetConnectionString(IConfiguration configuration) { - public static string GetConnectionString(IConfiguration configuration) + if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { - if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) - { - return configuration.GetConnectionString("DefaultConnectionForLinux"); - } - - return configuration.GetConnectionString("DefaultConnectionForWindows"); + return configuration.GetConnectionString("DefaultConnectionForLinux"); } + + return configuration.GetConnectionString("DefaultConnectionForWindows"); } -} \ No newline at end of file +} diff --git a/HwProj.Common/HwProj.Utils/Configuration/Middleware/NoApiGatewayMiddleware.cs b/HwProj.Common/HwProj.Utils/Configuration/Middleware/NoApiGatewayMiddleware.cs index 57a1d506e..707573f78 100644 --- a/HwProj.Common/HwProj.Utils/Configuration/Middleware/NoApiGatewayMiddleware.cs +++ b/HwProj.Common/HwProj.Utils/Configuration/Middleware/NoApiGatewayMiddleware.cs @@ -2,25 +2,24 @@ using HwProj.Models.Roles; using Microsoft.AspNetCore.Http; -namespace HwProj.Utils.Configuration.Middleware +namespace HwProj.Utils.Configuration.Middleware; + +public class NoApiGatewayMiddleware : IMiddleware { - public class NoApiGatewayMiddleware : IMiddleware + public async Task InvokeAsync(HttpContext context, RequestDelegate next) { - public async Task InvokeAsync(HttpContext context, RequestDelegate next) - { - var request = context.Request; + var request = context.Request; - if (!request.Query.ContainsKey("_id")) - { - request.QueryString = request.QueryString.Add("_id", "hwprojDevUser"); - } - - if (!request.Query.ContainsKey("_role")) - { - request.QueryString = request.QueryString.Add("_role", Roles.LecturerRole); - } + if (!request.Query.ContainsKey("_id")) + { + request.QueryString = request.QueryString.Add("_id", "hwprojDevUser"); + } - await next.Invoke(context); + if (!request.Query.ContainsKey("_role")) + { + request.QueryString = request.QueryString.Add("_role", Roles.LecturerRole); } + + await next.Invoke(context); } } \ No newline at end of file diff --git a/HwProj.Common/HwProj.Utils/Configuration/StartupExtensions.cs b/HwProj.Common/HwProj.Utils/Configuration/StartupExtensions.cs index 9c19fdb44..86325a396 100644 --- a/HwProj.Common/HwProj.Utils/Configuration/StartupExtensions.cs +++ b/HwProj.Common/HwProj.Utils/Configuration/StartupExtensions.cs @@ -1,8 +1,7 @@ using System; -using System.Collections.Generic; using System.Linq; using System.Net.Sockets; -using AutoMapper; +using System.Text.Json.Serialization; using HwProj.EventBus.Client; using HwProj.EventBus.Client.Implementations; using HwProj.EventBus.Client.Interfaces; @@ -11,143 +10,141 @@ using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Microsoft.IdentityModel.Tokens; -using Newtonsoft.Json; +using Microsoft.OpenApi.Models; using Polly; using RabbitMQ.Client; using RabbitMQ.Client.Exceptions; -using Swashbuckle.AspNetCore.Swagger; -namespace HwProj.Utils.Configuration +namespace HwProj.Utils.Configuration; + +public static class StartupExtensions { - public static class StartupExtensions + public static IServiceCollection ConfigureHwProjServices(this IServiceCollection services, string serviceName) { - public static IServiceCollection ConfigureHwProjServices(this IServiceCollection services, string serviceName) - { - services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()) - .AddCors() - .AddMvc() - .AddJsonOptions(options => - options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore) - .SetCompatibilityVersion(CompatibilityVersion.Version_2_1); - - services.AddSwaggerGen(c => - { - c.SwaggerDoc("v1", new Info { Title = serviceName, Version = "v1" }); + services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()) + .AddCors() + .AddMvc() + .AddJsonOptions(options => + options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles); - if (serviceName == "API Gateway") - { - c.AddSecurityDefinition("Bearer", - new ApiKeyScheme - { - In = "header", - Description = "Please enter into field the word 'Bearer' following by space and JWT", - Name = "Authorization", - Type = "apiKey" - }); - c.AddSecurityRequirement(new Dictionary> { - { "Bearer", Enumerable.Empty() }, - }); - } - }); + services.AddSwaggerGen(c => + { + c.SwaggerDoc("v1", new OpenApiInfo { Title = serviceName, Version = "v1" }); - if (serviceName != "AuthService API") + if (serviceName == "API Gateway") { - services.AddAuthentication(options => - { - options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; - options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; - }) - .AddJwtBearer(x => + c.AddSecurityDefinition("Bearer", + new OpenApiSecurityScheme { - x.RequireHttpsMetadata = false; //TODO: dev env setting - x.TokenValidationParameters = new TokenValidationParameters - { - ValidIssuer = "AuthService", - ValidateIssuer = true, - ValidateAudience = false, - ValidateLifetime = true, - IssuerSigningKey = AuthorizationKey.SecurityKey, - ValidateIssuerSigningKey = true - }; + In = ParameterLocation.Header, + Description = "Please enter into field the word 'Bearer' following by space and JWT", + Name = "Authorization", + Type = SecuritySchemeType.ApiKey }); + c.AddSecurityRequirement(new OpenApiSecurityRequirement + { + { "Bearer", Enumerable.Empty() }, + }); } + }); - services.AddTransient(); - - services.AddHttpContextAccessor(); - - return services; - } - - public static IServiceCollection AddEventBus(this IServiceCollection services, IConfiguration configuration) + if (serviceName != "AuthService API") { - var eventBusSection = configuration.GetSection("EventBus"); + services.AddAuthentication(options => + { + options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; + options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; + }) + .AddJwtBearer(x => + { + x.RequireHttpsMetadata = false; //TODO: dev env setting + x.TokenValidationParameters = new TokenValidationParameters + { + ValidIssuer = "AuthService", + ValidateIssuer = true, + ValidateAudience = false, + ValidateLifetime = true, + IssuerSigningKey = AuthorizationKey.SecurityKey, + ValidateIssuerSigningKey = true + }; + }); + } - var retryCount = 5; - if (!string.IsNullOrEmpty(eventBusSection["EventBusRetryCount"])) - { - retryCount = int.Parse(eventBusSection["EventBusRetryCount"]); - } + services.AddTransient(); - services.AddSingleton(sp => Policy.Handle() - .Or() - .WaitAndRetry(retryCount, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)))); + services.AddHttpContextAccessor(); - services.AddSingleton(sp => new ConnectionFactory - { - HostName = eventBusSection["EventBusHostName"], - UserName = eventBusSection["EventBusUserName"], - Password = eventBusSection["EventBusPassword"], - VirtualHost = eventBusSection["EventBusVirtualHost"] - }); - - services.AddSingleton(); - services.AddSingleton(); - - var types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => x.GetTypes()).ToList(); - var eventTypes = types.Where(x => typeof(Event).IsAssignableFrom(x)); - foreach (var eventType in eventTypes) - { - var fullTypeInterface = typeof(IEventHandler<>).MakeGenericType(eventType); - var handlersTypes = types.Where(x => - fullTypeInterface.IsAssignableFrom(x) && !x.IsInterface && !x.IsAbstract); + return services; + } - foreach (var handlerType in handlersTypes) - { - services.AddTransient(handlerType); - } - } + public static IServiceCollection AddEventBus(this IServiceCollection services, IConfiguration configuration) + { + var eventBusSection = configuration.GetSection("EventBus"); - return services; + var retryCount = 5; + if (!string.IsNullOrEmpty(eventBusSection["EventBusRetryCount"])) + { + retryCount = int.Parse(eventBusSection["EventBusRetryCount"]); } - public static IApplicationBuilder ConfigureHwProj(this IApplicationBuilder app, IHostingEnvironment env, - string serviceName) + services.AddSingleton(sp => Policy.Handle() + .Or() + .WaitAndRetry(retryCount, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)))); + + services.AddSingleton(sp => new ConnectionFactory { - if (env.IsDevelopment()) - { - app.UseDeveloperExceptionPage() - .UseSwagger() - .UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", serviceName); }); - } - else + HostName = eventBusSection["EventBusHostName"], + UserName = eventBusSection["EventBusUserName"], + Password = eventBusSection["EventBusPassword"], + VirtualHost = eventBusSection["EventBusVirtualHost"] + }); + + services.AddSingleton(); + services.AddSingleton(); + + var types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => x.GetTypes()).ToList(); + var eventTypes = types.Where(x => typeof(Event).IsAssignableFrom(x)); + foreach (var eventType in eventTypes) + { + var fullTypeInterface = typeof(IEventHandler<>).MakeGenericType(eventType); + var handlersTypes = types.Where(x => + fullTypeInterface.IsAssignableFrom(x) && !x.IsInterface && !x.IsAbstract); + + foreach (var handlerType in handlersTypes) { - app.UseHsts(); + services.AddTransient(handlerType); } + } - app.UseAuthentication(); - app.UseCors(x => x - .AllowAnyMethod() - .AllowAnyHeader() - .SetIsOriginAllowed(origin => true) - .AllowCredentials()); - app.UseMvc(); + return services; + } - return app; + public static IApplicationBuilder ConfigureHwProj(this IApplicationBuilder app, IWebHostEnvironment env, + string serviceName) + { + if (env.IsDevelopment()) + { + app.UseDeveloperExceptionPage() + .UseSwagger() + .UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", serviceName); }); } + else + { + app.UseHsts(); + } + + app.UseAuthentication(); + app.UseCors(x => x + .AllowAnyMethod() + .AllowAnyHeader() + .SetIsOriginAllowed(origin => true) + .AllowCredentials()); + app.UseMvc(); + + return app; } } diff --git a/HwProj.Common/HwProj.Utils/HwProj.Utils.csproj b/HwProj.Common/HwProj.Utils/HwProj.Utils.csproj index 74fe97898..522acd1e2 100644 --- a/HwProj.Common/HwProj.Utils/HwProj.Utils.csproj +++ b/HwProj.Common/HwProj.Utils/HwProj.Utils.csproj @@ -1,16 +1,16 @@  - netcoreapp2.2 + net6.0 $(CSharpLanguageVersion) $(NullableReferenceTypes) - - - - + + + + @@ -18,25 +18,4 @@ - - - C:\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.aspnetcore.hosting.abstractions\2.1.1\lib\netstandard2.0\Microsoft.AspNetCore.Hosting.Abstractions.dll - - - C:\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.aspnetcore.http.abstractions\2.1.1\lib\netstandard2.0\Microsoft.AspNetCore.Http.Abstractions.dll - - - C:\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.aspnetcore.mvc.core\2.1.1\lib\netstandard2.0\Microsoft.AspNetCore.Mvc.Core.dll - - - C:\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.extensions.dependencyinjection.abstractions\2.1.1\lib\netstandard2.0\Microsoft.Extensions.DependencyInjection.Abstractions.dll - - - C:\Program Files\dotnet\sdk\NuGetFallbackFolder\newtonsoft.json\11.0.2\lib\netstandard2.0\Newtonsoft.Json.dll - - - C:\Users\Alex Berezhnyh\.nuget\packages\swashbuckle.aspnetcore.swagger\4.0.1\lib\netstandard2.0\Swashbuckle.AspNetCore.Swagger.dll - - - diff --git a/HwProj.CourseWorkService/HwProj.CourseWorkService.API/HwProj.CourseWorkService.API.csproj b/HwProj.CourseWorkService/HwProj.CourseWorkService.API/HwProj.CourseWorkService.API.csproj index 2d8ad6d5c..202e2f048 100644 --- a/HwProj.CourseWorkService/HwProj.CourseWorkService.API/HwProj.CourseWorkService.API.csproj +++ b/HwProj.CourseWorkService/HwProj.CourseWorkService.API/HwProj.CourseWorkService.API.csproj @@ -1,7 +1,7 @@  - netcoreapp2.2 + net6.0 InProcess @@ -10,10 +10,10 @@ - + - + diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/ApplicationProfile.cs b/HwProj.CoursesService/HwProj.CoursesService.API/ApplicationProfile.cs index 495aa621c..158d8b209 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/ApplicationProfile.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.API/ApplicationProfile.cs @@ -6,54 +6,53 @@ using System; using HwProj.Models; -namespace HwProj.CoursesService.API +namespace HwProj.CoursesService.API; + +public class ApplicationProfile : Profile { - public class ApplicationProfile : Profile + public ApplicationProfile() { - public ApplicationProfile() - { - CreateMap().ForMember( - t => t.MentorIds, - cm => cm.MapFrom(course => course.MentorIds.Split("/", StringSplitOptions.None))); - CreateMap().ForMember( - t => t.MentorIds, - cm => cm.MapFrom(course => course.MentorIds.Split("/", StringSplitOptions.None))); + CreateMap().ForMember( + t => t.MentorIds, + cm => cm.MapFrom(course => course.MentorIds.Split("/", StringSplitOptions.None))); + CreateMap().ForMember( + t => t.MentorIds, + cm => cm.MapFrom(course => course.MentorIds.Split("/", StringSplitOptions.None))); - CreateMap().ReverseMap(); - CreateMap().ReverseMap(); + CreateMap().ReverseMap(); + CreateMap().ReverseMap(); - CreateMap(); - CreateMap() - .ForMember("Tasks", cm => cm.MapFrom(g => g.Tasks.Select(c => c.TaskId).ToList())) - .ForMember("GroupMates", - cm => cm.MapFrom(g => - g.GroupMates.Select(c => new GroupMateViewModel { StudentId = c.StudentId }).ToList())); - CreateMap().ReverseMap() - .ForMember("Tasks", cm => cm.MapFrom(g => g.Tasks.Select(c => c.TaskId).ToList())) - .ForMember("GroupMates", - cm => cm.MapFrom(g => - g.GroupMates.Select(c => new GroupMateViewModel { StudentId = c.StudentId }).ToList())); - CreateMap().ReverseMap() - .ForMember("Tasks", cm => cm.MapFrom(g => g.Tasks.Select(c => new TaskModel { TaskId = c }).ToList())) - .ForMember("GroupMates", - cm => cm.MapFrom(g => - g.GroupMates.Select(c => new GroupMate { StudentId = c.StudentId }).ToList())); - CreateMap() - .ForMember("Tasks", cm => cm.MapFrom(g => g.Tasks.Select(c => new TaskModel { TaskId = c }).ToList())) - .ForMember("GroupMates", - cm => cm.MapFrom(g => - g.GroupMates.Select(c => new GroupMate { StudentId = c.StudentId }).ToList())); + CreateMap(); + CreateMap() + .ForMember("Tasks", cm => cm.MapFrom(g => g.Tasks.Select(c => c.TaskId).ToList())) + .ForMember("GroupMates", + cm => cm.MapFrom(g => + g.GroupMates.Select(c => new GroupMateViewModel { StudentId = c.StudentId }).ToList())); + CreateMap().ReverseMap() + .ForMember("Tasks", cm => cm.MapFrom(g => g.Tasks.Select(c => c.TaskId).ToList())) + .ForMember("GroupMates", + cm => cm.MapFrom(g => + g.GroupMates.Select(c => new GroupMateViewModel { StudentId = c.StudentId }).ToList())); + CreateMap().ReverseMap() + .ForMember("Tasks", cm => cm.MapFrom(g => g.Tasks.Select(c => new TaskModel { TaskId = c }).ToList())) + .ForMember("GroupMates", + cm => cm.MapFrom(g => + g.GroupMates.Select(c => new GroupMate { StudentId = c.StudentId }).ToList())); + CreateMap() + .ForMember("Tasks", cm => cm.MapFrom(g => g.Tasks.Select(c => new TaskModel { TaskId = c }).ToList())) + .ForMember("GroupMates", + cm => cm.MapFrom(g => + g.GroupMates.Select(c => new GroupMate { StudentId = c.StudentId }).ToList())); - CreateMap(); + CreateMap(); - CreateMap(); + CreateMap(); - CreateMap(); - CreateMap(); - CreateMap().ReverseMap(); - CreateMap() - .ForMember("IsDeferred", cm => cm.MapFrom(g => DateTimeUtils.GetMoscowNow() < g.PublicationDate)); - CreateMap().ReverseMap(); - } + CreateMap(); + CreateMap(); + CreateMap().ReverseMap(); + CreateMap() + .ForMember("IsDeferred", cm => cm.MapFrom(g => DateTimeUtils.GetMoscowNow() < g.PublicationDate)); + CreateMap().ReverseMap(); } -} +} \ No newline at end of file diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Controllers/CourseGroupsController.cs b/HwProj.CoursesService/HwProj.CoursesService.API/Controllers/CourseGroupsController.cs index 48af84a68..48a315cd0 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Controllers/CourseGroupsController.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.API/Controllers/CourseGroupsController.cs @@ -6,92 +6,91 @@ using HwProj.Models.CoursesService.ViewModels; using Microsoft.AspNetCore.Mvc; -namespace HwProj.CoursesService.API.Controllers +namespace HwProj.CoursesService.API.Controllers; + +[ApiController] +[Route("api/[controller]")] +public class CourseGroupsController : Controller { - [ApiController] - [Route("api/[controller]")] - public class CourseGroupsController : Controller - { - private readonly IGroupsService _groupsService; - private readonly IMapper _mapper; + private readonly IGroupsService _groupsService; + private readonly IMapper _mapper; - public CourseGroupsController(IMapper mapper, IGroupsService groupsService) - { - _mapper = mapper; - _groupsService = groupsService; - } + public CourseGroupsController(IMapper mapper, IGroupsService groupsService) + { + _mapper = mapper; + _groupsService = groupsService; + } - [HttpGet("{courseId}/getAll")] - public async Task GetAll(long courseId) - { - var groups = await _groupsService.GetAllAsync(courseId); - return _mapper.Map(groups); - } + [HttpGet("{courseId}/getAll")] + public async Task GetAll(long courseId) + { + var groups = await _groupsService.GetAllAsync(courseId); + return _mapper.Map(groups); + } - [HttpPost("{courseId}/create")] - [ServiceFilter(typeof(CourseMentorOnlyAttribute))] - public async Task CreateGroup([FromBody] CreateGroupViewModel groupViewModel) - { - var group = _mapper.Map(groupViewModel); - var id = await _groupsService.AddGroupAsync(group); - return Ok(id); - } + [HttpPost("{courseId}/create")] + [ServiceFilter(typeof(CourseMentorOnlyAttribute))] + public async Task CreateGroup([FromBody] CreateGroupViewModel groupViewModel) + { + var group = _mapper.Map(groupViewModel); + var id = await _groupsService.AddGroupAsync(group); + return Ok(id); + } - [HttpDelete("{courseId}/delete/{groupId}")] - [ServiceFilter(typeof(CourseMentorOnlyAttribute))] - public async Task DeleteGroup(long groupId) - { - await _groupsService.DeleteGroupAsync(groupId).ConfigureAwait(false); - return Ok(); - } + [HttpDelete("{courseId}/delete/{groupId}")] + [ServiceFilter(typeof(CourseMentorOnlyAttribute))] + public async Task DeleteGroup(long groupId) + { + await _groupsService.DeleteGroupAsync(groupId).ConfigureAwait(false); + return Ok(); + } - [HttpPost("{courseId}/update/{groupId}")] - [ServiceFilter(typeof(CourseMentorOnlyAttribute))] - public async Task UpdateGroup(long groupId, [FromBody] UpdateGroupViewModel groupViewModel) - { - await _groupsService.UpdateAsync(groupId, _mapper.Map(groupViewModel)); - return Ok(); - } + [HttpPost("{courseId}/update/{groupId}")] + [ServiceFilter(typeof(CourseMentorOnlyAttribute))] + public async Task UpdateGroup(long groupId, [FromBody] UpdateGroupViewModel groupViewModel) + { + await _groupsService.UpdateAsync(groupId, _mapper.Map(groupViewModel)); + return Ok(); + } - [HttpGet("{courseId}/get")] - public async Task GetCoursesGroups(long courseId, [FromQuery] string userId) - { - var groups = await _groupsService.GetStudentGroupsAsync(courseId, userId); - return Ok(groups); - } + [HttpGet("{courseId}/get")] + public async Task GetCoursesGroups(long courseId, [FromQuery] string userId) + { + var groups = await _groupsService.GetStudentGroupsAsync(courseId, userId); + return Ok(groups); + } - [HttpPost("{courseId}/addStudentInGroup/{groupId}")] - [ServiceFilter(typeof(CourseMentorOnlyAttribute))] - public async Task AddStudentInGroup(long groupId, [FromQuery] string userId) - { - await _groupsService.AddGroupMateAsync(groupId, userId); - return Ok(); - } + [HttpPost("{courseId}/addStudentInGroup/{groupId}")] + [ServiceFilter(typeof(CourseMentorOnlyAttribute))] + public async Task AddStudentInGroup(long groupId, [FromQuery] string userId) + { + await _groupsService.AddGroupMateAsync(groupId, userId); + return Ok(); + } - [HttpPost("{courseId}/removeStudentFromGroup/{groupId}")] - [ServiceFilter(typeof(CourseMentorOnlyAttribute))] - public async Task RemoveStudentFromGroup(long groupId, [FromQuery] string userId) - { - return await _groupsService.DeleteGroupMateAsync(groupId, userId) - ? Ok() - : NotFound() as IActionResult; - } + [HttpPost("{courseId}/removeStudentFromGroup/{groupId}")] + [ServiceFilter(typeof(CourseMentorOnlyAttribute))] + public async Task RemoveStudentFromGroup(long groupId, [FromQuery] string userId) + { + return await _groupsService.DeleteGroupMateAsync(groupId, userId) + ? Ok() + : NotFound(); + } - [HttpGet("get/{groupId}")] - public async Task Get(long groupId) - { - var group = await _groupsService.GetGroupAsync(groupId); - return group == null - ? NotFound() - : Ok(_mapper.Map(group)) as IActionResult; - } + [HttpGet("get/{groupId}")] + public async Task Get(long groupId) + { + var group = await _groupsService.GetGroupAsync(groupId); + return group == null + ? NotFound() + : Ok(_mapper.Map(group)); + } - [HttpGet("getTasks/{groupId}")] - public async Task GetGroupTasks(long groupId) - { - var ids = await _groupsService.GetTasksIds(groupId); - return Ok(ids); - } + [HttpGet("getTasks/{groupId}")] + public async Task GetGroupTasks(long groupId) + { + var ids = await _groupsService.GetTasksIds(groupId); + return Ok(ids); } -} +} \ No newline at end of file diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Controllers/CoursesController.cs b/HwProj.CoursesService/HwProj.CoursesService.API/Controllers/CoursesController.cs index 325d68207..7e507fb2c 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Controllers/CoursesController.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.API/Controllers/CoursesController.cs @@ -14,164 +14,163 @@ using HwProj.Models.CoursesService.DTO; using Microsoft.EntityFrameworkCore; -namespace HwProj.CoursesService.API.Controllers +namespace HwProj.CoursesService.API.Controllers; + +[ApiController] +[Route("api/[controller]")] +public class CoursesController : Controller { - [ApiController] - [Route("api/[controller]")] - public class CoursesController : Controller + private readonly ICoursesService _coursesService; + private readonly ICoursesRepository _coursesRepository; + private readonly ICourseMatesRepository _courseMatesRepository; + private readonly IMapper _mapper; + + public CoursesController(ICoursesService coursesService, + ICoursesRepository coursesRepository, + ICourseMatesRepository courseMatesRepository, IMapper mapper) { - private readonly ICoursesService _coursesService; - private readonly ICoursesRepository _coursesRepository; - private readonly ICourseMatesRepository _courseMatesRepository; - private readonly IMapper _mapper; - - public CoursesController(ICoursesService coursesService, - ICoursesRepository coursesRepository, - ICourseMatesRepository courseMatesRepository, IMapper mapper) - { - _coursesService = coursesService; - _coursesRepository = coursesRepository; - _courseMatesRepository = courseMatesRepository; - _mapper = mapper; - } - - [HttpGet] - public async Task GetAll() - { - var coursesFromDb = await _coursesService.GetAllAsync(); - var courses = _mapper.Map(coursesFromDb).ToArray(); - return courses; - } + _coursesService = coursesService; + _coursesRepository = coursesRepository; + _courseMatesRepository = courseMatesRepository; + _mapper = mapper; + } - [HttpGet("{courseId}")] - public async Task Get(long courseId, [FromBody] string userId) - { - var courseFromDb = await _coursesService.GetAsync(courseId, userId); - if (courseFromDb == null) return NotFound(); + [HttpGet] + public async Task GetAll() + { + var coursesFromDb = await _coursesService.GetAllAsync(); + var courses = _mapper.Map(coursesFromDb).ToArray(); + return courses; + } - var course = _mapper.Map(courseFromDb); - return Ok(course); - } + [HttpGet("{courseId}")] + public async Task Get(long courseId, [FromBody] string userId) + { + var courseFromDb = await _coursesService.GetAsync(courseId, userId); + if (courseFromDb == null) return NotFound(); - [HttpPost("create")] - [ServiceFilter(typeof(CourseMentorOnlyAttribute))] - public async Task AddCourse([FromBody] CreateCourseViewModel courseViewModel, - [FromQuery] string mentorId) - { - var course = _mapper.Map(courseViewModel); - var id = await _coursesService.AddAsync(course, mentorId); - return Ok(id); - } - - [HttpDelete("{courseId}")] - [ServiceFilter(typeof(CourseMentorOnlyAttribute))] - public async Task DeleteCourse(long courseId) - { - await _coursesService.DeleteAsync(courseId); - return Ok(); - } + var course = _mapper.Map(courseFromDb); + return Ok(course); + } - [HttpPost("update/{courseId}")] - [ServiceFilter(typeof(CourseMentorOnlyAttribute))] - public async Task UpdateCourse(long courseId, [FromBody] UpdateCourseViewModel courseViewModel) - { - await _coursesService.UpdateAsync(courseId, new Course - { - Name = courseViewModel.Name, - GroupName = courseViewModel.GroupName, - IsCompleted = courseViewModel.IsCompleted, - IsOpen = courseViewModel.IsOpen - }); - - return Ok(); - } - - [HttpPost("signInCourse/{courseId}")] - public async Task SignInCourse(long courseId, [FromQuery] string studentId) - { - return await _coursesService.AddStudentAsync(courseId, studentId) - ? Ok() as IActionResult - : NotFound(); - } - - [HttpPost("acceptStudent/{courseId}")] - [ServiceFilter(typeof(CourseMentorOnlyAttribute))] - public async Task AcceptStudent(long courseId, [FromQuery] string studentId) - { - return await _coursesService.AcceptCourseMateAsync(courseId, studentId) - ? Ok() as IActionResult - : NotFound(); - } - - [HttpPost("rejectStudent/{courseId}")] - [ServiceFilter(typeof(CourseMentorOnlyAttribute))] - public async Task RejectStudent(long courseId, [FromQuery] string studentId) - { - return await _coursesService.RejectCourseMateAsync(courseId, studentId) - ? Ok() as IActionResult - : NotFound(); - } + [HttpPost("create")] + [ServiceFilter(typeof(CourseMentorOnlyAttribute))] + public async Task AddCourse([FromBody] CreateCourseViewModel courseViewModel, + [FromQuery] string mentorId) + { + var course = _mapper.Map(courseViewModel); + var id = await _coursesService.AddAsync(course, mentorId); + return Ok(id); + } - [HttpGet("userCourses")] - public async Task GetUserCourses() - { - var userId = Request.GetUserIdFromHeader(); - var coursesFromDb = await _coursesService.GetUserCoursesAsync(userId); - var courses = _mapper.Map(coursesFromDb).ToArray(); - return courses; - } - - [HttpGet("acceptLecturer/{courseId}")] - [ServiceFilter(typeof(CourseMentorOnlyAttribute))] - public async Task AcceptLecturer(long courseId, [FromQuery] string lecturerEmail) - { - await _coursesService.AcceptLecturerAsync(courseId, lecturerEmail); - return Ok(); - } + [HttpDelete("{courseId}")] + [ServiceFilter(typeof(CourseMentorOnlyAttribute))] + public async Task DeleteCourse(long courseId) + { + await _coursesService.DeleteAsync(courseId); + return Ok(); + } - [HttpGet("getLecturersAvailableForCourse/{courseId}")] - [ProducesResponseType(typeof(AccountDataDto[]), (int)HttpStatusCode.OK)] - public async Task GetLecturersAvailableForCourse(long courseId) - { - var mentorId = Request.GetMentorId(); - var result = await _coursesService.GetLecturersAvailableForCourse(courseId, mentorId); - return result == null - ? NotFound() as IActionResult - : Ok(result); - } - - //TODO: optimize - [HttpGet("taskDeadlines")] - public async Task GetUserDeadlines() + [HttpPost("update/{courseId}")] + [ServiceFilter(typeof(CourseMentorOnlyAttribute))] + public async Task UpdateCourse(long courseId, [FromBody] UpdateCourseViewModel courseViewModel) + { + await _coursesService.UpdateAsync(courseId, new Course { - var userId = Request.GetUserIdFromHeader(); - var courseIds = await _courseMatesRepository.FindAll(t => t.StudentId == userId).Select(t => t.CourseId) - .ToListAsync(); - - var currentDate = DateTimeUtils.GetMoscowNow(); - var courses = await _coursesRepository - .FindAll(t => courseIds.Contains(t.Id)) - .Include(t => t.Homeworks) - .ThenInclude(t => t.Tasks) - .ToListAsync(); - - var result = courses - .SelectMany(course => course.Homeworks - .SelectMany(x => x.Tasks) - .Where(t => t.HasDeadline && t.PublicationDate <= currentDate && t.DeadlineDate > currentDate) - .Select(task => new TaskDeadlineDto - { - TaskId = task.Id, - TaskTitle = task.Title, - CourseTitle = course.Name + " / " + course.GroupName, - PublicationDate = task.PublicationDate, - MaxRating = task.MaxRating, - DeadlineDate = task.DeadlineDate!.Value - })) - .OrderBy(t => t.DeadlineDate) - .ToArray(); - - return result; - } + Name = courseViewModel.Name, + GroupName = courseViewModel.GroupName, + IsCompleted = courseViewModel.IsCompleted, + IsOpen = courseViewModel.IsOpen + }); + + return Ok(); + } + + [HttpPost("signInCourse/{courseId}")] + public async Task SignInCourse(long courseId, [FromQuery] string studentId) + { + return await _coursesService.AddStudentAsync(courseId, studentId) + ? Ok() + : NotFound(); + } + + [HttpPost("acceptStudent/{courseId}")] + [ServiceFilter(typeof(CourseMentorOnlyAttribute))] + public async Task AcceptStudent(long courseId, [FromQuery] string studentId) + { + return await _coursesService.AcceptCourseMateAsync(courseId, studentId) + ? Ok() + : NotFound(); + } + + [HttpPost("rejectStudent/{courseId}")] + [ServiceFilter(typeof(CourseMentorOnlyAttribute))] + public async Task RejectStudent(long courseId, [FromQuery] string studentId) + { + return await _coursesService.RejectCourseMateAsync(courseId, studentId) + ? Ok() + : NotFound(); + } + + [HttpGet("userCourses")] + public async Task GetUserCourses() + { + var userId = Request.GetUserIdFromHeader(); + var coursesFromDb = await _coursesService.GetUserCoursesAsync(userId); + var courses = _mapper.Map(coursesFromDb).ToArray(); + return courses; + } + + [HttpGet("acceptLecturer/{courseId}")] + [ServiceFilter(typeof(CourseMentorOnlyAttribute))] + public async Task AcceptLecturer(long courseId, [FromQuery] string lecturerEmail) + { + await _coursesService.AcceptLecturerAsync(courseId, lecturerEmail); + return Ok(); + } + + [HttpGet("getLecturersAvailableForCourse/{courseId}")] + [ProducesResponseType(typeof(AccountDataDto[]), (int)HttpStatusCode.OK)] + public async Task GetLecturersAvailableForCourse(long courseId) + { + var mentorId = Request.GetMentorId(); + var result = await _coursesService.GetLecturersAvailableForCourse(courseId, mentorId); + return result == null + ? NotFound() + : Ok(result); + } + + //TODO: optimize + [HttpGet("taskDeadlines")] + public async Task GetUserDeadlines() + { + var userId = Request.GetUserIdFromHeader(); + var courseIds = await _courseMatesRepository.FindAll(t => t.StudentId == userId).Select(t => t.CourseId) + .ToListAsync(); + + var currentDate = DateTimeUtils.GetMoscowNow(); + var courses = await _coursesRepository + .FindAll(t => courseIds.Contains(t.Id)) + .Include(t => t.Homeworks) + .ThenInclude(t => t.Tasks) + .ToListAsync(); + + var result = courses + .SelectMany(course => course.Homeworks + .SelectMany(x => x.Tasks) + .Where(t => t.HasDeadline && t.PublicationDate <= currentDate && t.DeadlineDate > currentDate) + .Select(task => new TaskDeadlineDto + { + TaskId = task.Id, + TaskTitle = task.Title, + CourseTitle = course.Name + " / " + course.GroupName, + PublicationDate = task.PublicationDate, + MaxRating = task.MaxRating, + DeadlineDate = task.DeadlineDate!.Value + })) + .OrderBy(t => t.DeadlineDate) + .ToArray(); + + return result; } } diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Controllers/HomeworksController.cs b/HwProj.CoursesService/HwProj.CoursesService.API/Controllers/HomeworksController.cs index 1b29fd1a3..590dcf205 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Controllers/HomeworksController.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.API/Controllers/HomeworksController.cs @@ -6,56 +6,55 @@ using HwProj.Models.CoursesService.ViewModels; using Microsoft.AspNetCore.Mvc; -namespace HwProj.CoursesService.API.Controllers +namespace HwProj.CoursesService.API.Controllers; + +[Route("api/[controller]")] +[ApiController] +public class HomeworksController : Controller { - [Route("api/[controller]")] - [ApiController] - public class HomeworksController : Controller - { - private readonly IHomeworksService _homeworksService; - private readonly IMapper _mapper; + private readonly IHomeworksService _homeworksService; + private readonly IMapper _mapper; - public HomeworksController(IHomeworksService homeworksService, IMapper mapper) - { - _homeworksService = homeworksService; - _mapper = mapper; - } + public HomeworksController(IHomeworksService homeworksService, IMapper mapper) + { + _homeworksService = homeworksService; + _mapper = mapper; + } - [HttpPost("{courseId}/add")] - [ServiceFilter(typeof(CourseMentorOnlyAttribute))] - public async Task AddHomework(long courseId, [FromBody] CreateHomeworkViewModel homeworkViewModel) - { - homeworkViewModel.Tasks.ForEach(task => task.InitializeDeadline()); - var homework = _mapper.Map(homeworkViewModel); - var homeworkId = await _homeworksService.AddHomeworkAsync(courseId, homework); - return homeworkId; - } + [HttpPost("{courseId}/add")] + [ServiceFilter(typeof(CourseMentorOnlyAttribute))] + public async Task AddHomework(long courseId, [FromBody] CreateHomeworkViewModel homeworkViewModel) + { + homeworkViewModel.Tasks.ForEach(task => task.InitializeDeadline()); + var homework = _mapper.Map(homeworkViewModel); + var homeworkId = await _homeworksService.AddHomeworkAsync(courseId, homework); + return homeworkId; + } - [HttpGet("get/{homeworkId}")] - public async Task GetHomework(long homeworkId) - { - var homeworkFromDb = await _homeworksService.GetHomeworkAsync(homeworkId); - var homework = _mapper.Map(homeworkFromDb); - return homework; - } + [HttpGet("get/{homeworkId}")] + public async Task GetHomework(long homeworkId) + { + var homeworkFromDb = await _homeworksService.GetHomeworkAsync(homeworkId); + var homework = _mapper.Map(homeworkFromDb); + return homework; + } - [HttpDelete("delete/{homeworkId}")] - [ServiceFilter(typeof(CourseMentorOnlyAttribute))] - public async Task DeleteHomework(long homeworkId) - { - await _homeworksService.DeleteHomeworkAsync(homeworkId); - } + [HttpDelete("delete/{homeworkId}")] + [ServiceFilter(typeof(CourseMentorOnlyAttribute))] + public async Task DeleteHomework(long homeworkId) + { + await _homeworksService.DeleteHomeworkAsync(homeworkId); + } - [HttpPut("update/{homeworkId}")] - [ServiceFilter(typeof(CourseMentorOnlyAttribute))] - public async Task UpdateHomework(long homeworkId, [FromBody] CreateHomeworkViewModel homeworkViewModel) + [HttpPut("update/{homeworkId}")] + [ServiceFilter(typeof(CourseMentorOnlyAttribute))] + public async Task UpdateHomework(long homeworkId, [FromBody] CreateHomeworkViewModel homeworkViewModel) + { + homeworkViewModel.Tasks.ForEach(task => task.InitializeDeadline()); + await _homeworksService.UpdateHomeworkAsync(homeworkId, new Homework { - homeworkViewModel.Tasks.ForEach(task => task.InitializeDeadline()); - await _homeworksService.UpdateHomeworkAsync(homeworkId, new Homework - { - Title = homeworkViewModel.Title, - Description = homeworkViewModel.Description - }); - } + Title = homeworkViewModel.Title, + Description = homeworkViewModel.Description + }); } -} +} \ No newline at end of file diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Controllers/SystemController.cs b/HwProj.CoursesService/HwProj.CoursesService.API/Controllers/SystemController.cs index c7402ea90..651a11b75 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Controllers/SystemController.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.API/Controllers/SystemController.cs @@ -1,12 +1,11 @@ using Microsoft.AspNetCore.Mvc; -namespace HwProj.CoursesService.API.Controllers +namespace HwProj.CoursesService.API.Controllers; + +[Route("api/[controller]")] +[ApiController] +public class SystemController : ControllerBase { - [Route("api/[controller]")] - [ApiController] - public class SystemController : ControllerBase - { - [HttpGet("status")] - public IActionResult Status() => Ok(); - } -} + [HttpGet("status")] + public IActionResult Status() => Ok(); +} \ No newline at end of file diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Controllers/TasksController.cs b/HwProj.CoursesService/HwProj.CoursesService.API/Controllers/TasksController.cs index 19c042933..08838175e 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Controllers/TasksController.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.API/Controllers/TasksController.cs @@ -6,67 +6,66 @@ using HwProj.Models.CoursesService.ViewModels; using Microsoft.AspNetCore.Mvc; -namespace HwProj.CoursesService.API.Controllers +namespace HwProj.CoursesService.API.Controllers; + +[Route("api/[controller]")] +[ApiController] +public class TasksController : Controller { - [Route("api/[controller]")] - [ApiController] - public class TasksController : Controller + private readonly ITasksService _tasksService; + private readonly IMapper _mapper; + + public TasksController(ITasksService tasksService, IMapper mapper) { - private readonly ITasksService _tasksService; - private readonly IMapper _mapper; + _tasksService = tasksService; + _mapper = mapper; + } - public TasksController(ITasksService tasksService, IMapper mapper) - { - _tasksService = tasksService; - _mapper = mapper; - } + [HttpGet("get/{taskId}")] + public async Task GetTask(long taskId) + { + var taskFromDb = await _tasksService.GetTaskAsync(taskId); - [HttpGet("get/{taskId}")] - public async Task GetTask(long taskId) + if (taskFromDb == null) { - var taskFromDb = await _tasksService.GetTaskAsync(taskId); - - if (taskFromDb == null) - { - return NotFound(); - } - - var task = _mapper.Map(taskFromDb); - return Ok(task); + return NotFound(); } + + var task = _mapper.Map(taskFromDb); + return Ok(task); + } - [HttpPost("{homeworkId}/add")] - [ServiceFilter(typeof(CourseMentorOnlyAttribute))] - public async Task AddTask(long homeworkId, [FromBody] CreateTaskViewModel taskViewModel) - { - taskViewModel.InitializeDeadline(); - var task = _mapper.Map(taskViewModel); - var taskId = await _tasksService.AddTaskAsync(homeworkId, task); - return taskId; - } + [HttpPost("{homeworkId}/add")] + [ServiceFilter(typeof(CourseMentorOnlyAttribute))] + public async Task AddTask(long homeworkId, [FromBody] CreateTaskViewModel taskViewModel) + { + taskViewModel.InitializeDeadline(); + var task = _mapper.Map(taskViewModel); + var taskId = await _tasksService.AddTaskAsync(homeworkId, task); + return taskId; + } - [HttpDelete("delete/{taskId}")] //bug with rights - [ServiceFilter(typeof(CourseMentorOnlyAttribute))] - public async Task DeleteTask(long taskId) - { - await _tasksService.DeleteTaskAsync(taskId); - } + [HttpDelete("delete/{taskId}")] //bug with rights + [ServiceFilter(typeof(CourseMentorOnlyAttribute))] + public async Task DeleteTask(long taskId) + { + await _tasksService.DeleteTaskAsync(taskId); + } - [HttpPut("update/{taskId}")] - [ServiceFilter(typeof(CourseMentorOnlyAttribute))] - public async Task UpdateTask(long taskId, [FromBody] CreateTaskViewModel taskViewModel) + [HttpPut("update/{taskId}")] + [ServiceFilter(typeof(CourseMentorOnlyAttribute))] + public async Task UpdateTask(long taskId, [FromBody] CreateTaskViewModel taskViewModel) + { + taskViewModel.InitializeDeadline(); + await _tasksService.UpdateTaskAsync(taskId, new HomeworkTask() { - taskViewModel.InitializeDeadline(); - await _tasksService.UpdateTaskAsync(taskId, new HomeworkTask() - { - Title = taskViewModel.Title, - Description = taskViewModel.Description, - MaxRating = taskViewModel.MaxRating, - DeadlineDate = taskViewModel.DeadlineDate, - HasDeadline = taskViewModel.HasDeadline, - IsDeadlineStrict = taskViewModel.IsDeadlineStrict, - PublicationDate = taskViewModel.PublicationDate - }); - } + Title = taskViewModel.Title, + Description = taskViewModel.Description, + MaxRating = taskViewModel.MaxRating, + DeadlineDate = taskViewModel.DeadlineDate, + HasDeadline = taskViewModel.HasDeadline, + IsDeadlineStrict = taskViewModel.IsDeadlineStrict, + PublicationDate = taskViewModel.PublicationDate + }); } -} +} \ No newline at end of file diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Events/LecturerAcceptToCourseEvent.cs b/HwProj.CoursesService/HwProj.CoursesService.API/Events/LecturerAcceptToCourseEvent.cs index 163af8672..7376481df 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Events/LecturerAcceptToCourseEvent.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.API/Events/LecturerAcceptToCourseEvent.cs @@ -1,12 +1,11 @@ using HwProj.EventBus.Client; -namespace HwProj.CoursesService.API.Events +namespace HwProj.CoursesService.API.Events; + +public class LecturerAcceptToCourseEvent : Event { - public class LecturerAcceptToCourseEvent : Event - { - public long CourseId { get; set; } - public string CourseName { get; set; } - public string MentorIds { get; set; } - public string StudentId { get; set; } - } -} + public long CourseId { get; set; } + public string CourseName { get; set; } + public string MentorIds { get; set; } + public string StudentId { get; set; } +} \ No newline at end of file diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Events/LecturerInvitedToCourseEvent.cs b/HwProj.CoursesService/HwProj.CoursesService.API/Events/LecturerInvitedToCourseEvent.cs index 31be36694..883fae621 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Events/LecturerInvitedToCourseEvent.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.API/Events/LecturerInvitedToCourseEvent.cs @@ -1,12 +1,11 @@ using HwProj.EventBus.Client; -namespace HwProj.CoursesService.API.Events +namespace HwProj.CoursesService.API.Events; + +public class LecturerInvitedToCourseEvent : Event { - public class LecturerInvitedToCourseEvent : Event - { - public long CourseId { get; set; } - public string CourseName { get; set; } - public string MentorId { get; set; } - public string MentorEmail { get; set; } - } -} + public long CourseId { get; set; } + public string CourseName { get; set; } + public string MentorId { get; set; } + public string MentorEmail { get; set; } +} \ No newline at end of file diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Events/LecturerRejectToCourseEvent.cs b/HwProj.CoursesService/HwProj.CoursesService.API/Events/LecturerRejectToCourseEvent.cs index 9386a6cb1..05e0aa550 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Events/LecturerRejectToCourseEvent.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.API/Events/LecturerRejectToCourseEvent.cs @@ -1,12 +1,11 @@ using HwProj.EventBus.Client; -namespace HwProj.CoursesService.API.Events +namespace HwProj.CoursesService.API.Events; + +public class LecturerRejectToCourseEvent : Event { - public class LecturerRejectToCourseEvent : Event - { - public long CourseId { get; set; } - public string CourseName { get; set; } - public string MentorIds { get; set; } - public string StudentId { get; set; } - } -} + public long CourseId { get; set; } + public string CourseName { get; set; } + public string MentorIds { get; set; } + public string StudentId { get; set; } +} \ No newline at end of file diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Events/NewCourseMateEvent.cs b/HwProj.CoursesService/HwProj.CoursesService.API/Events/NewCourseMateEvent.cs index 747917731..c48968346 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Events/NewCourseMateEvent.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.API/Events/NewCourseMateEvent.cs @@ -1,13 +1,12 @@ using HwProj.EventBus.Client; -namespace HwProj.CoursesService.API.Events +namespace HwProj.CoursesService.API.Events; + +public class NewCourseMateEvent : Event { - public class NewCourseMateEvent : Event - { - public long CourseId { get; set; } - public string CourseName { get; set; } - public string MentorIds { get; set; } - public string StudentId { get; set; } - public bool IsAccepted { get; set; } - } + public long CourseId { get; set; } + public string CourseName { get; set; } + public string MentorIds { get; set; } + public string StudentId { get; set; } + public bool IsAccepted { get; set; } } \ No newline at end of file diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Events/NewHomeworkEvent.cs b/HwProj.CoursesService/HwProj.CoursesService.API/Events/NewHomeworkEvent.cs index b78429c18..d1778bf27 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Events/NewHomeworkEvent.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.API/Events/NewHomeworkEvent.cs @@ -1,17 +1,16 @@ using HwProj.EventBus.Client; using HwProj.Models.CoursesService.ViewModels; -namespace HwProj.CoursesService.API.Events +namespace HwProj.CoursesService.API.Events; + +public class NewHomeworkEvent : Event { - public class NewHomeworkEvent : Event - { - public string Homework { get; set; } - public CourseDTO Course { get; set; } + public string Homework { get; set; } + public CourseDTO Course { get; set; } - public NewHomeworkEvent(string homework, CourseDTO course) - { - Homework = homework; - Course = course; - } + public NewHomeworkEvent(string homework, CourseDTO course) + { + Homework = homework; + Course = course; } -} +} \ No newline at end of file diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Events/NewHomeworkTaskEvent.cs b/HwProj.CoursesService/HwProj.CoursesService.API/Events/NewHomeworkTaskEvent.cs index 3a5ed857a..ee126f776 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Events/NewHomeworkTaskEvent.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.API/Events/NewHomeworkTaskEvent.cs @@ -2,21 +2,20 @@ using HwProj.EventBus.Client; using HwProj.Models.CoursesService.ViewModels; -namespace HwProj.CoursesService.API.Events +namespace HwProj.CoursesService.API.Events; + +public class NewHomeworkTaskEvent : Event { - public class NewHomeworkTaskEvent : Event + public NewHomeworkTaskEvent(string taskTitle, long taskId, DateTime? deadline, CourseDTO course) { - public NewHomeworkTaskEvent(string taskTitle, long taskId, DateTime? deadline, CourseDTO course) - { - TaskTitle = taskTitle; - TaskId = taskId; - Deadline = deadline; - Course = course; - } - - public string TaskTitle { get; set; } - public long TaskId { get; set; } - public DateTime? Deadline { get; set; } - public CourseDTO Course { get; set; } + TaskTitle = taskTitle; + TaskId = taskId; + Deadline = deadline; + Course = course; } -} + + public string TaskTitle { get; set; } + public long TaskId { get; set; } + public DateTime? Deadline { get; set; } + public CourseDTO Course { get; set; } +} \ No newline at end of file diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Events/UpdateHomeworkEvent.cs b/HwProj.CoursesService/HwProj.CoursesService.API/Events/UpdateHomeworkEvent.cs index 9045f256d..87ebdca75 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Events/UpdateHomeworkEvent.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.API/Events/UpdateHomeworkEvent.cs @@ -1,17 +1,16 @@ using HwProj.EventBus.Client; using HwProj.Models.CoursesService.ViewModels; -namespace HwProj.CoursesService.API.Events +namespace HwProj.CoursesService.API.Events; + +public class UpdateHomeworkEvent : Event { - public class UpdateHomeworkEvent : Event - { - public HomeworkViewModel Homework { get; set; } - public CourseDTO Course { get; set; } + public HomeworkViewModel Homework { get; set; } + public CourseDTO Course { get; set; } - public UpdateHomeworkEvent(HomeworkViewModel homework, CourseDTO course) - { - Homework = homework; - Course = course; - } + public UpdateHomeworkEvent(HomeworkViewModel homework, CourseDTO course) + { + Homework = homework; + Course = course; } -} +} \ No newline at end of file diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Events/UpdateSolutionMaxRatingEvent.cs b/HwProj.CoursesService/HwProj.CoursesService.API/Events/UpdateSolutionMaxRatingEvent.cs index 59f77ce4c..9e7cafcd5 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Events/UpdateSolutionMaxRatingEvent.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.API/Events/UpdateSolutionMaxRatingEvent.cs @@ -1,18 +1,17 @@ using HwProj.EventBus.Client; -namespace HwProj.CoursesService.API.Events +namespace HwProj.CoursesService.API.Events; + +public class UpdateSolutionMaxRatingEvent : Event { - public class UpdateSolutionMaxRatingEvent : Event - { - public long TaskId { get; set; } - public long SolutionId { get; set; } - public int MaxRating { get; set; } + public long TaskId { get; set; } + public long SolutionId { get; set; } + public int MaxRating { get; set; } - public UpdateSolutionMaxRatingEvent(long taskId, long solutionId, int rating) - { - TaskId = taskId; - MaxRating = rating; - SolutionId = solutionId; - } + public UpdateSolutionMaxRatingEvent(long taskId, long solutionId, int rating) + { + TaskId = taskId; + MaxRating = rating; + SolutionId = solutionId; } -} +} \ No newline at end of file diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Events/UpdateTaskMaxRatingEvent.cs b/HwProj.CoursesService/HwProj.CoursesService.API/Events/UpdateTaskMaxRatingEvent.cs index 4f20de847..ba561e763 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Events/UpdateTaskMaxRatingEvent.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.API/Events/UpdateTaskMaxRatingEvent.cs @@ -1,19 +1,18 @@ using HwProj.EventBus.Client; using HwProj.Models.CoursesService.ViewModels; -namespace HwProj.CoursesService.API.Events +namespace HwProj.CoursesService.API.Events; + +public class UpdateTaskMaxRatingEvent : Event { - public class UpdateTaskMaxRatingEvent : Event - { - public CourseDTO Course { get; set; } - public HomeworkTaskViewModel Task { get; set; } - public int MaxRating { get; set; } + public CourseDTO Course { get; set; } + public HomeworkTaskViewModel Task { get; set; } + public int MaxRating { get; set; } - public UpdateTaskMaxRatingEvent(CourseDTO course, HomeworkTaskViewModel task, int rating) - { - Course = course; - Task = task; - MaxRating = rating; - } + public UpdateTaskMaxRatingEvent(CourseDTO course, HomeworkTaskViewModel task, int rating) + { + Course = course; + Task = task; + MaxRating = rating; } -} +} \ No newline at end of file diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Filters/CourseMentorOnlyAttribute.cs b/HwProj.CoursesService/HwProj.CoursesService.API/Filters/CourseMentorOnlyAttribute.cs index bb9fbb6a7..02d7b5de4 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Filters/CourseMentorOnlyAttribute.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.API/Filters/CourseMentorOnlyAttribute.cs @@ -6,32 +6,31 @@ using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.AspNetCore.Routing; -namespace HwProj.CoursesService.API.Filters +namespace HwProj.CoursesService.API.Filters; + +public class CourseMentorOnlyAttribute : Attribute, IAuthorizationFilter { - public class CourseMentorOnlyAttribute : Attribute, IAuthorizationFilter + private readonly ICoursesService _coursesService; + + public CourseMentorOnlyAttribute(ICoursesService coursesService) { - private readonly ICoursesService _coursesService; + _coursesService = coursesService; + } - public CourseMentorOnlyAttribute(ICoursesService coursesService) - { - _coursesService = coursesService; - } + public void OnAuthorization(AuthorizationFilterContext context) + { + var routeData = context.HttpContext.GetRouteData(); + var headers = context.HttpContext.Request.Headers; - public void OnAuthorization(AuthorizationFilterContext context) + if (routeData.Values.TryGetValue("courseId", out var courseId)) { - var routeData = context.HttpContext.GetRouteData(); - var headers = context.HttpContext.Request.Headers; + headers.TryGetValue("UserId", out var userId); + var mentorIds = _coursesService.GetCourseLecturers(long.Parse(courseId.ToString())).Result; - if (routeData.Values.TryGetValue("courseId", out var courseId)) + if (!mentorIds.Contains(userId.ToString())) { - headers.TryGetValue("UserId", out var userId); - var mentorIds = _coursesService.GetCourseLecturers(long.Parse(courseId.ToString())).Result; - - if (!mentorIds.Contains(userId.ToString())) - { - context.Result = new StatusCodeResult(StatusCodes.Status403Forbidden); - } + context.Result = new StatusCodeResult(StatusCodes.Status403Forbidden); } } } -} +} \ No newline at end of file diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/HwProj.CoursesService.API.csproj b/HwProj.CoursesService/HwProj.CoursesService.API/HwProj.CoursesService.API.csproj index 0c82fe45c..6400981f6 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/HwProj.CoursesService.API.csproj +++ b/HwProj.CoursesService/HwProj.CoursesService.API/HwProj.CoursesService.API.csproj @@ -1,6 +1,6 @@  - netcoreapp2.2 + net6.0 ..\..\docker-compose.dcproj Linux ..\.. @@ -11,17 +11,12 @@ - - - - - - + + - - \ No newline at end of file + diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Models/Course.cs b/HwProj.CoursesService/HwProj.CoursesService.API/Models/Course.cs index a96e4ede9..37237aee5 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Models/Course.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.API/Models/Course.cs @@ -2,19 +2,18 @@ using System.ComponentModel.DataAnnotations; using HwProj.Repositories; -namespace HwProj.CoursesService.API.Models +namespace HwProj.CoursesService.API.Models; + +public class Course : IEntity { - public class Course : IEntity - { - [Key] - public long Id { get; set; } - public string Name { get; set; } - public string GroupName { get; set; } - public bool IsOpen { get; set; } - public string InviteCode { get; set; } - public bool IsCompleted { get; set; } - public string MentorIds { get; set; } - public List CourseMates { get; set; } = new List(); - public List Homeworks { get; set; } = new List(); - } -} + [Key] + public long Id { get; set; } + public string Name { get; set; } + public string GroupName { get; set; } + public bool IsOpen { get; set; } + public string InviteCode { get; set; } + public bool IsCompleted { get; set; } + public string MentorIds { get; set; } + public List CourseMates { get; set; } = new(); + public List Homeworks { get; set; } = new(); +} \ No newline at end of file diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Models/CourseContext.cs b/HwProj.CoursesService/HwProj.CoursesService.API/Models/CourseContext.cs index d3cc3dac0..94921bfb5 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Models/CourseContext.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.API/Models/CourseContext.cs @@ -1,26 +1,25 @@ using Microsoft.EntityFrameworkCore; -namespace HwProj.CoursesService.API.Models +namespace HwProj.CoursesService.API.Models; + +public sealed class CourseContext : DbContext { - public sealed class CourseContext : DbContext - { - public DbSet Courses { get; set; } - public DbSet CourseMates { get; set; } - public DbSet Groups { get; set; } - public DbSet GroupMates { get; set; } - public DbSet TasksModels { get; set; } - public DbSet Homeworks { get; set; } - public DbSet Tasks { get; set; } + public DbSet Courses { get; set; } + public DbSet CourseMates { get; set; } + public DbSet Groups { get; set; } + public DbSet GroupMates { get; set; } + public DbSet TasksModels { get; set; } + public DbSet Homeworks { get; set; } + public DbSet Tasks { get; set; } - public CourseContext(DbContextOptions options) - : base(options) - { - Database.EnsureCreated(); - } + public CourseContext(DbContextOptions options) + : base(options) + { + Database.EnsureCreated(); + } - protected override void OnModelCreating(ModelBuilder modelBuilder) - { - modelBuilder.Entity().HasAlternateKey(u => new { u.GroupId, u.StudentId }); - } + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + modelBuilder.Entity().HasAlternateKey(u => new { u.GroupId, u.StudentId }); } -} +} \ No newline at end of file diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Models/CourseMate.cs b/HwProj.CoursesService/HwProj.CoursesService.API/Models/CourseMate.cs index 034abada8..fa27f00ca 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Models/CourseMate.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.API/Models/CourseMate.cs @@ -1,17 +1,16 @@ using System.ComponentModel.DataAnnotations; using HwProj.Repositories; -namespace HwProj.CoursesService.API.Models +namespace HwProj.CoursesService.API.Models; + +public class CourseMate : IEntity { - public class CourseMate : IEntity - { - [Key] - public long Id { get; set; } + [Key] + public long Id { get; set; } - public long CourseId { get; set; } + public long CourseId { get; set; } - public string StudentId { get; set; } + public string StudentId { get; set; } - public bool IsAccepted { get; set; } - } -} + public bool IsAccepted { get; set; } +} \ No newline at end of file diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Models/Group.cs b/HwProj.CoursesService/HwProj.CoursesService.API/Models/Group.cs index 624f8fc69..8c79b4433 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Models/Group.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.API/Models/Group.cs @@ -2,19 +2,18 @@ using System.ComponentModel.DataAnnotations; using HwProj.Repositories; -namespace HwProj.CoursesService.API.Models +namespace HwProj.CoursesService.API.Models; + +public class Group : IEntity { - public class Group : IEntity - { - [Key] - public long Id { get; set; } + [Key] + public long Id { get; set; } - public long CourseId { get; set; } + public long CourseId { get; set; } - public string Name { get; set; } + public string Name { get; set; } - public List GroupMates { get; set; } = new List(); + public List GroupMates { get; set; } = new(); - public List Tasks { get; set; } = new List(); - } -} + public List Tasks { get; set; } = new(); +} \ No newline at end of file diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Models/GroupMate.cs b/HwProj.CoursesService/HwProj.CoursesService.API/Models/GroupMate.cs index 1e4841a13..01268e0af 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Models/GroupMate.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.API/Models/GroupMate.cs @@ -1,15 +1,14 @@ using System.ComponentModel.DataAnnotations; using HwProj.Repositories; -namespace HwProj.CoursesService.API.Models +namespace HwProj.CoursesService.API.Models; + +public class GroupMate : IEntity { - public class GroupMate : IEntity - { - [Key] - public long Id { get; set; } + [Key] + public long Id { get; set; } - public long GroupId { get; set; } + public long GroupId { get; set; } - public string StudentId { get; set; } - } -} + public string StudentId { get; set; } +} \ No newline at end of file diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Models/Homework.cs b/HwProj.CoursesService/HwProj.CoursesService.API/Models/Homework.cs index fe58c148d..527131ba1 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Models/Homework.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.API/Models/Homework.cs @@ -2,20 +2,19 @@ using System.Collections.Generic; using HwProj.Repositories; -namespace HwProj.CoursesService.API.Models +namespace HwProj.CoursesService.API.Models; + +public class Homework : IEntity { - public class Homework : IEntity - { - public long Id { get; set; } + public long Id { get; set; } - public string Title { get; set; } + public string Title { get; set; } - public string Description { get; set; } + public string Description { get; set; } - public DateTime Date { get; set; } + public DateTime Date { get; set; } - public long CourseId { get; set; } + public long CourseId { get; set; } - public List Tasks { get; set; } - } -} + public List Tasks { get; set; } +} \ No newline at end of file diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Models/HomeworkTask.cs b/HwProj.CoursesService/HwProj.CoursesService.API/Models/HomeworkTask.cs index bc310ba03..f355d2fc3 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Models/HomeworkTask.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.API/Models/HomeworkTask.cs @@ -1,28 +1,27 @@ using System; using HwProj.Repositories; -namespace HwProj.CoursesService.API.Models +namespace HwProj.CoursesService.API.Models; + +public class HomeworkTask : IEntity { - public class HomeworkTask : IEntity - { - public long Id { get; set; } + public long Id { get; set; } - public string Title { get; set; } + public string Title { get; set; } - public string Description { get; set; } + public string Description { get; set; } - public int MaxRating { get; set; } + public int MaxRating { get; set; } - public bool HasDeadline { get; set; } + public bool HasDeadline { get; set; } - public DateTime? DeadlineDate { get; set; } + public DateTime? DeadlineDate { get; set; } - public bool IsDeadlineStrict { get; set; } + public bool IsDeadlineStrict { get; set; } - public DateTime PublicationDate { get; set; } + public DateTime PublicationDate { get; set; } - public long HomeworkId { get; set; } + public long HomeworkId { get; set; } - public Homework Homework { get; set; } - } -} + public Homework Homework { get; set; } +} \ No newline at end of file diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Models/TaskModel.cs b/HwProj.CoursesService/HwProj.CoursesService.API/Models/TaskModel.cs index c275e590a..efddaff2d 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Models/TaskModel.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.API/Models/TaskModel.cs @@ -1,15 +1,14 @@ using HwProj.Repositories; using System.ComponentModel.DataAnnotations; -namespace HwProj.CoursesService.API.Models +namespace HwProj.CoursesService.API.Models; + +public class TaskModel : IEntity { - public class TaskModel : IEntity - { - [Key] - public long Id { get; set; } + [Key] + public long Id { get; set; } - public long TaskId { get; set; } + public long TaskId { get; set; } - public long GroupId { get; set; } - } -} + public long GroupId { get; set; } +} \ No newline at end of file diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Program.cs b/HwProj.CoursesService/HwProj.CoursesService.API/Program.cs index 8007161a9..2e7c468be 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Program.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.API/Program.cs @@ -1,17 +1,16 @@ using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; -namespace HwProj.CoursesService.API +namespace HwProj.CoursesService.API; + +public static class Program { - public static class Program + public static void Main(string[] args) { - public static void Main(string[] args) - { - CreateWebHostBuilder(args).Build().Run(); - } - - public static IWebHostBuilder CreateWebHostBuilder(string[] args) => - WebHost.CreateDefaultBuilder(args) - .UseStartup(); + CreateWebHostBuilder(args).Build().Run(); } -} + + public static IWebHostBuilder CreateWebHostBuilder(string[] args) => + WebHost.CreateDefaultBuilder(args) + .UseStartup(); +} \ No newline at end of file diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Repositories/CourseMatesRepository.cs b/HwProj.CoursesService/HwProj.CoursesService.API/Repositories/CourseMatesRepository.cs index 9bf439ce8..5564a15c2 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Repositories/CourseMatesRepository.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.API/Repositories/CourseMatesRepository.cs @@ -1,13 +1,12 @@ using HwProj.Repositories; using HwProj.CoursesService.API.Models; -namespace HwProj.CoursesService.API.Repositories +namespace HwProj.CoursesService.API.Repositories; + +public class CourseMatesRepository : CrudRepository, ICourseMatesRepository { - public class CourseMatesRepository : CrudRepository, ICourseMatesRepository + public CourseMatesRepository(CourseContext context) + : base(context) { - public CourseMatesRepository(CourseContext context) - : base(context) - { - } } } \ No newline at end of file diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Repositories/CoursesRepository.cs b/HwProj.CoursesService/HwProj.CoursesService.API/Repositories/CoursesRepository.cs index 5b1b193b8..90964480c 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Repositories/CoursesRepository.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.API/Repositories/CoursesRepository.cs @@ -4,32 +4,31 @@ using HwProj.Repositories; using Microsoft.EntityFrameworkCore; -namespace HwProj.CoursesService.API.Repositories +namespace HwProj.CoursesService.API.Repositories; + +public class CoursesRepository : CrudRepository, ICoursesRepository { - public class CoursesRepository : CrudRepository, ICoursesRepository + public CoursesRepository(CourseContext context) + : base(context) { - public CoursesRepository(CourseContext context) - : base(context) - { - } + } - public async Task GetWithCourseMatesAsync(long id) - { - return await Context.Set() - .Include(c => c.CourseMates) - .Include(c => c.Homeworks) - .ThenInclude(c => c.Tasks) - .AsNoTracking() - .FirstOrDefaultAsync(c => c.Id == id); - } + public async Task GetWithCourseMatesAsync(long id) + { + return await Context.Set() + .Include(c => c.CourseMates) + .Include(c => c.Homeworks) + .ThenInclude(c => c.Tasks) + .AsNoTracking() + .FirstOrDefaultAsync(c => c.Id == id); + } - public IQueryable GetAllWithCourseMatesAndHomeworks() - { - return Context.Set() - .Include(c => c.CourseMates) - .Include(c => c.Homeworks) - .ThenInclude(c => c.Tasks) - .AsNoTracking(); - } + public IQueryable GetAllWithCourseMatesAndHomeworks() + { + return Context.Set() + .Include(c => c.CourseMates) + .Include(c => c.Homeworks) + .ThenInclude(c => c.Tasks) + .AsNoTracking(); } -} +} \ No newline at end of file diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Repositories/Groups/GroupMatesRepository.cs b/HwProj.CoursesService/HwProj.CoursesService.API/Repositories/Groups/GroupMatesRepository.cs index 160b20ea0..93a32ff6a 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Repositories/Groups/GroupMatesRepository.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.API/Repositories/Groups/GroupMatesRepository.cs @@ -1,13 +1,12 @@ using HwProj.Repositories; using HwProj.CoursesService.API.Models; -namespace HwProj.CoursesService.API.Repositories.Groups +namespace HwProj.CoursesService.API.Repositories.Groups; + +public class GroupMatesRepository : CrudRepository, IGroupMatesRepository { - public class GroupMatesRepository : CrudRepository, IGroupMatesRepository + public GroupMatesRepository(CourseContext context) + : base(context) { - public GroupMatesRepository(CourseContext context) - : base(context) - { - } } -} +} \ No newline at end of file diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Repositories/Groups/GroupsRepository.cs b/HwProj.CoursesService/HwProj.CoursesService.API/Repositories/Groups/GroupsRepository.cs index e866925dd..a75c710dd 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Repositories/Groups/GroupsRepository.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.API/Repositories/Groups/GroupsRepository.cs @@ -4,33 +4,32 @@ using HwProj.Repositories; using Microsoft.EntityFrameworkCore; -namespace HwProj.CoursesService.API.Repositories.Groups +namespace HwProj.CoursesService.API.Repositories.Groups; + +public class GroupsRepository : CrudRepository, IGroupsRepository { - public class GroupsRepository : CrudRepository, IGroupsRepository + public GroupsRepository(CourseContext context) + : base(context) { - public GroupsRepository(CourseContext context) - : base(context) - { - } + } - public async Task GetGroupWithGroupMatesAsync(long id) - { - return await Context.Set().Include(c => c.GroupMates) - .AsNoTracking() - .Include(c => c.Tasks) - .AsNoTracking() - .FirstOrDefaultAsync(c => c.Id == id) - .ConfigureAwait(false); - } + public async Task GetGroupWithGroupMatesAsync(long id) + { + return await Context.Set().Include(c => c.GroupMates) + .AsNoTracking() + .Include(c => c.Tasks) + .AsNoTracking() + .FirstOrDefaultAsync(c => c.Id == id) + .ConfigureAwait(false); + } - public IQueryable GetGroupsWithGroupMatesByCourse(long courseId) - { - return Context.Set() - .Where(c => c.CourseId == courseId) - .Include(c => c.GroupMates) - .AsNoTracking() - .Include(c => c.Tasks) - .AsNoTracking(); - } + public IQueryable GetGroupsWithGroupMatesByCourse(long courseId) + { + return Context.Set() + .Where(c => c.CourseId == courseId) + .Include(c => c.GroupMates) + .AsNoTracking() + .Include(c => c.Tasks) + .AsNoTracking(); } -} +} \ No newline at end of file diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Repositories/Groups/IGroupMatesRepository.cs b/HwProj.CoursesService/HwProj.CoursesService.API/Repositories/Groups/IGroupMatesRepository.cs index 3d507966c..22c0f50b1 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Repositories/Groups/IGroupMatesRepository.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.API/Repositories/Groups/IGroupMatesRepository.cs @@ -1,9 +1,8 @@ using HwProj.Repositories; using HwProj.CoursesService.API.Models; -namespace HwProj.CoursesService.API.Repositories.Groups +namespace HwProj.CoursesService.API.Repositories.Groups; + +public interface IGroupMatesRepository : ICrudRepository { - public interface IGroupMatesRepository : ICrudRepository - { - } -} +} \ No newline at end of file diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Repositories/Groups/IGroupsRepository.cs b/HwProj.CoursesService/HwProj.CoursesService.API/Repositories/Groups/IGroupsRepository.cs index 5fe53e108..1bfa34fb8 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Repositories/Groups/IGroupsRepository.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.API/Repositories/Groups/IGroupsRepository.cs @@ -3,11 +3,10 @@ using HwProj.CoursesService.API.Models; using HwProj.Repositories; -namespace HwProj.CoursesService.API.Repositories.Groups +namespace HwProj.CoursesService.API.Repositories.Groups; + +public interface IGroupsRepository : ICrudRepository { - public interface IGroupsRepository : ICrudRepository - { - Task GetGroupWithGroupMatesAsync(long id); - IQueryable GetGroupsWithGroupMatesByCourse(long courseId); - } -} + Task GetGroupWithGroupMatesAsync(long id); + IQueryable GetGroupsWithGroupMatesByCourse(long courseId); +} \ No newline at end of file diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Repositories/Groups/ITaskModelsRepository.cs b/HwProj.CoursesService/HwProj.CoursesService.API/Repositories/Groups/ITaskModelsRepository.cs index 3a179fd4b..af3510c59 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Repositories/Groups/ITaskModelsRepository.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.API/Repositories/Groups/ITaskModelsRepository.cs @@ -1,9 +1,8 @@ using HwProj.CoursesService.API.Models; using HwProj.Repositories; -namespace HwProj.CoursesService.API.Repositories.Groups +namespace HwProj.CoursesService.API.Repositories.Groups; + +public interface ITaskModelsRepository : ICrudRepository { - public interface ITaskModelsRepository : ICrudRepository - { - } -} +} \ No newline at end of file diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Repositories/Groups/TaskModelsRepository.cs b/HwProj.CoursesService/HwProj.CoursesService.API/Repositories/Groups/TaskModelsRepository.cs index 102e1dead..b9e336629 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Repositories/Groups/TaskModelsRepository.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.API/Repositories/Groups/TaskModelsRepository.cs @@ -1,13 +1,12 @@ using HwProj.CoursesService.API.Models; using HwProj.Repositories; -namespace HwProj.CoursesService.API.Repositories.Groups +namespace HwProj.CoursesService.API.Repositories.Groups; + +public class TaskModelsRepository : CrudRepository, ITaskModelsRepository { - public class TaskModelsRepository : CrudRepository, ITaskModelsRepository + public TaskModelsRepository(CourseContext context) + : base(context) { - public TaskModelsRepository(CourseContext context) - : base(context) - { - } } -} +} \ No newline at end of file diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Repositories/HomeworksRepository.cs b/HwProj.CoursesService/HwProj.CoursesService.API/Repositories/HomeworksRepository.cs index 46bb5cd2f..1f4464e7f 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Repositories/HomeworksRepository.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.API/Repositories/HomeworksRepository.cs @@ -4,31 +4,30 @@ using HwProj.Repositories; using Microsoft.EntityFrameworkCore; -namespace HwProj.CoursesService.API.Repositories +namespace HwProj.CoursesService.API.Repositories; + +public class HomeworksRepository : CrudRepository, IHomeworksRepository { - public class HomeworksRepository : CrudRepository, IHomeworksRepository + public HomeworksRepository(CourseContext context) + : base(context) { - public HomeworksRepository(CourseContext context) - : base(context) - { - } + } - public async Task GetAllWithTasksAsync() - { - return await Context.Set().Include(h => h.Tasks).ToArrayAsync(); - } + public async Task GetAllWithTasksAsync() + { + return await Context.Set().Include(h => h.Tasks).ToArrayAsync(); + } - public async Task GetAllWithTasksByCourseAsync(long courseId) - { - return await Context.Set().Include(h => h.Tasks) - .Where(h => h.CourseId == courseId) - .ToArrayAsync(); - } + public async Task GetAllWithTasksByCourseAsync(long courseId) + { + return await Context.Set().Include(h => h.Tasks) + .Where(h => h.CourseId == courseId) + .ToArrayAsync(); + } - public async Task GetWithTasksAsync(long id) - { - return await Context.Set().Include(h => h.Tasks) - .FirstOrDefaultAsync(h => h.Id == id); - } + public async Task GetWithTasksAsync(long id) + { + return await Context.Set().Include(h => h.Tasks) + .FirstOrDefaultAsync(h => h.Id == id); } -} +} \ No newline at end of file diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Repositories/ICourseMatesRepository.cs b/HwProj.CoursesService/HwProj.CoursesService.API/Repositories/ICourseMatesRepository.cs index 374bd62e0..6d4751b50 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Repositories/ICourseMatesRepository.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.API/Repositories/ICourseMatesRepository.cs @@ -1,9 +1,8 @@ using HwProj.Repositories; using HwProj.CoursesService.API.Models; -namespace HwProj.CoursesService.API.Repositories +namespace HwProj.CoursesService.API.Repositories; + +public interface ICourseMatesRepository : ICrudRepository { - public interface ICourseMatesRepository : ICrudRepository - { - } } \ No newline at end of file diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Repositories/ICoursesRepository.cs b/HwProj.CoursesService/HwProj.CoursesService.API/Repositories/ICoursesRepository.cs index 9edaa26a7..688e3708e 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Repositories/ICoursesRepository.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.API/Repositories/ICoursesRepository.cs @@ -3,11 +3,10 @@ using System.Linq; using System.Threading.Tasks; -namespace HwProj.CoursesService.API.Repositories +namespace HwProj.CoursesService.API.Repositories; + +public interface ICoursesRepository : ICrudRepository { - public interface ICoursesRepository : ICrudRepository - { - Task GetWithCourseMatesAsync(long id); - IQueryable GetAllWithCourseMatesAndHomeworks(); - } -} + Task GetWithCourseMatesAsync(long id); + IQueryable GetAllWithCourseMatesAndHomeworks(); +} \ No newline at end of file diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Repositories/IHomeworksRepository.cs b/HwProj.CoursesService/HwProj.CoursesService.API/Repositories/IHomeworksRepository.cs index 66c967996..9692bc79e 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Repositories/IHomeworksRepository.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.API/Repositories/IHomeworksRepository.cs @@ -2,12 +2,11 @@ using HwProj.CoursesService.API.Models; using HwProj.Repositories; -namespace HwProj.CoursesService.API.Repositories +namespace HwProj.CoursesService.API.Repositories; + +public interface IHomeworksRepository : ICrudRepository { - public interface IHomeworksRepository : ICrudRepository - { - Task GetAllWithTasksAsync(); - Task GetAllWithTasksByCourseAsync(long courseId); - Task GetWithTasksAsync(long id); - } -} + Task GetAllWithTasksAsync(); + Task GetAllWithTasksByCourseAsync(long courseId); + Task GetWithTasksAsync(long id); +} \ No newline at end of file diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Repositories/ITasksRepository.cs b/HwProj.CoursesService/HwProj.CoursesService.API/Repositories/ITasksRepository.cs index 724db4c3f..25559b90f 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Repositories/ITasksRepository.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.API/Repositories/ITasksRepository.cs @@ -1,9 +1,8 @@ using HwProj.CoursesService.API.Models; using HwProj.Repositories; -namespace HwProj.CoursesService.API.Repositories +namespace HwProj.CoursesService.API.Repositories; + +public interface ITasksRepository : ICrudRepository { - public interface ITasksRepository : ICrudRepository - { - } -} +} \ No newline at end of file diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Repositories/TasksRepository.cs b/HwProj.CoursesService/HwProj.CoursesService.API/Repositories/TasksRepository.cs index 0033d1d58..3f192eed1 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Repositories/TasksRepository.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.API/Repositories/TasksRepository.cs @@ -1,13 +1,12 @@ using HwProj.CoursesService.API.Models; using HwProj.Repositories; -namespace HwProj.CoursesService.API.Repositories +namespace HwProj.CoursesService.API.Repositories; + +public class TasksRepository : CrudRepository, ITasksRepository { - public class TasksRepository : CrudRepository, ITasksRepository + public TasksRepository(CourseContext context) + : base(context) { - public TasksRepository(CourseContext context) - : base(context) - { - } } -} +} \ No newline at end of file diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Services/CoursesService.cs b/HwProj.CoursesService/HwProj.CoursesService.API/Services/CoursesService.cs index 937cc1055..f1f6d3d54 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Services/CoursesService.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.API/Services/CoursesService.cs @@ -12,239 +12,238 @@ using HwProj.Models.Roles; using Microsoft.EntityFrameworkCore; -namespace HwProj.CoursesService.API.Services +namespace HwProj.CoursesService.API.Services; + +public class CoursesService : ICoursesService { - public class CoursesService : ICoursesService + private readonly ICoursesRepository _coursesRepository; + private readonly ICourseMatesRepository _courseMatesRepository; + private readonly IEventBus _eventBus; + private readonly IAuthServiceClient _authServiceClient; + + public CoursesService(ICoursesRepository coursesRepository, + ICourseMatesRepository courseMatesRepository, + IEventBus eventBus, + IAuthServiceClient authServiceClient + ) { - private readonly ICoursesRepository _coursesRepository; - private readonly ICourseMatesRepository _courseMatesRepository; - private readonly IEventBus _eventBus; - private readonly IAuthServiceClient _authServiceClient; - - public CoursesService(ICoursesRepository coursesRepository, - ICourseMatesRepository courseMatesRepository, - IEventBus eventBus, - IAuthServiceClient authServiceClient - ) - { - _coursesRepository = coursesRepository; - _courseMatesRepository = courseMatesRepository; - _eventBus = eventBus; - _authServiceClient = authServiceClient; - } + _coursesRepository = coursesRepository; + _courseMatesRepository = courseMatesRepository; + _eventBus = eventBus; + _authServiceClient = authServiceClient; + } - public async Task GetAllAsync() - { - return await _coursesRepository.GetAllWithCourseMatesAndHomeworks().ToArrayAsync(); - } + public async Task GetAllAsync() + { + return await _coursesRepository.GetAllWithCourseMatesAndHomeworks().ToArrayAsync(); + } + + public async Task GetAsync(long id, string userId) + { + var course = await _coursesRepository.GetWithCourseMatesAsync(id); + if (course == null) return null; - public async Task GetAsync(long id, string userId) + if (!course.MentorIds.Contains(userId)) { - var course = await _coursesRepository.GetWithCourseMatesAsync(id); - if (course == null) return null; + var currentDate = DateTimeUtils.GetMoscowNow(); + course.Homeworks.ForEach(hw => + hw.Tasks = new List(hw.Tasks.Where(t => currentDate >= t.PublicationDate))); - if (!course.MentorIds.Contains(userId)) - { - var currentDate = DateTimeUtils.GetMoscowNow(); - course.Homeworks.ForEach(hw => - hw.Tasks = new List(hw.Tasks.Where(t => currentDate >= t.PublicationDate))); + course.CourseMates = course.CourseMates.Where(t => t.IsAccepted || t.StudentId == userId).ToList(); + } - course.CourseMates = course.CourseMates.Where(t => t.IsAccepted || t.StudentId == userId).ToList(); - } + return course; + } - return course; - } + public async Task AddAsync(Course course, string mentorId) + { + course.MentorIds = mentorId; + course.InviteCode = Guid.NewGuid().ToString(); + return await _coursesRepository.AddAsync(course); + } - public async Task AddAsync(Course course, string mentorId) - { - course.MentorIds = mentorId; - course.InviteCode = Guid.NewGuid().ToString(); - return await _coursesRepository.AddAsync(course); - } + public async Task DeleteAsync(long id) + { + await _coursesRepository.DeleteAsync(id); + } - public async Task DeleteAsync(long id) + public async Task UpdateAsync(long courseId, Course updated) + { + await _coursesRepository.UpdateAsync(courseId, c => new Course { - await _coursesRepository.DeleteAsync(id); - } + Name = updated.Name, + GroupName = updated.GroupName, + IsCompleted = updated.IsCompleted, + IsOpen = updated.IsOpen + }); + } + + public async Task AddStudentAsync(long courseId, string studentId) + { + var getCourseTask = _coursesRepository.GetAsync(courseId); + var getCourseMateTask = + _courseMatesRepository.FindAsync(cm => cm.CourseId == courseId && cm.StudentId == studentId); + await Task.WhenAll(getCourseTask, getCourseMateTask); - public async Task UpdateAsync(long courseId, Course updated) + var course = getCourseTask.Result; + if (course == null || getCourseMateTask.Result != null) { - await _coursesRepository.UpdateAsync(courseId, c => new Course - { - Name = updated.Name, - GroupName = updated.GroupName, - IsCompleted = updated.IsCompleted, - IsOpen = updated.IsOpen - }); + return false; } - public async Task AddStudentAsync(long courseId, string studentId) + var courseMate = new CourseMate { - var getCourseTask = _coursesRepository.GetAsync(courseId); - var getCourseMateTask = - _courseMatesRepository.FindAsync(cm => cm.CourseId == courseId && cm.StudentId == studentId); - await Task.WhenAll(getCourseTask, getCourseMateTask); + CourseId = courseId, + StudentId = studentId, + IsAccepted = false + }; - var course = getCourseTask.Result; - if (course == null || getCourseMateTask.Result != null) - { - return false; - } - - var courseMate = new CourseMate - { - CourseId = courseId, - StudentId = studentId, - IsAccepted = false - }; + await _courseMatesRepository.AddAsync(courseMate); + _eventBus.Publish(new NewCourseMateEvent + { + CourseId = courseId, + CourseName = course.Name, + MentorIds = course.MentorIds, + StudentId = studentId, + IsAccepted = false + }); + + return true; + } - await _courseMatesRepository.AddAsync(courseMate); - _eventBus.Publish(new NewCourseMateEvent - { - CourseId = courseId, - CourseName = course.Name, - MentorIds = course.MentorIds, - StudentId = studentId, - IsAccepted = false - }); - - return true; - } + public async Task AcceptCourseMateAsync(long courseId, string studentId) + { + var getCourseTask = _coursesRepository.GetAsync(courseId); + var getCourseMateTask = + _courseMatesRepository.FindAsync(cm => cm.CourseId == courseId && cm.StudentId == studentId); + await Task.WhenAll(getCourseTask, getCourseMateTask); - public async Task AcceptCourseMateAsync(long courseId, string studentId) + if (getCourseTask.Result == null || getCourseMateTask.Result == null) { - var getCourseTask = _coursesRepository.GetAsync(courseId); - var getCourseMateTask = - _courseMatesRepository.FindAsync(cm => cm.CourseId == courseId && cm.StudentId == studentId); - await Task.WhenAll(getCourseTask, getCourseMateTask); + return false; + } - if (getCourseTask.Result == null || getCourseMateTask.Result == null) - { - return false; - } + await _courseMatesRepository.UpdateAsync( + getCourseMateTask.Result.Id, + cm => new CourseMate { IsAccepted = true } + ); - await _courseMatesRepository.UpdateAsync( - getCourseMateTask.Result.Id, - cm => new CourseMate { IsAccepted = true } - ); + var course = getCourseTask.Result; + var courseMate = new CourseMate + { + CourseId = courseId, + StudentId = studentId, + IsAccepted = false + }; - var course = getCourseTask.Result; - var courseMate = new CourseMate - { - CourseId = courseId, - StudentId = studentId, - IsAccepted = false - }; + _eventBus.Publish(new LecturerAcceptToCourseEvent + { + CourseId = courseId, + CourseName = course.Name, + MentorIds = course.MentorIds, + StudentId = studentId + }); - _eventBus.Publish(new LecturerAcceptToCourseEvent - { - CourseId = courseId, - CourseName = course.Name, - MentorIds = course.MentorIds, - StudentId = studentId - }); + return true; + } - return true; - } + public async Task RejectCourseMateAsync(long courseId, string studentId) + { + var getCourseTask = _coursesRepository.GetAsync(courseId); + var getCourseMateTask = + _courseMatesRepository.FindAsync(cm => cm.CourseId == courseId && cm.StudentId == studentId); + await Task.WhenAll(getCourseTask, getCourseMateTask); - public async Task RejectCourseMateAsync(long courseId, string studentId) + if (getCourseTask.Result == null || getCourseMateTask.Result == null) { - var getCourseTask = _coursesRepository.GetAsync(courseId); - var getCourseMateTask = - _courseMatesRepository.FindAsync(cm => cm.CourseId == courseId && cm.StudentId == studentId); - await Task.WhenAll(getCourseTask, getCourseMateTask); - - if (getCourseTask.Result == null || getCourseMateTask.Result == null) - { - return false; - } + return false; + } - await _courseMatesRepository.DeleteAsync(getCourseMateTask.Result.Id); + await _courseMatesRepository.DeleteAsync(getCourseMateTask.Result.Id); - var course = getCourseTask.Result; - _eventBus.Publish(new LecturerRejectToCourseEvent - { - CourseId = courseId, - CourseName = course.Name, - MentorIds = course.MentorIds, - StudentId = studentId - }); + var course = getCourseTask.Result; + _eventBus.Publish(new LecturerRejectToCourseEvent + { + CourseId = courseId, + CourseName = course.Name, + MentorIds = course.MentorIds, + StudentId = studentId + }); - return true; - } + return true; + } - public async Task GetUserCoursesAsync(string userId) - { - var studentCoursesIds = await _courseMatesRepository - .FindAll(cm => cm.StudentId == userId && cm.IsAccepted == true) - .Select(cm => cm.CourseId) - .ToArrayAsync() - .ConfigureAwait(false); + public async Task GetUserCoursesAsync(string userId) + { + var studentCoursesIds = await _courseMatesRepository + .FindAll(cm => cm.StudentId == userId && cm.IsAccepted == true) + .Select(cm => cm.CourseId) + .ToArrayAsync() + .ConfigureAwait(false); - var getStudentCoursesTasks = studentCoursesIds - .Select(id => _coursesRepository.GetAsync(id)) // TODO: optimize - .ToArray(); + var getStudentCoursesTasks = studentCoursesIds + .Select(id => _coursesRepository.GetAsync(id)) // TODO: optimize + .ToArray(); - var studentCourses = await Task.WhenAll(getStudentCoursesTasks).ConfigureAwait(false); + var studentCourses = await Task.WhenAll(getStudentCoursesTasks).ConfigureAwait(false); - var getMentorCoursesTask = _coursesRepository - .FindAll(c => c.MentorIds.Contains(userId)) - .Include(c => c.Homeworks).ThenInclude(t => t.Tasks) - .ToArrayAsync(); + var getMentorCoursesTask = _coursesRepository + .FindAll(c => c.MentorIds.Contains(userId)) + .Include(c => c.Homeworks).ThenInclude(t => t.Tasks) + .ToArrayAsync(); - var mentorCourses = await getMentorCoursesTask.ConfigureAwait(false); + var mentorCourses = await getMentorCoursesTask.ConfigureAwait(false); - return studentCourses.Union(mentorCourses).ToArray(); - } + return studentCourses.Union(mentorCourses).ToArray(); + } - public async Task AcceptLecturerAsync(long courseId, string lecturerEmail) + public async Task AcceptLecturerAsync(long courseId, string lecturerEmail) + { + var userId = await _authServiceClient.FindByEmailAsync(lecturerEmail); + if (!(userId is null)) { - var userId = await _authServiceClient.FindByEmailAsync(lecturerEmail); - if (!(userId is null)) + var course = await _coursesRepository.GetAsync(courseId); + var user = await _authServiceClient.GetAccountData(userId); + if (user.Role == Roles.LecturerRole && !course.MentorIds.Contains(userId)) { - var course = await _coursesRepository.GetAsync(courseId); - var user = await _authServiceClient.GetAccountData(userId); - if (user.Role == Roles.LecturerRole && !course.MentorIds.Contains(userId)) + string newMentors = course.MentorIds + "/" + userId; + await _coursesRepository.UpdateAsync(courseId, с => new Course + { + MentorIds = newMentors, + }); + + _eventBus.Publish(new LecturerInvitedToCourseEvent { - string newMentors = course.MentorIds + "/" + userId; - await _coursesRepository.UpdateAsync(courseId, с => new Course - { - MentorIds = newMentors, - }); - - _eventBus.Publish(new LecturerInvitedToCourseEvent - { - CourseId = courseId, - CourseName = course.Name, - MentorId = userId, - MentorEmail = lecturerEmail - }); - - //TODO: remove - await RejectCourseMateAsync(courseId, userId); - } + CourseId = courseId, + CourseName = course.Name, + MentorId = userId, + MentorEmail = lecturerEmail + }); + + //TODO: remove + await RejectCourseMateAsync(courseId, userId); } } + } - public async Task GetCourseLecturers(long courseId) - { - var course = await _coursesRepository.GetAsync(courseId); + public async Task GetCourseLecturers(long courseId) + { + var course = await _coursesRepository.GetAsync(courseId); - return course.MentorIds - .Split('/') - .ToArray(); - } + return course.MentorIds + .Split('/') + .ToArray(); + } - public async Task GetLecturersAvailableForCourse(long courseId, string mentorId) - { - var lecturers = await _authServiceClient.GetAllLecturers(); - var mentorIds = await GetCourseLecturers(courseId); - var availableLecturers = lecturers.Where(u => !mentorIds.Contains(u.Id)); - - return availableLecturers - .Select(u => new AccountDataDto(u.Id, u.Name, u.Surname, u.Email, Roles.LecturerRole, u.IsExternalAuth, - u.MiddleName)) - .ToArray(); - } + public async Task GetLecturersAvailableForCourse(long courseId, string mentorId) + { + var lecturers = await _authServiceClient.GetAllLecturers(); + var mentorIds = await GetCourseLecturers(courseId); + var availableLecturers = lecturers.Where(u => !mentorIds.Contains(u.Id)); + + return availableLecturers + .Select(u => new AccountDataDto(u.Id, u.Name, u.Surname, u.Email, Roles.LecturerRole, u.IsExternalAuth, + u.MiddleName)) + .ToArray(); } -} +} \ No newline at end of file diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Services/GroupsService.cs b/HwProj.CoursesService/HwProj.CoursesService.API/Services/GroupsService.cs index b98e4c23b..b2529cbeb 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Services/GroupsService.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.API/Services/GroupsService.cs @@ -6,120 +6,119 @@ using HwProj.Models.CoursesService.DTO; using Microsoft.EntityFrameworkCore; -namespace HwProj.CoursesService.API.Services +namespace HwProj.CoursesService.API.Services; + +public class GroupsService : IGroupsService { - public class GroupsService : IGroupsService + private readonly IGroupsRepository _groupsRepository; + private readonly IGroupMatesRepository _groupMatesRepository; + private readonly ITaskModelsRepository _taskModelsRepository; + private readonly IMapper _mapper; + + public GroupsService(IGroupsRepository groupsRepository, + IGroupMatesRepository groupMatesRepository, + ITaskModelsRepository taskModelsRepository, + IMapper mapper) { - private readonly IGroupsRepository _groupsRepository; - private readonly IGroupMatesRepository _groupMatesRepository; - private readonly ITaskModelsRepository _taskModelsRepository; - private readonly IMapper _mapper; - - public GroupsService(IGroupsRepository groupsRepository, - IGroupMatesRepository groupMatesRepository, - ITaskModelsRepository taskModelsRepository, - IMapper mapper) - { - _groupsRepository = groupsRepository; - _groupMatesRepository = groupMatesRepository; - _taskModelsRepository = taskModelsRepository; - _mapper = mapper; - } + _groupsRepository = groupsRepository; + _groupMatesRepository = groupMatesRepository; + _taskModelsRepository = taskModelsRepository; + _mapper = mapper; + } - public async Task GetAllAsync(long courseId) - { - return await _groupsRepository.GetGroupsWithGroupMatesByCourse(courseId).ToArrayAsync().ConfigureAwait(false); - } + public async Task GetAllAsync(long courseId) + { + return await _groupsRepository.GetGroupsWithGroupMatesByCourse(courseId).ToArrayAsync().ConfigureAwait(false); + } - public async Task GetGroupAsync(long groupId) - { - return await _groupsRepository.GetGroupWithGroupMatesAsync(groupId).ConfigureAwait(false); - } + public async Task GetGroupAsync(long groupId) + { + return await _groupsRepository.GetGroupWithGroupMatesAsync(groupId).ConfigureAwait(false); + } - public async Task AddGroupAsync(Group group) - { - return await _groupsRepository.AddAsync(group).ConfigureAwait(false); - } + public async Task AddGroupAsync(Group group) + { + return await _groupsRepository.AddAsync(group).ConfigureAwait(false); + } - public async Task AddGroupMateAsync(long groupId, string studentId) + public async Task AddGroupMateAsync(long groupId, string studentId) + { + var groupMate = new GroupMate { - var groupMate = new GroupMate - { - GroupId = groupId, - StudentId = studentId, - }; + GroupId = groupId, + StudentId = studentId, + }; - await _groupMatesRepository.AddAsync(groupMate).ConfigureAwait(false); - } + await _groupMatesRepository.AddAsync(groupMate).ConfigureAwait(false); + } - public async Task DeleteGroupAsync(long groupId) - { - var group = await _groupsRepository.GetAsync(groupId); - group.GroupMates.RemoveAll(cm => true); - group.Tasks.RemoveAll(cm => true); + public async Task DeleteGroupAsync(long groupId) + { + var group = await _groupsRepository.GetAsync(groupId); + group.GroupMates.RemoveAll(cm => true); + group.Tasks.RemoveAll(cm => true); - await _groupsRepository.DeleteAsync(groupId).ConfigureAwait(false); - } + await _groupsRepository.DeleteAsync(groupId).ConfigureAwait(false); + } - public async Task UpdateAsync(long groupId, Group updated) - { - var group = await _groupsRepository.GetAsync(groupId); - group.GroupMates.RemoveAll(cm => true); - group.Tasks.RemoveAll(cm => true); + public async Task UpdateAsync(long groupId, Group updated) + { + var group = await _groupsRepository.GetAsync(groupId); + group.GroupMates.RemoveAll(cm => true); + group.Tasks.RemoveAll(cm => true); - updated.GroupMates.ForEach(cm => cm.GroupId = groupId); - updated.Tasks.ForEach(cm => cm.GroupId = groupId); - var mateTasks = updated.GroupMates.Select(cm => _groupMatesRepository.AddAsync(cm)); - var idTasks = updated.Tasks.Select(cm => _taskModelsRepository.AddAsync(cm)); + updated.GroupMates.ForEach(cm => cm.GroupId = groupId); + updated.Tasks.ForEach(cm => cm.GroupId = groupId); + var mateTasks = updated.GroupMates.Select(cm => _groupMatesRepository.AddAsync(cm)); + var idTasks = updated.Tasks.Select(cm => _taskModelsRepository.AddAsync(cm)); - group.Name = updated.Name; + group.Name = updated.Name; - await Task.WhenAll(mateTasks); - await Task.WhenAll(idTasks); - } + await Task.WhenAll(mateTasks); + await Task.WhenAll(idTasks); + } - public async Task DeleteGroupMateAsync(long groupId, string studentId) + public async Task DeleteGroupMateAsync(long groupId, string studentId) + { + var group = await _groupsRepository.GetAsync(groupId).ConfigureAwait(false); + if (group == null) { - var group = await _groupsRepository.GetAsync(groupId).ConfigureAwait(false); - if (group == null) - { - return false; - } + return false; + } - var getGroupMateTask = - await _groupMatesRepository.FindAsync(cm => cm.GroupId == groupId && cm.StudentId == studentId).ConfigureAwait(false); + var getGroupMateTask = + await _groupMatesRepository.FindAsync(cm => cm.GroupId == groupId && cm.StudentId == studentId).ConfigureAwait(false); - if (getGroupMateTask == null) - { - return false; - } + if (getGroupMateTask == null) + { + return false; + } - await _groupMatesRepository.DeleteAsync(getGroupMateTask.Id); - return true; - } + await _groupMatesRepository.DeleteAsync(getGroupMateTask.Id); + return true; + } - public async Task GetStudentGroupsAsync(long courseId, string studentId) - { - var studentGroupsIds = await _groupMatesRepository - .FindAll(cm => cm.StudentId == studentId) - .Select(cm => cm.GroupId) - .ToArrayAsync() - .ConfigureAwait(false); - - var getStudentGroupsTask = studentGroupsIds - .Select(async id => await _groupsRepository.GetAsync(id).ConfigureAwait(false)) - .Where(cm => cm.Result.CourseId == courseId) - .ToArray(); - var studentGroups = await Task.WhenAll(getStudentGroupsTask).ConfigureAwait(false); - - return studentGroups.Select(c => _mapper.Map(c)).ToArray(); - } + public async Task GetStudentGroupsAsync(long courseId, string studentId) + { + var studentGroupsIds = await _groupMatesRepository + .FindAll(cm => cm.StudentId == studentId) + .Select(cm => cm.GroupId) + .ToArrayAsync() + .ConfigureAwait(false); + + var getStudentGroupsTask = studentGroupsIds + .Select(async id => await _groupsRepository.GetAsync(id).ConfigureAwait(false)) + .Where(cm => cm.Result.CourseId == courseId) + .ToArray(); + var studentGroups = await Task.WhenAll(getStudentGroupsTask).ConfigureAwait(false); + + return studentGroups.Select(c => _mapper.Map(c)).ToArray(); + } - public async Task GetTasksIds(long groupId) - { - var group = await GetGroupAsync(groupId); - return group.Tasks.Select(cm => cm.TaskId).ToArray(); - } + public async Task GetTasksIds(long groupId) + { + var group = await GetGroupAsync(groupId); + return group.Tasks.Select(cm => cm.TaskId).ToArray(); } } \ No newline at end of file diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Services/HomeworksService.cs b/HwProj.CoursesService/HwProj.CoursesService.API/Services/HomeworksService.cs index 2558e64fc..63700a806 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Services/HomeworksService.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.API/Services/HomeworksService.cs @@ -7,57 +7,56 @@ using HwProj.Models; using HwProj.Models.CoursesService.ViewModels; -namespace HwProj.CoursesService.API.Services +namespace HwProj.CoursesService.API.Services; + +public class HomeworksService : IHomeworksService { - public class HomeworksService : IHomeworksService + private readonly IHomeworksRepository _homeworksRepository; + private readonly IEventBus _eventBus; + private readonly IMapper _mapper; + private readonly ICoursesRepository _coursesRepository; + public HomeworksService(IHomeworksRepository homeworksRepository, IEventBus eventBus, IMapper mapper, ICoursesRepository coursesRepository) { - private readonly IHomeworksRepository _homeworksRepository; - private readonly IEventBus _eventBus; - private readonly IMapper _mapper; - private readonly ICoursesRepository _coursesRepository; - public HomeworksService(IHomeworksRepository homeworksRepository, IEventBus eventBus, IMapper mapper, ICoursesRepository coursesRepository) - { - _homeworksRepository = homeworksRepository; - _eventBus = eventBus; - _mapper = mapper; - _coursesRepository = coursesRepository; - } + _homeworksRepository = homeworksRepository; + _eventBus = eventBus; + _mapper = mapper; + _coursesRepository = coursesRepository; + } - public async Task AddHomeworkAsync(long courseId, Homework homework) - { - homework.CourseId = courseId; - homework.Date = DateTimeUtils.GetMoscowNow(); + public async Task AddHomeworkAsync(long courseId, Homework homework) + { + homework.CourseId = courseId; + homework.Date = DateTimeUtils.GetMoscowNow(); - var course = await _coursesRepository.GetWithCourseMatesAsync(courseId); - var courseModel = _mapper.Map(course); - _eventBus.Publish(new NewHomeworkEvent(homework.Title, courseModel)); + var course = await _coursesRepository.GetWithCourseMatesAsync(courseId); + var courseModel = _mapper.Map(course); + _eventBus.Publish(new NewHomeworkEvent(homework.Title, courseModel)); - return await _homeworksRepository.AddAsync(homework); - } + return await _homeworksRepository.AddAsync(homework); + } - public async Task GetHomeworkAsync(long homeworkId) - { - return await _homeworksRepository.GetWithTasksAsync(homeworkId); - } + public async Task GetHomeworkAsync(long homeworkId) + { + return await _homeworksRepository.GetWithTasksAsync(homeworkId); + } - public async Task DeleteHomeworkAsync(long homeworkId) - { - await _homeworksRepository.DeleteAsync(homeworkId); - } + public async Task DeleteHomeworkAsync(long homeworkId) + { + await _homeworksRepository.DeleteAsync(homeworkId); + } + + public async Task UpdateHomeworkAsync(long homeworkId, Homework update) + { + var homework = await _homeworksRepository.GetAsync(homeworkId); + var course = await _coursesRepository.GetWithCourseMatesAsync(homework.CourseId); + var courseModel = _mapper.Map(course); + var homeworkModel = _mapper.Map(homework); + _eventBus.Publish(new UpdateHomeworkEvent(homeworkModel, courseModel)); - public async Task UpdateHomeworkAsync(long homeworkId, Homework update) + await _homeworksRepository.UpdateAsync(homeworkId, hw => new Homework() { - var homework = await _homeworksRepository.GetAsync(homeworkId); - var course = await _coursesRepository.GetWithCourseMatesAsync(homework.CourseId); - var courseModel = _mapper.Map(course); - var homeworkModel = _mapper.Map(homework); - _eventBus.Publish(new UpdateHomeworkEvent(homeworkModel, courseModel)); - - await _homeworksRepository.UpdateAsync(homeworkId, hw => new Homework() - { - Title = update.Title, - Description = update.Description - }); - } + Title = update.Title, + Description = update.Description + }); } -} +} \ No newline at end of file diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Services/ICoursesService.cs b/HwProj.CoursesService/HwProj.CoursesService.API/Services/ICoursesService.cs index 44ae05177..97cdba54d 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Services/ICoursesService.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.API/Services/ICoursesService.cs @@ -2,21 +2,20 @@ using HwProj.CoursesService.API.Models; using HwProj.Models.AuthService.DTO; -namespace HwProj.CoursesService.API.Services +namespace HwProj.CoursesService.API.Services; + +public interface ICoursesService { - public interface ICoursesService - { - Task GetAllAsync(); - Task GetAsync(long id, string userId); - Task AddAsync(Course course, string mentorId); - Task DeleteAsync(long id); - Task UpdateAsync(long courseId, Course updated); - Task AddStudentAsync(long courseId, string studentId); - Task AcceptCourseMateAsync(long courseId, string studentId); - Task RejectCourseMateAsync(long courseId, string studentId); - Task GetUserCoursesAsync(string userId); - Task AcceptLecturerAsync(long courseId, string lecturerEmail); - Task GetLecturersAvailableForCourse(long courseId, string mentorId); - Task GetCourseLecturers(long courseId); - } -} + Task GetAllAsync(); + Task GetAsync(long id, string userId); + Task AddAsync(Course course, string mentorId); + Task DeleteAsync(long id); + Task UpdateAsync(long courseId, Course updated); + Task AddStudentAsync(long courseId, string studentId); + Task AcceptCourseMateAsync(long courseId, string studentId); + Task RejectCourseMateAsync(long courseId, string studentId); + Task GetUserCoursesAsync(string userId); + Task AcceptLecturerAsync(long courseId, string lecturerEmail); + Task GetLecturersAvailableForCourse(long courseId, string mentorId); + Task GetCourseLecturers(long courseId); +} \ No newline at end of file diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Services/IGroupsService.cs b/HwProj.CoursesService/HwProj.CoursesService.API/Services/IGroupsService.cs index 3a0959524..4a3c65c41 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Services/IGroupsService.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.API/Services/IGroupsService.cs @@ -2,26 +2,25 @@ using HwProj.CoursesService.API.Models; using HwProj.Models.CoursesService.DTO; -namespace HwProj.CoursesService.API.Services +namespace HwProj.CoursesService.API.Services; + +public interface IGroupsService { - public interface IGroupsService - { - Task GetAllAsync(long courseId); + Task GetAllAsync(long courseId); - Task GetGroupAsync(long groupId); + Task GetGroupAsync(long groupId); - Task AddGroupAsync(Group group); + Task AddGroupAsync(Group group); - Task DeleteGroupAsync(long id); + Task DeleteGroupAsync(long id); - Task UpdateAsync(long groupId, Group updated); + Task UpdateAsync(long groupId, Group updated); - Task AddGroupMateAsync(long groupId, string studentId); + Task AddGroupMateAsync(long groupId, string studentId); - Task DeleteGroupMateAsync(long groupId, string studentId); + Task DeleteGroupMateAsync(long groupId, string studentId); - Task GetStudentGroupsAsync(long courseId, string studentId); + Task GetStudentGroupsAsync(long courseId, string studentId); - Task GetTasksIds(long groupId); - } -} + Task GetTasksIds(long groupId); +} \ No newline at end of file diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Services/IHomeworksService.cs b/HwProj.CoursesService/HwProj.CoursesService.API/Services/IHomeworksService.cs index 5c2d98a60..4b72bf056 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Services/IHomeworksService.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.API/Services/IHomeworksService.cs @@ -1,16 +1,15 @@ using System.Threading.Tasks; using HwProj.CoursesService.API.Models; -namespace HwProj.CoursesService.API.Services +namespace HwProj.CoursesService.API.Services; + +public interface IHomeworksService { - public interface IHomeworksService - { - Task AddHomeworkAsync(long courseId, Homework homework); + Task AddHomeworkAsync(long courseId, Homework homework); - Task GetHomeworkAsync(long homeworkId); + Task GetHomeworkAsync(long homeworkId); - Task DeleteHomeworkAsync(long homeworkId); + Task DeleteHomeworkAsync(long homeworkId); - Task UpdateHomeworkAsync(long homeworkId, Homework update); - } -} + Task UpdateHomeworkAsync(long homeworkId, Homework update); +} \ No newline at end of file diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Services/ITasksService.cs b/HwProj.CoursesService/HwProj.CoursesService.API/Services/ITasksService.cs index fc7c4489d..d0c5e8439 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Services/ITasksService.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.API/Services/ITasksService.cs @@ -1,13 +1,12 @@ using System.Threading.Tasks; using HwProj.CoursesService.API.Models; -namespace HwProj.CoursesService.API.Services +namespace HwProj.CoursesService.API.Services; + +public interface ITasksService { - public interface ITasksService - { - Task GetTaskAsync(long taskId); - Task AddTaskAsync(long homeworkId, HomeworkTask task); - Task DeleteTaskAsync(long taskId); - Task UpdateTaskAsync(long taskId, HomeworkTask update); - } -} + Task GetTaskAsync(long taskId); + Task AddTaskAsync(long homeworkId, HomeworkTask task); + Task DeleteTaskAsync(long taskId); + Task UpdateTaskAsync(long taskId, HomeworkTask update); +} \ No newline at end of file diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Services/TasksService.cs b/HwProj.CoursesService/HwProj.CoursesService.API/Services/TasksService.cs index 8c849a2e6..6d44191ff 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Services/TasksService.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.API/Services/TasksService.cs @@ -7,71 +7,70 @@ using HwProj.Models; using HwProj.Models.CoursesService.ViewModels; -namespace HwProj.CoursesService.API.Services +namespace HwProj.CoursesService.API.Services; + +public class TasksService : ITasksService { - public class TasksService : ITasksService + private readonly ITasksRepository _tasksRepository; + private readonly IEventBus _eventBus; + private readonly IMapper _mapper; + private readonly ICoursesRepository _coursesRepository; + private readonly IHomeworksRepository _homeworksRepository; + + public TasksService(ITasksRepository tasksRepository, IEventBus eventBus, IMapper mapper, + ICoursesRepository coursesRepository, IHomeworksRepository homeworksRepository) { - private readonly ITasksRepository _tasksRepository; - private readonly IEventBus _eventBus; - private readonly IMapper _mapper; - private readonly ICoursesRepository _coursesRepository; - private readonly IHomeworksRepository _homeworksRepository; + _tasksRepository = tasksRepository; + _homeworksRepository = homeworksRepository; + _eventBus = eventBus; + _mapper = mapper; + _coursesRepository = coursesRepository; + } - public TasksService(ITasksRepository tasksRepository, IEventBus eventBus, IMapper mapper, - ICoursesRepository coursesRepository, IHomeworksRepository homeworksRepository) - { - _tasksRepository = tasksRepository; - _homeworksRepository = homeworksRepository; - _eventBus = eventBus; - _mapper = mapper; - _coursesRepository = coursesRepository; - } + public async Task GetTaskAsync(long taskId) + { + return await _tasksRepository.GetAsync(taskId); + } - public async Task GetTaskAsync(long taskId) - { - return await _tasksRepository.GetAsync(taskId); - } + public async Task AddTaskAsync(long homeworkId, HomeworkTask task) + { + task.HomeworkId = homeworkId; - public async Task AddTaskAsync(long homeworkId, HomeworkTask task) - { - task.HomeworkId = homeworkId; + var homework = await _homeworksRepository.GetAsync(task.HomeworkId); + var course = await _coursesRepository.GetWithCourseMatesAsync(homework.CourseId); + var courseModel = _mapper.Map(course); - var homework = await _homeworksRepository.GetAsync(task.HomeworkId); - var course = await _coursesRepository.GetWithCourseMatesAsync(homework.CourseId); - var courseModel = _mapper.Map(course); + var taskId = await _tasksRepository.AddAsync(task); - var taskId = await _tasksRepository.AddAsync(task); + if (task.PublicationDate <= DateTimeUtils.GetMoscowNow()) + _eventBus.Publish(new NewHomeworkTaskEvent(task.Title, taskId, task.DeadlineDate, courseModel)); - if (task.PublicationDate <= DateTimeUtils.GetMoscowNow()) - _eventBus.Publish(new NewHomeworkTaskEvent(task.Title, taskId, task.DeadlineDate, courseModel)); + return taskId; + } - return taskId; - } + public async Task DeleteTaskAsync(long taskId) + { + await _tasksRepository.DeleteAsync(taskId); + } - public async Task DeleteTaskAsync(long taskId) - { - await _tasksRepository.DeleteAsync(taskId); - } + public async Task UpdateTaskAsync(long taskId, HomeworkTask update) + { + var task = await _tasksRepository.GetAsync(taskId); + var taskModel = _mapper.Map(task); + var homework = await _homeworksRepository.GetAsync(task.HomeworkId); + var course = await _coursesRepository.GetWithCourseMatesAsync(homework.CourseId); + var courseModel = _mapper.Map(course); + _eventBus.Publish(new UpdateTaskMaxRatingEvent(courseModel, taskModel, update.MaxRating)); - public async Task UpdateTaskAsync(long taskId, HomeworkTask update) + await _tasksRepository.UpdateAsync(taskId, t => new HomeworkTask() { - var task = await _tasksRepository.GetAsync(taskId); - var taskModel = _mapper.Map(task); - var homework = await _homeworksRepository.GetAsync(task.HomeworkId); - var course = await _coursesRepository.GetWithCourseMatesAsync(homework.CourseId); - var courseModel = _mapper.Map(course); - _eventBus.Publish(new UpdateTaskMaxRatingEvent(courseModel, taskModel, update.MaxRating)); - - await _tasksRepository.UpdateAsync(taskId, t => new HomeworkTask() - { - Title = update.Title, - Description = update.Description, - MaxRating = update.MaxRating, - DeadlineDate = update.DeadlineDate, - HasDeadline = update.HasDeadline, - IsDeadlineStrict = update.IsDeadlineStrict, - PublicationDate = update.PublicationDate - }); - } + Title = update.Title, + Description = update.Description, + MaxRating = update.MaxRating, + DeadlineDate = update.DeadlineDate, + HasDeadline = update.HasDeadline, + IsDeadlineStrict = update.IsDeadlineStrict, + PublicationDate = update.PublicationDate + }); } -} +} \ No newline at end of file diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Startup.cs b/HwProj.CoursesService/HwProj.CoursesService.API/Startup.cs index 74c5fbae3..c52ecb045 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Startup.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.API/Startup.cs @@ -11,45 +11,44 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; -namespace HwProj.CoursesService.API +namespace HwProj.CoursesService.API; + +public class Startup { - public class Startup + public Startup(IConfiguration configuration) + { + Configuration = configuration; + } + + private IConfiguration Configuration { get; } + + public void ConfigureServices(IServiceCollection services) + { + var connectionString = ConnectionString.GetConnectionString(Configuration); + services.AddDbContext(options => options.UseSqlServer(connectionString)); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + + services.AddEventBus(Configuration); + + services.AddHttpClient(); + services.AddAuthServiceClient(); + + services.ConfigureHwProjServices("Courses API"); + } + + public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { - public Startup(IConfiguration configuration) - { - Configuration = configuration; - } - - private IConfiguration Configuration { get; } - - public void ConfigureServices(IServiceCollection services) - { - var connectionString = ConnectionString.GetConnectionString(Configuration); - services.AddDbContext(options => options.UseSqlServer(connectionString)); - services.AddScoped(); - services.AddScoped(); - services.AddScoped(); - services.AddScoped(); - services.AddScoped(); - services.AddScoped(); - services.AddScoped(); - services.AddScoped(); - services.AddScoped(); - services.AddScoped(); - services.AddScoped(); - services.AddScoped(); - - services.AddEventBus(Configuration); - - services.AddHttpClient(); - services.AddAuthServiceClient(); - - services.ConfigureHwProjServices("Courses API"); - } - - public void Configure(IApplicationBuilder app, IHostingEnvironment env) - { - app.ConfigureHwProj(env, "Courses API"); - } + app.ConfigureHwProj(env, "Courses API"); } -} \ No newline at end of file +} diff --git a/HwProj.CoursesService/HwProj.CoursesService.Client/ConfigurationExtensions.cs b/HwProj.CoursesService/HwProj.CoursesService.Client/ConfigurationExtensions.cs index 242ca7085..3f82671b8 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.Client/ConfigurationExtensions.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.Client/ConfigurationExtensions.cs @@ -1,13 +1,12 @@ using Microsoft.Extensions.DependencyInjection; -namespace HwProj.CoursesService.Client +namespace HwProj.CoursesService.Client; + +public static class ConfigurationExtensions { - public static class ConfigurationExtensions + public static IServiceCollection AddCoursesServiceClient(this IServiceCollection services) { - public static IServiceCollection AddCoursesServiceClient(this IServiceCollection services) - { - services.AddScoped(); - return services; - } + services.AddScoped(); + return services; } -} \ No newline at end of file +} diff --git a/HwProj.CoursesService/HwProj.CoursesService.Client/CoursesServiceClient.cs b/HwProj.CoursesService/HwProj.CoursesService.Client/CoursesServiceClient.cs index 3ca5abf46..99d88a159 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.Client/CoursesServiceClient.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.Client/CoursesServiceClient.cs @@ -11,404 +11,403 @@ using Microsoft.Extensions.Configuration; using Newtonsoft.Json; -namespace HwProj.CoursesService.Client +namespace HwProj.CoursesService.Client; + +public class CoursesServiceClient : ICoursesServiceClient { - public class CoursesServiceClient : ICoursesServiceClient + private readonly HttpClient _httpClient; + private readonly Uri _coursesServiceUri; + private readonly IHttpContextAccessor _httpContextAccessor; + + public CoursesServiceClient(IHttpClientFactory clientFactory, IHttpContextAccessor httpContextAccessor, + IConfiguration configuration) { - private readonly HttpClient _httpClient; - private readonly Uri _coursesServiceUri; - private readonly IHttpContextAccessor _httpContextAccessor; + _httpClient = clientFactory.CreateClient(); + _httpContextAccessor = httpContextAccessor; + _coursesServiceUri = new Uri(configuration.GetSection("Services")["Courses"]); + } - public CoursesServiceClient(IHttpClientFactory clientFactory, IHttpContextAccessor httpContextAccessor, - IConfiguration configuration) - { - _httpClient = clientFactory.CreateClient(); - _httpContextAccessor = httpContextAccessor; - _coursesServiceUri = new Uri(configuration.GetSection("Services")["Courses"]); - } + public async Task GetAllCourses() + { + using var httpRequest = new HttpRequestMessage( + HttpMethod.Get, + _coursesServiceUri + "api/Courses"); + + var response = await _httpClient.SendAsync(httpRequest); + return await response.DeserializeAsync(); + } - public async Task GetAllCourses() + public async Task GetCourseById(long courseId, string userId) + { + using var httpRequest = new HttpRequestMessage( + HttpMethod.Get, + _coursesServiceUri + $"api/Courses/{courseId}") { - using var httpRequest = new HttpRequestMessage( - HttpMethod.Get, - _coursesServiceUri + "api/Courses"); + Content = new StringContent( + JsonConvert.SerializeObject(userId), + Encoding.UTF8, + "application/json") + }; + var response = await _httpClient.SendAsync(httpRequest); + return response.IsSuccessStatusCode ? await response.DeserializeAsync() : null; + } - var response = await _httpClient.SendAsync(httpRequest); - return await response.DeserializeAsync(); - } + public async Task DeleteCourse(long courseId) + { + using var httpRequest = new HttpRequestMessage( + HttpMethod.Delete, + _coursesServiceUri + $"api/Courses/{courseId}"); - public async Task GetCourseById(long courseId, string userId) + httpRequest.AddUserId(_httpContextAccessor); + var response = await _httpClient.SendAsync(httpRequest); + return response.IsSuccessStatusCode ? Result.Success() : Result.Failed(response.ReasonPhrase); + } + + public async Task CreateCourse(CreateCourseViewModel model, string mentorId) + { + using var httpRequest = new HttpRequestMessage( + HttpMethod.Post, + _coursesServiceUri + $"api/Courses/create?mentorId={mentorId}") { - using var httpRequest = new HttpRequestMessage( - HttpMethod.Get, - _coursesServiceUri + $"api/Courses/{courseId}") - { - Content = new StringContent( - JsonConvert.SerializeObject(userId), - Encoding.UTF8, - "application/json") - }; - var response = await _httpClient.SendAsync(httpRequest); - return response.IsSuccessStatusCode ? await response.DeserializeAsync() : null; - } + Content = new StringContent( + JsonConvert.SerializeObject(model), + Encoding.UTF8, + "application/json") + }; + + var response = await _httpClient.SendAsync(httpRequest); + return await response.DeserializeAsync(); + } - public async Task DeleteCourse(long courseId) + public async Task UpdateCourse(UpdateCourseViewModel model, long courseId) + { + using var httpRequest = new HttpRequestMessage( + HttpMethod.Post, + _coursesServiceUri + $"api/Courses/update/{courseId}") { - using var httpRequest = new HttpRequestMessage( - HttpMethod.Delete, - _coursesServiceUri + $"api/Courses/{courseId}"); + Content = new StringContent( + JsonConvert.SerializeObject(model), + Encoding.UTF8, + "application/json") + }; + + httpRequest.AddUserId(_httpContextAccessor); + var response = await _httpClient.SendAsync(httpRequest); + return response.IsSuccessStatusCode ? Result.Success() : Result.Failed(response.ReasonPhrase); + } - httpRequest.AddUserId(_httpContextAccessor); - var response = await _httpClient.SendAsync(httpRequest); - return response.IsSuccessStatusCode ? Result.Success() : Result.Failed(response.ReasonPhrase); - } + public async Task SignInCourse(long courseId, string studentId) + { + using var httpRequest = new HttpRequestMessage( + HttpMethod.Post, + _coursesServiceUri + $"api/Courses/signInCourse/{courseId}?studentId={studentId}"); - public async Task CreateCourse(CreateCourseViewModel model, string mentorId) - { - using var httpRequest = new HttpRequestMessage( - HttpMethod.Post, - _coursesServiceUri + $"api/Courses/create?mentorId={mentorId}") - { - Content = new StringContent( - JsonConvert.SerializeObject(model), - Encoding.UTF8, - "application/json") - }; - - var response = await _httpClient.SendAsync(httpRequest); - return await response.DeserializeAsync(); - } + await _httpClient.SendAsync(httpRequest); + } - public async Task UpdateCourse(UpdateCourseViewModel model, long courseId) - { - using var httpRequest = new HttpRequestMessage( - HttpMethod.Post, - _coursesServiceUri + $"api/Courses/update/{courseId}") - { - Content = new StringContent( - JsonConvert.SerializeObject(model), - Encoding.UTF8, - "application/json") - }; - - httpRequest.AddUserId(_httpContextAccessor); - var response = await _httpClient.SendAsync(httpRequest); - return response.IsSuccessStatusCode ? Result.Success() : Result.Failed(response.ReasonPhrase); - } + public async Task AcceptStudent(long courseId, string studentId) + { + using var httpRequest = new HttpRequestMessage( + HttpMethod.Post, + _coursesServiceUri + $"api/Courses/acceptStudent/{courseId}?studentId={studentId}"); - public async Task SignInCourse(long courseId, string studentId) - { - using var httpRequest = new HttpRequestMessage( - HttpMethod.Post, - _coursesServiceUri + $"api/Courses/signInCourse/{courseId}?studentId={studentId}"); + httpRequest.AddUserId(_httpContextAccessor); + var response = await _httpClient.SendAsync(httpRequest); + return response.IsSuccessStatusCode ? Result.Success() : Result.Failed(response.ReasonPhrase); + } - await _httpClient.SendAsync(httpRequest); - } + public async Task RejectStudent(long courseId, string studentId) + { + using var httpRequest = new HttpRequestMessage( + HttpMethod.Post, + _coursesServiceUri + $"api/Courses/rejectStudent/{courseId}?studentId={studentId}"); - public async Task AcceptStudent(long courseId, string studentId) - { - using var httpRequest = new HttpRequestMessage( - HttpMethod.Post, - _coursesServiceUri + $"api/Courses/acceptStudent/{courseId}?studentId={studentId}"); + httpRequest.AddUserId(_httpContextAccessor); + var response = await _httpClient.SendAsync(httpRequest); + return response.IsSuccessStatusCode ? Result.Success() : Result.Failed(response.ReasonPhrase); + } - httpRequest.AddUserId(_httpContextAccessor); - var response = await _httpClient.SendAsync(httpRequest); - return response.IsSuccessStatusCode ? Result.Success() : Result.Failed(response.ReasonPhrase); - } + public async Task GetAllUserCourses() + { + using var httpRequest = new HttpRequestMessage( + HttpMethod.Get, + _coursesServiceUri + "api/Courses/userCourses"); - public async Task RejectStudent(long courseId, string studentId) - { - using var httpRequest = new HttpRequestMessage( - HttpMethod.Post, - _coursesServiceUri + $"api/Courses/rejectStudent/{courseId}?studentId={studentId}"); + httpRequest.AddUserId(_httpContextAccessor); + var response = await _httpClient.SendAsync(httpRequest); + return await response.DeserializeAsync(); + } - httpRequest.AddUserId(_httpContextAccessor); - var response = await _httpClient.SendAsync(httpRequest); - return response.IsSuccessStatusCode ? Result.Success() : Result.Failed(response.ReasonPhrase); - } + public async Task GetTaskDeadlines() + { + using var httpRequest = new HttpRequestMessage( + HttpMethod.Get, + _coursesServiceUri + "api/Courses/taskDeadlines"); + + httpRequest.AddUserId(_httpContextAccessor); + var response = await _httpClient.SendAsync(httpRequest); + return await response.DeserializeAsync(); + } - public async Task GetAllUserCourses() + public async Task> AddHomeworkToCourse(CreateHomeworkViewModel model, long courseId) + { + using var httpRequest = new HttpRequestMessage( + HttpMethod.Post, + _coursesServiceUri + $"api/Homeworks/{courseId}/add") { - using var httpRequest = new HttpRequestMessage( - HttpMethod.Get, - _coursesServiceUri + "api/Courses/userCourses"); + Content = new StringContent( + JsonConvert.SerializeObject(model), + Encoding.UTF8, + "application/json") + }; + + httpRequest.AddUserId(_httpContextAccessor); + + var response = await _httpClient.SendAsync(httpRequest); + return response.IsSuccessStatusCode + ? Result.Success(await response.DeserializeAsync()) + : Result.Failed(response.ReasonPhrase); + } - httpRequest.AddUserId(_httpContextAccessor); - var response = await _httpClient.SendAsync(httpRequest); - return await response.DeserializeAsync(); - } + public async Task GetHomework(long homeworkId) + { + using var httpRequest = new HttpRequestMessage( + HttpMethod.Get, + _coursesServiceUri + $"api/Homeworks/get/{homeworkId}"); - public async Task GetTaskDeadlines() + var response = await _httpClient.SendAsync(httpRequest); + return await response.DeserializeAsync(); + } + + public async Task UpdateHomework(CreateHomeworkViewModel model, long homeworkId) + { + using var httpRequest = new HttpRequestMessage( + HttpMethod.Put, + _coursesServiceUri + $"api/Homeworks/update/{homeworkId}") { - using var httpRequest = new HttpRequestMessage( - HttpMethod.Get, - _coursesServiceUri + "api/Courses/taskDeadlines"); + Content = new StringContent( + JsonConvert.SerializeObject(model), + Encoding.UTF8, + "application/json") + }; + + httpRequest.AddUserId(_httpContextAccessor); + var response = await _httpClient.SendAsync(httpRequest); + return response.IsSuccessStatusCode ? Result.Success() : Result.Failed(response.ReasonPhrase); + } - httpRequest.AddUserId(_httpContextAccessor); - var response = await _httpClient.SendAsync(httpRequest); - return await response.DeserializeAsync(); - } + public async Task DeleteHomework(long homeworkId) + { + using var httpRequest = new HttpRequestMessage( + HttpMethod.Delete, + _coursesServiceUri + $"api/Homeworks/delete/{homeworkId}"); - public async Task> AddHomeworkToCourse(CreateHomeworkViewModel model, long courseId) - { - using var httpRequest = new HttpRequestMessage( - HttpMethod.Post, - _coursesServiceUri + $"api/Homeworks/{courseId}/add") - { - Content = new StringContent( - JsonConvert.SerializeObject(model), - Encoding.UTF8, - "application/json") - }; - - httpRequest.AddUserId(_httpContextAccessor); - - var response = await _httpClient.SendAsync(httpRequest); - return response.IsSuccessStatusCode - ? Result.Success(await response.DeserializeAsync()) - : Result.Failed(response.ReasonPhrase); - } + httpRequest.AddUserId(_httpContextAccessor); + var response = await _httpClient.SendAsync(httpRequest); + return response.IsSuccessStatusCode ? Result.Success() : Result.Failed(response.ReasonPhrase); + } - public async Task GetHomework(long homeworkId) - { - using var httpRequest = new HttpRequestMessage( - HttpMethod.Get, - _coursesServiceUri + $"api/Homeworks/get/{homeworkId}"); + public async Task GetTask(long taskId) + { + using var httpRequest = new HttpRequestMessage( + HttpMethod.Get, + _coursesServiceUri + $"api/Tasks/get/{taskId}"); - var response = await _httpClient.SendAsync(httpRequest); - return await response.DeserializeAsync(); - } + var response = await _httpClient.SendAsync(httpRequest); + return await response.DeserializeAsync(); + } - public async Task UpdateHomework(CreateHomeworkViewModel model, long homeworkId) + public async Task> AddTask(CreateTaskViewModel taskViewModel, long homeworkId) + { + using var httpRequest = new HttpRequestMessage( + HttpMethod.Post, + _coursesServiceUri + $"api/Tasks/{homeworkId}/add") { - using var httpRequest = new HttpRequestMessage( - HttpMethod.Put, - _coursesServiceUri + $"api/Homeworks/update/{homeworkId}") - { - Content = new StringContent( - JsonConvert.SerializeObject(model), - Encoding.UTF8, - "application/json") - }; - - httpRequest.AddUserId(_httpContextAccessor); - var response = await _httpClient.SendAsync(httpRequest); - return response.IsSuccessStatusCode ? Result.Success() : Result.Failed(response.ReasonPhrase); - } + Content = new StringContent( + JsonConvert.SerializeObject(taskViewModel), + Encoding.UTF8, + "application/json") + }; + + httpRequest.AddUserId(_httpContextAccessor); + + var response = await _httpClient.SendAsync(httpRequest); + return response.IsSuccessStatusCode + ? Result.Success(await response.DeserializeAsync()) + : Result.Failed(response.ReasonPhrase); + } - public async Task DeleteHomework(long homeworkId) - { - using var httpRequest = new HttpRequestMessage( - HttpMethod.Delete, - _coursesServiceUri + $"api/Homeworks/delete/{homeworkId}"); + public async Task DeleteTask(long taskId) + { + using var httpRequest = new HttpRequestMessage( + HttpMethod.Delete, + _coursesServiceUri + $"api/Tasks/delete/{taskId}"); - httpRequest.AddUserId(_httpContextAccessor); - var response = await _httpClient.SendAsync(httpRequest); - return response.IsSuccessStatusCode ? Result.Success() : Result.Failed(response.ReasonPhrase); - } + httpRequest.AddUserId(_httpContextAccessor); + var response = await _httpClient.SendAsync(httpRequest); + return response.IsSuccessStatusCode ? Result.Success() : Result.Failed(response.ReasonPhrase); + } - public async Task GetTask(long taskId) + public async Task UpdateTask(CreateTaskViewModel taskViewModel, long taskId) + { + using var httpRequest = new HttpRequestMessage( + HttpMethod.Put, + _coursesServiceUri + $"api/Tasks/update/{taskId}") { - using var httpRequest = new HttpRequestMessage( - HttpMethod.Get, - _coursesServiceUri + $"api/Tasks/get/{taskId}"); + Content = new StringContent( + JsonConvert.SerializeObject(taskViewModel), + Encoding.UTF8, + "application/json") + }; + + httpRequest.AddUserId(_httpContextAccessor); + var response = await _httpClient.SendAsync(httpRequest); + return response.IsSuccessStatusCode ? Result.Success() : Result.Failed(response.ReasonPhrase); + } - var response = await _httpClient.SendAsync(httpRequest); - return await response.DeserializeAsync(); - } + public async Task GetAllCourseGroups(long courseId) + { + using var httpRequest = new HttpRequestMessage( + HttpMethod.Get, + _coursesServiceUri + $"api/CourseGroups/{courseId}/getAll"); - public async Task> AddTask(CreateTaskViewModel taskViewModel, long homeworkId) - { - using var httpRequest = new HttpRequestMessage( - HttpMethod.Post, - _coursesServiceUri + $"api/Tasks/{homeworkId}/add") - { - Content = new StringContent( - JsonConvert.SerializeObject(taskViewModel), - Encoding.UTF8, - "application/json") - }; - - httpRequest.AddUserId(_httpContextAccessor); - - var response = await _httpClient.SendAsync(httpRequest); - return response.IsSuccessStatusCode - ? Result.Success(await response.DeserializeAsync()) - : Result.Failed(response.ReasonPhrase); - } + var response = await _httpClient.SendAsync(httpRequest); + return await response.DeserializeAsync(); + } - public async Task DeleteTask(long taskId) + public async Task CreateCourseGroup(CreateGroupViewModel model, long courseId) + { + using var httpRequest = new HttpRequestMessage( + HttpMethod.Post, + _coursesServiceUri + $"api/CourseGroups/{courseId}/create") { - using var httpRequest = new HttpRequestMessage( - HttpMethod.Delete, - _coursesServiceUri + $"api/Tasks/delete/{taskId}"); + Content = new StringContent( + JsonConvert.SerializeObject(model), + Encoding.UTF8, + "application/json") + }; - httpRequest.AddUserId(_httpContextAccessor); - var response = await _httpClient.SendAsync(httpRequest); - return response.IsSuccessStatusCode ? Result.Success() : Result.Failed(response.ReasonPhrase); - } + httpRequest.AddUserId(_httpContextAccessor); - public async Task UpdateTask(CreateTaskViewModel taskViewModel, long taskId) - { - using var httpRequest = new HttpRequestMessage( - HttpMethod.Put, - _coursesServiceUri + $"api/Tasks/update/{taskId}") - { - Content = new StringContent( - JsonConvert.SerializeObject(taskViewModel), - Encoding.UTF8, - "application/json") - }; - - httpRequest.AddUserId(_httpContextAccessor); - var response = await _httpClient.SendAsync(httpRequest); - return response.IsSuccessStatusCode ? Result.Success() : Result.Failed(response.ReasonPhrase); - } + var response = await _httpClient.SendAsync(httpRequest); + return await response.DeserializeAsync(); + } - public async Task GetAllCourseGroups(long courseId) - { - using var httpRequest = new HttpRequestMessage( - HttpMethod.Get, - _coursesServiceUri + $"api/CourseGroups/{courseId}/getAll"); + public async Task DeleteCourseGroup(long courseId, long groupId) + { + using var httpRequest = new HttpRequestMessage( + HttpMethod.Delete, + _coursesServiceUri + $"api/CourseGroups/{courseId}/delete/{groupId}"); - var response = await _httpClient.SendAsync(httpRequest); - return await response.DeserializeAsync(); - } + httpRequest.AddUserId(_httpContextAccessor); - public async Task CreateCourseGroup(CreateGroupViewModel model, long courseId) - { - using var httpRequest = new HttpRequestMessage( - HttpMethod.Post, - _coursesServiceUri + $"api/CourseGroups/{courseId}/create") - { - Content = new StringContent( - JsonConvert.SerializeObject(model), - Encoding.UTF8, - "application/json") - }; - - httpRequest.AddUserId(_httpContextAccessor); - - var response = await _httpClient.SendAsync(httpRequest); - return await response.DeserializeAsync(); - } + await _httpClient.SendAsync(httpRequest); + } - public async Task DeleteCourseGroup(long courseId, long groupId) + public async Task UpdateCourseGroup(UpdateGroupViewModel model, long courseId, long groupId) + { + using var httpRequest = new HttpRequestMessage( + HttpMethod.Post, + _coursesServiceUri + $"api/CourseGroups/{courseId}/update/{groupId}") { - using var httpRequest = new HttpRequestMessage( - HttpMethod.Delete, - _coursesServiceUri + $"api/CourseGroups/{courseId}/delete/{groupId}"); + Content = new StringContent( + JsonConvert.SerializeObject(model), + Encoding.UTF8, + "application/json") + }; - httpRequest.AddUserId(_httpContextAccessor); + httpRequest.AddUserId(_httpContextAccessor); - await _httpClient.SendAsync(httpRequest); - } + await _httpClient.SendAsync(httpRequest); + } - public async Task UpdateCourseGroup(UpdateGroupViewModel model, long courseId, long groupId) - { - using var httpRequest = new HttpRequestMessage( - HttpMethod.Post, - _coursesServiceUri + $"api/CourseGroups/{courseId}/update/{groupId}") - { - Content = new StringContent( - JsonConvert.SerializeObject(model), - Encoding.UTF8, - "application/json") - }; - - httpRequest.AddUserId(_httpContextAccessor); - - await _httpClient.SendAsync(httpRequest); - } + public async Task GetCourseGroupsById(long courseId, string userId) + { + using var httpRequest = new HttpRequestMessage( + HttpMethod.Get, + _coursesServiceUri + $"api/CourseGroups/{courseId}/get?userId={userId}"); - public async Task GetCourseGroupsById(long courseId, string userId) - { - using var httpRequest = new HttpRequestMessage( - HttpMethod.Get, - _coursesServiceUri + $"api/CourseGroups/{courseId}/get?userId={userId}"); + var response = await _httpClient.SendAsync(httpRequest); + return await response.DeserializeAsync(); + } - var response = await _httpClient.SendAsync(httpRequest); - return await response.DeserializeAsync(); - } + public async Task AddStudentInGroup(long courseId, long groupId, string userId) + { + using var httpRequest = new HttpRequestMessage( + HttpMethod.Post, + _coursesServiceUri + $"api/CourseGroups/{courseId}/addStudentInGroup/{groupId}?userId={userId}"); - public async Task AddStudentInGroup(long courseId, long groupId, string userId) - { - using var httpRequest = new HttpRequestMessage( - HttpMethod.Post, - _coursesServiceUri + $"api/CourseGroups/{courseId}/addStudentInGroup/{groupId}?userId={userId}"); + httpRequest.AddUserId(_httpContextAccessor); - httpRequest.AddUserId(_httpContextAccessor); + await _httpClient.SendAsync(httpRequest); + } - await _httpClient.SendAsync(httpRequest); - } + public async Task RemoveStudentFromGroup(long courseId, long groupId, string userId) + { + using var httpRequest = new HttpRequestMessage( + HttpMethod.Post, + _coursesServiceUri + $"api/CourseGroups/{courseId}/removeStudentFromGroup/{groupId}?userId={userId}"); - public async Task RemoveStudentFromGroup(long courseId, long groupId, string userId) - { - using var httpRequest = new HttpRequestMessage( - HttpMethod.Post, - _coursesServiceUri + $"api/CourseGroups/{courseId}/removeStudentFromGroup/{groupId}?userId={userId}"); + httpRequest.AddUserId(_httpContextAccessor); - httpRequest.AddUserId(_httpContextAccessor); + await _httpClient.SendAsync(httpRequest); + } - await _httpClient.SendAsync(httpRequest); - } + public async Task GetGroupById(long groupId) + { + using var httpRequest = new HttpRequestMessage( + HttpMethod.Get, + _coursesServiceUri + $"api/CourseGroups/get/{groupId}"); - public async Task GetGroupById(long groupId) - { - using var httpRequest = new HttpRequestMessage( - HttpMethod.Get, - _coursesServiceUri + $"api/CourseGroups/get/{groupId}"); + var response = await _httpClient.SendAsync(httpRequest); + return await response.DeserializeAsync(); + } - var response = await _httpClient.SendAsync(httpRequest); - return await response.DeserializeAsync(); - } + public async Task GetGroupTasks(long groupId) + { + using var httpRequest = new HttpRequestMessage( + HttpMethod.Get, + _coursesServiceUri + $"api/CourseGroups/getTasks/{groupId}"); - public async Task GetGroupTasks(long groupId) - { - using var httpRequest = new HttpRequestMessage( - HttpMethod.Get, - _coursesServiceUri + $"api/CourseGroups/getTasks/{groupId}"); + var response = await _httpClient.SendAsync(httpRequest); + return await response.DeserializeAsync(); + } - var response = await _httpClient.SendAsync(httpRequest); - return await response.DeserializeAsync(); - } + public async Task AcceptLecturer(long courseId, string lecturerEmail) + { + using var httpRequest = new HttpRequestMessage( + HttpMethod.Get, + _coursesServiceUri + $"api/Courses/acceptLecturer/{courseId}?lecturerEmail={lecturerEmail}"); - public async Task AcceptLecturer(long courseId, string lecturerEmail) - { - using var httpRequest = new HttpRequestMessage( - HttpMethod.Get, - _coursesServiceUri + $"api/Courses/acceptLecturer/{courseId}?lecturerEmail={lecturerEmail}"); + httpRequest.AddUserId(_httpContextAccessor); + var response = await _httpClient.SendAsync(httpRequest); + return response.IsSuccessStatusCode ? Result.Success() : Result.Failed(response.ReasonPhrase); + } - httpRequest.AddUserId(_httpContextAccessor); - var response = await _httpClient.SendAsync(httpRequest); - return response.IsSuccessStatusCode ? Result.Success() : Result.Failed(response.ReasonPhrase); - } + public async Task> GetLecturersAvailableForCourse(long courseId) + { + using var httpRequest = new HttpRequestMessage( + HttpMethod.Get, + _coursesServiceUri + $"api/Courses/getLecturersAvailableForCourse/{courseId}"); - public async Task> GetLecturersAvailableForCourse(long courseId) - { - using var httpRequest = new HttpRequestMessage( - HttpMethod.Get, - _coursesServiceUri + $"api/Courses/getLecturersAvailableForCourse/{courseId}"); + httpRequest.AddUserId(_httpContextAccessor); - httpRequest.AddUserId(_httpContextAccessor); + var response = await _httpClient.SendAsync(httpRequest); + return response.IsSuccessStatusCode + ? Result.Success(await response.DeserializeAsync()) + : Result.Failed(response.ReasonPhrase); + } - var response = await _httpClient.SendAsync(httpRequest); - return response.IsSuccessStatusCode - ? Result.Success(await response.DeserializeAsync()) - : Result.Failed(response.ReasonPhrase); + public async Task Ping() + { + try + { + await _httpClient.GetAsync(_coursesServiceUri + "api/system/ping"); + return true; } - - public async Task Ping() + catch { - try - { - await _httpClient.GetAsync(_coursesServiceUri + "api/system/ping"); - return true; - } - catch - { - return false; - } + return false; } } -} +} \ No newline at end of file diff --git a/HwProj.CoursesService/HwProj.CoursesService.Client/HwProj.CoursesService.Client.csproj b/HwProj.CoursesService/HwProj.CoursesService.Client/HwProj.CoursesService.Client.csproj index 8deea7c02..a35c155b7 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.Client/HwProj.CoursesService.Client.csproj +++ b/HwProj.CoursesService/HwProj.CoursesService.Client/HwProj.CoursesService.Client.csproj @@ -2,7 +2,7 @@ Library - netcoreapp2.2 + net6.0 $(CSharpLanguageVersion) @@ -11,8 +11,9 @@ - - + + + diff --git a/HwProj.CoursesService/HwProj.CoursesService.Client/ICoursesServiceClient.cs b/HwProj.CoursesService/HwProj.CoursesService.Client/ICoursesServiceClient.cs index fac678aa9..22e978dec 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.Client/ICoursesServiceClient.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.Client/ICoursesServiceClient.cs @@ -4,39 +4,38 @@ using HwProj.Models.CoursesService.ViewModels; using HwProj.Models.Result; -namespace HwProj.CoursesService.Client +namespace HwProj.CoursesService.Client; + +public interface ICoursesServiceClient { - public interface ICoursesServiceClient - { - Task GetAllCourses(); - Task GetCourseById(long courseId, string userId); - Task DeleteCourse(long courseId); - Task CreateCourse(CreateCourseViewModel model, string mentorId); - Task UpdateCourse(UpdateCourseViewModel model, long courseId); - Task SignInCourse(long courseId, string studentId); - Task AcceptStudent(long courseId, string studentId); - Task RejectStudent(long courseId, string studentId); - Task GetAllUserCourses(); - Task GetTaskDeadlines(); - Task> AddHomeworkToCourse(CreateHomeworkViewModel model, long courseId); - Task GetHomework(long homeworkId); - Task UpdateHomework(CreateHomeworkViewModel model, long homeworkId); - Task DeleteHomework(long homeworkId); - Task GetTask(long taskId); - Task> AddTask(CreateTaskViewModel taskViewModel, long homeworkId); - Task DeleteTask(long taskId); - Task UpdateTask(CreateTaskViewModel taskViewModel, long taskId); - Task GetAllCourseGroups(long courseId); - Task CreateCourseGroup(CreateGroupViewModel model, long courseId); - Task DeleteCourseGroup(long courseId, long groupId); - Task UpdateCourseGroup(UpdateGroupViewModel model, long courseId, long groupId); - Task GetCourseGroupsById(long courseId, string userId); - Task AddStudentInGroup(long courseId, long groupId, string userId); - Task RemoveStudentFromGroup(long courseId, long groupId, string userId); - Task GetGroupById(long groupId); - Task GetGroupTasks(long groupId); - Task AcceptLecturer(long courseId, string lecturerEmail); - Task> GetLecturersAvailableForCourse(long courseId); - Task Ping(); - } -} + Task GetAllCourses(); + Task GetCourseById(long courseId, string userId); + Task DeleteCourse(long courseId); + Task CreateCourse(CreateCourseViewModel model, string mentorId); + Task UpdateCourse(UpdateCourseViewModel model, long courseId); + Task SignInCourse(long courseId, string studentId); + Task AcceptStudent(long courseId, string studentId); + Task RejectStudent(long courseId, string studentId); + Task GetAllUserCourses(); + Task GetTaskDeadlines(); + Task> AddHomeworkToCourse(CreateHomeworkViewModel model, long courseId); + Task GetHomework(long homeworkId); + Task UpdateHomework(CreateHomeworkViewModel model, long homeworkId); + Task DeleteHomework(long homeworkId); + Task GetTask(long taskId); + Task> AddTask(CreateTaskViewModel taskViewModel, long homeworkId); + Task DeleteTask(long taskId); + Task UpdateTask(CreateTaskViewModel taskViewModel, long taskId); + Task GetAllCourseGroups(long courseId); + Task CreateCourseGroup(CreateGroupViewModel model, long courseId); + Task DeleteCourseGroup(long courseId, long groupId); + Task UpdateCourseGroup(UpdateGroupViewModel model, long courseId, long groupId); + Task GetCourseGroupsById(long courseId, string userId); + Task AddStudentInGroup(long courseId, long groupId, string userId); + Task RemoveStudentFromGroup(long courseId, long groupId, string userId); + Task GetGroupById(long groupId); + Task GetGroupTasks(long groupId); + Task AcceptLecturer(long courseId, string lecturerEmail); + Task> GetLecturersAvailableForCourse(long courseId); + Task Ping(); +} \ No newline at end of file diff --git a/HwProj.CoursesService/HwProj.CoursesService.Tests/CoursesServiceTests.cs b/HwProj.CoursesService/HwProj.CoursesService.Tests/CoursesServiceTests.cs index c4be549b3..649537556 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.Tests/CoursesServiceTests.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.Tests/CoursesServiceTests.cs @@ -1,14 +1,13 @@ using NUnit.Framework; -namespace HwProj.CoursesService.Tests +namespace HwProj.CoursesService.Tests; + +[TestFixture] +public class CoursesServiceTests { - [TestFixture] - public class CoursesServiceTests + [Test] + public void SimpleTest() { - [Test] - public void SimpleTest() - { - Assert.AreEqual(1, 1); - } + Assert.AreEqual(1, 1); } } \ No newline at end of file diff --git a/HwProj.CoursesService/HwProj.CoursesService.Tests/GroupsServiceTests.cs b/HwProj.CoursesService/HwProj.CoursesService.Tests/GroupsServiceTests.cs index f748f2f38..591dd3be1 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.Tests/GroupsServiceTests.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.Tests/GroupsServiceTests.cs @@ -1,317 +1,316 @@ -namespace HwProj.CoursesService.Tests +namespace HwProj.CoursesService.Tests; + +/* +[TestFixture] +public class GroupsServiceTests { - /* - [TestFixture] - public class GroupsServiceTests + private CourseContext _courseContext; + private GroupsRepository _groupsRepository; + private GroupMatesRepository _groupMatesRepository; + private GroupsService _service; + private IMapper _mapper; + + [SetUp] + public void Setup() { - private CourseContext _courseContext; - private GroupsRepository _groupsRepository; - private GroupMatesRepository _groupMatesRepository; - private GroupsService _service; - private IMapper _mapper; - - [SetUp] - public void Setup() + var connectionString = "Server=(localdb)\\mssqllocaldb;Database=GroupsServiceDB;Trusted_Connection=True;"; + var builder = new DbContextOptionsBuilder(); + var options = builder.UseSqlServer(connectionString).Options; + _courseContext = new CourseContext(options); + _groupsRepository = new GroupsRepository(_courseContext); + _groupMatesRepository = new GroupMatesRepository(_courseContext); + var _taskModelsRepository = new TaskModelsRepository(_courseContext); + + var config = new MapperConfiguration(cfg => { - var connectionString = "Server=(localdb)\\mssqllocaldb;Database=GroupsServiceDB;Trusted_Connection=True;"; - var builder = new DbContextOptionsBuilder(); - var options = builder.UseSqlServer(connectionString).Options; - _courseContext = new CourseContext(options); - _groupsRepository = new GroupsRepository(_courseContext); - _groupMatesRepository = new GroupMatesRepository(_courseContext); - var _taskModelsRepository = new TaskModelsRepository(_courseContext); - - var config = new MapperConfiguration(cfg => - { - cfg.AddProfile(); - }); - _mapper = config.CreateMapper(); + cfg.AddProfile(); + }); + _mapper = config.CreateMapper(); - _service = new GroupsService(_groupsRepository, _groupMatesRepository, _taskModelsRepository, _mapper); - } + _service = new GroupsService(_groupsRepository, _groupMatesRepository, _taskModelsRepository, _mapper); + } - [Test] - public async Task GetGroupTest() + [Test] + public async Task GetGroupTest() + { + using (var transaction = _courseContext.Database.BeginTransaction()) { - using (var transaction = _courseContext.Database.BeginTransaction()) - { - #region init data - var group = new Group { CourseId = 1, GroupMates = new List(), Name = "0_o" }; - var addedGroupId = await _groupsRepository.AddAsync(group); - var addedGroup = await _service.GetGroupAsync(addedGroupId).ConfigureAwait(false); - #endregion + #region init data + var group = new Group { CourseId = 1, GroupMates = new List(), Name = "0_o" }; + var addedGroupId = await _groupsRepository.AddAsync(group); + var addedGroup = await _service.GetGroupAsync(addedGroupId).ConfigureAwait(false); + #endregion - addedGroup.Should().BeEquivalentTo(group); - } - } - - [Test, Description("Test if group returns with group mates")] - public async Task GetGroupWithMatesTest() - { - using (var transaction = _courseContext.Database.BeginTransaction()) - { - #region init data - var mates = new List - { - new GroupMate{ StudentId = "st1" }, - new GroupMate{ StudentId = "st2" }, - new GroupMate{ StudentId = "st3" } - }; - var group = new Group { CourseId = 1, GroupMates = mates, Name = "0_o" }; - var addedGroupId = await _groupsRepository.AddAsync(group); - #endregion - - Group addedGroup = await _service.GetGroupAsync(addedGroupId); - addedGroup.Should().BeEquivalentTo(group); - } + addedGroup.Should().BeEquivalentTo(group); } + } - [Test] - public async Task AddGroupTest() + [Test, Description("Test if group returns with group mates")] + public async Task GetGroupWithMatesTest() + { + using (var transaction = _courseContext.Database.BeginTransaction()) { - using (var transaction = _courseContext.Database.BeginTransaction()) + #region init data + var mates = new List { - #region init data - var group = new Group { CourseId = 1, GroupMates = new List(), Name = "0_o" }; - var addedGroupId = await _service.AddGroupAsync(group).ConfigureAwait(false); - #endregion + new GroupMate{ StudentId = "st1" }, + new GroupMate{ StudentId = "st2" }, + new GroupMate{ StudentId = "st3" } + }; + var group = new Group { CourseId = 1, GroupMates = mates, Name = "0_o" }; + var addedGroupId = await _groupsRepository.AddAsync(group); + #endregion - var addedGroup = await _groupsRepository.GetAsync(addedGroupId); - addedGroup.Should().BeEquivalentTo(group); - } + Group addedGroup = await _service.GetGroupAsync(addedGroupId); + addedGroup.Should().BeEquivalentTo(group); } + } - [Test] - public async Task AddGroupWithMatesAndTasksTest() + [Test] + public async Task AddGroupTest() + { + using (var transaction = _courseContext.Database.BeginTransaction()) { - using (var transaction = _courseContext.Database.BeginTransaction()) - { - #region init data - var mates = new List - { - new GroupMate { StudentId = "st1" }, - new GroupMate { StudentId = "st2" } - }; - - var tasks = new List - { - new TaskModel { TaskId = 1 }, - new TaskModel { TaskId = 2 } - }; - - var group = new Group { CourseId = 1, GroupMates = mates, Name = "0_o", Tasks = tasks }; - var addedGroupId = await _service.AddGroupAsync(group).ConfigureAwait(false); - #endregion - - var addedGroup = await _groupsRepository.GetAsync(addedGroupId); - - addedGroup.Should().BeEquivalentTo(group); - } + #region init data + var group = new Group { CourseId = 1, GroupMates = new List(), Name = "0_o" }; + var addedGroupId = await _service.AddGroupAsync(group).ConfigureAwait(false); + #endregion + + var addedGroup = await _groupsRepository.GetAsync(addedGroupId); + addedGroup.Should().BeEquivalentTo(group); } + } - [Test] - public async Task DeleteGroupTest() + [Test] + public async Task AddGroupWithMatesAndTasksTest() + { + using (var transaction = _courseContext.Database.BeginTransaction()) { - using (var transaction = _courseContext.Database.BeginTransaction()) + #region init data + var mates = new List { - #region init data - var mates = new List - { new GroupMate { StudentId = "st1" }, new GroupMate { StudentId = "st2" } - }; - - var group = new Group { CourseId = 1, GroupMates = mates, Name = "0_o" }; - var addedGroupId = await _service.AddGroupAsync(group); - #endregion - - var matesIds = _groupMatesRepository.FindAll(cm => cm.GroupId == addedGroupId).ToList(); - await _service.DeleteGroupAsync(addedGroupId); - - //Local part of Database is not updated automaticly, so... - foreach (var x in _courseContext.Set().Local.ToList()) - { - _courseContext.Entry(x).State = EntityState.Detached; - } - _courseContext.Set().Load(); - - foreach (var x in _courseContext.Set().Local.ToList()) - { - _courseContext.Entry(x).State = EntityState.Detached; - } - _courseContext.Set().Load(); - - foreach (var x in _courseContext.Set().Local.ToList()) - { - _courseContext.Entry(x).State = EntityState.Detached; - } - _courseContext.Set().Load(); - //end - - var addedGroup = await _groupsRepository.GetAsync(addedGroupId).ConfigureAwait(false); - addedGroup.Should().Be(null); - matesIds.ForEach(async cm => (await _groupMatesRepository.GetAsync(cm.Id)).Should().Be(null)); - } + }; + + var tasks = new List + { + new TaskModel { TaskId = 1 }, + new TaskModel { TaskId = 2 } + }; + + var group = new Group { CourseId = 1, GroupMates = mates, Name = "0_o", Tasks = tasks }; + var addedGroupId = await _service.AddGroupAsync(group).ConfigureAwait(false); + #endregion + + var addedGroup = await _groupsRepository.GetAsync(addedGroupId); + + addedGroup.Should().BeEquivalentTo(group); } + } - [Test] - public async Task AddGroupMateTest() + [Test] + public async Task DeleteGroupTest() + { + using (var transaction = _courseContext.Database.BeginTransaction()) { - using (var transaction = _courseContext.Database.BeginTransaction()) + #region init data + var mates = new List { - #region init data - var group = new Group { CourseId = 1, GroupMates = new List(), Name = "0_o" }; - var addedGroupId = await _groupsRepository.AddAsync(group); - #endregion + new GroupMate { StudentId = "st1" }, + new GroupMate { StudentId = "st2" } + }; + + var group = new Group { CourseId = 1, GroupMates = mates, Name = "0_o" }; + var addedGroupId = await _service.AddGroupAsync(group); + #endregion - var mate = new GroupMate { StudentId = "st"}; - await _service.AddGroupMateAsync(addedGroupId, mate.StudentId); + var matesIds = _groupMatesRepository.FindAll(cm => cm.GroupId == addedGroupId).ToList(); + await _service.DeleteGroupAsync(addedGroupId); - var addedGroup = await _service.GetGroupAsync(addedGroupId).ConfigureAwait(false); - addedGroup.GroupMates.Select(cm => cm.StudentId).Should().ContainEquivalentOf(mate.StudentId); + //Local part of Database is not updated automaticly, so... + foreach (var x in _courseContext.Set().Local.ToList()) + { + _courseContext.Entry(x).State = EntityState.Detached; } - } + _courseContext.Set().Load(); - [Test] - public async Task AddSameGroupMateTest() - { - using (var transaction = _courseContext.Database.BeginTransaction()) + foreach (var x in _courseContext.Set().Local.ToList()) { - #region init data - var group = new Group { CourseId = 1, GroupMates = new List(), Name = "0_o" }; - var addedGroupId = await _groupsRepository.AddAsync(group); - #endregion + _courseContext.Entry(x).State = EntityState.Detached; + } + _courseContext.Set().Load(); - await _service.AddGroupMateAsync(addedGroupId, "st"); - Assert.ThrowsAsync(async () => await _service.AddGroupMateAsync(addedGroupId, "st")); + foreach (var x in _courseContext.Set().Local.ToList()) + { + _courseContext.Entry(x).State = EntityState.Detached; } + _courseContext.Set().Load(); + //end + + var addedGroup = await _groupsRepository.GetAsync(addedGroupId).ConfigureAwait(false); + addedGroup.Should().Be(null); + matesIds.ForEach(async cm => (await _groupMatesRepository.GetAsync(cm.Id)).Should().Be(null)); } + } - [Test] - public async Task DeleteGroupMateTest() + [Test] + public async Task AddGroupMateTest() + { + using (var transaction = _courseContext.Database.BeginTransaction()) { - using (var transaction = _courseContext.Database.BeginTransaction()) - { - #region init data - var group = new Group { CourseId = 1, GroupMates = new List(), Name = "0_o" }; - var addedGroupId = await _groupsRepository.AddAsync(group); - await _service.AddGroupMateAsync(addedGroupId, "st"); - #endregion - - await _service.DeleteGroupMateAsync(addedGroupId, "st"); - foreach (var x in _courseContext.Set().Local.ToList()) - { - _courseContext.Entry(x).State = EntityState.Detached; - } - _courseContext.Set().Load(); - - var addedGroup = await _service.GetGroupAsync(addedGroupId).ConfigureAwait(false); - addedGroup.GroupMates.Should().BeEmpty(); - } + #region init data + var group = new Group { CourseId = 1, GroupMates = new List(), Name = "0_o" }; + var addedGroupId = await _groupsRepository.AddAsync(group); + #endregion + + var mate = new GroupMate { StudentId = "st"}; + await _service.AddGroupMateAsync(addedGroupId, mate.StudentId); + + var addedGroup = await _service.GetGroupAsync(addedGroupId).ConfigureAwait(false); + addedGroup.GroupMates.Select(cm => cm.StudentId).Should().ContainEquivalentOf(mate.StudentId); } + } - [Test] - public async Task GetAllGroupsInCourseTest() + [Test] + public async Task AddSameGroupMateTest() + { + using (var transaction = _courseContext.Database.BeginTransaction()) { - using (var transaction = _courseContext.Database.BeginTransaction()) - { - #region init data - var gr1 = new Group { CourseId = 1, Name = "gr1", - GroupMates = new List { new GroupMate { StudentId = "st1" }, new GroupMate { StudentId = "st2" } } }; - var gr2 = new Group { CourseId = 1, Name = "gr2", GroupMates = new List { new GroupMate { StudentId = "st3" } } }; - var gr3 = new Group { CourseId = 2, Name = "gr3", GroupMates = new List { new GroupMate { StudentId = "st42" } } }; - await _groupsRepository.AddAsync(gr1); - await _groupsRepository.AddAsync(gr2); - await _groupsRepository.AddAsync(gr3); - #endregion - - var course1Groups = await _service.GetAllAsync(1).ConfigureAwait(false); - var course2Groups = await _service.GetAllAsync(2).ConfigureAwait(false); - - course1Groups.Should().ContainEquivalentOf(gr1); - course1Groups.Should().ContainEquivalentOf(gr2); - course2Groups.Should().ContainEquivalentOf(gr3); - } + #region init data + var group = new Group { CourseId = 1, GroupMates = new List(), Name = "0_o" }; + var addedGroupId = await _groupsRepository.AddAsync(group); + #endregion + + await _service.AddGroupMateAsync(addedGroupId, "st"); + Assert.ThrowsAsync(async () => await _service.AddGroupMateAsync(addedGroupId, "st")); } + } - [Test] - public async Task UpdateGroupTest() + [Test] + public async Task DeleteGroupMateTest() + { + using (var transaction = _courseContext.Database.BeginTransaction()) { - using (var transaction = _courseContext.Database.BeginTransaction()) + #region init data + var group = new Group { CourseId = 1, GroupMates = new List(), Name = "0_o" }; + var addedGroupId = await _groupsRepository.AddAsync(group); + await _service.AddGroupMateAsync(addedGroupId, "st"); + #endregion + + await _service.DeleteGroupMateAsync(addedGroupId, "st"); + foreach (var x in _courseContext.Set().Local.ToList()) { - var group = new Group - { - CourseId = 1, - Name = "gr1", - GroupMates = new List { new GroupMate { StudentId = "st1" }, new GroupMate { StudentId = "st2" } }, - Tasks = new List { new TaskModel { TaskId = 1 } } - }; - - var id = await _service.AddGroupAsync(group); - - var updated = new Group - { - CourseId = 1, - Name = "gr2", - GroupMates = new List { }, - Tasks = new List { new TaskModel { TaskId = 2 } } - }; - - await _service.UpdateAsync(id, updated); - - var addedGroup = await _groupsRepository.GetAsync(id); - - updated.Id = id; - addedGroup.Should().BeEquivalentTo(updated); + _courseContext.Entry(x).State = EntityState.Detached; } + _courseContext.Set().Load(); + + var addedGroup = await _service.GetGroupAsync(addedGroupId).ConfigureAwait(false); + addedGroup.GroupMates.Should().BeEmpty(); } + } - [Test] - public async Task GetStudentsGroupTest() + [Test] + public async Task GetAllGroupsInCourseTest() + { + using (var transaction = _courseContext.Database.BeginTransaction()) { - using (var transaction = _courseContext.Database.BeginTransaction()) - { - #region init data - var gr1 = new Group { CourseId = 1, Name = "gr1" }; - var gr2 = new Group { CourseId = 1, Name = "gr2" }; - var gr3 = new Group { CourseId = 2, Name = "gr3" }; - var addedGroup1Id = await _groupsRepository.AddAsync(gr1); - var addedGroup2Id = await _groupsRepository.AddAsync(gr2); - var addedGroup3Id = await _groupsRepository.AddAsync(gr3); - await _service.AddGroupMateAsync(addedGroup1Id, "st"); - await _service.AddGroupMateAsync(addedGroup2Id, "st"); - await _service.AddGroupMateAsync(addedGroup3Id, "st"); - #endregion - - var groups1 = await _service.GetStudentGroupsAsync(1, "st"); - var groups2 = await _service.GetStudentGroupsAsync(2, "st"); - groups1.Should().ContainEquivalentOf(_mapper.Map(gr1)); - groups1.Should().ContainEquivalentOf(_mapper.Map(gr2)); - groups2.Should().ContainEquivalentOf(_mapper.Map(gr3)); - } + #region init data + var gr1 = new Group { CourseId = 1, Name = "gr1", + GroupMates = new List { new GroupMate { StudentId = "st1" }, new GroupMate { StudentId = "st2" } } }; + var gr2 = new Group { CourseId = 1, Name = "gr2", GroupMates = new List { new GroupMate { StudentId = "st3" } } }; + var gr3 = new Group { CourseId = 2, Name = "gr3", GroupMates = new List { new GroupMate { StudentId = "st42" } } }; + await _groupsRepository.AddAsync(gr1); + await _groupsRepository.AddAsync(gr2); + await _groupsRepository.AddAsync(gr3); + #endregion + + var course1Groups = await _service.GetAllAsync(1).ConfigureAwait(false); + var course2Groups = await _service.GetAllAsync(2).ConfigureAwait(false); + + course1Groups.Should().ContainEquivalentOf(gr1); + course1Groups.Should().ContainEquivalentOf(gr2); + course2Groups.Should().ContainEquivalentOf(gr3); } + } - [Test] - public void MapperTest() + [Test] + public async Task UpdateGroupTest() + { + using (var transaction = _courseContext.Database.BeginTransaction()) { - var groupViewModel = new CreateGroupViewModel - { + var group = new Group + { + CourseId = 1, + Name = "gr1", + GroupMates = new List { new GroupMate { StudentId = "st1" }, new GroupMate { StudentId = "st2" } }, + Tasks = new List { new TaskModel { TaskId = 1 } } + }; + + var id = await _service.AddGroupAsync(group); + + var updated = new Group + { CourseId = 1, - GroupMates = new List - { - new GroupMateViewModel {StudentId = "st1" } - }, - Tasks = new List - { - 42 - } + Name = "gr2", + GroupMates = new List { }, + Tasks = new List { new TaskModel { TaskId = 2 } } }; - var group = _mapper.Map(groupViewModel); + await _service.UpdateAsync(id, updated); + + var addedGroup = await _groupsRepository.GetAsync(id); + + updated.Id = id; + addedGroup.Should().BeEquivalentTo(updated); + } + } - Assert.IsNotEmpty(group.GroupMates.Where(cm => cm.StudentId == "st1")); - Assert.IsNotEmpty(group.Tasks.Where(cm => cm.TaskId == 42)); + [Test] + public async Task GetStudentsGroupTest() + { + using (var transaction = _courseContext.Database.BeginTransaction()) + { + #region init data + var gr1 = new Group { CourseId = 1, Name = "gr1" }; + var gr2 = new Group { CourseId = 1, Name = "gr2" }; + var gr3 = new Group { CourseId = 2, Name = "gr3" }; + var addedGroup1Id = await _groupsRepository.AddAsync(gr1); + var addedGroup2Id = await _groupsRepository.AddAsync(gr2); + var addedGroup3Id = await _groupsRepository.AddAsync(gr3); + await _service.AddGroupMateAsync(addedGroup1Id, "st"); + await _service.AddGroupMateAsync(addedGroup2Id, "st"); + await _service.AddGroupMateAsync(addedGroup3Id, "st"); + #endregion + + var groups1 = await _service.GetStudentGroupsAsync(1, "st"); + var groups2 = await _service.GetStudentGroupsAsync(2, "st"); + groups1.Should().ContainEquivalentOf(_mapper.Map(gr1)); + groups1.Should().ContainEquivalentOf(_mapper.Map(gr2)); + groups2.Should().ContainEquivalentOf(_mapper.Map(gr3)); } } - */ -} \ No newline at end of file + + [Test] + public void MapperTest() + { + var groupViewModel = new CreateGroupViewModel + { + CourseId = 1, + GroupMates = new List + { + new GroupMateViewModel {StudentId = "st1" } + }, + Tasks = new List + { + 42 + } + }; + + var group = _mapper.Map(groupViewModel); + + Assert.IsNotEmpty(group.GroupMates.Where(cm => cm.StudentId == "st1")); + Assert.IsNotEmpty(group.Tasks.Where(cm => cm.TaskId == 42)); + } +} +*/ \ No newline at end of file diff --git a/HwProj.CoursesService/HwProj.CoursesService.Tests/HwProj.CoursesService.Tests.csproj b/HwProj.CoursesService/HwProj.CoursesService.Tests/HwProj.CoursesService.Tests.csproj index c33da57d4..3f20a9057 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.Tests/HwProj.CoursesService.Tests.csproj +++ b/HwProj.CoursesService/HwProj.CoursesService.Tests/HwProj.CoursesService.Tests.csproj @@ -1,7 +1,7 @@  - netcoreapp2.2 + net6.0 false @@ -11,9 +11,9 @@ - + - + diff --git a/HwProj.EventBus/HwProj.EventBus.Client/Event.cs b/HwProj.EventBus/HwProj.EventBus.Client/Event.cs index 8a62cbd96..dab2f5bcb 100644 --- a/HwProj.EventBus/HwProj.EventBus.Client/Event.cs +++ b/HwProj.EventBus/HwProj.EventBus.Client/Event.cs @@ -1,26 +1,25 @@ using System; using Newtonsoft.Json; -namespace HwProj.EventBus.Client +namespace HwProj.EventBus.Client; + +public class Event { - public class Event - { - [JsonProperty] - public Guid Id { get; set; } + [JsonProperty] + public Guid Id { get; set; } - [JsonProperty] - public DateTime CreationData { get; set; } + [JsonProperty] + public DateTime CreationData { get; set; } - public Event() - { - Id = Guid.NewGuid(); - CreationData = DateTime.UtcNow; - } + public Event() + { + Id = Guid.NewGuid(); + CreationData = DateTime.UtcNow; + } - public Event(Guid id, DateTime data) - { - Id = id; - CreationData = data; - } + public Event(Guid id, DateTime data) + { + Id = id; + CreationData = data; } -} +} \ No newline at end of file diff --git a/HwProj.EventBus/HwProj.EventBus.Client/HwProj.EventBus.Client.csproj b/HwProj.EventBus/HwProj.EventBus.Client/HwProj.EventBus.Client.csproj index 7932fcc9d..4585f44f5 100644 --- a/HwProj.EventBus/HwProj.EventBus.Client/HwProj.EventBus.Client.csproj +++ b/HwProj.EventBus/HwProj.EventBus.Client/HwProj.EventBus.Client.csproj @@ -2,7 +2,7 @@ Library - netcoreapp2.2 + net6.0 HwProj.EventBus.Client @@ -12,15 +12,10 @@ - - - + + - - - - - + diff --git a/HwProj.EventBus/HwProj.EventBus.Client/Implementations/DefaultConnection.cs b/HwProj.EventBus/HwProj.EventBus.Client/Implementations/DefaultConnection.cs index 5f115add5..31fa59af1 100644 --- a/HwProj.EventBus/HwProj.EventBus.Client/Implementations/DefaultConnection.cs +++ b/HwProj.EventBus/HwProj.EventBus.Client/Implementations/DefaultConnection.cs @@ -3,69 +3,68 @@ using Polly.Retry; using RabbitMQ.Client; -namespace HwProj.EventBus.Client.Implementations +namespace HwProj.EventBus.Client.Implementations; + +public class DefaultConnection : IDefaultConnection { - public class DefaultConnection : IDefaultConnection - { - private readonly object _lock = new object(); + private readonly object _lock = new(); - private readonly RetryPolicy _policy; + private readonly RetryPolicy _policy; - private readonly IConnectionFactory _factory; - private IConnection _connection; + private readonly IConnectionFactory _factory; + private IConnection _connection; - private bool _isDisposed; + private bool _isDisposed; - public bool IsConnected => _connection != null && _connection.IsOpen && !_isDisposed; + public bool IsConnected => _connection != null && _connection.IsOpen && !_isDisposed; - public DefaultConnection(RetryPolicy policy, IConnectionFactory factory) - { - _factory = factory; - _policy = policy; - TryConnect(); - } + public DefaultConnection(RetryPolicy policy, IConnectionFactory factory) + { + _factory = factory; + _policy = policy; + TryConnect(); + } - public IModel CreateModel() - { - return IsConnected ? _connection.CreateModel() : throw new InvalidOperationException("No RabbitMQ connections are available to perform this action"); - } + public IModel CreateModel() + { + return IsConnected ? _connection.CreateModel() : throw new InvalidOperationException("No RabbitMQ connections are available to perform this action"); + } - public bool TryConnect() + public bool TryConnect() + { + lock (_lock) { - lock (_lock) - { - _policy.Execute(() => _connection = _factory.CreateConnection()); - - if (IsConnected) - { - _connection.CallbackException += OnErrorConnection; - _connection.ConnectionBlocked += OnErrorConnection; - _connection.ConnectionShutdown += OnErrorConnection; + _policy.Execute(() => _connection = _factory.CreateConnection()); - return true; - } - else - { - return false; - } - } - } + if (IsConnected) + { + _connection.CallbackException += OnErrorConnection; + _connection.ConnectionBlocked += OnErrorConnection; + _connection.ConnectionShutdown += OnErrorConnection; - public void Dispose() - { - if (!_isDisposed) + return true; + } + else { - _connection?.Close(); - _isDisposed = true; + return false; } + } + } + + public void Dispose() + { + if (!_isDisposed) + { + _connection?.Close(); + _isDisposed = true; } + } - private void OnErrorConnection(object sender, EventArgs ea) + private void OnErrorConnection(object sender, EventArgs ea) + { + if (!_isDisposed) { - if (!_isDisposed) - { - TryConnect(); - } + TryConnect(); } } -} +} \ No newline at end of file diff --git a/HwProj.EventBus/HwProj.EventBus.Client/Implementations/EventBusRabbitMQ.cs b/HwProj.EventBus/HwProj.EventBus.Client/Implementations/EventBusRabbitMQ.cs index 2ef286191..c7de8794b 100644 --- a/HwProj.EventBus/HwProj.EventBus.Client/Implementations/EventBusRabbitMQ.cs +++ b/HwProj.EventBus/HwProj.EventBus.Client/Implementations/EventBusRabbitMQ.cs @@ -1,150 +1,144 @@ using System; using System.Collections.Generic; -using System.Linq; using System.Text; using System.Threading.Tasks; using HwProj.EventBus.Client.Interfaces; -using Microsoft.AspNetCore.DataProtection; using Microsoft.Extensions.DependencyInjection; using Newtonsoft.Json; using Polly.Retry; using RabbitMQ.Client; using RabbitMQ.Client.Events; -namespace HwProj.EventBus.Client.Implementations +namespace HwProj.EventBus.Client.Implementations; + +public class EventBusRabbitMq : IEventBus, IDisposable { - public class EventBusRabbitMq : IEventBus, IDisposable - { - private const string BrokerName = "hwproj_event_bus"; + private const string BrokerName = "hwproj_event_bus"; - private readonly IDefaultConnection _connection; - private readonly IServiceScopeFactory _scopeFactory; + private readonly IDefaultConnection _connection; + private readonly IServiceScopeFactory _scopeFactory; - private readonly string _queueName; - private readonly RetryPolicy _policy; + private readonly string _queueName; + private readonly RetryPolicy _policy; - private IModel _consumerChannel; + private IModel _consumerChannel; - private readonly Dictionary _eventTypes = new Dictionary(); + private readonly Dictionary _eventTypes = new(); - private readonly Dictionary> _handlers = - new Dictionary>(); + private readonly Dictionary> _handlers = new(); - public EventBusRabbitMq(IDefaultConnection connection, IServiceProvider serviceProvider, - IServiceScopeFactory scopeFactory, RetryPolicy policy) - { - _connection = connection; - _scopeFactory = scopeFactory; - _queueName = serviceProvider.GetApplicationUniqueIdentifier().Split('\\').Last(); - _policy = policy; - _consumerChannel = CreateConsumerChannel(); - } + public EventBusRabbitMq(IDefaultConnection connection, IServiceProvider serviceProvider, + IServiceScopeFactory scopeFactory, RetryPolicy policy) + { + _connection = connection; + _scopeFactory = scopeFactory; + _queueName = serviceProvider.GetApplicationUniqueIdentifier().Split('\\').Last(); + _policy = policy; + _consumerChannel = CreateConsumerChannel(); + } - public void Publish(Event @event) - { - using (var channel = _connection.CreateModel()) - { - channel.ExchangeDeclare(exchange: BrokerName, type: ExchangeType.Direct, durable: true); - - var message = JsonConvert.SerializeObject(@event); - var body = Encoding.UTF8.GetBytes(message); - var eventName = @event.GetType().Name; - - var properties = channel.CreateBasicProperties(); - properties.Persistent = true; - - _policy.Execute(() => - { - channel.BasicPublish(exchange: BrokerName, - routingKey: eventName, - mandatory: true, - basicProperties: properties, - body: body); - }); - } - } + public void Publish(Event @event) + { + using var channel = _connection.CreateModel(); + channel.ExchangeDeclare(exchange: BrokerName, type: ExchangeType.Direct, durable: true); - public IEventBusSubscriber CreateSubscriber() => new EventBusSubscriber(this); + var message = JsonConvert.SerializeObject(@event); + var body = Encoding.UTF8.GetBytes(message); + var eventName = @event.GetType().Name; - internal void Subscribe() - where TEvent : Event - where THandler : EventHandlerBase - { - using var channel = _connection.CreateModel(); - var eventName = GetEventName(); - if (!_handlers.TryGetValue(eventName, out var handlers)) - { - handlers = new List(); - _handlers.Add(eventName, handlers); - } - - handlers.Add(typeof(THandler)); - _eventTypes[eventName] = typeof(TEvent); - channel.QueueBind(queue: _queueName, exchange: BrokerName, routingKey: eventName); - } + var properties = channel.CreateBasicProperties(); + properties.Persistent = true; - private IModel CreateConsumerChannel() + _policy.Execute(() => { - var channel = _connection.CreateModel(); - - channel.ExchangeDeclare(exchange: BrokerName, type: ExchangeType.Direct, durable: true); - channel.QueueDeclare(queue: _queueName, - durable: true, - exclusive: false, - autoDelete: false, - arguments: null); - - channel.CallbackException += (sender, ea) => - { - _consumerChannel.Close(); - _consumerChannel = CreateConsumerChannel(); - StartBasicConsume(); - }; - - return channel; - } + channel.BasicPublish(exchange: BrokerName, + routingKey: eventName, + mandatory: true, + basicProperties: properties, + body: body); + }); + } - internal void StartBasicConsume() + public IEventBusSubscriber CreateSubscriber() => new EventBusSubscriber(this); + + internal void Subscribe() + where TEvent : Event + where THandler : EventHandlerBase + { + using var channel = _connection.CreateModel(); + var eventName = GetEventName(); + if (!_handlers.TryGetValue(eventName, out var handlers)) { - var consumer = new EventingBasicConsumer(_consumerChannel); - consumer.Received += Consumer_Received; - _consumerChannel.BasicConsume(queue: _queueName, autoAck: false, consumer: consumer); + handlers = new List(); + _handlers.Add(eventName, handlers); } - private async void Consumer_Received(object sender, BasicDeliverEventArgs eventArgs) - { - var eventName = eventArgs.RoutingKey; - var message = Encoding.UTF8.GetString(eventArgs.Body); + handlers.Add(typeof(THandler)); + _eventTypes[eventName] = typeof(TEvent); + channel.QueueBind(queue: _queueName, exchange: BrokerName, routingKey: eventName); + } - await ProcessEvent(eventName, message); + private IModel CreateConsumerChannel() + { + var channel = _connection.CreateModel(); - _consumerChannel.BasicAck(deliveryTag: eventArgs.DeliveryTag, multiple: false); - } + channel.ExchangeDeclare(exchange: BrokerName, type: ExchangeType.Direct, durable: true); + channel.QueueDeclare(queue: _queueName, + durable: true, + exclusive: false, + autoDelete: false, + arguments: null); - private async Task ProcessEvent(string eventName, string message) - { - if (!_handlers.TryGetValue(eventName, out var handlers) || - !_eventTypes.TryGetValue(eventName, out var eventType) || - !(JsonConvert.DeserializeObject(message, eventType) is Event @event)) return; - - //TODO: log - using var scope = _scopeFactory.CreateScope(); - foreach (var handler in handlers) - { - var eventHandler = scope.ServiceProvider.GetRequiredService(handler) as IEventHandler; - await eventHandler?.HandleAsync(@event); - } - } - - public void Dispose() + channel.CallbackException += (sender, ea) => { _consumerChannel.Close(); - _connection.Dispose(); - } + _consumerChannel = CreateConsumerChannel(); + StartBasicConsume(); + }; + + return channel; + } + + internal void StartBasicConsume() + { + var consumer = new EventingBasicConsumer(_consumerChannel); + consumer.Received += Consumer_Received; + _consumerChannel.BasicConsume(queue: _queueName, autoAck: false, consumer: consumer); + } + + private async void Consumer_Received(object sender, BasicDeliverEventArgs eventArgs) + { + var eventName = eventArgs.RoutingKey; + var message = Encoding.UTF8.GetString(eventArgs.Body.Span); + + await ProcessEvent(eventName, message); - private static string GetEventName() + _consumerChannel.BasicAck(deliveryTag: eventArgs.DeliveryTag, multiple: false); + } + + private async Task ProcessEvent(string eventName, string message) + { + if (!_handlers.TryGetValue(eventName, out var handlers) || + !_eventTypes.TryGetValue(eventName, out var eventType) || + JsonConvert.DeserializeObject(message, eventType) is not Event @event) return; + + //TODO: log + using var scope = _scopeFactory.CreateScope(); + foreach (var handler in handlers) { - return typeof(TEvent).Name; + var eventHandler = scope.ServiceProvider.GetRequiredService(handler) as IEventHandler; + await eventHandler?.HandleAsync(@event); } } + + public void Dispose() + { + _consumerChannel.Close(); + _connection.Dispose(); + } + + private static string GetEventName() + { + return typeof(TEvent).Name; + } } diff --git a/HwProj.EventBus/HwProj.EventBus.Client/Implementations/EventBusSubscriber.cs b/HwProj.EventBus/HwProj.EventBus.Client/Implementations/EventBusSubscriber.cs index 07d4c7b1c..c2475931a 100644 --- a/HwProj.EventBus/HwProj.EventBus.Client/Implementations/EventBusSubscriber.cs +++ b/HwProj.EventBus/HwProj.EventBus.Client/Implementations/EventBusSubscriber.cs @@ -1,23 +1,22 @@ using HwProj.EventBus.Client.Interfaces; -namespace HwProj.EventBus.Client.Implementations -{ - public class EventBusSubscriber : IEventBusSubscriber - { - private readonly EventBusRabbitMq _eventBusRabbitMq; +namespace HwProj.EventBus.Client.Implementations; - public EventBusSubscriber(EventBusRabbitMq eventBusRabbitMq) - { - _eventBusRabbitMq = eventBusRabbitMq; - } +public class EventBusSubscriber : IEventBusSubscriber +{ + private readonly EventBusRabbitMq _eventBusRabbitMq; - public void Dispose() - { - _eventBusRabbitMq.StartBasicConsume(); - } + public EventBusSubscriber(EventBusRabbitMq eventBusRabbitMq) + { + _eventBusRabbitMq = eventBusRabbitMq; + } - public void Subscribe() - where TEvent : Event - where THandler : EventHandlerBase => _eventBusRabbitMq.Subscribe(); + public void Dispose() + { + _eventBusRabbitMq.StartBasicConsume(); } -} + + public void Subscribe() + where TEvent : Event + where THandler : EventHandlerBase => _eventBusRabbitMq.Subscribe(); +} \ No newline at end of file diff --git a/HwProj.EventBus/HwProj.EventBus.Client/Interfaces/IDefaultConnection.cs b/HwProj.EventBus/HwProj.EventBus.Client/Interfaces/IDefaultConnection.cs index 422f800ce..a662ae2a8 100644 --- a/HwProj.EventBus/HwProj.EventBus.Client/Interfaces/IDefaultConnection.cs +++ b/HwProj.EventBus/HwProj.EventBus.Client/Interfaces/IDefaultConnection.cs @@ -1,14 +1,13 @@ using System; using RabbitMQ.Client; -namespace HwProj.EventBus.Client.Interfaces -{ - public interface IDefaultConnection : IDisposable - { - bool IsConnected { get; } +namespace HwProj.EventBus.Client.Interfaces; - IModel CreateModel(); +public interface IDefaultConnection : IDisposable +{ + bool IsConnected { get; } - bool TryConnect(); - } + IModel CreateModel(); + + bool TryConnect(); } \ No newline at end of file diff --git a/HwProj.EventBus/HwProj.EventBus.Client/Interfaces/IEventBus.cs b/HwProj.EventBus/HwProj.EventBus.Client/Interfaces/IEventBus.cs index a650c6475..1c0b8d7ad 100644 --- a/HwProj.EventBus/HwProj.EventBus.Client/Interfaces/IEventBus.cs +++ b/HwProj.EventBus/HwProj.EventBus.Client/Interfaces/IEventBus.cs @@ -1,18 +1,17 @@ using System; -namespace HwProj.EventBus.Client.Interfaces -{ - public interface IEventBus - { - void Publish(Event @event); +namespace HwProj.EventBus.Client.Interfaces; - IEventBusSubscriber CreateSubscriber(); - } +public interface IEventBus +{ + void Publish(Event @event); - public interface IEventBusSubscriber : IDisposable - { - void Subscribe() - where TEvent : Event - where THandler : EventHandlerBase; - } + IEventBusSubscriber CreateSubscriber(); } + +public interface IEventBusSubscriber : IDisposable +{ + void Subscribe() + where TEvent : Event + where THandler : EventHandlerBase; +} \ No newline at end of file diff --git a/HwProj.EventBus/HwProj.EventBus.Client/Interfaces/IEventHandler.cs b/HwProj.EventBus/HwProj.EventBus.Client/Interfaces/IEventHandler.cs index 35ceac94b..31c5be01c 100644 --- a/HwProj.EventBus/HwProj.EventBus.Client/Interfaces/IEventHandler.cs +++ b/HwProj.EventBus/HwProj.EventBus.Client/Interfaces/IEventHandler.cs @@ -1,17 +1,16 @@ using System.Threading.Tasks; -namespace HwProj.EventBus.Client.Interfaces +namespace HwProj.EventBus.Client.Interfaces; + +public interface IEventHandler { - public interface IEventHandler - { - Task HandleAsync(TEvent @event); - } + Task HandleAsync(TEvent @event); +} - public abstract class EventHandlerBase : IEventHandler where TEvent : Event - { - public Task HandleAsync(Event @event) => - @event as TEvent is { } x ? HandleAsync(x) : Task.CompletedTask; +public abstract class EventHandlerBase : IEventHandler where TEvent : Event +{ + public Task HandleAsync(Event @event) => + @event as TEvent is { } x ? HandleAsync(x) : Task.CompletedTask; - public abstract Task HandleAsync(TEvent @event); - } -} + public abstract Task HandleAsync(TEvent @event); +} \ No newline at end of file diff --git a/HwProj.EventBus/HwProj.EventBus.Tests/HwProj.EventBus.Tests.csproj b/HwProj.EventBus/HwProj.EventBus.Tests/HwProj.EventBus.Tests.csproj index 11e6c6f0f..4f0dc1788 100644 --- a/HwProj.EventBus/HwProj.EventBus.Tests/HwProj.EventBus.Tests.csproj +++ b/HwProj.EventBus/HwProj.EventBus.Tests/HwProj.EventBus.Tests.csproj @@ -1,7 +1,7 @@  - netcoreapp2.2 + net6.0 false @@ -11,7 +11,6 @@ - diff --git a/HwProj.EventBus/HwProj.EventBus.Tests/OtherTestHandler.cs b/HwProj.EventBus/HwProj.EventBus.Tests/OtherTestHandler.cs index b67a1ba05..dc1282495 100644 --- a/HwProj.EventBus/HwProj.EventBus.Tests/OtherTestHandler.cs +++ b/HwProj.EventBus/HwProj.EventBus.Tests/OtherTestHandler.cs @@ -2,27 +2,26 @@ using System.Threading.Tasks; using HwProj.EventBus.Client.Interfaces; -namespace HwProj.EventBus.Tests +namespace HwProj.EventBus.Tests; + +public class OtherTestHandler : EventHandlerBase { - public class OtherTestHandler : EventHandlerBase - { - public int NewPrice { get; set; } - public int OldPrice { get; set; } + public int NewPrice { get; set; } + public int OldPrice { get; set; } - public int ChangedSum => Math.Abs(NewPrice - OldPrice); + public int ChangedSum => Math.Abs(NewPrice - OldPrice); - public OtherTestHandler() - { - NewPrice = 0; - OldPrice = 0; - } + public OtherTestHandler() + { + NewPrice = 0; + OldPrice = 0; + } - public override Task HandleAsync(TestEvent @event) - { - NewPrice = @event.NewPrice; - OldPrice = @event.OldPrice; + public override Task HandleAsync(TestEvent @event) + { + NewPrice = @event.NewPrice; + OldPrice = @event.OldPrice; - return Task.CompletedTask; - } + return Task.CompletedTask; } -} +} \ No newline at end of file diff --git a/HwProj.EventBus/HwProj.EventBus.Tests/TestEvent.cs b/HwProj.EventBus/HwProj.EventBus.Tests/TestEvent.cs index 62acb15b3..89dd0445f 100644 --- a/HwProj.EventBus/HwProj.EventBus.Tests/TestEvent.cs +++ b/HwProj.EventBus/HwProj.EventBus.Tests/TestEvent.cs @@ -1,17 +1,16 @@ using HwProj.EventBus.Client; -namespace HwProj.EventBus.Tests +namespace HwProj.EventBus.Tests; + +public class TestEvent : Event { - public class TestEvent : Event - { - public int OldPrice { get; set; } + public int OldPrice { get; set; } - public int NewPrice { get; set; } + public int NewPrice { get; set; } - public TestEvent(int newPrice, int oldPrice) - { - OldPrice = oldPrice; - NewPrice = newPrice; - } + public TestEvent(int newPrice, int oldPrice) + { + OldPrice = oldPrice; + NewPrice = newPrice; } -} +} \ No newline at end of file diff --git a/HwProj.EventBus/HwProj.EventBus.Tests/TestEventBus.cs b/HwProj.EventBus/HwProj.EventBus.Tests/TestEventBus.cs index 6e54e52c4..e764d293d 100644 --- a/HwProj.EventBus/HwProj.EventBus.Tests/TestEventBus.cs +++ b/HwProj.EventBus/HwProj.EventBus.Tests/TestEventBus.cs @@ -1,24 +1,23 @@ using System.Threading; using Xunit; -namespace HwProj.EventBus.Tests +namespace HwProj.EventBus.Tests; + +public class TestEventBus { - public class TestEventBus - { - private const string Hostname = "localhost"; + private const string Hostname = "localhost"; - [Fact] - public void ShouldHandleEventPropertyChange() - { - var handler = new TestHandler(); - var otherHandler = new OtherTestHandler(); - var testEvent = new TestEvent(100, 0); + [Fact] + public void ShouldHandleEventPropertyChange() + { + var handler = new TestHandler(); + var otherHandler = new OtherTestHandler(); + var testEvent = new TestEvent(100, 0); - Thread.Sleep(1000); + Thread.Sleep(1000); - //Assert.True(handler.IsHandled); - //Assert.Equal(testEvent.NewPrice - testEvent.OldPrice, otherHandler.ChangedSum); - Assert.Equal(1, 1); - } + //Assert.True(handler.IsHandled); + //Assert.Equal(testEvent.NewPrice - testEvent.OldPrice, otherHandler.ChangedSum); + Assert.Equal(1, 1); } -} +} \ No newline at end of file diff --git a/HwProj.EventBus/HwProj.EventBus.Tests/TestHandler.cs b/HwProj.EventBus/HwProj.EventBus.Tests/TestHandler.cs index 6dd0c7909..1ee543b5c 100644 --- a/HwProj.EventBus/HwProj.EventBus.Tests/TestHandler.cs +++ b/HwProj.EventBus/HwProj.EventBus.Tests/TestHandler.cs @@ -1,20 +1,19 @@ using System.Threading.Tasks; using HwProj.EventBus.Client.Interfaces; -namespace HwProj.EventBus.Tests +namespace HwProj.EventBus.Tests; + +public class TestHandler : EventHandlerBase { - public class TestHandler : EventHandlerBase - { - public bool IsHandled { get; set; } + public bool IsHandled { get; set; } - public TestHandler() - { - IsHandled = false; - } + public TestHandler() + { + IsHandled = false; + } - public override Task HandleAsync(TestEvent @event) - { - throw new System.NotImplementedException(); - } + public override Task HandleAsync(TestEvent @event) + { + throw new System.NotImplementedException(); } -} +} \ No newline at end of file diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/AutomapperProfile.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/AutomapperProfile.cs index 0395763ee..dd797e237 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/AutomapperProfile.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/AutomapperProfile.cs @@ -1,13 +1,12 @@ using AutoMapper; using HwProj.Models.NotificationsService; -namespace HwProj.NotificationsService.API +namespace HwProj.NotificationsService.API; + +public class AutomapperProfile : Profile { - public class AutomapperProfile : Profile + public AutomapperProfile() { - public AutomapperProfile() - { - CreateMap().ReverseMap(); - } + CreateMap().ReverseMap(); } } \ No newline at end of file diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/Controllers/NotificationsController.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/Controllers/NotificationsController.cs index 9d843e688..dd94bb7e6 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/Controllers/NotificationsController.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/Controllers/NotificationsController.cs @@ -7,43 +7,42 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; -namespace HwProj.NotificationsService.API.Controllers +namespace HwProj.NotificationsService.API.Controllers; + +[Route("api/[controller]")] +[ApiController] +public class NotificationsController : ControllerBase { - [Route("api/[controller]")] - [ApiController] - public class NotificationsController : ControllerBase - { - private readonly INotificationsRepository _repository; - private readonly IMapper _mapper; + private readonly INotificationsRepository _repository; + private readonly IMapper _mapper; - public NotificationsController(INotificationsRepository repository, IMapper mapper) - { - _repository = repository; - _mapper = mapper; - } + public NotificationsController(INotificationsRepository repository, IMapper mapper) + { + _repository = repository; + _mapper = mapper; + } - [HttpGet("get/{userId}")] - [ProducesResponseType(typeof(CategorizedNotifications[]), (int)HttpStatusCode.OK)] - public async Task Get(string userId) - { - var notifications = await _repository.GetAllByUserAsync(userId); - var notificationViewModels = _mapper.Map(notifications); - var groupedNotifications = NotificationsDomain.Group(notificationViewModels); - return Ok(groupedNotifications); - } + [HttpGet("get/{userId}")] + [ProducesResponseType(typeof(CategorizedNotifications[]), (int)HttpStatusCode.OK)] + public async Task Get(string userId) + { + var notifications = await _repository.GetAllByUserAsync(userId); + var notificationViewModels = _mapper.Map(notifications); + var groupedNotifications = NotificationsDomain.Group(notificationViewModels); + return Ok(groupedNotifications); + } - [HttpPut("markAsSeen/{userId}")] - public async Task MarkNotifications([FromBody] long[] notificationIds, string userId) - { - await _repository.MarkAsSeenAsync(userId, notificationIds); - return Ok(); - } + [HttpPut("markAsSeen/{userId}")] + public async Task MarkNotifications([FromBody] long[] notificationIds, string userId) + { + await _repository.MarkAsSeenAsync(userId, notificationIds); + return Ok(); + } - [HttpGet("new/{userId}")] - public async Task GetNewNotificationsCount(string userId) - { - var count = await _repository.FindAll(t => t.Owner == userId && !t.HasSeen).CountAsync(); - return count; - } + [HttpGet("new/{userId}")] + public async Task GetNewNotificationsCount(string userId) + { + var count = await _repository.FindAll(t => t.Owner == userId && !t.HasSeen).CountAsync(); + return count; } -} +} \ No newline at end of file diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/Controllers/SystemController.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/Controllers/SystemController.cs index 3694b1d5c..7b7c07869 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/Controllers/SystemController.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/Controllers/SystemController.cs @@ -1,12 +1,11 @@ using Microsoft.AspNetCore.Mvc; -namespace HwProj.NotificationsService.API.Controllers +namespace HwProj.NotificationsService.API.Controllers; + +[Route("api/[controller]")] +[ApiController] +public class SystemController : ControllerBase { - [Route("api/[controller]")] - [ApiController] - public class SystemController : ControllerBase - { - [HttpGet("status")] - public IActionResult Status() => Ok(); - } -} + [HttpGet("status")] + public IActionResult Status() => Ok(); +} \ No newline at end of file diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/InviteLecturerEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/InviteLecturerEventHandler.cs index f8ea9fcff..0e9d18f39 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/InviteLecturerEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/InviteLecturerEventHandler.cs @@ -6,34 +6,33 @@ using HwProj.NotificationsService.API.Repositories; using HwProj.NotificationsService.API.Services; -namespace HwProj.NotificationsService.API.EventHandlers +namespace HwProj.NotificationsService.API.EventHandlers; + +public class InviteLecturerEventHandler : EventHandlerBase { - public class InviteLecturerEventHandler : EventHandlerBase - { - private readonly INotificationsRepository _notificationRepository; - private readonly IEmailService _emailService; + private readonly INotificationsRepository _notificationRepository; + private readonly IEmailService _emailService; - public InviteLecturerEventHandler(INotificationsRepository notificationRepository, IEmailService emailService) - { - _notificationRepository = notificationRepository; - _emailService = emailService; - } + public InviteLecturerEventHandler(INotificationsRepository notificationRepository, IEmailService emailService) + { + _notificationRepository = notificationRepository; + _emailService = emailService; + } - public override async Task HandleAsync(InviteLecturerEvent @event) + public override async Task HandleAsync(InviteLecturerEvent @event) + { + var notification = new Notification { - var notification = new Notification - { - Sender = "AuthService", - Body = "Вас добавили в список лекторов.", - Category = CategoryState.Courses, - Date = DateTimeUtils.GetMoscowNow(), - Owner = @event.UserId - }; + Sender = "AuthService", + Body = "Вас добавили в список лекторов.", + Category = CategoryState.Courses, + Date = DateTimeUtils.GetMoscowNow(), + Owner = @event.UserId + }; - var addNotificationTask = _notificationRepository.AddAsync(notification); - var sendEmailTask = _emailService.SendEmailAsync(notification, @event.UserEmail, "HwProj"); + var addNotificationTask = _notificationRepository.AddAsync(notification); + var sendEmailTask = _emailService.SendEmailAsync(notification, @event.UserEmail, "HwProj"); - await Task.WhenAll(addNotificationTask, sendEmailTask); - } + await Task.WhenAll(addNotificationTask, sendEmailTask); } -} +} \ No newline at end of file diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/LecturerAcceptToCourseEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/LecturerAcceptToCourseEventHandler.cs index 6949e1854..dbe5fe418 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/LecturerAcceptToCourseEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/LecturerAcceptToCourseEventHandler.cs @@ -8,45 +8,44 @@ using HwProj.NotificationsService.API.Services; using Microsoft.Extensions.Configuration; -namespace HwProj.NotificationsService.API.EventHandlers +namespace HwProj.NotificationsService.API.EventHandlers; + +public class LecturerAcceptToCourseEventHandler : EventHandlerBase { - public class LecturerAcceptToCourseEventHandler : EventHandlerBase - { - private readonly INotificationsRepository _notificationRepository; - private readonly IAuthServiceClient _authServiceClient; - private readonly IConfigurationSection _configuration; - private readonly IEmailService _emailService; + private readonly INotificationsRepository _notificationRepository; + private readonly IAuthServiceClient _authServiceClient; + private readonly IConfigurationSection _configuration; + private readonly IEmailService _emailService; - public LecturerAcceptToCourseEventHandler( - INotificationsRepository notificationRepository, - IAuthServiceClient authServiceClient, - IConfiguration configuration, - IEmailService emailService) - { - _notificationRepository = notificationRepository; - _authServiceClient = authServiceClient; - _emailService = emailService; - _configuration = configuration.GetSection("Notification"); - } + public LecturerAcceptToCourseEventHandler( + INotificationsRepository notificationRepository, + IAuthServiceClient authServiceClient, + IConfiguration configuration, + IEmailService emailService) + { + _notificationRepository = notificationRepository; + _authServiceClient = authServiceClient; + _emailService = emailService; + _configuration = configuration.GetSection("Notification"); + } - public override async Task HandleAsync(LecturerAcceptToCourseEvent @event) + public override async Task HandleAsync(LecturerAcceptToCourseEvent @event) + { + var notification = new Notification { - var notification = new Notification - { - Sender = "CourseService", - Body = - $"Вас приняли на курс {@event.CourseName}.", - Category = CategoryState.Courses, - Date = DateTimeUtils.GetMoscowNow(), - Owner = @event.StudentId - }; + Sender = "CourseService", + Body = + $"Вас приняли на курс {@event.CourseName}.", + Category = CategoryState.Courses, + Date = DateTimeUtils.GetMoscowNow(), + Owner = @event.StudentId + }; - var student = await _authServiceClient.GetAccountData(notification.Owner); + var student = await _authServiceClient.GetAccountData(notification.Owner); - var addNotificationTask = _notificationRepository.AddAsync(notification); - var sendEmailTask = _emailService.SendEmailAsync(notification, student.Email, "HwProj"); + var addNotificationTask = _notificationRepository.AddAsync(notification); + var sendEmailTask = _emailService.SendEmailAsync(notification, student.Email, "HwProj"); - await Task.WhenAll(addNotificationTask, sendEmailTask); - } + await Task.WhenAll(addNotificationTask, sendEmailTask); } -} +} \ No newline at end of file diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/LecturerInvitedToCourseEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/LecturerInvitedToCourseEventHandler.cs index 22d0bb7a2..e5fa13a51 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/LecturerInvitedToCourseEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/LecturerInvitedToCourseEventHandler.cs @@ -7,40 +7,39 @@ using HwProj.NotificationsService.API.Services; using Microsoft.Extensions.Configuration; -namespace HwProj.NotificationsService.API.EventHandlers +namespace HwProj.NotificationsService.API.EventHandlers; + +public class LecturerInvitedToCourseEventHandler : EventHandlerBase { - public class LecturerInvitedToCourseEventHandler : EventHandlerBase - { - private readonly INotificationsRepository _notificationRepository; - private readonly IConfigurationSection _configuration; - private readonly IEmailService _emailService; + private readonly INotificationsRepository _notificationRepository; + private readonly IConfigurationSection _configuration; + private readonly IEmailService _emailService; - public LecturerInvitedToCourseEventHandler( - INotificationsRepository notificationRepository, - IConfiguration configuration, - IEmailService emailService) - { - _notificationRepository = notificationRepository; - _emailService = emailService; - _configuration = configuration.GetSection("Notification"); - } + public LecturerInvitedToCourseEventHandler( + INotificationsRepository notificationRepository, + IConfiguration configuration, + IEmailService emailService) + { + _notificationRepository = notificationRepository; + _emailService = emailService; + _configuration = configuration.GetSection("Notification"); + } - public override async Task HandleAsync(LecturerInvitedToCourseEvent @event) + public override async Task HandleAsync(LecturerInvitedToCourseEvent @event) + { + var notification = new Notification { - var notification = new Notification - { - Sender = "CourseService", - Body = - $"Вас пригласили в качестве преподавателя на курс {@event.CourseName}.", - Category = CategoryState.Courses, - Date = DateTimeUtils.GetMoscowNow(), - Owner = @event.MentorId - }; + Sender = "CourseService", + Body = + $"Вас пригласили в качестве преподавателя на курс {@event.CourseName}.", + Category = CategoryState.Courses, + Date = DateTimeUtils.GetMoscowNow(), + Owner = @event.MentorId + }; - var addNotificationTask = _notificationRepository.AddAsync(notification); - var sendEmailTask = _emailService.SendEmailAsync(notification, @event.MentorEmail, "HwProj"); + var addNotificationTask = _notificationRepository.AddAsync(notification); + var sendEmailTask = _emailService.SendEmailAsync(notification, @event.MentorEmail, "HwProj"); - await Task.WhenAll(addNotificationTask, sendEmailTask); - } + await Task.WhenAll(addNotificationTask, sendEmailTask); } -} +} \ No newline at end of file diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/LecturerRejectToCourseEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/LecturerRejectToCourseEventHandler.cs index cd9b28ab9..8880aff63 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/LecturerRejectToCourseEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/LecturerRejectToCourseEventHandler.cs @@ -8,45 +8,44 @@ using HwProj.NotificationsService.API.Services; using Microsoft.Extensions.Configuration; -namespace HwProj.NotificationsService.API.EventHandlers +namespace HwProj.NotificationsService.API.EventHandlers; + +public class LecturerRejectToCourseEventHandler : EventHandlerBase { - public class LecturerRejectToCourseEventHandler : EventHandlerBase - { - private readonly INotificationsRepository _notificationRepository; - private readonly IAuthServiceClient _authServiceClient; - private readonly IConfigurationSection _configuration; - private readonly IEmailService _emailService; + private readonly INotificationsRepository _notificationRepository; + private readonly IAuthServiceClient _authServiceClient; + private readonly IConfigurationSection _configuration; + private readonly IEmailService _emailService; - public LecturerRejectToCourseEventHandler( - INotificationsRepository notificationRepository, - IAuthServiceClient authServiceClient, - IConfiguration configuration, - IEmailService emailService) - { - _notificationRepository = notificationRepository; - _authServiceClient = authServiceClient; - _emailService = emailService; - _configuration = configuration.GetSection("Notification"); - } + public LecturerRejectToCourseEventHandler( + INotificationsRepository notificationRepository, + IAuthServiceClient authServiceClient, + IConfiguration configuration, + IEmailService emailService) + { + _notificationRepository = notificationRepository; + _authServiceClient = authServiceClient; + _emailService = emailService; + _configuration = configuration.GetSection("Notification"); + } - public override async Task HandleAsync(LecturerRejectToCourseEvent @event) + public override async Task HandleAsync(LecturerRejectToCourseEvent @event) + { + var notification = new Notification { - var notification = new Notification - { - Sender = "CourseService", - Body = - $"Вас не приняли на курс {@event.CourseName}.", - Category = CategoryState.Courses, - Date = DateTimeUtils.GetMoscowNow(), - Owner = @event.StudentId - }; + Sender = "CourseService", + Body = + $"Вас не приняли на курс {@event.CourseName}.", + Category = CategoryState.Courses, + Date = DateTimeUtils.GetMoscowNow(), + Owner = @event.StudentId + }; - var student = await _authServiceClient.GetAccountData(notification.Owner); + var student = await _authServiceClient.GetAccountData(notification.Owner); - var addNotificationTask = _notificationRepository.AddAsync(notification); - var sendEmailTask = _emailService.SendEmailAsync(notification, student.Email, "HwProj"); + var addNotificationTask = _notificationRepository.AddAsync(notification); + var sendEmailTask = _emailService.SendEmailAsync(notification, student.Email, "HwProj"); - await Task.WhenAll(addNotificationTask, sendEmailTask); - } + await Task.WhenAll(addNotificationTask, sendEmailTask); } -} +} \ No newline at end of file diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/NewCourseMateHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/NewCourseMateHandler.cs index 69ad03441..9df438e79 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/NewCourseMateHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/NewCourseMateHandler.cs @@ -8,54 +8,53 @@ using HwProj.NotificationsService.API.Services; using Microsoft.Extensions.Configuration; -namespace HwProj.NotificationsService.API.EventHandlers +namespace HwProj.NotificationsService.API.EventHandlers; + +public class NewCourseMateHandler : EventHandlerBase { - public class NewCourseMateHandler : EventHandlerBase + private readonly INotificationsRepository _notificationRepository; + private readonly IAuthServiceClient _authServiceClient; + private readonly IConfigurationSection _configuration; + private readonly IEmailService _emailService; + + public NewCourseMateHandler( + INotificationsRepository notificationRepository, + IAuthServiceClient authServiceClient, + IConfiguration configuration, + IEmailService emailService) { - private readonly INotificationsRepository _notificationRepository; - private readonly IAuthServiceClient _authServiceClient; - private readonly IConfigurationSection _configuration; - private readonly IEmailService _emailService; - - public NewCourseMateHandler( - INotificationsRepository notificationRepository, - IAuthServiceClient authServiceClient, - IConfiguration configuration, - IEmailService emailService) - { - _notificationRepository = notificationRepository; - _authServiceClient = authServiceClient; - _emailService = emailService; - _configuration = configuration.GetSection("Notification"); - } + _notificationRepository = notificationRepository; + _authServiceClient = authServiceClient; + _emailService = emailService; + _configuration = configuration.GetSection("Notification"); + } - public override async Task HandleAsync(NewCourseMateEvent @event) - { - var user = await _authServiceClient.GetAccountData(@event.StudentId); - var url = _configuration["Url"]; + public override async Task HandleAsync(NewCourseMateEvent @event) + { + var user = await _authServiceClient.GetAccountData(@event.StudentId); + var url = _configuration["Url"]; - //TODO: fix - foreach (var m in @event.MentorIds.Split('/')) + //TODO: fix + foreach (var m in @event.MentorIds.Split('/')) + { + var notification = new Notification { - var notification = new Notification - { - Sender = "CourseService", - Body = - $"Пользователь {user.Name} {user.Surname}" + - $" подал заявку на вступление в курс {@event.CourseName}.", - Category = CategoryState.Courses, - Date = DateTimeUtils.GetMoscowNow(), - HasSeen = false, - Owner = m - }; - - var mentor = await _authServiceClient.GetAccountData(notification.Owner); - - var addNotificationTask = _notificationRepository.AddAsync(notification); - var sendEmailTask = _emailService.SendEmailAsync(notification, mentor.Email, "HwProj"); - - await Task.WhenAll(addNotificationTask, sendEmailTask); - } + Sender = "CourseService", + Body = + $"Пользователь {user.Name} {user.Surname}" + + $" подал заявку на вступление в курс {@event.CourseName}.", + Category = CategoryState.Courses, + Date = DateTimeUtils.GetMoscowNow(), + HasSeen = false, + Owner = m + }; + + var mentor = await _authServiceClient.GetAccountData(notification.Owner); + + var addNotificationTask = _notificationRepository.AddAsync(notification); + var sendEmailTask = _emailService.SendEmailAsync(notification, mentor.Email, "HwProj"); + + await Task.WhenAll(addNotificationTask, sendEmailTask); } } -} +} \ No newline at end of file diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/NewHomeworkEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/NewHomeworkEventHandler.cs index 716374aca..06330f483 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/NewHomeworkEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/NewHomeworkEventHandler.cs @@ -9,51 +9,50 @@ using HwProj.NotificationsService.API.Services; using Microsoft.Extensions.Configuration; -namespace HwProj.NotificationsService.API.EventHandlers +namespace HwProj.NotificationsService.API.EventHandlers; + +public class NewHomeworkEventHandler : EventHandlerBase { - public class NewHomeworkEventHandler : EventHandlerBase + private readonly INotificationsRepository _notificationRepository; + private readonly IAuthServiceClient _authServiceClient; + private readonly IConfigurationSection _configuration; + private readonly IEmailService _emailService; + + public NewHomeworkEventHandler( + INotificationsRepository notificationRepository, + IAuthServiceClient authServiceClient, + IConfiguration configuration, + IEmailService emailService) { - private readonly INotificationsRepository _notificationRepository; - private readonly IAuthServiceClient _authServiceClient; - private readonly IConfigurationSection _configuration; - private readonly IEmailService _emailService; + _notificationRepository = notificationRepository; + _authServiceClient = authServiceClient; + _emailService = emailService; + _configuration = configuration.GetSection("Notification"); + } - public NewHomeworkEventHandler( - INotificationsRepository notificationRepository, - IAuthServiceClient authServiceClient, - IConfiguration configuration, - IEmailService emailService) - { - _notificationRepository = notificationRepository; - _authServiceClient = authServiceClient; - _emailService = emailService; - _configuration = configuration.GetSection("Notification"); - } + public override async Task HandleAsync(NewHomeworkEvent @event) + { + var studentIds = @event.Course.CourseMates.Select(t => t.StudentId).ToArray(); + var accountsData = await _authServiceClient.GetAccountsData(studentIds); - public override async Task HandleAsync(NewHomeworkEvent @event) + foreach (var student in accountsData) { - var studentIds = @event.Course.CourseMates.Select(t => t.StudentId).ToArray(); - var accountsData = await _authServiceClient.GetAccountsData(studentIds); - - foreach (var student in accountsData) + var notification = new Notification { - var notification = new Notification - { - Sender = "CourseService", - Body = - $"В курсе {@event.Course.Name}" + - $" опубликована новая домашняя работа {@event.Homework}.", - Category = CategoryState.Homeworks, - Date = DateTimeUtils.GetMoscowNow(), - HasSeen = false, - Owner = student!.UserId - }; + Sender = "CourseService", + Body = + $"В курсе {@event.Course.Name}" + + $" опубликована новая домашняя работа {@event.Homework}.", + Category = CategoryState.Homeworks, + Date = DateTimeUtils.GetMoscowNow(), + HasSeen = false, + Owner = student!.UserId + }; - var addNotificationTask = _notificationRepository.AddAsync(notification); - var sendEmailTask = _emailService.SendEmailAsync(notification, student.Email, "Домашняя работа"); + var addNotificationTask = _notificationRepository.AddAsync(notification); + var sendEmailTask = _emailService.SendEmailAsync(notification, student.Email, "Домашняя работа"); - await Task.WhenAll(addNotificationTask, sendEmailTask); - } + await Task.WhenAll(addNotificationTask, sendEmailTask); } } -} +} \ No newline at end of file diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/NewHomeworkTaskEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/NewHomeworkTaskEventHandler.cs index ba832df25..72bb38b6f 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/NewHomeworkTaskEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/NewHomeworkTaskEventHandler.cs @@ -9,53 +9,52 @@ using HwProj.NotificationsService.API.Services; using Microsoft.Extensions.Configuration; -namespace HwProj.NotificationsService.API.EventHandlers +namespace HwProj.NotificationsService.API.EventHandlers; + +public class NewHomeworkTaskEventHandler : EventHandlerBase { - public class NewHomeworkTaskEventHandler : EventHandlerBase + private readonly INotificationsRepository _notificationRepository; + private readonly IAuthServiceClient _authServiceClient; + private readonly IConfigurationSection _configuration; + private readonly IEmailService _emailService; + + public NewHomeworkTaskEventHandler( + INotificationsRepository notificationRepository, + IAuthServiceClient authServiceClient, + IConfiguration configuration, + IEmailService emailService) { - private readonly INotificationsRepository _notificationRepository; - private readonly IAuthServiceClient _authServiceClient; - private readonly IConfigurationSection _configuration; - private readonly IEmailService _emailService; - - public NewHomeworkTaskEventHandler( - INotificationsRepository notificationRepository, - IAuthServiceClient authServiceClient, - IConfiguration configuration, - IEmailService emailService) - { - _notificationRepository = notificationRepository; - _authServiceClient = authServiceClient; - _emailService = emailService; - _configuration = configuration.GetSection("Notification"); - } + _notificationRepository = notificationRepository; + _authServiceClient = authServiceClient; + _emailService = emailService; + _configuration = configuration.GetSection("Notification"); + } - public override async Task HandleAsync(NewHomeworkTaskEvent @event) - { - var studentIds = @event.Course.CourseMates.Select(t => t.StudentId).ToArray(); - var accountsData = await _authServiceClient.GetAccountsData(studentIds); - var url = _configuration["Url"]; + public override async Task HandleAsync(NewHomeworkTaskEvent @event) + { + var studentIds = @event.Course.CourseMates.Select(t => t.StudentId).ToArray(); + var accountsData = await _authServiceClient.GetAccountsData(studentIds); + var url = _configuration["Url"]; - foreach (var student in accountsData) + foreach (var student in accountsData) + { + var notification = new Notification { - var notification = new Notification - { - Sender = "CourseService", - Body = - $"В курсе {@event.Course.Name}" + - $" опубликована новая задача {@event.TaskTitle}." + - (@event.Deadline is { } deadline ? $"\n\nДедлайн: {deadline:U}" : ""), - - Category = CategoryState.Homeworks, - Date = DateTimeUtils.GetMoscowNow(), - Owner = student!.UserId - }; - - var addNotificationTask = _notificationRepository.AddAsync(notification); - var sendEmailTask = _emailService.SendEmailAsync(notification, student.Email, "Новая задача"); - - await Task.WhenAll(addNotificationTask, sendEmailTask); - } + Sender = "CourseService", + Body = + $"В курсе {@event.Course.Name}" + + $" опубликована новая задача {@event.TaskTitle}." + + (@event.Deadline is { } deadline ? $"\n\nДедлайн: {deadline:U}" : ""), + + Category = CategoryState.Homeworks, + Date = DateTimeUtils.GetMoscowNow(), + Owner = student!.UserId + }; + + var addNotificationTask = _notificationRepository.AddAsync(notification); + var sendEmailTask = _emailService.SendEmailAsync(notification, student.Email, "Новая задача"); + + await Task.WhenAll(addNotificationTask, sendEmailTask); } } -} +} \ No newline at end of file diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/RateEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/RateEventHandler.cs index fa6657e28..f9e1e75f9 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/RateEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/RateEventHandler.cs @@ -8,46 +8,45 @@ using HwProj.SolutionsService.API.Events; using Microsoft.Extensions.Configuration; -namespace HwProj.NotificationsService.API.EventHandlers +namespace HwProj.NotificationsService.API.EventHandlers; + +public class RateEventHandler : EventHandlerBase { - public class RateEventHandler : EventHandlerBase - { - private readonly INotificationsRepository _notificationRepository; - private readonly IAuthServiceClient _authServiceClient; - private readonly IConfigurationSection _configuration; - private readonly IEmailService _emailService; + private readonly INotificationsRepository _notificationRepository; + private readonly IAuthServiceClient _authServiceClient; + private readonly IConfigurationSection _configuration; + private readonly IEmailService _emailService; - public RateEventHandler( - INotificationsRepository notificationRepository, - IAuthServiceClient authServiceClient, - IConfiguration configuration, - IEmailService emailService) - { - _notificationRepository = notificationRepository; - _authServiceClient = authServiceClient; - _emailService = emailService; - _configuration = configuration.GetSection("Notification"); - } + public RateEventHandler( + INotificationsRepository notificationRepository, + IAuthServiceClient authServiceClient, + IConfiguration configuration, + IEmailService emailService) + { + _notificationRepository = notificationRepository; + _authServiceClient = authServiceClient; + _emailService = emailService; + _configuration = configuration.GetSection("Notification"); + } - public override async Task HandleAsync(RateEvent @event) + public override async Task HandleAsync(RateEvent @event) + { + var notification = new Notification { - var notification = new Notification - { - Sender = "SolutionService", - Body = - $"Задача {@event.Task.Title} оценена.", - Category = CategoryState.Homeworks, - Date = DateTimeUtils.GetMoscowNow(), - HasSeen = false, - Owner = @event.Solution.StudentId - }; + Sender = "SolutionService", + Body = + $"Задача {@event.Task.Title} оценена.", + Category = CategoryState.Homeworks, + Date = DateTimeUtils.GetMoscowNow(), + HasSeen = false, + Owner = @event.Solution.StudentId + }; - var student = await _authServiceClient.GetAccountData(notification.Owner); + var student = await _authServiceClient.GetAccountData(notification.Owner); - var addNotificationTask = _notificationRepository.AddAsync(notification); - var sendEmailTask = _emailService.SendEmailAsync(notification, student.Email, "Оценка"); + var addNotificationTask = _notificationRepository.AddAsync(notification); + var sendEmailTask = _emailService.SendEmailAsync(notification, student.Email, "Оценка"); - await Task.WhenAll(addNotificationTask, sendEmailTask); - } + await Task.WhenAll(addNotificationTask, sendEmailTask); } -} +} \ No newline at end of file diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/RegisterEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/RegisterEventHandler.cs index e094fdc05..390197dc3 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/RegisterEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/RegisterEventHandler.cs @@ -6,35 +6,34 @@ using HwProj.NotificationsService.API.Repositories; using HwProj.NotificationsService.API.Services; -namespace HwProj.NotificationsService.API.EventHandlers +namespace HwProj.NotificationsService.API.EventHandlers; + +public class RegisterEventHandler : EventHandlerBase { - public class RegisterEventHandler : EventHandlerBase - { - private readonly INotificationsRepository _notificationRepository; - private readonly IEmailService _emailService; + private readonly INotificationsRepository _notificationRepository; + private readonly IEmailService _emailService; - public RegisterEventHandler(INotificationsRepository notificationRepository, IEmailService emailService) - { - _notificationRepository = notificationRepository; - _emailService = emailService; - } + public RegisterEventHandler(INotificationsRepository notificationRepository, IEmailService emailService) + { + _notificationRepository = notificationRepository; + _emailService = emailService; + } - public override async Task HandleAsync(StudentRegisterEvent @event) + public override async Task HandleAsync(StudentRegisterEvent @event) + { + var notification = new Notification { - var notification = new Notification - { - Sender = "AuthService", - Body = $"{@event.Name} {@event.Surname}, Добро Пожаловать в HwProj2.", - Category = CategoryState.Profile, - Date = DateTimeUtils.GetMoscowNow(), - HasSeen = false, - Owner = @event.UserId - }; + Sender = "AuthService", + Body = $"{@event.Name} {@event.Surname}, Добро Пожаловать в HwProj2.", + Category = CategoryState.Profile, + Date = DateTimeUtils.GetMoscowNow(), + HasSeen = false, + Owner = @event.UserId + }; - var addNotificationTask = _notificationRepository.AddAsync(notification); - var sendEmailTask = _emailService.SendEmailAsync(notification, @event.Email, "HwProj"); + var addNotificationTask = _notificationRepository.AddAsync(notification); + var sendEmailTask = _emailService.SendEmailAsync(notification, @event.Email, "HwProj"); - await Task.WhenAll(addNotificationTask, sendEmailTask); - } + await Task.WhenAll(addNotificationTask, sendEmailTask); } -} +} \ No newline at end of file diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/StudentPassTaskEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/StudentPassTaskEventHandler.cs index 58d78d933..16269401a 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/StudentPassTaskEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/StudentPassTaskEventHandler.cs @@ -8,51 +8,50 @@ using HwProj.SolutionsService.API.Events; using Microsoft.Extensions.Configuration; -namespace HwProj.NotificationsService.API.EventHandlers +namespace HwProj.NotificationsService.API.EventHandlers; + +public class StudentPassTaskEventHandler : EventHandlerBase { - public class StudentPassTaskEventHandler : EventHandlerBase - { - private readonly INotificationsRepository _notificationRepository; - private readonly IAuthServiceClient _authServiceClient; - private readonly IConfigurationSection _configuration; - private readonly IEmailService _emailService; + private readonly INotificationsRepository _notificationRepository; + private readonly IAuthServiceClient _authServiceClient; + private readonly IConfigurationSection _configuration; + private readonly IEmailService _emailService; - public StudentPassTaskEventHandler( - INotificationsRepository notificationRepository, - IAuthServiceClient authServiceClient, - IConfiguration configuration, - IEmailService emailService) - { - _notificationRepository = notificationRepository; - _authServiceClient = authServiceClient; - _emailService = emailService; - _configuration = configuration.GetSection("Notification"); - } + public StudentPassTaskEventHandler( + INotificationsRepository notificationRepository, + IAuthServiceClient authServiceClient, + IConfiguration configuration, + IEmailService emailService) + { + _notificationRepository = notificationRepository; + _authServiceClient = authServiceClient; + _emailService = emailService; + _configuration = configuration.GetSection("Notification"); + } - public override async Task HandleAsync(StudentPassTaskEvent @event) + public override async Task HandleAsync(StudentPassTaskEvent @event) + { + foreach (var m in @event.Course.MentorIds) { - foreach (var m in @event.Course.MentorIds) + var notification = new Notification { - var notification = new Notification - { - Sender = "SolutionService", - Body = $"{@event.Student.Name} {@event.Student.Surname} добавил новое " + - $"решение" + - $" задачи {@event.Task.Title}" + - $" из курса {@event.Course.Name}.", - Category = CategoryState.Homeworks, - Date = DateTimeUtils.GetMoscowNow(), - HasSeen = false, - Owner = m - }; + Sender = "SolutionService", + Body = $"{@event.Student.Name} {@event.Student.Surname} добавил новое " + + $"решение" + + $" задачи {@event.Task.Title}" + + $" из курса {@event.Course.Name}.", + Category = CategoryState.Homeworks, + Date = DateTimeUtils.GetMoscowNow(), + HasSeen = false, + Owner = m + }; - var mentor = await _authServiceClient.GetAccountData(notification.Owner); + var mentor = await _authServiceClient.GetAccountData(notification.Owner); - var addNotificationTask = _notificationRepository.AddAsync(notification); - var sendEmailTask = _emailService.SendEmailAsync(notification, mentor.Email, "HwProj"); + var addNotificationTask = _notificationRepository.AddAsync(notification); + var sendEmailTask = _emailService.SendEmailAsync(notification, mentor.Email, "HwProj"); - await Task.WhenAll(addNotificationTask, sendEmailTask); - } + await Task.WhenAll(addNotificationTask, sendEmailTask); } } -} +} \ No newline at end of file diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/UpdateHomeworkEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/UpdateHomeworkEventHandler.cs index d2bbc4de3..051682c00 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/UpdateHomeworkEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/UpdateHomeworkEventHandler.cs @@ -8,48 +8,47 @@ using HwProj.NotificationsService.API.Services; using Microsoft.Extensions.Configuration; -namespace HwProj.NotificationsService.API.EventHandlers +namespace HwProj.NotificationsService.API.EventHandlers; + +public class UpdateHomeworkEventHandler : EventHandlerBase { - public class UpdateHomeworkEventHandler : EventHandlerBase - { - private readonly INotificationsRepository _notificationRepository; - private readonly IAuthServiceClient _authServiceClient; - private readonly IConfigurationSection _configuration; - private readonly IEmailService _emailService; + private readonly INotificationsRepository _notificationRepository; + private readonly IAuthServiceClient _authServiceClient; + private readonly IConfigurationSection _configuration; + private readonly IEmailService _emailService; - public UpdateHomeworkEventHandler( - INotificationsRepository notificationRepository, - IAuthServiceClient authServiceClient, - IConfiguration configuration, - IEmailService emailService) - { - _notificationRepository = notificationRepository; - _authServiceClient = authServiceClient; - _emailService = emailService; - _configuration = configuration.GetSection("Notification"); - } + public UpdateHomeworkEventHandler( + INotificationsRepository notificationRepository, + IAuthServiceClient authServiceClient, + IConfiguration configuration, + IEmailService emailService) + { + _notificationRepository = notificationRepository; + _authServiceClient = authServiceClient; + _emailService = emailService; + _configuration = configuration.GetSection("Notification"); + } - public override async Task HandleAsync(UpdateHomeworkEvent @event) + public override async Task HandleAsync(UpdateHomeworkEvent @event) + { + foreach (var student in @event.Course.CourseMates) { - foreach (var student in @event.Course.CourseMates) + var studentModel = await _authServiceClient.GetAccountData(student.StudentId); + var notification = new Notification { - var studentModel = await _authServiceClient.GetAccountData(student.StudentId); - var notification = new Notification - { - Sender = "CourseService", - Body = - $"В курсе {@event.Course.Name} домашнее задание {@event.Homework.Title} обновлено.", - Category = CategoryState.Homeworks, - Date = DateTimeUtils.GetMoscowNow(), - HasSeen = false, - Owner = student.StudentId - }; + Sender = "CourseService", + Body = + $"В курсе {@event.Course.Name} домашнее задание {@event.Homework.Title} обновлено.", + Category = CategoryState.Homeworks, + Date = DateTimeUtils.GetMoscowNow(), + HasSeen = false, + Owner = student.StudentId + }; - var addNotificationTask = _notificationRepository.AddAsync(notification); - var sendEmailTask = _emailService.SendEmailAsync(notification, studentModel.Email, "Домашняя работа"); + var addNotificationTask = _notificationRepository.AddAsync(notification); + var sendEmailTask = _emailService.SendEmailAsync(notification, studentModel.Email, "Домашняя работа"); - await Task.WhenAll(addNotificationTask, sendEmailTask); - } + await Task.WhenAll(addNotificationTask, sendEmailTask); } } -} +} \ No newline at end of file diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/HwProj.NotificationsService.API.csproj b/HwProj.NotificationsService/HwProj.NotificationsService.API/HwProj.NotificationsService.API.csproj index 118a5f418..d651aae8f 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/HwProj.NotificationsService.API.csproj +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/HwProj.NotificationsService.API.csproj @@ -1,7 +1,7 @@  - netcoreapp2.2 + net6.0 ..\..\docker-compose.dcproj Linux ..\.. @@ -14,12 +14,9 @@ - - - - - - + + + diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/Models/NotificationsContext.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/Models/NotificationsContext.cs index 183f2b721..8eb8be03f 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/Models/NotificationsContext.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/Models/NotificationsContext.cs @@ -1,16 +1,15 @@ using HwProj.Models.NotificationsService; using Microsoft.EntityFrameworkCore; -namespace HwProj.NotificationsService.API.Models +namespace HwProj.NotificationsService.API.Models; + +public sealed class NotificationsContext : DbContext { - public sealed class NotificationsContext : DbContext - { - public DbSet Notifications { get; set; } + public DbSet Notifications { get; set; } - public NotificationsContext(DbContextOptions options) - : base(options) - { - Database.EnsureCreated(); - } + public NotificationsContext(DbContextOptions options) + : base(options) + { + Database.EnsureCreated(); } } \ No newline at end of file diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/Program.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/Program.cs index 6cd459acb..9cd260aff 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/Program.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/Program.cs @@ -1,17 +1,16 @@ using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; -namespace HwProj.NotificationsService.API +namespace HwProj.NotificationsService.API; + +public class Program { - public class Program + public static void Main(string[] args) { - public static void Main(string[] args) - { - CreateWebHostBuilder(args).Build().Run(); - } - - public static IWebHostBuilder CreateWebHostBuilder(string[] args) => - WebHost.CreateDefaultBuilder(args) - .UseStartup(); + CreateWebHostBuilder(args).Build().Run(); } -} + + public static IWebHostBuilder CreateWebHostBuilder(string[] args) => + WebHost.CreateDefaultBuilder(args) + .UseStartup(); +} \ No newline at end of file diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/Repositories/INotificationsRepository.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/Repositories/INotificationsRepository.cs index 8742cccc0..19159aa1f 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/Repositories/INotificationsRepository.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/Repositories/INotificationsRepository.cs @@ -4,13 +4,12 @@ using HwProj.Models.NotificationsService; using HwProj.Repositories; -namespace HwProj.NotificationsService.API.Repositories +namespace HwProj.NotificationsService.API.Repositories; + +public interface INotificationsRepository : ICrudRepository { - public interface INotificationsRepository : ICrudRepository - { - Task UpdateBatchAsync(string userId, long[] ids, Expression> updateFactory); - Task GetAllByUserAsync(string userId); - Task MarkAsSeenAsync(string userId, long[] notificationIds); - Task AddNotificationAsync(Notification notification); - } + Task UpdateBatchAsync(string userId, long[] ids, Expression> updateFactory); + Task GetAllByUserAsync(string userId); + Task MarkAsSeenAsync(string userId, long[] notificationIds); + Task AddNotificationAsync(Notification notification); } \ No newline at end of file diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/Repositories/NotificationsRepository.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/Repositories/NotificationsRepository.cs index 5e9df57a4..adf9c1ffc 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/Repositories/NotificationsRepository.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/Repositories/NotificationsRepository.cs @@ -8,36 +8,35 @@ using Microsoft.EntityFrameworkCore; using Z.EntityFramework.Plus; -namespace HwProj.NotificationsService.API.Repositories +namespace HwProj.NotificationsService.API.Repositories; + +public class NotificationsRepository : CrudRepository, INotificationsRepository { - public class NotificationsRepository : CrudRepository, INotificationsRepository + public NotificationsRepository(NotificationsContext context) + : base(context) { - public NotificationsRepository(NotificationsContext context) - : base(context) - { - } + } - public async Task AddNotificationAsync(Notification notification) - { - var id = await AddAsync(notification); - return id; - } + public async Task AddNotificationAsync(Notification notification) + { + var id = await AddAsync(notification); + return id; + } - public async Task MarkAsSeenAsync(string userId, long[] notificationIds) => - await UpdateBatchAsync(userId, notificationIds, - t => new Notification {HasSeen = true}); + public async Task MarkAsSeenAsync(string userId, long[] notificationIds) => + await UpdateBatchAsync(userId, notificationIds, + t => new Notification {HasSeen = true}); - public async Task UpdateBatchAsync(string userId, long[] ids, - Expression> updateFactory) => - await Context.Set() - .Where(t => t.Owner == userId && ids.Contains(t.Id)) - .UpdateAsync(updateFactory); + public async Task UpdateBatchAsync(string userId, long[] ids, + Expression> updateFactory) => + await Context.Set() + .Where(t => t.Owner == userId && ids.Contains(t.Id)) + .UpdateAsync(updateFactory); - public async Task GetAllByUserAsync(string userId) - { - var result = Context.Set().Where(t => t.Owner == userId); + public async Task GetAllByUserAsync(string userId) + { + var result = Context.Set().Where(t => t.Owner == userId); - return await result.OrderByDescending(t => t.Date).ToArrayAsync(); - } + return await result.OrderByDescending(t => t.Date).ToArrayAsync(); } } \ No newline at end of file diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/Services/EmailService.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/Services/EmailService.cs index ee3a38fb3..91aa54d98 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/Services/EmailService.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/Services/EmailService.cs @@ -6,48 +6,47 @@ using Microsoft.Extensions.Logging; using MimeKit; -namespace HwProj.NotificationsService.API.Services +namespace HwProj.NotificationsService.API.Services; + +public class EmailService : IEmailService { - public class EmailService : IEmailService + private readonly IConfiguration _configuration; + private readonly ILogger _logger; + + public EmailService(IConfiguration configuration, ILogger logger) { - private readonly IConfiguration _configuration; - private readonly ILogger _logger; + _configuration = configuration; + _logger = logger; + } - public EmailService(IConfiguration configuration, ILogger logger) + public async Task SendEmailAsync(Notification notification, string email, string topic) + { + try { - _configuration = configuration; - _logger = logger; - } + var configurationSection = _configuration.GetSection("Notification"); + var connectSite = configurationSection["ConnectSite"]; + var password = configurationSection["Password"]; + var serviceMail = configurationSection["Mail"]; - public async Task SendEmailAsync(Notification notification, string email, string topic) - { - try - { - var configurationSection = _configuration.GetSection("Notification"); - var connectSite = configurationSection["ConnectSite"]; - var password = configurationSection["Password"]; - var serviceMail = configurationSection["Mail"]; - - using var client = new MailKit.Net.Smtp.SmtpClient(); - await client.ConnectAsync(connectSite, 465, true); - await client.AuthenticateAsync(serviceMail, password); - - var emailMessage = new MimeMessage - { - From = { new MailboxAddress("HwProj-2.0.1", serviceMail) }, - To = { new MailboxAddress("", email) }, - Body = new TextPart(MimeKit.Text.TextFormat.Html) { Text = notification.Body }, - Subject = topic - }; - - _logger.LogInformation($"Sending email to {email} with topic {topic}"); - - await client.SendAsync(emailMessage); - } - catch (Exception ex) + using var client = new MailKit.Net.Smtp.SmtpClient(); + await client.ConnectAsync(connectSite, 465, true); + await client.AuthenticateAsync(serviceMail, password); + + var emailMessage = new MimeMessage { - _logger.LogError(ex, $"Error while sending email to {email} with topic {topic}"); - } + From = { new MailboxAddress("HwProj-2.0.1", serviceMail) }, + To = { new MailboxAddress("", email) }, + Body = new TextPart(MimeKit.Text.TextFormat.Html) { Text = notification.Body }, + Subject = topic + }; + + _logger.LogInformation($"Sending email to {email} with topic {topic}"); + + await client.SendAsync(emailMessage); + } + catch (Exception ex) + { + _logger.LogError(ex, $"Error while sending email to {email} with topic {topic}"); } } -} +} \ No newline at end of file diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/Services/IEmailService.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/Services/IEmailService.cs index b2dcbdc86..c29f98900 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/Services/IEmailService.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/Services/IEmailService.cs @@ -1,10 +1,9 @@ using HwProj.Models.NotificationsService; using System.Threading.Tasks; -namespace HwProj.NotificationsService.API.Services +namespace HwProj.NotificationsService.API.Services; + +public interface IEmailService { - public interface IEmailService - { - Task SendEmailAsync(Notification notification, string email, string topic); - } + Task SendEmailAsync(Notification notification, string email, string topic); } \ No newline at end of file diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/Services/NotificationsDomain.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/Services/NotificationsDomain.cs index 7ac73f149..3af685a74 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/Services/NotificationsDomain.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/Services/NotificationsDomain.cs @@ -1,24 +1,23 @@ using System.Linq; using HwProj.Models.NotificationsService; -namespace HwProj.NotificationsService.API.Services +namespace HwProj.NotificationsService.API.Services; + +public static class NotificationsDomain { - public static class NotificationsDomain - { - public static CategorizedNotifications[] Group(NotificationViewModel[] notifications) => - notifications - .GroupBy(t => t.Category) - .Select(category => ( - category.Key, - category.Where(t => t.HasSeen).ToArray(), - category.Where(t => !t.HasSeen).ToArray())) - .Select(element => - new CategorizedNotifications - { - Category = element.Key, - SeenNotifications = element.Item2, - NotSeenNotifications = element.Item3 - }) - .ToArray(); - } -} + public static CategorizedNotifications[] Group(NotificationViewModel[] notifications) => + notifications + .GroupBy(t => t.Category) + .Select(category => ( + category.Key, + category.Where(t => t.HasSeen).ToArray(), + category.Where(t => !t.HasSeen).ToArray())) + .Select(element => + new CategorizedNotifications + { + Category = element.Key, + SeenNotifications = element.Item2, + NotSeenNotifications = element.Item3 + }) + .ToArray(); +} \ No newline at end of file diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/Startup.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/Startup.cs index 723444a4f..bdf2a04fb 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/Startup.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/Startup.cs @@ -17,64 +17,63 @@ using HwProj.SolutionsService.Client; using UpdateTaskMaxRatingEvent = HwProj.CoursesService.API.Events.UpdateTaskMaxRatingEvent; -namespace HwProj.NotificationsService.API +namespace HwProj.NotificationsService.API; + +public class Startup { - public class Startup + public Startup(IConfiguration configuration) { - public Startup(IConfiguration configuration) - { - Configuration = configuration; - } + Configuration = configuration; + } - public IConfiguration Configuration { get; } + public IConfiguration Configuration { get; } - public void ConfigureServices(IServiceCollection services) - { - var connectionString = ConnectionString.GetConnectionString(Configuration); - services.AddDbContext(options => options.UseSqlServer(connectionString)); - services.AddScoped(); - services.AddEventBus(Configuration); - services.AddTransient, RegisterEventHandler>(); - services.AddTransient, RateEventHandler>(); - services.AddTransient, StudentPassTaskEventHandler>(); - services.AddTransient, UpdateHomeworkEventHandler>(); - services.AddTransient, UpdateTaskMaxRatingEventHandler>(); - services.AddTransient, LecturerAcceptToCourseEventHandler>(); - services.AddTransient, LecturerRejectToCourseEventHandler>(); - services.AddTransient, LecturerInvitedToCourseEventHandler>(); - services.AddTransient, NewHomeworkEventHandler>(); - services.AddTransient, NewHomeworkTaskEventHandler>(); - services.AddTransient, InviteLecturerEventHandler>(); - services.AddTransient, NewCourseMateHandler>(); - services.AddSingleton(); + public void ConfigureServices(IServiceCollection services) + { + var connectionString = ConnectionString.GetConnectionString(Configuration); + services.AddDbContext(options => options.UseSqlServer(connectionString)); + services.AddScoped(); + services.AddEventBus(Configuration); + services.AddTransient, RegisterEventHandler>(); + services.AddTransient, RateEventHandler>(); + services.AddTransient, StudentPassTaskEventHandler>(); + services.AddTransient, UpdateHomeworkEventHandler>(); + services.AddTransient, UpdateTaskMaxRatingEventHandler>(); + services.AddTransient, LecturerAcceptToCourseEventHandler>(); + services.AddTransient, LecturerRejectToCourseEventHandler>(); + services.AddTransient, LecturerInvitedToCourseEventHandler>(); + services.AddTransient, NewHomeworkEventHandler>(); + services.AddTransient, NewHomeworkTaskEventHandler>(); + services.AddTransient, InviteLecturerEventHandler>(); + services.AddTransient, NewCourseMateHandler>(); + services.AddSingleton(); - services.AddHttpClient(); - services.AddAuthServiceClient(); - services.AddCoursesServiceClient(); - services.AddSolutionServiceClient(); + services.AddHttpClient(); + services.AddAuthServiceClient(); + services.AddCoursesServiceClient(); + services.AddSolutionServiceClient(); - services.ConfigureHwProjServices("Notifications API"); - } + services.ConfigureHwProjServices("Notifications API"); + } - public void Configure(IApplicationBuilder app, IHostingEnvironment env, IEventBus eventBus) + public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IEventBus eventBus) + { + using (var eventBustSubscriber = eventBus.CreateSubscriber()) { - using (var eventBustSubscriber = eventBus.CreateSubscriber()) - { - eventBustSubscriber.Subscribe(); - eventBustSubscriber.Subscribe(); - eventBustSubscriber.Subscribe(); - eventBustSubscriber.Subscribe(); - eventBustSubscriber.Subscribe(); - eventBustSubscriber.Subscribe(); - eventBustSubscriber.Subscribe(); - eventBustSubscriber.Subscribe(); - eventBustSubscriber.Subscribe(); - eventBustSubscriber.Subscribe(); - eventBustSubscriber.Subscribe(); - eventBustSubscriber.Subscribe(); - } - - app.ConfigureHwProj(env, "Notifications API"); + eventBustSubscriber.Subscribe(); + eventBustSubscriber.Subscribe(); + eventBustSubscriber.Subscribe(); + eventBustSubscriber.Subscribe(); + eventBustSubscriber.Subscribe(); + eventBustSubscriber.Subscribe(); + eventBustSubscriber.Subscribe(); + eventBustSubscriber.Subscribe(); + eventBustSubscriber.Subscribe(); + eventBustSubscriber.Subscribe(); + eventBustSubscriber.Subscribe(); + eventBustSubscriber.Subscribe(); } + + app.ConfigureHwProj(env, "Notifications API"); } } diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.Client/ConfigurationExtensions.cs b/HwProj.NotificationsService/HwProj.NotificationsService.Client/ConfigurationExtensions.cs index f53647176..8a7e5364c 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.Client/ConfigurationExtensions.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.Client/ConfigurationExtensions.cs @@ -1,13 +1,12 @@ using Microsoft.Extensions.DependencyInjection; -namespace HwProj.NotificationsService.Client +namespace HwProj.NotificationsService.Client; + +public static class ConfigurationExtensions { - public static class ConfigurationExtensions + public static IServiceCollection AddNotificationsServiceClient(this IServiceCollection services) { - public static IServiceCollection AddNotificationsServiceClient(this IServiceCollection services) - { - services.AddScoped(); - return services; - } + services.AddScoped(); + return services; } -} +} \ No newline at end of file diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.Client/HwProj.NotificationsService.Client.csproj b/HwProj.NotificationsService/HwProj.NotificationsService.Client/HwProj.NotificationsService.Client.csproj index 628a06d8a..40616791b 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.Client/HwProj.NotificationsService.Client.csproj +++ b/HwProj.NotificationsService/HwProj.NotificationsService.Client/HwProj.NotificationsService.Client.csproj @@ -2,7 +2,7 @@ Library - netcoreapp2.2 + net6.0 $(CSharpLanguageVersion) @@ -15,7 +15,8 @@ - + + diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.Client/INotificationsServiceClient.cs b/HwProj.NotificationsService/HwProj.NotificationsService.Client/INotificationsServiceClient.cs index 04a04fca2..61fe3eae3 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.Client/INotificationsServiceClient.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.Client/INotificationsServiceClient.cs @@ -1,13 +1,12 @@ using HwProj.Models.NotificationsService; using System.Threading.Tasks; -namespace HwProj.NotificationsService.Client +namespace HwProj.NotificationsService.Client; + +public interface INotificationsServiceClient { - public interface INotificationsServiceClient - { - Task Get(string userId); - Task MarkAsSeen(string userId, long[] notificationIds); - Task GetNewNotificationsCount(string userId); - Task Ping(); - } -} + Task Get(string userId); + Task MarkAsSeen(string userId, long[] notificationIds); + Task GetNewNotificationsCount(string userId); + Task Ping(); +} \ No newline at end of file diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.Client/NotificationsServiceClient.cs b/HwProj.NotificationsService/HwProj.NotificationsService.Client/NotificationsServiceClient.cs index 59b80faaf..ce971d207 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.Client/NotificationsServiceClient.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.Client/NotificationsServiceClient.cs @@ -7,56 +7,55 @@ using System.Threading.Tasks; using Microsoft.Extensions.Configuration; -namespace HwProj.NotificationsService.Client +namespace HwProj.NotificationsService.Client; + +public class NotificationsServiceClient : INotificationsServiceClient { - public class NotificationsServiceClient : INotificationsServiceClient + private readonly HttpClient _httpClient; + private readonly Uri _notificationServiceUri; + + public NotificationsServiceClient(IHttpClientFactory clientFactory, IConfiguration configuration) { - private readonly HttpClient _httpClient; - private readonly Uri _notificationServiceUri; + _httpClient = clientFactory.CreateClient(); + _notificationServiceUri = new Uri(configuration.GetSection("Services")["Notifications"]); + } - public NotificationsServiceClient(IHttpClientFactory clientFactory, IConfiguration configuration) - { - _httpClient = clientFactory.CreateClient(); - _notificationServiceUri = new Uri(configuration.GetSection("Services")["Notifications"]); - } + public async Task Get(string userId) + { + using var response = + await _httpClient.GetAsync(_notificationServiceUri + $"api/notifications/get/{userId}"); + return await response.DeserializeAsync() ?? new CategorizedNotifications[] { }; + } - public async Task Get(string userId) - { - using var response = - await _httpClient.GetAsync(_notificationServiceUri + $"api/notifications/get/{userId}"); - return await response.DeserializeAsync() ?? new CategorizedNotifications[] { }; - } + public async Task MarkAsSeen(string userId, long[] notificationIds) + { + using var httpRequest = new HttpRequestMessage( + HttpMethod.Put, + _notificationServiceUri + "api/notifications/markAsSeen/" + userId); - public async Task MarkAsSeen(string userId, long[] notificationIds) - { - using var httpRequest = new HttpRequestMessage( - HttpMethod.Put, - _notificationServiceUri + "api/notifications/markAsSeen/" + userId); + var jsonIds = JsonConvert.SerializeObject(notificationIds); + httpRequest.Content = new StringContent(jsonIds, Encoding.UTF8, "application/json"); - var jsonIds = JsonConvert.SerializeObject(notificationIds); - httpRequest.Content = new StringContent(jsonIds, Encoding.UTF8, "application/json"); + await _httpClient.SendAsync(httpRequest); + } - await _httpClient.SendAsync(httpRequest); - } + public async Task GetNewNotificationsCount(string userId) + { + using var response = + await _httpClient.GetAsync(_notificationServiceUri + $"api/notifications/new/{userId}"); + return await response.DeserializeAsync(); + } - public async Task GetNewNotificationsCount(string userId) + public async Task Ping() + { + try { - using var response = - await _httpClient.GetAsync(_notificationServiceUri + $"api/notifications/new/{userId}"); - return await response.DeserializeAsync(); + await _httpClient.GetAsync(_notificationServiceUri + "api/system/ping"); + return true; } - - public async Task Ping() + catch { - try - { - await _httpClient.GetAsync(_notificationServiceUri + "api/system/ping"); - return true; - } - catch - { - return false; - } + return false; } } -} +} \ No newline at end of file diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.Tests/HwProj.NotificationsService.Tests.csproj b/HwProj.NotificationsService/HwProj.NotificationsService.Tests/HwProj.NotificationsService.Tests.csproj index f2af1e77f..d33a76c34 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.Tests/HwProj.NotificationsService.Tests.csproj +++ b/HwProj.NotificationsService/HwProj.NotificationsService.Tests/HwProj.NotificationsService.Tests.csproj @@ -1,7 +1,7 @@  - netcoreapp2.2 + net6.0 false @@ -11,10 +11,10 @@ - - - - + + + + diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.Tests/NotificationsServiceTests.cs b/HwProj.NotificationsService/HwProj.NotificationsService.Tests/NotificationsServiceTests.cs index 4f8f579fb..47c3ce479 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.Tests/NotificationsServiceTests.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.Tests/NotificationsServiceTests.cs @@ -1,14 +1,13 @@ using NUnit.Framework; -namespace HwProj.NotificationsService.Tests +namespace HwProj.NotificationsService.Tests; + +[TestFixture] +public class SolutionsServiceTests { - [TestFixture] - public class SolutionsServiceTests + [Test] + public void SimpleTest() { - [Test] - public void SimpleTest() - { - Assert.AreEqual(1, 1); - } + Assert.AreEqual(1, 1); } } \ No newline at end of file diff --git a/HwProj.SolutionsService/HwProj.SolutionsService.API/AutomapperProfile.cs b/HwProj.SolutionsService/HwProj.SolutionsService.API/AutomapperProfile.cs index e34eb7446..48076e2f1 100644 --- a/HwProj.SolutionsService/HwProj.SolutionsService.API/AutomapperProfile.cs +++ b/HwProj.SolutionsService/HwProj.SolutionsService.API/AutomapperProfile.cs @@ -1,13 +1,12 @@ using AutoMapper; using HwProj.Models.SolutionsService; -namespace HwProj.SolutionsService.API +namespace HwProj.SolutionsService.API; + +public class AutomapperProfile : Profile { - public class AutomapperProfile : Profile + public AutomapperProfile() { - public AutomapperProfile() - { - CreateMap().ReverseMap(); - } + CreateMap().ReverseMap(); } -} +} \ No newline at end of file diff --git a/HwProj.SolutionsService/HwProj.SolutionsService.API/Controllers/SolutionsController.cs b/HwProj.SolutionsService/HwProj.SolutionsService.API/Controllers/SolutionsController.cs index 1e12541f4..ded87eac6 100644 --- a/HwProj.SolutionsService/HwProj.SolutionsService.API/Controllers/SolutionsController.cs +++ b/HwProj.SolutionsService/HwProj.SolutionsService.API/Controllers/SolutionsController.cs @@ -12,175 +12,174 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; -namespace HwProj.SolutionsService.API.Controllers +namespace HwProj.SolutionsService.API.Controllers; + +[Route("api/[controller]")] +[ApiController] +public class SolutionsController : Controller { - [Route("api/[controller]")] - [ApiController] - public class SolutionsController : Controller + private readonly ISolutionsService _solutionsService; + private readonly ISolutionsRepository _solutionsRepository; + private readonly IMapper _mapper; + private readonly ICoursesServiceClient _coursesClient; + + public SolutionsController( + ISolutionsService solutionsService, + ISolutionsRepository solutionsRepository, + IMapper mapper, + ICoursesServiceClient coursesClient) { - private readonly ISolutionsService _solutionsService; - private readonly ISolutionsRepository _solutionsRepository; - private readonly IMapper _mapper; - private readonly ICoursesServiceClient _coursesClient; - - public SolutionsController( - ISolutionsService solutionsService, - ISolutionsRepository solutionsRepository, - IMapper mapper, - ICoursesServiceClient coursesClient) - { - _solutionsService = solutionsService; - _solutionsRepository = solutionsRepository; - _coursesClient = coursesClient; - _mapper = mapper; - } + _solutionsService = solutionsService; + _solutionsRepository = solutionsRepository; + _coursesClient = coursesClient; + _mapper = mapper; + } - [HttpGet] - public async Task GetAllSolutions() - { - return await _solutionsService.GetAllSolutionsAsync(); - } + [HttpGet] + public async Task GetAllSolutions() + { + return await _solutionsService.GetAllSolutionsAsync(); + } - [HttpGet("{solutionId}")] - public async Task GetSolution(long solutionId) - { - var solution = await _solutionsService.GetSolutionAsync(solutionId); - return solution == null - ? NotFound() - : Ok(solution) as IActionResult; - } + [HttpGet("{solutionId}")] + public async Task GetSolution(long solutionId) + { + var solution = await _solutionsService.GetSolutionAsync(solutionId); + return solution == null + ? NotFound() + : Ok(solution) as IActionResult; + } - [HttpGet("taskSolutions/{taskId}/{studentId}")] - public async Task GetTaskSolutionsFromStudent(long taskId, string studentId) - { - return await _solutionsService.GetTaskSolutionsFromStudentAsync(taskId, studentId); - } + [HttpGet("taskSolutions/{taskId}/{studentId}")] + public async Task GetTaskSolutionsFromStudent(long taskId, string studentId) + { + return await _solutionsService.GetTaskSolutionsFromStudentAsync(taskId, studentId); + } - [HttpPost("taskSolutions/{studentId}")] - public async Task GetLastTaskSolutions([FromBody] long[] taskIds, string studentId) + [HttpPost("taskSolutions/{studentId}")] + public async Task GetLastTaskSolutions([FromBody] long[] taskIds, string studentId) + { + return await _solutionsService.GetLastTaskSolutions(taskIds, studentId); + } + + [HttpPost("{taskId}")] + [ProducesResponseType(typeof(long), (int)HttpStatusCode.OK)] + public async Task PostSolution(long taskId, [FromBody] SolutionViewModel solutionViewModel) + { + var task = await _coursesClient.GetTask(taskId); + var homework = await _coursesClient.GetHomework(task.HomeworkId); + var course = await _coursesClient.GetCourseById(homework.CourseId, solutionViewModel.StudentId); + + if (course.CourseMates.Any(courseMate => + courseMate.StudentId == solutionViewModel.StudentId && courseMate.IsAccepted) && + task.CanSendSolution) { - return await _solutionsService.GetLastTaskSolutions(taskIds, studentId); + var solution = _mapper.Map(solutionViewModel); + solution.TaskId = taskId; + var solutionId = await _solutionsService.PostOrUpdateAsync(taskId, solution); + return Ok(solutionId); } - [HttpPost("{taskId}")] - [ProducesResponseType(typeof(long), (int)HttpStatusCode.OK)] - public async Task PostSolution(long taskId, [FromBody] SolutionViewModel solutionViewModel) - { - var task = await _coursesClient.GetTask(taskId); - var homework = await _coursesClient.GetHomework(task.HomeworkId); - var course = await _coursesClient.GetCourseById(homework.CourseId, solutionViewModel.StudentId); + return Forbid(); + } - if (course.CourseMates.Any(courseMate => - courseMate.StudentId == solutionViewModel.StudentId && courseMate.IsAccepted) && - task.CanSendSolution) - { - var solution = _mapper.Map(solutionViewModel); - solution.TaskId = taskId; - var solutionId = await _solutionsService.PostOrUpdateAsync(taskId, solution); - return Ok(solutionId); - } + [HttpPost("rateSolution/{solutionId}")] + public async Task RateSolution(long solutionId, [FromQuery] int newRating, + [FromQuery] string lecturerComment, [FromQuery] string lecturerId) + { + var solution = await _solutionsService.GetSolutionAsync(solutionId); + var task = await _coursesClient.GetTask(solution.TaskId); + var homework = await _coursesClient.GetHomework(task.HomeworkId); + var course = await _coursesClient.GetCourseById(homework.CourseId, ""); - return Forbid(); + if (course.MentorIds.Contains(lecturerId)) + { + await _solutionsService.RateSolutionAsync(solutionId, newRating, lecturerComment); + return Ok(); } - [HttpPost("rateSolution/{solutionId}")] - public async Task RateSolution(long solutionId, [FromQuery] int newRating, - [FromQuery] string lecturerComment, [FromQuery] string lecturerId) - { - var solution = await _solutionsService.GetSolutionAsync(solutionId); - var task = await _coursesClient.GetTask(solution.TaskId); - var homework = await _coursesClient.GetHomework(task.HomeworkId); - var course = await _coursesClient.GetCourseById(homework.CourseId, ""); + return Forbid(); + } - if (course.MentorIds.Contains(lecturerId)) - { - await _solutionsService.RateSolutionAsync(solutionId, newRating, lecturerComment); - return Ok(); - } + [HttpPost("markSolutionFinal/{solutionId}")] + public async Task MarkSolutionFinal(long solutionId) + { + await _solutionsService.MarkSolutionFinal(solutionId); + } - return Forbid(); - } + [HttpDelete("delete/{solutionId}")] + public async Task DeleteSolution(long solutionId) + { + await _solutionsService.DeleteSolutionAsync(solutionId); + } - [HttpPost("markSolutionFinal/{solutionId}")] - public async Task MarkSolutionFinal(long solutionId) - { - await _solutionsService.MarkSolutionFinal(solutionId); - } + [HttpPost("{groupId}/{taskId}")] + public async Task PostSolution(long groupId, long taskId, [FromBody] SolutionViewModel solutionViewModel) + { + var solution = _mapper.Map(solutionViewModel); + solution.GroupId = groupId; + var solutionId = await _solutionsService.PostOrUpdateAsync(taskId, solution); + return solutionId; + } - [HttpDelete("delete/{solutionId}")] - public async Task DeleteSolution(long solutionId) - { - await _solutionsService.DeleteSolutionAsync(solutionId); - } + [HttpGet("{groupId}/taskSolutions/{taskId}")] + public async Task GetTaskSolutionsFromGroup(long groupId, long taskId) + { + return await _solutionsService.GetTaskSolutionsFromGroupAsync(taskId, groupId); + } - [HttpPost("{groupId}/{taskId}")] - public async Task PostSolution(long groupId, long taskId, [FromBody] SolutionViewModel solutionViewModel) - { - var solution = _mapper.Map(solutionViewModel); - solution.GroupId = groupId; - var solutionId = await _solutionsService.PostOrUpdateAsync(taskId, solution); - return solutionId; - } + [HttpGet("getCourseStat/{courseId}")] + [ProducesResponseType(typeof(StatisticsCourseMatesDto[]), (int)HttpStatusCode.OK)] + public async Task GetCourseStat(long courseId, [FromQuery] string userId) + { + var course = await _coursesClient.GetCourseById(courseId, userId); + if (course == null) return NotFound(); - [HttpGet("{groupId}/taskSolutions/{taskId}")] - public async Task GetTaskSolutionsFromGroup(long groupId, long taskId) - { - return await _solutionsService.GetTaskSolutionsFromGroupAsync(taskId, groupId); - } + var taskIds = course.Homeworks + .SelectMany(t => t.Tasks) + .Select(t => t.Id) + .ToArray(); + + var solutions = await _solutionsRepository.FindAll(t => taskIds.Contains(t.TaskId)).ToListAsync(); + var courseMates = course.MentorIds.Contains(userId) + ? course.CourseMates.Where(t => t.IsAccepted) + : course.CourseMates.Where(t => t.StudentId == userId); - [HttpGet("getCourseStat/{courseId}")] - [ProducesResponseType(typeof(StatisticsCourseMatesDto[]), (int)HttpStatusCode.OK)] - public async Task GetCourseStat(long courseId, [FromQuery] string userId) + var solutionsStatsContext = new StatisticsAggregateModel { - var course = await _coursesClient.GetCourseById(courseId, userId); - if (course == null) return NotFound(); + CourseMates = courseMates, + Homeworks = course.Homeworks.Where(t => t.Tasks.Any()).ToList(), + Solutions = solutions + }; - var taskIds = course.Homeworks - .SelectMany(t => t.Tasks) - .Select(t => t.Id) - .ToArray(); + var result = SolutionsStatsDomain.GetCourseStatistics(solutionsStatsContext).ToArray(); - var solutions = await _solutionsRepository.FindAll(t => taskIds.Contains(t.TaskId)).ToListAsync(); - var courseMates = course.MentorIds.Contains(userId) - ? course.CourseMates.Where(t => t.IsAccepted) - : course.CourseMates.Where(t => t.StudentId == userId); + return Ok(result); + } - var solutionsStatsContext = new StatisticsAggregateModel + [HttpPost("allUnrated")] + public async Task GetAllUnratedSolutionsForTasks([FromBody] long[] taskIds) + { + var solutions = await _solutionsRepository + .FindAll(t => taskIds.Contains(t.TaskId)) + .GroupBy(t => new { t.TaskId, t.StudentId }) + .Select(t => t.OrderByDescending(x => x.PublicationDate)) + .Select(t => new { - CourseMates = courseMates, - Homeworks = course.Homeworks.Where(t => t.Tasks.Any()).ToList(), - Solutions = solutions - }; - - var result = SolutionsStatsDomain.GetCourseStatistics(solutionsStatsContext).ToArray(); - - return Ok(result); - } - - [HttpPost("allUnrated")] - public async Task GetAllUnratedSolutionsForTasks([FromBody] long[] taskIds) - { - var solutions = await _solutionsRepository - .FindAll(t => taskIds.Contains(t.TaskId)) - .GroupBy(t => new { t.TaskId, t.StudentId }) - .Select(t => t.OrderByDescending(x => x.PublicationDate)) - .Select(t => new - { - LastSolution = t.FirstOrDefault(), - IsFirstTry = t.Skip(1).All(s => s.State == SolutionState.Posted) - }) - .Where(t => t.LastSolution != null && t.LastSolution.State == SolutionState.Posted) - .OrderBy(t => t.LastSolution!.PublicationDate) - .Select(t => new SolutionPreviewDto - { - StudentId = t.LastSolution!.StudentId, - TaskId = t.LastSolution.TaskId, - PublicationDate = t.LastSolution.PublicationDate, - IsFirstTry = t.IsFirstTry - }) - .ToArrayAsync(); - - return solutions; - } + LastSolution = t.FirstOrDefault(), + IsFirstTry = t.Skip(1).All(s => s.State == SolutionState.Posted) + }) + .Where(t => t.LastSolution != null && t.LastSolution.State == SolutionState.Posted) + .OrderBy(t => t.LastSolution!.PublicationDate) + .Select(t => new SolutionPreviewDto + { + StudentId = t.LastSolution!.StudentId, + TaskId = t.LastSolution.TaskId, + PublicationDate = t.LastSolution.PublicationDate, + IsFirstTry = t.IsFirstTry + }) + .ToArrayAsync(); + + return solutions; } -} +} \ No newline at end of file diff --git a/HwProj.SolutionsService/HwProj.SolutionsService.API/Controllers/SystemController.cs b/HwProj.SolutionsService/HwProj.SolutionsService.API/Controllers/SystemController.cs index 564d1b209..2ea1745fb 100644 --- a/HwProj.SolutionsService/HwProj.SolutionsService.API/Controllers/SystemController.cs +++ b/HwProj.SolutionsService/HwProj.SolutionsService.API/Controllers/SystemController.cs @@ -1,12 +1,11 @@ using Microsoft.AspNetCore.Mvc; -namespace HwProj.SolutionsService.API.Controllers +namespace HwProj.SolutionsService.API.Controllers; + +[Route("api/[controller]")] +[ApiController] +public class SystemController : ControllerBase { - [Route("api/[controller]")] - [ApiController] - public class SystemController : ControllerBase - { - [HttpGet("status")] - public IActionResult Status() => Ok(); - } -} + [HttpGet("status")] + public IActionResult Status() => Ok(); +} \ No newline at end of file diff --git a/HwProj.SolutionsService/HwProj.SolutionsService.API/Domains/SolutionsStatsDomain.cs b/HwProj.SolutionsService/HwProj.SolutionsService.API/Domains/SolutionsStatsDomain.cs index 40232df45..a42554c39 100644 --- a/HwProj.SolutionsService/HwProj.SolutionsService.API/Domains/SolutionsStatsDomain.cs +++ b/HwProj.SolutionsService/HwProj.SolutionsService.API/Domains/SolutionsStatsDomain.cs @@ -3,36 +3,35 @@ using HwProj.Models.StatisticsService; using HwProj.SolutionsService.API.Models; -namespace HwProj.SolutionsService.API.Domains +namespace HwProj.SolutionsService.API.Domains; + +public static class SolutionsStatsDomain { - public static class SolutionsStatsDomain - { - //TODO: rewrite - public static StatisticsCourseMatesDto[] GetCourseStatistics(StatisticsAggregateModel model) => - model.CourseMates - .Where(t => t.IsAccepted) - .Select(m => new StatisticsCourseMatesDto - { - StudentId = m.StudentId, - Homeworks = new List(model.Homeworks.Select(h => - new StatisticsCourseHomeworksModel + //TODO: rewrite + public static StatisticsCourseMatesDto[] GetCourseStatistics(StatisticsAggregateModel model) => + model.CourseMates + .Where(t => t.IsAccepted) + .Select(m => new StatisticsCourseMatesDto + { + StudentId = m.StudentId, + Homeworks = new List(model.Homeworks.Select(h => + new StatisticsCourseHomeworksModel + { + Id = h.Id, + Tasks = new List(h.Tasks.Select(t => { - Id = h.Id, - Tasks = new List(h.Tasks.Select(t => + var solutions = + model.Solutions.Where(s => s.TaskId == t.Id && s.StudentId == m.StudentId) + .OrderBy(s => s.PublicationDate); + var solutionsInRightModel = + new List(solutions.Select(s => + new StatisticsCourseSolutionsModel(s))); + return new StatisticsCourseTasksModel { - var solutions = - model.Solutions.Where(s => s.TaskId == t.Id && s.StudentId == m.StudentId) - .OrderBy(s => s.PublicationDate); - var solutionsInRightModel = - new List(solutions.Select(s => - new StatisticsCourseSolutionsModel(s))); - return new StatisticsCourseTasksModel - { - Id = t.Id, - Solution = solutionsInRightModel - }; - })) + Id = t.Id, + Solution = solutionsInRightModel + }; })) - }).ToArray(); - } -} + })) + }).ToArray(); +} \ No newline at end of file diff --git a/HwProj.SolutionsService/HwProj.SolutionsService.API/Events/RateEvent.cs b/HwProj.SolutionsService/HwProj.SolutionsService.API/Events/RateEvent.cs index 9a1d88091..cecc72814 100644 --- a/HwProj.SolutionsService/HwProj.SolutionsService.API/Events/RateEvent.cs +++ b/HwProj.SolutionsService/HwProj.SolutionsService.API/Events/RateEvent.cs @@ -2,17 +2,16 @@ using HwProj.Models.CoursesService.ViewModels; using HwProj.Models.SolutionsService; -namespace HwProj.SolutionsService.API.Events +namespace HwProj.SolutionsService.API.Events; + +public class RateEvent : Event { - public class RateEvent : Event - { - public HomeworkTaskViewModel Task { get; set; } - public SolutionViewModel Solution { get; set; } + public HomeworkTaskViewModel Task { get; set; } + public SolutionViewModel Solution { get; set; } - public RateEvent(HomeworkTaskViewModel task, SolutionViewModel solution) - { - Task = task; - Solution = solution; - } + public RateEvent(HomeworkTaskViewModel task, SolutionViewModel solution) + { + Task = task; + Solution = solution; } -} +} \ No newline at end of file diff --git a/HwProj.SolutionsService/HwProj.SolutionsService.API/Events/StudentPassTaskEvent.cs b/HwProj.SolutionsService/HwProj.SolutionsService.API/Events/StudentPassTaskEvent.cs index e9798b28d..626090563 100644 --- a/HwProj.SolutionsService/HwProj.SolutionsService.API/Events/StudentPassTaskEvent.cs +++ b/HwProj.SolutionsService/HwProj.SolutionsService.API/Events/StudentPassTaskEvent.cs @@ -3,21 +3,20 @@ using HwProj.Models.CoursesService.ViewModels; using HwProj.Models.SolutionsService; -namespace HwProj.SolutionsService.API.Events +namespace HwProj.SolutionsService.API.Events; + +public class StudentPassTaskEvent : Event { - public class StudentPassTaskEvent : Event - { - public CourseDTO Course { get; set; } - public SolutionViewModel Solution { get; set; } - public AccountDataDto Student { get; set; } - public HomeworkTaskViewModel Task { get; set; } + public CourseDTO Course { get; set; } + public SolutionViewModel Solution { get; set; } + public AccountDataDto Student { get; set; } + public HomeworkTaskViewModel Task { get; set; } - public StudentPassTaskEvent(CourseDTO course, SolutionViewModel solution, AccountDataDto student, HomeworkTaskViewModel task) - { - Course = course; - Solution = solution; - Student= student; - Task = task; - } + public StudentPassTaskEvent(CourseDTO course, SolutionViewModel solution, AccountDataDto student, HomeworkTaskViewModel task) + { + Course = course; + Solution = solution; + Student= student; + Task = task; } -} +} \ No newline at end of file diff --git a/HwProj.SolutionsService/HwProj.SolutionsService.API/HwProj.SolutionsService.API.csproj b/HwProj.SolutionsService/HwProj.SolutionsService.API/HwProj.SolutionsService.API.csproj index 694e78ba7..e16672c90 100644 --- a/HwProj.SolutionsService/HwProj.SolutionsService.API/HwProj.SolutionsService.API.csproj +++ b/HwProj.SolutionsService/HwProj.SolutionsService.API/HwProj.SolutionsService.API.csproj @@ -1,6 +1,6 @@  - netcoreapp2.2 + net6.0 Linux ..\..\docker-compose.dcproj ..\.. @@ -18,12 +18,9 @@ - + - - - - + @@ -32,4 +29,4 @@ - \ No newline at end of file + diff --git a/HwProj.SolutionsService/HwProj.SolutionsService.API/Models/SolutionsContext.cs b/HwProj.SolutionsService/HwProj.SolutionsService.API/Models/SolutionsContext.cs index cddb534d3..5224e7769 100644 --- a/HwProj.SolutionsService/HwProj.SolutionsService.API/Models/SolutionsContext.cs +++ b/HwProj.SolutionsService/HwProj.SolutionsService.API/Models/SolutionsContext.cs @@ -1,16 +1,15 @@ using HwProj.Models.SolutionsService; using Microsoft.EntityFrameworkCore; -namespace HwProj.SolutionsService.API.Models +namespace HwProj.SolutionsService.API.Models; + +public sealed class SolutionContext : DbContext { - public sealed class SolutionContext : DbContext - { - public DbSet Solutions { get; set; } + public DbSet Solutions { get; set; } - public SolutionContext(DbContextOptions options) - : base(options) - { - Database.EnsureCreated(); - } + public SolutionContext(DbContextOptions options) + : base(options) + { + Database.EnsureCreated(); } -} +} \ No newline at end of file diff --git a/HwProj.SolutionsService/HwProj.SolutionsService.API/Models/StatisticsAggregateModel.cs b/HwProj.SolutionsService/HwProj.SolutionsService.API/Models/StatisticsAggregateModel.cs index 7a24365d3..499ae68c3 100644 --- a/HwProj.SolutionsService/HwProj.SolutionsService.API/Models/StatisticsAggregateModel.cs +++ b/HwProj.SolutionsService/HwProj.SolutionsService.API/Models/StatisticsAggregateModel.cs @@ -2,12 +2,11 @@ using HwProj.Models.CoursesService.ViewModels; using HwProj.Models.SolutionsService; -namespace HwProj.SolutionsService.API.Models +namespace HwProj.SolutionsService.API.Models; + +public class StatisticsAggregateModel { - public class StatisticsAggregateModel - { - public IEnumerable CourseMates { get; set; } - public List Homeworks { get; set; } - public List Solutions { get; set; } - } -} + public IEnumerable CourseMates { get; set; } + public List Homeworks { get; set; } + public List Solutions { get; set; } +} \ No newline at end of file diff --git a/HwProj.SolutionsService/HwProj.SolutionsService.API/Program.cs b/HwProj.SolutionsService/HwProj.SolutionsService.API/Program.cs index 264172f93..955db1325 100644 --- a/HwProj.SolutionsService/HwProj.SolutionsService.API/Program.cs +++ b/HwProj.SolutionsService/HwProj.SolutionsService.API/Program.cs @@ -1,17 +1,16 @@ using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; -namespace HwProj.SolutionsService.API +namespace HwProj.SolutionsService.API; + +public class Program { - public class Program + public static void Main(string[] args) { - public static void Main(string[] args) - { - CreateWebHostBuilder(args).Build().Run(); - } - - public static IWebHostBuilder CreateWebHostBuilder(string[] args) => - WebHost.CreateDefaultBuilder(args) - .UseStartup(); + CreateWebHostBuilder(args).Build().Run(); } -} + + public static IWebHostBuilder CreateWebHostBuilder(string[] args) => + WebHost.CreateDefaultBuilder(args) + .UseStartup(); +} \ No newline at end of file diff --git a/HwProj.SolutionsService/HwProj.SolutionsService.API/Repositories/ISolutionsRepository.cs b/HwProj.SolutionsService/HwProj.SolutionsService.API/Repositories/ISolutionsRepository.cs index 46fd9bb8e..577f9d44e 100644 --- a/HwProj.SolutionsService/HwProj.SolutionsService.API/Repositories/ISolutionsRepository.cs +++ b/HwProj.SolutionsService/HwProj.SolutionsService.API/Repositories/ISolutionsRepository.cs @@ -2,14 +2,13 @@ using HwProj.Models.SolutionsService; using HwProj.Repositories; -namespace HwProj.SolutionsService.API.Repositories +namespace HwProj.SolutionsService.API.Repositories; + +public interface ISolutionsRepository : ICrudRepository { - public interface ISolutionsRepository : ICrudRepository - { - Task RateSolutionAsync(long solutionId, SolutionState newState, int newRating, string lecturerComment); + Task RateSolutionAsync(long solutionId, SolutionState newState, int newRating, string lecturerComment); - Task ChangeTaskSolutionsMaxRatingAsync(long solutionId, int newMaxRating); + Task ChangeTaskSolutionsMaxRatingAsync(long solutionId, int newMaxRating); - Task UpdateSolutionState(long solutionId, SolutionState newState); - } -} + Task UpdateSolutionState(long solutionId, SolutionState newState); +} \ No newline at end of file diff --git a/HwProj.SolutionsService/HwProj.SolutionsService.API/Repositories/SolutionsRepository.cs b/HwProj.SolutionsService/HwProj.SolutionsService.API/Repositories/SolutionsRepository.cs index 070e301ba..f9e542ac0 100644 --- a/HwProj.SolutionsService/HwProj.SolutionsService.API/Repositories/SolutionsRepository.cs +++ b/HwProj.SolutionsService/HwProj.SolutionsService.API/Repositories/SolutionsRepository.cs @@ -5,59 +5,58 @@ using HwProj.SolutionsService.API.Models; using Microsoft.EntityFrameworkCore; -namespace HwProj.SolutionsService.API.Repositories +namespace HwProj.SolutionsService.API.Repositories; + +public class SolutionsRepository : CrudRepository, ISolutionsRepository { - public class SolutionsRepository : CrudRepository, ISolutionsRepository - { - public SolutionsRepository(SolutionContext context) - : base(context) - { - } + public SolutionsRepository(SolutionContext context) + : base(context) + { + } - public async Task RateSolutionAsync(long solutionId, SolutionState newState, int newRating, string lecturerComment) + public async Task RateSolutionAsync(long solutionId, SolutionState newState, int newRating, string lecturerComment) + { + await UpdateAsync(solutionId, solution => new Solution { - await UpdateAsync(solutionId, solution => new Solution - { - State = newState, - Rating = newRating, - LecturerComment = lecturerComment - }); - } + State = newState, + Rating = newRating, + LecturerComment = lecturerComment + }); + } - public async Task ChangeTaskSolutionsMaxRatingAsync(long taskId, int newMaxRating) - { - var solutions = await Context.Set().Where(solution => solution.TaskId == taskId) - .ToArrayAsync() - .ConfigureAwait(false); - - foreach (var solution in solutions) - { - if (solution.Rating == newMaxRating) - solution.State = SolutionState.Final; - else if (solution.State != SolutionState.Posted && solution.Rating < newMaxRating) - solution.State = SolutionState.Rated; - } - - await Context.SaveChangesAsync().ConfigureAwait(false); - } + public async Task ChangeTaskSolutionsMaxRatingAsync(long taskId, int newMaxRating) + { + var solutions = await Context.Set().Where(solution => solution.TaskId == taskId) + .ToArrayAsync() + .ConfigureAwait(false); - public async Task ChangeSolutionMaxRatingAsync(long solutionId, int newMaxRating) - { - var solution = await GetAsync(solutionId); - //solution.MaxRating = newMaxRating; - + foreach (var solution in solutions) + { if (solution.Rating == newMaxRating) solution.State = SolutionState.Final; - else if (solution.State == SolutionState.Posted && solution.Rating < newMaxRating) + else if (solution.State != SolutionState.Posted && solution.Rating < newMaxRating) solution.State = SolutionState.Rated; - - await Context.SaveChangesAsync().ConfigureAwait(false); } + + await Context.SaveChangesAsync().ConfigureAwait(false); + } + + public async Task ChangeSolutionMaxRatingAsync(long solutionId, int newMaxRating) + { + var solution = await GetAsync(solutionId); + //solution.MaxRating = newMaxRating; + + if (solution.Rating == newMaxRating) + solution.State = SolutionState.Final; + else if (solution.State == SolutionState.Posted && solution.Rating < newMaxRating) + solution.State = SolutionState.Rated; + + await Context.SaveChangesAsync().ConfigureAwait(false); + } - public async Task UpdateSolutionState(long solutionId, SolutionState newState) - { - await UpdateAsync(solutionId, solution => new Solution {State = newState}).ConfigureAwait(false); - } + public async Task UpdateSolutionState(long solutionId, SolutionState newState) + { + await UpdateAsync(solutionId, solution => new Solution {State = newState}).ConfigureAwait(false); } -} +} \ No newline at end of file diff --git a/HwProj.SolutionsService/HwProj.SolutionsService.API/Services/ISolutionsService.cs b/HwProj.SolutionsService/HwProj.SolutionsService.API/Services/ISolutionsService.cs index b4efc55f7..1d4269207 100644 --- a/HwProj.SolutionsService/HwProj.SolutionsService.API/Services/ISolutionsService.cs +++ b/HwProj.SolutionsService/HwProj.SolutionsService.API/Services/ISolutionsService.cs @@ -1,25 +1,24 @@ using System.Threading.Tasks; using HwProj.Models.SolutionsService; -namespace HwProj.SolutionsService.API.Services +namespace HwProj.SolutionsService.API.Services; + +public interface ISolutionsService { - public interface ISolutionsService - { - Task GetAllSolutionsAsync(); + Task GetAllSolutionsAsync(); - Task GetSolutionAsync(long solutionId); + Task GetSolutionAsync(long solutionId); - Task GetTaskSolutionsFromStudentAsync(long taskId, string studentId); - Task GetLastTaskSolutions(long[] taskIds, string studentId); + Task GetTaskSolutionsFromStudentAsync(long taskId, string studentId); + Task GetLastTaskSolutions(long[] taskIds, string studentId); - Task GetTaskSolutionsFromGroupAsync(long taskId, long groupId); + Task GetTaskSolutionsFromGroupAsync(long taskId, long groupId); - Task PostOrUpdateAsync(long taskId, Solution solution); + Task PostOrUpdateAsync(long taskId, Solution solution); - Task RateSolutionAsync(long solutionId, int newRating, string lecturerComment); + Task RateSolutionAsync(long solutionId, int newRating, string lecturerComment); - Task DeleteSolutionAsync(long solutionId); + Task DeleteSolutionAsync(long solutionId); - Task MarkSolutionFinal(long solutionId); - } -} + Task MarkSolutionFinal(long solutionId); +} \ No newline at end of file diff --git a/HwProj.SolutionsService/HwProj.SolutionsService.API/Services/SolutionsService.cs b/HwProj.SolutionsService/HwProj.SolutionsService.API/Services/SolutionsService.cs index 79472cfaf..503b348e3 100644 --- a/HwProj.SolutionsService/HwProj.SolutionsService.API/Services/SolutionsService.cs +++ b/HwProj.SolutionsService/HwProj.SolutionsService.API/Services/SolutionsService.cs @@ -13,115 +13,114 @@ using Microsoft.EntityFrameworkCore; -namespace HwProj.SolutionsService.API.Services +namespace HwProj.SolutionsService.API.Services; + +public class SolutionsService : ISolutionsService { - public class SolutionsService : ISolutionsService + private readonly ISolutionsRepository _solutionsRepository; + private readonly IEventBus _eventBus; + private readonly IMapper _mapper; + private readonly ICoursesServiceClient _coursesServiceClient; + private readonly IAuthServiceClient _authServiceClient; + + public SolutionsService(ISolutionsRepository solutionsRepository, IEventBus eventBus, IMapper mapper, + ICoursesServiceClient coursesServiceClient, IAuthServiceClient authServiceClient) { - private readonly ISolutionsRepository _solutionsRepository; - private readonly IEventBus _eventBus; - private readonly IMapper _mapper; - private readonly ICoursesServiceClient _coursesServiceClient; - private readonly IAuthServiceClient _authServiceClient; - - public SolutionsService(ISolutionsRepository solutionsRepository, IEventBus eventBus, IMapper mapper, - ICoursesServiceClient coursesServiceClient, IAuthServiceClient authServiceClient) - { - _solutionsRepository = solutionsRepository; - _eventBus = eventBus; - _mapper = mapper; - _coursesServiceClient = coursesServiceClient; - _authServiceClient = authServiceClient; - } + _solutionsRepository = solutionsRepository; + _eventBus = eventBus; + _mapper = mapper; + _coursesServiceClient = coursesServiceClient; + _authServiceClient = authServiceClient; + } - public async Task GetAllSolutionsAsync() - { - return await _solutionsRepository.GetAll().ToArrayAsync(); - } + public async Task GetAllSolutionsAsync() + { + return await _solutionsRepository.GetAll().ToArrayAsync(); + } - public Task GetSolutionAsync(long solutionId) - { - return _solutionsRepository.GetAsync(solutionId); - } + public Task GetSolutionAsync(long solutionId) + { + return _solutionsRepository.GetAsync(solutionId); + } - public async Task GetTaskSolutionsFromStudentAsync(long taskId, string studentId) - { - return await _solutionsRepository - .FindAll(solution => solution.TaskId == taskId && solution.StudentId == studentId) - .OrderBy(t => t.PublicationDate) - .ToArrayAsync(); - } + public async Task GetTaskSolutionsFromStudentAsync(long taskId, string studentId) + { + return await _solutionsRepository + .FindAll(solution => solution.TaskId == taskId && solution.StudentId == studentId) + .OrderBy(t => t.PublicationDate) + .ToArrayAsync(); + } - public async Task GetLastTaskSolutions(long[] taskIds, string studentId) - { - var solutions = await _solutionsRepository - .FindAll(s => s.StudentId == studentId && taskIds.Contains(s.TaskId)) - .GroupBy(t => t.TaskId) - .Select(t => t.OrderByDescending(s => s.PublicationDate).FirstOrDefault()) - .ToArrayAsync(); + public async Task GetLastTaskSolutions(long[] taskIds, string studentId) + { + var solutions = await _solutionsRepository + .FindAll(s => s.StudentId == studentId && taskIds.Contains(s.TaskId)) + .GroupBy(t => t.TaskId) + .Select(t => t.OrderByDescending(s => s.PublicationDate).FirstOrDefault()) + .ToArrayAsync(); - return taskIds.Select(t => solutions.FirstOrDefault(s => s?.TaskId == t)).ToArray(); - } + return taskIds.Select(t => solutions.FirstOrDefault(s => s?.TaskId == t)).ToArray(); + } - public async Task PostOrUpdateAsync(long taskId, Solution solution) + public async Task PostOrUpdateAsync(long taskId, Solution solution) + { + solution.PublicationDate = DateTimeUtils.GetMoscowNow(); + var allSolutionsForTask = await GetTaskSolutionsFromStudentAsync(taskId, solution.StudentId); + var currentSolution = allSolutionsForTask.FirstOrDefault(s => s.Id == solution.Id); + var solutionModel = _mapper.Map(solution); + var task = await _coursesServiceClient.GetTask(solution.TaskId); + var taskModel = _mapper.Map(task); + var homework = await _coursesServiceClient.GetHomework(task.HomeworkId); + var courses = await _coursesServiceClient.GetCourseById(homework.CourseId, solution.StudentId); + var student = await _authServiceClient.GetAccountData((solutionModel.StudentId)); + var studentModel = _mapper.Map(student); + _eventBus.Publish(new StudentPassTaskEvent(courses, solutionModel, studentModel, taskModel)); + + if (currentSolution == null) { - solution.PublicationDate = DateTimeUtils.GetMoscowNow(); - var allSolutionsForTask = await GetTaskSolutionsFromStudentAsync(taskId, solution.StudentId); - var currentSolution = allSolutionsForTask.FirstOrDefault(s => s.Id == solution.Id); - var solutionModel = _mapper.Map(solution); - var task = await _coursesServiceClient.GetTask(solution.TaskId); - var taskModel = _mapper.Map(task); - var homework = await _coursesServiceClient.GetHomework(task.HomeworkId); - var courses = await _coursesServiceClient.GetCourseById(homework.CourseId, solution.StudentId); - var student = await _authServiceClient.GetAccountData((solutionModel.StudentId)); - var studentModel = _mapper.Map(student); - _eventBus.Publish(new StudentPassTaskEvent(courses, solutionModel, studentModel, taskModel)); + solution.TaskId = taskId; + var id = await _solutionsRepository.AddAsync(solution); + return id; + } - if (currentSolution == null) + await _solutionsRepository.UpdateAsync(currentSolution.Id, s => new Solution() { - solution.TaskId = taskId; - var id = await _solutionsRepository.AddAsync(solution); - return id; + State = SolutionState.Rated, + Comment = solution.Comment, + GithubUrl = solution.GithubUrl, + PublicationDate = solution.PublicationDate, } + ); - await _solutionsRepository.UpdateAsync(currentSolution.Id, s => new Solution() - { - State = SolutionState.Rated, - Comment = solution.Comment, - GithubUrl = solution.GithubUrl, - PublicationDate = solution.PublicationDate, - } - ); - - return solution.Id; - } + return solution.Id; + } - public async Task RateSolutionAsync(long solutionId, int newRating, string lecturerComment) + public async Task RateSolutionAsync(long solutionId, int newRating, string lecturerComment) + { + var solution = await _solutionsRepository.GetAsync(solutionId); + var task = await _coursesServiceClient.GetTask(solution.TaskId); + if (0 <= newRating && newRating <= task.MaxRating) { - var solution = await _solutionsRepository.GetAsync(solutionId); - var task = await _coursesServiceClient.GetTask(solution.TaskId); - if (0 <= newRating && newRating <= task.MaxRating) - { - var solutionModel = _mapper.Map(solution); - var taskModel = _mapper.Map(task); - _eventBus.Publish(new RateEvent(taskModel, solutionModel)); - var state = newRating >= task.MaxRating ? SolutionState.Final : SolutionState.Rated; - await _solutionsRepository.RateSolutionAsync(solutionId, state, newRating, lecturerComment); - } + var solutionModel = _mapper.Map(solution); + var taskModel = _mapper.Map(task); + _eventBus.Publish(new RateEvent(taskModel, solutionModel)); + var state = newRating >= task.MaxRating ? SolutionState.Final : SolutionState.Rated; + await _solutionsRepository.RateSolutionAsync(solutionId, state, newRating, lecturerComment); } + } - public Task DeleteSolutionAsync(long solutionId) - { - return _solutionsRepository.DeleteAsync(solutionId); - } + public Task DeleteSolutionAsync(long solutionId) + { + return _solutionsRepository.DeleteAsync(solutionId); + } - public async Task MarkSolutionFinal(long solutionId) - { - await _solutionsRepository.UpdateSolutionState(solutionId, SolutionState.Final); - } + public async Task MarkSolutionFinal(long solutionId) + { + await _solutionsRepository.UpdateSolutionState(solutionId, SolutionState.Final); + } - public Task GetTaskSolutionsFromGroupAsync(long taskId, long groupId) - { - return _solutionsRepository.FindAll(cm => cm.GroupId == groupId).ToArrayAsync(); - } + public Task GetTaskSolutionsFromGroupAsync(long taskId, long groupId) + { + return _solutionsRepository.FindAll(cm => cm.GroupId == groupId).ToArrayAsync(); } -} +} \ No newline at end of file diff --git a/HwProj.SolutionsService/HwProj.SolutionsService.API/Startup.cs b/HwProj.SolutionsService/HwProj.SolutionsService.API/Startup.cs index abd8597a3..5f96991c0 100644 --- a/HwProj.SolutionsService/HwProj.SolutionsService.API/Startup.cs +++ b/HwProj.SolutionsService/HwProj.SolutionsService.API/Startup.cs @@ -11,36 +11,35 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; -namespace HwProj.SolutionsService.API +namespace HwProj.SolutionsService.API; + +public class Startup { - public class Startup + public Startup(IConfiguration configuration) { - public Startup(IConfiguration configuration) - { - Configuration = configuration; - } + Configuration = configuration; + } - public IConfiguration Configuration { get; } + public IConfiguration Configuration { get; } - public void ConfigureServices(IServiceCollection services) - { - var connectionString = ConnectionString.GetConnectionString(Configuration); - services.AddDbContext(options => options.UseSqlServer(connectionString)); - services.AddScoped(); - services.AddScoped(); + public void ConfigureServices(IServiceCollection services) + { + var connectionString = ConnectionString.GetConnectionString(Configuration); + services.AddDbContext(options => options.UseSqlServer(connectionString)); + services.AddScoped(); + services.AddScoped(); - services.AddHttpClient(); - services.AddHttpContextAccessor(); - services.AddAuthServiceClient(); - services.AddCoursesServiceClient(); + services.AddHttpClient(); + services.AddHttpContextAccessor(); + services.AddAuthServiceClient(); + services.AddCoursesServiceClient(); - services.AddEventBus(Configuration); - services.ConfigureHwProjServices("Solutions API"); - } + services.AddEventBus(Configuration); + services.ConfigureHwProjServices("Solutions API"); + } - public void Configure(IApplicationBuilder app, IHostingEnvironment env, IEventBus eventBus) - { - app.ConfigureHwProj(env, "Solutions API"); - } + public void Configure(IApplicationBuilder app, IHostingEnvironment env, IEventBus eventBus) + { + app.ConfigureHwProj(env, "Solutions API"); } -} +} \ No newline at end of file diff --git a/HwProj.SolutionsService/HwProj.SolutionsService.Client/ConfigurationExtensions.cs b/HwProj.SolutionsService/HwProj.SolutionsService.Client/ConfigurationExtensions.cs index 20a94c7fc..e6b6cae17 100644 --- a/HwProj.SolutionsService/HwProj.SolutionsService.Client/ConfigurationExtensions.cs +++ b/HwProj.SolutionsService/HwProj.SolutionsService.Client/ConfigurationExtensions.cs @@ -1,13 +1,12 @@ using Microsoft.Extensions.DependencyInjection; -namespace HwProj.SolutionsService.Client +namespace HwProj.SolutionsService.Client; + +public static class ConfigurationExtensions { - public static class ConfigurationExtensions + public static IServiceCollection AddSolutionServiceClient(this IServiceCollection services) { - public static IServiceCollection AddSolutionServiceClient(this IServiceCollection services) - { - services.AddScoped(); - return services; - } + services.AddScoped(); + return services; } -} +} \ No newline at end of file diff --git a/HwProj.SolutionsService/HwProj.SolutionsService.Client/HwProj.SolutionsService.Client.csproj b/HwProj.SolutionsService/HwProj.SolutionsService.Client/HwProj.SolutionsService.Client.csproj index 59b572990..da3d1d710 100644 --- a/HwProj.SolutionsService/HwProj.SolutionsService.Client/HwProj.SolutionsService.Client.csproj +++ b/HwProj.SolutionsService/HwProj.SolutionsService.Client/HwProj.SolutionsService.Client.csproj @@ -2,7 +2,7 @@ Library - netcoreapp2.2 + net6.0 $(CSharpLanguageVersion) @@ -11,8 +11,8 @@ - - + + diff --git a/HwProj.SolutionsService/HwProj.SolutionsService.Client/ISolutionsServiceClient.cs b/HwProj.SolutionsService/HwProj.SolutionsService.Client/ISolutionsServiceClient.cs index 8bd833d63..bfc7e7e71 100644 --- a/HwProj.SolutionsService/HwProj.SolutionsService.Client/ISolutionsServiceClient.cs +++ b/HwProj.SolutionsService/HwProj.SolutionsService.Client/ISolutionsServiceClient.cs @@ -2,22 +2,21 @@ using HwProj.Models.SolutionsService; using HwProj.Models.StatisticsService; -namespace HwProj.SolutionsService.Client -{ - public interface ISolutionsServiceClient - { - Task GetAllSolutions(); - Task GetSolutionById(long solutionId); - Task GetUserSolutions(long taskId, string studentId); - Task PostSolution(SolutionViewModel model, long taskId); - Task RateSolution(long solutionId, int newRating, string lecturerComment, string lecturerId); - Task MarkSolution(long solutionId); - Task DeleteSolution(long solutionId); - Task PostGroupSolution(SolutionViewModel model, long taskId, long groupId); - Task GetTaskSolutions(long groupId, long taskId); - Task GetCourseStatistics(long courseId, string userId); - Task GetLastTaskSolutions(long[] taskIds, string userId); - Task GetAllUnratedSolutionsForTasks(long[] taskIds); - Task Ping(); - } -} +namespace HwProj.SolutionsService.Client; + +public interface ISolutionsServiceClient +{ + Task GetAllSolutions(); + Task GetSolutionById(long solutionId); + Task GetUserSolutions(long taskId, string studentId); + Task PostSolution(SolutionViewModel model, long taskId); + Task RateSolution(long solutionId, int newRating, string lecturerComment, string lecturerId); + Task MarkSolution(long solutionId); + Task DeleteSolution(long solutionId); + Task PostGroupSolution(SolutionViewModel model, long taskId, long groupId); + Task GetTaskSolutions(long groupId, long taskId); + Task GetCourseStatistics(long courseId, string userId); + Task GetLastTaskSolutions(long[] taskIds, string userId); + Task GetAllUnratedSolutionsForTasks(long[] taskIds); + Task Ping(); +} \ No newline at end of file diff --git a/HwProj.SolutionsService/HwProj.SolutionsService.Client/SolutionsServiceClient.cs b/HwProj.SolutionsService/HwProj.SolutionsService.Client/SolutionsServiceClient.cs index a8d0100bb..415c922bf 100644 --- a/HwProj.SolutionsService/HwProj.SolutionsService.Client/SolutionsServiceClient.cs +++ b/HwProj.SolutionsService/HwProj.SolutionsService.Client/SolutionsServiceClient.cs @@ -9,181 +9,180 @@ using Microsoft.Extensions.Configuration; using Newtonsoft.Json; -namespace HwProj.SolutionsService.Client +namespace HwProj.SolutionsService.Client; + +public class SolutionsServiceClient : ISolutionsServiceClient { - public class SolutionsServiceClient : ISolutionsServiceClient + private readonly HttpClient _httpClient; + private readonly Uri _solutionServiceUri; + + public SolutionsServiceClient(IHttpClientFactory clientFactory, IConfiguration configuration) { - private readonly HttpClient _httpClient; - private readonly Uri _solutionServiceUri; + _httpClient = clientFactory.CreateClient(); + _solutionServiceUri = new Uri(configuration.GetSection("Services")["Solutions"]); + } - public SolutionsServiceClient(IHttpClientFactory clientFactory, IConfiguration configuration) - { - _httpClient = clientFactory.CreateClient(); - _solutionServiceUri = new Uri(configuration.GetSection("Services")["Solutions"]); - } + public async Task GetAllSolutions() + { + using var httpRequest = new HttpRequestMessage( + HttpMethod.Get, + _solutionServiceUri + "api/Solutions"); - public async Task GetAllSolutions() - { - using var httpRequest = new HttpRequestMessage( - HttpMethod.Get, - _solutionServiceUri + "api/Solutions"); + var response = await _httpClient.SendAsync(httpRequest); + return await response.DeserializeAsync(); + } - var response = await _httpClient.SendAsync(httpRequest); - return await response.DeserializeAsync(); - } + public async Task GetSolutionById(long solutionId) + { + using var httpRequest = new HttpRequestMessage( + HttpMethod.Get, + _solutionServiceUri + $"api/Solutions/{solutionId}"); - public async Task GetSolutionById(long solutionId) - { - using var httpRequest = new HttpRequestMessage( - HttpMethod.Get, - _solutionServiceUri + $"api/Solutions/{solutionId}"); + var response = await _httpClient.SendAsync(httpRequest); + return await response.DeserializeAsync(); + } - var response = await _httpClient.SendAsync(httpRequest); - return await response.DeserializeAsync(); - } + public async Task GetUserSolutions(long taskId, string studentId) + { + using var httpRequest = new HttpRequestMessage( + HttpMethod.Get, + _solutionServiceUri + $"api/Solutions/taskSolutions/{taskId}/{studentId}"); - public async Task GetUserSolutions(long taskId, string studentId) - { - using var httpRequest = new HttpRequestMessage( - HttpMethod.Get, - _solutionServiceUri + $"api/Solutions/taskSolutions/{taskId}/{studentId}"); + var response = await _httpClient.SendAsync(httpRequest); + return await response.DeserializeAsync(); + } - var response = await _httpClient.SendAsync(httpRequest); - return await response.DeserializeAsync(); + public async Task PostSolution(SolutionViewModel model, long taskId) + { + using var httpRequest = new HttpRequestMessage( + HttpMethod.Post, + _solutionServiceUri + $"api/Solutions/{taskId}") + { + Content = new StringContent( + JsonConvert.SerializeObject(model), + Encoding.UTF8, + "application/json") + }; + + var response = await _httpClient.SendAsync(httpRequest); + if (response.IsSuccessStatusCode) + { + return await response.DeserializeAsync(); } - public async Task PostSolution(SolutionViewModel model, long taskId) - { - using var httpRequest = new HttpRequestMessage( - HttpMethod.Post, - _solutionServiceUri + $"api/Solutions/{taskId}") - { - Content = new StringContent( - JsonConvert.SerializeObject(model), - Encoding.UTF8, - "application/json") - }; - - var response = await _httpClient.SendAsync(httpRequest); - if (response.IsSuccessStatusCode) - { - return await response.DeserializeAsync(); - } + throw new ForbiddenException(); + } - throw new ForbiddenException(); - } + public async Task RateSolution(long solutionId, int newRating, string lecturerComment, string lecturerId) + { + using var httpRequest = new HttpRequestMessage( + HttpMethod.Post, + _solutionServiceUri + + $"api/Solutions/rateSolution/{solutionId}?newRating={newRating}&lecturerComment={lecturerComment}&lecturerId={lecturerId}"); - public async Task RateSolution(long solutionId, int newRating, string lecturerComment, string lecturerId) + var response = await _httpClient.SendAsync(httpRequest); + if (!response.IsSuccessStatusCode) { - using var httpRequest = new HttpRequestMessage( - HttpMethod.Post, - _solutionServiceUri + - $"api/Solutions/rateSolution/{solutionId}?newRating={newRating}&lecturerComment={lecturerComment}&lecturerId={lecturerId}"); - - var response = await _httpClient.SendAsync(httpRequest); - if (!response.IsSuccessStatusCode) - { - throw new ForbiddenException(); - } + throw new ForbiddenException(); } + } - public async Task MarkSolution(long solutionId) - { - using var httpRequest = new HttpRequestMessage( - HttpMethod.Post, - _solutionServiceUri + $"api/Solutions/markSolutionFinal/{solutionId}"); + public async Task MarkSolution(long solutionId) + { + using var httpRequest = new HttpRequestMessage( + HttpMethod.Post, + _solutionServiceUri + $"api/Solutions/markSolutionFinal/{solutionId}"); - await _httpClient.SendAsync(httpRequest); - } + await _httpClient.SendAsync(httpRequest); + } - public async Task DeleteSolution(long solutionId) - { - using var httpRequest = new HttpRequestMessage( - HttpMethod.Delete, - _solutionServiceUri + $"api/Solutions/delete/{solutionId}"); + public async Task DeleteSolution(long solutionId) + { + using var httpRequest = new HttpRequestMessage( + HttpMethod.Delete, + _solutionServiceUri + $"api/Solutions/delete/{solutionId}"); - await _httpClient.SendAsync(httpRequest); - } + await _httpClient.SendAsync(httpRequest); + } - public async Task PostGroupSolution(SolutionViewModel model, long taskId, long groupId) + public async Task PostGroupSolution(SolutionViewModel model, long taskId, long groupId) + { + using var httpRequest = new HttpRequestMessage( + HttpMethod.Post, + _solutionServiceUri + $"api/Solutions/{groupId}/{taskId}") { - using var httpRequest = new HttpRequestMessage( - HttpMethod.Post, - _solutionServiceUri + $"api/Solutions/{groupId}/{taskId}") - { - Content = new StringContent( - JsonConvert.SerializeObject(model), - Encoding.UTF8, - "application/json") - }; - - var response = await _httpClient.SendAsync(httpRequest); - return await response.DeserializeAsync(); - } + Content = new StringContent( + JsonConvert.SerializeObject(model), + Encoding.UTF8, + "application/json") + }; + + var response = await _httpClient.SendAsync(httpRequest); + return await response.DeserializeAsync(); + } - public async Task GetTaskSolutions(long groupId, long taskId) - { - using var httpRequest = new HttpRequestMessage( - HttpMethod.Get, - _solutionServiceUri + $"api/Solutions/{groupId}/taskSolutions/{taskId}"); + public async Task GetTaskSolutions(long groupId, long taskId) + { + using var httpRequest = new HttpRequestMessage( + HttpMethod.Get, + _solutionServiceUri + $"api/Solutions/{groupId}/taskSolutions/{taskId}"); - var response = await _httpClient.SendAsync(httpRequest); - return await response.DeserializeAsync(); - } + var response = await _httpClient.SendAsync(httpRequest); + return await response.DeserializeAsync(); + } - public async Task GetCourseStatistics(long courseId, string userId) - { - using var httpRequest = new HttpRequestMessage( - HttpMethod.Get, - _solutionServiceUri + $"api/Solutions/getCourseStat/{courseId}?userId={userId}"); + public async Task GetCourseStatistics(long courseId, string userId) + { + using var httpRequest = new HttpRequestMessage( + HttpMethod.Get, + _solutionServiceUri + $"api/Solutions/getCourseStat/{courseId}?userId={userId}"); - var response = await _httpClient.SendAsync(httpRequest); - return await response.DeserializeAsync(); - } + var response = await _httpClient.SendAsync(httpRequest); + return await response.DeserializeAsync(); + } - public async Task GetLastTaskSolutions(long[] taskIds, string userId) + public async Task GetLastTaskSolutions(long[] taskIds, string userId) + { + using var httpRequest = new HttpRequestMessage( + HttpMethod.Post, + _solutionServiceUri + $"api/Solutions/taskSolutions/{userId}") { - using var httpRequest = new HttpRequestMessage( - HttpMethod.Post, - _solutionServiceUri + $"api/Solutions/taskSolutions/{userId}") - { - Content = new StringContent( - JsonConvert.SerializeObject(taskIds), - Encoding.UTF8, - "application/json") - }; - - var response = await _httpClient.SendAsync(httpRequest); - return await response.DeserializeAsync(); - } + Content = new StringContent( + JsonConvert.SerializeObject(taskIds), + Encoding.UTF8, + "application/json") + }; + + var response = await _httpClient.SendAsync(httpRequest); + return await response.DeserializeAsync(); + } - public async Task GetAllUnratedSolutionsForTasks(long[] taskIds) + public async Task GetAllUnratedSolutionsForTasks(long[] taskIds) + { + using var httpRequest = new HttpRequestMessage( + HttpMethod.Post, + _solutionServiceUri + "api/Solutions/allUnrated") { - using var httpRequest = new HttpRequestMessage( - HttpMethod.Post, - _solutionServiceUri + "api/Solutions/allUnrated") - { - Content = new StringContent( - JsonConvert.SerializeObject(taskIds), - Encoding.UTF8, - "application/json") - }; - - var response = await _httpClient.SendAsync(httpRequest); - return await response.DeserializeAsync(); - } + Content = new StringContent( + JsonConvert.SerializeObject(taskIds), + Encoding.UTF8, + "application/json") + }; + + var response = await _httpClient.SendAsync(httpRequest); + return await response.DeserializeAsync(); + } - public async Task Ping() + public async Task Ping() + { + try + { + await _httpClient.GetAsync(_solutionServiceUri + "api/system/ping"); + return true; + } + catch { - try - { - await _httpClient.GetAsync(_solutionServiceUri + "api/system/ping"); - return true; - } - catch - { - return false; - } + return false; } } -} +} \ No newline at end of file diff --git a/HwProj.SolutionsService/HwProj.SolutionsService.IntegrationTests/HwProj.SolutionsService.IntegrationTests.csproj b/HwProj.SolutionsService/HwProj.SolutionsService.IntegrationTests/HwProj.SolutionsService.IntegrationTests.csproj index 2d8badede..ca5511097 100644 --- a/HwProj.SolutionsService/HwProj.SolutionsService.IntegrationTests/HwProj.SolutionsService.IntegrationTests.csproj +++ b/HwProj.SolutionsService/HwProj.SolutionsService.IntegrationTests/HwProj.SolutionsService.IntegrationTests.csproj @@ -1,7 +1,7 @@ - netcoreapp2.2 + net6.0 enable false diff --git a/HwProj.SolutionsService/HwProj.SolutionsService.IntegrationTests/SolutionsServiceTests.cs b/HwProj.SolutionsService/HwProj.SolutionsService.IntegrationTests/SolutionsServiceTests.cs index e5fbad844..258ef297e 100644 --- a/HwProj.SolutionsService/HwProj.SolutionsService.IntegrationTests/SolutionsServiceTests.cs +++ b/HwProj.SolutionsService/HwProj.SolutionsService.IntegrationTests/SolutionsServiceTests.cs @@ -18,361 +18,360 @@ using FluentAssertions; using HwProj.Exceptions; -namespace HwProj.SolutionsService.IntegrationTests +namespace HwProj.SolutionsService.IntegrationTests; + +[TestFixture] +public class SolutionsServiceTests { - [TestFixture] - public class SolutionsServiceTests + private RegisterViewModel GenerateRegisterViewModel() { - private RegisterViewModel GenerateRegisterViewModel() - { - var password = new Fixture().Create(); - var fixture = new Fixture().Build() - .With(vm => vm.Password, password) - .With(vm => vm.PasswordConfirm, password); - var viewModel = fixture.Create(); - viewModel.Email += "@mail.ru"; - return viewModel; - } + var password = new Fixture().Create(); + var fixture = new Fixture().Build() + .With(vm => vm.Password, password) + .With(vm => vm.PasswordConfirm, password); + var viewModel = fixture.Create(); + viewModel.Email += "@mail.ru"; + return viewModel; + } - private AuthServiceClient CreateAuthServiceClient() - { - var mockIConfiguration = new Mock(); - mockIConfiguration.Setup(x => x.GetSection("Services")["Auth"]).Returns("http://localhost:5001"); - var mockClientFactory = new Mock(); - mockClientFactory.Setup(x => x.CreateClient(Options.DefaultName)).Returns(new HttpClient()); - return new AuthServiceClient(mockClientFactory.Object, mockIConfiguration.Object); - } + private AuthServiceClient CreateAuthServiceClient() + { + var mockIConfiguration = new Mock(); + mockIConfiguration.Setup(x => x.GetSection("Services")["Auth"]).Returns("http://localhost:5001"); + var mockClientFactory = new Mock(); + mockClientFactory.Setup(x => x.CreateClient(Options.DefaultName)).Returns(new HttpClient()); + return new AuthServiceClient(mockClientFactory.Object, mockIConfiguration.Object); + } - private CreateCourseViewModel GenerateCreateCourseViewModel() - { - var fixture = new Fixture().Build() - .With(cvm => cvm.IsOpen, true); - return fixture.Create(); - } + private CreateCourseViewModel GenerateCreateCourseViewModel() + { + var fixture = new Fixture().Build() + .With(cvm => cvm.IsOpen, true); + return fixture.Create(); + } - private CreateHomeworkViewModel GenerateCreateHomeworkViewModel() - { - var fixture = new Fixture().Build() - .With(hvm => hvm.Tasks, new List()) - .With(hvm => hvm.Tasks, new List()); - return fixture.Create(); - } + private CreateHomeworkViewModel GenerateCreateHomeworkViewModel() + { + var fixture = new Fixture().Build() + .With(hvm => hvm.Tasks, new List()) + .With(hvm => hvm.Tasks, new List()); + return fixture.Create(); + } - private CreateTaskViewModel GenerateCreateTaskViewModelWithoutDeadLine() - { - return new Fixture().Build() - .With(t => t.HasDeadline, false) - .Create(); - } + private CreateTaskViewModel GenerateCreateTaskViewModelWithoutDeadLine() + { + return new Fixture().Build() + .With(t => t.HasDeadline, false) + .Create(); + } - private CreateTaskViewModel GenerateCreateTaskViewModelWithStrictDeadLine() - { - return new Fixture().Build() - .With(t => t.HasDeadline, true) - .With(t => t.IsDeadlineStrict, true) - .With(t => t.DeadlineDate, DateTime.MinValue) - .Create(); - } + private CreateTaskViewModel GenerateCreateTaskViewModelWithStrictDeadLine() + { + return new Fixture().Build() + .With(t => t.HasDeadline, true) + .With(t => t.IsDeadlineStrict, true) + .With(t => t.DeadlineDate, DateTime.MinValue) + .Create(); + } - private CoursesServiceClient CreateCourseServiceClient(string userId) - { - var mockIConfiguration = new Mock(); - mockIConfiguration.Setup(x => x.GetSection("Services")["Courses"]).Returns("http://localhost:5002"); - var mockClientFactory = new Mock(); - mockClientFactory.Setup(x => x.CreateClient(Options.DefaultName)).Returns(new HttpClient()); - var mockHttpContextAccessor = new Mock(); - mockHttpContextAccessor.Setup(x => x.HttpContext.User.FindFirst("_id")).Returns(new Claim("", userId)); - return new CoursesServiceClient(mockClientFactory.Object, mockHttpContextAccessor.Object, - mockIConfiguration.Object); - } + private CoursesServiceClient CreateCourseServiceClient(string userId) + { + var mockIConfiguration = new Mock(); + mockIConfiguration.Setup(x => x.GetSection("Services")["Courses"]).Returns("http://localhost:5002"); + var mockClientFactory = new Mock(); + mockClientFactory.Setup(x => x.CreateClient(Options.DefaultName)).Returns(new HttpClient()); + var mockHttpContextAccessor = new Mock(); + mockHttpContextAccessor.Setup(x => x.HttpContext.User.FindFirst("_id")).Returns(new Claim("", userId)); + return new CoursesServiceClient(mockClientFactory.Object, mockHttpContextAccessor.Object, + mockIConfiguration.Object); + } - private async Task<(string, string)> CreateAndRegisterUser() - { - var authClient = CreateAuthServiceClient(); - var userData = GenerateRegisterViewModel(); - await authClient.Register(userData); - var userId = await authClient.FindByEmailAsync(userData.Email); - return (userId, userData.Email); - } + private async Task<(string, string)> CreateAndRegisterUser() + { + var authClient = CreateAuthServiceClient(); + var userData = GenerateRegisterViewModel(); + await authClient.Register(userData); + var userId = await authClient.FindByEmailAsync(userData.Email); + return (userId, userData.Email); + } - private async Task<(string, string)> CreateAndRegisterLecture() - { - var (userId, mail) = await CreateAndRegisterUser(); - var authClient = CreateAuthServiceClient(); - await authClient.InviteNewLecturer(new InviteLecturerViewModel() {Email = mail}); - return (userId, mail); - } + private async Task<(string, string)> CreateAndRegisterLecture() + { + var (userId, mail) = await CreateAndRegisterUser(); + var authClient = CreateAuthServiceClient(); + await authClient.InviteNewLecturer(new InviteLecturerViewModel() {Email = mail}); + return (userId, mail); + } - private async Task CreateCourse(CoursesServiceClient courseClient, string userId) - { - var newCourseViewModel = GenerateCreateCourseViewModel(); - var courseId = await courseClient.CreateCourse(newCourseViewModel, userId); - return courseId; - } + private async Task CreateCourse(CoursesServiceClient courseClient, string userId) + { + var newCourseViewModel = GenerateCreateCourseViewModel(); + var courseId = await courseClient.CreateCourse(newCourseViewModel, userId); + return courseId; + } - private async Task SignStudentInCourse( - CoursesServiceClient studentCourseClient, - CoursesServiceClient lectureCourseClient, - long courseId, - string studentId) - { - await studentCourseClient.SignInCourse(courseId, studentId); - await lectureCourseClient.AcceptStudent(courseId, studentId); - } + private async Task SignStudentInCourse( + CoursesServiceClient studentCourseClient, + CoursesServiceClient lectureCourseClient, + long courseId, + string studentId) + { + await studentCourseClient.SignInCourse(courseId, studentId); + await lectureCourseClient.AcceptStudent(courseId, studentId); + } - private SolutionViewModel GenerateSolutionViewModel(string userId) - { - var url = new Fixture().Create(); - var fixture = new Fixture().Build() - .With(h => h.GithubUrl, url) - .With(h => h.StudentId, userId); - var viewModel = fixture.Create(); - return viewModel; - } + private SolutionViewModel GenerateSolutionViewModel(string userId) + { + var url = new Fixture().Create(); + var fixture = new Fixture().Build() + .With(h => h.GithubUrl, url) + .With(h => h.StudentId, userId); + var viewModel = fixture.Create(); + return viewModel; + } - private SolutionsServiceClient CreateSolutionsServiceClient() - { - var mockIConfiguration = new Mock(); - mockIConfiguration.Setup(x => x.GetSection("Services")["Solutions"]).Returns("http://localhost:5007"); - var mockClientFactory = new Mock(); - mockClientFactory.Setup(x => x.CreateClient(Options.DefaultName)).Returns(new HttpClient()); - return new SolutionsServiceClient(mockClientFactory.Object, mockIConfiguration.Object); - } + private SolutionsServiceClient CreateSolutionsServiceClient() + { + var mockIConfiguration = new Mock(); + mockIConfiguration.Setup(x => x.GetSection("Services")["Solutions"]).Returns("http://localhost:5007"); + var mockClientFactory = new Mock(); + mockClientFactory.Setup(x => x.CreateClient(Options.DefaultName)).Returns(new HttpClient()); + return new SolutionsServiceClient(mockClientFactory.Object, mockIConfiguration.Object); + } - private async Task<(string, string)> CreateUserAndLecture() - { - var (studentId, _) = await CreateAndRegisterUser(); - var (lectureId, _) = await CreateAndRegisterLecture(); - return (studentId, lectureId); - } + private async Task<(string, string)> CreateUserAndLecture() + { + var (studentId, _) = await CreateAndRegisterUser(); + var (lectureId, _) = await CreateAndRegisterLecture(); + return (studentId, lectureId); + } - private async Task<(long, long, long)> CreateCourseHomeworkTaskWithOutDeadLine(CoursesServiceClient lectureCourseClient, string lectureId) - { - var courseId = await CreateCourse(lectureCourseClient, lectureId); - var newHomeworkViewModel = GenerateCreateHomeworkViewModel(); - var newTaskViewModel = GenerateCreateTaskViewModelWithoutDeadLine(); - var homeworkId = await lectureCourseClient.AddHomeworkToCourse(newHomeworkViewModel, courseId); - var taskId = await lectureCourseClient.AddTask(newTaskViewModel, homeworkId.Value); - return (courseId, homeworkId.Value, taskId.Value); - } + private async Task<(long, long, long)> CreateCourseHomeworkTaskWithOutDeadLine(CoursesServiceClient lectureCourseClient, string lectureId) + { + var courseId = await CreateCourse(lectureCourseClient, lectureId); + var newHomeworkViewModel = GenerateCreateHomeworkViewModel(); + var newTaskViewModel = GenerateCreateTaskViewModelWithoutDeadLine(); + var homeworkId = await lectureCourseClient.AddHomeworkToCourse(newHomeworkViewModel, courseId); + var taskId = await lectureCourseClient.AddTask(newTaskViewModel, homeworkId.Value); + return (courseId, homeworkId.Value, taskId.Value); + } - [Test] - public async Task PostByStudentNotFromThisCourseTest() - { - var (studentId, lectureId) = await CreateUserAndLecture(); - var lectureCourseClient = CreateCourseServiceClient(lectureId); - var (courseId, homeworkId, taskId) = await CreateCourseHomeworkTaskWithOutDeadLine(lectureCourseClient, lectureId); - var solutionClient = CreateSolutionsServiceClient(); - var solutionViewModel = GenerateSolutionViewModel(studentId); + [Test] + public async Task PostByStudentNotFromThisCourseTest() + { + var (studentId, lectureId) = await CreateUserAndLecture(); + var lectureCourseClient = CreateCourseServiceClient(lectureId); + var (courseId, homeworkId, taskId) = await CreateCourseHomeworkTaskWithOutDeadLine(lectureCourseClient, lectureId); + var solutionClient = CreateSolutionsServiceClient(); + var solutionViewModel = GenerateSolutionViewModel(studentId); - Assert.ThrowsAsync(async () => await solutionClient.PostSolution(solutionViewModel, taskId)); - } + Assert.ThrowsAsync(async () => await solutionClient.PostSolution(solutionViewModel, taskId)); + } - [Test] - public async Task PostAndGetSolutionByIdTest() - { - var (studentId, lectureId) = await CreateUserAndLecture(); - var studentCourseClient = CreateCourseServiceClient(studentId); - var lectureCourseClient = CreateCourseServiceClient(lectureId); - var (courseId, homeworkId, taskId) = await CreateCourseHomeworkTaskWithOutDeadLine(lectureCourseClient, lectureId); - await SignStudentInCourse(studentCourseClient, lectureCourseClient, courseId, studentId); - var solutionClient = CreateSolutionsServiceClient(); - var solutionViewModel = GenerateSolutionViewModel(studentId); + [Test] + public async Task PostAndGetSolutionByIdTest() + { + var (studentId, lectureId) = await CreateUserAndLecture(); + var studentCourseClient = CreateCourseServiceClient(studentId); + var lectureCourseClient = CreateCourseServiceClient(lectureId); + var (courseId, homeworkId, taskId) = await CreateCourseHomeworkTaskWithOutDeadLine(lectureCourseClient, lectureId); + await SignStudentInCourse(studentCourseClient, lectureCourseClient, courseId, studentId); + var solutionClient = CreateSolutionsServiceClient(); + var solutionViewModel = GenerateSolutionViewModel(studentId); - var solutionId = await solutionClient.PostSolution(solutionViewModel, taskId); - var solutionIdGet = await solutionClient.GetSolutionById(solutionId); + var solutionId = await solutionClient.PostSolution(solutionViewModel, taskId); + var solutionIdGet = await solutionClient.GetSolutionById(solutionId); - solutionIdGet.Id.Should().Be(solutionId); - solutionIdGet.Comment.Should().Be(solutionViewModel.Comment); - solutionIdGet.Comment.Should().Be(solutionViewModel.Comment); - solutionIdGet.Comment.Should().Be(solutionViewModel.Comment); - } + solutionIdGet.Id.Should().Be(solutionId); + solutionIdGet.Comment.Should().Be(solutionViewModel.Comment); + solutionIdGet.Comment.Should().Be(solutionViewModel.Comment); + solutionIdGet.Comment.Should().Be(solutionViewModel.Comment); + } - [Test] - public async Task PostAndGetUserSolutionTest() - { - var (studentId, lectureId) = await CreateUserAndLecture(); - var studentCourseClient = CreateCourseServiceClient(studentId); - var lectureCourseClient = CreateCourseServiceClient(lectureId); - var (courseId, homeworkId, taskId) = await CreateCourseHomeworkTaskWithOutDeadLine(lectureCourseClient, lectureId); - await SignStudentInCourse(studentCourseClient, lectureCourseClient, courseId, studentId); - var solutionClient = CreateSolutionsServiceClient(); - var solutionViewModel1 = GenerateSolutionViewModel(studentId); - var solutionViewModel2 = GenerateSolutionViewModel(studentId); + [Test] + public async Task PostAndGetUserSolutionTest() + { + var (studentId, lectureId) = await CreateUserAndLecture(); + var studentCourseClient = CreateCourseServiceClient(studentId); + var lectureCourseClient = CreateCourseServiceClient(lectureId); + var (courseId, homeworkId, taskId) = await CreateCourseHomeworkTaskWithOutDeadLine(lectureCourseClient, lectureId); + await SignStudentInCourse(studentCourseClient, lectureCourseClient, courseId, studentId); + var solutionClient = CreateSolutionsServiceClient(); + var solutionViewModel1 = GenerateSolutionViewModel(studentId); + var solutionViewModel2 = GenerateSolutionViewModel(studentId); - var solutionId1 = await solutionClient.PostSolution(solutionViewModel1, taskId); - var solutionId2 = await solutionClient.PostSolution(solutionViewModel2, taskId); - var solutionIdGet = await solutionClient.GetUserSolutions(taskId, studentId); + var solutionId1 = await solutionClient.PostSolution(solutionViewModel1, taskId); + var solutionId2 = await solutionClient.PostSolution(solutionViewModel2, taskId); + var solutionIdGet = await solutionClient.GetUserSolutions(taskId, studentId); - solutionIdGet.Should().HaveCount(2); - solutionIdGet.Should().ContainSingle(s => s.Id == solutionId1); - solutionIdGet.Should().ContainSingle(s => s.Id == solutionId2); - } + solutionIdGet.Should().HaveCount(2); + solutionIdGet.Should().ContainSingle(s => s.Id == solutionId1); + solutionIdGet.Should().ContainSingle(s => s.Id == solutionId2); + } - [Test] - public async Task PostAndGetAllSolutionTest() - { - var (studentId1, lectureId) = await CreateUserAndLecture(); - var (studentId2, _) = await CreateAndRegisterUser(); - var student1CourseClient = CreateCourseServiceClient(studentId1); - var student2CourseClient = CreateCourseServiceClient(studentId2); - var lectureCourseClient = CreateCourseServiceClient(lectureId); - var (courseId, homeworkId, taskId) = await CreateCourseHomeworkTaskWithOutDeadLine(lectureCourseClient, lectureId); - await SignStudentInCourse(student1CourseClient, lectureCourseClient, courseId, studentId1); - await SignStudentInCourse(student2CourseClient, lectureCourseClient, courseId, studentId2); - var solutionClient = CreateSolutionsServiceClient(); - var solutionViewModelFromStudent1 = GenerateSolutionViewModel(studentId1); - var solutionViewModelFromStudent2 = GenerateSolutionViewModel(studentId2); + [Test] + public async Task PostAndGetAllSolutionTest() + { + var (studentId1, lectureId) = await CreateUserAndLecture(); + var (studentId2, _) = await CreateAndRegisterUser(); + var student1CourseClient = CreateCourseServiceClient(studentId1); + var student2CourseClient = CreateCourseServiceClient(studentId2); + var lectureCourseClient = CreateCourseServiceClient(lectureId); + var (courseId, homeworkId, taskId) = await CreateCourseHomeworkTaskWithOutDeadLine(lectureCourseClient, lectureId); + await SignStudentInCourse(student1CourseClient, lectureCourseClient, courseId, studentId1); + await SignStudentInCourse(student2CourseClient, lectureCourseClient, courseId, studentId2); + var solutionClient = CreateSolutionsServiceClient(); + var solutionViewModelFromStudent1 = GenerateSolutionViewModel(studentId1); + var solutionViewModelFromStudent2 = GenerateSolutionViewModel(studentId2); - var solutionIdFromStudent1 = await solutionClient.PostSolution(solutionViewModelFromStudent1, taskId); - var solutionIdFromStudent2 = await solutionClient.PostSolution(solutionViewModelFromStudent2, taskId); - var solutionsGet = await solutionClient.GetAllSolutions(); + var solutionIdFromStudent1 = await solutionClient.PostSolution(solutionViewModelFromStudent1, taskId); + var solutionIdFromStudent2 = await solutionClient.PostSolution(solutionViewModelFromStudent2, taskId); + var solutionsGet = await solutionClient.GetAllSolutions(); - solutionsGet.Should().ContainSingle(s => s.Id == solutionIdFromStudent1); - solutionsGet.Should().ContainSingle(s => s.Id == solutionIdFromStudent2); - } + solutionsGet.Should().ContainSingle(s => s.Id == solutionIdFromStudent1); + solutionsGet.Should().ContainSingle(s => s.Id == solutionIdFromStudent2); + } - [Test] - public async Task RateSolutionByLectureTest() - { - var (studentId, lectureId) = await CreateUserAndLecture(); - var studentCourseClient = CreateCourseServiceClient(studentId); - var lectureCourseClient = CreateCourseServiceClient(lectureId); - var (courseId, homeworkId, taskId) = await CreateCourseHomeworkTaskWithOutDeadLine(lectureCourseClient, lectureId); - await SignStudentInCourse(studentCourseClient, lectureCourseClient, courseId, studentId); - var solutionClient = CreateSolutionsServiceClient(); - var solutionViewModelFromStudent = GenerateSolutionViewModel(studentId); + [Test] + public async Task RateSolutionByLectureTest() + { + var (studentId, lectureId) = await CreateUserAndLecture(); + var studentCourseClient = CreateCourseServiceClient(studentId); + var lectureCourseClient = CreateCourseServiceClient(lectureId); + var (courseId, homeworkId, taskId) = await CreateCourseHomeworkTaskWithOutDeadLine(lectureCourseClient, lectureId); + await SignStudentInCourse(studentCourseClient, lectureCourseClient, courseId, studentId); + var solutionClient = CreateSolutionsServiceClient(); + var solutionViewModelFromStudent = GenerateSolutionViewModel(studentId); - var solutionId = await solutionClient.PostSolution(solutionViewModelFromStudent, taskId); - await solutionClient.RateSolution(solutionId, 2, "Not Bad", lectureId); - var solutionsGet = await solutionClient.GetSolutionById(solutionId); + var solutionId = await solutionClient.PostSolution(solutionViewModelFromStudent, taskId); + await solutionClient.RateSolution(solutionId, 2, "Not Bad", lectureId); + var solutionsGet = await solutionClient.GetSolutionById(solutionId); - solutionsGet.LecturerComment.Should().Be("Not Bad"); - solutionsGet.Rating.Should().Be(2); - } + solutionsGet.LecturerComment.Should().Be("Not Bad"); + solutionsGet.Rating.Should().Be(2); + } - [Test] - public async Task RateSolutionByNotLectureTest() - { - var (studentId, lectureId) = await CreateUserAndLecture(); - var studentCourseClient = CreateCourseServiceClient(studentId); - var lectureCourseClient = CreateCourseServiceClient(lectureId); - var (courseId, homeworkId, taskId) = await CreateCourseHomeworkTaskWithOutDeadLine(lectureCourseClient, lectureId); - await SignStudentInCourse(studentCourseClient, lectureCourseClient, courseId, studentId); - var solutionClient = CreateSolutionsServiceClient(); - var solutionViewModelFromStudent = GenerateSolutionViewModel(studentId); + [Test] + public async Task RateSolutionByNotLectureTest() + { + var (studentId, lectureId) = await CreateUserAndLecture(); + var studentCourseClient = CreateCourseServiceClient(studentId); + var lectureCourseClient = CreateCourseServiceClient(lectureId); + var (courseId, homeworkId, taskId) = await CreateCourseHomeworkTaskWithOutDeadLine(lectureCourseClient, lectureId); + await SignStudentInCourse(studentCourseClient, lectureCourseClient, courseId, studentId); + var solutionClient = CreateSolutionsServiceClient(); + var solutionViewModelFromStudent = GenerateSolutionViewModel(studentId); - var solutionId = await solutionClient.PostSolution(solutionViewModelFromStudent, taskId); + var solutionId = await solutionClient.PostSolution(solutionViewModelFromStudent, taskId); - Assert.ThrowsAsync(async () => await solutionClient.RateSolution(solutionId, 2, "Not Bad", studentId)); - } + Assert.ThrowsAsync(async () => await solutionClient.RateSolution(solutionId, 2, "Not Bad", studentId)); + } - [Test] - public async Task MarkSolutionTest() - { - var (studentId, lectureId) = await CreateUserAndLecture(); - var studentCourseClient = CreateCourseServiceClient(studentId); - var lectureCourseClient = CreateCourseServiceClient(lectureId); - var (courseId, homeworkId, taskId) = await CreateCourseHomeworkTaskWithOutDeadLine(lectureCourseClient, lectureId); - await SignStudentInCourse(studentCourseClient, lectureCourseClient, courseId, studentId); - var solutionClient = CreateSolutionsServiceClient(); - var solutionViewModelFromStudent = GenerateSolutionViewModel(studentId); + [Test] + public async Task MarkSolutionTest() + { + var (studentId, lectureId) = await CreateUserAndLecture(); + var studentCourseClient = CreateCourseServiceClient(studentId); + var lectureCourseClient = CreateCourseServiceClient(lectureId); + var (courseId, homeworkId, taskId) = await CreateCourseHomeworkTaskWithOutDeadLine(lectureCourseClient, lectureId); + await SignStudentInCourse(studentCourseClient, lectureCourseClient, courseId, studentId); + var solutionClient = CreateSolutionsServiceClient(); + var solutionViewModelFromStudent = GenerateSolutionViewModel(studentId); - var solutionId = await solutionClient.PostSolution(solutionViewModelFromStudent, taskId); - await solutionClient.MarkSolution(solutionId); - var solutionsGet = await solutionClient.GetSolutionById(solutionId); + var solutionId = await solutionClient.PostSolution(solutionViewModelFromStudent, taskId); + await solutionClient.MarkSolution(solutionId); + var solutionsGet = await solutionClient.GetSolutionById(solutionId); - solutionsGet.State.Should().Be(SolutionState.Final); - } + solutionsGet.State.Should().Be(SolutionState.Final); + } - [Test] - public async Task DeleteSolutionTest() - { - var (studentId, lectureId) = await CreateUserAndLecture(); - var studentCourseClient = CreateCourseServiceClient(studentId); - var lectureCourseClient = CreateCourseServiceClient(lectureId); - var (courseId, homeworkId, taskId) = await CreateCourseHomeworkTaskWithOutDeadLine(lectureCourseClient, lectureId); - await SignStudentInCourse(studentCourseClient, lectureCourseClient, courseId, studentId); - var solutionClient = CreateSolutionsServiceClient(); - var solutionViewModel = GenerateSolutionViewModel(studentId); + [Test] + public async Task DeleteSolutionTest() + { + var (studentId, lectureId) = await CreateUserAndLecture(); + var studentCourseClient = CreateCourseServiceClient(studentId); + var lectureCourseClient = CreateCourseServiceClient(lectureId); + var (courseId, homeworkId, taskId) = await CreateCourseHomeworkTaskWithOutDeadLine(lectureCourseClient, lectureId); + await SignStudentInCourse(studentCourseClient, lectureCourseClient, courseId, studentId); + var solutionClient = CreateSolutionsServiceClient(); + var solutionViewModel = GenerateSolutionViewModel(studentId); - var solutionId = await solutionClient.PostSolution(solutionViewModel, taskId); - var solutionIdBefore = await solutionClient.GetSolutionById(solutionId); - await solutionClient.DeleteSolution(solutionId); - var solutionIdAfter = await solutionClient.GetUserSolutions(taskId, studentId); + var solutionId = await solutionClient.PostSolution(solutionViewModel, taskId); + var solutionIdBefore = await solutionClient.GetSolutionById(solutionId); + await solutionClient.DeleteSolution(solutionId); + var solutionIdAfter = await solutionClient.GetUserSolutions(taskId, studentId); - solutionIdBefore.Id.Should().Be(solutionId); - solutionIdAfter.Should().NotContain(s => s.Id == solutionIdBefore.Id); - } + solutionIdBefore.Id.Should().Be(solutionId); + solutionIdAfter.Should().NotContain(s => s.Id == solutionIdBefore.Id); + } - [Test] - public async Task GetCourseStatisticsTest() - { - var (studentId, lectureId) = await CreateUserAndLecture(); - var studentCourseClient = CreateCourseServiceClient(studentId); - var lectureCourseClient = CreateCourseServiceClient(lectureId); - var (courseId, homeworkId, taskId) = await CreateCourseHomeworkTaskWithOutDeadLine(lectureCourseClient, lectureId); - await SignStudentInCourse(studentCourseClient, lectureCourseClient, courseId, studentId); - var solutionClient = CreateSolutionsServiceClient(); - var solutionViewModel = GenerateSolutionViewModel(studentId); + [Test] + public async Task GetCourseStatisticsTest() + { + var (studentId, lectureId) = await CreateUserAndLecture(); + var studentCourseClient = CreateCourseServiceClient(studentId); + var lectureCourseClient = CreateCourseServiceClient(lectureId); + var (courseId, homeworkId, taskId) = await CreateCourseHomeworkTaskWithOutDeadLine(lectureCourseClient, lectureId); + await SignStudentInCourse(studentCourseClient, lectureCourseClient, courseId, studentId); + var solutionClient = CreateSolutionsServiceClient(); + var solutionViewModel = GenerateSolutionViewModel(studentId); - var solutionId = await solutionClient.PostSolution(solutionViewModel, taskId); - await solutionClient.RateSolution(solutionId, 2, "Not Bad", lectureId); - var statisticsFromStudent = await solutionClient.GetCourseStatistics(courseId, studentId); - var statisticsFromLecture = await solutionClient.GetCourseStatistics(courseId, lectureId); + var solutionId = await solutionClient.PostSolution(solutionViewModel, taskId); + await solutionClient.RateSolution(solutionId, 2, "Not Bad", lectureId); + var statisticsFromStudent = await solutionClient.GetCourseStatistics(courseId, studentId); + var statisticsFromLecture = await solutionClient.GetCourseStatistics(courseId, lectureId); - statisticsFromStudent.Should().HaveCount(1); - statisticsFromLecture.Should().HaveCount(1); - statisticsFromLecture[0].Homeworks.Should().HaveCount(1); - statisticsFromLecture[0].Homeworks[0].Tasks.Should().HaveCount(1); - statisticsFromLecture[0].Homeworks[0].Tasks[0].Solution.Should().HaveCount(1); - statisticsFromLecture[0].Homeworks[0].Tasks[0].Solution[0].Rating.Should().Be(2); - } + statisticsFromStudent.Should().HaveCount(1); + statisticsFromLecture.Should().HaveCount(1); + statisticsFromLecture[0].Homeworks.Should().HaveCount(1); + statisticsFromLecture[0].Homeworks[0].Tasks.Should().HaveCount(1); + statisticsFromLecture[0].Homeworks[0].Tasks[0].Solution.Should().HaveCount(1); + statisticsFromLecture[0].Homeworks[0].Tasks[0].Solution[0].Rating.Should().Be(2); + } - [Test] - public async Task PostSolutionAfterNotStrictDeadLine() - { - var (studentId, lectureId) = await CreateUserAndLecture(); - var studentCourseClient = CreateCourseServiceClient(studentId); - var lectureCourseClient = CreateCourseServiceClient(lectureId); - var courseId = await CreateCourse(lectureCourseClient, lectureId); - var homeworkViewModel = GenerateCreateHomeworkViewModel(); - var homeworkId = await lectureCourseClient.AddHomeworkToCourse(homeworkViewModel, courseId); - var taskViewModel = GenerateCreateTaskViewModelWithStrictDeadLine(); - taskViewModel.IsDeadlineStrict = false; - var taskId = await lectureCourseClient.AddTask(taskViewModel, homeworkId.Value); - await SignStudentInCourse(studentCourseClient, lectureCourseClient, courseId, studentId); - var solutionsClient = CreateSolutionsServiceClient(); + [Test] + public async Task PostSolutionAfterNotStrictDeadLine() + { + var (studentId, lectureId) = await CreateUserAndLecture(); + var studentCourseClient = CreateCourseServiceClient(studentId); + var lectureCourseClient = CreateCourseServiceClient(lectureId); + var courseId = await CreateCourse(lectureCourseClient, lectureId); + var homeworkViewModel = GenerateCreateHomeworkViewModel(); + var homeworkId = await lectureCourseClient.AddHomeworkToCourse(homeworkViewModel, courseId); + var taskViewModel = GenerateCreateTaskViewModelWithStrictDeadLine(); + taskViewModel.IsDeadlineStrict = false; + var taskId = await lectureCourseClient.AddTask(taskViewModel, homeworkId.Value); + await SignStudentInCourse(studentCourseClient, lectureCourseClient, courseId, studentId); + var solutionsClient = CreateSolutionsServiceClient(); - var solutionViewModel = GenerateSolutionViewModel(studentId); - solutionViewModel.PublicationDate = DateTime.MaxValue; + var solutionViewModel = GenerateSolutionViewModel(studentId); + solutionViewModel.PublicationDate = DateTime.MaxValue; - var solutionId = await solutionsClient.PostSolution(solutionViewModel, taskId.Value); - var solutionIdGet = await solutionsClient.GetUserSolutions(taskId.Value, studentId); + var solutionId = await solutionsClient.PostSolution(solutionViewModel, taskId.Value); + var solutionIdGet = await solutionsClient.GetUserSolutions(taskId.Value, studentId); - solutionIdGet.Should().HaveCount(1); - solutionIdGet.Should().Contain(s => s.Id == solutionId); - } + solutionIdGet.Should().HaveCount(1); + solutionIdGet.Should().Contain(s => s.Id == solutionId); + } - [Test] - public async Task PostSolutionAfterStrictDeadLine() - { - var (studentId, lectureId) = await CreateUserAndLecture(); - var studentCourseClient = CreateCourseServiceClient(studentId); - var lectureCourseClient = CreateCourseServiceClient(lectureId); - var courseId = await CreateCourse(lectureCourseClient, lectureId); - var homeworkViewModel = GenerateCreateHomeworkViewModel(); - var homeworkId = await lectureCourseClient.AddHomeworkToCourse(homeworkViewModel, courseId); - var taskViewModel = GenerateCreateTaskViewModelWithStrictDeadLine(); - var taskId = await lectureCourseClient.AddTask(taskViewModel, homeworkId.Value); - await SignStudentInCourse(studentCourseClient, lectureCourseClient, courseId, studentId); - var solutionsClient = CreateSolutionsServiceClient(); + [Test] + public async Task PostSolutionAfterStrictDeadLine() + { + var (studentId, lectureId) = await CreateUserAndLecture(); + var studentCourseClient = CreateCourseServiceClient(studentId); + var lectureCourseClient = CreateCourseServiceClient(lectureId); + var courseId = await CreateCourse(lectureCourseClient, lectureId); + var homeworkViewModel = GenerateCreateHomeworkViewModel(); + var homeworkId = await lectureCourseClient.AddHomeworkToCourse(homeworkViewModel, courseId); + var taskViewModel = GenerateCreateTaskViewModelWithStrictDeadLine(); + var taskId = await lectureCourseClient.AddTask(taskViewModel, homeworkId.Value); + await SignStudentInCourse(studentCourseClient, lectureCourseClient, courseId, studentId); + var solutionsClient = CreateSolutionsServiceClient(); - var solutionViewModel = GenerateSolutionViewModel(studentId); - solutionViewModel.PublicationDate = DateTime.MaxValue; + var solutionViewModel = GenerateSolutionViewModel(studentId); + solutionViewModel.PublicationDate = DateTime.MaxValue; - Assert.ThrowsAsync(async () => await solutionsClient.PostSolution(solutionViewModel, taskId.Value)); - } + Assert.ThrowsAsync(async () => await solutionsClient.PostSolution(solutionViewModel, taskId.Value)); } } \ No newline at end of file diff --git a/HwProj.sln b/HwProj.sln index 4a92cd40e..11b26bb2a 100644 --- a/HwProj.sln +++ b/HwProj.sln @@ -44,10 +44,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HwProj.AuthService.Client", EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HwProj.CoursesService.Client", "HwProj.CoursesService\HwProj.CoursesService.Client\HwProj.CoursesService.Client.csproj", "{0A9B7E03-680B-4BAC-9599-87AB5219D376}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HwProj.CourseWorkService.API", "HwProj.CourseWorkService\HwProj.CourseWorkService.API\HwProj.CourseWorkService.API.csproj", "{CB5FAC80-3B44-4719-8077-8CC1A896E349}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "HwProj.CourseWorkService", "HwProj.CourseWorkService", "{35A92562-020E-43ED-9F23-67D2B99C4F9C}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HwProj.EventBus.Client", "HwProj.EventBus\HwProj.EventBus.Client\HwProj.EventBus.Client.csproj", "{1B390715-0A95-4B09-8E04-D3F8F5CAC7BB}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HwProj.EventBus.Tests", "HwProj.EventBus\HwProj.EventBus.Tests\HwProj.EventBus.Tests.csproj", "{9D2ECCE5-E63B-4362-889C-406966AF8F5E}" @@ -120,10 +116,6 @@ Global {0A9B7E03-680B-4BAC-9599-87AB5219D376}.Debug|Any CPU.Build.0 = Debug|Any CPU {0A9B7E03-680B-4BAC-9599-87AB5219D376}.Release|Any CPU.ActiveCfg = Release|Any CPU {0A9B7E03-680B-4BAC-9599-87AB5219D376}.Release|Any CPU.Build.0 = Release|Any CPU - {CB5FAC80-3B44-4719-8077-8CC1A896E349}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {CB5FAC80-3B44-4719-8077-8CC1A896E349}.Debug|Any CPU.Build.0 = Debug|Any CPU - {CB5FAC80-3B44-4719-8077-8CC1A896E349}.Release|Any CPU.ActiveCfg = Release|Any CPU - {CB5FAC80-3B44-4719-8077-8CC1A896E349}.Release|Any CPU.Build.0 = Release|Any CPU {1B390715-0A95-4B09-8E04-D3F8F5CAC7BB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {1B390715-0A95-4B09-8E04-D3F8F5CAC7BB}.Debug|Any CPU.Build.0 = Debug|Any CPU {1B390715-0A95-4B09-8E04-D3F8F5CAC7BB}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -173,7 +165,6 @@ Global {ECFA80DA-E0F5-4613-A15E-55FC8B9C8401} = {77D857A8-45C6-4432-B4BF-A2F2C9ECA7FE} {8F56C068-4827-412F-A29A-419B8AC5BECD} = {D7F8BC73-A6CB-4E07-984D-2D65B740BC69} {0A9B7E03-680B-4BAC-9599-87AB5219D376} = {CB37F9AC-88CB-425C-8200-1B40F372F38D} - {CB5FAC80-3B44-4719-8077-8CC1A896E349} = {35A92562-020E-43ED-9F23-67D2B99C4F9C} {1B390715-0A95-4B09-8E04-D3F8F5CAC7BB} = {5C097F08-BB63-49F4-BC69-892AE8136E40} {9D2ECCE5-E63B-4362-889C-406966AF8F5E} = {5C097F08-BB63-49F4-BC69-892AE8136E40} {6E686DBA-1B30-4F72-86BC-BF1602B3B2FC} = {77D857A8-45C6-4432-B4BF-A2F2C9ECA7FE} From 350d5179741d57876572a85f40724623267cb182 Mon Sep 17 00:00:00 2001 From: overnight Date: Mon, 6 Mar 2023 14:44:06 +0300 Subject: [PATCH 02/14] update auth service dependencies --- .../Controllers/AccountController.cs | 4 ++-- .../HwProj.AuthService.API.csproj | 17 +++++++++-------- .../Models/IdentityContext.cs | 1 - .../AuthServiceClient.cs | 2 +- .../HwProj.SolutionsService.API.csproj | 4 ++-- global.json | 7 +++++++ 6 files changed, 21 insertions(+), 14 deletions(-) create mode 100644 global.json diff --git a/HwProj.AuthService/HwProj.AuthService.API/Controllers/AccountController.cs b/HwProj.AuthService/HwProj.AuthService.API/Controllers/AccountController.cs index 9dc2b38e8..5d52797c0 100644 --- a/HwProj.AuthService/HwProj.AuthService.API/Controllers/AccountController.cs +++ b/HwProj.AuthService/HwProj.AuthService.API/Controllers/AccountController.cs @@ -12,9 +12,9 @@ namespace HwProj.AuthService.API.Controllers; -[Route("api/account")] +[Route("api/[controller]")] [ApiController] -public class AccountController : ControllerBase +public class AccountController : Controller { private readonly IAccountService _accountService; private readonly IUserManager _userManager; diff --git a/HwProj.AuthService/HwProj.AuthService.API/HwProj.AuthService.API.csproj b/HwProj.AuthService/HwProj.AuthService.API/HwProj.AuthService.API.csproj index e0b845020..d16cd35b6 100644 --- a/HwProj.AuthService/HwProj.AuthService.API/HwProj.AuthService.API.csproj +++ b/HwProj.AuthService/HwProj.AuthService.API/HwProj.AuthService.API.csproj @@ -5,19 +5,20 @@ Linux ..\..\docker-compose.dcproj ..\.. - $(CSharpLanguageVersion) + 10 603911e4-ace8-4439-96f8-1705a0dae761 $(NullableReferenceTypes) - - - - - - - + + + + + + + + diff --git a/HwProj.AuthService/HwProj.AuthService.API/Models/IdentityContext.cs b/HwProj.AuthService/HwProj.AuthService.API/Models/IdentityContext.cs index ceb4def99..166311b09 100644 --- a/HwProj.AuthService/HwProj.AuthService.API/Models/IdentityContext.cs +++ b/HwProj.AuthService/HwProj.AuthService.API/Models/IdentityContext.cs @@ -1,7 +1,6 @@ using HwProj.Models.AuthService.ViewModels; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; - namespace HwProj.AuthService.API.Models; public sealed class IdentityContext : IdentityDbContext diff --git a/HwProj.AuthService/HwProj.AuthService.Client/AuthServiceClient.cs b/HwProj.AuthService/HwProj.AuthService.Client/AuthServiceClient.cs index 4a50b5de5..5f4672ac9 100644 --- a/HwProj.AuthService/HwProj.AuthService.Client/AuthServiceClient.cs +++ b/HwProj.AuthService/HwProj.AuthService.Client/AuthServiceClient.cs @@ -5,9 +5,9 @@ using HwProj.HttpUtils; using HwProj.Models.AuthService.ViewModels; using HwProj.Models.AuthService.DTO; -using Newtonsoft.Json; using HwProj.Models.Result; using Microsoft.Extensions.Configuration; +using Newtonsoft.Json; namespace HwProj.AuthService.Client; diff --git a/HwProj.SolutionsService/HwProj.SolutionsService.API/HwProj.SolutionsService.API.csproj b/HwProj.SolutionsService/HwProj.SolutionsService.API/HwProj.SolutionsService.API.csproj index e16672c90..0b90dd42f 100644 --- a/HwProj.SolutionsService/HwProj.SolutionsService.API/HwProj.SolutionsService.API.csproj +++ b/HwProj.SolutionsService/HwProj.SolutionsService.API/HwProj.SolutionsService.API.csproj @@ -4,7 +4,7 @@ Linux ..\..\docker-compose.dcproj ..\.. - $(CSharpLanguageVersion) + 10 $(NullableReferenceTypes) 467aaa56-ee17-4f11-b2da-7d9a74c68753 @@ -20,7 +20,7 @@ - + diff --git a/global.json b/global.json new file mode 100644 index 000000000..9e5e1fd1d --- /dev/null +++ b/global.json @@ -0,0 +1,7 @@ +{ + "sdk": { + "version": "6.0.0", + "rollForward": "latestMajor", + "allowPrerelease": true + } +} \ No newline at end of file From f9a2bbfb0a853b9d8f086c9133f22478463ad9e7 Mon Sep 17 00:00:00 2001 From: Roman Pozharskiy Date: Wed, 29 Mar 2023 22:04:03 +0300 Subject: [PATCH 03/14] wip --- Directory.Build.props | 2 +- .../HwProj.APIGateway.API.csproj | 2 +- .../HwProj.AuthService.Client.csproj | 2 +- ...HwProj.AuthService.IntegrationTests.csproj | 4 +-- .../HwProj.Models/HwProj.Models.csproj | 4 +-- .../HwProj.Repositories.csproj | 4 +-- .../Configuration/StartupExtensions.cs | 32 ++++++++++++------- .../HwProj.Utils/HwProj.Utils.csproj | 4 +-- .../HwProj.CoursesService.API/Dockerfile | 2 +- .../HwProj.CoursesService.API.csproj | 2 +- .../HwProj.CoursesService.Client.csproj | 6 ++-- .../HwProj.CoursesService.Tests.csproj | 2 +- .../HwProj.EventBus.Client.csproj | 6 +++- .../Implementations/EventBusRabbitMQ.cs | 5 +-- .../HwProj.NotificationsService.API.csproj | 2 +- .../Services/EmailService.cs | 5 ++- .../HwProj.NotificationsService.Client.csproj | 4 +-- .../HwProj.NotificationsService.Tests.csproj | 2 +- .../Controllers/SolutionsController.cs | 3 ++ .../HwProj.SolutionsService.API/Startup.cs | 2 +- .../HwProj.SolutionsService.Client.csproj | 4 +-- 21 files changed, 58 insertions(+), 41 deletions(-) diff --git a/Directory.Build.props b/Directory.Build.props index 208b791ca..bc8ae8f35 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -4,6 +4,6 @@ - enable + disable \ No newline at end of file diff --git a/HwProj.APIGateway/HwProj.APIGateway.API/HwProj.APIGateway.API.csproj b/HwProj.APIGateway/HwProj.APIGateway.API/HwProj.APIGateway.API.csproj index b2442e0ba..2e077edf3 100644 --- a/HwProj.APIGateway/HwProj.APIGateway.API/HwProj.APIGateway.API.csproj +++ b/HwProj.APIGateway/HwProj.APIGateway.API/HwProj.APIGateway.API.csproj @@ -10,7 +10,7 @@ - + diff --git a/HwProj.AuthService/HwProj.AuthService.Client/HwProj.AuthService.Client.csproj b/HwProj.AuthService/HwProj.AuthService.Client/HwProj.AuthService.Client.csproj index e3c2850c2..202b5079f 100644 --- a/HwProj.AuthService/HwProj.AuthService.Client/HwProj.AuthService.Client.csproj +++ b/HwProj.AuthService/HwProj.AuthService.Client/HwProj.AuthService.Client.csproj @@ -15,7 +15,7 @@ - + diff --git a/HwProj.AuthService/HwProj.AuthService.IntegrationTests/HwProj.AuthService.IntegrationTests.csproj b/HwProj.AuthService/HwProj.AuthService.IntegrationTests/HwProj.AuthService.IntegrationTests.csproj index 53d295526..ddb4298b1 100644 --- a/HwProj.AuthService/HwProj.AuthService.IntegrationTests/HwProj.AuthService.IntegrationTests.csproj +++ b/HwProj.AuthService/HwProj.AuthService.IntegrationTests/HwProj.AuthService.IntegrationTests.csproj @@ -11,12 +11,12 @@ - + - + diff --git a/HwProj.Common/HwProj.Models/HwProj.Models.csproj b/HwProj.Common/HwProj.Models/HwProj.Models.csproj index 1ff494e0d..2cd83d2dc 100644 --- a/HwProj.Common/HwProj.Models/HwProj.Models.csproj +++ b/HwProj.Common/HwProj.Models/HwProj.Models.csproj @@ -7,8 +7,8 @@ - - + + diff --git a/HwProj.Common/HwProj.Repositories/HwProj.Repositories.csproj b/HwProj.Common/HwProj.Repositories/HwProj.Repositories.csproj index d2f985328..3eb033397 100644 --- a/HwProj.Common/HwProj.Repositories/HwProj.Repositories.csproj +++ b/HwProj.Common/HwProj.Repositories/HwProj.Repositories.csproj @@ -5,8 +5,8 @@ $(NullableReferenceTypes) - - + + diff --git a/HwProj.Common/HwProj.Utils/Configuration/StartupExtensions.cs b/HwProj.Common/HwProj.Utils/Configuration/StartupExtensions.cs index 86325a396..1097579d6 100644 --- a/HwProj.Common/HwProj.Utils/Configuration/StartupExtensions.cs +++ b/HwProj.Common/HwProj.Utils/Configuration/StartupExtensions.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Linq; using System.Net.Sockets; using System.Text.Json.Serialization; @@ -21,13 +22,13 @@ namespace HwProj.Utils.Configuration; -public static class StartupExtensions +public static class StartupExtensions { public static IServiceCollection ConfigureHwProjServices(this IServiceCollection services, string serviceName) { services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()) .AddCors() - .AddMvc() + .AddControllers() .AddJsonOptions(options => options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles); @@ -37,17 +38,24 @@ public static IServiceCollection ConfigureHwProjServices(this IServiceCollection if (serviceName == "API Gateway") { - c.AddSecurityDefinition("Bearer", - new OpenApiSecurityScheme + var securityScheme = new OpenApiSecurityScheme + { + Name = "Bearer", + Description = "Enter JWT Bearer token _only_", + In = ParameterLocation.Header, + Type = SecuritySchemeType.Http, + Scheme = "bearer", + BearerFormat = "JWT", + Reference = new OpenApiReference { - In = ParameterLocation.Header, - Description = "Please enter into field the word 'Bearer' following by space and JWT", - Name = "Authorization", - Type = SecuritySchemeType.ApiKey - }); + Id = JwtBearerDefaults.AuthenticationScheme, + Type = ReferenceType.SecurityScheme + } + }; + c.AddSecurityDefinition(securityScheme.Reference.Id, securityScheme); c.AddSecurityRequirement(new OpenApiSecurityRequirement { - { "Bearer", Enumerable.Empty() }, + { securityScheme, Array.Empty() }, }); } }); @@ -143,7 +151,9 @@ public static IApplicationBuilder ConfigureHwProj(this IApplicationBuilder app, .AllowAnyHeader() .SetIsOriginAllowed(origin => true) .AllowCredentials()); - app.UseMvc(); + app.UseRouting(); + app.UseAuthorization(); + app.UseEndpoints(endpoints => endpoints.MapControllers()); return app; } diff --git a/HwProj.Common/HwProj.Utils/HwProj.Utils.csproj b/HwProj.Common/HwProj.Utils/HwProj.Utils.csproj index 522acd1e2..b2d35f816 100644 --- a/HwProj.Common/HwProj.Utils/HwProj.Utils.csproj +++ b/HwProj.Common/HwProj.Utils/HwProj.Utils.csproj @@ -8,8 +8,8 @@ - - + + diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Dockerfile b/HwProj.CoursesService/HwProj.CoursesService.API/Dockerfile index 7ace0cd68..5124d732c 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Dockerfile +++ b/HwProj.CoursesService/HwProj.CoursesService.API/Dockerfile @@ -18,7 +18,7 @@ RUN dotnet build "HwProj.CoursesService.API.csproj" -c Release -o /app/build FROM build AS publish RUN dotnet publish "HwProj.CoursesService.API.csproj" -c Release -o /app/publish -FROM base AS final +FROM base AS final WORKDIR /app COPY --from=publish /app/publish . ENTRYPOINT ["dotnet", "HwProj.CoursesService.API.dll"] diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/HwProj.CoursesService.API.csproj b/HwProj.CoursesService/HwProj.CoursesService.API/HwProj.CoursesService.API.csproj index 6400981f6..e167bfc10 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/HwProj.CoursesService.API.csproj +++ b/HwProj.CoursesService/HwProj.CoursesService.API/HwProj.CoursesService.API.csproj @@ -12,7 +12,7 @@ - + diff --git a/HwProj.CoursesService/HwProj.CoursesService.Client/HwProj.CoursesService.Client.csproj b/HwProj.CoursesService/HwProj.CoursesService.Client/HwProj.CoursesService.Client.csproj index a35c155b7..9a82d27a5 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.Client/HwProj.CoursesService.Client.csproj +++ b/HwProj.CoursesService/HwProj.CoursesService.Client/HwProj.CoursesService.Client.csproj @@ -11,9 +11,9 @@ - - - + + + diff --git a/HwProj.CoursesService/HwProj.CoursesService.Tests/HwProj.CoursesService.Tests.csproj b/HwProj.CoursesService/HwProj.CoursesService.Tests/HwProj.CoursesService.Tests.csproj index 3f20a9057..24647c96e 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.Tests/HwProj.CoursesService.Tests.csproj +++ b/HwProj.CoursesService/HwProj.CoursesService.Tests/HwProj.CoursesService.Tests.csproj @@ -13,7 +13,7 @@ - + diff --git a/HwProj.EventBus/HwProj.EventBus.Client/HwProj.EventBus.Client.csproj b/HwProj.EventBus/HwProj.EventBus.Client/HwProj.EventBus.Client.csproj index 4585f44f5..82fb44c0b 100644 --- a/HwProj.EventBus/HwProj.EventBus.Client/HwProj.EventBus.Client.csproj +++ b/HwProj.EventBus/HwProj.EventBus.Client/HwProj.EventBus.Client.csproj @@ -12,10 +12,14 @@ - + + + + + diff --git a/HwProj.EventBus/HwProj.EventBus.Client/Implementations/EventBusRabbitMQ.cs b/HwProj.EventBus/HwProj.EventBus.Client/Implementations/EventBusRabbitMQ.cs index c7de8794b..8a9e6e26a 100644 --- a/HwProj.EventBus/HwProj.EventBus.Client/Implementations/EventBusRabbitMQ.cs +++ b/HwProj.EventBus/HwProj.EventBus.Client/Implementations/EventBusRabbitMQ.cs @@ -3,6 +3,7 @@ using System.Text; using System.Threading.Tasks; using HwProj.EventBus.Client.Interfaces; +using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Newtonsoft.Json; using Polly.Retry; @@ -27,12 +28,12 @@ public class EventBusRabbitMq : IEventBus, IDisposable private readonly Dictionary> _handlers = new(); - public EventBusRabbitMq(IDefaultConnection connection, IServiceProvider serviceProvider, + public EventBusRabbitMq(IDefaultConnection connection, IConfiguration configuration, IServiceScopeFactory scopeFactory, RetryPolicy policy) { _connection = connection; _scopeFactory = scopeFactory; - _queueName = serviceProvider.GetApplicationUniqueIdentifier().Split('\\').Last(); + _queueName = configuration.GetSection("EventBus")["EventBusQueueName"]; _policy = policy; _consumerChannel = CreateConsumerChannel(); } diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/HwProj.NotificationsService.API.csproj b/HwProj.NotificationsService/HwProj.NotificationsService.API/HwProj.NotificationsService.API.csproj index d651aae8f..399462cf9 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/HwProj.NotificationsService.API.csproj +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/HwProj.NotificationsService.API.csproj @@ -15,7 +15,7 @@ - + diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/Services/EmailService.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/Services/EmailService.cs index 91aa54d98..a958d64c7 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/Services/EmailService.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/Services/EmailService.cs @@ -1,6 +1,5 @@ using System; using System.Threading.Tasks; -using Autofac.Core; using HwProj.Models.NotificationsService; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; @@ -11,9 +10,9 @@ namespace HwProj.NotificationsService.API.Services; public class EmailService : IEmailService { private readonly IConfiguration _configuration; - private readonly ILogger _logger; + private readonly ILogger _logger; - public EmailService(IConfiguration configuration, ILogger logger) + public EmailService(IConfiguration configuration, ILogger logger) { _configuration = configuration; _logger = logger; diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.Client/HwProj.NotificationsService.Client.csproj b/HwProj.NotificationsService/HwProj.NotificationsService.Client/HwProj.NotificationsService.Client.csproj index 40616791b..1f0fa7295 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.Client/HwProj.NotificationsService.Client.csproj +++ b/HwProj.NotificationsService/HwProj.NotificationsService.Client/HwProj.NotificationsService.Client.csproj @@ -15,8 +15,8 @@ - - + + diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.Tests/HwProj.NotificationsService.Tests.csproj b/HwProj.NotificationsService/HwProj.NotificationsService.Tests/HwProj.NotificationsService.Tests.csproj index d33a76c34..d8f69f5e3 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.Tests/HwProj.NotificationsService.Tests.csproj +++ b/HwProj.NotificationsService/HwProj.NotificationsService.Tests/HwProj.NotificationsService.Tests.csproj @@ -11,7 +11,7 @@ - + diff --git a/HwProj.SolutionsService/HwProj.SolutionsService.API/Controllers/SolutionsController.cs b/HwProj.SolutionsService/HwProj.SolutionsService.API/Controllers/SolutionsController.cs index ded87eac6..c3ed7a811 100644 --- a/HwProj.SolutionsService/HwProj.SolutionsService.API/Controllers/SolutionsController.cs +++ b/HwProj.SolutionsService/HwProj.SolutionsService.API/Controllers/SolutionsController.cs @@ -1,3 +1,4 @@ +using System; using System.Linq; using System.Net; using System.Threading.Tasks; @@ -160,6 +161,8 @@ public async Task GetCourseStat(long courseId, [FromQuery] string [HttpPost("allUnrated")] public async Task GetAllUnratedSolutionsForTasks([FromBody] long[] taskIds) { + // TODO: Fix + return Array.Empty(); var solutions = await _solutionsRepository .FindAll(t => taskIds.Contains(t.TaskId)) .GroupBy(t => new { t.TaskId, t.StudentId }) diff --git a/HwProj.SolutionsService/HwProj.SolutionsService.API/Startup.cs b/HwProj.SolutionsService/HwProj.SolutionsService.API/Startup.cs index 5f96991c0..643ff9968 100644 --- a/HwProj.SolutionsService/HwProj.SolutionsService.API/Startup.cs +++ b/HwProj.SolutionsService/HwProj.SolutionsService.API/Startup.cs @@ -38,7 +38,7 @@ public void ConfigureServices(IServiceCollection services) services.ConfigureHwProjServices("Solutions API"); } - public void Configure(IApplicationBuilder app, IHostingEnvironment env, IEventBus eventBus) + public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IEventBus eventBus) { app.ConfigureHwProj(env, "Solutions API"); } diff --git a/HwProj.SolutionsService/HwProj.SolutionsService.Client/HwProj.SolutionsService.Client.csproj b/HwProj.SolutionsService/HwProj.SolutionsService.Client/HwProj.SolutionsService.Client.csproj index da3d1d710..5e445b19f 100644 --- a/HwProj.SolutionsService/HwProj.SolutionsService.Client/HwProj.SolutionsService.Client.csproj +++ b/HwProj.SolutionsService/HwProj.SolutionsService.Client/HwProj.SolutionsService.Client.csproj @@ -11,8 +11,8 @@ - - + + From 2650b1637665bba3fb528b23d4c6eb4e03aa601f Mon Sep 17 00:00:00 2001 From: Roman Pozharskiy Date: Tue, 18 Apr 2023 14:43:04 +0300 Subject: [PATCH 04/14] fix multithread usage of db context --- .../Controllers/AccountController.cs | 11 +++----- .../HwProj.AuthService.API.csproj | 2 +- .../Services/AccountService.cs | 26 +++++++++++++++++-- .../Services/IAccountService.cs | 5 ++-- .../Services/IUserManager.cs | 4 ++- .../Services/ProxyUserManager.cs | 9 +++++++ .../StatisticsCourseHomeworksModel.cs | 2 +- .../Configuration/StartupExtensions.cs | 2 +- .../Services/CoursesService.cs | 10 +++---- .../components/Courses/CourseExperimental.tsx | 6 ++--- .../src/components/Courses/StudentStats.tsx | 16 +++++++++--- 11 files changed, 66 insertions(+), 27 deletions(-) diff --git a/HwProj.AuthService/HwProj.AuthService.API/Controllers/AccountController.cs b/HwProj.AuthService/HwProj.AuthService.API/Controllers/AccountController.cs index 5d52797c0..fad248dbf 100644 --- a/HwProj.AuthService/HwProj.AuthService.API/Controllers/AccountController.cs +++ b/HwProj.AuthService/HwProj.AuthService.API/Controllers/AccountController.cs @@ -41,10 +41,7 @@ public async Task GetUserDataById(string userId) [HttpGet("getUsersData")] public async Task GetUsersData([FromBody] string[] userIds) { - var getAccountsDataTasks = userIds.Select(_accountService.GetAccountDataAsync).ToList(); - await Task.WhenAll(getAccountsDataTasks); - - return getAccountsDataTasks.Select(t => t.Result).ToArray(); + return await _accountService.GetManyAccountDataAsync(userIds); } [HttpPost("register")] @@ -77,7 +74,7 @@ public async Task Edit([FromBody] EditAccountViewModel model, str [ProducesResponseType(typeof(Result), (int)HttpStatusCode.OK)] public async Task InviteNewLecturer(InviteLecturerViewModel model) { - var result = await _accountService.InviteNewLecturer(model.Email).ConfigureAwait(false); + var result = await _accountService.InviteNewLecturerAsync(model.Email).ConfigureAwait(false); return Ok(result); } @@ -121,7 +118,7 @@ public async Task GetRolesAsync([FromBody] User user) [ProducesResponseType(typeof(AccountDataDto[]), (int)HttpStatusCode.OK)] public async Task GetAllStudents() { - var allStudents = await _accountService.GetUsersInRole(Roles.StudentRole); + var allStudents = await _accountService.GetUsersInRoleAsync(Roles.StudentRole); var result = allStudents .Select(u => new AccountDataDto(u.Id, u.Name, u.Surname, u.Email, Roles.StudentRole, u.IsExternalAuth, @@ -135,7 +132,7 @@ public async Task GetAllStudents() [ProducesResponseType(typeof(User[]), (int)HttpStatusCode.OK)] public async Task GetAllLecturers() { - var allLecturers = await _accountService.GetUsersInRole(Roles.LecturerRole); + var allLecturers = await _accountService.GetUsersInRoleAsync(Roles.LecturerRole); var result = allLecturers.ToArray(); return Ok(result); diff --git a/HwProj.AuthService/HwProj.AuthService.API/HwProj.AuthService.API.csproj b/HwProj.AuthService/HwProj.AuthService.API/HwProj.AuthService.API.csproj index d16cd35b6..2636636e0 100644 --- a/HwProj.AuthService/HwProj.AuthService.API/HwProj.AuthService.API.csproj +++ b/HwProj.AuthService/HwProj.AuthService.API/HwProj.AuthService.API.csproj @@ -5,7 +5,7 @@ Linux ..\..\docker-compose.dcproj ..\.. - 10 + $(CSharpLanguageVersion) 603911e4-ace8-4439-96f8-1705a0dae761 $(NullableReferenceTypes) diff --git a/HwProj.AuthService/HwProj.AuthService.API/Services/AccountService.cs b/HwProj.AuthService/HwProj.AuthService.API/Services/AccountService.cs index d309cc2b3..90bf74124 100644 --- a/HwProj.AuthService/HwProj.AuthService.API/Services/AccountService.cs +++ b/HwProj.AuthService/HwProj.AuthService.API/Services/AccountService.cs @@ -35,6 +35,7 @@ public AccountService(IUserManager userManager, _mapper = mapper; } + public async Task GetAccountDataAsync(string userId) { var user = await _userManager.FindByIdAsync(userId).ConfigureAwait(false); @@ -49,6 +50,27 @@ public async Task GetAccountDataAsync(string userId) user.MiddleName); } + public async Task GetManyAccountDataAsync(string[] userIds) + { + var users = await _userManager.FindManyByIdAsync(userIds); + if (users == null) + { + return null; + } + + var accountDataDtos = new List(); + + foreach (var user in users) + { + var userRoles = await _userManager.GetRolesAsync(user).ConfigureAwait(false); + var userRole = userRoles.FirstOrDefault() ?? Roles.StudentRole; + accountDataDtos.Add(new AccountDataDto(user.Id, user.Name, user.Surname, user.Email, + userRole, user.IsExternalAuth, user.MiddleName)); + } + + return accountDataDtos.ToArray(); + } + public async Task EditAccountAsync(string id, EditDataDTO model) { var user = await _userManager.FindByIdAsync(id).ConfigureAwait(false); @@ -167,7 +189,7 @@ public async Task> RegisterUserAsync(RegisterDataDTO mo return Result.Failed(result.Errors.Select(errors => errors.Description).ToArray()); } - public async Task InviteNewLecturer(string emailOfInvitedUser) + public async Task InviteNewLecturerAsync(string emailOfInvitedUser) { var invitedUser = await _userManager.FindByEmailAsync(emailOfInvitedUser).ConfigureAwait(false); @@ -193,7 +215,7 @@ public async Task InviteNewLecturer(string emailOfInvitedUser) return Result.Failed("Пользователь уже является преподавателем"); } - public async Task> GetUsersInRole(string role) + public async Task> GetUsersInRoleAsync(string role) { return await _userManager.GetUsersInRoleAsync(role); } diff --git a/HwProj.AuthService/HwProj.AuthService.API/Services/IAccountService.cs b/HwProj.AuthService/HwProj.AuthService.API/Services/IAccountService.cs index 1f5737dad..cb55c2478 100644 --- a/HwProj.AuthService/HwProj.AuthService.API/Services/IAccountService.cs +++ b/HwProj.AuthService/HwProj.AuthService.API/Services/IAccountService.cs @@ -10,10 +10,11 @@ namespace HwProj.AuthService.API.Services; public interface IAccountService { Task GetAccountDataAsync(string userId); + Task GetManyAccountDataAsync(string[] userIds); Task> RegisterUserAsync(RegisterDataDTO model); Task EditAccountAsync(string accountId, EditDataDTO model); Task> LoginUserAsync(LoginViewModel model); Task> LoginUserByGoogleAsync(GoogleJsonWebSignature.Payload payload); - Task InviteNewLecturer(string emailOfInvitedUser); - Task> GetUsersInRole(string role); + Task InviteNewLecturerAsync(string emailOfInvitedUser); + Task> GetUsersInRoleAsync(string role); } \ No newline at end of file diff --git a/HwProj.AuthService/HwProj.AuthService.API/Services/IUserManager.cs b/HwProj.AuthService/HwProj.AuthService.API/Services/IUserManager.cs index 13fe057dc..ff18436e1 100644 --- a/HwProj.AuthService/HwProj.AuthService.API/Services/IUserManager.cs +++ b/HwProj.AuthService/HwProj.AuthService.API/Services/IUserManager.cs @@ -1,4 +1,5 @@ -using System.Collections.Generic; +using System.Collections; +using System.Collections.Generic; using System.Threading.Tasks; using HwProj.Models.AuthService.ViewModels; using Microsoft.AspNetCore.Identity; @@ -10,6 +11,7 @@ public interface IUserManager Task CreateAsync(User user); Task CreateAsync(User user, string password); Task FindByIdAsync(string id); + Task> FindManyByIdAsync(string[] ids); Task FindByEmailAsync(string email); Task UpdateAsync(User user); Task AddToRoleAsync(User user, string role); diff --git a/HwProj.AuthService/HwProj.AuthService.API/Services/ProxyUserManager.cs b/HwProj.AuthService/HwProj.AuthService.API/Services/ProxyUserManager.cs index 7ff2b7ed9..8f9f5bd96 100644 --- a/HwProj.AuthService/HwProj.AuthService.API/Services/ProxyUserManager.cs +++ b/HwProj.AuthService/HwProj.AuthService.API/Services/ProxyUserManager.cs @@ -1,7 +1,9 @@ using System.Collections.Generic; +using System.Linq; using System.Threading.Tasks; using HwProj.Models.AuthService.ViewModels; using Microsoft.AspNetCore.Identity; +using Microsoft.EntityFrameworkCore; namespace HwProj.AuthService.API.Services; @@ -29,6 +31,13 @@ public Task FindByIdAsync(string id) return _aspUserManager.FindByIdAsync(id); } + public async Task> FindManyByIdAsync(string[] ids) + { + var users = await _aspUserManager.Users.Where(user => ids.Contains(user.Id)).ToListAsync(); + return users; + + } + public Task FindByEmailAsync(string email) { return _aspUserManager.FindByEmailAsync(email); diff --git a/HwProj.Common/HwProj.Models/StatisticsService/StatisticsCourseHomeworksModel.cs b/HwProj.Common/HwProj.Models/StatisticsService/StatisticsCourseHomeworksModel.cs index 3a8f0091c..1c7a3465a 100644 --- a/HwProj.Common/HwProj.Models/StatisticsService/StatisticsCourseHomeworksModel.cs +++ b/HwProj.Common/HwProj.Models/StatisticsService/StatisticsCourseHomeworksModel.cs @@ -4,6 +4,6 @@ namespace HwProj.Models.StatisticsService; public class StatisticsCourseHomeworksModel { - public long? Id; + public long? Id { get; set; } public List Tasks { get; set; } = new(); } \ No newline at end of file diff --git a/HwProj.Common/HwProj.Utils/Configuration/StartupExtensions.cs b/HwProj.Common/HwProj.Utils/Configuration/StartupExtensions.cs index 1097579d6..d90b0b4b1 100644 --- a/HwProj.Common/HwProj.Utils/Configuration/StartupExtensions.cs +++ b/HwProj.Common/HwProj.Utils/Configuration/StartupExtensions.cs @@ -22,7 +22,7 @@ namespace HwProj.Utils.Configuration; -public static class StartupExtensions +public static class StartupExtensions { public static IServiceCollection ConfigureHwProjServices(this IServiceCollection services, string serviceName) { diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Services/CoursesService.cs b/HwProj.CoursesService/HwProj.CoursesService.API/Services/CoursesService.cs index f1f6d3d54..565e8806c 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Services/CoursesService.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.API/Services/CoursesService.cs @@ -80,13 +80,11 @@ public async Task UpdateAsync(long courseId, Course updated) public async Task AddStudentAsync(long courseId, string studentId) { - var getCourseTask = _coursesRepository.GetAsync(courseId); - var getCourseMateTask = - _courseMatesRepository.FindAsync(cm => cm.CourseId == courseId && cm.StudentId == studentId); - await Task.WhenAll(getCourseTask, getCourseMateTask); + var course = await _coursesRepository.GetAsync(courseId); + var cm = await _courseMatesRepository.FindAsync( + mate => mate.CourseId == courseId && mate.StudentId == studentId); - var course = getCourseTask.Result; - if (course == null || getCourseMateTask.Result != null) + if (course == null || cm != null) { return false; } diff --git a/hwproj.front/src/components/Courses/CourseExperimental.tsx b/hwproj.front/src/components/Courses/CourseExperimental.tsx index 27fddce24..ff7ab3efa 100644 --- a/hwproj.front/src/components/Courses/CourseExperimental.tsx +++ b/hwproj.front/src/components/Courses/CourseExperimental.tsx @@ -40,12 +40,12 @@ interface ICourseExperimentalState { const CourseExperimental: FC = (props) => { const homeworks = props.homeworks.slice().reverse() const {isMentor, studentSolutions, isStudentAccepted, userId} = props - + const [state, setState] = useState({ selectedItem: { isHomework: true, - id: homeworks && homeworks[0].id, - data: homeworks && homeworks[0] + id: homeworks && homeworks.length > 0 ? homeworks[0].id : undefined, + data: homeworks && homeworks.length > 0 ? homeworks[0] : undefined } }) diff --git a/hwproj.front/src/components/Courses/StudentStats.tsx b/hwproj.front/src/components/Courses/StudentStats.tsx index 1b3e513ae..d3695b16d 100644 --- a/hwproj.front/src/components/Courses/StudentStats.tsx +++ b/hwproj.front/src/components/Courses/StudentStats.tsx @@ -102,7 +102,17 @@ class StudentStats extends React.Component {homeworks.map((homework) => - homework.tasks!.map((task) => ( + homework.tasks!.map((task) => { + //console.log(cm) + // console.log(solutions) + console.log(solutions) + // console.log(homeworks) + // console.log(homework) + //console.log(task) + //console.log(solutions + // .find(s => s.id == cm.id)!.homeworks! + // .find(h => h.id == homework.id)) + return( s.id == cm.id)!.homeworks! @@ -112,8 +122,8 @@ class StudentStats extends React.Component - )) + taskMaxRating={task.maxRating!}/>) + }) )} ))} From df13ecbb67895cac230852413c2cd6fb5d349201 Mon Sep 17 00:00:00 2001 From: Roman Pozharskiy Date: Tue, 18 Apr 2023 17:40:49 +0300 Subject: [PATCH 05/14] fix add student to course --- .../HwProj.CoursesService.API/Services/CoursesService.cs | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Services/CoursesService.cs b/HwProj.CoursesService/HwProj.CoursesService.API/Services/CoursesService.cs index 565e8806c..4114f1112 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Services/CoursesService.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.API/Services/CoursesService.cs @@ -127,12 +127,6 @@ await _courseMatesRepository.UpdateAsync( ); var course = getCourseTask.Result; - var courseMate = new CourseMate - { - CourseId = courseId, - StudentId = studentId, - IsAccepted = false - }; _eventBus.Publish(new LecturerAcceptToCourseEvent { @@ -198,7 +192,7 @@ public async Task GetUserCoursesAsync(string userId) public async Task AcceptLecturerAsync(long courseId, string lecturerEmail) { var userId = await _authServiceClient.FindByEmailAsync(lecturerEmail); - if (!(userId is null)) + if (userId is not null) { var course = await _coursesRepository.GetAsync(courseId); var user = await _authServiceClient.GetAccountData(userId); From f4b1d967f8f985f1abced8b18b05cb7549aaa69a Mon Sep 17 00:00:00 2001 From: Roman Pozharskiy Date: Thu, 27 Apr 2023 12:51:50 +0300 Subject: [PATCH 06/14] order users by id in GetManyAccountData; remove ProxyUserManager --- .../Controllers/CoursesController.cs | 11 ++- .../Controllers/AccountController.cs | 22 ++++- .../HwProj.AuthService.API.csproj | 1 + .../Services/AccountService.cs | 25 +++--- .../Services/IUserManager.cs | 24 ------ .../Services/ProxyUserManager.cs | 85 ------------------- .../HwProj.AuthService.API/Startup.cs | 6 +- .../Services/CoursesService.cs | 28 +++--- .../Controllers/SolutionsController.cs | 2 +- .../src/components/Courses/StudentStats.tsx | 14 +-- 10 files changed, 61 insertions(+), 157 deletions(-) delete mode 100644 HwProj.AuthService/HwProj.AuthService.API/Services/IUserManager.cs delete mode 100644 HwProj.AuthService/HwProj.AuthService.API/Services/ProxyUserManager.cs diff --git a/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/CoursesController.cs b/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/CoursesController.cs index ddeae9d32..b178ff9b3 100644 --- a/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/CoursesController.cs +++ b/HwProj.APIGateway/HwProj.APIGateway.API/Controllers/CoursesController.cs @@ -46,7 +46,6 @@ public async Task GetCourseData(long courseId) var getMentorsTask = AuthServiceClient.GetAccountsData(course.MentorIds); await Task.WhenAll(getStudentsTask, getMentorsTask); - var students = getStudentsTask.Result; var acceptedStudents = new List(); @@ -54,8 +53,14 @@ public async Task GetCourseData(long courseId) for (var i = 0; i < students.Length; i++) { if (!(students[i] is { } student)) continue; - if (course.CourseMates[i].IsAccepted) acceptedStudents.Add(student); - else newStudents.Add(student); + if (course.CourseMates[i].IsAccepted) + { + acceptedStudents.Add(students[i]); + } + else + { + newStudents.Add(student); + } } var result = new CourseViewModel diff --git a/HwProj.AuthService/HwProj.AuthService.API/Controllers/AccountController.cs b/HwProj.AuthService/HwProj.AuthService.API/Controllers/AccountController.cs index fad248dbf..c9db48b29 100644 --- a/HwProj.AuthService/HwProj.AuthService.API/Controllers/AccountController.cs +++ b/HwProj.AuthService/HwProj.AuthService.API/Controllers/AccountController.cs @@ -1,4 +1,5 @@ -using System.Linq; +using System.Collections.Generic; +using System.Linq; using System.Net; using System.Threading.Tasks; using AutoMapper; @@ -9,6 +10,7 @@ using HwProj.Models.Result; using Google.Apis.Auth; using HwProj.Models.Roles; +using Microsoft.AspNetCore.Identity; namespace HwProj.AuthService.API.Controllers; @@ -17,10 +19,10 @@ namespace HwProj.AuthService.API.Controllers; public class AccountController : Controller { private readonly IAccountService _accountService; - private readonly IUserManager _userManager; + private readonly UserManager _userManager; private readonly IMapper _mapper; - public AccountController(IAccountService accountService, IUserManager userManager, IMapper mapper) + public AccountController(IAccountService accountService, UserManager userManager, IMapper mapper) { _accountService = accountService; _userManager = userManager; @@ -41,7 +43,19 @@ public async Task GetUserDataById(string userId) [HttpGet("getUsersData")] public async Task GetUsersData([FromBody] string[] userIds) { - return await _accountService.GetManyAccountDataAsync(userIds); + // var list = new List(); + // foreach (var id in userIds) + // { + // list.Add(await _accountService.GetAccountDataAsync(id)); + // } + // + // return list.ToArray(); + var many = await _accountService.GetManyAccountDataAsync(userIds); + return many; + + var userDataTasks = userIds.Select(_accountService.GetAccountDataAsync).ToArray(); + await Task.WhenAll(userDataTasks); + return userDataTasks.Select(task => task.Result).ToArray(); } [HttpPost("register")] diff --git a/HwProj.AuthService/HwProj.AuthService.API/HwProj.AuthService.API.csproj b/HwProj.AuthService/HwProj.AuthService.API/HwProj.AuthService.API.csproj index 2636636e0..06a2dbc61 100644 --- a/HwProj.AuthService/HwProj.AuthService.API/HwProj.AuthService.API.csproj +++ b/HwProj.AuthService/HwProj.AuthService.API/HwProj.AuthService.API.csproj @@ -15,6 +15,7 @@ + diff --git a/HwProj.AuthService/HwProj.AuthService.API/Services/AccountService.cs b/HwProj.AuthService/HwProj.AuthService.API/Services/AccountService.cs index 90bf74124..6f02713f2 100644 --- a/HwProj.AuthService/HwProj.AuthService.API/Services/AccountService.cs +++ b/HwProj.AuthService/HwProj.AuthService.API/Services/AccountService.cs @@ -11,18 +11,19 @@ using HwProj.Models.AuthService.DTO; using HwProj.Models.AuthService.ViewModels; using HwProj.Models.Result; +using Microsoft.EntityFrameworkCore; namespace HwProj.AuthService.API.Services; public class AccountService : IAccountService { - private readonly IUserManager _userManager; + private readonly UserManager _userManager; private readonly SignInManager _signInManager; private readonly IAuthTokenService _tokenService; private readonly IEventBus _eventBus; private readonly IMapper _mapper; - public AccountService(IUserManager userManager, + public AccountService(UserManager userManager, SignInManager signInManager, IAuthTokenService authTokenService, IEventBus eventBus, @@ -49,26 +50,28 @@ public async Task GetAccountDataAsync(string userId) return new AccountDataDto(user.Id, user.Name, user.Surname, user.Email, userRole, user.IsExternalAuth, user.MiddleName); } - + public async Task GetManyAccountDataAsync(string[] userIds) { - var users = await _userManager.FindManyByIdAsync(userIds); - if (users == null) + var users = await _userManager.Users.Where(user => userIds.Contains(user.Id)).ToArrayAsync().ConfigureAwait(false); + var orderedByIdUsers = new User[users.Length]; + for (var i = 0; i < users.Length; i++) { - return null; + orderedByIdUsers[i] = users.First(user => user.Id == userIds[i]); } + + var usersDto = new List(); - var accountDataDtos = new List(); - - foreach (var user in users) + // TODO сразу роли получить + foreach (var user in orderedByIdUsers) { var userRoles = await _userManager.GetRolesAsync(user).ConfigureAwait(false); var userRole = userRoles.FirstOrDefault() ?? Roles.StudentRole; - accountDataDtos.Add(new AccountDataDto(user.Id, user.Name, user.Surname, user.Email, + usersDto.Add(new AccountDataDto(user.Id, user.Name, user.Surname, user.Email, userRole, user.IsExternalAuth, user.MiddleName)); } - return accountDataDtos.ToArray(); + return usersDto.ToArray(); } public async Task EditAccountAsync(string id, EditDataDTO model) diff --git a/HwProj.AuthService/HwProj.AuthService.API/Services/IUserManager.cs b/HwProj.AuthService/HwProj.AuthService.API/Services/IUserManager.cs deleted file mode 100644 index ff18436e1..000000000 --- a/HwProj.AuthService/HwProj.AuthService.API/Services/IUserManager.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System.Collections; -using System.Collections.Generic; -using System.Threading.Tasks; -using HwProj.Models.AuthService.ViewModels; -using Microsoft.AspNetCore.Identity; - -namespace HwProj.AuthService.API.Services; - -public interface IUserManager -{ - Task CreateAsync(User user); - Task CreateAsync(User user, string password); - Task FindByIdAsync(string id); - Task> FindManyByIdAsync(string[] ids); - Task FindByEmailAsync(string email); - Task UpdateAsync(User user); - Task AddToRoleAsync(User user, string role); - Task RemoveFromRoleAsync(User user, string role); - Task> GetRolesAsync(User user); - Task IsEmailConfirmedAsync(User user); - Task CheckPasswordAsync(User user, string password); - Task ChangePasswordAsync(User user, string currentPassword, string newPassword); - Task> GetUsersInRoleAsync(string role); -} \ No newline at end of file diff --git a/HwProj.AuthService/HwProj.AuthService.API/Services/ProxyUserManager.cs b/HwProj.AuthService/HwProj.AuthService.API/Services/ProxyUserManager.cs deleted file mode 100644 index 8f9f5bd96..000000000 --- a/HwProj.AuthService/HwProj.AuthService.API/Services/ProxyUserManager.cs +++ /dev/null @@ -1,85 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using HwProj.Models.AuthService.ViewModels; -using Microsoft.AspNetCore.Identity; -using Microsoft.EntityFrameworkCore; - -namespace HwProj.AuthService.API.Services; - -public class ProxyUserManager : IUserManager -{ - private readonly UserManager _aspUserManager; - - public ProxyUserManager(UserManager aspUserManager) - { - _aspUserManager = aspUserManager; - } - - public Task CreateAsync(User user) - { - return _aspUserManager.CreateAsync(user); - } - - public Task CreateAsync(User user, string password) - { - return _aspUserManager.CreateAsync(user, password); - } - - public Task FindByIdAsync(string id) - { - return _aspUserManager.FindByIdAsync(id); - } - - public async Task> FindManyByIdAsync(string[] ids) - { - var users = await _aspUserManager.Users.Where(user => ids.Contains(user.Id)).ToListAsync(); - return users; - - } - - public Task FindByEmailAsync(string email) - { - return _aspUserManager.FindByEmailAsync(email); - } - - public Task UpdateAsync(User user) - { - return _aspUserManager.UpdateAsync(user); - } - - public Task AddToRoleAsync(User user, string role) - { - return _aspUserManager.AddToRoleAsync(user, role); - } - - public Task RemoveFromRoleAsync(User user, string role) - { - return _aspUserManager.RemoveFromRoleAsync(user, role); - } - - public Task> GetRolesAsync(User user) - { - return _aspUserManager.GetRolesAsync(user); - } - - public Task IsEmailConfirmedAsync(User user) - { - return _aspUserManager.IsEmailConfirmedAsync(user); - } - - public Task CheckPasswordAsync(User user, string password) - { - return _aspUserManager.CheckPasswordAsync(user, password); - } - - public Task ChangePasswordAsync(User user, string currentPassword, string newPassword) - { - return _aspUserManager.ChangePasswordAsync(user, currentPassword, newPassword); - } - - public Task> GetUsersInRoleAsync(string role) - { - return _aspUserManager.GetUsersInRoleAsync(role); - } -} \ No newline at end of file diff --git a/HwProj.AuthService/HwProj.AuthService.API/Startup.cs b/HwProj.AuthService/HwProj.AuthService.API/Startup.cs index 6df22fa4c..ff00186da 100644 --- a/HwProj.AuthService/HwProj.AuthService.API/Startup.cs +++ b/HwProj.AuthService/HwProj.AuthService.API/Startup.cs @@ -27,8 +27,6 @@ public Startup(IConfiguration configuration) public void ConfigureServices(IServiceCollection services) { - services.ConfigureHwProjServices("AuthService API"); - //var appSettingsSection = Configuration.GetSection("AppSettings"); //services.Configure(appSettingsSection); @@ -81,8 +79,8 @@ public void ConfigureServices(IServiceCollection services) services.AddEventBus(Configuration); services.AddScoped() - .AddScoped() - .AddScoped(); + .AddScoped(); + services.ConfigureHwProjServices("AuthService API"); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Services/CoursesService.cs b/HwProj.CoursesService/HwProj.CoursesService.API/Services/CoursesService.cs index 4114f1112..c4d951c73 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Services/CoursesService.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.API/Services/CoursesService.cs @@ -80,23 +80,23 @@ public async Task UpdateAsync(long courseId, Course updated) public async Task AddStudentAsync(long courseId, string studentId) { - var course = await _coursesRepository.GetAsync(courseId); - var cm = await _courseMatesRepository.FindAsync( - mate => mate.CourseId == courseId && mate.StudentId == studentId); - - if (course == null || cm != null) + var course = await _coursesRepository.GetAsync(courseId); + var courseMate = + await _courseMatesRepository.FindAsync(cm => cm.CourseId == courseId && cm.StudentId == studentId); + + if (course == null || courseMate != null) { return false; } - var courseMate = new CourseMate + var newCourseMate = new CourseMate { CourseId = courseId, StudentId = studentId, IsAccepted = false }; - await _courseMatesRepository.AddAsync(courseMate); + await _courseMatesRepository.AddAsync(newCourseMate); _eventBus.Publish(new NewCourseMateEvent { CourseId = courseId, @@ -111,10 +111,11 @@ public async Task AddStudentAsync(long courseId, string studentId) public async Task AcceptCourseMateAsync(long courseId, string studentId) { + // TODO вместе с courseMate получать var getCourseTask = _coursesRepository.GetAsync(courseId); var getCourseMateTask = _courseMatesRepository.FindAsync(cm => cm.CourseId == courseId && cm.StudentId == studentId); - await Task.WhenAll(getCourseTask, getCourseMateTask); + await Task.WhenAll(getCourseTask, getCourseMateTask).ConfigureAwait(false); if (getCourseTask.Result == null || getCourseMateTask.Result == null) { @@ -123,8 +124,11 @@ public async Task AcceptCourseMateAsync(long courseId, string studentId) await _courseMatesRepository.UpdateAsync( getCourseMateTask.Result.Id, - cm => new CourseMate { IsAccepted = true } - ); + cm => new CourseMate + { + IsAccepted = true + } + ).ConfigureAwait(false); var course = getCourseTask.Result; @@ -144,14 +148,14 @@ public async Task RejectCourseMateAsync(long courseId, string studentId) var getCourseTask = _coursesRepository.GetAsync(courseId); var getCourseMateTask = _courseMatesRepository.FindAsync(cm => cm.CourseId == courseId && cm.StudentId == studentId); - await Task.WhenAll(getCourseTask, getCourseMateTask); + await Task.WhenAll(getCourseTask, getCourseMateTask).ConfigureAwait(false); if (getCourseTask.Result == null || getCourseMateTask.Result == null) { return false; } - await _courseMatesRepository.DeleteAsync(getCourseMateTask.Result.Id); + await _courseMatesRepository.DeleteAsync(getCourseMateTask.Result.Id).ConfigureAwait(false); var course = getCourseTask.Result; _eventBus.Publish(new LecturerRejectToCourseEvent diff --git a/HwProj.SolutionsService/HwProj.SolutionsService.API/Controllers/SolutionsController.cs b/HwProj.SolutionsService/HwProj.SolutionsService.API/Controllers/SolutionsController.cs index c3ed7a811..e0bf6d469 100644 --- a/HwProj.SolutionsService/HwProj.SolutionsService.API/Controllers/SolutionsController.cs +++ b/HwProj.SolutionsService/HwProj.SolutionsService.API/Controllers/SolutionsController.cs @@ -48,7 +48,7 @@ public async Task GetSolution(long solutionId) var solution = await _solutionsService.GetSolutionAsync(solutionId); return solution == null ? NotFound() - : Ok(solution) as IActionResult; + : Ok(solution); } [HttpGet("taskSolutions/{taskId}/{studentId}")] diff --git a/hwproj.front/src/components/Courses/StudentStats.tsx b/hwproj.front/src/components/Courses/StudentStats.tsx index d3695b16d..07bc5fdf0 100644 --- a/hwproj.front/src/components/Courses/StudentStats.tsx +++ b/hwproj.front/src/components/Courses/StudentStats.tsx @@ -102,18 +102,7 @@ class StudentStats extends React.Component {homeworks.map((homework) => - homework.tasks!.map((task) => { - //console.log(cm) - // console.log(solutions) - console.log(solutions) - // console.log(homeworks) - // console.log(homework) - //console.log(task) - //console.log(solutions - // .find(s => s.id == cm.id)!.homeworks! - // .find(h => h.id == homework.id)) - return( - s.id == cm.id)!.homeworks! .find(h => h.id == homework.id)!.tasks! @@ -123,7 +112,6 @@ class StudentStats extends React.Component) - }) )} ))} From 55bbe915ea95ff60fbd0add40f9687e5cd61df39 Mon Sep 17 00:00:00 2001 From: Roman Pozharskiy Date: Thu, 27 Apr 2023 13:41:44 +0300 Subject: [PATCH 07/14] replace course, cm tasks with course with cm task --- .../Services/AccountService.cs | 3 +- .../Services/CoursesService.cs | 52 ++++++++++--------- 2 files changed, 29 insertions(+), 26 deletions(-) diff --git a/HwProj.AuthService/HwProj.AuthService.API/Services/AccountService.cs b/HwProj.AuthService/HwProj.AuthService.API/Services/AccountService.cs index 6f02713f2..36ecd18fb 100644 --- a/HwProj.AuthService/HwProj.AuthService.API/Services/AccountService.cs +++ b/HwProj.AuthService/HwProj.AuthService.API/Services/AccountService.cs @@ -53,13 +53,12 @@ public async Task GetAccountDataAsync(string userId) public async Task GetManyAccountDataAsync(string[] userIds) { - var users = await _userManager.Users.Where(user => userIds.Contains(user.Id)).ToArrayAsync().ConfigureAwait(false); + var users = await _userManager.Users.Where(user => userIds.Contains(user.Id)). ToArrayAsync().ConfigureAwait(false); var orderedByIdUsers = new User[users.Length]; for (var i = 0; i < users.Length; i++) { orderedByIdUsers[i] = users.First(user => user.Id == userIds[i]); } - var usersDto = new List(); // TODO сразу роли получить diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Services/CoursesService.cs b/HwProj.CoursesService/HwProj.CoursesService.API/Services/CoursesService.cs index c4d951c73..055040de1 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Services/CoursesService.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.API/Services/CoursesService.cs @@ -80,11 +80,14 @@ public async Task UpdateAsync(long courseId, Course updated) public async Task AddStudentAsync(long courseId, string studentId) { - var course = await _coursesRepository.GetAsync(courseId); - var courseMate = - await _courseMatesRepository.FindAsync(cm => cm.CourseId == courseId && cm.StudentId == studentId); - - if (course == null || courseMate != null) + var course = await _coursesRepository.GetWithCourseMatesAsync(courseId); + if (course == null) + { + return false; + } + + var courseMate = course.CourseMates.FirstOrDefault(cm => cm.StudentId == studentId); + if (courseMate != null) { return false; } @@ -111,26 +114,26 @@ public async Task AddStudentAsync(long courseId, string studentId) public async Task AcceptCourseMateAsync(long courseId, string studentId) { - // TODO вместе с courseMate получать - var getCourseTask = _coursesRepository.GetAsync(courseId); - var getCourseMateTask = - _courseMatesRepository.FindAsync(cm => cm.CourseId == courseId && cm.StudentId == studentId); - await Task.WhenAll(getCourseTask, getCourseMateTask).ConfigureAwait(false); - - if (getCourseTask.Result == null || getCourseMateTask.Result == null) + var course = await _coursesRepository.GetWithCourseMatesAsync(courseId).ConfigureAwait(false); + if (course == null) + { + return false; + } + + var courseMate = course.CourseMates.FirstOrDefault(cm => cm.StudentId == studentId); + if (courseMate == null) { return false; } await _courseMatesRepository.UpdateAsync( - getCourseMateTask.Result.Id, + courseMate.Id, cm => new CourseMate { IsAccepted = true } ).ConfigureAwait(false); - - var course = getCourseTask.Result; + _eventBus.Publish(new LecturerAcceptToCourseEvent { @@ -145,19 +148,20 @@ await _courseMatesRepository.UpdateAsync( public async Task RejectCourseMateAsync(long courseId, string studentId) { - var getCourseTask = _coursesRepository.GetAsync(courseId); - var getCourseMateTask = - _courseMatesRepository.FindAsync(cm => cm.CourseId == courseId && cm.StudentId == studentId); - await Task.WhenAll(getCourseTask, getCourseMateTask).ConfigureAwait(false); - - if (getCourseTask.Result == null || getCourseMateTask.Result == null) + var course = await _coursesRepository.GetWithCourseMatesAsync(courseId); + if (course == null) { return false; } - await _courseMatesRepository.DeleteAsync(getCourseMateTask.Result.Id).ConfigureAwait(false); - - var course = getCourseTask.Result; + var courseMate = course.CourseMates.FirstOrDefault(cm => cm.StudentId == studentId); + if (courseMate == null) + { + return false; + } + + await _courseMatesRepository.DeleteAsync(courseMate.Id).ConfigureAwait(false); + _eventBus.Publish(new LecturerRejectToCourseEvent { CourseId = courseId, From c8daa95b2363387eaf1d93f95afd6669da60efea Mon Sep 17 00:00:00 2001 From: Roman Pozharskiy Date: Mon, 1 May 2023 17:56:10 +0300 Subject: [PATCH 08/14] reading roles in single request --- .../Controllers/AccountController.cs | 14 +------------- .../Services/AccountService.cs | 8 ++++---- 2 files changed, 5 insertions(+), 17 deletions(-) diff --git a/HwProj.AuthService/HwProj.AuthService.API/Controllers/AccountController.cs b/HwProj.AuthService/HwProj.AuthService.API/Controllers/AccountController.cs index c9db48b29..8fb1ab465 100644 --- a/HwProj.AuthService/HwProj.AuthService.API/Controllers/AccountController.cs +++ b/HwProj.AuthService/HwProj.AuthService.API/Controllers/AccountController.cs @@ -43,19 +43,7 @@ public async Task GetUserDataById(string userId) [HttpGet("getUsersData")] public async Task GetUsersData([FromBody] string[] userIds) { - // var list = new List(); - // foreach (var id in userIds) - // { - // list.Add(await _accountService.GetAccountDataAsync(id)); - // } - // - // return list.ToArray(); - var many = await _accountService.GetManyAccountDataAsync(userIds); - return many; - - var userDataTasks = userIds.Select(_accountService.GetAccountDataAsync).ToArray(); - await Task.WhenAll(userDataTasks); - return userDataTasks.Select(task => task.Result).ToArray(); + return await _accountService.GetManyAccountDataAsync(userIds); } [HttpPost("register")] diff --git a/HwProj.AuthService/HwProj.AuthService.API/Services/AccountService.cs b/HwProj.AuthService/HwProj.AuthService.API/Services/AccountService.cs index 36ecd18fb..06686472c 100644 --- a/HwProj.AuthService/HwProj.AuthService.API/Services/AccountService.cs +++ b/HwProj.AuthService/HwProj.AuthService.API/Services/AccountService.cs @@ -53,19 +53,19 @@ public async Task GetAccountDataAsync(string userId) public async Task GetManyAccountDataAsync(string[] userIds) { - var users = await _userManager.Users.Where(user => userIds.Contains(user.Id)). ToArrayAsync().ConfigureAwait(false); + var users = await _userManager.Users.Where(user => userIds.Contains(user.Id)).ToArrayAsync().ConfigureAwait(false); var orderedByIdUsers = new User[users.Length]; for (var i = 0; i < users.Length; i++) { orderedByIdUsers[i] = users.First(user => user.Id == userIds[i]); } + var usersDto = new List(); - + var lecturerIds = (await _userManager.GetUsersInRoleAsync(Roles.LecturerRole)).Select(l => l.Id).ToHashSet(); // TODO сразу роли получить foreach (var user in orderedByIdUsers) { - var userRoles = await _userManager.GetRolesAsync(user).ConfigureAwait(false); - var userRole = userRoles.FirstOrDefault() ?? Roles.StudentRole; + var userRole = lecturerIds.Contains(user.Id) ? Roles.LecturerRole : Roles.StudentRole; usersDto.Add(new AccountDataDto(user.Id, user.Name, user.Surname, user.Email, userRole, user.IsExternalAuth, user.MiddleName)); } From 2531c22b9180cde97619bca076cd1c13117cb8ae Mon Sep 17 00:00:00 2001 From: Roman Pozharskiy Date: Sat, 6 May 2023 10:06:46 +0300 Subject: [PATCH 09/14] install isomorphic fetch --- hwproj.front/package-lock.json | 38 ++++++++++++++++++++++++++++++++++ hwproj.front/package.json | 1 + 2 files changed, 39 insertions(+) diff --git a/hwproj.front/package-lock.json b/hwproj.front/package-lock.json index a1cfcfd33..f8326b2fa 100644 --- a/hwproj.front/package-lock.json +++ b/hwproj.front/package-lock.json @@ -14648,6 +14648,44 @@ "integrity": "sha512-S/2fF5wH8SJA/kmwr6HYhK/RI/OkhD84k8ntalo0iJjZikgq1XFvR5M8NPT1x5F7fBwCG3qHfnzeP/Vh/ZxCUA==", "dev": true }, + "isomorphic-fetch": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/isomorphic-fetch/-/isomorphic-fetch-3.0.0.tgz", + "integrity": "sha512-qvUtwJ3j6qwsF3jLxkZ72qCgjMysPzDfeV240JHiGZsANBYd+EEuu35v7dfrJ9Up0Ak07D7GGSkGhCHTqg/5wA==", + "requires": { + "node-fetch": "^2.6.1", + "whatwg-fetch": "^3.4.1" + }, + "dependencies": { + "node-fetch": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.9.tgz", + "integrity": "sha512-DJm/CJkZkRjKKj4Zi4BsKVZh3ValV5IR5s7LVZnW+6YMh0W1BfNA8XSs6DLMGYlId5F3KnA70uu2qepcR08Qqg==", + "requires": { + "whatwg-url": "^5.0.0" + } + }, + "tr46": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", + "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==" + }, + "webidl-conversions": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", + "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==" + }, + "whatwg-url": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", + "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", + "requires": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + } + } + } + }, "istanbul-lib-coverage": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.0.0.tgz", diff --git a/hwproj.front/package.json b/hwproj.front/package.json index 79c2bca5f..309914d1b 100644 --- a/hwproj.front/package.json +++ b/hwproj.front/package.json @@ -30,6 +30,7 @@ "dotenv": "^10.0.0", "es6-promise": "^4.2.8", "html-react-parser": "^1.2.8", + "isomorphic-fetch": "^3.0.0", "jwt-decode": "^3.1.2", "lowdb": "^1.0.0", "portable-fetch": "^3.0.0", From 0993c0ef2372c625f71d7b62600f6ac808aa0892 Mon Sep 17 00:00:00 2001 From: Roman Pozharskiy Date: Sun, 7 May 2023 18:34:15 +0300 Subject: [PATCH 10/14] edit swagger options; generate new typescript fetch client --- .../Configuration/StartupExtensions.cs | 8 +- .../HwProj.Utils/StringExtensions.cs | 21 + hwproj.front/src/api/api.ts | 498 +++++++++--------- 3 files changed, 279 insertions(+), 248 deletions(-) create mode 100644 HwProj.Common/HwProj.Utils/StringExtensions.cs diff --git a/HwProj.Common/HwProj.Utils/Configuration/StartupExtensions.cs b/HwProj.Common/HwProj.Utils/Configuration/StartupExtensions.cs index d90b0b4b1..c5fc63d36 100644 --- a/HwProj.Common/HwProj.Utils/Configuration/StartupExtensions.cs +++ b/HwProj.Common/HwProj.Utils/Configuration/StartupExtensions.cs @@ -35,15 +35,17 @@ public static IServiceCollection ConfigureHwProjServices(this IServiceCollection services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = serviceName, Version = "v1" }); + c.CustomOperationIds(selector => selector.RelativePath.ToCamelCase(selector.HttpMethod)); + c.UseInlineDefinitionsForEnums(); if (serviceName == "API Gateway") { var securityScheme = new OpenApiSecurityScheme { - Name = "Bearer", + Name = "Authorization", Description = "Enter JWT Bearer token _only_", In = ParameterLocation.Header, - Type = SecuritySchemeType.Http, + Type = SecuritySchemeType.ApiKey, Scheme = "bearer", BearerFormat = "JWT", Reference = new OpenApiReference @@ -137,7 +139,7 @@ public static IApplicationBuilder ConfigureHwProj(this IApplicationBuilder app, if (env.IsDevelopment()) { app.UseDeveloperExceptionPage() - .UseSwagger() + .UseSwagger(options => options.SerializeAsV2 = true) .UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", serviceName); }); } else diff --git a/HwProj.Common/HwProj.Utils/StringExtensions.cs b/HwProj.Common/HwProj.Utils/StringExtensions.cs new file mode 100644 index 000000000..04bd7e94f --- /dev/null +++ b/HwProj.Common/HwProj.Utils/StringExtensions.cs @@ -0,0 +1,21 @@ +using System; +using System.Linq; +using System.Text; + +namespace HwProj.Utils; + +public static class StringExtensions +{ + public static string ToCamelCase(this string route, string httpMethod) + { + var formattedRoute = new StringBuilder(route).Append($"/{httpMethod.ToLower()}"); + formattedRoute.Replace("{", "By/").Replace("}", string.Empty); + var camelCaseRoute = formattedRoute.ToString().Split('/').Select(s => s.FirstCharToUpperCase()); + return string.Join(string.Empty, camelCaseRoute); + } + + public static string FirstCharToUpperCase(this string s) + { + return $"{s[0].ToString().ToUpper()}{s.AsSpan(1)}"; + } +} \ No newline at end of file diff --git a/hwproj.front/src/api/api.ts b/hwproj.front/src/api/api.ts index fcd7ebf5c..a82f3df62 100644 --- a/hwproj.front/src/api/api.ts +++ b/hwproj.front/src/api/api.ts @@ -55,7 +55,7 @@ export interface FetchArgs { * @class BaseAPI */ export class BaseAPI { - protected configuration!: Configuration; + protected configuration: Configuration; constructor(configuration?: Configuration, protected basePath: string = BASE_PATH, protected fetch: FetchAPI = portableFetch) { if (configuration) { @@ -72,7 +72,7 @@ export class BaseAPI { * @extends {Error} */ export class RequiredError extends Error { - name!: "RequiredError" + name: "RequiredError" constructor(public field: string, msg?: string) { super(msg); } @@ -810,32 +810,6 @@ export interface Result { errors?: Array; } -/** - * - * @export - * @interface ResultTokenCredentials - */ -export interface ResultTokenCredentials { - /** - * - * @type {TokenCredentials} - * @memberof ResultTokenCredentials - */ - value?: TokenCredentials; - /** - * - * @type {boolean} - * @memberof ResultTokenCredentials - */ - succeeded?: boolean; - /** - * - * @type {Array} - * @memberof ResultTokenCredentials - */ - errors?: Array; -} - /** * * @export @@ -928,10 +902,10 @@ export namespace Solution { export interface SolutionPreviewView { /** * - * @type {AccountDataDto} + * @type {TaskDeadlineViewDeadline} * @memberof SolutionPreviewView */ - student?: AccountDataDto; + student?: TaskDeadlineViewDeadline; /** * * @type {string} @@ -1206,10 +1180,10 @@ export interface TaskDeadlineDto { export interface TaskDeadlineView { /** * - * @type {TaskDeadlineDto} + * @type {TaskDeadlineViewDeadline} * @memberof TaskDeadlineView */ - deadline?: TaskDeadlineDto; + deadline?: TaskDeadlineViewDeadline; /** * * @type {number} @@ -1246,6 +1220,14 @@ export namespace TaskDeadlineView { } } +/** + * + * @export + * @interface TaskDeadlineViewDeadline + */ +export interface TaskDeadlineViewDeadline { +} + /** * * @export @@ -1260,6 +1242,32 @@ export interface TokenCredentials { accessToken?: string; } +/** + * + * @export + * @interface TokenCredentialsResult + */ +export interface TokenCredentialsResult { + /** + * + * @type {TaskDeadlineViewDeadline} + * @memberof TokenCredentialsResult + */ + value?: TaskDeadlineViewDeadline; + /** + * + * @type {boolean} + * @memberof TokenCredentialsResult + */ + succeeded?: boolean; + /** + * + * @type {Array} + * @memberof TokenCredentialsResult + */ + errors?: Array; +} + /** * * @export @@ -1340,10 +1348,10 @@ export interface UpdateGroupViewModel { export interface UserDataDto { /** * - * @type {AccountDataDto} + * @type {TaskDeadlineViewDeadline} * @memberof UserDataDto */ - userData?: AccountDataDto; + userData?: TaskDeadlineViewDeadline; /** * * @type {Array} @@ -1372,10 +1380,10 @@ export interface UserTaskSolutions { solutions?: Array; /** * - * @type {AccountDataDto} + * @type {TaskDeadlineViewDeadline} * @memberof UserTaskSolutions */ - user?: AccountDataDto; + user?: TaskDeadlineViewDeadline; } @@ -1387,11 +1395,11 @@ export const AccountApiFetchParamCreator = function (configuration?: Configurati return { /** * - * @param {EditExternalViewModel} [model] + * @param {EditExternalViewModel} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} */ - apiAccountEditExternalPut(model?: EditExternalViewModel, options: any = {}): FetchArgs { + apiAccountEditExternalPut(body?: EditExternalViewModel, options: any = {}): FetchArgs { const localVarPath = `/api/Account/editExternal`; const localVarUrlObj = url.parse(localVarPath, true); const localVarRequestOptions = Object.assign({ method: 'PUT' }, options); @@ -1406,14 +1414,14 @@ export const AccountApiFetchParamCreator = function (configuration?: Configurati localVarHeaderParameter["Authorization"] = localVarApiKeyValue; } - localVarHeaderParameter['Content-Type'] = 'application/json-patch+json'; + localVarHeaderParameter['Content-Type'] = 'application/json'; localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); const needsSerialization = ("EditExternalViewModel" !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; - localVarRequestOptions.body = needsSerialization ? JSON.stringify(model || {}) : (model || ""); + localVarRequestOptions.body = needsSerialization ? JSON.stringify(body || {}) : (body || ""); return { url: url.format(localVarUrlObj), @@ -1422,11 +1430,11 @@ export const AccountApiFetchParamCreator = function (configuration?: Configurati }, /** * - * @param {EditAccountViewModel} [model] + * @param {EditAccountViewModel} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} */ - apiAccountEditPut(model?: EditAccountViewModel, options: any = {}): FetchArgs { + apiAccountEditPut(body?: EditAccountViewModel, options: any = {}): FetchArgs { const localVarPath = `/api/Account/edit`; const localVarUrlObj = url.parse(localVarPath, true); const localVarRequestOptions = Object.assign({ method: 'PUT' }, options); @@ -1441,14 +1449,14 @@ export const AccountApiFetchParamCreator = function (configuration?: Configurati localVarHeaderParameter["Authorization"] = localVarApiKeyValue; } - localVarHeaderParameter['Content-Type'] = 'application/json-patch+json'; + localVarHeaderParameter['Content-Type'] = 'application/json'; localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); const needsSerialization = ("EditAccountViewModel" !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; - localVarRequestOptions.body = needsSerialization ? JSON.stringify(model || {}) : (model || ""); + localVarRequestOptions.body = needsSerialization ? JSON.stringify(body || {}) : (body || ""); return { url: url.format(localVarUrlObj), @@ -1588,11 +1596,11 @@ export const AccountApiFetchParamCreator = function (configuration?: Configurati }, /** * - * @param {InviteLecturerViewModel} [model] + * @param {InviteLecturerViewModel} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} */ - apiAccountInviteNewLecturerPost(model?: InviteLecturerViewModel, options: any = {}): FetchArgs { + apiAccountInviteNewLecturerPost(body?: InviteLecturerViewModel, options: any = {}): FetchArgs { const localVarPath = `/api/Account/inviteNewLecturer`; const localVarUrlObj = url.parse(localVarPath, true); const localVarRequestOptions = Object.assign({ method: 'POST' }, options); @@ -1607,14 +1615,14 @@ export const AccountApiFetchParamCreator = function (configuration?: Configurati localVarHeaderParameter["Authorization"] = localVarApiKeyValue; } - localVarHeaderParameter['Content-Type'] = 'application/json-patch+json'; + localVarHeaderParameter['Content-Type'] = 'application/json'; localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); const needsSerialization = ("InviteLecturerViewModel" !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; - localVarRequestOptions.body = needsSerialization ? JSON.stringify(model || {}) : (model || ""); + localVarRequestOptions.body = needsSerialization ? JSON.stringify(body || {}) : (body || ""); return { url: url.format(localVarUrlObj), @@ -1623,11 +1631,11 @@ export const AccountApiFetchParamCreator = function (configuration?: Configurati }, /** * - * @param {LoginViewModel} [model] + * @param {LoginViewModel} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} */ - apiAccountLoginPost(model?: LoginViewModel, options: any = {}): FetchArgs { + apiAccountLoginPost(body?: LoginViewModel, options: any = {}): FetchArgs { const localVarPath = `/api/Account/login`; const localVarUrlObj = url.parse(localVarPath, true); const localVarRequestOptions = Object.assign({ method: 'POST' }, options); @@ -1642,14 +1650,14 @@ export const AccountApiFetchParamCreator = function (configuration?: Configurati localVarHeaderParameter["Authorization"] = localVarApiKeyValue; } - localVarHeaderParameter['Content-Type'] = 'application/json-patch+json'; + localVarHeaderParameter['Content-Type'] = 'application/json'; localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); const needsSerialization = ("LoginViewModel" !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; - localVarRequestOptions.body = needsSerialization ? JSON.stringify(model || {}) : (model || ""); + localVarRequestOptions.body = needsSerialization ? JSON.stringify(body || {}) : (body || ""); return { url: url.format(localVarUrlObj), @@ -1658,11 +1666,11 @@ export const AccountApiFetchParamCreator = function (configuration?: Configurati }, /** * - * @param {RegisterViewModel} [model] + * @param {RegisterViewModel} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} */ - apiAccountRegisterPost(model?: RegisterViewModel, options: any = {}): FetchArgs { + apiAccountRegisterPost(body?: RegisterViewModel, options: any = {}): FetchArgs { const localVarPath = `/api/Account/register`; const localVarUrlObj = url.parse(localVarPath, true); const localVarRequestOptions = Object.assign({ method: 'POST' }, options); @@ -1677,14 +1685,14 @@ export const AccountApiFetchParamCreator = function (configuration?: Configurati localVarHeaderParameter["Authorization"] = localVarApiKeyValue; } - localVarHeaderParameter['Content-Type'] = 'application/json-patch+json'; + localVarHeaderParameter['Content-Type'] = 'application/json'; localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); const needsSerialization = ("RegisterViewModel" !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; - localVarRequestOptions.body = needsSerialization ? JSON.stringify(model || {}) : (model || ""); + localVarRequestOptions.body = needsSerialization ? JSON.stringify(body || {}) : (body || ""); return { url: url.format(localVarUrlObj), @@ -1702,12 +1710,12 @@ export const AccountApiFp = function(configuration?: Configuration) { return { /** * - * @param {EditExternalViewModel} [model] + * @param {EditExternalViewModel} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} */ - apiAccountEditExternalPut(model?: EditExternalViewModel, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { - const localVarFetchArgs = AccountApiFetchParamCreator(configuration).apiAccountEditExternalPut(model, options); + apiAccountEditExternalPut(body?: EditExternalViewModel, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { + const localVarFetchArgs = AccountApiFetchParamCreator(configuration).apiAccountEditExternalPut(body, options); return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -1720,12 +1728,12 @@ export const AccountApiFp = function(configuration?: Configuration) { }, /** * - * @param {EditAccountViewModel} [model] + * @param {EditAccountViewModel} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} */ - apiAccountEditPut(model?: EditAccountViewModel, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { - const localVarFetchArgs = AccountApiFetchParamCreator(configuration).apiAccountEditPut(model, options); + apiAccountEditPut(body?: EditAccountViewModel, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { + const localVarFetchArgs = AccountApiFetchParamCreator(configuration).apiAccountEditPut(body, options); return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -1794,7 +1802,7 @@ export const AccountApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - apiAccountGooglePost(tokenId?: string, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { + apiAccountGooglePost(tokenId?: string, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { const localVarFetchArgs = AccountApiFetchParamCreator(configuration).apiAccountGooglePost(tokenId, options); return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { @@ -1808,12 +1816,12 @@ export const AccountApiFp = function(configuration?: Configuration) { }, /** * - * @param {InviteLecturerViewModel} [model] + * @param {InviteLecturerViewModel} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} */ - apiAccountInviteNewLecturerPost(model?: InviteLecturerViewModel, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { - const localVarFetchArgs = AccountApiFetchParamCreator(configuration).apiAccountInviteNewLecturerPost(model, options); + apiAccountInviteNewLecturerPost(body?: InviteLecturerViewModel, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { + const localVarFetchArgs = AccountApiFetchParamCreator(configuration).apiAccountInviteNewLecturerPost(body, options); return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -1826,12 +1834,12 @@ export const AccountApiFp = function(configuration?: Configuration) { }, /** * - * @param {LoginViewModel} [model] + * @param {LoginViewModel} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} */ - apiAccountLoginPost(model?: LoginViewModel, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { - const localVarFetchArgs = AccountApiFetchParamCreator(configuration).apiAccountLoginPost(model, options); + apiAccountLoginPost(body?: LoginViewModel, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { + const localVarFetchArgs = AccountApiFetchParamCreator(configuration).apiAccountLoginPost(body, options); return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -1844,12 +1852,12 @@ export const AccountApiFp = function(configuration?: Configuration) { }, /** * - * @param {RegisterViewModel} [model] + * @param {RegisterViewModel} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} */ - apiAccountRegisterPost(model?: RegisterViewModel, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { - const localVarFetchArgs = AccountApiFetchParamCreator(configuration).apiAccountRegisterPost(model, options); + apiAccountRegisterPost(body?: RegisterViewModel, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { + const localVarFetchArgs = AccountApiFetchParamCreator(configuration).apiAccountRegisterPost(body, options); return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -1871,21 +1879,21 @@ export const AccountApiFactory = function (configuration?: Configuration, fetch? return { /** * - * @param {EditExternalViewModel} [model] + * @param {EditExternalViewModel} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} */ - apiAccountEditExternalPut(model?: EditExternalViewModel, options?: any) { - return AccountApiFp(configuration).apiAccountEditExternalPut(model, options)(fetch, basePath); + apiAccountEditExternalPut(body?: EditExternalViewModel, options?: any) { + return AccountApiFp(configuration).apiAccountEditExternalPut(body, options)(fetch, basePath); }, /** * - * @param {EditAccountViewModel} [model] + * @param {EditAccountViewModel} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} */ - apiAccountEditPut(model?: EditAccountViewModel, options?: any) { - return AccountApiFp(configuration).apiAccountEditPut(model, options)(fetch, basePath); + apiAccountEditPut(body?: EditAccountViewModel, options?: any) { + return AccountApiFp(configuration).apiAccountEditPut(body, options)(fetch, basePath); }, /** * @@ -1923,30 +1931,30 @@ export const AccountApiFactory = function (configuration?: Configuration, fetch? }, /** * - * @param {InviteLecturerViewModel} [model] + * @param {InviteLecturerViewModel} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} */ - apiAccountInviteNewLecturerPost(model?: InviteLecturerViewModel, options?: any) { - return AccountApiFp(configuration).apiAccountInviteNewLecturerPost(model, options)(fetch, basePath); + apiAccountInviteNewLecturerPost(body?: InviteLecturerViewModel, options?: any) { + return AccountApiFp(configuration).apiAccountInviteNewLecturerPost(body, options)(fetch, basePath); }, /** * - * @param {LoginViewModel} [model] + * @param {LoginViewModel} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} */ - apiAccountLoginPost(model?: LoginViewModel, options?: any) { - return AccountApiFp(configuration).apiAccountLoginPost(model, options)(fetch, basePath); + apiAccountLoginPost(body?: LoginViewModel, options?: any) { + return AccountApiFp(configuration).apiAccountLoginPost(body, options)(fetch, basePath); }, /** * - * @param {RegisterViewModel} [model] + * @param {RegisterViewModel} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} */ - apiAccountRegisterPost(model?: RegisterViewModel, options?: any) { - return AccountApiFp(configuration).apiAccountRegisterPost(model, options)(fetch, basePath); + apiAccountRegisterPost(body?: RegisterViewModel, options?: any) { + return AccountApiFp(configuration).apiAccountRegisterPost(body, options)(fetch, basePath); }, }; }; @@ -1960,24 +1968,24 @@ export const AccountApiFactory = function (configuration?: Configuration, fetch? export class AccountApi extends BaseAPI { /** * - * @param {EditExternalViewModel} [model] + * @param {EditExternalViewModel} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof AccountApi */ - public apiAccountEditExternalPut(model?: EditExternalViewModel, options?: any) { - return AccountApiFp(this.configuration).apiAccountEditExternalPut(model, options)(this.fetch, this.basePath); + public apiAccountEditExternalPut(body?: EditExternalViewModel, options?: any) { + return AccountApiFp(this.configuration).apiAccountEditExternalPut(body, options)(this.fetch, this.basePath); } /** * - * @param {EditAccountViewModel} [model] + * @param {EditAccountViewModel} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof AccountApi */ - public apiAccountEditPut(model?: EditAccountViewModel, options?: any) { - return AccountApiFp(this.configuration).apiAccountEditPut(model, options)(this.fetch, this.basePath); + public apiAccountEditPut(body?: EditAccountViewModel, options?: any) { + return AccountApiFp(this.configuration).apiAccountEditPut(body, options)(this.fetch, this.basePath); } /** @@ -2024,35 +2032,35 @@ export class AccountApi extends BaseAPI { /** * - * @param {InviteLecturerViewModel} [model] + * @param {InviteLecturerViewModel} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof AccountApi */ - public apiAccountInviteNewLecturerPost(model?: InviteLecturerViewModel, options?: any) { - return AccountApiFp(this.configuration).apiAccountInviteNewLecturerPost(model, options)(this.fetch, this.basePath); + public apiAccountInviteNewLecturerPost(body?: InviteLecturerViewModel, options?: any) { + return AccountApiFp(this.configuration).apiAccountInviteNewLecturerPost(body, options)(this.fetch, this.basePath); } /** * - * @param {LoginViewModel} [model] + * @param {LoginViewModel} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof AccountApi */ - public apiAccountLoginPost(model?: LoginViewModel, options?: any) { - return AccountApiFp(this.configuration).apiAccountLoginPost(model, options)(this.fetch, this.basePath); + public apiAccountLoginPost(body?: LoginViewModel, options?: any) { + return AccountApiFp(this.configuration).apiAccountLoginPost(body, options)(this.fetch, this.basePath); } /** * - * @param {RegisterViewModel} [model] + * @param {RegisterViewModel} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof AccountApi */ - public apiAccountRegisterPost(model?: RegisterViewModel, options?: any) { - return AccountApiFp(this.configuration).apiAccountRegisterPost(model, options)(this.fetch, this.basePath); + public apiAccountRegisterPost(body?: RegisterViewModel, options?: any) { + return AccountApiFp(this.configuration).apiAccountRegisterPost(body, options)(this.fetch, this.basePath); } } @@ -2113,11 +2121,11 @@ export const CourseGroupsApiFetchParamCreator = function (configuration?: Config /** * * @param {number} courseId - * @param {CreateGroupViewModel} [model] + * @param {CreateGroupViewModel} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} */ - apiCourseGroupsByCourseIdCreatePost(courseId: number, model?: CreateGroupViewModel, options: any = {}): FetchArgs { + apiCourseGroupsByCourseIdCreatePost(courseId: number, body?: CreateGroupViewModel, options: any = {}): FetchArgs { // verify required parameter 'courseId' is not null or undefined if (courseId === null || courseId === undefined) { throw new RequiredError('courseId','Required parameter courseId was null or undefined when calling apiCourseGroupsByCourseIdCreatePost.'); @@ -2137,14 +2145,14 @@ export const CourseGroupsApiFetchParamCreator = function (configuration?: Config localVarHeaderParameter["Authorization"] = localVarApiKeyValue; } - localVarHeaderParameter['Content-Type'] = 'application/json-patch+json'; + localVarHeaderParameter['Content-Type'] = 'application/json'; localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); const needsSerialization = ("CreateGroupViewModel" !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; - localVarRequestOptions.body = needsSerialization ? JSON.stringify(model || {}) : (model || ""); + localVarRequestOptions.body = needsSerialization ? JSON.stringify(body || {}) : (body || ""); return { url: url.format(localVarUrlObj), @@ -2316,11 +2324,11 @@ export const CourseGroupsApiFetchParamCreator = function (configuration?: Config * * @param {number} courseId * @param {number} groupId - * @param {UpdateGroupViewModel} [model] + * @param {UpdateGroupViewModel} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} */ - apiCourseGroupsByCourseIdUpdateByGroupIdPost(courseId: number, groupId: number, model?: UpdateGroupViewModel, options: any = {}): FetchArgs { + apiCourseGroupsByCourseIdUpdateByGroupIdPost(courseId: number, groupId: number, body?: UpdateGroupViewModel, options: any = {}): FetchArgs { // verify required parameter 'courseId' is not null or undefined if (courseId === null || courseId === undefined) { throw new RequiredError('courseId','Required parameter courseId was null or undefined when calling apiCourseGroupsByCourseIdUpdateByGroupIdPost.'); @@ -2345,14 +2353,14 @@ export const CourseGroupsApiFetchParamCreator = function (configuration?: Config localVarHeaderParameter["Authorization"] = localVarApiKeyValue; } - localVarHeaderParameter['Content-Type'] = 'application/json-patch+json'; + localVarHeaderParameter['Content-Type'] = 'application/json'; localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); const needsSerialization = ("UpdateGroupViewModel" !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; - localVarRequestOptions.body = needsSerialization ? JSON.stringify(model || {}) : (model || ""); + localVarRequestOptions.body = needsSerialization ? JSON.stringify(body || {}) : (body || ""); return { url: url.format(localVarUrlObj), @@ -2463,12 +2471,12 @@ export const CourseGroupsApiFp = function(configuration?: Configuration) { /** * * @param {number} courseId - * @param {CreateGroupViewModel} [model] + * @param {CreateGroupViewModel} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} */ - apiCourseGroupsByCourseIdCreatePost(courseId: number, model?: CreateGroupViewModel, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { - const localVarFetchArgs = CourseGroupsApiFetchParamCreator(configuration).apiCourseGroupsByCourseIdCreatePost(courseId, model, options); + apiCourseGroupsByCourseIdCreatePost(courseId: number, body?: CreateGroupViewModel, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { + const localVarFetchArgs = CourseGroupsApiFetchParamCreator(configuration).apiCourseGroupsByCourseIdCreatePost(courseId, body, options); return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -2558,12 +2566,12 @@ export const CourseGroupsApiFp = function(configuration?: Configuration) { * * @param {number} courseId * @param {number} groupId - * @param {UpdateGroupViewModel} [model] + * @param {UpdateGroupViewModel} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} */ - apiCourseGroupsByCourseIdUpdateByGroupIdPost(courseId: number, groupId: number, model?: UpdateGroupViewModel, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { - const localVarFetchArgs = CourseGroupsApiFetchParamCreator(configuration).apiCourseGroupsByCourseIdUpdateByGroupIdPost(courseId, groupId, model, options); + apiCourseGroupsByCourseIdUpdateByGroupIdPost(courseId: number, groupId: number, body?: UpdateGroupViewModel, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { + const localVarFetchArgs = CourseGroupsApiFetchParamCreator(configuration).apiCourseGroupsByCourseIdUpdateByGroupIdPost(courseId, groupId, body, options); return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -2633,12 +2641,12 @@ export const CourseGroupsApiFactory = function (configuration?: Configuration, f /** * * @param {number} courseId - * @param {CreateGroupViewModel} [model] + * @param {CreateGroupViewModel} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} */ - apiCourseGroupsByCourseIdCreatePost(courseId: number, model?: CreateGroupViewModel, options?: any) { - return CourseGroupsApiFp(configuration).apiCourseGroupsByCourseIdCreatePost(courseId, model, options)(fetch, basePath); + apiCourseGroupsByCourseIdCreatePost(courseId: number, body?: CreateGroupViewModel, options?: any) { + return CourseGroupsApiFp(configuration).apiCourseGroupsByCourseIdCreatePost(courseId, body, options)(fetch, basePath); }, /** * @@ -2683,12 +2691,12 @@ export const CourseGroupsApiFactory = function (configuration?: Configuration, f * * @param {number} courseId * @param {number} groupId - * @param {UpdateGroupViewModel} [model] + * @param {UpdateGroupViewModel} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} */ - apiCourseGroupsByCourseIdUpdateByGroupIdPost(courseId: number, groupId: number, model?: UpdateGroupViewModel, options?: any) { - return CourseGroupsApiFp(configuration).apiCourseGroupsByCourseIdUpdateByGroupIdPost(courseId, groupId, model, options)(fetch, basePath); + apiCourseGroupsByCourseIdUpdateByGroupIdPost(courseId: number, groupId: number, body?: UpdateGroupViewModel, options?: any) { + return CourseGroupsApiFp(configuration).apiCourseGroupsByCourseIdUpdateByGroupIdPost(courseId, groupId, body, options)(fetch, basePath); }, /** * @@ -2734,13 +2742,13 @@ export class CourseGroupsApi extends BaseAPI { /** * * @param {number} courseId - * @param {CreateGroupViewModel} [model] + * @param {CreateGroupViewModel} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof CourseGroupsApi */ - public apiCourseGroupsByCourseIdCreatePost(courseId: number, model?: CreateGroupViewModel, options?: any) { - return CourseGroupsApiFp(this.configuration).apiCourseGroupsByCourseIdCreatePost(courseId, model, options)(this.fetch, this.basePath); + public apiCourseGroupsByCourseIdCreatePost(courseId: number, body?: CreateGroupViewModel, options?: any) { + return CourseGroupsApiFp(this.configuration).apiCourseGroupsByCourseIdCreatePost(courseId, body, options)(this.fetch, this.basePath); } /** @@ -2794,13 +2802,13 @@ export class CourseGroupsApi extends BaseAPI { * * @param {number} courseId * @param {number} groupId - * @param {UpdateGroupViewModel} [model] + * @param {UpdateGroupViewModel} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof CourseGroupsApi */ - public apiCourseGroupsByCourseIdUpdateByGroupIdPost(courseId: number, groupId: number, model?: UpdateGroupViewModel, options?: any) { - return CourseGroupsApiFp(this.configuration).apiCourseGroupsByCourseIdUpdateByGroupIdPost(courseId, groupId, model, options)(this.fetch, this.basePath); + public apiCourseGroupsByCourseIdUpdateByGroupIdPost(courseId: number, groupId: number, body?: UpdateGroupViewModel, options?: any) { + return CourseGroupsApiFp(this.configuration).apiCourseGroupsByCourseIdUpdateByGroupIdPost(courseId, groupId, body, options)(this.fetch, this.basePath); } /** @@ -2991,11 +2999,11 @@ export const CoursesApiFetchParamCreator = function (configuration?: Configurati }, /** * - * @param {CreateCourseViewModel} [model] + * @param {CreateCourseViewModel} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} */ - apiCoursesCreatePost(model?: CreateCourseViewModel, options: any = {}): FetchArgs { + apiCoursesCreatePost(body?: CreateCourseViewModel, options: any = {}): FetchArgs { const localVarPath = `/api/Courses/create`; const localVarUrlObj = url.parse(localVarPath, true); const localVarRequestOptions = Object.assign({ method: 'POST' }, options); @@ -3010,14 +3018,14 @@ export const CoursesApiFetchParamCreator = function (configuration?: Configurati localVarHeaderParameter["Authorization"] = localVarApiKeyValue; } - localVarHeaderParameter['Content-Type'] = 'application/json-patch+json'; + localVarHeaderParameter['Content-Type'] = 'application/json'; localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); const needsSerialization = ("CreateCourseViewModel" !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; - localVarRequestOptions.body = needsSerialization ? JSON.stringify(model || {}) : (model || ""); + localVarRequestOptions.body = needsSerialization ? JSON.stringify(body || {}) : (body || ""); return { url: url.format(localVarUrlObj), @@ -3171,11 +3179,11 @@ export const CoursesApiFetchParamCreator = function (configuration?: Configurati /** * * @param {number} courseId - * @param {UpdateCourseViewModel} [model] + * @param {UpdateCourseViewModel} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} */ - apiCoursesUpdateByCourseIdPost(courseId: number, model?: UpdateCourseViewModel, options: any = {}): FetchArgs { + apiCoursesUpdateByCourseIdPost(courseId: number, body?: UpdateCourseViewModel, options: any = {}): FetchArgs { // verify required parameter 'courseId' is not null or undefined if (courseId === null || courseId === undefined) { throw new RequiredError('courseId','Required parameter courseId was null or undefined when calling apiCoursesUpdateByCourseIdPost.'); @@ -3195,14 +3203,14 @@ export const CoursesApiFetchParamCreator = function (configuration?: Configurati localVarHeaderParameter["Authorization"] = localVarApiKeyValue; } - localVarHeaderParameter['Content-Type'] = 'application/json-patch+json'; + localVarHeaderParameter['Content-Type'] = 'application/json'; localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); const needsSerialization = ("UpdateCourseViewModel" !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; - localVarRequestOptions.body = needsSerialization ? JSON.stringify(model || {}) : (model || ""); + localVarRequestOptions.body = needsSerialization ? JSON.stringify(body || {}) : (body || ""); return { url: url.format(localVarUrlObj), @@ -3324,12 +3332,12 @@ export const CoursesApiFp = function(configuration?: Configuration) { }, /** * - * @param {CreateCourseViewModel} [model] + * @param {CreateCourseViewModel} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} */ - apiCoursesCreatePost(model?: CreateCourseViewModel, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { - const localVarFetchArgs = CoursesApiFetchParamCreator(configuration).apiCoursesCreatePost(model, options); + apiCoursesCreatePost(body?: CreateCourseViewModel, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { + const localVarFetchArgs = CoursesApiFetchParamCreator(configuration).apiCoursesCreatePost(body, options); return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -3415,12 +3423,12 @@ export const CoursesApiFp = function(configuration?: Configuration) { /** * * @param {number} courseId - * @param {UpdateCourseViewModel} [model] + * @param {UpdateCourseViewModel} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} */ - apiCoursesUpdateByCourseIdPost(courseId: number, model?: UpdateCourseViewModel, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { - const localVarFetchArgs = CoursesApiFetchParamCreator(configuration).apiCoursesUpdateByCourseIdPost(courseId, model, options); + apiCoursesUpdateByCourseIdPost(courseId: number, body?: UpdateCourseViewModel, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { + const localVarFetchArgs = CoursesApiFetchParamCreator(configuration).apiCoursesUpdateByCourseIdPost(courseId, body, options); return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -3497,12 +3505,12 @@ export const CoursesApiFactory = function (configuration?: Configuration, fetch? }, /** * - * @param {CreateCourseViewModel} [model] + * @param {CreateCourseViewModel} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} */ - apiCoursesCreatePost(model?: CreateCourseViewModel, options?: any) { - return CoursesApiFp(configuration).apiCoursesCreatePost(model, options)(fetch, basePath); + apiCoursesCreatePost(body?: CreateCourseViewModel, options?: any) { + return CoursesApiFp(configuration).apiCoursesCreatePost(body, options)(fetch, basePath); }, /** * @@ -3543,12 +3551,12 @@ export const CoursesApiFactory = function (configuration?: Configuration, fetch? /** * * @param {number} courseId - * @param {UpdateCourseViewModel} [model] + * @param {UpdateCourseViewModel} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} */ - apiCoursesUpdateByCourseIdPost(courseId: number, model?: UpdateCourseViewModel, options?: any) { - return CoursesApiFp(configuration).apiCoursesUpdateByCourseIdPost(courseId, model, options)(fetch, basePath); + apiCoursesUpdateByCourseIdPost(courseId: number, body?: UpdateCourseViewModel, options?: any) { + return CoursesApiFp(configuration).apiCoursesUpdateByCourseIdPost(courseId, body, options)(fetch, basePath); }, /** * @@ -3616,13 +3624,13 @@ export class CoursesApi extends BaseAPI { /** * - * @param {CreateCourseViewModel} [model] + * @param {CreateCourseViewModel} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof CoursesApi */ - public apiCoursesCreatePost(model?: CreateCourseViewModel, options?: any) { - return CoursesApiFp(this.configuration).apiCoursesCreatePost(model, options)(this.fetch, this.basePath); + public apiCoursesCreatePost(body?: CreateCourseViewModel, options?: any) { + return CoursesApiFp(this.configuration).apiCoursesCreatePost(body, options)(this.fetch, this.basePath); } /** @@ -3672,13 +3680,13 @@ export class CoursesApi extends BaseAPI { /** * * @param {number} courseId - * @param {UpdateCourseViewModel} [model] + * @param {UpdateCourseViewModel} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof CoursesApi */ - public apiCoursesUpdateByCourseIdPost(courseId: number, model?: UpdateCourseViewModel, options?: any) { - return CoursesApiFp(this.configuration).apiCoursesUpdateByCourseIdPost(courseId, model, options)(this.fetch, this.basePath); + public apiCoursesUpdateByCourseIdPost(courseId: number, body?: UpdateCourseViewModel, options?: any) { + return CoursesApiFp(this.configuration).apiCoursesUpdateByCourseIdPost(courseId, body, options)(this.fetch, this.basePath); } /** @@ -3702,11 +3710,11 @@ export const HomeworksApiFetchParamCreator = function (configuration?: Configura /** * * @param {number} courseId - * @param {CreateHomeworkViewModel} [homeworkViewModel] + * @param {CreateHomeworkViewModel} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} */ - apiHomeworksByCourseIdAddPost(courseId: number, homeworkViewModel?: CreateHomeworkViewModel, options: any = {}): FetchArgs { + apiHomeworksByCourseIdAddPost(courseId: number, body?: CreateHomeworkViewModel, options: any = {}): FetchArgs { // verify required parameter 'courseId' is not null or undefined if (courseId === null || courseId === undefined) { throw new RequiredError('courseId','Required parameter courseId was null or undefined when calling apiHomeworksByCourseIdAddPost.'); @@ -3726,14 +3734,14 @@ export const HomeworksApiFetchParamCreator = function (configuration?: Configura localVarHeaderParameter["Authorization"] = localVarApiKeyValue; } - localVarHeaderParameter['Content-Type'] = 'application/json-patch+json'; + localVarHeaderParameter['Content-Type'] = 'application/json'; localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); const needsSerialization = ("CreateHomeworkViewModel" !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; - localVarRequestOptions.body = needsSerialization ? JSON.stringify(homeworkViewModel || {}) : (homeworkViewModel || ""); + localVarRequestOptions.body = needsSerialization ? JSON.stringify(body || {}) : (body || ""); return { url: url.format(localVarUrlObj), @@ -3815,11 +3823,11 @@ export const HomeworksApiFetchParamCreator = function (configuration?: Configura /** * * @param {number} homeworkId - * @param {CreateHomeworkViewModel} [homeworkViewModel] + * @param {CreateHomeworkViewModel} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} */ - apiHomeworksUpdateByHomeworkIdPut(homeworkId: number, homeworkViewModel?: CreateHomeworkViewModel, options: any = {}): FetchArgs { + apiHomeworksUpdateByHomeworkIdPut(homeworkId: number, body?: CreateHomeworkViewModel, options: any = {}): FetchArgs { // verify required parameter 'homeworkId' is not null or undefined if (homeworkId === null || homeworkId === undefined) { throw new RequiredError('homeworkId','Required parameter homeworkId was null or undefined when calling apiHomeworksUpdateByHomeworkIdPut.'); @@ -3839,14 +3847,14 @@ export const HomeworksApiFetchParamCreator = function (configuration?: Configura localVarHeaderParameter["Authorization"] = localVarApiKeyValue; } - localVarHeaderParameter['Content-Type'] = 'application/json-patch+json'; + localVarHeaderParameter['Content-Type'] = 'application/json'; localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); const needsSerialization = ("CreateHomeworkViewModel" !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; - localVarRequestOptions.body = needsSerialization ? JSON.stringify(homeworkViewModel || {}) : (homeworkViewModel || ""); + localVarRequestOptions.body = needsSerialization ? JSON.stringify(body || {}) : (body || ""); return { url: url.format(localVarUrlObj), @@ -3865,12 +3873,12 @@ export const HomeworksApiFp = function(configuration?: Configuration) { /** * * @param {number} courseId - * @param {CreateHomeworkViewModel} [homeworkViewModel] + * @param {CreateHomeworkViewModel} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} */ - apiHomeworksByCourseIdAddPost(courseId: number, homeworkViewModel?: CreateHomeworkViewModel, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { - const localVarFetchArgs = HomeworksApiFetchParamCreator(configuration).apiHomeworksByCourseIdAddPost(courseId, homeworkViewModel, options); + apiHomeworksByCourseIdAddPost(courseId: number, body?: CreateHomeworkViewModel, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { + const localVarFetchArgs = HomeworksApiFetchParamCreator(configuration).apiHomeworksByCourseIdAddPost(courseId, body, options); return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -3920,12 +3928,12 @@ export const HomeworksApiFp = function(configuration?: Configuration) { /** * * @param {number} homeworkId - * @param {CreateHomeworkViewModel} [homeworkViewModel] + * @param {CreateHomeworkViewModel} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} */ - apiHomeworksUpdateByHomeworkIdPut(homeworkId: number, homeworkViewModel?: CreateHomeworkViewModel, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { - const localVarFetchArgs = HomeworksApiFetchParamCreator(configuration).apiHomeworksUpdateByHomeworkIdPut(homeworkId, homeworkViewModel, options); + apiHomeworksUpdateByHomeworkIdPut(homeworkId: number, body?: CreateHomeworkViewModel, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { + const localVarFetchArgs = HomeworksApiFetchParamCreator(configuration).apiHomeworksUpdateByHomeworkIdPut(homeworkId, body, options); return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -3948,12 +3956,12 @@ export const HomeworksApiFactory = function (configuration?: Configuration, fetc /** * * @param {number} courseId - * @param {CreateHomeworkViewModel} [homeworkViewModel] + * @param {CreateHomeworkViewModel} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} */ - apiHomeworksByCourseIdAddPost(courseId: number, homeworkViewModel?: CreateHomeworkViewModel, options?: any) { - return HomeworksApiFp(configuration).apiHomeworksByCourseIdAddPost(courseId, homeworkViewModel, options)(fetch, basePath); + apiHomeworksByCourseIdAddPost(courseId: number, body?: CreateHomeworkViewModel, options?: any) { + return HomeworksApiFp(configuration).apiHomeworksByCourseIdAddPost(courseId, body, options)(fetch, basePath); }, /** * @@ -3976,12 +3984,12 @@ export const HomeworksApiFactory = function (configuration?: Configuration, fetc /** * * @param {number} homeworkId - * @param {CreateHomeworkViewModel} [homeworkViewModel] + * @param {CreateHomeworkViewModel} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} */ - apiHomeworksUpdateByHomeworkIdPut(homeworkId: number, homeworkViewModel?: CreateHomeworkViewModel, options?: any) { - return HomeworksApiFp(configuration).apiHomeworksUpdateByHomeworkIdPut(homeworkId, homeworkViewModel, options)(fetch, basePath); + apiHomeworksUpdateByHomeworkIdPut(homeworkId: number, body?: CreateHomeworkViewModel, options?: any) { + return HomeworksApiFp(configuration).apiHomeworksUpdateByHomeworkIdPut(homeworkId, body, options)(fetch, basePath); }, }; }; @@ -3996,13 +4004,13 @@ export class HomeworksApi extends BaseAPI { /** * * @param {number} courseId - * @param {CreateHomeworkViewModel} [homeworkViewModel] + * @param {CreateHomeworkViewModel} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof HomeworksApi */ - public apiHomeworksByCourseIdAddPost(courseId: number, homeworkViewModel?: CreateHomeworkViewModel, options?: any) { - return HomeworksApiFp(this.configuration).apiHomeworksByCourseIdAddPost(courseId, homeworkViewModel, options)(this.fetch, this.basePath); + public apiHomeworksByCourseIdAddPost(courseId: number, body?: CreateHomeworkViewModel, options?: any) { + return HomeworksApiFp(this.configuration).apiHomeworksByCourseIdAddPost(courseId, body, options)(this.fetch, this.basePath); } /** @@ -4030,13 +4038,13 @@ export class HomeworksApi extends BaseAPI { /** * * @param {number} homeworkId - * @param {CreateHomeworkViewModel} [homeworkViewModel] + * @param {CreateHomeworkViewModel} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof HomeworksApi */ - public apiHomeworksUpdateByHomeworkIdPut(homeworkId: number, homeworkViewModel?: CreateHomeworkViewModel, options?: any) { - return HomeworksApiFp(this.configuration).apiHomeworksUpdateByHomeworkIdPut(homeworkId, homeworkViewModel, options)(this.fetch, this.basePath); + public apiHomeworksUpdateByHomeworkIdPut(homeworkId: number, body?: CreateHomeworkViewModel, options?: any) { + return HomeworksApiFp(this.configuration).apiHomeworksUpdateByHomeworkIdPut(homeworkId, body, options)(this.fetch, this.basePath); } } @@ -4109,11 +4117,11 @@ export const NotificationsApiFetchParamCreator = function (configuration?: Confi }, /** * - * @param {Array} [notificationIds] + * @param {Array} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} */ - apiNotificationsMarkAsSeenPut(notificationIds?: Array, options: any = {}): FetchArgs { + apiNotificationsMarkAsSeenPut(body?: Array, options: any = {}): FetchArgs { const localVarPath = `/api/Notifications/markAsSeen`; const localVarUrlObj = url.parse(localVarPath, true); const localVarRequestOptions = Object.assign({ method: 'PUT' }, options); @@ -4128,14 +4136,14 @@ export const NotificationsApiFetchParamCreator = function (configuration?: Confi localVarHeaderParameter["Authorization"] = localVarApiKeyValue; } - localVarHeaderParameter['Content-Type'] = 'application/json-patch+json'; + localVarHeaderParameter['Content-Type'] = 'application/json'; localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); const needsSerialization = ("Array<number>" !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; - localVarRequestOptions.body = needsSerialization ? JSON.stringify(notificationIds || {}) : (notificationIds || ""); + localVarRequestOptions.body = needsSerialization ? JSON.stringify(body || {}) : (body || ""); return { url: url.format(localVarUrlObj), @@ -4187,12 +4195,12 @@ export const NotificationsApiFp = function(configuration?: Configuration) { }, /** * - * @param {Array} [notificationIds] + * @param {Array} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} */ - apiNotificationsMarkAsSeenPut(notificationIds?: Array, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { - const localVarFetchArgs = NotificationsApiFetchParamCreator(configuration).apiNotificationsMarkAsSeenPut(notificationIds, options); + apiNotificationsMarkAsSeenPut(body?: Array, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { + const localVarFetchArgs = NotificationsApiFetchParamCreator(configuration).apiNotificationsMarkAsSeenPut(body, options); return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -4230,12 +4238,12 @@ export const NotificationsApiFactory = function (configuration?: Configuration, }, /** * - * @param {Array} [notificationIds] + * @param {Array} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} */ - apiNotificationsMarkAsSeenPut(notificationIds?: Array, options?: any) { - return NotificationsApiFp(configuration).apiNotificationsMarkAsSeenPut(notificationIds, options)(fetch, basePath); + apiNotificationsMarkAsSeenPut(body?: Array, options?: any) { + return NotificationsApiFp(configuration).apiNotificationsMarkAsSeenPut(body, options)(fetch, basePath); }, }; }; @@ -4269,13 +4277,13 @@ export class NotificationsApi extends BaseAPI { /** * - * @param {Array} [notificationIds] + * @param {Array} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof NotificationsApi */ - public apiNotificationsMarkAsSeenPut(notificationIds?: Array, options?: any) { - return NotificationsApiFp(this.configuration).apiNotificationsMarkAsSeenPut(notificationIds, options)(this.fetch, this.basePath); + public apiNotificationsMarkAsSeenPut(body?: Array, options?: any) { + return NotificationsApiFp(this.configuration).apiNotificationsMarkAsSeenPut(body, options)(this.fetch, this.basePath); } } @@ -4290,11 +4298,11 @@ export const SolutionsApiFetchParamCreator = function (configuration?: Configura * * @param {number} taskId * @param {number} groupId - * @param {SolutionViewModel} [model] + * @param {SolutionViewModel} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} */ - apiSolutionsByGroupIdByTaskIdPost(taskId: number, groupId: number, model?: SolutionViewModel, options: any = {}): FetchArgs { + apiSolutionsByGroupIdByTaskIdPost(taskId: number, groupId: number, body?: SolutionViewModel, options: any = {}): FetchArgs { // verify required parameter 'taskId' is not null or undefined if (taskId === null || taskId === undefined) { throw new RequiredError('taskId','Required parameter taskId was null or undefined when calling apiSolutionsByGroupIdByTaskIdPost.'); @@ -4319,14 +4327,14 @@ export const SolutionsApiFetchParamCreator = function (configuration?: Configura localVarHeaderParameter["Authorization"] = localVarApiKeyValue; } - localVarHeaderParameter['Content-Type'] = 'application/json-patch+json'; + localVarHeaderParameter['Content-Type'] = 'application/json'; localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); const needsSerialization = ("SolutionViewModel" !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; - localVarRequestOptions.body = needsSerialization ? JSON.stringify(model || {}) : (model || ""); + localVarRequestOptions.body = needsSerialization ? JSON.stringify(body || {}) : (body || ""); return { url: url.format(localVarUrlObj), @@ -4414,11 +4422,11 @@ export const SolutionsApiFetchParamCreator = function (configuration?: Configura /** * * @param {number} taskId - * @param {SolutionViewModel} [model] + * @param {SolutionViewModel} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} */ - apiSolutionsByTaskIdPost(taskId: number, model?: SolutionViewModel, options: any = {}): FetchArgs { + apiSolutionsByTaskIdPost(taskId: number, body?: SolutionViewModel, options: any = {}): FetchArgs { // verify required parameter 'taskId' is not null or undefined if (taskId === null || taskId === undefined) { throw new RequiredError('taskId','Required parameter taskId was null or undefined when calling apiSolutionsByTaskIdPost.'); @@ -4438,14 +4446,14 @@ export const SolutionsApiFetchParamCreator = function (configuration?: Configura localVarHeaderParameter["Authorization"] = localVarApiKeyValue; } - localVarHeaderParameter['Content-Type'] = 'application/json-patch+json'; + localVarHeaderParameter['Content-Type'] = 'application/json'; localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); const needsSerialization = ("SolutionViewModel" !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; - localVarRequestOptions.body = needsSerialization ? JSON.stringify(model || {}) : (model || ""); + localVarRequestOptions.body = needsSerialization ? JSON.stringify(body || {}) : (body || ""); return { url: url.format(localVarUrlObj), @@ -4691,12 +4699,12 @@ export const SolutionsApiFp = function(configuration?: Configuration) { * * @param {number} taskId * @param {number} groupId - * @param {SolutionViewModel} [model] + * @param {SolutionViewModel} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} */ - apiSolutionsByGroupIdByTaskIdPost(taskId: number, groupId: number, model?: SolutionViewModel, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { - const localVarFetchArgs = SolutionsApiFetchParamCreator(configuration).apiSolutionsByGroupIdByTaskIdPost(taskId, groupId, model, options); + apiSolutionsByGroupIdByTaskIdPost(taskId: number, groupId: number, body?: SolutionViewModel, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { + const localVarFetchArgs = SolutionsApiFetchParamCreator(configuration).apiSolutionsByGroupIdByTaskIdPost(taskId, groupId, body, options); return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -4747,12 +4755,12 @@ export const SolutionsApiFp = function(configuration?: Configuration) { /** * * @param {number} taskId - * @param {SolutionViewModel} [model] + * @param {SolutionViewModel} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} */ - apiSolutionsByTaskIdPost(taskId: number, model?: SolutionViewModel, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { - const localVarFetchArgs = SolutionsApiFetchParamCreator(configuration).apiSolutionsByTaskIdPost(taskId, model, options); + apiSolutionsByTaskIdPost(taskId: number, body?: SolutionViewModel, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { + const localVarFetchArgs = SolutionsApiFetchParamCreator(configuration).apiSolutionsByTaskIdPost(taskId, body, options); return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -4886,12 +4894,12 @@ export const SolutionsApiFactory = function (configuration?: Configuration, fetc * * @param {number} taskId * @param {number} groupId - * @param {SolutionViewModel} [model] + * @param {SolutionViewModel} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} */ - apiSolutionsByGroupIdByTaskIdPost(taskId: number, groupId: number, model?: SolutionViewModel, options?: any) { - return SolutionsApiFp(configuration).apiSolutionsByGroupIdByTaskIdPost(taskId, groupId, model, options)(fetch, basePath); + apiSolutionsByGroupIdByTaskIdPost(taskId: number, groupId: number, body?: SolutionViewModel, options?: any) { + return SolutionsApiFp(configuration).apiSolutionsByGroupIdByTaskIdPost(taskId, groupId, body, options)(fetch, basePath); }, /** * @@ -4915,12 +4923,12 @@ export const SolutionsApiFactory = function (configuration?: Configuration, fetc /** * * @param {number} taskId - * @param {SolutionViewModel} [model] + * @param {SolutionViewModel} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} */ - apiSolutionsByTaskIdPost(taskId: number, model?: SolutionViewModel, options?: any) { - return SolutionsApiFp(configuration).apiSolutionsByTaskIdPost(taskId, model, options)(fetch, basePath); + apiSolutionsByTaskIdPost(taskId: number, body?: SolutionViewModel, options?: any) { + return SolutionsApiFp(configuration).apiSolutionsByTaskIdPost(taskId, body, options)(fetch, basePath); }, /** * @@ -4992,13 +5000,13 @@ export class SolutionsApi extends BaseAPI { * * @param {number} taskId * @param {number} groupId - * @param {SolutionViewModel} [model] + * @param {SolutionViewModel} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof SolutionsApi */ - public apiSolutionsByGroupIdByTaskIdPost(taskId: number, groupId: number, model?: SolutionViewModel, options?: any) { - return SolutionsApiFp(this.configuration).apiSolutionsByGroupIdByTaskIdPost(taskId, groupId, model, options)(this.fetch, this.basePath); + public apiSolutionsByGroupIdByTaskIdPost(taskId: number, groupId: number, body?: SolutionViewModel, options?: any) { + return SolutionsApiFp(this.configuration).apiSolutionsByGroupIdByTaskIdPost(taskId, groupId, body, options)(this.fetch, this.basePath); } /** @@ -5027,13 +5035,13 @@ export class SolutionsApi extends BaseAPI { /** * * @param {number} taskId - * @param {SolutionViewModel} [model] + * @param {SolutionViewModel} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof SolutionsApi */ - public apiSolutionsByTaskIdPost(taskId: number, model?: SolutionViewModel, options?: any) { - return SolutionsApiFp(this.configuration).apiSolutionsByTaskIdPost(taskId, model, options)(this.fetch, this.basePath); + public apiSolutionsByTaskIdPost(taskId: number, body?: SolutionViewModel, options?: any) { + return SolutionsApiFp(this.configuration).apiSolutionsByTaskIdPost(taskId, body, options)(this.fetch, this.basePath); } /** @@ -5326,11 +5334,11 @@ export const TasksApiFetchParamCreator = function (configuration?: Configuration /** * * @param {number} homeworkId - * @param {CreateTaskViewModel} [taskViewModel] + * @param {CreateTaskViewModel} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} */ - apiTasksAddByHomeworkIdPost(homeworkId: number, taskViewModel?: CreateTaskViewModel, options: any = {}): FetchArgs { + apiTasksAddByHomeworkIdPost(homeworkId: number, body?: CreateTaskViewModel, options: any = {}): FetchArgs { // verify required parameter 'homeworkId' is not null or undefined if (homeworkId === null || homeworkId === undefined) { throw new RequiredError('homeworkId','Required parameter homeworkId was null or undefined when calling apiTasksAddByHomeworkIdPost.'); @@ -5350,14 +5358,14 @@ export const TasksApiFetchParamCreator = function (configuration?: Configuration localVarHeaderParameter["Authorization"] = localVarApiKeyValue; } - localVarHeaderParameter['Content-Type'] = 'application/json-patch+json'; + localVarHeaderParameter['Content-Type'] = 'application/json'; localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); const needsSerialization = ("CreateTaskViewModel" !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; - localVarRequestOptions.body = needsSerialization ? JSON.stringify(taskViewModel || {}) : (taskViewModel || ""); + localVarRequestOptions.body = needsSerialization ? JSON.stringify(body || {}) : (body || ""); return { url: url.format(localVarUrlObj), @@ -5439,11 +5447,11 @@ export const TasksApiFetchParamCreator = function (configuration?: Configuration /** * * @param {number} taskId - * @param {CreateTaskViewModel} [taskViewModel] + * @param {CreateTaskViewModel} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} */ - apiTasksUpdateByTaskIdPut(taskId: number, taskViewModel?: CreateTaskViewModel, options: any = {}): FetchArgs { + apiTasksUpdateByTaskIdPut(taskId: number, body?: CreateTaskViewModel, options: any = {}): FetchArgs { // verify required parameter 'taskId' is not null or undefined if (taskId === null || taskId === undefined) { throw new RequiredError('taskId','Required parameter taskId was null or undefined when calling apiTasksUpdateByTaskIdPut.'); @@ -5463,14 +5471,14 @@ export const TasksApiFetchParamCreator = function (configuration?: Configuration localVarHeaderParameter["Authorization"] = localVarApiKeyValue; } - localVarHeaderParameter['Content-Type'] = 'application/json-patch+json'; + localVarHeaderParameter['Content-Type'] = 'application/json'; localVarUrlObj.query = Object.assign({}, localVarUrlObj.query, localVarQueryParameter, options.query); // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; localVarRequestOptions.headers = Object.assign({}, localVarHeaderParameter, options.headers); const needsSerialization = ("CreateTaskViewModel" !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; - localVarRequestOptions.body = needsSerialization ? JSON.stringify(taskViewModel || {}) : (taskViewModel || ""); + localVarRequestOptions.body = needsSerialization ? JSON.stringify(body || {}) : (body || ""); return { url: url.format(localVarUrlObj), @@ -5489,12 +5497,12 @@ export const TasksApiFp = function(configuration?: Configuration) { /** * * @param {number} homeworkId - * @param {CreateTaskViewModel} [taskViewModel] + * @param {CreateTaskViewModel} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} */ - apiTasksAddByHomeworkIdPost(homeworkId: number, taskViewModel?: CreateTaskViewModel, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { - const localVarFetchArgs = TasksApiFetchParamCreator(configuration).apiTasksAddByHomeworkIdPost(homeworkId, taskViewModel, options); + apiTasksAddByHomeworkIdPost(homeworkId: number, body?: CreateTaskViewModel, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { + const localVarFetchArgs = TasksApiFetchParamCreator(configuration).apiTasksAddByHomeworkIdPost(homeworkId, body, options); return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -5544,12 +5552,12 @@ export const TasksApiFp = function(configuration?: Configuration) { /** * * @param {number} taskId - * @param {CreateTaskViewModel} [taskViewModel] + * @param {CreateTaskViewModel} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} */ - apiTasksUpdateByTaskIdPut(taskId: number, taskViewModel?: CreateTaskViewModel, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { - const localVarFetchArgs = TasksApiFetchParamCreator(configuration).apiTasksUpdateByTaskIdPut(taskId, taskViewModel, options); + apiTasksUpdateByTaskIdPut(taskId: number, body?: CreateTaskViewModel, options?: any): (fetch?: FetchAPI, basePath?: string) => Promise { + const localVarFetchArgs = TasksApiFetchParamCreator(configuration).apiTasksUpdateByTaskIdPut(taskId, body, options); return (fetch: FetchAPI = portableFetch, basePath: string = BASE_PATH) => { return fetch(basePath + localVarFetchArgs.url, localVarFetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -5572,12 +5580,12 @@ export const TasksApiFactory = function (configuration?: Configuration, fetch?: /** * * @param {number} homeworkId - * @param {CreateTaskViewModel} [taskViewModel] + * @param {CreateTaskViewModel} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} */ - apiTasksAddByHomeworkIdPost(homeworkId: number, taskViewModel?: CreateTaskViewModel, options?: any) { - return TasksApiFp(configuration).apiTasksAddByHomeworkIdPost(homeworkId, taskViewModel, options)(fetch, basePath); + apiTasksAddByHomeworkIdPost(homeworkId: number, body?: CreateTaskViewModel, options?: any) { + return TasksApiFp(configuration).apiTasksAddByHomeworkIdPost(homeworkId, body, options)(fetch, basePath); }, /** * @@ -5600,12 +5608,12 @@ export const TasksApiFactory = function (configuration?: Configuration, fetch?: /** * * @param {number} taskId - * @param {CreateTaskViewModel} [taskViewModel] + * @param {CreateTaskViewModel} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} */ - apiTasksUpdateByTaskIdPut(taskId: number, taskViewModel?: CreateTaskViewModel, options?: any) { - return TasksApiFp(configuration).apiTasksUpdateByTaskIdPut(taskId, taskViewModel, options)(fetch, basePath); + apiTasksUpdateByTaskIdPut(taskId: number, body?: CreateTaskViewModel, options?: any) { + return TasksApiFp(configuration).apiTasksUpdateByTaskIdPut(taskId, body, options)(fetch, basePath); }, }; }; @@ -5620,13 +5628,13 @@ export class TasksApi extends BaseAPI { /** * * @param {number} homeworkId - * @param {CreateTaskViewModel} [taskViewModel] + * @param {CreateTaskViewModel} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof TasksApi */ - public apiTasksAddByHomeworkIdPost(homeworkId: number, taskViewModel?: CreateTaskViewModel, options?: any) { - return TasksApiFp(this.configuration).apiTasksAddByHomeworkIdPost(homeworkId, taskViewModel, options)(this.fetch, this.basePath); + public apiTasksAddByHomeworkIdPost(homeworkId: number, body?: CreateTaskViewModel, options?: any) { + return TasksApiFp(this.configuration).apiTasksAddByHomeworkIdPost(homeworkId, body, options)(this.fetch, this.basePath); } /** @@ -5654,13 +5662,13 @@ export class TasksApi extends BaseAPI { /** * * @param {number} taskId - * @param {CreateTaskViewModel} [taskViewModel] + * @param {CreateTaskViewModel} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof TasksApi */ - public apiTasksUpdateByTaskIdPut(taskId: number, taskViewModel?: CreateTaskViewModel, options?: any) { - return TasksApiFp(this.configuration).apiTasksUpdateByTaskIdPut(taskId, taskViewModel, options)(this.fetch, this.basePath); + public apiTasksUpdateByTaskIdPut(taskId: number, body?: CreateTaskViewModel, options?: any) { + return TasksApiFp(this.configuration).apiTasksUpdateByTaskIdPut(taskId, body, options)(this.fetch, this.basePath); } } From b3be6bb872a84f3fb044655c5f4d422f254cf0b7 Mon Sep 17 00:00:00 2001 From: Roman Pozharskiy Date: Sun, 14 May 2023 13:42:34 +0300 Subject: [PATCH 11/14] update dockerfiles --- .../HwProj.APIGateway.API/Dockerfile | 24 ++++++++++--------- .../HwProj.AuthService.API/Dockerfile | 13 +++------- .../HwProj.CoursesService.API/Dockerfile | 13 +++------- .../Dockerfile | 21 ++++------------ .../HwProj.SolutionsService.API/Dockerfile | 13 +++------- 5 files changed, 27 insertions(+), 57 deletions(-) diff --git a/HwProj.APIGateway/HwProj.APIGateway.API/Dockerfile b/HwProj.APIGateway/HwProj.APIGateway.API/Dockerfile index 002d9d289..8d531b916 100644 --- a/HwProj.APIGateway/HwProj.APIGateway.API/Dockerfile +++ b/HwProj.APIGateway/HwProj.APIGateway.API/Dockerfile @@ -3,26 +3,28 @@ WORKDIR /app FROM mcr.microsoft.com/dotnet/core/sdk:2.2-stretch AS build WORKDIR /src -COPY ["HwProj.APIGateway/HwProj.APIGateway.API/HwProj.APIGateway.API.csproj", "HwProj.APIGateway/HwProj.APIGateway.API/"] -COPY ["HwProj.NotificationsService/HwProj.NotificationsService.Client/HwProj.NotificationsService.Client.csproj", "HwProj.NotificationsService/HwProj.NotificationsService.Client/"] +COPY ["HwProj.NotificationsService/HwProj.NotificationsService.API/HwProj.NotificationsService.API.csproj", "HwProj.NotificationsService/HwProj.NotificationsService.API/"] +COPY ["HwProj.AuthService/HwProj.AuthService.API/HwProj.AuthService.API.csproj", "HwProj.AuthService/HwProj.AuthService.API/"] +COPY ["HwProj.Common/HwProj.Utils/HwProj.Utils.csproj", "HwProj.Common/HwProj.Utils/"] +COPY ["HwProj.EventBus/HwProj.EventBus.Client/HwProj.EventBus.Client.csproj", "HwProj.EventBus/HwProj.EventBus.Client/"] COPY ["HwProj.Common/HwProj.Models/HwProj.Models.csproj", "HwProj.Common/HwProj.Models/"] COPY ["HwProj.Common/HwProj.Repositories/HwProj.Repositories.csproj", "HwProj.Common/HwProj.Repositories/"] +COPY ["HwProj.SolutionsService/HwProj.SolutionsService.API/HwProj.SolutionsService.API.csproj", "HwProj.SolutionsService/HwProj.SolutionsService.API/"] +COPY ["HwProj.SolutionsService/HwProj.SolutionsService.Client/HwProj.SolutionsService.Client.csproj", "HwProj.SolutionsService/HwProj.SolutionsService.Client/"] +COPY ["HwProj.Common/HwProj.Exceptions/HwProj.Exceptions.csproj", "HwProj.Common/HwProj.Exceptions/"] COPY ["HwProj.Common/HwProj.HttpUtils/HwProj.HttpUtils.csproj", "HwProj.Common/HwProj.HttpUtils/"] -COPY ["HwProj.Common/HwProj.Utils/HwProj.Utils.csproj", "HwProj.Common/HwProj.Utils/"] -COPY ["HwProj.EventBus/HwProj.EventBus.Client/HwProj.EventBus.Client.csproj", "HwProj.EventBus/HwProj.EventBus.Client/"] COPY ["HwProj.CoursesService/HwProj.CoursesService.Client/HwProj.CoursesService.Client.csproj", "HwProj.CoursesService/HwProj.CoursesService.Client/"] COPY ["HwProj.AuthService/HwProj.AuthService.Client/HwProj.AuthService.Client.csproj", "HwProj.AuthService/HwProj.AuthService.Client/"] -COPY ["HwProj.SolutionsService/HwProj.SolutionsService.Client/HwProj.SolutionsService.Client.csproj", "HwProj.SolutionsService/HwProj.SolutionsService.Client/"] -COPY ["HwProj.Common/HwProj.Exceptions/HwProj.Exceptions.csproj", "HwProj.Common/HwProj.Exceptions/"] -RUN dotnet restore "HwProj.APIGateway/HwProj.APIGateway.API/HwProj.APIGateway.API.csproj" +COPY ["HwProj.CoursesService/HwProj.CoursesService.API/HwProj.CoursesService.API.csproj", "HwProj.CoursesService/HwProj.CoursesService.API/"] +RUN dotnet restore "HwProj.NotificationsService/HwProj.NotificationsService.API/HwProj.NotificationsService.API.csproj" COPY . . -WORKDIR "/src/HwProj.APIGateway/HwProj.APIGateway.API" -RUN dotnet build "HwProj.APIGateway.API.csproj" -c Release -o /app/build +WORKDIR "/src/HwProj.NotificationsService/HwProj.NotificationsService.API" +RUN dotnet build "HwProj.NotificationsService.API.csproj" -c Release -o /app/build FROM build AS publish -RUN dotnet publish "HwProj.APIGateway.API.csproj" -c Release -o /app/publish +RUN dotnet publish "HwProj.NotificationsService.API.csproj" -c Release -o /app/publish FROM base AS final WORKDIR /app COPY --from=publish /app/publish . -ENTRYPOINT ["dotnet", "HwProj.APIGateway.API.dll"] +ENTRYPOINT ["dotnet", "HwProj.NotificationsService.API.dll"] \ No newline at end of file diff --git a/HwProj.AuthService/HwProj.AuthService.API/Dockerfile b/HwProj.AuthService/HwProj.AuthService.API/Dockerfile index 042ca5ad3..7b5720f46 100644 --- a/HwProj.AuthService/HwProj.AuthService.API/Dockerfile +++ b/HwProj.AuthService/HwProj.AuthService.API/Dockerfile @@ -1,22 +1,15 @@ -FROM mcr.microsoft.com/dotnet/core/aspnet:2.2-stretch-slim AS base -WORKDIR /app - -FROM mcr.microsoft.com/dotnet/core/sdk:2.2-stretch AS build +FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build WORKDIR /src COPY ["HwProj.AuthService/HwProj.AuthService.API/HwProj.AuthService.API.csproj", "HwProj.AuthService/HwProj.AuthService.API/"] COPY ["HwProj.Common/HwProj.Utils/HwProj.Utils.csproj", "HwProj.Common/HwProj.Utils/"] COPY ["HwProj.EventBus/HwProj.EventBus.Client/HwProj.EventBus.Client.csproj", "HwProj.EventBus/HwProj.EventBus.Client/"] COPY ["HwProj.Common/HwProj.Models/HwProj.Models.csproj", "HwProj.Common/HwProj.Models/"] COPY ["HwProj.Common/HwProj.Repositories/HwProj.Repositories.csproj", "HwProj.Common/HwProj.Repositories/"] -RUN dotnet restore "HwProj.AuthService/HwProj.AuthService.API/HwProj.AuthService.API.csproj" COPY . . WORKDIR "/src/HwProj.AuthService/HwProj.AuthService.API" -RUN dotnet build "HwProj.AuthService.API.csproj" -c Release -o /app/build - -FROM build AS publish RUN dotnet publish "HwProj.AuthService.API.csproj" -c Release -o /app/publish -FROM base AS final +FROM build AS final WORKDIR /app -COPY --from=publish /app/publish . +COPY --from=build /app/publish . ENTRYPOINT ["dotnet", "HwProj.AuthService.API.dll"] diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Dockerfile b/HwProj.CoursesService/HwProj.CoursesService.API/Dockerfile index 5124d732c..5aa258ad6 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Dockerfile +++ b/HwProj.CoursesService/HwProj.CoursesService.API/Dockerfile @@ -1,7 +1,4 @@ -FROM mcr.microsoft.com/dotnet/core/aspnet:2.2-stretch-slim AS base -WORKDIR /app - -FROM mcr.microsoft.com/dotnet/core/sdk:2.2-stretch AS build +FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build WORKDIR /src COPY ["HwProj.CoursesService/HwProj.CoursesService.API/HwProj.CoursesService.API.csproj", "HwProj.CoursesService/HwProj.CoursesService.API/"] COPY ["HwProj.Common/HwProj.Utils/HwProj.Utils.csproj", "HwProj.Common/HwProj.Utils/"] @@ -10,15 +7,11 @@ COPY ["HwProj.Common/HwProj.Models/HwProj.Models.csproj", "HwProj.Common/HwProj. COPY ["HwProj.Common/HwProj.Repositories/HwProj.Repositories.csproj", "HwProj.Common/HwProj.Repositories/"] COPY ["HwProj.AuthService/HwProj.AuthService.Client/HwProj.AuthService.Client.csproj", "HwProj.AuthService/HwProj.AuthService.Client/"] COPY ["HwProj.Common/HwProj.HttpUtils/HwProj.HttpUtils.csproj", "HwProj.Common/HwProj.HttpUtils/"] -RUN dotnet restore "HwProj.CoursesService/HwProj.CoursesService.API/HwProj.CoursesService.API.csproj" COPY . . WORKDIR "/src/HwProj.CoursesService/HwProj.CoursesService.API" -RUN dotnet build "HwProj.CoursesService.API.csproj" -c Release -o /app/build - -FROM build AS publish RUN dotnet publish "HwProj.CoursesService.API.csproj" -c Release -o /app/publish -FROM base AS final +FROM build AS final WORKDIR /app -COPY --from=publish /app/publish . +COPY --from=build /app/publish . ENTRYPOINT ["dotnet", "HwProj.CoursesService.API.dll"] diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/Dockerfile b/HwProj.NotificationsService/HwProj.NotificationsService.API/Dockerfile index 8bec4004d..94768eb45 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/Dockerfile +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/Dockerfile @@ -1,30 +1,19 @@ -FROM mcr.microsoft.com/dotnet/core/aspnet:2.2-stretch-slim AS base -WORKDIR /app - -FROM mcr.microsoft.com/dotnet/core/sdk:2.2-stretch AS build -WORKDIR /src +FROM mcr.microsoft.com/dotnet/sdk:6.0@sha256:dd19f6aa2774de9fde18c78970bc4fdebc695bd824c73371b6faec306a18b230 AS build COPY ["HwProj.NotificationsService/HwProj.NotificationsService.API/HwProj.NotificationsService.API.csproj", "HwProj.NotificationsService/HwProj.NotificationsService.API/"] -COPY ["HwProj.AuthService/HwProj.AuthService.API/HwProj.AuthService.API.csproj", "HwProj.AuthService/HwProj.AuthService.API/"] COPY ["HwProj.Common/HwProj.Utils/HwProj.Utils.csproj", "HwProj.Common/HwProj.Utils/"] COPY ["HwProj.EventBus/HwProj.EventBus.Client/HwProj.EventBus.Client.csproj", "HwProj.EventBus/HwProj.EventBus.Client/"] COPY ["HwProj.Common/HwProj.Models/HwProj.Models.csproj", "HwProj.Common/HwProj.Models/"] COPY ["HwProj.Common/HwProj.Repositories/HwProj.Repositories.csproj", "HwProj.Common/HwProj.Repositories/"] -COPY ["HwProj.SolutionsService/HwProj.SolutionsService.API/HwProj.SolutionsService.API.csproj", "HwProj.SolutionsService/HwProj.SolutionsService.API/"] COPY ["HwProj.SolutionsService/HwProj.SolutionsService.Client/HwProj.SolutionsService.Client.csproj", "HwProj.SolutionsService/HwProj.SolutionsService.Client/"] COPY ["HwProj.Common/HwProj.Exceptions/HwProj.Exceptions.csproj", "HwProj.Common/HwProj.Exceptions/"] COPY ["HwProj.Common/HwProj.HttpUtils/HwProj.HttpUtils.csproj", "HwProj.Common/HwProj.HttpUtils/"] COPY ["HwProj.CoursesService/HwProj.CoursesService.Client/HwProj.CoursesService.Client.csproj", "HwProj.CoursesService/HwProj.CoursesService.Client/"] COPY ["HwProj.AuthService/HwProj.AuthService.Client/HwProj.AuthService.Client.csproj", "HwProj.AuthService/HwProj.AuthService.Client/"] -COPY ["HwProj.CoursesService/HwProj.CoursesService.API/HwProj.CoursesService.API.csproj", "HwProj.CoursesService/HwProj.CoursesService.API/"] -RUN dotnet restore "HwProj.NotificationsService/HwProj.NotificationsService.API/HwProj.NotificationsService.API.csproj" COPY . . -WORKDIR "/src/HwProj.NotificationsService/HwProj.NotificationsService.API" -RUN dotnet build "HwProj.NotificationsService.API.csproj" -c Release -o /app/build - -FROM build AS publish -RUN dotnet publish "HwProj.NotificationsService.API.csproj" -c Release -o /app/publish +WORKDIR "/HwProj.NotificationsService/HwProj.NotificationsService.API" +RUN dotnet publish "HwProj.NotificationsService.API.csproj" -c Release --verbosity n -o /app/publish -FROM base AS final +FROM build AS final WORKDIR /app -COPY --from=publish /app/publish . +COPY --from=build /app/publish . ENTRYPOINT ["dotnet", "HwProj.NotificationsService.API.dll"] diff --git a/HwProj.SolutionsService/HwProj.SolutionsService.API/Dockerfile b/HwProj.SolutionsService/HwProj.SolutionsService.API/Dockerfile index 10ad01dc4..0a9c1a5b7 100644 --- a/HwProj.SolutionsService/HwProj.SolutionsService.API/Dockerfile +++ b/HwProj.SolutionsService/HwProj.SolutionsService.API/Dockerfile @@ -1,7 +1,4 @@ -FROM mcr.microsoft.com/dotnet/core/aspnet:2.2-stretch-slim AS base -WORKDIR /app - -FROM mcr.microsoft.com/dotnet/core/sdk:2.2-stretch AS build +FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build WORKDIR /src COPY ["HwProj.SolutionsService/HwProj.SolutionsService.API/HwProj.SolutionsService.API.csproj", "HwProj.SolutionsService/HwProj.SolutionsService.API/"] COPY ["HwProj.SolutionsService/HwProj.SolutionsService.Client/HwProj.SolutionsService.Client.csproj", "HwProj.SolutionsService/HwProj.SolutionsService.Client/"] @@ -13,15 +10,11 @@ COPY ["HwProj.Common/HwProj.Utils/HwProj.Utils.csproj", "HwProj.Common/HwProj.Ut COPY ["HwProj.EventBus/HwProj.EventBus.Client/HwProj.EventBus.Client.csproj", "HwProj.EventBus/HwProj.EventBus.Client/"] COPY ["HwProj.CoursesService/HwProj.CoursesService.Client/HwProj.CoursesService.Client.csproj", "HwProj.CoursesService/HwProj.CoursesService.Client/"] COPY ["HwProj.AuthService/HwProj.AuthService.Client/HwProj.AuthService.Client.csproj", "HwProj.AuthService/HwProj.AuthService.Client/"] -RUN dotnet restore "HwProj.SolutionsService/HwProj.SolutionsService.API/HwProj.SolutionsService.API.csproj" COPY . . WORKDIR /src/HwProj.SolutionsService/HwProj.SolutionsService.API -RUN dotnet build "HwProj.SolutionsService.API.csproj" -c Release -o /app/build - -FROM build AS publish RUN dotnet publish "HwProj.SolutionsService.API.csproj" -c Release -o /app/publish -FROM base AS final +FROM build AS final WORKDIR /app -COPY --from=publish /app/publish . +COPY --from=build /app/publish . ENTRYPOINT ["dotnet", "HwProj.SolutionsService.API.dll"] From a6ed75b9834917b8f186121419858a989cf73916 Mon Sep 17 00:00:00 2001 From: Roman Pozharskiy Date: Sun, 14 May 2023 13:51:44 +0300 Subject: [PATCH 12/14] docker wip --- .../HwProj.APIGateway.API/Dockerfile | 31 +++++++------------ .../Dockerfile | 2 +- 2 files changed, 12 insertions(+), 21 deletions(-) diff --git a/HwProj.APIGateway/HwProj.APIGateway.API/Dockerfile b/HwProj.APIGateway/HwProj.APIGateway.API/Dockerfile index 8d531b916..361583044 100644 --- a/HwProj.APIGateway/HwProj.APIGateway.API/Dockerfile +++ b/HwProj.APIGateway/HwProj.APIGateway.API/Dockerfile @@ -1,30 +1,21 @@ -FROM mcr.microsoft.com/dotnet/core/aspnet:2.2-stretch-slim AS base -WORKDIR /app - -FROM mcr.microsoft.com/dotnet/core/sdk:2.2-stretch AS build +FROM mcr.microsoft.com/dotnet/sdk:6.0 as build WORKDIR /src -COPY ["HwProj.NotificationsService/HwProj.NotificationsService.API/HwProj.NotificationsService.API.csproj", "HwProj.NotificationsService/HwProj.NotificationsService.API/"] -COPY ["HwProj.AuthService/HwProj.AuthService.API/HwProj.AuthService.API.csproj", "HwProj.AuthService/HwProj.AuthService.API/"] -COPY ["HwProj.Common/HwProj.Utils/HwProj.Utils.csproj", "HwProj.Common/HwProj.Utils/"] -COPY ["HwProj.EventBus/HwProj.EventBus.Client/HwProj.EventBus.Client.csproj", "HwProj.EventBus/HwProj.EventBus.Client/"] +COPY ["HwProj.APIGateway/HwProj.APIGateway.API/HwProj.APIGateway.API.csproj", "HwProj.APIGateway/HwProj.APIGateway.API/"] +COPY ["HwProj.NotificationsService/HwProj.NotificationsService.Client/HwProj.NotificationsService.Client.csproj", "HwProj.NotificationsService/HwProj.NotificationsService.Client/"] COPY ["HwProj.Common/HwProj.Models/HwProj.Models.csproj", "HwProj.Common/HwProj.Models/"] COPY ["HwProj.Common/HwProj.Repositories/HwProj.Repositories.csproj", "HwProj.Common/HwProj.Repositories/"] -COPY ["HwProj.SolutionsService/HwProj.SolutionsService.API/HwProj.SolutionsService.API.csproj", "HwProj.SolutionsService/HwProj.SolutionsService.API/"] -COPY ["HwProj.SolutionsService/HwProj.SolutionsService.Client/HwProj.SolutionsService.Client.csproj", "HwProj.SolutionsService/HwProj.SolutionsService.Client/"] -COPY ["HwProj.Common/HwProj.Exceptions/HwProj.Exceptions.csproj", "HwProj.Common/HwProj.Exceptions/"] COPY ["HwProj.Common/HwProj.HttpUtils/HwProj.HttpUtils.csproj", "HwProj.Common/HwProj.HttpUtils/"] +COPY ["HwProj.Common/HwProj.Utils/HwProj.Utils.csproj", "HwProj.Common/HwProj.Utils/"] +COPY ["HwProj.EventBus/HwProj.EventBus.Client/HwProj.EventBus.Client.csproj", "HwProj.EventBus/HwProj.EventBus.Client/"] COPY ["HwProj.CoursesService/HwProj.CoursesService.Client/HwProj.CoursesService.Client.csproj", "HwProj.CoursesService/HwProj.CoursesService.Client/"] COPY ["HwProj.AuthService/HwProj.AuthService.Client/HwProj.AuthService.Client.csproj", "HwProj.AuthService/HwProj.AuthService.Client/"] -COPY ["HwProj.CoursesService/HwProj.CoursesService.API/HwProj.CoursesService.API.csproj", "HwProj.CoursesService/HwProj.CoursesService.API/"] -RUN dotnet restore "HwProj.NotificationsService/HwProj.NotificationsService.API/HwProj.NotificationsService.API.csproj" +COPY ["HwProj.SolutionsService/HwProj.SolutionsService.Client/HwProj.SolutionsService.Client.csproj", "HwProj.SolutionsService/HwProj.SolutionsService.Client/"] +COPY ["HwProj.Common/HwProj.Exceptions/HwProj.Exceptions.csproj", "HwProj.Common/HwProj.Exceptions/"] COPY . . -WORKDIR "/src/HwProj.NotificationsService/HwProj.NotificationsService.API" -RUN dotnet build "HwProj.NotificationsService.API.csproj" -c Release -o /app/build - -FROM build AS publish -RUN dotnet publish "HwProj.NotificationsService.API.csproj" -c Release -o /app/publish +WORKDIR "/src/HwProj.APIGateway/HwProj.APIGateway.API" +RUN dotnet publish "HwProj.APIGateway.API.csproj" -c Release -o /app/publish -FROM base AS final +FROM build AS final WORKDIR /app COPY --from=publish /app/publish . -ENTRYPOINT ["dotnet", "HwProj.NotificationsService.API.dll"] \ No newline at end of file +ENTRYPOINT ["dotnet", "HwProj.APIGateway.API.dll"] \ No newline at end of file diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/Dockerfile b/HwProj.NotificationsService/HwProj.NotificationsService.API/Dockerfile index 94768eb45..b781294c8 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/Dockerfile +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/Dockerfile @@ -1,4 +1,4 @@ -FROM mcr.microsoft.com/dotnet/sdk:6.0@sha256:dd19f6aa2774de9fde18c78970bc4fdebc695bd824c73371b6faec306a18b230 AS build +FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build COPY ["HwProj.NotificationsService/HwProj.NotificationsService.API/HwProj.NotificationsService.API.csproj", "HwProj.NotificationsService/HwProj.NotificationsService.API/"] COPY ["HwProj.Common/HwProj.Utils/HwProj.Utils.csproj", "HwProj.Common/HwProj.Utils/"] COPY ["HwProj.EventBus/HwProj.EventBus.Client/HwProj.EventBus.Client.csproj", "HwProj.EventBus/HwProj.EventBus.Client/"] From b0fbc8bb62328839bb27d4342aae2791aaa92f87 Mon Sep 17 00:00:00 2001 From: Roman Pozharskiy Date: Mon, 15 May 2023 23:19:36 +0300 Subject: [PATCH 13/14] edit notifications service dependencies; move events to common --- HwProj.APIGateway/HwProj.APIGateway.API/Dockerfile | 2 +- .../HwProj.AuthService.API/Services/AccountService.cs | 1 + .../AuthService}/Events/AdminRegisterEvent.cs | 4 +++- .../AuthService}/Events/InviteLecturerEvent.cs | 2 +- .../HwProj.Models/AuthService}/Events/RegisterEvent.cs | 2 +- .../AuthService}/Events/StudentRegisterEvent.cs | 4 +++- .../CoursesService}/Events/LecturerAcceptToCourseEvent.cs | 2 +- .../CoursesService}/Events/LecturerInvitedToCourseEvent.cs | 2 +- .../CoursesService}/Events/LecturerRejectToCourseEvent.cs | 2 +- .../CoursesService}/Events/NewCourseMateEvent.cs | 2 +- .../CoursesService}/Events/NewHomeworkEvent.cs | 2 +- .../CoursesService}/Events/NewHomeworkTaskEvent.cs | 2 +- .../CoursesService}/Events/UpdateHomeworkEvent.cs | 2 +- .../CoursesService}/Events/UpdateSolutionMaxRatingEvent.cs | 2 +- .../CoursesService}/Events/UpdateTaskMaxRatingEvent.cs | 2 +- HwProj.Common/HwProj.Models/HwProj.Models.csproj | 1 + .../HwProj.Models/SolutionsService}/Events/RateEvent.cs | 3 +-- .../SolutionsService}/Events/StudentPassTaskEvent.cs | 3 +-- .../HwProj.CoursesService.API/Services/CoursesService.cs | 2 +- .../HwProj.CoursesService.API/Services/HomeworksService.cs | 2 +- .../HwProj.CoursesService.API/Services/TasksService.cs | 2 +- .../EventHandlers/InviteLecturerEventHandler.cs | 2 +- .../EventHandlers/LecturerAcceptToCourseEventHandler.cs | 2 +- .../EventHandlers/LecturerInvitedToCourseEventHandler.cs | 2 +- .../EventHandlers/LecturerRejectToCourseEventHandler.cs | 2 +- .../EventHandlers/NewCourseMateHandler.cs | 2 +- .../EventHandlers/NewHomeworkEventHandler.cs | 2 +- .../EventHandlers/NewHomeworkTaskEventHandler.cs | 2 +- .../EventHandlers/RateEventHandler.cs | 2 +- .../EventHandlers/StudentPassTaskEventHandler.cs | 2 +- .../EventHandlers/UpdateHomeworkEventHandler.cs | 2 +- .../EventHandlers/UpdateTaskMaxRatingEventHandler.cs | 2 +- .../HwProj.NotificationsService.API.csproj | 3 --- .../HwProj.NotificationsService.API/Startup.cs | 7 ++++--- .../Services/SolutionsService.cs | 2 +- 35 files changed, 41 insertions(+), 39 deletions(-) rename {HwProj.AuthService/HwProj.AuthService.API => HwProj.Common/HwProj.Models/AuthService}/Events/AdminRegisterEvent.cs (73%) rename {HwProj.AuthService/HwProj.AuthService.API => HwProj.Common/HwProj.Models/AuthService}/Events/InviteLecturerEvent.cs (78%) rename {HwProj.AuthService/HwProj.AuthService.API => HwProj.Common/HwProj.Models/AuthService}/Events/RegisterEvent.cs (92%) rename {HwProj.AuthService/HwProj.AuthService.API => HwProj.Common/HwProj.Models/AuthService}/Events/StudentRegisterEvent.cs (74%) rename {HwProj.CoursesService/HwProj.CoursesService.API => HwProj.Common/HwProj.Models/CoursesService}/Events/LecturerAcceptToCourseEvent.cs (84%) rename {HwProj.CoursesService/HwProj.CoursesService.API => HwProj.Common/HwProj.Models/CoursesService}/Events/LecturerInvitedToCourseEvent.cs (84%) rename {HwProj.CoursesService/HwProj.CoursesService.API => HwProj.Common/HwProj.Models/CoursesService}/Events/LecturerRejectToCourseEvent.cs (84%) rename {HwProj.CoursesService/HwProj.CoursesService.API => HwProj.Common/HwProj.Models/CoursesService}/Events/NewCourseMateEvent.cs (85%) rename {HwProj.CoursesService/HwProj.CoursesService.API => HwProj.Common/HwProj.Models/CoursesService}/Events/NewHomeworkEvent.cs (87%) rename {HwProj.CoursesService/HwProj.CoursesService.API => HwProj.Common/HwProj.Models/CoursesService}/Events/NewHomeworkTaskEvent.cs (91%) rename {HwProj.CoursesService/HwProj.CoursesService.API => HwProj.Common/HwProj.Models/CoursesService}/Events/UpdateHomeworkEvent.cs (88%) rename {HwProj.CoursesService/HwProj.CoursesService.API => HwProj.Common/HwProj.Models/CoursesService}/Events/UpdateSolutionMaxRatingEvent.cs (89%) rename {HwProj.CoursesService/HwProj.CoursesService.API => HwProj.Common/HwProj.Models/CoursesService}/Events/UpdateTaskMaxRatingEvent.cs (90%) rename {HwProj.SolutionsService/HwProj.SolutionsService.API => HwProj.Common/HwProj.Models/SolutionsService}/Events/RateEvent.cs (80%) rename {HwProj.SolutionsService/HwProj.SolutionsService.API => HwProj.Common/HwProj.Models/SolutionsService}/Events/StudentPassTaskEvent.cs (87%) diff --git a/HwProj.APIGateway/HwProj.APIGateway.API/Dockerfile b/HwProj.APIGateway/HwProj.APIGateway.API/Dockerfile index 361583044..06712d702 100644 --- a/HwProj.APIGateway/HwProj.APIGateway.API/Dockerfile +++ b/HwProj.APIGateway/HwProj.APIGateway.API/Dockerfile @@ -17,5 +17,5 @@ RUN dotnet publish "HwProj.APIGateway.API.csproj" -c Release -o /app/publish FROM build AS final WORKDIR /app -COPY --from=publish /app/publish . +COPY --from=build /app/publish . ENTRYPOINT ["dotnet", "HwProj.APIGateway.API.dll"] \ No newline at end of file diff --git a/HwProj.AuthService/HwProj.AuthService.API/Services/AccountService.cs b/HwProj.AuthService/HwProj.AuthService.API/Services/AccountService.cs index 06686472c..c31a7ec16 100644 --- a/HwProj.AuthService/HwProj.AuthService.API/Services/AccountService.cs +++ b/HwProj.AuthService/HwProj.AuthService.API/Services/AccountService.cs @@ -9,6 +9,7 @@ using HwProj.AuthService.API.Events; using HwProj.EventBus.Client.Interfaces; using HwProj.Models.AuthService.DTO; +using HwProj.Models.AuthService.Events; using HwProj.Models.AuthService.ViewModels; using HwProj.Models.Result; using Microsoft.EntityFrameworkCore; diff --git a/HwProj.AuthService/HwProj.AuthService.API/Events/AdminRegisterEvent.cs b/HwProj.Common/HwProj.Models/AuthService/Events/AdminRegisterEvent.cs similarity index 73% rename from HwProj.AuthService/HwProj.AuthService.API/Events/AdminRegisterEvent.cs rename to HwProj.Common/HwProj.Models/AuthService/Events/AdminRegisterEvent.cs index 2d389784d..29816b4a6 100644 --- a/HwProj.AuthService/HwProj.AuthService.API/Events/AdminRegisterEvent.cs +++ b/HwProj.Common/HwProj.Models/AuthService/Events/AdminRegisterEvent.cs @@ -1,4 +1,6 @@ -namespace HwProj.AuthService.API.Events; +using HwProj.Models.AuthService.Events; + +namespace HwProj.AuthService.API.Events; public class AdminRegisterEvent : RegisterEvent { diff --git a/HwProj.AuthService/HwProj.AuthService.API/Events/InviteLecturerEvent.cs b/HwProj.Common/HwProj.Models/AuthService/Events/InviteLecturerEvent.cs similarity index 78% rename from HwProj.AuthService/HwProj.AuthService.API/Events/InviteLecturerEvent.cs rename to HwProj.Common/HwProj.Models/AuthService/Events/InviteLecturerEvent.cs index f277436eb..5dd4194ee 100644 --- a/HwProj.AuthService/HwProj.AuthService.API/Events/InviteLecturerEvent.cs +++ b/HwProj.Common/HwProj.Models/AuthService/Events/InviteLecturerEvent.cs @@ -1,6 +1,6 @@ using HwProj.EventBus.Client; -namespace HwProj.AuthService.API.Events; +namespace HwProj.Models.AuthService.Events; public class InviteLecturerEvent : Event { diff --git a/HwProj.AuthService/HwProj.AuthService.API/Events/RegisterEvent.cs b/HwProj.Common/HwProj.Models/AuthService/Events/RegisterEvent.cs similarity index 92% rename from HwProj.AuthService/HwProj.AuthService.API/Events/RegisterEvent.cs rename to HwProj.Common/HwProj.Models/AuthService/Events/RegisterEvent.cs index a4ae1e98b..25d7d6fc7 100644 --- a/HwProj.AuthService/HwProj.AuthService.API/Events/RegisterEvent.cs +++ b/HwProj.Common/HwProj.Models/AuthService/Events/RegisterEvent.cs @@ -1,6 +1,6 @@ using HwProj.EventBus.Client; -namespace HwProj.AuthService.API.Events; +namespace HwProj.Models.AuthService.Events; public abstract class RegisterEvent : Event { diff --git a/HwProj.AuthService/HwProj.AuthService.API/Events/StudentRegisterEvent.cs b/HwProj.Common/HwProj.Models/AuthService/Events/StudentRegisterEvent.cs similarity index 74% rename from HwProj.AuthService/HwProj.AuthService.API/Events/StudentRegisterEvent.cs rename to HwProj.Common/HwProj.Models/AuthService/Events/StudentRegisterEvent.cs index e276404d2..dafe3f425 100644 --- a/HwProj.AuthService/HwProj.AuthService.API/Events/StudentRegisterEvent.cs +++ b/HwProj.Common/HwProj.Models/AuthService/Events/StudentRegisterEvent.cs @@ -1,4 +1,6 @@ -namespace HwProj.AuthService.API.Events; +using HwProj.Models.AuthService.Events; + +namespace HwProj.AuthService.API.Events; public class StudentRegisterEvent : RegisterEvent { diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Events/LecturerAcceptToCourseEvent.cs b/HwProj.Common/HwProj.Models/CoursesService/Events/LecturerAcceptToCourseEvent.cs similarity index 84% rename from HwProj.CoursesService/HwProj.CoursesService.API/Events/LecturerAcceptToCourseEvent.cs rename to HwProj.Common/HwProj.Models/CoursesService/Events/LecturerAcceptToCourseEvent.cs index 7376481df..af492c704 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Events/LecturerAcceptToCourseEvent.cs +++ b/HwProj.Common/HwProj.Models/CoursesService/Events/LecturerAcceptToCourseEvent.cs @@ -1,6 +1,6 @@ using HwProj.EventBus.Client; -namespace HwProj.CoursesService.API.Events; +namespace HwProj.Models.CoursesService.Events; public class LecturerAcceptToCourseEvent : Event { diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Events/LecturerInvitedToCourseEvent.cs b/HwProj.Common/HwProj.Models/CoursesService/Events/LecturerInvitedToCourseEvent.cs similarity index 84% rename from HwProj.CoursesService/HwProj.CoursesService.API/Events/LecturerInvitedToCourseEvent.cs rename to HwProj.Common/HwProj.Models/CoursesService/Events/LecturerInvitedToCourseEvent.cs index 883fae621..e5e254424 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Events/LecturerInvitedToCourseEvent.cs +++ b/HwProj.Common/HwProj.Models/CoursesService/Events/LecturerInvitedToCourseEvent.cs @@ -1,6 +1,6 @@ using HwProj.EventBus.Client; -namespace HwProj.CoursesService.API.Events; +namespace HwProj.Models.CoursesService.Events; public class LecturerInvitedToCourseEvent : Event { diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Events/LecturerRejectToCourseEvent.cs b/HwProj.Common/HwProj.Models/CoursesService/Events/LecturerRejectToCourseEvent.cs similarity index 84% rename from HwProj.CoursesService/HwProj.CoursesService.API/Events/LecturerRejectToCourseEvent.cs rename to HwProj.Common/HwProj.Models/CoursesService/Events/LecturerRejectToCourseEvent.cs index 05e0aa550..331f2f0af 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Events/LecturerRejectToCourseEvent.cs +++ b/HwProj.Common/HwProj.Models/CoursesService/Events/LecturerRejectToCourseEvent.cs @@ -1,6 +1,6 @@ using HwProj.EventBus.Client; -namespace HwProj.CoursesService.API.Events; +namespace HwProj.Models.CoursesService.Events; public class LecturerRejectToCourseEvent : Event { diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Events/NewCourseMateEvent.cs b/HwProj.Common/HwProj.Models/CoursesService/Events/NewCourseMateEvent.cs similarity index 85% rename from HwProj.CoursesService/HwProj.CoursesService.API/Events/NewCourseMateEvent.cs rename to HwProj.Common/HwProj.Models/CoursesService/Events/NewCourseMateEvent.cs index c48968346..8db7f740a 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Events/NewCourseMateEvent.cs +++ b/HwProj.Common/HwProj.Models/CoursesService/Events/NewCourseMateEvent.cs @@ -1,6 +1,6 @@ using HwProj.EventBus.Client; -namespace HwProj.CoursesService.API.Events; +namespace HwProj.Models.CoursesService.Events; public class NewCourseMateEvent : Event { diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Events/NewHomeworkEvent.cs b/HwProj.Common/HwProj.Models/CoursesService/Events/NewHomeworkEvent.cs similarity index 87% rename from HwProj.CoursesService/HwProj.CoursesService.API/Events/NewHomeworkEvent.cs rename to HwProj.Common/HwProj.Models/CoursesService/Events/NewHomeworkEvent.cs index d1778bf27..13c580c39 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Events/NewHomeworkEvent.cs +++ b/HwProj.Common/HwProj.Models/CoursesService/Events/NewHomeworkEvent.cs @@ -1,7 +1,7 @@ using HwProj.EventBus.Client; using HwProj.Models.CoursesService.ViewModels; -namespace HwProj.CoursesService.API.Events; +namespace HwProj.Models.CoursesService.Events; public class NewHomeworkEvent : Event { diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Events/NewHomeworkTaskEvent.cs b/HwProj.Common/HwProj.Models/CoursesService/Events/NewHomeworkTaskEvent.cs similarity index 91% rename from HwProj.CoursesService/HwProj.CoursesService.API/Events/NewHomeworkTaskEvent.cs rename to HwProj.Common/HwProj.Models/CoursesService/Events/NewHomeworkTaskEvent.cs index ee126f776..e2fa95b41 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Events/NewHomeworkTaskEvent.cs +++ b/HwProj.Common/HwProj.Models/CoursesService/Events/NewHomeworkTaskEvent.cs @@ -2,7 +2,7 @@ using HwProj.EventBus.Client; using HwProj.Models.CoursesService.ViewModels; -namespace HwProj.CoursesService.API.Events; +namespace HwProj.Models.CoursesService.Events; public class NewHomeworkTaskEvent : Event { diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Events/UpdateHomeworkEvent.cs b/HwProj.Common/HwProj.Models/CoursesService/Events/UpdateHomeworkEvent.cs similarity index 88% rename from HwProj.CoursesService/HwProj.CoursesService.API/Events/UpdateHomeworkEvent.cs rename to HwProj.Common/HwProj.Models/CoursesService/Events/UpdateHomeworkEvent.cs index 87ebdca75..5bfd97d80 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Events/UpdateHomeworkEvent.cs +++ b/HwProj.Common/HwProj.Models/CoursesService/Events/UpdateHomeworkEvent.cs @@ -1,7 +1,7 @@ using HwProj.EventBus.Client; using HwProj.Models.CoursesService.ViewModels; -namespace HwProj.CoursesService.API.Events; +namespace HwProj.Models.CoursesService.Events; public class UpdateHomeworkEvent : Event { diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Events/UpdateSolutionMaxRatingEvent.cs b/HwProj.Common/HwProj.Models/CoursesService/Events/UpdateSolutionMaxRatingEvent.cs similarity index 89% rename from HwProj.CoursesService/HwProj.CoursesService.API/Events/UpdateSolutionMaxRatingEvent.cs rename to HwProj.Common/HwProj.Models/CoursesService/Events/UpdateSolutionMaxRatingEvent.cs index 9e7cafcd5..df3d7b4cf 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Events/UpdateSolutionMaxRatingEvent.cs +++ b/HwProj.Common/HwProj.Models/CoursesService/Events/UpdateSolutionMaxRatingEvent.cs @@ -1,6 +1,6 @@ using HwProj.EventBus.Client; -namespace HwProj.CoursesService.API.Events; +namespace HwProj.Models.CoursesService.Events; public class UpdateSolutionMaxRatingEvent : Event { diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Events/UpdateTaskMaxRatingEvent.cs b/HwProj.Common/HwProj.Models/CoursesService/Events/UpdateTaskMaxRatingEvent.cs similarity index 90% rename from HwProj.CoursesService/HwProj.CoursesService.API/Events/UpdateTaskMaxRatingEvent.cs rename to HwProj.Common/HwProj.Models/CoursesService/Events/UpdateTaskMaxRatingEvent.cs index ba561e763..082dd87e1 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Events/UpdateTaskMaxRatingEvent.cs +++ b/HwProj.Common/HwProj.Models/CoursesService/Events/UpdateTaskMaxRatingEvent.cs @@ -1,7 +1,7 @@ using HwProj.EventBus.Client; using HwProj.Models.CoursesService.ViewModels; -namespace HwProj.CoursesService.API.Events; +namespace HwProj.Models.CoursesService.Events; public class UpdateTaskMaxRatingEvent : Event { diff --git a/HwProj.Common/HwProj.Models/HwProj.Models.csproj b/HwProj.Common/HwProj.Models/HwProj.Models.csproj index 2cd83d2dc..a8a1b6c56 100644 --- a/HwProj.Common/HwProj.Models/HwProj.Models.csproj +++ b/HwProj.Common/HwProj.Models/HwProj.Models.csproj @@ -13,6 +13,7 @@ + diff --git a/HwProj.SolutionsService/HwProj.SolutionsService.API/Events/RateEvent.cs b/HwProj.Common/HwProj.Models/SolutionsService/Events/RateEvent.cs similarity index 80% rename from HwProj.SolutionsService/HwProj.SolutionsService.API/Events/RateEvent.cs rename to HwProj.Common/HwProj.Models/SolutionsService/Events/RateEvent.cs index cecc72814..97b1084ff 100644 --- a/HwProj.SolutionsService/HwProj.SolutionsService.API/Events/RateEvent.cs +++ b/HwProj.Common/HwProj.Models/SolutionsService/Events/RateEvent.cs @@ -1,8 +1,7 @@ using HwProj.EventBus.Client; using HwProj.Models.CoursesService.ViewModels; -using HwProj.Models.SolutionsService; -namespace HwProj.SolutionsService.API.Events; +namespace HwProj.Models.SolutionsService.Events; public class RateEvent : Event { diff --git a/HwProj.SolutionsService/HwProj.SolutionsService.API/Events/StudentPassTaskEvent.cs b/HwProj.Common/HwProj.Models/SolutionsService/Events/StudentPassTaskEvent.cs similarity index 87% rename from HwProj.SolutionsService/HwProj.SolutionsService.API/Events/StudentPassTaskEvent.cs rename to HwProj.Common/HwProj.Models/SolutionsService/Events/StudentPassTaskEvent.cs index 626090563..71613200f 100644 --- a/HwProj.SolutionsService/HwProj.SolutionsService.API/Events/StudentPassTaskEvent.cs +++ b/HwProj.Common/HwProj.Models/SolutionsService/Events/StudentPassTaskEvent.cs @@ -1,9 +1,8 @@ using HwProj.EventBus.Client; using HwProj.Models.AuthService.DTO; using HwProj.Models.CoursesService.ViewModels; -using HwProj.Models.SolutionsService; -namespace HwProj.SolutionsService.API.Events; +namespace HwProj.Models.SolutionsService.Events; public class StudentPassTaskEvent : Event { diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Services/CoursesService.cs b/HwProj.CoursesService/HwProj.CoursesService.API/Services/CoursesService.cs index 055040de1..7e93559fc 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Services/CoursesService.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.API/Services/CoursesService.cs @@ -3,12 +3,12 @@ using System.Linq; using System.Threading.Tasks; using HwProj.AuthService.Client; -using HwProj.CoursesService.API.Events; using HwProj.CoursesService.API.Models; using HwProj.CoursesService.API.Repositories; using HwProj.EventBus.Client.Interfaces; using HwProj.Models; using HwProj.Models.AuthService.DTO; +using HwProj.Models.CoursesService.Events; using HwProj.Models.Roles; using Microsoft.EntityFrameworkCore; diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Services/HomeworksService.cs b/HwProj.CoursesService/HwProj.CoursesService.API/Services/HomeworksService.cs index 63700a806..1de0a4943 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Services/HomeworksService.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.API/Services/HomeworksService.cs @@ -3,8 +3,8 @@ using HwProj.CoursesService.API.Models; using HwProj.CoursesService.API.Repositories; using HwProj.EventBus.Client.Interfaces; -using HwProj.CoursesService.API.Events; using HwProj.Models; +using HwProj.Models.CoursesService.Events; using HwProj.Models.CoursesService.ViewModels; namespace HwProj.CoursesService.API.Services; diff --git a/HwProj.CoursesService/HwProj.CoursesService.API/Services/TasksService.cs b/HwProj.CoursesService/HwProj.CoursesService.API/Services/TasksService.cs index 6d44191ff..917f7e42d 100644 --- a/HwProj.CoursesService/HwProj.CoursesService.API/Services/TasksService.cs +++ b/HwProj.CoursesService/HwProj.CoursesService.API/Services/TasksService.cs @@ -1,10 +1,10 @@ using System.Threading.Tasks; using AutoMapper; -using HwProj.CoursesService.API.Events; using HwProj.CoursesService.API.Models; using HwProj.CoursesService.API.Repositories; using HwProj.EventBus.Client.Interfaces; using HwProj.Models; +using HwProj.Models.CoursesService.Events; using HwProj.Models.CoursesService.ViewModels; namespace HwProj.CoursesService.API.Services; diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/InviteLecturerEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/InviteLecturerEventHandler.cs index 0e9d18f39..cf236388f 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/InviteLecturerEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/InviteLecturerEventHandler.cs @@ -1,7 +1,7 @@ using System.Threading.Tasks; -using HwProj.AuthService.API.Events; using HwProj.EventBus.Client.Interfaces; using HwProj.Models; +using HwProj.Models.AuthService.Events; using HwProj.Models.NotificationsService; using HwProj.NotificationsService.API.Repositories; using HwProj.NotificationsService.API.Services; diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/LecturerAcceptToCourseEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/LecturerAcceptToCourseEventHandler.cs index dbe5fe418..aa440df4c 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/LecturerAcceptToCourseEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/LecturerAcceptToCourseEventHandler.cs @@ -1,8 +1,8 @@ using System.Threading.Tasks; using HwProj.AuthService.Client; -using HwProj.CoursesService.API.Events; using HwProj.EventBus.Client.Interfaces; using HwProj.Models; +using HwProj.Models.CoursesService.Events; using HwProj.Models.NotificationsService; using HwProj.NotificationsService.API.Repositories; using HwProj.NotificationsService.API.Services; diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/LecturerInvitedToCourseEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/LecturerInvitedToCourseEventHandler.cs index e5fa13a51..6c7f666fc 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/LecturerInvitedToCourseEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/LecturerInvitedToCourseEventHandler.cs @@ -1,7 +1,7 @@ using System.Threading.Tasks; -using HwProj.CoursesService.API.Events; using HwProj.EventBus.Client.Interfaces; using HwProj.Models; +using HwProj.Models.CoursesService.Events; using HwProj.Models.NotificationsService; using HwProj.NotificationsService.API.Repositories; using HwProj.NotificationsService.API.Services; diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/LecturerRejectToCourseEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/LecturerRejectToCourseEventHandler.cs index 8880aff63..708dd419d 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/LecturerRejectToCourseEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/LecturerRejectToCourseEventHandler.cs @@ -1,8 +1,8 @@ using System.Threading.Tasks; using HwProj.AuthService.Client; -using HwProj.CoursesService.API.Events; using HwProj.EventBus.Client.Interfaces; using HwProj.Models; +using HwProj.Models.CoursesService.Events; using HwProj.Models.NotificationsService; using HwProj.NotificationsService.API.Repositories; using HwProj.NotificationsService.API.Services; diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/NewCourseMateHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/NewCourseMateHandler.cs index 9df438e79..e12c1207a 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/NewCourseMateHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/NewCourseMateHandler.cs @@ -1,8 +1,8 @@ using System.Threading.Tasks; using HwProj.AuthService.Client; -using HwProj.CoursesService.API.Events; using HwProj.EventBus.Client.Interfaces; using HwProj.Models; +using HwProj.Models.CoursesService.Events; using HwProj.Models.NotificationsService; using HwProj.NotificationsService.API.Repositories; using HwProj.NotificationsService.API.Services; diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/NewHomeworkEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/NewHomeworkEventHandler.cs index 06330f483..a4c51b3a7 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/NewHomeworkEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/NewHomeworkEventHandler.cs @@ -4,8 +4,8 @@ using HwProj.EventBus.Client.Interfaces; using HwProj.Models.NotificationsService; using HwProj.NotificationsService.API.Repositories; -using HwProj.CoursesService.API.Events; using HwProj.Models; +using HwProj.Models.CoursesService.Events; using HwProj.NotificationsService.API.Services; using Microsoft.Extensions.Configuration; diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/NewHomeworkTaskEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/NewHomeworkTaskEventHandler.cs index 72bb38b6f..798b50b88 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/NewHomeworkTaskEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/NewHomeworkTaskEventHandler.cs @@ -4,8 +4,8 @@ using HwProj.EventBus.Client.Interfaces; using HwProj.Models.NotificationsService; using HwProj.NotificationsService.API.Repositories; -using HwProj.CoursesService.API.Events; using HwProj.Models; +using HwProj.Models.CoursesService.Events; using HwProj.NotificationsService.API.Services; using Microsoft.Extensions.Configuration; diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/RateEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/RateEventHandler.cs index f9e1e75f9..f8c75b3a7 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/RateEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/RateEventHandler.cs @@ -3,9 +3,9 @@ using HwProj.EventBus.Client.Interfaces; using HwProj.Models; using HwProj.Models.NotificationsService; +using HwProj.Models.SolutionsService.Events; using HwProj.NotificationsService.API.Repositories; using HwProj.NotificationsService.API.Services; -using HwProj.SolutionsService.API.Events; using Microsoft.Extensions.Configuration; namespace HwProj.NotificationsService.API.EventHandlers; diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/StudentPassTaskEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/StudentPassTaskEventHandler.cs index 16269401a..cc99a8678 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/StudentPassTaskEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/StudentPassTaskEventHandler.cs @@ -3,9 +3,9 @@ using HwProj.EventBus.Client.Interfaces; using HwProj.Models; using HwProj.Models.NotificationsService; +using HwProj.Models.SolutionsService.Events; using HwProj.NotificationsService.API.Repositories; using HwProj.NotificationsService.API.Services; -using HwProj.SolutionsService.API.Events; using Microsoft.Extensions.Configuration; namespace HwProj.NotificationsService.API.EventHandlers; diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/UpdateHomeworkEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/UpdateHomeworkEventHandler.cs index 051682c00..7dc870be2 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/UpdateHomeworkEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/UpdateHomeworkEventHandler.cs @@ -3,8 +3,8 @@ using HwProj.EventBus.Client.Interfaces; using HwProj.Models.NotificationsService; using HwProj.NotificationsService.API.Repositories; -using HwProj.CoursesService.API.Events; using HwProj.Models; +using HwProj.Models.CoursesService.Events; using HwProj.NotificationsService.API.Services; using Microsoft.Extensions.Configuration; diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/UpdateTaskMaxRatingEventHandler.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/UpdateTaskMaxRatingEventHandler.cs index 1289a1333..0c7c22143 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/UpdateTaskMaxRatingEventHandler.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/EventHandlers/UpdateTaskMaxRatingEventHandler.cs @@ -4,9 +4,9 @@ using HwProj.EventBus.Client.Interfaces; using HwProj.Models.NotificationsService; using HwProj.NotificationsService.API.Repositories; -using HwProj.CoursesService.API.Events; using HwProj.Models; using HwProj.Models.AuthService.DTO; +using HwProj.Models.CoursesService.Events; using HwProj.NotificationsService.API.Services; using Microsoft.Extensions.Configuration; diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/HwProj.NotificationsService.API.csproj b/HwProj.NotificationsService/HwProj.NotificationsService.API/HwProj.NotificationsService.API.csproj index 399462cf9..dcf3cd679 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/HwProj.NotificationsService.API.csproj +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/HwProj.NotificationsService.API.csproj @@ -20,13 +20,10 @@ - - - diff --git a/HwProj.NotificationsService/HwProj.NotificationsService.API/Startup.cs b/HwProj.NotificationsService/HwProj.NotificationsService.API/Startup.cs index bdf2a04fb..2c989f328 100644 --- a/HwProj.NotificationsService/HwProj.NotificationsService.API/Startup.cs +++ b/HwProj.NotificationsService/HwProj.NotificationsService.API/Startup.cs @@ -11,11 +11,12 @@ using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; -using HwProj.CoursesService.API.Events; using HwProj.CoursesService.Client; -using HwProj.SolutionsService.API.Events; +using HwProj.Models.AuthService.Events; +using HwProj.Models.CoursesService.Events; +using HwProj.Models.SolutionsService.Events; using HwProj.SolutionsService.Client; -using UpdateTaskMaxRatingEvent = HwProj.CoursesService.API.Events.UpdateTaskMaxRatingEvent; +using UpdateTaskMaxRatingEvent = HwProj.Models.CoursesService.Events.UpdateTaskMaxRatingEvent; namespace HwProj.NotificationsService.API; diff --git a/HwProj.SolutionsService/HwProj.SolutionsService.API/Services/SolutionsService.cs b/HwProj.SolutionsService/HwProj.SolutionsService.API/Services/SolutionsService.cs index 503b348e3..8d1cd22d2 100644 --- a/HwProj.SolutionsService/HwProj.SolutionsService.API/Services/SolutionsService.cs +++ b/HwProj.SolutionsService/HwProj.SolutionsService.API/Services/SolutionsService.cs @@ -8,7 +8,7 @@ using HwProj.Models.AuthService.DTO; using HwProj.Models.CoursesService.ViewModels; using HwProj.Models.SolutionsService; -using HwProj.SolutionsService.API.Events; +using HwProj.Models.SolutionsService.Events; using HwProj.SolutionsService.API.Repositories; using Microsoft.EntityFrameworkCore; From 98241beff6852a85b86aa61012aa89947bd4ce12 Mon Sep 17 00:00:00 2001 From: Roman Pozharskiy Date: Fri, 19 May 2023 08:15:39 +0300 Subject: [PATCH 14/14] fix unrated solutions request --- .../Controllers/SolutionsController.cs | 25 ++++++++++--------- 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/HwProj.SolutionsService/HwProj.SolutionsService.API/Controllers/SolutionsController.cs b/HwProj.SolutionsService/HwProj.SolutionsService.API/Controllers/SolutionsController.cs index e0bf6d469..8fbf67e69 100644 --- a/HwProj.SolutionsService/HwProj.SolutionsService.API/Controllers/SolutionsController.cs +++ b/HwProj.SolutionsService/HwProj.SolutionsService.API/Controllers/SolutionsController.cs @@ -161,18 +161,19 @@ public async Task GetCourseStat(long courseId, [FromQuery] string [HttpPost("allUnrated")] public async Task GetAllUnratedSolutionsForTasks([FromBody] long[] taskIds) { - // TODO: Fix - return Array.Empty(); - var solutions = await _solutionsRepository - .FindAll(t => taskIds.Contains(t.TaskId)) - .GroupBy(t => new { t.TaskId, t.StudentId }) - .Select(t => t.OrderByDescending(x => x.PublicationDate)) - .Select(t => new + // TODO: Fix + var groupedSolutions = await _solutionsRepository + .FindAll(s => taskIds.Contains(s.TaskId)) + .GroupBy(s => new { s.TaskId, s.StudentId }) + .Select(st => st.OrderByDescending(x => x.PublicationDate).ToArray()) + .ToListAsync(); + var unratedSolutions = groupedSolutions + .Select(s => new { - LastSolution = t.FirstOrDefault(), - IsFirstTry = t.Skip(1).All(s => s.State == SolutionState.Posted) + LastSolution = s.FirstOrDefault(), + IsFirstTry = s.Skip(1).All(solution => solution.State == SolutionState.Posted) }) - .Where(t => t.LastSolution != null && t.LastSolution.State == SolutionState.Posted) + .Where(t => t.LastSolution is { State: SolutionState.Posted }) .OrderBy(t => t.LastSolution!.PublicationDate) .Select(t => new SolutionPreviewDto { @@ -181,8 +182,8 @@ public async Task GetAllUnratedSolutionsForTasks([FromBody PublicationDate = t.LastSolution.PublicationDate, IsFirstTry = t.IsFirstTry }) - .ToArrayAsync(); + .ToArray(); - return solutions; + return unratedSolutions; } } \ No newline at end of file