refactor ArgumentInvalidException

This commit is contained in:
ngfrolov 2023-09-29 12:06:46 +05:00
parent 33c49e8a48
commit 7ae00fe2f7
Signed by untrusted user who does not match committer: ng.frolov
GPG Key ID: E99907A0357B29A7
33 changed files with 168 additions and 221 deletions

View File

@ -1,4 +1,5 @@
using System;
using System.ComponentModel.DataAnnotations;
namespace AsbCloudApp.Data;
@ -25,12 +26,14 @@ public class NotificationDto : IId
/// <summary>
/// Заголовок уведомления
/// </summary>
[Required, StringLength(300, MinimumLength = 1, ErrorMessage = "Заголовок должен мыть не меньше 1-го знака и не больше 300")]
public string Title { get; set; } = null!;
/// <summary>
/// Сообщение уведомления
/// </summary>
public string Message { get; set; } = null!;
/// <summary>
/// Сообщение уведомления
/// </summary>
[Required, StringLength(2048, MinimumLength = 1, ErrorMessage = "Заголовок должен мыть не меньше 1-го знака и не больше 2048")]
public string Message { get; set; } = null!;
/// <summary>
/// Дата регистрации уведомления
@ -90,6 +93,7 @@ public class NotificationDto : IId
/// 0 - SignalR
/// 1 - Email
/// </summary>
[Range(0,1)]
public int IdTransportType { get; set; }
/// <summary>

View File

@ -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;
/// <summary>
/// РТК план проработка скважины
/// </summary>
public class ProcessMapWellboreDevelopmentDto : IId, IWellRelated
public class ProcessMapWellboreDevelopmentDto : IId, IWellRelated, IValidatableObject
{
/// <inheritdoc/>
public int Id { get; set; }
@ -94,4 +95,13 @@ public class ProcessMapWellboreDevelopmentDto : IId, IWellRelated
/// Комментарий
/// </summary>
public string? Comment { get; set; }
/// <inheritdoc/>
public IEnumerable<ValidationResult> 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;
}
}

View File

@ -47,6 +47,7 @@ namespace AsbCloudApp.Data
/// <summary>
/// ID типа скважины
/// </summary>
[Range(1, 2, ErrorMessage = "Тип скважины указан неправильно.")]
public int IdWellType { get; set; }
/// <summary>
@ -59,6 +60,7 @@ namespace AsbCloudApp.Data
/// 1 - в работе,
/// 2 - завершена
/// </summary>
[Range(0, 2, ErrorMessage = "Текущее состояние работы скважины указано неправильно.")]
public int IdState { get; set; }
/// <summary>

View File

@ -1,3 +1,5 @@
using System.ComponentModel.DataAnnotations;
namespace AsbCloudApp.Data.WellOperationImport;
/// <summary>
@ -8,7 +10,8 @@ public class WellOperationParserOptionsDto
/// <summary>
/// Название листа
/// </summary>
public string? SheetName { get; set; }
[StringLength(250, MinimumLength =1, ErrorMessage = "Название листа должно быть задано")]
public string SheetName { get; set; } = null!;
/// <summary>
/// Id шаблона

View File

@ -15,9 +15,9 @@ namespace AsbCloudApp.Exceptions
/// <summary>
/// конструктор
/// </summary>
/// <param name="message"></param>
/// <param name="paramName"></param>
public ArgumentInvalidException(string message, string paramName)
/// <param name="message"></param>
public ArgumentInvalidException(string paramName, string message)
: base(message)
{
ParamName = paramName;

View File

@ -18,7 +18,7 @@ namespace AsbCloudApp.Repositories
/// <param name="dtos"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<IEnumerable<WellFinalDocumentDBDto>> UpdateRangeAsync(int idWell, IEnumerable<WellFinalDocumentInputDto>? dtos, CancellationToken token);
Task<IEnumerable<WellFinalDocumentDBDto>> UpdateRangeAsync(int idWell, IEnumerable<WellFinalDocumentInputDto> dtos, CancellationToken token);
/// <summary>
/// Получение всех записей

View File

@ -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;
}

