diff --git a/AsbCloudApp/Data/NotificationDto.cs b/AsbCloudApp/Data/NotificationDto.cs index 06fbc189..ba6c5bce 100644 --- a/AsbCloudApp/Data/NotificationDto.cs +++ b/AsbCloudApp/Data/NotificationDto.cs @@ -1,4 +1,5 @@ using System; +using System.ComponentModel.DataAnnotations; namespace AsbCloudApp.Data; @@ -25,12 +26,14 @@ public class NotificationDto : IId /// /// Заголовок уведомления /// + [Required, StringLength(300, MinimumLength = 1, ErrorMessage = "Заголовок должен мыть не меньше 1-го знака и не больше 300")] public string Title { get; set; } = null!; - /// - /// Сообщение уведомления - /// - public string Message { get; set; } = null!; + /// + /// Сообщение уведомления + /// + [Required, StringLength(2048, MinimumLength = 1, ErrorMessage = "Заголовок должен мыть не меньше 1-го знака и не больше 2048")] + public string Message { get; set; } = null!; /// /// Дата регистрации уведомления @@ -90,6 +93,7 @@ public class NotificationDto : IId /// 0 - SignalR /// 1 - Email /// + [Range(0,1)] public int IdTransportType { get; set; } /// diff --git a/AsbCloudApp/Data/ProcessMap/ProcessMapWellboreDevelopmentDto.cs b/AsbCloudApp/Data/ProcessMap/ProcessMapWellboreDevelopmentDto.cs index 260c41ef..08fb9b50 100644 --- a/AsbCloudApp/Data/ProcessMap/ProcessMapWellboreDevelopmentDto.cs +++ b/AsbCloudApp/Data/ProcessMap/ProcessMapWellboreDevelopmentDto.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace AsbCloudApp.Data.ProcessMap; @@ -6,7 +7,7 @@ namespace AsbCloudApp.Data.ProcessMap; /// /// РТК план проработка скважины /// -public class ProcessMapWellboreDevelopmentDto : IId, IWellRelated +public class ProcessMapWellboreDevelopmentDto : IId, IWellRelated, IValidatableObject { /// public int Id { get; set; } @@ -94,4 +95,13 @@ public class ProcessMapWellboreDevelopmentDto : IId, IWellRelated /// Комментарий /// public string? Comment { get; set; } + + /// + public IEnumerable Validate(ValidationContext validationContext) + { + if (DepthEnd < DepthStart) + yield return new ValidationResult($"{nameof(DepthEnd)}:{DepthEnd:#0.0} меньше {nameof(DepthStart)}:{DepthStart:#0.0}", new[] { nameof(DepthEnd), nameof(DepthStart) }); + + yield break; + } } \ No newline at end of file diff --git a/AsbCloudApp/Data/WellDto.cs b/AsbCloudApp/Data/WellDto.cs index b347bdd8..979d6885 100644 --- a/AsbCloudApp/Data/WellDto.cs +++ b/AsbCloudApp/Data/WellDto.cs @@ -47,6 +47,7 @@ namespace AsbCloudApp.Data /// /// ID типа скважины /// + [Range(1, 2, ErrorMessage = "Тип скважины указан неправильно.")] public int IdWellType { get; set; } /// @@ -59,6 +60,7 @@ namespace AsbCloudApp.Data /// 1 - в работе, /// 2 - завершена /// + [Range(0, 2, ErrorMessage = "Текущее состояние работы скважины указано неправильно.")] public int IdState { get; set; } /// diff --git a/AsbCloudApp/Data/WellOperationImport/WellOperationImportOptionsDto.cs b/AsbCloudApp/Data/WellOperationImport/WellOperationImportOptionsDto.cs index 5a1efc22..b085754f 100644 --- a/AsbCloudApp/Data/WellOperationImport/WellOperationImportOptionsDto.cs +++ b/AsbCloudApp/Data/WellOperationImport/WellOperationImportOptionsDto.cs @@ -1,3 +1,5 @@ +using System.ComponentModel.DataAnnotations; + namespace AsbCloudApp.Data.WellOperationImport; /// @@ -8,7 +10,8 @@ public class WellOperationParserOptionsDto /// /// Название листа /// - public string? SheetName { get; set; } + [StringLength(250, MinimumLength =1, ErrorMessage = "Название листа должно быть задано")] + public string SheetName { get; set; } = null!; /// /// Id шаблона diff --git a/AsbCloudApp/Exceptions/ArgumentInvalidException.cs b/AsbCloudApp/Exceptions/ArgumentInvalidException.cs index af239d00..4fe150e3 100644 --- a/AsbCloudApp/Exceptions/ArgumentInvalidException.cs +++ b/AsbCloudApp/Exceptions/ArgumentInvalidException.cs @@ -15,9 +15,9 @@ namespace AsbCloudApp.Exceptions /// /// конструктор /// - /// /// - public ArgumentInvalidException(string message, string paramName) + /// + public ArgumentInvalidException(string paramName, string message) : base(message) { ParamName = paramName; diff --git a/AsbCloudApp/Repositories/IWellFinalDocumentsRepository.cs b/AsbCloudApp/Repositories/IWellFinalDocumentsRepository.cs index d80bd352..3f3ad72e 100644 --- a/AsbCloudApp/Repositories/IWellFinalDocumentsRepository.cs +++ b/AsbCloudApp/Repositories/IWellFinalDocumentsRepository.cs @@ -18,7 +18,7 @@ namespace AsbCloudApp.Repositories /// /// /// - Task> UpdateRangeAsync(int idWell, IEnumerable? dtos, CancellationToken token); + Task> UpdateRangeAsync(int idWell, IEnumerable dtos, CancellationToken token); /// /// Получение всех записей diff --git a/AsbCloudApp/Services/Notifications/NotificationService.cs b/AsbCloudApp/Services/Notifications/NotificationService.cs index 901a5348..85c521e3 100644 --- a/AsbCloudApp/Services/Notifications/NotificationService.cs +++ b/AsbCloudApp/Services/Notifications/NotificationService.cs @@ -43,7 +43,7 @@ public class NotificationService CancellationToken cancellationToken) { var notificationCategory = await notificationCategoryRepository.GetOrDefaultAsync(request.IdNotificationCategory, cancellationToken) - ?? throw new ArgumentInvalidException("Категория уведомления не найдена", nameof(request.IdNotificationCategory)); + ?? throw new ArgumentInvalidException(nameof(request.IdNotificationCategory), "Категория уведомления не найдена"); var notification = new NotificationDto { @@ -75,10 +75,10 @@ public class NotificationService CancellationToken cancellationToken) { var notification = await notificationRepository.GetOrDefaultAsync(idNotification, cancellationToken) - ?? throw new ArgumentInvalidException("Уведомление не найдено", nameof(idNotification)); + ?? throw new ArgumentInvalidException(nameof(idNotification), "Уведомление не найдено"); if(isRead && !notification.SentDate.HasValue) - throw new ArgumentInvalidException("Уведомление не может быть прочитано", nameof(isRead)); + throw new ArgumentInvalidException(nameof(isRead), "Уведомление не может быть прочитано"); notification.ReadDate = isRead ? DateTime.UtcNow : null; @@ -111,7 +111,7 @@ public class NotificationService { var notificationTransportService = notificationTransportServices .FirstOrDefault(s => s.IdTransportType == idTransportType) - ?? throw new ArgumentInvalidException("Доставщик уведомлений не найден", nameof(idTransportType)); + ?? throw new ArgumentInvalidException(nameof(idTransportType), "Доставщик уведомлений не найден"); return notificationTransportService; } diff --git a/AsbCloudInfrastructure/ReportDataSourcePgCloud.cs b/AsbCloudInfrastructure/ReportDataSourcePgCloud.cs index 24bfd399..d06a5f1a 100644 --- a/AsbCloudInfrastructure/ReportDataSourcePgCloud.cs +++ b/AsbCloudInfrastructure/ReportDataSourcePgCloud.cs @@ -37,10 +37,10 @@ namespace AsbCloudInfrastructure .ThenInclude(r => r.Company) .Include(w => w.Telemetry) .FirstOrDefault(w => w.Id == idWell) - ?? throw new ArgumentInvalidException("idWell doesn`t exist", nameof(idWell)); + ?? throw new ArgumentInvalidException(nameof(idWell), "idWell doesn`t exist"); idTelemetry = well?.IdTelemetry - ?? throw new ArgumentInvalidException($"Well {idWell} doesn't contain telemetry", nameof(idWell)); + ?? throw new ArgumentInvalidException(nameof(idWell), $"Well {idWell} doesn't contain telemetry"); events = context.TelemetryEvents .Where(e => e.IdTelemetry == idTelemetry) diff --git a/AsbCloudInfrastructure/Repository/FaqRepository.cs b/AsbCloudInfrastructure/Repository/FaqRepository.cs index d266494c..efe09074 100644 --- a/AsbCloudInfrastructure/Repository/FaqRepository.cs +++ b/AsbCloudInfrastructure/Repository/FaqRepository.cs @@ -93,7 +93,7 @@ namespace AsbCloudInfrastructure.Repository { var sourceFaqs = db.Faqs.Where(e => e.Id == sourceId1 || e.Id == sourceId2).ToArray(); if (sourceFaqs.Count() < 2) - throw new ArgumentInvalidException("Questions with target ids don't exist", nameof(sourceFaqs)); + throw new ArgumentInvalidException(nameof(sourceFaqs), "Questions with target ids don't exist"); var newFaq = new Faq() { @@ -115,7 +115,7 @@ namespace AsbCloudInfrastructure.Repository await db.SaveChangesAsync(token).ConfigureAwait(false); if (newFaq.Id == 0) - throw new ArgumentInvalidException("Error creating new question", nameof(newFaq)); + throw new ArgumentInvalidException(nameof(sourceId1), "Error creating new question"); foreach (var sourceFaq in sourceFaqs) { @@ -138,9 +138,8 @@ namespace AsbCloudInfrastructure.Repository public async Task MarkAsDeletedAsync(int id, CancellationToken token) { - var entity = db.Faqs.FirstOrDefault(e => e.Id == id); - if (entity is null) - throw new ArgumentInvalidException("Question doesn't exist", nameof(id)); + var entity = db.Faqs.FirstOrDefault(e => e.Id == id) + ?? throw new ArgumentInvalidException(nameof(id), "Question doesn't exist"); entity.State = Faq.StateDeleted; entity.DateLastEditedQuestion = DateTimeOffset.UtcNow; @@ -151,9 +150,8 @@ namespace AsbCloudInfrastructure.Repository public async Task DeleteAsync(int id, CancellationToken token) { - var faq = db.Faqs.FirstOrDefault(f => f.Id == id); - if (faq is null) - throw new ArgumentInvalidException("Question doesn't exist", nameof(id)); + var faq = db.Faqs.FirstOrDefault(f => f.Id == id) + ?? throw new ArgumentInvalidException(nameof(id), "Question doesn't exist"); db.Faqs.Remove(faq); return await db.SaveChangesAsync(token); diff --git a/AsbCloudInfrastructure/Repository/TrajectoryPlanRepository.cs b/AsbCloudInfrastructure/Repository/TrajectoryPlanRepository.cs index 94b66365..bab706b3 100644 --- a/AsbCloudInfrastructure/Repository/TrajectoryPlanRepository.cs +++ b/AsbCloudInfrastructure/Repository/TrajectoryPlanRepository.cs @@ -28,7 +28,8 @@ namespace AsbCloudInfrastructure.Repository { var idWell = plannedTrajectoryRows.First().IdWell; if (!plannedTrajectoryRows.All(r => r.IdWell == idWell)) - throw new ArgumentInvalidException("Все строки должны относиться к одной скважине", nameof(plannedTrajectoryRows)); + throw new ArgumentInvalidException(nameof(plannedTrajectoryRows), "Все строки должны относиться к одной скважине"); + var offsetHours = wellService.GetTimezone(idWell).Hours; var entities = plannedTrajectoryRows .Select(e => @@ -77,9 +78,9 @@ namespace AsbCloudInfrastructure.Repository /// public async Task> GetAsync(int idWell, CancellationToken token) { - var well = wellService.GetOrDefault(idWell); - if (well is null || well.Timezone is null) - throw new ArgumentInvalidException("idWell doesn`t exist", nameof(idWell)); + var well = wellService.GetOrDefault(idWell) + ?? throw new ArgumentInvalidException(nameof(idWell), "idWell doesn`t exist"); + var offsetHours = well.Timezone.Hours; var query = db.PlannedTrajectories .AsNoTracking() diff --git a/AsbCloudInfrastructure/Repository/UserRepository.cs b/AsbCloudInfrastructure/Repository/UserRepository.cs index 4876a9e2..df58affe 100644 --- a/AsbCloudInfrastructure/Repository/UserRepository.cs +++ b/AsbCloudInfrastructure/Repository/UserRepository.cs @@ -97,13 +97,10 @@ namespace AsbCloudInfrastructure.Repository public async Task UpdateAsync(UserExtendedDto dto, CancellationToken token) { if (dto.Id <= 1) - throw new ArgumentInvalidException - ($"Invalid id {dto.Id}. You can't edit this user.", nameof(dto)); + throw new ArgumentInvalidException(nameof(dto), $"Invalid id {dto.Id}. You can't edit this user."); - var oldUser = (await GetCacheUserAsync(token)).FirstOrDefault(u => u.Id == dto.Id); - if (oldUser is null) - throw new ArgumentInvalidException - ($"Invalid id {dto.Id}. You can't edit this user.", nameof(dto)); + var oldUser = (await GetCacheUserAsync(token)).FirstOrDefault(u => u.Id == dto.Id) + ?? throw new ArgumentInvalidException(nameof(dto), $"Invalid id {dto.Id}. You can't edit this user."); if (oldUser.Login != dto.Login) await AssertLoginIsBusyAsync(dto.Login, token); @@ -111,10 +108,9 @@ namespace AsbCloudInfrastructure.Repository var userRoles = await userRoleRepository.GetByNamesAsync(dto.RoleNames, token).ConfigureAwait(false); await UpdateRolesCacheForUserAsync(dto.Id, userRoles, token); - var entity = dbContext.Users.FirstOrDefault(u => u.Id == dto.Id); - if (entity is null) - throw new ArgumentInvalidException - ($"Invalid id {dto.Id}. You can't edit this user.", nameof(dto)); + var entity = dbContext.Users.FirstOrDefault(u => u.Id == dto.Id) + ?? throw new ArgumentInvalidException(nameof(dto), $"Invalid id {dto.Id}. You can't edit this user."); + entity.Id = dto.Id; entity.Login = dto.Login; entity.Name = dto.Name; @@ -132,10 +128,9 @@ namespace AsbCloudInfrastructure.Repository public async Task DeleteAsync(int id, CancellationToken token) { - var user = (await GetCacheUserAsync(token)).FirstOrDefault(u => u.Id == id); - if (user is null) - throw new ArgumentInvalidException - ($"Invalid id {id}. You can't edit this user.", nameof(id)); + var user = (await GetCacheUserAsync(token)).FirstOrDefault(u => u.Id == id) + ?? throw new ArgumentInvalidException(nameof(id), $"Invalid id {id}. You can't edit this user."); + var query = dbContext .Users .Where(u => u.Id == id); @@ -147,7 +142,7 @@ namespace AsbCloudInfrastructure.Repository return result.Entity.Id; } throw new ArgumentInvalidException - ($"Invalid id {id}. You can't edit this user.", nameof(id)); + (nameof(id), $"Invalid id {id}. You can't edit this user."); } public IEnumerable GetRolesByIdUser(int idUser, int nestedLevel = 0) @@ -161,6 +156,7 @@ namespace AsbCloudInfrastructure.Repository var roles = GetRolesByIdUser(idUser, 7); if (roles is null) return Enumerable.Empty(); + var permissions = roles .Where(r => r.Permissions is not null) .SelectMany(r => r.Permissions); @@ -198,9 +194,8 @@ namespace AsbCloudInfrastructure.Repository .FirstOrDefault(u => u.Login.ToLower() == login.ToLower()); if (existingUserDto is not null) - throw new ArgumentInvalidException($"Login {login} is busy by {existingUserDto.MakeDisplayName()}, id{existingUserDto.Id}", nameof(login)); - } - + throw new ArgumentInvalidException(nameof(login), $"Login {login} is busy by {existingUserDto.MakeDisplayName()}, id{existingUserDto.Id}"); + } private IEnumerable GetCachRelationUserUserRoleCacheTag() { @@ -215,7 +210,8 @@ namespace AsbCloudInfrastructure.Repository return entities; }); return cache!; - } + } + private void DropCacheRelationUserUserRoleCacheTag() { memoryCache.Remove(relationUserUserRoleCacheTag); diff --git a/AsbCloudInfrastructure/Repository/UserRoleRepository.cs b/AsbCloudInfrastructure/Repository/UserRoleRepository.cs index 7b946cab..427870c0 100644 --- a/AsbCloudInfrastructure/Repository/UserRoleRepository.cs +++ b/AsbCloudInfrastructure/Repository/UserRoleRepository.cs @@ -85,7 +85,7 @@ namespace AsbCloudInfrastructure.Repository .Where(r => names.Contains(r.Caption)); if (entities?.Count() != names.Count()) - throw new ArgumentInvalidException("Invalid role names", nameof(names)); + throw new ArgumentInvalidException(nameof(names), "Invalid role names"); return entities.Select(Convert); } @@ -196,7 +196,7 @@ namespace AsbCloudInfrastructure.Repository var idsIncludeRole = GetNestedByIds(dto.Roles.Select(x => x.Id)).Select(x => x.Id); if (idsIncludeRole.Any(x => x == dto.Id)) - throw new ArgumentInvalidException("Invalid include role (self reference)", nameof(dto)); + throw new ArgumentInvalidException(nameof(dto), "Invalid include role (self reference)"); var removeRelationsQuery = dbContext.RelationUserRoleUserRoles .Where(r => r.Id == dto.Id); diff --git a/AsbCloudInfrastructure/Repository/WellFinalDocumentsRepository.cs b/AsbCloudInfrastructure/Repository/WellFinalDocumentsRepository.cs index 01413ba2..7160a85e 100644 --- a/AsbCloudInfrastructure/Repository/WellFinalDocumentsRepository.cs +++ b/AsbCloudInfrastructure/Repository/WellFinalDocumentsRepository.cs @@ -32,10 +32,10 @@ namespace AsbCloudInfrastructure.Repository } /// - public async Task> UpdateRangeAsync(int idWell, IEnumerable? dtos, CancellationToken token) + public async Task> UpdateRangeAsync(int idWell, IEnumerable dtos, CancellationToken token) { - if (dtos is null) - throw new ArgumentInvalidException("Данные по категориям отсутствуют.", nameof(dtos)); + if (!dtos.Any()) + throw new ArgumentInvalidException(nameof(dtos), "Данные по категориям отсутствуют."); var entities = dtos .Where(dto => dto.IdsPublishers?.Any() == true) @@ -128,11 +128,8 @@ namespace AsbCloudInfrastructure.Repository { var entity = await context.WellFinalDocuments .AsNoTracking() - .FirstOrDefaultAsync(x => x.IdWell == idWell && x.IdCategory == idCategory && x.IdUser == idUser, token); - - if (entity is null) - throw new ArgumentInvalidException("Пользователь не является ответственным за загрузку файла для данной категории.", nameof(entity)); - + .FirstOrDefaultAsync(x => x.IdWell == idWell && x.IdCategory == idCategory && x.IdUser == idUser, token) + ?? throw new ArgumentInvalidException(nameof(idUser), "Пользователь не является ответственным за загрузку файла для данной категории."); var dto = Convert(entity); return dto; } diff --git a/AsbCloudInfrastructure/Services/AuthService.cs b/AsbCloudInfrastructure/Services/AuthService.cs index e5677420..d469ab54 100644 --- a/AsbCloudInfrastructure/Services/AuthService.cs +++ b/AsbCloudInfrastructure/Services/AuthService.cs @@ -79,10 +79,8 @@ namespace AsbCloudInfrastructure.Services /// public void Register(UserRegistrationDto userDto) { - var user = db.Users.FirstOrDefault(u => u.Login == userDto.Login); - - if (user is not null) - throw new ArgumentInvalidException("Логин уже занят", nameof(userDto.Login)); + var user = db.Users.FirstOrDefault(u => u.Login == userDto.Login) + ?? throw new ArgumentInvalidException(nameof(userDto.Login), "Логин уже занят"); var salt = GenerateSalt(); @@ -114,7 +112,7 @@ namespace AsbCloudInfrastructure.Services public void ChangePassword(string userLogin, string newPassword) { var user = db.Users.FirstOrDefault(u => u.Login == userLogin) - ?? throw new ArgumentInvalidException("Логин не зарегистрирован", nameof(userLogin)); + ?? throw new ArgumentInvalidException(nameof(userLogin), "Логин не зарегистрирован"); var salt = GenerateSalt(); user.PasswordHash = salt + ComputeHash(salt, newPassword); @@ -125,7 +123,7 @@ namespace AsbCloudInfrastructure.Services public void ChangePassword(int idUser, string newPassword) { var user = db.Users.FirstOrDefault(u => u.Id == idUser) - ?? throw new ArgumentInvalidException($"Пользователь с idUser:{idUser} не зарегистрирован", nameof(idUser)); + ?? throw new ArgumentInvalidException(nameof(idUser), $"Пользователь с idUser:{idUser} не зарегистрирован"); var salt = GenerateSalt(); user.PasswordHash = salt + ComputeHash(salt, newPassword); diff --git a/AsbCloudInfrastructure/Services/AutoGeneratedDailyReports/AutoGeneratedDailyReportService.cs b/AsbCloudInfrastructure/Services/AutoGeneratedDailyReports/AutoGeneratedDailyReportService.cs index 0e364319..2f402285 100644 --- a/AsbCloudInfrastructure/Services/AutoGeneratedDailyReports/AutoGeneratedDailyReportService.cs +++ b/AsbCloudInfrastructure/Services/AutoGeneratedDailyReports/AutoGeneratedDailyReportService.cs @@ -57,10 +57,10 @@ public class AutoGeneratedDailyReportService : IAutoGeneratedDailyReportService var reports = new List(); var well = await wellService.GetOrDefaultAsync(idWell, cancellationToken) - ?? throw new ArgumentInvalidException("Скважина не найдена", nameof(idWell)); + ?? throw new ArgumentInvalidException(nameof(idWell), "Скважина не найдена"); if (!well.IdTelemetry.HasValue) - throw new ArgumentInvalidException("Телеметрия для скважины отсутствует", nameof(idWell)); + throw new ArgumentInvalidException(nameof(idWell), "Телеметрия для скважины отсутствует"); var datesRange = await GetDatesRangeAsync(idWell, cancellationToken); @@ -112,10 +112,10 @@ public class AutoGeneratedDailyReportService : IAutoGeneratedDailyReportService var finishDate = startDate.AddDays(1); var well = await wellService.GetOrDefaultAsync(idWell, cancellationToken) - ?? throw new ArgumentInvalidException("Скважина не найдена", nameof(idWell)); + ?? throw new ArgumentInvalidException(nameof(idWell), "Скважина не найдена"); if (!well.IdTelemetry.HasValue) - throw new ArgumentInvalidException("Телеметрия для скважины отсутствует", nameof(idWell)); + throw new ArgumentInvalidException(nameof(idWell), "Телеметрия для скважины отсутствует"); var factOperations = await GetFactOperationsAsync(well.Id, startDate, finishDate, cancellationToken); diff --git a/AsbCloudInfrastructure/Services/DailyReport/DailyReportService.cs b/AsbCloudInfrastructure/Services/DailyReport/DailyReportService.cs index 8b3b11ef..abb88b14 100644 --- a/AsbCloudInfrastructure/Services/DailyReport/DailyReportService.cs +++ b/AsbCloudInfrastructure/Services/DailyReport/DailyReportService.cs @@ -42,9 +42,8 @@ namespace AsbCloudInfrastructure.Services.DailyReport public async Task> GetListAsync(int idWell, DateOnly? begin, DateOnly? end, CancellationToken token) { - var well = wellService.GetOrDefault(idWell); - if (well is null || well.Timezone is null) - throw new ArgumentInvalidException("idWell doesn`t exist", nameof(idWell)); + var well = wellService.GetOrDefault(idWell) + ?? throw new ArgumentInvalidException(nameof(idWell), "idWell doesn`t exist"); var query = db.DailyReports.Where(r => r.IdWell == idWell); @@ -90,15 +89,13 @@ namespace AsbCloudInfrastructure.Services.DailyReport public async Task AddAsync(int idWell, DateOnly startDate, int idUser, CancellationToken token) { - var well = wellService.GetOrDefault(idWell); - if (well is null) - throw new ArgumentInvalidException("idWell doesn`t exist", nameof(idWell)); - + var well = wellService.GetOrDefault(idWell) + ?? throw new ArgumentInvalidException(nameof(idWell), "idWell doesn`t exist"); var hasEntity = await db.DailyReports .AnyAsync(r => r.IdWell == idWell && r.StartDate == startDate, token); if (hasEntity) - throw new ArgumentInvalidException($"daily report on {startDate} already exists", nameof(startDate)); + throw new ArgumentInvalidException(nameof(startDate), $"daily report on {startDate} already exists"); var entity = new AsbCloudDb.Model.DailyReport.DailyReport { @@ -116,14 +113,11 @@ namespace AsbCloudInfrastructure.Services.DailyReport public async Task UpdateBlockAsync(int idWell, DateOnly startDate, ItemInfoDto dto, CancellationToken token) { - var well = wellService.GetOrDefault(idWell); - if (well is null) - throw new ArgumentInvalidException("idWell doesn`t exist", nameof(idWell)); + var well = wellService.GetOrDefault(idWell) + ?? throw new ArgumentInvalidException(nameof(idWell), "idWell doesn`t exist"); - var entity = await db.DailyReports.FirstOrDefaultAsync(r => r.IdWell == idWell && r.StartDate == startDate, token); - - if (entity is null) - throw new ArgumentInvalidException("Daily report doesn`t exist", nameof(startDate)); + var entity = await db.DailyReports.FirstOrDefaultAsync(r => r.IdWell == idWell && r.StartDate == startDate, token) + ?? throw new ArgumentInvalidException(nameof(startDate), "Daily report doesn`t exist"); dto.LastUpdateDate = DateTimeOffset.Now; if (dto is HeadDto headDto) @@ -161,10 +155,8 @@ namespace AsbCloudInfrastructure.Services.DailyReport private async Task GetOrDefaultAsync(int idWell, DateOnly date, CancellationToken token) { var entity = await db.DailyReports - .FirstOrDefaultAsync(r => r.IdWell == idWell && r.StartDate == date, token); - - if (entity is null) - throw new ArgumentInvalidException("Daily report doesn`t exist", nameof(date)); + .FirstOrDefaultAsync(r => r.IdWell == idWell && r.StartDate == date, token) + ?? throw new ArgumentInvalidException(nameof(date), "Daily report doesn`t exist"); var factOperationsForDtos = await GetFactOperationsForDailyReportAsync(idWell, token); var userDtos = await userRepository.GetAllAsync(token); diff --git a/AsbCloudInfrastructure/Services/DrillingProgram/DrillingProgramService.cs b/AsbCloudInfrastructure/Services/DrillingProgram/DrillingProgramService.cs index 37275559..adb410d6 100644 --- a/AsbCloudInfrastructure/Services/DrillingProgram/DrillingProgramService.cs +++ b/AsbCloudInfrastructure/Services/DrillingProgram/DrillingProgramService.cs @@ -185,10 +185,8 @@ namespace AsbCloudInfrastructure.Services.DrillingProgram var part = await context.DrillingProgramParts .Include(p => p.RelatedUsers) .ThenInclude(r => r.User) - .FirstOrDefaultAsync(p => p.IdWell == idWell && p.IdFileCategory == idFileCategory, token); - - if (part == null) - throw new ArgumentInvalidException($"DrillingProgramPart id == {idFileCategory} does not exist", nameof(idFileCategory)); + .FirstOrDefaultAsync(p => p.IdWell == idWell && p.IdFileCategory == idFileCategory, token) + ?? throw new ArgumentInvalidException(nameof(idFileCategory), $"DrillingProgramPart id == {idFileCategory} does not exist"); if (!part.RelatedUsers.Any(r => r.IdUser == idUser && r.IdUserRole == idUserRolePublisher)) throw new ForbidException($"User {idUser} is not in the publisher list."); @@ -246,19 +244,16 @@ namespace AsbCloudInfrastructure.Services.DrillingProgram public async Task AddUserAsync(int idWell, int idFileCategory, int idUser, int idUserRole, CancellationToken token = default) { - var user = await userRepository.GetOrDefaultAsync(idUser, token); - if (user is null) - throw new ArgumentInvalidException($"User id == {idUser} does not exist", nameof(idUser)); + var user = await userRepository.GetOrDefaultAsync(idUser, token) + ?? throw new ArgumentInvalidException(nameof(idUser), $"User id: {idUser} does not exist"); var part = await context.DrillingProgramParts .Include(p => p.FileCategory) - .FirstOrDefaultAsync(p => p.IdWell == idWell && p.IdFileCategory == idFileCategory, token); - - if (part is null) - throw new ArgumentInvalidException($"DrillingProgramPart idFileCategory == {idFileCategory} does not exist", nameof(idFileCategory)); + .FirstOrDefaultAsync(p => p.IdWell == idWell && p.IdFileCategory == idFileCategory, token) + ?? throw new ArgumentInvalidException(nameof(idFileCategory), $"DrillingProgramPart idFileCategory: {idFileCategory} does not exist"); if (idUserRole != idUserRoleApprover && idUserRole != idUserRolePublisher) - throw new ArgumentInvalidException($"idUserRole ({idUserRole}), should be approver ({idUserRoleApprover}) or publisher ({idUserRolePublisher})", nameof(idUserRole)); + throw new ArgumentInvalidException(nameof(idUserRole), $"idUserRole ({idUserRole}), should be approver ({idUserRoleApprover}) or publisher ({idUserRolePublisher})"); var oldRelation = await context.RelationDrillingProgramPartUsers .FirstOrDefaultAsync(r => r.IdUser == idUser && r.IdDrillingProgramPart == part.Id, token); @@ -300,17 +295,14 @@ namespace AsbCloudInfrastructure.Services.DrillingProgram { if (fileMarkDto.IdMarkType != idMarkTypeApprove && fileMarkDto.IdMarkType != idMarkTypeReject) - throw new ArgumentInvalidException($"В этом методе допустимы только отметки о принятии или отклонении.", nameof(fileMarkDto)); + throw new ArgumentInvalidException(nameof(fileMarkDto), $"В этом методе допустимы только отметки о принятии или отклонении."); var fileInfo = await fileService.GetOrDefaultAsync(fileMarkDto.IdFile, token) - .ConfigureAwait(false); - - if (fileInfo is null) - throw new ArgumentInvalidException($"Файла для такой отметки не существует.", nameof(fileMarkDto)); + ?? throw new ArgumentInvalidException(nameof(fileMarkDto), $"Файла для такой отметки не существует."); if (fileInfo.IdCategory < idFileCategoryDrillingProgramPartsStart || fileInfo.IdCategory > idFileCategoryDrillingProgramPartsEnd) - throw new ArgumentInvalidException($"Этот метод допустим только для файлов-частей программы бурения.", nameof(fileMarkDto)); + throw new ArgumentInvalidException(nameof(fileMarkDto), $"Этот метод допустим только для файлов-частей программы бурения."); var part = await context.DrillingProgramParts .Include(p => p.RelatedUsers) @@ -318,9 +310,8 @@ namespace AsbCloudInfrastructure.Services.DrillingProgram .AsNoTracking() .FirstOrDefaultAsync(p => p.IdWell == fileInfo.IdWell && p.IdFileCategory == fileInfo.IdCategory, token); - var user = part?.RelatedUsers.FirstOrDefault(r => r.IdUser == idUser && r.IdUserRole == idUserRoleApprover)?.User; - if (user is null) - throw new ForbidException($"User {idUser} is not in the approvers list."); + var user = part?.RelatedUsers.FirstOrDefault(r => r.IdUser == idUser && r.IdUserRole == idUserRoleApprover)?.User + ?? throw new ForbidException($"User {idUser} is not in the approvers list."); fileMarkDto.User = user.Adapt(); @@ -363,7 +354,7 @@ namespace AsbCloudInfrastructure.Services.DrillingProgram if (fileInfo.IdCategory < idFileCategoryDrillingProgramPartsStart || fileInfo.IdCategory > idFileCategoryDrillingProgramPartsEnd) - throw new ArgumentInvalidException($"Этот метод допустим только для файлов-частей программы бурения.", nameof(idMark)); + throw new ArgumentInvalidException(nameof(idMark), $"Этот метод допустим только для файлов-частей программы бурения."); var result = await fileService.MarkFileMarkAsDeletedAsync(idMark, token) .ConfigureAwait(false); @@ -375,9 +366,8 @@ namespace AsbCloudInfrastructure.Services.DrillingProgram private async Task NotifyPublisherOnFullAccepAsync(FileMarkDto fileMark, CancellationToken token) { var file = await fileService.GetOrDefaultAsync(fileMark.IdFile, token); - var well = await wellService.GetOrDefaultAsync(file!.IdWell, token); - if (well is null) - throw new ArgumentInvalidException("idWell doesn`t exist", nameof(file.IdWell)); + var well = await wellService.GetOrDefaultAsync(file!.IdWell, token) + ?? throw new ArgumentInvalidException(nameof(file.IdWell), "idWell doesn`t exist"); var user = file.Author!; var factory = new DrillingMailBodyFactory(configuration); @@ -397,9 +387,8 @@ namespace AsbCloudInfrastructure.Services.DrillingProgram private async Task NotifyPublisherOnRejectAsync(FileMarkDto fileMark, CancellationToken token) { var file = await fileService.GetOrDefaultAsync(fileMark.IdFile, token); - var well = await wellService.GetOrDefaultAsync(file!.IdWell, token); - if (well is null) - throw new ArgumentInvalidException("idWell doesn`t exist", nameof(file.IdWell)); + var well = await wellService.GetOrDefaultAsync(file!.IdWell, token) + ?? throw new ArgumentInvalidException(nameof(file.IdWell), "idWell doesn`t exist"); var user = file.Author!; var factory = new DrillingMailBodyFactory(configuration); @@ -418,9 +407,8 @@ namespace AsbCloudInfrastructure.Services.DrillingProgram private async Task NotifyApproversAsync(DrillingProgramPart part, int idFile, string fileName, CancellationToken token) { - var well = await wellService.GetOrDefaultAsync(part.IdWell, token); - if (well is null) - throw new ArgumentInvalidException("idWell doesn`t exist", nameof(part.IdWell)); + var well = await wellService.GetOrDefaultAsync(part.IdWell, token) + ?? throw new ArgumentInvalidException(nameof(part.IdWell), "idWell doesn`t exist"); var factory = new DrillingMailBodyFactory(configuration); var subject = factory.MakeSubject(well, "Загружен новый документ для согласования."); @@ -444,9 +432,8 @@ namespace AsbCloudInfrastructure.Services.DrillingProgram private async Task NotifyNewPublisherAsync(int idWell, UserDto user, string documentCategory, CancellationToken token) { - var well = await wellService.GetOrDefaultAsync(idWell, token); - if (well is null) - throw new ArgumentInvalidException("idWell doesn`t exist", nameof(idWell)); + var well = await wellService.GetOrDefaultAsync(idWell, token) + ?? throw new ArgumentInvalidException(nameof(idWell), "idWell doesn`t exist"); var factory = new DrillingMailBodyFactory(configuration); var subject = factory.MakeSubject(well, $"От вас ожидается загрузка на портал документа «{documentCategory}»"); diff --git a/AsbCloudInfrastructure/Services/Email/BaseFactory.cs b/AsbCloudInfrastructure/Services/Email/BaseFactory.cs index 26c5b06b..11c8feaa 100644 --- a/AsbCloudInfrastructure/Services/Email/BaseFactory.cs +++ b/AsbCloudInfrastructure/Services/Email/BaseFactory.cs @@ -25,7 +25,7 @@ namespace AsbCloudInfrastructure.Services.Email public static string GetOrEmptyImageBase64(string resourceFileName) { if (string.IsNullOrEmpty(resourceFileName)) - throw new ArgumentInvalidException("ResourceFileName doesn`t exist", nameof(resourceFileName)); + throw new ArgumentInvalidException(nameof(resourceFileName), "ResourceFileName doesn`t exist"); var baseDir = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) ?? string.Empty; diff --git a/AsbCloudInfrastructure/Services/Email/EmailNotificationTransportService.cs b/AsbCloudInfrastructure/Services/Email/EmailNotificationTransportService.cs index e0f4ba0e..26eed2be 100644 --- a/AsbCloudInfrastructure/Services/Email/EmailNotificationTransportService.cs +++ b/AsbCloudInfrastructure/Services/Email/EmailNotificationTransportService.cs @@ -70,26 +70,22 @@ namespace AsbCloudInfrastructure.Services.Email return Task.WhenAll(tasks); } - private Func MakeEmailSendWorkAction(NotificationDto notification) { - if (string.IsNullOrWhiteSpace(notification.Title)) - throw new ArgumentInvalidException($"{nameof(notification.Title)} should be set", nameof(notification.Title)); - return async (_, serviceProvider, token) => { var notificationRepository = serviceProvider.GetRequiredService(); var userRepository = serviceProvider.GetRequiredService(); var user = await userRepository.GetOrDefaultAsync(notification.IdUser, token) - ?? throw new ArgumentInvalidException("Пользователь не найден" , nameof(notification.IdUser)); + ?? throw new ArgumentInvalidException(nameof(notification.IdUser), "Пользователь не найден"); if(!MailAddress.TryCreate(user.Email, out var mailAddress)) + { Trace.TraceWarning($"Mail {user.Email} is not correct."); + throw new ArgumentInvalidException(nameof(user.Email), $"Mail {user.Email} is not null."); + } - if (mailAddress is null) - throw new ArgumentInvalidException($"Mail {user.Email} is not null.", nameof(user.Email)); - var from = new MailAddress(sender); var message = new MailMessage { diff --git a/AsbCloudInfrastructure/Services/ManualCatalogService.cs b/AsbCloudInfrastructure/Services/ManualCatalogService.cs index eb98d76d..c8713ab1 100644 --- a/AsbCloudInfrastructure/Services/ManualCatalogService.cs +++ b/AsbCloudInfrastructure/Services/ManualCatalogService.cs @@ -47,8 +47,8 @@ public class ManualCatalogService : IManualCatalogService if (!validExtensions.Contains(extension)) throw new ArgumentInvalidException( - $"Невозможно загрузить файл с расширением '{extension}'. Допустимые форматы файлов: {string.Join(", ", validExtensions)}", - extension); + nameof(name), + $"Невозможно загрузить файл с расширением '{extension}'. Допустимые форматы файлов: {string.Join(", ", validExtensions)}"); var path = await BuildFilePathAsync(idDirectory, name, cancellationToken); @@ -69,7 +69,7 @@ public class ManualCatalogService : IManualCatalogService public async Task AddDirectoryAsync(string name, int? idParent, CancellationToken cancellationToken) { if (idParent.HasValue && !await manualDirectoryRepository.IsExistsAsync(idParent.Value, cancellationToken)) - throw new ArgumentInvalidException("Родительской директории не существует", nameof(idParent)); + throw new ArgumentInvalidException(nameof(idParent), "Родительской директории не существует"); var directory = new ManualDirectoryDto { @@ -78,7 +78,7 @@ public class ManualCatalogService : IManualCatalogService }; if (await IsExistDirectoryAsync(directory, cancellationToken)) - throw new ArgumentInvalidException("Директория с таким названием уже существует", name); + throw new ArgumentInvalidException(name, "Директория с таким названием уже существует"); return await manualDirectoryRepository.InsertAsync(directory, cancellationToken); } @@ -86,12 +86,12 @@ public class ManualCatalogService : IManualCatalogService public async Task UpdateDirectoryAsync(int id, string name, CancellationToken cancellationToken) { var directory = await manualDirectoryRepository.GetOrDefaultAsync(id, cancellationToken) - ?? throw new ArgumentInvalidException($"Директории с Id: {id} не существует", nameof(id)); + ?? throw new ArgumentInvalidException(nameof(id), $"Директории с Id: {id} не существует"); directory.Name = name; if (await IsExistDirectoryAsync(directory, cancellationToken)) - throw new ArgumentInvalidException("Директория с таким названием уже существует", name); + throw new ArgumentInvalidException(name, "Директория с таким названием уже существует"); await manualDirectoryRepository.UpdateAsync(directory, cancellationToken); } @@ -112,7 +112,7 @@ public class ManualCatalogService : IManualCatalogService } catch (InvalidOperationException ex) { - throw new ArgumentInvalidException(ex.Message, nameof(id)); + throw new ArgumentInvalidException(nameof(id), ex.Message); } return await manualDirectoryRepository.DeleteAsync(directory.Id, cancellationToken); @@ -157,15 +157,14 @@ public class ManualCatalogService : IManualCatalogService var directiories = await manualDirectoryRepository.GetAllAsync(cancellationToken); var directory = directiories.FirstOrDefault(d => d.Id == idDirectory) - ?? throw new ArgumentInvalidException($"Директории с Id: {idDirectory} не существует", nameof(idDirectory)); + ?? throw new ArgumentInvalidException(nameof(idDirectory), $"Директории с Id: {idDirectory} не существует"); var pathSegments = new List { directory.Id }; while (directory.IdParent.HasValue) { directory = directiories.FirstOrDefault(d => d.Id == directory.IdParent.Value); - - pathSegments.Insert(0, directory.Id); + pathSegments.Insert(0, directory!.Id); } return string.Join("/", pathSegments); diff --git a/AsbCloudInfrastructure/Services/MeasureService.cs b/AsbCloudInfrastructure/Services/MeasureService.cs index 79dc1411..58c5c295 100644 --- a/AsbCloudInfrastructure/Services/MeasureService.cs +++ b/AsbCloudInfrastructure/Services/MeasureService.cs @@ -84,9 +84,9 @@ namespace AsbCloudInfrastructure.Services public Task InsertAsync(int idWell, MeasureDto dto, CancellationToken token) { if (dto.IdCategory < 1) - throw new ArgumentInvalidException("wrong idCategory", nameof(dto)); - if (dto.Data is null) - throw new ArgumentInvalidException("data.data is not optional", nameof(dto)); + throw new ArgumentInvalidException(nameof(dto), "wrong idCategory"); + if (!dto.Data.Any()) + throw new ArgumentInvalidException(nameof(dto), "data.data is not optional"); var timezone = wellService.GetTimezone(idWell); var entity = Convert(dto, timezone.Hours); entity.IdWell = idWell; @@ -97,19 +97,16 @@ namespace AsbCloudInfrastructure.Services public async Task UpdateAsync(int idWell, MeasureDto dto, CancellationToken token) { if (dto.Id < 1) - throw new ArgumentInvalidException("wrong id", nameof(dto)); + throw new ArgumentInvalidException(nameof(dto), "wrong id"); if (dto.IdCategory < 1) - throw new ArgumentInvalidException("wrong idCategory", nameof(dto)); - if (dto.Data is null) - throw new ArgumentInvalidException("data.data is not optional", nameof(dto)); + throw new ArgumentInvalidException(nameof(dto), "wrong idCategory"); + if (!dto.Data.Any()) + throw new ArgumentInvalidException(nameof(dto), "data.data is not optional"); var entity = await db.Measures .Where(m => m.Id == dto.Id && !m.IsDeleted) .FirstOrDefaultAsync(token) - .ConfigureAwait(false); - - if (entity is null) - throw new ArgumentInvalidException("id doesn't exist", nameof(dto)); + ?? throw new ArgumentInvalidException(nameof(dto), "id doesn't exist"); var timezone = wellService.GetTimezone(idWell); entity.IdWell = idWell; @@ -122,14 +119,11 @@ namespace AsbCloudInfrastructure.Services public async Task MarkAsDeleteAsync(int idWell, int idData, CancellationToken token) { if (idData < 1) - throw new ArgumentInvalidException("wrong id", nameof(idData)); + throw new ArgumentInvalidException(nameof(idData), "wrong id"); var entity = await db.Measures.Where(m => m.IdWell == idWell && m.Id == idData) .FirstOrDefaultAsync(token) - .ConfigureAwait(false); - - if (entity is null) - throw new ArgumentInvalidException($"Measure doesn't exist", nameof(idWell)); + ?? throw new ArgumentInvalidException(nameof(idWell), $"Measure doesn't exist"); entity.IsDeleted = true; @@ -139,7 +133,7 @@ namespace AsbCloudInfrastructure.Services public Task DeleteAsync(int idWell, int idData, CancellationToken token) { if (idData < 1) - throw new ArgumentInvalidException("wrong id", nameof(idData)); + throw new ArgumentInvalidException(nameof(idData), "wrong id"); db.Measures.RemoveRange(db.Measures.Where(m => m.IdWell == idWell && m.Id == idData)); return db.SaveChangesAsync(token); } diff --git a/AsbCloudInfrastructure/Services/ProcessMap/ProcessMapService.cs b/AsbCloudInfrastructure/Services/ProcessMap/ProcessMapService.cs index a2193fd3..97df17ed 100644 --- a/AsbCloudInfrastructure/Services/ProcessMap/ProcessMapService.cs +++ b/AsbCloudInfrastructure/Services/ProcessMap/ProcessMapService.cs @@ -35,10 +35,10 @@ namespace AsbCloudInfrastructure.Services.ProcessMap public async Task> GetProcessMapReportAsync(int idWell, CancellationToken token) { var well = wellService.GetOrDefault(idWell) - ?? throw new ArgumentInvalidException("idWell not found", nameof(idWell)); + ?? throw new ArgumentInvalidException(nameof(idWell), "idWell not found"); var idTelemetry = well.IdTelemetry - ?? throw new ArgumentInvalidException("telemetry by well not found", nameof(idWell)); + ?? throw new ArgumentInvalidException(nameof(idWell), "telemetry by well not found"); var processMapPlan = await processMapPlanRepository.GetByIdWellAsync(idWell, token); diff --git a/AsbCloudInfrastructure/Services/ProcessMap/ProcessMapWellboreDevelopment/ProcessMapWellboreDevelopmentService.cs b/AsbCloudInfrastructure/Services/ProcessMap/ProcessMapWellboreDevelopment/ProcessMapWellboreDevelopmentService.cs index 6a2c3834..1a709cda 100644 --- a/AsbCloudInfrastructure/Services/ProcessMap/ProcessMapWellboreDevelopment/ProcessMapWellboreDevelopmentService.cs +++ b/AsbCloudInfrastructure/Services/ProcessMap/ProcessMapWellboreDevelopment/ProcessMapWellboreDevelopmentService.cs @@ -26,15 +26,9 @@ public class ProcessMapWellboreDevelopmentService : IProcessMapWellboreDevelopme public async Task InsertAsync(ProcessMapWellboreDevelopmentDto processMapWellboreDevelopment, CancellationToken cancellationToken) { - var well = await wellService.GetOrDefaultAsync(processMapWellboreDevelopment.IdWell, cancellationToken); - - if (well is null) - throw new ArgumentInvalidException($"Скважины с Id: {processMapWellboreDevelopment.IdWell} не существует", - nameof(processMapWellboreDevelopment.IdWell)); - - if (processMapWellboreDevelopment.DepthStart > processMapWellboreDevelopment.DepthEnd) - throw new ArgumentInvalidException("Значение стартовой глубины должно быть не больше значения конечной глубины", - nameof(processMapWellboreDevelopment.DepthStart)); + var well = await wellService.GetOrDefaultAsync(processMapWellboreDevelopment.IdWell, cancellationToken) + ?? throw new ArgumentInvalidException(nameof(processMapWellboreDevelopment.IdWell), + $"Скважины с Id: {processMapWellboreDevelopment.IdWell} не существует"); processMapWellboreDevelopment.LastUpdate = DateTimeOffset.UtcNow; @@ -46,20 +40,16 @@ public class ProcessMapWellboreDevelopmentService : IProcessMapWellboreDevelopme var well = await wellService.GetOrDefaultAsync(processMapWellboreDevelopment.IdWell, cancellationToken); if (well is null) - throw new ArgumentInvalidException($"Скважины с Id: {processMapWellboreDevelopment.IdWell} не существует", - nameof(processMapWellboreDevelopment.IdWell)); - - if (processMapWellboreDevelopment.DepthStart > processMapWellboreDevelopment.DepthEnd) - throw new ArgumentInvalidException("Значение стартовой глубины должно быть не больше значения конечной глубины", - nameof(processMapWellboreDevelopment.DepthStart)); + throw new ArgumentInvalidException(nameof(processMapWellboreDevelopment.IdWell), + $"Скважины с Id: {processMapWellboreDevelopment.IdWell} не существует"); processMapWellboreDevelopment.LastUpdate = DateTimeOffset.UtcNow; var result = await processMapWellboreDevelopmentRepository.UpdateAsync(processMapWellboreDevelopment, cancellationToken); if (result == ICrudRepository.ErrorIdNotFound) - throw new ArgumentInvalidException($"Проработки с Id: {processMapWellboreDevelopment.Id} не существует", - nameof(processMapWellboreDevelopment.Id)); + throw new ArgumentInvalidException(nameof(processMapWellboreDevelopment.Id), + $"Проработки с Id: {processMapWellboreDevelopment.Id} не существует"); return result; } @@ -70,7 +60,7 @@ public class ProcessMapWellboreDevelopmentService : IProcessMapWellboreDevelopme var idWell = telemetryService.GetIdWellByTelemetryUid(uid); if (!idWell.HasValue) - throw new ArgumentInvalidException($"Неправильный телеметрии. Uid: {uid}", nameof(uid)); + throw new ArgumentInvalidException(nameof(uid), $"Неправильный телеметрии. Uid: {uid}"); return await processMapWellboreDevelopmentRepository.GetAllAsync(idWell.Value, updateFrom, cancellationToken); } diff --git a/AsbCloudInfrastructure/Services/SAUB/TelemetryDataSaubService.cs b/AsbCloudInfrastructure/Services/SAUB/TelemetryDataSaubService.cs index 9aaf26bf..afe89528 100644 --- a/AsbCloudInfrastructure/Services/SAUB/TelemetryDataSaubService.cs +++ b/AsbCloudInfrastructure/Services/SAUB/TelemetryDataSaubService.cs @@ -114,10 +114,10 @@ namespace AsbCloudInfrastructure.Services.SAUB { double intervalSec = (endDate - beginDate).TotalSeconds; if (intervalSec > 60*60*24*3) - throw new ArgumentInvalidException("Слишком большой диапазон", nameof(endDate)); + throw new ArgumentInvalidException(nameof(endDate), "Слишком большой диапазон"); var telemetry = telemetryService.GetOrDefaultTelemetryByIdWell(idWell) - ?? throw new ArgumentInvalidException($"Скважина id:{idWell} не содержит телеметрии", nameof(idWell)); + ?? throw new ArgumentInvalidException(nameof(idWell), $"Скважина id:{idWell} не содержит телеметрии"); var approxPointsCount = intervalSec switch { diff --git a/AsbCloudInfrastructure/Services/Subsystems/SubsystemOperationTimeService.cs b/AsbCloudInfrastructure/Services/Subsystems/SubsystemOperationTimeService.cs index 1b26b03f..a1abde3a 100644 --- a/AsbCloudInfrastructure/Services/Subsystems/SubsystemOperationTimeService.cs +++ b/AsbCloudInfrastructure/Services/Subsystems/SubsystemOperationTimeService.cs @@ -336,9 +336,8 @@ namespace AsbCloudInfrastructure.Services.Subsystems private IQueryable BuildQuery(SubsystemOperationTimeRequest request) { - var well = wellService.GetOrDefault(request.IdWell); - if (well?.IdTelemetry is null || well.Timezone is null) - throw new ArgumentInvalidException($"Not valid IdWell = {request.IdWell}", nameof(request.IdWell)); + var well = wellService.GetOrDefault(request.IdWell) + ?? throw new ArgumentInvalidException(nameof(request.IdWell), $"Not valid IdWell = {request.IdWell}"); var query = db.SubsystemOperationTimes .Include(o => o.Subsystem) diff --git a/AsbCloudInfrastructure/Services/WellFinalDocumentsService.cs b/AsbCloudInfrastructure/Services/WellFinalDocumentsService.cs index 24f956e2..591f28fc 100644 --- a/AsbCloudInfrastructure/Services/WellFinalDocumentsService.cs +++ b/AsbCloudInfrastructure/Services/WellFinalDocumentsService.cs @@ -110,7 +110,7 @@ namespace AsbCloudInfrastructure.Services })); if(!docs.Any()) - throw new ArgumentInvalidException("Нет такой категории, или в нее уже загружен документ", nameof(idCategory)); + throw new ArgumentInvalidException(nameof(idCategory), "Нет такой категории, или в нее уже загружен документ"); var message = requester.MakeDisplayName() + " ожидает от Вас загрузку на портал документа «{{0}}»"; await NotifyUsersAsync(docs, message, token); @@ -126,9 +126,8 @@ namespace AsbCloudInfrastructure.Services if (user?.Email is not null) { var category = await fileCategoryService.GetOrDefaultAsync(item.IdCategory, token); - var well = await wellService.GetOrDefaultAsync(item.IdWell, token); - if(well is null) - throw new ArgumentInvalidException("idWell doesn`t exist", nameof(item.IdWell)); + var well = await wellService.GetOrDefaultAsync(item.IdWell, token) + ?? throw new ArgumentInvalidException(nameof(item.IdWell), "idWell doesn`t exist"); await SendMessageAsync(well, user, category?.Name ?? string.Empty, message, token); diff --git a/AsbCloudInfrastructure/Services/WellOperationImport/FileParser/WellOperationDefaultExcelParser.cs b/AsbCloudInfrastructure/Services/WellOperationImport/FileParser/WellOperationDefaultExcelParser.cs index 7d79e243..f5f56612 100644 --- a/AsbCloudInfrastructure/Services/WellOperationImport/FileParser/WellOperationDefaultExcelParser.cs +++ b/AsbCloudInfrastructure/Services/WellOperationImport/FileParser/WellOperationDefaultExcelParser.cs @@ -26,7 +26,7 @@ public class WellOperationDefaultExcelParser : IWellOperationExcelParser private static IEnumerable ParseWorkbook(IXLWorkbook workbook, WellOperationParserOptionsDto options) { if (string.IsNullOrWhiteSpace(options.SheetName)) - throw new ArgumentInvalidException("Не указано название листа", nameof(options.SheetName)); + throw new ArgumentInvalidException(nameof(options.SheetName), "Не указано название листа"); var sheet = workbook.Worksheets.FirstOrDefault(ws => string.Equals(ws.Name, options.SheetName, StringComparison.CurrentCultureIgnoreCase)) diff --git a/AsbCloudInfrastructure/Services/WellOperationImport/FileParser/WellOperationGazpromKhantosExcelParser.cs b/AsbCloudInfrastructure/Services/WellOperationImport/FileParser/WellOperationGazpromKhantosExcelParser.cs index 4de99d77..6f0b412d 100644 --- a/AsbCloudInfrastructure/Services/WellOperationImport/FileParser/WellOperationGazpromKhantosExcelParser.cs +++ b/AsbCloudInfrastructure/Services/WellOperationImport/FileParser/WellOperationGazpromKhantosExcelParser.cs @@ -57,16 +57,16 @@ public class WellOperationGazpromKhantosExcelParser : IWellOperationExcelParser private IEnumerable ParseWorkBook(IXLWorkbook workbook, WellOperationParserOptionsDto options) { if (string.IsNullOrWhiteSpace(options.SheetName)) - throw new ArgumentInvalidException("Не указано название листа", nameof(options.SheetName)); + throw new ArgumentInvalidException(nameof(options.SheetName), "Не указано название листа"); if (options.StartRow is null or < 1 or > 1048576) - throw new ArgumentInvalidException("Некорректное значение начальной строки", nameof(options.StartRow)); + throw new ArgumentInvalidException(nameof(options.StartRow), "Некорректное значение начальной строки"); if (options.EndRow is null or < 1 or > 1048576) - throw new ArgumentInvalidException("Некорректное значение конечной строки", nameof(options.EndRow)); + throw new ArgumentInvalidException(nameof(options.EndRow), "Некорректное значение конечной строки"); if (options.EndRow < options.StartRow) - throw new ArgumentInvalidException("Конечный номер строки не может быть больше начального", nameof(options.EndRow)); + throw new ArgumentInvalidException(nameof(options.EndRow), "Конечный номер строки не может быть больше начального"); var sheet = workbook.Worksheets.FirstOrDefault(ws => string.Equals(ws.Name, options.SheetName, StringComparison.CurrentCultureIgnoreCase)) diff --git a/AsbCloudInfrastructure/Services/WellOperationImport/WellOperationImportService.cs b/AsbCloudInfrastructure/Services/WellOperationImport/WellOperationImportService.cs index c57a3531..af84f3a9 100644 --- a/AsbCloudInfrastructure/Services/WellOperationImport/WellOperationImportService.cs +++ b/AsbCloudInfrastructure/Services/WellOperationImport/WellOperationImportService.cs @@ -34,14 +34,11 @@ public class WellOperationImportService : IWellOperationImportService public async Task ImportAsync(int idWell, int idUser, int idType, Stream stream, WellOperationParserOptionsDto options, bool deleteWellOperationsBeforeImport, CancellationToken cancellationToken) { - var excelParser = excelParsers.FirstOrDefault(p => p.IdTemplate == options.IdTemplate && - p.IdTypes.Contains(idType)); + var excelParser = excelParsers.FirstOrDefault(p => p.IdTemplate == options.IdTemplate && p.IdTypes.Contains(idType)) + ?? throw new ArgumentInvalidException(nameof(options.IdTemplate), "Невозможно импортировать файл"); - if (excelParser is null) - throw new ArgumentInvalidException("Невозможно импортировать файл", nameof(options.IdTemplate)); - - if (idType != WellOperation.IdOperationTypePlan && idType != WellOperation.IdOperationTypeFact) - throw new ArgumentInvalidException("Операции не существует", nameof(idType)); + if (idType != WellOperation.IdOperationTypePlan && idType != WellOperation.IdOperationTypeFact) + throw new ArgumentInvalidException(nameof(idType), "Операции не существует"); RowDto[] rows; var validationErrors = new List(); diff --git a/AsbCloudInfrastructure/Services/WellOperationService/ScheduleReportService.cs b/AsbCloudInfrastructure/Services/WellOperationService/ScheduleReportService.cs index e847179d..d46bfff1 100644 --- a/AsbCloudInfrastructure/Services/WellOperationService/ScheduleReportService.cs +++ b/AsbCloudInfrastructure/Services/WellOperationService/ScheduleReportService.cs @@ -33,10 +33,8 @@ namespace AsbCloudInfrastructure.Services.WellOperationService { var tvd = await operationsStatService.GetTvdAsync(idWell, token); - var well = await wellService.GetOrDefaultAsync(idWell, token); - - if(well is null) - throw new ArgumentInvalidException("idWell doesn`t exist", nameof(idWell)); + var well = await wellService.GetOrDefaultAsync(idWell, token) + ?? throw new ArgumentInvalidException(nameof(idWell), "idWell doesn`t exist"); var ecxelTemplateStream = GetExcelTemplateStream(); using var workbook = new XLWorkbook(ecxelTemplateStream, XLEventTracking.Disabled); diff --git a/AsbCloudInfrastructure/Services/WellService.cs b/AsbCloudInfrastructure/Services/WellService.cs index 4973baf0..97bf9e06 100644 --- a/AsbCloudInfrastructure/Services/WellService.cs +++ b/AsbCloudInfrastructure/Services/WellService.cs @@ -146,16 +146,10 @@ namespace AsbCloudInfrastructure.Services public override async Task InsertAsync(WellDto dto, CancellationToken token) { if (IsTelemetryAssignedToDifferentWell(dto)) - throw new ArgumentInvalidException("Телеметрия уже была привязана к другой скважине.", nameof(dto)); + throw new ArgumentInvalidException(nameof(dto), "Телеметрия уже была привязана к другой скважине."); - if (dto.IdWellType is < 1 or > 2) - throw new ArgumentInvalidException("Тип скважины указан неправильно.", nameof(dto)); - - if (dto.IdState is < 0 or > 2) - throw new ArgumentInvalidException("Текущее состояние работы скважины указано неправильно.", nameof(dto)); - if (dto.Id != 0 && (await GetCacheAsync(token)).Any(w => w.Id == dto.Id)) - throw new ArgumentInvalidException($"Нельзя повторно добавить скважину с id: {dto.Id}", nameof(dto)); + throw new ArgumentInvalidException(nameof(dto), $"Нельзя повторно добавить скважину с id: {dto.Id}"); var entity = Convert(dto); @@ -181,14 +175,8 @@ namespace AsbCloudInfrastructure.Services CancellationToken token) { if (IsTelemetryAssignedToDifferentWell(dto)) - throw new ArgumentInvalidException("Телеметрия уже была привязана к другой скважине.", nameof(dto)); + throw new ArgumentInvalidException(nameof(dto), "Телеметрия уже была привязана к другой скважине."); - if (dto.IdWellType is < 1 or > 2) - throw new ArgumentInvalidException("Тип скважины указан неправильно.", nameof(dto)); - - if (dto.IdState is < 0 or > 2) - throw new ArgumentInvalidException("Текущее состояние работы скважины указано неправильно.", nameof(dto)); - var oldRelations = (await GetCacheRelationCompanyWellAsync(token)) .Where(r => r.IdWell == dto.Id).ToArray(); @@ -302,9 +290,8 @@ namespace AsbCloudInfrastructure.Services public SimpleTimezoneDto GetTimezone(int idWell) { - var well = GetOrDefault(idWell); - if (well == null) - throw new ArgumentInvalidException($"idWell: {idWell} does not exist.", nameof(idWell)); + var well = GetOrDefault(idWell) + ?? throw new ArgumentInvalidException(nameof(idWell), $"idWell: {idWell} does not exist."); return GetTimezone(well); } diff --git a/AsbCloudWebApi/Controllers/Subsystems/SubsystemOperationTimeController.cs b/AsbCloudWebApi/Controllers/Subsystems/SubsystemOperationTimeController.cs index f7bc7afd..39d60ea9 100644 --- a/AsbCloudWebApi/Controllers/Subsystems/SubsystemOperationTimeController.cs +++ b/AsbCloudWebApi/Controllers/Subsystems/SubsystemOperationTimeController.cs @@ -196,7 +196,7 @@ namespace AsbCloudWebApi.Controllers.Subsystems var ltDate = request.LtDate.Value; var utcDateRequest = ltDate.ToUtcDateTimeOffset(well.Timezone.Hours); if (utcDateRequest.AddHours(2) > DateTime.UtcNow) - throw new ArgumentInvalidException("Запрашиваемый диапазон должен заканчиваться за 2 часа до текущего времени", nameof(request.LtDate)); + throw new ArgumentInvalidException(nameof(request.LtDate), "Запрашиваемый диапазон должен заканчиваться за 2 часа до текущего времени"); } } } diff --git a/AsbCloudWebApi/Controllers/WellboreController.cs b/AsbCloudWebApi/Controllers/WellboreController.cs index e9a590a0..ba3a27cb 100644 --- a/AsbCloudWebApi/Controllers/WellboreController.cs +++ b/AsbCloudWebApi/Controllers/WellboreController.cs @@ -77,14 +77,14 @@ public class WellboreController : ControllerBase { var idPair = id.Split(','); if (!int.TryParse(idPair[0], out var idWell)) - throw new ArgumentInvalidException($"Не удалось получить Id скважины \"{idPair[0]}\"", nameof(id)); + throw new ArgumentInvalidException(nameof(id), $"Не удалось получить Id скважины \"{idPair[0]}\""); if (idPair.Length > 1) { if (int.TryParse(idPair[1], out int idWellSectionType)) return (idWell, idWellSectionType); else - throw new ArgumentInvalidException($"Не удалось получить Id ствола \"{idPair[1]}\"", nameof(id)); + throw new ArgumentInvalidException(nameof(id), $"Не удалось получить Id ствола \"{idPair[1]}\""); } return (idWell, null); }