View File

@ -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)

View File

@ -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<int> 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<int> 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);

View File

@ -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
/// <inheritdoc/>
public async Task<IEnumerable<TrajectoryGeoPlanDto>> 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()

View File

@ -97,13 +97,10 @@ namespace AsbCloudInfrastructure.Repository
public async Task<int> 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<int> 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<UserRoleDto> 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<PermissionDto>();
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<RelationUserUserRole> GetCachRelationUserUserRoleCacheTag()
{
@ -215,7 +210,8 @@ namespace AsbCloudInfrastructure.Repository
return entities;
});
return cache!;
}
}
private void DropCacheRelationUserUserRoleCacheTag()
{
memoryCache.Remove(relationUserUserRoleCacheTag);

View File

@ -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);

View File

@ -32,10 +32,10 @@ namespace AsbCloudInfrastructure.Repository
}
///<inheritdoc/>
public async Task<IEnumerable<WellFinalDocumentDBDto>> UpdateRangeAsync(int idWell, IEnumerable<WellFinalDocumentInputDto>? dtos, CancellationToken token)
public async Task<IEnumerable<WellFinalDocumentDBDto>> UpdateRangeAsync(int idWell, IEnumerable<WellFinalDocumentInputDto> 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;
}

View File

@ -79,10 +79,8 @@ namespace AsbCloudInfrastructure.Services
/// <inheritdoc/>
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);

View File

@ -57,10 +57,10 @@ public class AutoGeneratedDailyReportService : IAutoGeneratedDailyReportService
var reports = new List<AutoGeneratedDailyReportInfoDto>();
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);

View File

@ -42,9 +42,8 @@ namespace AsbCloudInfrastructure.Services.DailyReport
public async Task<IEnumerable<DailyReportDto>> 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<int> 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<int> 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<DailyReportDto?> 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);

View File

@ -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<int> 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<UserDto>();
@ -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}»");

View File

@ -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;

View File

@ -70,26 +70,22 @@ namespace AsbCloudInfrastructure.Services.Email
return Task.WhenAll(tasks);
}
private Func<string, IServiceProvider, CancellationToken, Task> 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<INotificationRepository>();
var userRepository = serviceProvider.GetRequiredService<IUserRepository>();
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
{

View File

@ -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<int> 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<int> { 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);

View File

@ -84,9 +84,9 @@ namespace AsbCloudInfrastructure.Services
public Task<int> 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<int> 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<int> 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<int> 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);
}

View File

@ -35,10 +35,10 @@ namespace AsbCloudInfrastructure.Services.ProcessMap
public async Task<IEnumerable<ProcessMapReportDto>> 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);

View File

@ -26,15 +26,9 @@ public class ProcessMapWellboreDevelopmentService : IProcessMapWellboreDevelopme
public async Task<int> 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<ProcessMapWellboreDevelopmentDto>.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);
}

View File

@ -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
{

View File

@ -336,9 +336,8 @@ namespace AsbCloudInfrastructure.Services.Subsystems
private IQueryable<SubsystemOperationTime> 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)

View File

@ -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);

View File

@ -26,7 +26,7 @@ public class WellOperationDefaultExcelParser : IWellOperationExcelParser
private static IEnumerable<RowDto> 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))

View File

@ -57,16 +57,16 @@ public class WellOperationGazpromKhantosExcelParser : IWellOperationExcelParser
private IEnumerable<RowDto> 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))

View File

@ -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<string>();

View File

@ -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);

View File

@ -146,16 +146,10 @@ namespace AsbCloudInfrastructure.Services
public override async Task<int> 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);
}

View File

@ -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 часа до текущего времени");
}
}
}

View File

@ -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);
}