diff --git a/AsbCloudApp/Data/DetectedOperationListDto.cs b/AsbCloudApp/Data/DetectedOperationListDto.cs index 82718e2d..a18f6e87 100644 --- a/AsbCloudApp/Data/DetectedOperationListDto.cs +++ b/AsbCloudApp/Data/DetectedOperationListDto.cs @@ -1,6 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; +using System.Collections.Generic; namespace AsbCloudApp.Data { @@ -31,7 +29,7 @@ namespace AsbCloudApp.Data public double? AverageTargetValue { get; set; } /// - /// Коэффициент эффективности + /// Коэффициент эффективности, % /// public double? Efficiency { get; set; } diff --git a/AsbCloudApp/Data/ITelemetryData.cs b/AsbCloudApp/Data/ITelemetryData.cs index 95c69c61..3769eeac 100644 --- a/AsbCloudApp/Data/ITelemetryData.cs +++ b/AsbCloudApp/Data/ITelemetryData.cs @@ -16,7 +16,7 @@ namespace AsbCloudApp.Data /// /// Интерфейс записи данных телеметрии /// - public interface ITelemetryData: ITelemetryRelated + public interface ITelemetryData : ITelemetryRelated { /// /// Отметка времени для этой записи diff --git a/AsbCloudApp/Data/OperationValueDto.cs b/AsbCloudApp/Data/OperationValueDto.cs index 4e9ea565..14715213 100644 --- a/AsbCloudApp/Data/OperationValueDto.cs +++ b/AsbCloudApp/Data/OperationValueDto.cs @@ -1,6 +1,4 @@ -using System; - -namespace AsbCloudApp.Data +namespace AsbCloudApp.Data { /// /// Описание целевых/нормативных показателей операций diff --git a/AsbCloudApp/Data/TimeDto.cs b/AsbCloudApp/Data/TimeDto.cs index 7d628c91..6bb4b1e5 100644 --- a/AsbCloudApp/Data/TimeDto.cs +++ b/AsbCloudApp/Data/TimeDto.cs @@ -5,7 +5,7 @@ namespace AsbCloudApp.Data /// /// DTO времени /// - public class TimeDto: IComparable + public class TimeDto : IComparable { private int hour = 0; private int minute = 0; @@ -14,13 +14,15 @@ namespace AsbCloudApp.Data /// /// час /// - public int Hour { - get => hour; - set { + public int Hour + { + get => hour; + set + { if (value > 23 || value < 0) throw new ArgumentOutOfRangeException(nameof(Hour), "hour should be in [0; 23]"); - hour = value; - } + hour = value; + } } /// diff --git a/AsbCloudApp/Data/WellOperationCategoryDto.cs b/AsbCloudApp/Data/WellOperationCategoryDto.cs index 84a54934..6238f97a 100644 --- a/AsbCloudApp/Data/WellOperationCategoryDto.cs +++ b/AsbCloudApp/Data/WellOperationCategoryDto.cs @@ -3,7 +3,7 @@ /// /// DTO категория операции /// - public class WellOperationCategoryDto: IId + public class WellOperationCategoryDto : IId { /// public int Id { get; set; } diff --git a/AsbCloudApp/Requests/DetectedOperationRequest.cs b/AsbCloudApp/Requests/DetectedOperationRequest.cs index cb0ac671..5ce2b499 100644 --- a/AsbCloudApp/Requests/DetectedOperationRequest.cs +++ b/AsbCloudApp/Requests/DetectedOperationRequest.cs @@ -1,12 +1,12 @@ -using System.Collections.Generic; -using System; +using System; +using System.Collections.Generic; namespace AsbCloudApp.Requests { /// /// Параметры запроса на получение операций определенных по телеметрии /// - public class DetectedOperationRequest: RequestBase + public class DetectedOperationRequest : RequestBase { /// /// категории операций diff --git a/AsbCloudApp/Services/ICrudService.cs b/AsbCloudApp/Services/ICrudService.cs index 37dff698..8114fbaa 100644 --- a/AsbCloudApp/Services/ICrudService.cs +++ b/AsbCloudApp/Services/ICrudService.cs @@ -9,9 +9,9 @@ namespace AsbCloudApp.Services /// /// Сервис получения, добавления, изменения, удаления данных /// - /// - public interface ICrudService - where Tdto : Data.IId + /// + public interface ICrudService + where TDto : Data.IId { /// /// Код возврата ошибки: Id не найден в БД. @@ -23,7 +23,7 @@ namespace AsbCloudApp.Services /// /// /// emptyList if nothing found - Task> GetAllAsync(CancellationToken token); + Task> GetAllAsync(CancellationToken token); /// /// Получить запись по id @@ -31,14 +31,14 @@ namespace AsbCloudApp.Services /// /// /// null if not found - Task GetAsync(int id, CancellationToken token); + Task GetAsync(int id, CancellationToken token); /// /// Получить запись по id /// /// /// null if not found - Tdto? Get(int id); + TDto? Get(int id); /// /// Добавление новой записи @@ -46,7 +46,7 @@ namespace AsbCloudApp.Services /// /// /// Id новой записи - Task InsertAsync(Tdto newItem, CancellationToken token); + Task InsertAsync(TDto newItem, CancellationToken token); /// /// Добавление нескольких записей @@ -54,7 +54,7 @@ namespace AsbCloudApp.Services /// /// /// количество добавленных - Task InsertRangeAsync(IEnumerable newItems, CancellationToken token); + Task InsertRangeAsync(IEnumerable newItems, CancellationToken token); /// /// Отредактировать запись @@ -62,7 +62,7 @@ namespace AsbCloudApp.Services /// /// /// если больше 0 - Id записи, если меньше 0 - код ошибки - Task UpdateAsync(Tdto item, CancellationToken token); + Task UpdateAsync(TDto item, CancellationToken token); /// /// Удалить запись diff --git a/AsbCloudApp/Services/ICrudWellRelatedService.cs b/AsbCloudApp/Services/ICrudWellRelatedService.cs index 25e3d8f8..b09e21bd 100644 --- a/AsbCloudApp/Services/ICrudWellRelatedService.cs +++ b/AsbCloudApp/Services/ICrudWellRelatedService.cs @@ -11,7 +11,7 @@ namespace AsbCloudApp.Services /// /// public interface ICrudWellRelatedService : ICrudService - where Tdto: IId, IWellRelated + where Tdto : IId, IWellRelated { /// /// Получение всех записей по скважине diff --git a/AsbCloudApp/Services/IScheduleService.cs b/AsbCloudApp/Services/IScheduleService.cs index 326490e6..db892c18 100644 --- a/AsbCloudApp/Services/IScheduleService.cs +++ b/AsbCloudApp/Services/IScheduleService.cs @@ -1,6 +1,5 @@ using AsbCloudApp.Data; using System; -using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; diff --git a/AsbCloudApp/Services/ISetpointsService.cs b/AsbCloudApp/Services/ISetpointsService.cs index d5384b3e..e11b5642 100644 --- a/AsbCloudApp/Services/ISetpointsService.cs +++ b/AsbCloudApp/Services/ISetpointsService.cs @@ -10,8 +10,8 @@ namespace AsbCloudApp.Services Task InsertAsync(SetpointsRequestDto setpoints, CancellationToken token); Task> GetAsync(int idWell, CancellationToken token); Task> GetForPanelAsync(string uid, CancellationToken token); - Task TryDelete(int idWell, int id, CancellationToken token); - Task UpdateStateAsync(string uid, int id, SetpointsRequestDto setpointsRequestDto, CancellationToken token); - IEnumerable GetSetpointsNames(int idWell); + Task TryDelete(int id, CancellationToken token); + Task UpdateStateAsync(int id, SetpointsRequestDto setpointsRequestDto, CancellationToken token); + IEnumerable GetSetpointsNames(); } } diff --git a/AsbCloudDb/EFExtentions.cs b/AsbCloudDb/EFExtentions.cs index d43d9b56..596787b5 100644 --- a/AsbCloudDb/EFExtentions.cs +++ b/AsbCloudDb/EFExtentions.cs @@ -55,13 +55,13 @@ namespace AsbCloudDb { return dbSet.Contains(value) ? dbSet.Update(value) - : dbSet.Add(value); + : dbSet.Add(value); } public static (int updated, int inserted) UpsertRange(this DbSet dbSet, IEnumerable values) where T : class { - (int updated, int inserted) stat = (0,0); + (int updated, int inserted) stat = (0, 0); foreach (var value in values) if (dbSet.Contains(value)) { diff --git a/AsbCloudDb/Model/DetectedOperation.cs b/AsbCloudDb/Model/DetectedOperation.cs index 88786f3c..b5e4cefc 100644 --- a/AsbCloudDb/Model/DetectedOperation.cs +++ b/AsbCloudDb/Model/DetectedOperation.cs @@ -1,6 +1,5 @@ using Microsoft.EntityFrameworkCore; using System; -using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Text.Json.Serialization; diff --git a/AsbCloudDb/Model/Driller.cs b/AsbCloudDb/Model/Driller.cs index ef30babd..cb2a30d5 100644 --- a/AsbCloudDb/Model/Driller.cs +++ b/AsbCloudDb/Model/Driller.cs @@ -7,10 +7,10 @@ using System.Text.Json.Serialization; namespace AsbCloudDb.Model { [Table("t_driller"), Comment("Бурильщик")] - public class Driller: IId + public class Driller : IId { [Key] - [Column("id"),Comment("Идентификатор")] + [Column("id"), Comment("Идентификатор")] public int Id { get; set; } [Column("name"), Comment("Имя")] diff --git a/AsbCloudDb/Model/OperationValue.cs b/AsbCloudDb/Model/OperationValue.cs index 515c2db2..227a4995 100644 --- a/AsbCloudDb/Model/OperationValue.cs +++ b/AsbCloudDb/Model/OperationValue.cs @@ -5,7 +5,7 @@ using System.ComponentModel.DataAnnotations.Schema; namespace AsbCloudDb.Model { [Table("t_operationvalue"), Comment("Целевые/нормативные показатели операции")] - public class OperationValue: IId, IWellRelated + public class OperationValue : IId, IWellRelated { [Key] [Column("id"), Comment("Идентификатор")] @@ -24,7 +24,7 @@ namespace AsbCloudDb.Model public double StandardValue { get; set; } [Column("depth_start"), Comment("Старотовая глубина")] - public double DepthStart { get; set; } + public double DepthStart { get; set; } [Column("depth_end"), Comment("Конечная глубина")] public double DepthEnd { get; set; } diff --git a/AsbCloudDb/Model/Schedule.cs b/AsbCloudDb/Model/Schedule.cs index 3704419a..f8aece41 100644 --- a/AsbCloudDb/Model/Schedule.cs +++ b/AsbCloudDb/Model/Schedule.cs @@ -6,10 +6,10 @@ using System.ComponentModel.DataAnnotations.Schema; namespace AsbCloudDb.Model { [Table("t_schedule"), Comment("График работы бурильщика")] - public class Schedule: IId, IWellRelated + public class Schedule : IId, IWellRelated { [Key] - [Column("id"),Comment("Идентификатор")] + [Column("id"), Comment("Идентификатор")] public int Id { get; set; } [Column("id_driller"), Comment("Идентификатор бурильщика")] diff --git a/AsbCloudInfrastructure/DependencyInjection.cs b/AsbCloudInfrastructure/DependencyInjection.cs index 97ae2dae..49602160 100644 --- a/AsbCloudInfrastructure/DependencyInjection.cs +++ b/AsbCloudInfrastructure/DependencyInjection.cs @@ -65,7 +65,7 @@ namespace AsbCloudInfrastructure TypeAdapterConfig.GlobalSettings.Default.Config .ForType() .Ignore(dst => dst.Deposit, - dst=>dst.Wells); + dst => dst.Wells); } @@ -120,7 +120,7 @@ namespace AsbCloudInfrastructure services.AddTransient(); // admin crud services: - services.AddTransient, CrudServiceBase>(s => + services.AddTransient, CrudServiceBase>(s => new CrudCacheServiceBase( s.GetService(), dbSet => dbSet.Include(t => t.Well))); // может быть включен в сервис TelemetryService @@ -132,9 +132,9 @@ namespace AsbCloudInfrastructure services.AddTransient, CrudCacheServiceBase>(s => new CrudCacheServiceBase( s.GetService(), - dbSet => dbSet.Include(c=>c.CompanyType))); + dbSet => dbSet.Include(c => c.CompanyType))); services.AddTransient, CrudCacheServiceBase>(); - services.AddTransient, CrudCacheServiceBase>(s => + services.AddTransient, CrudCacheServiceBase>(s => new CrudCacheServiceBase( s.GetService(), dbSet => dbSet diff --git a/AsbCloudInfrastructure/EfCache/EfCacheDictionaryExtensions.cs b/AsbCloudInfrastructure/EfCache/EfCacheDictionaryExtensions.cs index b4f45b3e..033a3d47 100644 --- a/AsbCloudInfrastructure/EfCache/EfCacheDictionaryExtensions.cs +++ b/AsbCloudInfrastructure/EfCache/EfCacheDictionaryExtensions.cs @@ -42,7 +42,7 @@ namespace AsbCloudInfrastructure.EfCache { if (Data is Dictionary typedData) return typedData; - if (Data is Dictionary typedEntityData) + if (Data is Dictionary typedEntityData) { if (semaphore.Wait(0)) { @@ -375,16 +375,16 @@ namespace AsbCloudInfrastructure.EfCache /// /// public static async Task> FromCacheDictionaryAsync( - this IQueryable query, - string tag, - TimeSpan obsolescence, - Func keySelector, + this IQueryable query, + string tag, + TimeSpan obsolescence, + Func keySelector, CancellationToken token = default) where TEntity : class where TKey : notnull { async Task factory(CancellationToken token) - => await query.AsNoTracking().ToDictionaryAsync(keySelector, token); + => await query.AsNoTracking().ToDictionaryAsync(keySelector, token); var cache = await GetOrAddCacheAsync(tag, factory, obsolescence, token); return cache.GetData(); } diff --git a/AsbCloudInfrastructure/EfCache/EfCacheExtensions.cs b/AsbCloudInfrastructure/EfCache/EfCacheExtensions.cs index 2c9c953f..e9f17c32 100644 --- a/AsbCloudInfrastructure/EfCache/EfCacheExtensions.cs +++ b/AsbCloudInfrastructure/EfCache/EfCacheExtensions.cs @@ -15,7 +15,7 @@ namespace AsbCloudInfrastructure.EfCache /// public static class EfCacheExtensions { - private static readonly Dictionary caches = new(16); + private static readonly Dictionary caches = new(16); private static readonly TimeSpan semaphoreTimeout = TimeSpan.FromSeconds(25); private static readonly SemaphoreSlim semaphore = new(1); private static readonly TimeSpan minCacheTime = TimeSpan.FromSeconds(2); @@ -71,7 +71,7 @@ namespace AsbCloudInfrastructure.EfCache } } } - if(attempt > 0) + if (attempt > 0) return GetData(convert, --attempt); throw new TypeAccessException("Cache data has wrong type. Possible 'tag' is not unique."); } @@ -84,18 +84,19 @@ namespace AsbCloudInfrastructure.EfCache { if (semaphore.Wait(0)) { - try { + try + { cache = new CacheItem(); caches.Add(tag, cache); } catch { - throw; + throw; } finally { semaphore.Release(); - } + } break; } else @@ -109,7 +110,7 @@ namespace AsbCloudInfrastructure.EfCache semaphore.Release(); throw new TimeoutException("EfCacheL2.GetOrAddCache. Can't wait too long while getting cache"); } - } + } } cache = caches[tag]; @@ -141,7 +142,7 @@ namespace AsbCloudInfrastructure.EfCache cache.semaphore.Release(); } } - else if(cache.DateObsoleteTotal < DateTime.Now) + else if (cache.DateObsoleteTotal < DateTime.Now) { if (cache.semaphore.Wait(semaphoreTimeout)) { @@ -152,7 +153,7 @@ namespace AsbCloudInfrastructure.EfCache cache.semaphore.Release(); throw new TimeoutException("EfCacheL2.GetOrAddCache. Can't wait too long while getting cache"); } - } + } } return cache; } @@ -281,7 +282,7 @@ namespace AsbCloudInfrastructure.EfCache public static IEnumerable FromCache(this IQueryable query, string tag, TimeSpan obsolescence, Func convert) where TEntity : class { - IEnumerable factory () => query.AsNoTracking().ToList(); + IEnumerable factory() => query.AsNoTracking().ToList(); var cache = GetOrAddCache(tag, factory, obsolescence); return cache.GetData(convert); } @@ -327,7 +328,7 @@ namespace AsbCloudInfrastructure.EfCache where TEntity : class { async Task factory(CancellationToken token) - => await query.AsNoTracking().ToListAsync(token); + => await query.AsNoTracking().ToListAsync(token); var cache = await GetOrAddCacheAsync(tag, factory, obsolescence, token); return cache.GetData(convert); } diff --git a/AsbCloudInfrastructure/IInfrastructureMarker.cs b/AsbCloudInfrastructure/IInfrastructureMarker.cs index 990c431c..207081d6 100644 --- a/AsbCloudInfrastructure/IInfrastructureMarker.cs +++ b/AsbCloudInfrastructure/IInfrastructureMarker.cs @@ -4,5 +4,5 @@ /// Тип для поиска этой сборки /// public interface IInfrastructureMarker - {} + { } } diff --git a/AsbCloudInfrastructure/MapsterExtension.cs b/AsbCloudInfrastructure/MapsterExtension.cs index d86af842..94ed630c 100644 --- a/AsbCloudInfrastructure/MapsterExtension.cs +++ b/AsbCloudInfrastructure/MapsterExtension.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; - -namespace Mapster +namespace Mapster { public static class MapsterExtension { diff --git a/AsbCloudInfrastructure/Services/CrudCacheServiceBase.cs b/AsbCloudInfrastructure/Services/CrudCacheServiceBase.cs index 82c19335..3da52cd0 100644 --- a/AsbCloudInfrastructure/Services/CrudCacheServiceBase.cs +++ b/AsbCloudInfrastructure/Services/CrudCacheServiceBase.cs @@ -15,7 +15,7 @@ namespace AsbCloudInfrastructure.Services /// /// /// - public class CrudCacheServiceBase: CrudServiceBase + public class CrudCacheServiceBase : CrudServiceBase where TDto : AsbCloudApp.Data.IId where TEntity : class, AsbCloudDb.Model.IId { @@ -87,6 +87,15 @@ namespace AsbCloudInfrastructure.Services return result; } + /// + public override async Task UpdateRangeAsync(IEnumerable dtos, CancellationToken token) + { + var result = await base.UpdateRangeAsync(dtos, token); + if (result > 0) + DropCache(); + return result; + } + /// public override async Task DeleteAsync(int id, CancellationToken token) { diff --git a/AsbCloudInfrastructure/Services/CrudServiceBase.cs b/AsbCloudInfrastructure/Services/CrudServiceBase.cs index c3e9fdb2..552afc61 100644 --- a/AsbCloudInfrastructure/Services/CrudServiceBase.cs +++ b/AsbCloudInfrastructure/Services/CrudServiceBase.cs @@ -3,7 +3,6 @@ using AsbCloudDb.Model; using Mapster; using Microsoft.EntityFrameworkCore; using System; -using System.Collections; using System.Collections.Generic; using System.Linq; using System.Threading; @@ -37,7 +36,8 @@ namespace AsbCloudInfrastructure.Services this.dbContext = dbContext; dbSet = dbContext.Set(); - GetQuery = () => { + GetQuery = () => + { IQueryable query = dbSet; foreach (var include in includes) query = query.Include(include); @@ -94,7 +94,7 @@ namespace AsbCloudInfrastructure.Services { var entity = Convert(item); entity.Id = 0; - var entry = dbSet.Add(entity); + var entry = dbSet.Add(entity); await dbContext.SaveChangesAsync(token); entry.State = EntityState.Detached; return entity.Id; @@ -129,10 +129,10 @@ namespace AsbCloudInfrastructure.Services .AsNoTracking() .FirstOrDefaultAsync(e => e.Id == item.Id, token) .ConfigureAwait(false); - + if (existingEntity is null) return ICrudService.ErrorIdNotFound; - + var entity = Convert(item); var entry = dbSet.Update(entity); await dbContext.SaveChangesAsync(token); @@ -140,6 +140,29 @@ namespace AsbCloudInfrastructure.Services return entry.Entity.Id; } + public virtual async Task UpdateRangeAsync(IEnumerable dtos, CancellationToken token) + { + var ids = dtos.Select(d => d.Id); + var existingEntities = await dbSet + .AsNoTracking() + .Where(d => ids.Contains(d.Id)) + .Select(d => d.Id) + .ToListAsync(token) + .ConfigureAwait(false); + + if (ids.Count() > existingEntities.Count) + return ICrudService.ErrorIdNotFound; + + foreach (var dto in dtos) + { + var entity = Convert(dto); + var entry = dbSet.Update(entity); + } + + var affected = await dbContext.SaveChangesAsync(token); + return affected; + } + /// public virtual Task DeleteAsync(int id, CancellationToken token = default) { diff --git a/AsbCloudInfrastructure/Services/CrudWellRelatedServiceBase.cs b/AsbCloudInfrastructure/Services/CrudWellRelatedServiceBase.cs index 044f6def..f3899c12 100644 --- a/AsbCloudInfrastructure/Services/CrudWellRelatedServiceBase.cs +++ b/AsbCloudInfrastructure/Services/CrudWellRelatedServiceBase.cs @@ -14,13 +14,13 @@ namespace AsbCloudInfrastructure.Services where TDto : AsbCloudApp.Data.IId, AsbCloudApp.Data.IWellRelated where TEntity : class, AsbCloudDb.Model.IId, AsbCloudDb.Model.IWellRelated { - public CrudWellRelatedServiceBase(IAsbCloudDbContext context) + public CrudWellRelatedServiceBase(IAsbCloudDbContext context) : base(context) { } - public CrudWellRelatedServiceBase(IAsbCloudDbContext dbContext, ISet includes) + public CrudWellRelatedServiceBase(IAsbCloudDbContext dbContext, ISet includes) : base(dbContext, includes) { } - public CrudWellRelatedServiceBase(IAsbCloudDbContext context, Func, IQueryable> makeQuery) + public CrudWellRelatedServiceBase(IAsbCloudDbContext context, Func, IQueryable> makeQuery) : base(context, makeQuery) { } public async Task> GetByIdWellAsync(int idWell, CancellationToken token) @@ -36,9 +36,9 @@ namespace AsbCloudInfrastructure.Services { if (!idsWells.Any()) return Enumerable.Empty(); - + var entities = await GetQuery() - .Where(e => idsWells.Contains( e.IdWell)) + .Where(e => idsWells.Contains(e.IdWell)) .ToListAsync(token); var dtos = entities.Select(Convert).ToList(); return dtos; diff --git a/AsbCloudInfrastructure/Services/DailyReport/DailyReportService.cs b/AsbCloudInfrastructure/Services/DailyReport/DailyReportService.cs index a503918d..058fb103 100644 --- a/AsbCloudInfrastructure/Services/DailyReport/DailyReportService.cs +++ b/AsbCloudInfrastructure/Services/DailyReport/DailyReportService.cs @@ -1,14 +1,14 @@ -using System; +using AsbCloudApp.Data; +using AsbCloudApp.Services; +using AsbCloudDb.Model; +using Mapster; +using Microsoft.EntityFrameworkCore; +using System; +using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; -using Microsoft.EntityFrameworkCore; -using Mapster; -using AsbCloudApp.Data; -using AsbCloudApp.Services; -using AsbCloudDb.Model; -using System.Collections.Generic; namespace AsbCloudInfrastructure.Services.DailyReport { @@ -26,7 +26,7 @@ namespace AsbCloudInfrastructure.Services.DailyReport } public async Task> GetListAsync(int idWell, DateTime? begin, DateTime? end, CancellationToken token) - { + { var query = db.DailyReports.Where(r => r.IdWell == idWell); var offsetHours = wellService.GetTimezone(idWell).Hours; @@ -41,7 +41,7 @@ namespace AsbCloudInfrastructure.Services.DailyReport var endOffset = ((DateTime)end).ToUtcDateTimeOffset(offsetHours); query = query.Where(d => d.StartDate <= endOffset); } - + var entities = await query .ToListAsync(token); @@ -127,7 +127,7 @@ namespace AsbCloudInfrastructure.Services.DailyReport { ReportDate = date, WellName = well.Caption, - ClusterName = well.Cluster, + ClusterName = well.Cluster, }; DailyReportDto result = dto; return result; @@ -143,7 +143,7 @@ namespace AsbCloudInfrastructure.Services.DailyReport private static DailyReportInfo Convert(DailyReportDto dto, double offsetHours) { - var entity = dto.Adapt(); + var entity = dto.Adapt(); entity.ReportDate = dto.ReportDate .ToUtcDateTimeOffset(offsetHours) .Date; diff --git a/AsbCloudInfrastructure/Services/DetectOperations/DetectedOperationService.cs b/AsbCloudInfrastructure/Services/DetectOperations/DetectedOperationService.cs index 4caa5687..f84127a3 100644 --- a/AsbCloudInfrastructure/Services/DetectOperations/DetectedOperationService.cs +++ b/AsbCloudInfrastructure/Services/DetectOperations/DetectedOperationService.cs @@ -13,7 +13,7 @@ using System.Threading.Tasks; namespace AsbCloudInfrastructure.Services.DetectOperations { - public class DetectedOperationService: IDetectedOperationService + public class DetectedOperationService : IDetectedOperationService { public const int IdOperationRotor = 1; public const int IdOperationSlide = 3; @@ -24,7 +24,7 @@ namespace AsbCloudInfrastructure.Services.DetectOperations private readonly IOperationValueService operationValueService; private readonly IScheduleService scheduleService; - public DetectedOperationService(IAsbCloudDbContext db, IWellService wellService, + public DetectedOperationService(IAsbCloudDbContext db, IWellService wellService, IOperationValueService operationValueService, IScheduleService scheduleService) { this.db = db; @@ -43,7 +43,7 @@ namespace AsbCloudInfrastructure.Services.DetectOperations .AsNoTracking(); var data = await query.ToListAsync(token); - + var operationValues = await operationValueService.GetByIdWellAsync(idWell, token); var schedules = await scheduleService.GetByIdWellAsync(idWell, token); var dtos = data.Select(o => Convert(o, well, operationValues, schedules)); @@ -84,7 +84,7 @@ namespace AsbCloudInfrastructure.Services.DetectOperations if (well?.IdTelemetry is null || well.Timezone is null) return 0; - var query = BuildQuery(well, request); + var query = BuildQuery(well, request); db.DetectedOperations.RemoveRange(query); return await db.SaveChangesAsync(token); } @@ -170,10 +170,10 @@ namespace AsbCloudInfrastructure.Services.DetectOperations && e.DepthStart <= dto.DepthStart); var timeStart = new TimeDto(dateStart); - var driller = schedules.FirstOrDefault(s => + var driller = schedules.FirstOrDefault(s => s.DrillStart <= dateStart && s.DrillEnd > dateStart && ( - s.ShiftStart > s.ShiftEnd + s.ShiftStart > s.ShiftEnd ) ^ (s.ShiftStart <= timeStart && s.ShiftEnd > timeStart )) @@ -191,6 +191,6 @@ namespace AsbCloudInfrastructure.Services.DetectOperations return result; } - + } } diff --git a/AsbCloudInfrastructure/Services/DetectOperations/Detectors/DetectorDrillingRotor.cs b/AsbCloudInfrastructure/Services/DetectOperations/Detectors/DetectorDrillingRotor.cs index e8ebf9da..4027ab42 100644 --- a/AsbCloudInfrastructure/Services/DetectOperations/Detectors/DetectorDrillingRotor.cs +++ b/AsbCloudInfrastructure/Services/DetectOperations/Detectors/DetectorDrillingRotor.cs @@ -16,11 +16,11 @@ namespace AsbCloudInfrastructure.Services.DetectOperations.Detectors { var firstItem = telemetry[position]; var delta = firstItem.WellDepth - firstItem.BitDepth; - if (delta is not null && + if (delta is not null && System.Math.Abs((float)delta) > 1d) return false; - var fragment = telemetry[position .. (position + FragmentLength)]; + var fragment = telemetry[position..(position + FragmentLength)]; const double minRop = 5; //м/час const double minRotorSpeed = 5; //об/мин @@ -31,7 +31,7 @@ namespace AsbCloudInfrastructure.Services.DetectOperations.Detectors return false; var lineWellDepth = new InterpolationLine(fragment.Select(d => (d.WellDepth ?? 0d, d.DateTime.Ticks / ticksPerHour))); - if(!lineWellDepth.IsYIncreases(minRop)) + if (!lineWellDepth.IsYIncreases(minRop)) return false; var lineRotorSpeed = new InterpolationLine(fragment.Select(d => (d.RotorSpeed ?? 0d, d.DateTime.Ticks / ticksPerHour))); diff --git a/AsbCloudInfrastructure/Services/DetectOperations/Detectors/DetectorDrillingSlide.cs b/AsbCloudInfrastructure/Services/DetectOperations/Detectors/DetectorDrillingSlide.cs index 3b4655c3..ddf15aa0 100644 --- a/AsbCloudInfrastructure/Services/DetectOperations/Detectors/DetectorDrillingSlide.cs +++ b/AsbCloudInfrastructure/Services/DetectOperations/Detectors/DetectorDrillingSlide.cs @@ -19,7 +19,7 @@ namespace AsbCloudInfrastructure.Services.DetectOperations.Detectors System.Math.Abs((float)delta) > 1d) return false; - var fragment = telemetry[position .. (position + FragmentLength)]; + var fragment = telemetry[position..(position + FragmentLength)]; const double minRop = 5; //м/час const double minRotorSpeed = 5; //об/мин @@ -30,7 +30,7 @@ namespace AsbCloudInfrastructure.Services.DetectOperations.Detectors return false; var lineWellDepth = new InterpolationLine(fragment.Select(d => (d.WellDepth ?? 0d, d.DateTime.Ticks / ticksPerHour))); - if(!lineWellDepth.IsYIncreases(minRop)) + if (!lineWellDepth.IsYIncreases(minRop)) return false; var lineRotorSpeed = new InterpolationLine(fragment.Select(d => (d.RotorSpeed ?? 0d, d.DateTime.Ticks / ticksPerHour))); diff --git a/AsbCloudInfrastructure/Services/DetectOperations/Detectors/DetectorSlipsTime.cs b/AsbCloudInfrastructure/Services/DetectOperations/Detectors/DetectorSlipsTime.cs index d7d7415a..ba8b70c6 100644 --- a/AsbCloudInfrastructure/Services/DetectOperations/Detectors/DetectorSlipsTime.cs +++ b/AsbCloudInfrastructure/Services/DetectOperations/Detectors/DetectorSlipsTime.cs @@ -5,7 +5,7 @@ namespace AsbCloudInfrastructure.Services.DetectOperations.Detectors #nullable enable class DetectorSlipsTime : DetectorAbstract { - public DetectorSlipsTime() :base(14) {} + public DetectorSlipsTime() : base(14) { } public double HookWeightSP { get; set; } = 20; public double PressureSP { get; set; } = 15; public double PosisionSP { get; set; } = 8; @@ -15,7 +15,7 @@ namespace AsbCloudInfrastructure.Services.DetectOperations.Detectors { var item = telemetry[position]; - var result = + var result = item.HookWeight < HookWeightSP && item.Pressure < PressureSP && item.BlockPosition < PosisionSP && diff --git a/AsbCloudInfrastructure/Services/DetectOperations/OperationDetectionBackgroundService.cs b/AsbCloudInfrastructure/Services/DetectOperations/OperationDetectionBackgroundService.cs index afb43a57..59cc3f31 100644 --- a/AsbCloudInfrastructure/Services/DetectOperations/OperationDetectionBackgroundService.cs +++ b/AsbCloudInfrastructure/Services/DetectOperations/OperationDetectionBackgroundService.cs @@ -4,10 +4,10 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using System; using System.Collections.Generic; +using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; -using System.Diagnostics; namespace AsbCloudInfrastructure.Services.DetectOperations { @@ -92,20 +92,20 @@ namespace AsbCloudInfrastructure.Services.DetectOperations .GroupJoin(lastDetectedDates, t => t, o => o.IdTelemetry, - (outer, inner) => new - { + (outer, inner) => new + { IdTelemetry = outer, - LastDate = inner.SingleOrDefault()?.LastDate , + LastDate = inner.SingleOrDefault()?.LastDate, }); var affected = 0; foreach (var item in JounedlastDetectedDates) { - var newOperations = await DetectOperationsAsync(item.IdTelemetry, item.LastDate??DateTimeOffset.MinValue, db, token); + var newOperations = await DetectOperationsAsync(item.IdTelemetry, item.LastDate ?? DateTimeOffset.MinValue, db, token); if (newOperations.Any()) { db.DetectedOperations.AddRange(newOperations); affected += await db.SaveChangesAsync(token); - } + } } return affected; } @@ -115,7 +115,8 @@ namespace AsbCloudInfrastructure.Services.DetectOperations var query = db.TelemetryDataSaub .AsNoTracking() .Where(d => d.IdTelemetry == idTelemetry) - .Select(d => new DetectableTelemetry{ + .Select(d => new DetectableTelemetry + { DateTime = d.DateTime, IdUser = d.IdUser, WellDepth = d.WellDepth, @@ -135,7 +136,7 @@ namespace AsbCloudInfrastructure.Services.DetectOperations var dbTime_ = 0d; var sw_ = new Stopwatch(); var otherTime_ = 0d; - + while (true) { sw_.Restart(); @@ -148,7 +149,7 @@ namespace AsbCloudInfrastructure.Services.DetectOperations dbTime_ += sw_.ElapsedMilliseconds; dbRequests_++; sw_.Restart(); - + if (data.Length < minFragmentLength) break; @@ -162,7 +163,7 @@ namespace AsbCloudInfrastructure.Services.DetectOperations foreach (var detector in detectors) { - if(data.Length < skip + detector.StepLength + detector.FragmentLength) + if (data.Length < skip + detector.StepLength + detector.FragmentLength) continue; var detectedOperation = detector.DetectOrDefault(data, ref skip); @@ -183,15 +184,15 @@ namespace AsbCloudInfrastructure.Services.DetectOperations sw_.Stop(); otherTime_ += sw_.ElapsedMilliseconds; - + if (!isDetected) { if (data.Length < take) break; - + var lastPartDate = data.Last().DateTime; startDate = startDate + (0.75 * (lastPartDate - startDate)); - } + } } return detectedOperations; diff --git a/AsbCloudInfrastructure/Services/DrillerService.cs b/AsbCloudInfrastructure/Services/DrillerService.cs index 3b5f0180..a268eea0 100644 --- a/AsbCloudInfrastructure/Services/DrillerService.cs +++ b/AsbCloudInfrastructure/Services/DrillerService.cs @@ -1,11 +1,6 @@ using AsbCloudApp.Data; using AsbCloudApp.Services; using AsbCloudDb.Model; -using AsbCloudInfrastructure.Services.Cache; -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; namespace AsbCloudInfrastructure.Services { diff --git a/AsbCloudInfrastructure/Services/DrillingProgram/DrillingProgramService.cs b/AsbCloudInfrastructure/Services/DrillingProgram/DrillingProgramService.cs index 7d5d79c3..7c8d6fe1 100644 --- a/AsbCloudInfrastructure/Services/DrillingProgram/DrillingProgramService.cs +++ b/AsbCloudInfrastructure/Services/DrillingProgram/DrillingProgramService.cs @@ -55,7 +55,7 @@ namespace AsbCloudInfrastructure.Services.DrillingProgram IConfiguration configuration, IBackgroundWorkerService backgroundWorker, IEmailService emailService) - { + { this.context = context; this.fileService = fileService; this.userService = userService; @@ -181,7 +181,7 @@ namespace AsbCloudInfrastructure.Services.DrillingProgram await RemoveDrillingProgramAsync(part.IdWell, token); - await NotifyApproversAsync(part, result.Id, fileFullName, token); + await NotifyApproversAsync(part, result.Id, fileFullName, token); return result.Id; } @@ -229,7 +229,7 @@ namespace AsbCloudInfrastructure.Services.DrillingProgram throw new ArgumentInvalidException($"User id == {idUser} does not exist", nameof(idUser)); var part = await context.DrillingProgramParts - .Include(p=>p.FileCategory) + .Include(p => p.FileCategory) .FirstOrDefaultAsync(p => p.IdWell == idWell && p.IdFileCategory == idFileCategory, token); if (part is null) @@ -367,7 +367,7 @@ namespace AsbCloudInfrastructure.Services.DrillingProgram private async Task NotifyPublisherOnRejectAsync(FileMarkDto fileMark, CancellationToken token) { - var file = await fileService.GetInfoAsync(fileMark.IdFile, token); + var file = await fileService.GetInfoAsync(fileMark.IdFile, token); var well = await wellService.GetAsync(file.IdWell, token); var user = file.Author; var factory = new MailBodyFactory(configuration); diff --git a/AsbCloudInfrastructure/Services/SAUB/SetpointsService.cs b/AsbCloudInfrastructure/Services/SAUB/SetpointsService.cs index 0161edbe..832c523b 100644 --- a/AsbCloudInfrastructure/Services/SAUB/SetpointsService.cs +++ b/AsbCloudInfrastructure/Services/SAUB/SetpointsService.cs @@ -1,8 +1,7 @@ using AsbCloudApp.Data.SAUB; using AsbCloudApp.Services; using AsbCloudDb.Model; -using AsbCloudInfrastructure.Services.Cache; -using Mapster; +using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; @@ -11,7 +10,7 @@ using System.Threading.Tasks; namespace AsbCloudInfrastructure.Services.SAUB { - public class SetpointsService : ISetpointsService, IConverter + public class SetpointsService : ISetpointsService { // ## Инфо от АПГ от 26.11.2021, дополнения ШОВ от 26.11.2021 private static readonly Dictionary SetpointInfos = new() @@ -23,38 +22,33 @@ namespace AsbCloudInfrastructure.Services.SAUB { "speedRotorSp", new SetpointInfoDto { Name = "speedRotorSp", DisplayName = "Скорость бурения в роторе, м/ч" } }, { "speedSlideSp", new SetpointInfoDto { Name = "speedSlideSp", DisplayName = "Скорость бурения в слайде, м/ч" } }, { "speedDevelopSp", new SetpointInfoDto { Name = "speedDevelopSp", DisplayName = "Скорость проработки, м/ч" } }, - { "torque_pid_out_limit", new SetpointInfoDto { Name = "torque_pid_out_limit", DisplayName = "Торк мастер. Допустимый процент отклонения от заданой скорости вращения" } }, // Такая же что и прямой + { "torque_pid_out_limit", new SetpointInfoDto { Name = "torque_pid_out_limit", DisplayName = "Торк мастер. Допустимый процент отклонения от заданной скорости вращения" } }, // Такая же что и прямой //{ "", new SetpointInfoDto { Name = "", DisplayName = "Обороты ВСП, об/мин" } }, // Оно в ПЛК спинмастера, пока сделать нельзя, позднее можно. //{ "", new SetpointInfoDto { Name = "", DisplayName = "Расход промывочной жидкости, л/с" } }, // Нет в контроллере }; - - private readonly CacheTable cacheSetpoints; + private readonly IAsbCloudDbContext db; private readonly ITelemetryService telemetryService; + private readonly CrudCacheServiceBase setpointsRepository; - public SetpointsService(IAsbCloudDbContext db, CacheDb cacheDb, ITelemetryService telemetryService) + public SetpointsService(IAsbCloudDbContext db, ITelemetryService telemetryService) { - cacheSetpoints = cacheDb.GetCachedTable( - (AsbCloudDbContext)db, - nameof(SetpointsRequest.Author), - nameof(SetpointsRequest.Well)); + setpointsRepository = new CrudCacheServiceBase(db, q => q.Include(s => s.Author).Include(s => s.Well)); + this.db = db; this.telemetryService = telemetryService; } - public async Task InsertAsync(SetpointsRequestDto setpoints, CancellationToken token) + public async Task InsertAsync(SetpointsRequestDto setpointsRequest, CancellationToken token) { - setpoints.IdState = 1; - setpoints.UploadDate = DateTime.UtcNow; - var dto = Convert(setpoints); - var inserted = await cacheSetpoints.InsertAsync(dto, token) - .ConfigureAwait(false); - return inserted?.Id ?? 0; + setpointsRequest.IdState = 1; + setpointsRequest.UploadDate = DateTime.UtcNow; + var result = await setpointsRepository.InsertAsync(setpointsRequest, token); + return result; } public async Task> GetAsync(int idWell, CancellationToken token) { - var entities = await cacheSetpoints.WhereAsync(s => s.IdWell == idWell, token) - .ConfigureAwait(false); - var dtos = entities.Select(s => Convert(s)); + var all = await setpointsRepository.GetAllAsync(token); + var dtos = all.Where(s => s.IdWell == idWell); return dtos; } @@ -64,79 +58,45 @@ namespace AsbCloudInfrastructure.Services.SAUB if (idWell < 0) return null; + var all = await setpointsRepository.GetAllAsync(token); + var filtered = all.Where(s => + s.IdWell == idWell && + s.IdState == 1 && + s.UploadDate.AddSeconds(s.ObsolescenceSec) > DateTime.Now); - var entities = (await cacheSetpoints.WhereAsync(s => - s.IdWell == idWell && s.IdState == 1 && s.UploadDate.AddSeconds(s.ObsolescenceSec) > DateTime.Now, - token) - .ConfigureAwait(false)) - .ToList();// без .ToList() работает не правильно. - - if (!entities.Any()) + if (!filtered.Any()) return null; - foreach (var entity in entities) + foreach (var entity in filtered) entity.IdState = 2; - await cacheSetpoints.UpsertAsync(entities, token) - .ConfigureAwait(false); + await setpointsRepository.UpdateRangeAsync(filtered, token); - var dtos = entities.Select(Convert); - - return dtos; + return filtered; } - public async Task UpdateStateAsync(string uid, int id, SetpointsRequestDto setpointsRequestDto, CancellationToken token) + public async Task UpdateStateAsync(int id, SetpointsRequestDto setpointsRequestDto, CancellationToken token) { if (setpointsRequestDto.IdState != 3 && setpointsRequestDto.IdState != 4) throw new ArgumentOutOfRangeException(nameof(setpointsRequestDto), $"{nameof(setpointsRequestDto.IdState)} = {setpointsRequestDto.IdState}. Mast be 3 or 4."); - var idWell = telemetryService.GetIdWellByTelemetryUid(uid) ?? -1; - - if (idWell < 0) - return 0; - - bool Predicate(SetpointsRequest s) => s.Id == id && s.IdWell == idWell && s.IdState == 2; - - var entity = await cacheSetpoints.FirstOrDefaultAsync(Predicate, token) - .ConfigureAwait(false); + var entity = await setpointsRepository.GetAsync(id, token); if (entity is null) return 0; entity.IdState = setpointsRequestDto.IdState; - await cacheSetpoints.UpsertAsync(entity, token) - .ConfigureAwait(false); - return 1; + var affected = await setpointsRepository.UpdateAsync(entity, token); + return affected; } - public async Task TryDelete(int idWell, int id, CancellationToken token) + public async Task TryDelete(int id, CancellationToken token) { - bool Predicate(SetpointsRequest s) => s.Id == id && s.IdWell == idWell && s.IdState == 1; - var isExist = await cacheSetpoints.ContainsAsync(Predicate, token) - .ConfigureAwait(false); - - if (!isExist) - return 0; - - await cacheSetpoints.RemoveAsync(Predicate, token) - .ConfigureAwait(false); - - return 1; + var affected = await setpointsRepository.DeleteAsync(id, token); + return affected; } - public SetpointsRequest Convert(SetpointsRequestDto src) - { - var entity = src.Adapt(); - return entity; - } - - public SetpointsRequestDto Convert(SetpointsRequest src) - { - var dto = src.Adapt(); - return dto; - } - - public IEnumerable GetSetpointsNames(int idWell) - => SetpointInfos.Values; + public IEnumerable GetSetpointsNames() + => SetpointInfos.Values; } } diff --git a/AsbCloudInfrastructure/Services/SAUB/TelemetryUserService.cs b/AsbCloudInfrastructure/Services/SAUB/TelemetryUserService.cs index 15ef2bce..2406a2b0 100644 --- a/AsbCloudInfrastructure/Services/SAUB/TelemetryUserService.cs +++ b/AsbCloudInfrastructure/Services/SAUB/TelemetryUserService.cs @@ -4,7 +4,6 @@ using AsbCloudApp.Services; using AsbCloudDb; using AsbCloudDb.Model; using AsbCloudInfrastructure.EfCache; -using AsbCloudInfrastructure.Services.Cache; using System.Collections.Generic; using System.Linq; using System.Threading; diff --git a/AsbCloudInfrastructure/Services/ScheduleService.cs b/AsbCloudInfrastructure/Services/ScheduleService.cs index 0a09331f..c51a5aad 100644 --- a/AsbCloudInfrastructure/Services/ScheduleService.cs +++ b/AsbCloudInfrastructure/Services/ScheduleService.cs @@ -4,7 +4,6 @@ using AsbCloudDb.Model; using Mapster; using Microsoft.EntityFrameworkCore; using System; -using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; @@ -16,7 +15,7 @@ namespace AsbCloudInfrastructure.Services { private readonly IWellService wellService; - public ScheduleService(IAsbCloudDbContext context, IWellService wellService) + public ScheduleService(IAsbCloudDbContext context, IWellService wellService) : base(context, dbSet => dbSet.Include(s => s.Driller)) { this.wellService = wellService; @@ -28,7 +27,7 @@ namespace AsbCloudInfrastructure.Services var date = workTime.ToUtcDateTimeOffset(hoursOffset); var entities = await GetQuery() - .Where(s => s.IdWell==idWell + .Where(s => s.IdWell == idWell && s.DrillStart <= date && s.DrillEnd >= date) .ToListAsync(token); @@ -39,7 +38,7 @@ namespace AsbCloudInfrastructure.Services var remoteDate = date.ToRemoteDateTime(hoursOffset); var time = new TimeOnly(remoteDate.Hour, remoteDate.Minute, remoteDate.Second); - var entity = entities.FirstOrDefault(s => + var entity = entities.FirstOrDefault(s => (s.ShiftStart > s.ShiftEnd) ^ (time >= s.ShiftStart && time < s.ShiftEnd) ); diff --git a/AsbCloudInfrastructure/Services/WellOperationService/WellOperationService.cs b/AsbCloudInfrastructure/Services/WellOperationService/WellOperationService.cs index 2b4433f1..67f4e8fc 100644 --- a/AsbCloudInfrastructure/Services/WellOperationService/WellOperationService.cs +++ b/AsbCloudInfrastructure/Services/WellOperationService/WellOperationService.cs @@ -52,7 +52,7 @@ namespace AsbCloudInfrastructure.Services.WellOperationService public DateTimeOffset? FirstOperationDate(int idWell) { - if(firstOperationsCache is null) + if (firstOperationsCache is null) { var query = db.WellOperations .GroupBy(o => o.IdWell) diff --git a/AsbCloudInfrastructure/Services/WellService.cs b/AsbCloudInfrastructure/Services/WellService.cs index 6478a296..30043b10 100644 --- a/AsbCloudInfrastructure/Services/WellService.cs +++ b/AsbCloudInfrastructure/Services/WellService.cs @@ -2,8 +2,8 @@ using AsbCloudApp.Exceptions; using AsbCloudApp.Services; using AsbCloudDb.Model; -using AsbCloudInfrastructure.Services.Cache; using AsbCloudInfrastructure.EfCache; +using AsbCloudInfrastructure.Services.Cache; using Mapster; using Microsoft.EntityFrameworkCore; using System; @@ -26,7 +26,7 @@ namespace AsbCloudInfrastructure.Services public ITelemetryService TelemetryService => telemetryService; - private static IQueryable MakeQueryWell(DbSet dbSet) + private static IQueryable MakeQueryWell(DbSet dbSet) => dbSet .Include(w => w.Cluster) .ThenInclude(c => c.Deposit) @@ -63,7 +63,7 @@ namespace AsbCloudInfrastructure.Services public DateTimeOffset GetLastTelemetryDate(int idWell) { var well = Get(idWell); - + if (well?.IdTelemetry is null) return DateTimeOffset.MinValue; @@ -73,7 +73,7 @@ namespace AsbCloudInfrastructure.Services public async Task> GetWellsByCompanyAsync(int idCompany, CancellationToken token) { - var relationsCache = await GetCacheRelationCompanyWellAsync(token); + var relationsCache = await GetCacheRelationCompanyWellAsync(token); var wellsIds = relationsCache .Where(r => r.IdCompany == idCompany) @@ -81,8 +81,8 @@ namespace AsbCloudInfrastructure.Services var wellsDtos = (await GetCacheAsync(token)) .Where(kv => wellsIds.Contains(kv.Key)) - .Select(kv =>kv.Value); - + .Select(kv => kv.Value); + return wellsDtos.ToList(); } @@ -227,7 +227,7 @@ namespace AsbCloudInfrastructure.Services dto.WellType = entity.WellType?.Caption; dto.Cluster = entity.Cluster?.Caption; dto.Deposit = entity.Cluster?.Deposit?.Caption; - if(entity.IdTelemetry is not null) + if (entity.IdTelemetry is not null) dto.LastTelemetryDate = telemetryService.GetLastTelemetryDate((int)entity.IdTelemetry); dto.Companies = entity.RelationCompaniesWells .Select(r => Convert(r.Company)) @@ -315,7 +315,7 @@ namespace AsbCloudInfrastructure.Services if (well.IdCluster is null) throw new Exception($"Can't find coordinates of well {well.Caption} id: {well.Id}"); - + var cluster = well.Cluster; if (cluster.Latitude is not null & cluster.Longitude is not null) diff --git a/AsbCloudInfrastructure/Validators/TimeDtoValidator.cs b/AsbCloudInfrastructure/Validators/TimeDtoValidator.cs index e9c7ba54..e0c97233 100644 --- a/AsbCloudInfrastructure/Validators/TimeDtoValidator.cs +++ b/AsbCloudInfrastructure/Validators/TimeDtoValidator.cs @@ -7,8 +7,8 @@ namespace AsbCloudInfrastructure.Validators { public TimeDtoValidator() { - RuleFor(x=>x.Hour) - .InclusiveBetween(0,23) + RuleFor(x => x.Hour) + .InclusiveBetween(0, 23) .WithMessage("hour should be in [0; 23]"); RuleFor(x => x.Minute) diff --git a/AsbCloudWebApi.Tests/ControllersTests/AnalyticsControllerTests.cs b/AsbCloudWebApi.Tests/ControllersTests/AnalyticsControllerTests.cs index 9de88a3a..68321cdd 100644 --- a/AsbCloudWebApi.Tests/ControllersTests/AnalyticsControllerTests.cs +++ b/AsbCloudWebApi.Tests/ControllersTests/AnalyticsControllerTests.cs @@ -1,17 +1,4 @@ -using AsbCloudApp.Data; -using AsbCloudApp.Services; -using AsbCloudWebApi.Controllers.SAUB; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc; -using Moq; -using System; -using System.Collections.Generic; -using System.Security.Claims; -using System.Threading; -using System.Threading.Tasks; -using Xunit; - -namespace AsbCloudWebApi.Tests.ControllersTests +namespace AsbCloudWebApi.Tests.ControllersTests { //public class AnalyticsControllerTests //{ diff --git a/AsbCloudWebApi.Tests/ControllersTests/ControllerExtentions.cs b/AsbCloudWebApi.Tests/ControllersTests/ControllerExtentions.cs index 450c145f..35b60a63 100644 --- a/AsbCloudWebApi.Tests/ControllersTests/ControllerExtentions.cs +++ b/AsbCloudWebApi.Tests/ControllersTests/ControllerExtentions.cs @@ -1,11 +1,6 @@ using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; -using System; -using System.Collections.Generic; -using System.Linq; using System.Security.Claims; -using System.Text; -using System.Threading.Tasks; namespace AsbCloudWebApi.Tests.ControllersTests { diff --git a/AsbCloudWebApi.Tests/ControllersTests/TelemetryDataSaubControllerTests.cs b/AsbCloudWebApi.Tests/ControllersTests/TelemetryDataSaubControllerTests.cs index 26a4c34b..f37ccfcf 100644 --- a/AsbCloudWebApi.Tests/ControllersTests/TelemetryDataSaubControllerTests.cs +++ b/AsbCloudWebApi.Tests/ControllersTests/TelemetryDataSaubControllerTests.cs @@ -1,17 +1,8 @@ using AsbCloudApp.Data.SAUB; using AsbCloudApp.Services; -using AsbCloudDb.Model; -using AsbCloudWebApi.Controllers; using AsbCloudWebApi.SignalR; using Microsoft.AspNetCore.SignalR; -using Microsoft.EntityFrameworkCore; using Moq; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Xunit; namespace AsbCloudWebApi.Tests.ControllersTests { diff --git a/AsbCloudWebApi.Tests/ServicesTests/ClusterServiceTest.cs b/AsbCloudWebApi.Tests/ServicesTests/ClusterServiceTest.cs index 92e77976..6ee6ec44 100644 --- a/AsbCloudWebApi.Tests/ServicesTests/ClusterServiceTest.cs +++ b/AsbCloudWebApi.Tests/ServicesTests/ClusterServiceTest.cs @@ -1,11 +1,11 @@ +using AsbCloudApp.Services; using AsbCloudDb.Model; using AsbCloudInfrastructure.Services; +using Moq; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -using Moq; using Xunit; -using AsbCloudApp.Services; namespace AsbCloudWebApi.Tests.ServicesTests; @@ -21,7 +21,7 @@ public class ClusterServiceTest new Deposit { Id = 3, Caption = "Test deposit 3" }, new Deposit { Id = 4, Caption = "Test deposit 4" } }; - + private readonly List clusters = new() { new Cluster { Id = 1, Caption = "Test cluster 1", IdDeposit = 1, Timezone = new SimpleTimezone()}, @@ -29,7 +29,7 @@ public class ClusterServiceTest new Cluster { Id = 3, Caption = "Test cluster 3", IdDeposit = 2, Timezone = new SimpleTimezone() }, new Cluster { Id = 4, Caption = "Test cluster 4", IdDeposit = 2, Timezone = new SimpleTimezone() } }; - + private readonly List wells = new() { new Well { Id = 1, Caption = "Test well 1", IdCluster = 1 }, @@ -37,25 +37,25 @@ public class ClusterServiceTest new Well { Id = 3, Caption = "Test well 3", IdCluster = 1 }, new Well { Id = 4, Caption = "Test well 4", IdCluster = 2 } }; - + private readonly List companiesTypes = new() { new CompanyType { Id = 1, Caption = "test company type"} }; - + private readonly List companies = new() { new Company { Id = 1, Caption = "Test company 1", IdCompanyType = 1}, new Company { Id = 2, Caption = "Test company 2", IdCompanyType = 1} }; - + private readonly List relations = new() { new RelationCompanyWell { IdCompany = 1, IdWell = 1 }, new RelationCompanyWell { IdCompany = 1, IdWell = 2 }, new RelationCompanyWell { IdCompany = 2, IdWell = 2 } }; - + private readonly List wellSectionTypes = new() { new WellSectionType { Id = 1, Caption = "Test well section type 1" } @@ -66,7 +66,7 @@ public class ClusterServiceTest new DrillParams {Id = 1, IdWell = 1, IdWellSectionType = 1}, new DrillParams {Id = 2, IdWell = 2, IdWellSectionType = 1} }; - + public ClusterServiceTest() { context = TestHelpter.MakeTestContext(); @@ -79,7 +79,7 @@ public class ClusterServiceTest context.RelationCompaniesWells.RemoveRange(context.RelationCompaniesWells); context.WellSectionTypes.RemoveRange(context.WellSectionTypes); context.DrillParams.RemoveRange(context.DrillParams); - if(context.ChangeTracker.HasChanges()) + if (context.ChangeTracker.HasChanges()) context.SaveChanges(); context.Deposits.AddRange(deposits); context.Clusters.AddRange(clusters); @@ -91,7 +91,7 @@ public class ClusterServiceTest context.DrillParams.AddRange(drillParams); context.SaveChanges(); } - + ~ClusterServiceTest() { context.Deposits.RemoveRange(context.Deposits); @@ -105,16 +105,16 @@ public class ClusterServiceTest [Fact] public async Task GetDepositsAsync_returns_one_deposit() - { + { var service = new ClusterService(context, wellService.Object); var dtos = await service.GetDepositsAsync(1); Assert.Single(dtos); } - + [Fact] public async Task GetDepositsAsync_returns_one_deposit_with_two_clusters() - { + { var service = new ClusterService(context, wellService.Object); var dtos = await service.GetDepositsAsync(1); @@ -122,57 +122,57 @@ public class ClusterServiceTest } [Fact] public async Task GetDrillParamsAsync_returns_depositDtos() - { + { var service = new ClusterService(context, wellService.Object); var dtos = await service.GetDepositsDrillParamsAsync(1); Assert.True(dtos.Any()); } - + [Fact] public async Task GetDrillParamsAsync_returns_one_deposit() - { + { var service = new ClusterService(context, wellService.Object); var dtos = await service.GetDepositsDrillParamsAsync(1); Assert.Single(dtos); } - + [Fact] public async Task GetDrillParamsAsync_returns_one_deposit_with_two_clusters() - { + { var service = new ClusterService(context, wellService.Object); var dtos = await service.GetDepositsDrillParamsAsync(1); Assert.Equal(2, dtos.FirstOrDefault()?.Clusters.Count()); } - + [Fact] public async Task GetClustersAsync_returns_two_dtos() - { + { var service = new ClusterService(context, wellService.Object); var dtos = await service.GetClustersAsync(1); Assert.Equal(2, dtos.Count()); } - + [Fact] public async Task GetClustersAsync_with_deposit_returns_two_clusters() - { + { var service = new ClusterService(context, wellService.Object); - var dtos = await service.GetClustersAsync(1,1); + var dtos = await service.GetClustersAsync(1, 1); Assert.Equal(2, dtos.Count()); } - + [Fact] public async Task GetWellsAsync_returns_one_well_by_cluster_and_company() - { + { var service = new ClusterService(context, wellService.Object); - var dtos = await service.GetWellsAsync(1,1); + var dtos = await service.GetWellsAsync(1, 1); Assert.Single(dtos); } - + } \ No newline at end of file diff --git a/AsbCloudWebApi.Tests/ServicesTests/CrudServiceTestAbstract.cs b/AsbCloudWebApi.Tests/ServicesTests/CrudServiceTestAbstract.cs index 043af57f..73b9269d 100644 --- a/AsbCloudWebApi.Tests/ServicesTests/CrudServiceTestAbstract.cs +++ b/AsbCloudWebApi.Tests/ServicesTests/CrudServiceTestAbstract.cs @@ -1,5 +1,4 @@ using AsbCloudApp.Services; -using System; using System.Linq; using System.Threading; using System.Threading.Tasks; @@ -8,7 +7,7 @@ using Xunit; namespace AsbCloudWebApi.Tests.ServicesTests { public abstract class CrudServiceTestAbstract - where TDto: AsbCloudApp.Data.IId + where TDto : AsbCloudApp.Data.IId { private readonly ICrudService service; diff --git a/AsbCloudWebApi.Tests/ServicesTests/DepositCrudCacheServiceTest.cs b/AsbCloudWebApi.Tests/ServicesTests/DepositCrudCacheServiceTest.cs index d7769352..d2247610 100644 --- a/AsbCloudWebApi.Tests/ServicesTests/DepositCrudCacheServiceTest.cs +++ b/AsbCloudWebApi.Tests/ServicesTests/DepositCrudCacheServiceTest.cs @@ -14,7 +14,7 @@ namespace AsbCloudWebApi.Tests.ServicesTests Caption = "test deposit", Latitude = 1, Longitude = 2, - Timezone = new SimpleTimezoneDto { Hours = 5, TimezoneId = "test Never-land"} + Timezone = new SimpleTimezoneDto { Hours = 5, TimezoneId = "test Never-land" } }; return item; } diff --git a/AsbCloudWebApi.Tests/ServicesTests/DetectedOperationServiceTest.cs b/AsbCloudWebApi.Tests/ServicesTests/DetectedOperationServiceTest.cs index 7095decd..f7187037 100644 --- a/AsbCloudWebApi.Tests/ServicesTests/DetectedOperationServiceTest.cs +++ b/AsbCloudWebApi.Tests/ServicesTests/DetectedOperationServiceTest.cs @@ -1,5 +1,4 @@ using AsbCloudApp.Data; -using AsbCloudApp.Data.SAUB; using AsbCloudApp.Services; using AsbCloudDb.Model; using AsbCloudInfrastructure.Services; @@ -7,9 +6,6 @@ using AsbCloudInfrastructure.Services.Cache; using AsbCloudInfrastructure.Services.DetectOperations; using Moq; using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; using System.Threading; using System.Threading.Tasks; using Xunit; @@ -28,7 +24,7 @@ namespace AsbCloudWebApi.Tests.ServicesTests { Id = 1, Caption = "Test well 1", - IdTelemetry=1, + IdTelemetry = 1, IdCluster = 1, Timezone = new SimpleTimezone { Hours = 5 } }; @@ -51,12 +47,12 @@ namespace AsbCloudWebApi.Tests.ServicesTests }; private Telemetry telemetry = new Telemetry { - Id=1, - RemoteUid = Guid.NewGuid().ToString() + Id = 1, + RemoteUid = Guid.NewGuid().ToString() }; - #endregion + #endregion - public DetectedOperationServiceTest() + public DetectedOperationServiceTest() { context = TestHelpter.MakeTestContext(); context.SaveChanges(); diff --git a/AsbCloudWebApi.Tests/ServicesTests/DrillerServiceTest.cs b/AsbCloudWebApi.Tests/ServicesTests/DrillerServiceTest.cs index 61cb6d49..a79e577f 100644 --- a/AsbCloudWebApi.Tests/ServicesTests/DrillerServiceTest.cs +++ b/AsbCloudWebApi.Tests/ServicesTests/DrillerServiceTest.cs @@ -1,11 +1,7 @@ using AsbCloudApp.Data; -using AsbCloudApp.Services; using AsbCloudDb.Model; using AsbCloudInfrastructure.Services; using AsbCloudInfrastructure.Services.Cache; -using Moq; -using System; -using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; @@ -61,7 +57,7 @@ namespace AsbCloudWebApi.Tests.ServicesTests [Fact] public async Task InsertAsync_returns_id() - { + { var id = await service.InsertAsync(drillerObj, CancellationToken.None); Assert.NotEqual(0, id); } diff --git a/AsbCloudWebApi.Tests/ServicesTests/DrillingProgramServiceTest.cs b/AsbCloudWebApi.Tests/ServicesTests/DrillingProgramServiceTest.cs index 29eec8c9..5499b9cc 100644 --- a/AsbCloudWebApi.Tests/ServicesTests/DrillingProgramServiceTest.cs +++ b/AsbCloudWebApi.Tests/ServicesTests/DrillingProgramServiceTest.cs @@ -1,24 +1,23 @@ -using AsbCloudDb.Model; -using AsbCloudInfrastructure.Services; +using AsbCloudApp.Data; +using AsbCloudApp.Services; +using AsbCloudDb.Model; +using AsbCloudInfrastructure.Services.DrillingProgram; +using Mapster; +using Microsoft.Extensions.Configuration; +using Moq; +using System; using System.Collections.Generic; using System.Linq; -using System.Threading.Tasks; -using Moq; -using Xunit; -using AsbCloudApp.Services; -using AsbCloudInfrastructure.Services.DrillingProgram; -using Microsoft.Extensions.Configuration; using System.Threading; -using AsbCloudApp.Data; -using Mapster; -using System; +using System.Threading.Tasks; +using Xunit; namespace AsbCloudWebApi.Tests.ServicesTests { public class DrillingProgramServiceTest { private const int idWell = 3001; - private static readonly SimpleTimezone baseTimezone = new () { Hours = 5d }; + private static readonly SimpleTimezone baseTimezone = new() { Hours = 5d }; private readonly AsbCloudDbContext db; private static readonly List wells = new() @@ -27,15 +26,15 @@ namespace AsbCloudWebApi.Tests.ServicesTests new Well { Id = 3002, Caption = "well 2", Timezone = baseTimezone }, }; - private static readonly List companies = new() { + private static readonly List companies = new() { new Company { Id = 3001, Caption = "company name", IdCompanyType = 2, }, new Company { Id = 3002, Caption = "company name", IdCompanyType = 2, }, new Company { Id = 3003, Caption = "company name", IdCompanyType = 2, }, }; - private static readonly User publisher1 = new () { Id = 3001, IdCompany = 3001, Login = "user 1", Email = "aa@aa.aa", IdState = 2 }; - private static readonly User approver1 = new () { Id = 3002, IdCompany = 3001, Login = "user 2", Email = "aa@aa.aa", IdState = 2 }; - private static readonly User approver2 = new () { Id = 3003, IdCompany = 3002, Login = "user 3", Email = "aa@aa.aa", IdState = 2 }; + private static readonly User publisher1 = new() { Id = 3001, IdCompany = 3001, Login = "user 1", Email = "aa@aa.aa", IdState = 2 }; + private static readonly User approver1 = new() { Id = 3002, IdCompany = 3001, Login = "user 2", Email = "aa@aa.aa", IdState = 2 }; + private static readonly User approver2 = new() { Id = 3003, IdCompany = 3002, Login = "user 3", Email = "aa@aa.aa", IdState = 2 }; private static readonly List users = new() { @@ -46,7 +45,7 @@ namespace AsbCloudWebApi.Tests.ServicesTests new User { Id = 3005, IdCompany = 3003, Login = "wrong 2", Email = "aa@aa.aa", IdState = 2 }, }; - private static readonly FileInfo file1001 = new () + private static readonly FileInfo file1001 = new() { Id = 3001, IdWell = idWell, @@ -58,7 +57,7 @@ namespace AsbCloudWebApi.Tests.ServicesTests UploadDate = System.DateTimeOffset.UtcNow, }; - private static readonly FileInfo file1002 = new () + private static readonly FileInfo file1002 = new() { Id = 3002, IdWell = idWell, @@ -117,7 +116,7 @@ namespace AsbCloudWebApi.Tests.ServicesTests emailService.Object); var users = await service.GetAvailableUsers(idWell, CancellationToken.None); - + Assert.Equal(3, users.Count()); } @@ -141,7 +140,7 @@ namespace AsbCloudWebApi.Tests.ServicesTests [Fact] public async Task RemovePartsAsync_returns_1() { - db.DrillingProgramParts.Add(new DrillingProgramPart { IdFileCategory = 1005, IdWell = idWell}); + db.DrillingProgramParts.Add(new DrillingProgramPart { IdFileCategory = 1005, IdWell = idWell }); db.SaveChanges(); var service = new DrillingProgramService( db, @@ -185,12 +184,13 @@ namespace AsbCloudWebApi.Tests.ServicesTests { const int idUserRole = 1; const int idFileCategory = 1001; - var entry = db.DrillingProgramParts.Add(new DrillingProgramPart { + var entry = db.DrillingProgramParts.Add(new DrillingProgramPart + { IdFileCategory = idFileCategory, - IdWell = idWell + IdWell = idWell }); db.SaveChanges(); - db.RelationDrillingProgramPartUsers.Add(new RelationUserDrillingProgramPart + db.RelationDrillingProgramPartUsers.Add(new RelationUserDrillingProgramPart { IdUser = publisher1.Id, IdDrillingProgramPart = entry.Entity.Id, @@ -210,7 +210,7 @@ namespace AsbCloudWebApi.Tests.ServicesTests emailService.Object); var result = await service.RemoveUserAsync(idWell, idFileCategory, publisher1.Id, idUserRole, CancellationToken.None); - + Assert.Equal(1, result); } @@ -310,7 +310,7 @@ namespace AsbCloudWebApi.Tests.ServicesTests IdMarkType = 0, DateCreated = DateTime.Now, }; - + int idMark = 0; var affected = await service.MarkAsDeletedFileMarkAsync(idMark, CancellationToken.None); @@ -372,7 +372,7 @@ namespace AsbCloudWebApi.Tests.ServicesTests new FileMark { IdFile = file1002.Id, IdUser = approver1.Id, IdMarkType = 1, DateCreated = DateTimeOffset.UtcNow }, new FileMark { IdFile = file1002.Id, IdUser = approver2.Id, IdMarkType = 1, DateCreated = DateTimeOffset.UtcNow } ); - db.Files.AddRange(new FileInfo { IdCategory = 1000, IdWell = idWell, Name = "DrillingProgram.xalsx", Size = 1024*1024, UploadDate = DateTimeOffset.UtcNow }); + db.Files.AddRange(new FileInfo { IdCategory = 1000, IdWell = idWell, Name = "DrillingProgram.xalsx", Size = 1024 * 1024, UploadDate = DateTimeOffset.UtcNow }); await db.SaveChangesAsync(); diff --git a/AsbCloudWebApi.Tests/ServicesTests/EventServiceTest.cs b/AsbCloudWebApi.Tests/ServicesTests/EventServiceTest.cs index 6c188b0d..1a6ac59a 100644 --- a/AsbCloudWebApi.Tests/ServicesTests/EventServiceTest.cs +++ b/AsbCloudWebApi.Tests/ServicesTests/EventServiceTest.cs @@ -1,21 +1,20 @@ +using AsbCloudApp.Data.SAUB; +using AsbCloudApp.Services; using AsbCloudDb.Model; using AsbCloudInfrastructure.Services.Cache; -using AsbCloudInfrastructure.Services; +using AsbCloudInfrastructure.Services.SAUB; +using Moq; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -using AsbCloudApp.Services; -using Moq; using Xunit; -using AsbCloudApp.Data.SAUB; -using AsbCloudInfrastructure.Services.SAUB; namespace AsbCloudWebApi.Tests.ServicesTests; public class EventServiceTest { private readonly AsbCloudDbContext context; - private readonly CacheDb cacheDb; + private readonly CacheDb cacheDb; private readonly EventService service; public EventServiceTest() @@ -38,7 +37,7 @@ public class EventServiceTest }; await service.UpsertAsync("uid", dtos); - + Assert.Equal(2, context.TelemetryEvents.Count()); } } \ No newline at end of file diff --git a/AsbCloudWebApi.Tests/ServicesTests/ScheduleServiceTest.cs b/AsbCloudWebApi.Tests/ServicesTests/ScheduleServiceTest.cs index a263ee35..5b9f64ba 100644 --- a/AsbCloudWebApi.Tests/ServicesTests/ScheduleServiceTest.cs +++ b/AsbCloudWebApi.Tests/ServicesTests/ScheduleServiceTest.cs @@ -40,10 +40,11 @@ namespace AsbCloudWebApi.Tests.ServicesTests DrillEnd = dto?.DrillEnd ?? DateTime.Parse("2022-05-16T18:00:00.286Z") }; } - - private Well well = new Well { - Id=1, - Caption = "Test well 1", + + private Well well = new Well + { + Id = 1, + Caption = "Test well 1", IdCluster = 1, Timezone = new SimpleTimezone { Hours = 5 } }; @@ -55,7 +56,7 @@ namespace AsbCloudWebApi.Tests.ServicesTests Surname = "Тестович" }; - public ScheduleServiceTest() + public ScheduleServiceTest() { context = TestHelpter.MakeTestContext(); context.SaveChanges(); @@ -117,7 +118,7 @@ namespace AsbCloudWebApi.Tests.ServicesTests dto.ShiftStart = new TimeOnly(8, 00); dto.ShiftEnd = new TimeOnly(20, 00); var id = await scheduleService.InsertAsync(dto, CancellationToken.None); - var drillerWorkTime = new DateTime( + var drillerWorkTime = new DateTime( dto.DrillStart.Year, dto.DrillStart.Month, dto.DrillStart.Day, diff --git a/AsbCloudWebApi.Tests/ServicesTests/TelemetryDataSaubServiceTest.cs b/AsbCloudWebApi.Tests/ServicesTests/TelemetryDataSaubServiceTest.cs index 8aa5c66c..5e61701d 100644 --- a/AsbCloudWebApi.Tests/ServicesTests/TelemetryDataSaubServiceTest.cs +++ b/AsbCloudWebApi.Tests/ServicesTests/TelemetryDataSaubServiceTest.cs @@ -24,7 +24,7 @@ namespace AsbCloudWebApi.Tests.ServicesTests private readonly TelemetryService telemetryService; private readonly DateTime drillingStartDate; - private readonly string uuid; + private readonly string uuid; public TelemetryDataSaubServiceTest() { timezone = new() { Hours = 7 }; @@ -65,22 +65,22 @@ namespace AsbCloudWebApi.Tests.ServicesTests { // Arrange var telemetryDataSaubService = new TelemetryDataSaubService(context, telemetryService, cacheDb); - + var now = DateTimeOffset.UtcNow.ToOffset(TimeSpan.FromHours(timezone.Hours)).DateTime; var tuser = "Завулон"; var newData = new List - { + { new TelemetryDataSaubDto{ DateTime = now, AxialLoad = 1, MseState = 1, User = tuser, - } + } }; // act var affected = await telemetryDataSaubService.UpdateDataAsync(uuid, newData, CancellationToken.None); - + // assert Assert.Equal(1, affected); } diff --git a/AsbCloudWebApi.Tests/ServicesTests/UserRoleServiceTest.cs b/AsbCloudWebApi.Tests/ServicesTests/UserRoleServiceTest.cs index 00bf86c9..7fa272cc 100644 --- a/AsbCloudWebApi.Tests/ServicesTests/UserRoleServiceTest.cs +++ b/AsbCloudWebApi.Tests/ServicesTests/UserRoleServiceTest.cs @@ -2,7 +2,6 @@ using AsbCloudDb.Model; using AsbCloudInfrastructure.Services; using AsbCloudInfrastructure.Services.Cache; -using Microsoft.EntityFrameworkCore; using System.Collections.Generic; using System.Linq; using System.Threading; @@ -62,7 +61,8 @@ namespace AsbCloudWebApi.Tests.ServicesTests context.SaveChanges(); } - ~UserRoleServiceTest(){ + ~UserRoleServiceTest() + { context.UserRoles.RemoveRange(roles); context.Permissions.RemoveRange(permissions); context.RelationUserRoleUserRoles.RemoveRange(relationRoleRole); @@ -104,7 +104,7 @@ namespace AsbCloudWebApi.Tests.ServicesTests Caption = "new role", IdType = 0, }; - var id = await service.InsertAsync(newRole, CancellationToken.None ); + var id = await service.InsertAsync(newRole, CancellationToken.None); Assert.NotEqual(0, id); } @@ -116,9 +116,9 @@ namespace AsbCloudWebApi.Tests.ServicesTests { Caption = "new role", IdType = 0, - Permissions = new[] { new PermissionDto{ Id = 2_000_001 } }, + Permissions = new[] { new PermissionDto { Id = 2_000_001 } }, }; - var id = await service.InsertAsync(newRole, CancellationToken.None); + var id = await service.InsertAsync(newRole, CancellationToken.None); var entity = await service.GetAsync(id); Assert.Equal(newRole.Permissions.Count(), entity.Permissions.Count()); } @@ -131,7 +131,7 @@ namespace AsbCloudWebApi.Tests.ServicesTests { Caption = "new role", IdType = 0, - Roles = new [] { new UserRoleDto { Id = 1_000_001 } } + Roles = new[] { new UserRoleDto { Id = 1_000_001 } } }; var id = await service.InsertAsync(newRole, CancellationToken.None); var entity = await service.GetAsync(id); @@ -143,10 +143,10 @@ namespace AsbCloudWebApi.Tests.ServicesTests { var service = new UserRoleService(context, cacheDb); const int updateId = 1_000_002; - var modRole = new UserRoleDto - { - Id = updateId, - Caption = "role 2 level 1" + var modRole = new UserRoleDto + { + Id = updateId, + Caption = "role 2 level 1" }; var id = await service.UpdateAsync(modRole, CancellationToken.None); Assert.Equal(updateId, id); diff --git a/AsbCloudWebApi.Tests/ServicesTests/UserServiceTest.cs b/AsbCloudWebApi.Tests/ServicesTests/UserServiceTest.cs index f662823e..1e3d1b3f 100644 --- a/AsbCloudWebApi.Tests/ServicesTests/UserServiceTest.cs +++ b/AsbCloudWebApi.Tests/ServicesTests/UserServiceTest.cs @@ -36,7 +36,7 @@ namespace AsbCloudWebApi.Tests.ServicesTests [Fact] public async Task InsertAsync_returns_id() - { + { var service = new UserService(context, cacheDb, roleService.Object); var dto = new UserExtendedDto { diff --git a/AsbCloudWebApi/Controllers/AdminClusterController.cs b/AsbCloudWebApi/Controllers/AdminClusterController.cs index 755f5c9b..a2a69cb3 100644 --- a/AsbCloudWebApi/Controllers/AdminClusterController.cs +++ b/AsbCloudWebApi/Controllers/AdminClusterController.cs @@ -12,6 +12,6 @@ namespace AsbCloudWebApi.Controllers { public AdminClusterController(ICrudService service) : base(service) - {} + { } } } diff --git a/AsbCloudWebApi/Controllers/AdminUserRoleController.cs b/AsbCloudWebApi/Controllers/AdminUserRoleController.cs index 39ea60ef..b9a7b8cd 100644 --- a/AsbCloudWebApi/Controllers/AdminUserRoleController.cs +++ b/AsbCloudWebApi/Controllers/AdminUserRoleController.cs @@ -19,7 +19,7 @@ namespace AsbCloudWebApi.Controllers return Task.FromResult(role?.IdType == 1); }; - UpdateForbidAsync = async ( dto, token) => + UpdateForbidAsync = async (dto, token) => { var role = await service.GetAsync(dto.Id, token); return role?.IdType == 1; diff --git a/AsbCloudWebApi/Controllers/AdminWellController.cs b/AsbCloudWebApi/Controllers/AdminWellController.cs index 0dd4457f..82161e1d 100644 --- a/AsbCloudWebApi/Controllers/AdminWellController.cs +++ b/AsbCloudWebApi/Controllers/AdminWellController.cs @@ -14,7 +14,7 @@ namespace AsbCloudWebApi.Controllers { public AdminWellController(IWellService service) : base(service) - {} + { } [HttpPost("EnshureTimezonesIsSet")] [Permission] diff --git a/AsbCloudWebApi/Controllers/CrudController.cs b/AsbCloudWebApi/Controllers/CrudController.cs index fd6c06de..06c1e811 100644 --- a/AsbCloudWebApi/Controllers/CrudController.cs +++ b/AsbCloudWebApi/Controllers/CrudController.cs @@ -92,9 +92,9 @@ namespace AsbCloudWebApi.Controllers if (!values.Any()) return BadRequest("there is no values to add"); - if (InsertForbidAsync is not null) - foreach (var value in values) - if(await InsertForbidAsync(value, token)) + if (InsertForbidAsync is not null) + foreach (var value in values) + if (await InsertForbidAsync(value, token)) return Forbid(); var result = await service.InsertRangeAsync(values, token).ConfigureAwait(false); diff --git a/AsbCloudWebApi/Controllers/CrudWellRelatedController.cs b/AsbCloudWebApi/Controllers/CrudWellRelatedController.cs index da6cb100..dcfc5942 100644 --- a/AsbCloudWebApi/Controllers/CrudWellRelatedController.cs +++ b/AsbCloudWebApi/Controllers/CrudWellRelatedController.cs @@ -22,7 +22,7 @@ namespace AsbCloudWebApi.Controllers where T : IId, IWellRelated where TService : ICrudWellRelatedService { - private readonly IWellService wellService; + protected readonly IWellService wellService; protected CrudWellRelatedController(IWellService wellService, TService service) : base(service) @@ -74,7 +74,7 @@ namespace AsbCloudWebApi.Controllers { var actionResult = await base.GetAsync(id, token); var result = actionResult.Value; - if(!await UserHasAccesToWellAsync(result.IdWell, token)) + if (!await UserHasAccesToWellAsync(result.IdWell, token)) return Forbid(); return Ok(result); } @@ -113,7 +113,7 @@ namespace AsbCloudWebApi.Controllers public override async Task> DeleteAsync(int id, CancellationToken token) { var item = await service.GetAsync(id, token); - if(item is null) + if (item is null) return NoContent(); if (!await UserHasAccesToWellAsync(item.IdWell, token)) return Forbid(); @@ -130,6 +130,4 @@ namespace AsbCloudWebApi.Controllers return false; } } - - } diff --git a/AsbCloudWebApi/Controllers/DailyReportController.cs b/AsbCloudWebApi/Controllers/DailyReportController.cs index 8dcaaa6b..7aec2106 100644 --- a/AsbCloudWebApi/Controllers/DailyReportController.cs +++ b/AsbCloudWebApi/Controllers/DailyReportController.cs @@ -1,4 +1,5 @@ using AsbCloudApp.Data; +using AsbCloudApp.Services; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using System; @@ -6,7 +7,6 @@ using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Threading; using System.Threading.Tasks; -using AsbCloudApp.Services; namespace AsbCloudWebApi.Controllers { @@ -105,7 +105,7 @@ namespace AsbCloudWebApi.Controllers var stream = await dailyReportService.MakeReportAsync(idWell, date, token); if (stream != null) { - + var fileName = $"Суточный рапорт по скважине {well.Caption} куст {well.Cluster}.xlsx"; return File(stream, "application/octet-stream", fileName); } diff --git a/AsbCloudWebApi/Controllers/DrillFlowChartController.cs b/AsbCloudWebApi/Controllers/DrillFlowChartController.cs index ec0aaefd..6d0fc44d 100644 --- a/AsbCloudWebApi/Controllers/DrillFlowChartController.cs +++ b/AsbCloudWebApi/Controllers/DrillFlowChartController.cs @@ -22,7 +22,7 @@ namespace AsbCloudWebApi.Controllers public DrillFlowChartController(IWellService wellService, IDrillFlowChartService service, ITelemetryService telemetryService) - :base(wellService, service) + : base(wellService, service) { this.telemetryService = telemetryService; this.wellService = wellService; diff --git a/AsbCloudWebApi/Controllers/DrillerController.cs b/AsbCloudWebApi/Controllers/DrillerController.cs index 4be2d876..ba397b15 100644 --- a/AsbCloudWebApi/Controllers/DrillerController.cs +++ b/AsbCloudWebApi/Controllers/DrillerController.cs @@ -11,7 +11,7 @@ namespace AsbCloudWebApi.Controllers public class DrillerController : CrudController { public DrillerController(IDrillerService drillerService) - :base(drillerService) - {} + : base(drillerService) + { } } } diff --git a/AsbCloudWebApi/Controllers/DrillingProgramController.cs b/AsbCloudWebApi/Controllers/DrillingProgramController.cs index 4fc2d13f..fd0fc41c 100644 --- a/AsbCloudWebApi/Controllers/DrillingProgramController.cs +++ b/AsbCloudWebApi/Controllers/DrillingProgramController.cs @@ -125,7 +125,7 @@ namespace AsbCloudWebApi.Controllers if (!fileName.EndsWith(".xlsx")) return BadRequest(ArgumentInvalidException.MakeValidationError("file", "Файл должен быть xlsx")); - + var fileStream = files[0].OpenReadStream(); var result = await drillingProgramService.AddFile(idWell, idFileCategory, (int)idUser, fileName, fileStream, token); diff --git a/AsbCloudWebApi/Controllers/ProtobufController.cs b/AsbCloudWebApi/Controllers/ProtobufController.cs index 0ec0f2d7..f6620e6e 100644 --- a/AsbCloudWebApi/Controllers/ProtobufController.cs +++ b/AsbCloudWebApi/Controllers/ProtobufController.cs @@ -1,12 +1,7 @@ -using AsbCloudApp.Data; -using AsbCloudApp.Services; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc; using ProtoBuf.Meta; using System.Collections.Generic; using System.Linq; -using System.Threading; -using System.Threading.Tasks; namespace AsbCloudWebApi.Controllers { diff --git a/AsbCloudWebApi/Controllers/SAUB/DetectedOperationController.cs b/AsbCloudWebApi/Controllers/SAUB/DetectedOperationController.cs index ac551003..828208bf 100644 --- a/AsbCloudWebApi/Controllers/SAUB/DetectedOperationController.cs +++ b/AsbCloudWebApi/Controllers/SAUB/DetectedOperationController.cs @@ -1,10 +1,10 @@ using AsbCloudApp.Data; +using AsbCloudApp.Requests; using AsbCloudApp.Services; using Microsoft.AspNetCore.Mvc; using System.Collections.Generic; -using System.Threading.Tasks; using System.Threading; -using AsbCloudApp.Requests; +using System.Threading.Tasks; namespace AsbCloudWebApi.Controllers.SAUB { diff --git a/AsbCloudWebApi/Controllers/SAUB/SetpointsController.cs b/AsbCloudWebApi/Controllers/SAUB/SetpointsController.cs index 2f0c2706..51ce7e92 100644 --- a/AsbCloudWebApi/Controllers/SAUB/SetpointsController.cs +++ b/AsbCloudWebApi/Controllers/SAUB/SetpointsController.cs @@ -34,7 +34,7 @@ namespace AsbCloudWebApi.Controllers.SAUB [AllowAnonymous] public IActionResult GetSetpointsNamesByIdWellAsync([FromRoute] int idWell) { - var result = setpointsService.GetSetpointsNames(idWell); + var result = setpointsService.GetSetpointsNames(); return Ok(result); } @@ -115,7 +115,7 @@ namespace AsbCloudWebApi.Controllers.SAUB [AllowAnonymous] public async Task UpdateByTelemetryUidAsync([FromRoute] string uid, int id, SetpointsRequestDto setpointsRequestDto, CancellationToken token = default) { - var result = await setpointsService.UpdateStateAsync(uid, id, setpointsRequestDto, token) + var result = await setpointsService.UpdateStateAsync(id, setpointsRequestDto, token) .ConfigureAwait(false); return Ok(result); @@ -156,7 +156,7 @@ namespace AsbCloudWebApi.Controllers.SAUB if (idCompany is null || idUser is null) return Forbid(); - var result = await setpointsService.TryDelete(idWell, id, token) + var result = await setpointsService.TryDelete(id, token) .ConfigureAwait(false); return Ok(result); diff --git a/AsbCloudWebApi/Controllers/ScheduleController.cs b/AsbCloudWebApi/Controllers/ScheduleController.cs index 38669886..7c47346f 100644 --- a/AsbCloudWebApi/Controllers/ScheduleController.cs +++ b/AsbCloudWebApi/Controllers/ScheduleController.cs @@ -3,7 +3,6 @@ using AsbCloudApp.Services; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using System; -using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; @@ -12,37 +11,16 @@ namespace AsbCloudWebApi.Controllers [Route("api/schedule")] [ApiController] [Authorize] - public class ScheduleController : CrudController + public class ScheduleController : CrudWellRelatedController { private readonly IScheduleService scheduleService; - private readonly IWellService wellService; public ScheduleController(IScheduleService scheduleService, IWellService wellService) - :base(scheduleService) + : base(wellService, scheduleService) { this.scheduleService = service; - this.wellService = wellService; } - /// - /// список расписаний бурильщиков по скважине - /// - /// - /// - /// - [HttpGet("byWellId/{idWell}")] - [ProducesResponseType(typeof(IEnumerable), (int)System.Net.HttpStatusCode.OK)] - public async Task GetByIdWellAsync(int idWell, CancellationToken token) - { - var idCompany = User.GetCompanyId(); - if(idCompany is null || !wellService.IsCompanyInvolvedInWell((int)idCompany, idWell)) - return Forbid(); - - var result = await scheduleService.GetByIdWellAsync(idWell, token); - return Ok(result); - } - - /// /// Получить бурильщика работавшего на скважине в определенное время. /// @@ -53,11 +31,10 @@ namespace AsbCloudWebApi.Controllers [HttpGet("driller")] public async Task> GetDrillerAsync(int idWell, DateTime workTime, CancellationToken token) { - var idCompany = User.GetCompanyId(); - if (idCompany is null || !wellService.IsCompanyInvolvedInWell((int)idCompany, idWell)) + if (!await UserHasAccesToWellAsync(idWell, token)) return Forbid(); - var result = await scheduleService.GetDrillerAsync(idWell,workTime, token); + var result = await scheduleService.GetDrillerAsync(idWell, workTime, token); return Ok(result); } diff --git a/AsbCloudWebApi/Controllers/WITS/WitsControllerAbstract.cs b/AsbCloudWebApi/Controllers/WITS/WitsControllerAbstract.cs index cf0ce7e3..2077037f 100644 --- a/AsbCloudWebApi/Controllers/WITS/WitsControllerAbstract.cs +++ b/AsbCloudWebApi/Controllers/WITS/WitsControllerAbstract.cs @@ -1,5 +1,4 @@ using AsbCloudApp.Data; -using AsbCloudApp.Data.WITS; using AsbCloudApp.Services; using AsbCloudWebApi.SignalR; using Microsoft.AspNetCore.Authorization; diff --git a/AsbCloudWebApi/Controllers/WITS/WitsInfoController.cs b/AsbCloudWebApi/Controllers/WITS/WitsInfoController.cs index 64c6d6cc..7aee64ac 100644 --- a/AsbCloudWebApi/Controllers/WITS/WitsInfoController.cs +++ b/AsbCloudWebApi/Controllers/WITS/WitsInfoController.cs @@ -1,5 +1,4 @@ using AsbCloudInfrastructure.Services; -using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System.Collections.Generic; diff --git a/AsbCloudWebApi/Controllers/WellController.cs b/AsbCloudWebApi/Controllers/WellController.cs index 46d072ea..6869964e 100644 --- a/AsbCloudWebApi/Controllers/WellController.cs +++ b/AsbCloudWebApi/Controllers/WellController.cs @@ -3,7 +3,6 @@ using AsbCloudApp.Services; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using System.Collections.Generic; -using System.Linq; using System.Threading; using System.Threading.Tasks; diff --git a/AsbCloudWebApi/Startup.cs b/AsbCloudWebApi/Startup.cs index 767a1519..7b536723 100644 --- a/AsbCloudWebApi/Startup.cs +++ b/AsbCloudWebApi/Startup.cs @@ -22,15 +22,16 @@ namespace AsbCloudWebApi services.AddControllers() .AddJsonOptions(new System.Action(options => { - options.JsonSerializerOptions.NumberHandling = + options.JsonSerializerOptions.NumberHandling = System.Text.Json.Serialization.JsonNumberHandling.AllowNamedFloatingPointLiterals | - System.Text.Json.Serialization.JsonNumberHandling.AllowReadingFromString;})) + System.Text.Json.Serialization.JsonNumberHandling.AllowReadingFromString; + })) .AddProtoBufNet(); ProtobufModel.EnshureRegistered(); services.AddSwagger(); - + services.AddInfrastructure(Configuration); services.AddJWTAuthentication(); diff --git a/ConsoleApp1/ActionWellOperationsRefactor.cs b/ConsoleApp1/ActionWellOperationsRefactor.cs index 234d6e3a..ada07ffc 100644 --- a/ConsoleApp1/ActionWellOperationsRefactor.cs +++ b/ConsoleApp1/ActionWellOperationsRefactor.cs @@ -1,10 +1,7 @@ using AsbCloudDb.Model; using Microsoft.EntityFrameworkCore; -using System; using System.Collections.Generic; using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace ConsoleApp1 { @@ -20,7 +17,7 @@ namespace ConsoleApp1 public static void Main() { using var db = new AsbCloudDbContext(options); - + var wellsIds = db.WellOperations .Select(o => o.IdWell) .Distinct() @@ -38,10 +35,10 @@ namespace ConsoleApp1 var operationsPlan = operations.Where(o => o.IdType == 0); RefactorWellOperations(operationsPlan); - + var operationsFact = operations.Where(o => o.IdType == 1); RefactorWellOperations(operationsFact); - + db.SaveChanges(); } transaction.Commit(); @@ -49,7 +46,7 @@ namespace ConsoleApp1 catch { transaction.Rollback(); - } + } } private static void RefactorWellOperations(IEnumerable operations) diff --git a/ConsoleApp1/ControllerLoadTester.cs b/ConsoleApp1/ControllerLoadTester.cs index 3c4133f2..d72eded4 100644 --- a/ConsoleApp1/ControllerLoadTester.cs +++ b/ConsoleApp1/ControllerLoadTester.cs @@ -1,12 +1,11 @@ +using AsbCloudApp.Data.SAUB; using System; using System.Collections.Generic; using System.Net.Http; -using System.Threading; -using System.Threading.Tasks; using System.Text; using System.Text.Json; -using AsbCloudApp.Data; -using AsbCloudApp.Data.SAUB; +using System.Threading; +using System.Threading.Tasks; namespace ConsoleApp1 { @@ -113,17 +112,17 @@ namespace ConsoleApp1 Flow = MakeFloatRandom(100), FlowIdle = MakeFloatRandom(100), FlowDeltaLimitMax = MakeFloatRandom(100), - }; + }; return dto; } - private static float MakeFloatRandom( float max, float min = 0) + private static float MakeFloatRandom(float max, float min = 0) { - var val = (float)( min + random.NextDouble() * (max - min)); + var val = (float)(min + random.NextDouble() * (max - min)); return val; } - private static float MakeFloatSin( float max, float min, float angle) + private static float MakeFloatSin(float max, float min, float angle) { var val = (float)(min + Math.Sin(angle) * (max - min) / 2); return val; diff --git a/ConsoleApp1/DebugWellOperationImportService.cs b/ConsoleApp1/DebugWellOperationImportService.cs index 2e0a7a8a..e152d3d3 100644 --- a/ConsoleApp1/DebugWellOperationImportService.cs +++ b/ConsoleApp1/DebugWellOperationImportService.cs @@ -1,13 +1,6 @@ using AsbCloudDb.Model; -using AsbCloudInfrastructure.Services; -using AsbCloudInfrastructure.Services.Cache; -using AsbCloudInfrastructure.Services.WellOperationService; using Microsoft.EntityFrameworkCore; using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace ConsoleApp1 { diff --git a/ConsoleApp1/DebugWellOperationsStatService.cs b/ConsoleApp1/DebugWellOperationsStatService.cs index 4d826145..acb6452c 100644 --- a/ConsoleApp1/DebugWellOperationsStatService.cs +++ b/ConsoleApp1/DebugWellOperationsStatService.cs @@ -1,14 +1,6 @@ using AsbCloudApp.Data; -using AsbCloudDb.Model; -using AsbCloudInfrastructure.Services; -using AsbCloudInfrastructure.Services.Cache; -using AsbCloudInfrastructure.Services.WellOperationService; -using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace ConsoleApp1 { diff --git a/ConsoleApp1/GoogleDriveService.cs b/ConsoleApp1/GoogleDriveService.cs index a96f0936..b26ea93e 100644 --- a/ConsoleApp1/GoogleDriveService.cs +++ b/ConsoleApp1/GoogleDriveService.cs @@ -2,11 +2,10 @@ using Google.Apis.Auth.OAuth2; using Google.Apis.Auth.OAuth2.Flows; using Google.Apis.Auth.OAuth2.Responses; using Google.Apis.Drive.v3; +using Google.Apis.Drive.v3.Data; using Google.Apis.Services; using Google.Apis.Util.Store; -using Google.Apis.Drive.v3.Data; using System.IO; -using System.Collections.Generic; using System.Linq; // usage example at the very bottom @@ -15,7 +14,7 @@ namespace ConsoleApp1 public class GoogleDriveService { private readonly DriveService service; - + public GoogleDriveService() { // ключи для почты asbautodrilling@gmail.com. var tokenResponse = new TokenResponse @@ -34,7 +33,7 @@ namespace ConsoleApp1 ClientId = "1020584579240-f7amqg35qg7j94ta1ntgitajq27cgh49.apps.googleusercontent.com", ClientSecret = "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" }, - Scopes = new[] {DriveService.Scope.Drive}, + Scopes = new[] { DriveService.Scope.Drive }, DataStore = new FileDataStore(applicationName) }); @@ -47,7 +46,7 @@ namespace ConsoleApp1 }); this.service = newService; } - + // public IEnumerable GetAllFiles() // get file names // { // var fileList = service.Files.List(); @@ -77,10 +76,10 @@ namespace ConsoleApp1 var file = filesResult.Files.FirstOrDefault(f => f.Id == idFile); return file?.WebViewLink ?? string.Empty; } - + // У Гугла почему-то folder это и папка, и файл. - public string CreateFolder(string folderName) - { + public string CreateFolder(string folderName) + { var driveFolder = new Google.Apis.Drive.v3.Data.File(); driveFolder.Name = folderName; driveFolder.MimeType = "application/vnd.google-apps.folder"; @@ -92,11 +91,11 @@ namespace ConsoleApp1 public void CreatePublicPermissionForFile(string idFile) { - var permission = new Permission() { Type = "anyone", Role = "reader"}; + var permission = new Permission() { Type = "anyone", Role = "reader" }; var addPermissionRequest = service.Permissions.Create(permission, idFile); addPermissionRequest.Execute(); } - + public string UploadFile(Stream file, string fileName, string fileMime, string fileDescription) { var driveFile = new Google.Apis.Drive.v3.Data.File(); @@ -104,14 +103,14 @@ namespace ConsoleApp1 driveFile.Description = fileDescription; driveFile.MimeType = fileMime; //driveFile.Parents = new [] {folder}; - + var request = service.Files.Create(driveFile, file, fileMime); request.Fields = "id"; - + var response = request.Upload(); if (response.Status != Google.Apis.Upload.UploadStatus.Completed) throw response.Exception; - + return request.ResponseBody.Id; } diff --git a/ConsoleApp1/Program.cs b/ConsoleApp1/Program.cs index 44610e58..c4f6f029 100644 --- a/ConsoleApp1/Program.cs +++ b/ConsoleApp1/Program.cs @@ -1,16 +1,12 @@ -using AsbCloudApp.Data; -using AsbCloudDb.Model; -using AsbCloudInfrastructure.EfCache; -using Microsoft.EntityFrameworkCore; +using AsbCloudInfrastructure.EfCache; using System; -using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace ConsoleApp1 { - + class Program { // use ServiceFactory to make services @@ -21,7 +17,8 @@ namespace ConsoleApp1 for (int i = 0; i < 24; i++) { - var t = new Thread(_ => { + var t = new Thread(_ => + { for (int j = 0; j < 32; j++) //Task.Run(GetDataAsync).Wait(); GetData(); @@ -60,7 +57,7 @@ namespace ConsoleApp1 .Where(t => t.IdTelemetry == 135) .OrderBy(t => t.DateTime) .Take(100_000) - .FromCacheDictionaryAsync("tds", obso, r => (r.IdTelemetry, r.DateTime), r => new {r.Pressure, r.HookWeight })) + .FromCacheDictionaryAsync("tds", obso, r => (r.IdTelemetry, r.DateTime), r => new { r.Pressure, r.HookWeight })) .ToList(); sw.Stop(); Console.WriteLine($"{DateTime.Now}\tth: {Thread.CurrentThread.ManagedThreadId}\ttime {sw.ElapsedMilliseconds}\tcount {cs.Count}"); diff --git a/ConsoleApp1/SendMail.cs b/ConsoleApp1/SendMail.cs index f72b659c..06637c58 100644 --- a/ConsoleApp1/SendMail.cs +++ b/ConsoleApp1/SendMail.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net.Mail; -using System.Text; -using System.Threading.Tasks; +using System.Net.Mail; namespace ConsoleApp1 { @@ -14,7 +9,7 @@ namespace ConsoleApp1 MailAddress to = new MailAddress("ng.frolov@autodrilling.ru"); MailAddress from = new MailAddress("bot@autodrilling.ru"); MailMessage message = new MailMessage(from, to); - + message.Subject = "Using the new SMTP client."; message.Body = "

this is a test text

"; message.IsBodyHtml = true; diff --git a/ConsoleApp1/ServiceFactory.cs b/ConsoleApp1/ServiceFactory.cs index 41cbd9a8..df7f8bb4 100644 --- a/ConsoleApp1/ServiceFactory.cs +++ b/ConsoleApp1/ServiceFactory.cs @@ -64,10 +64,10 @@ namespace ConsoleApp1 public static TelemetryTracker MakeTelemetryTracker() => new TelemetryTracker(CacheDb, ConfigurationService); - public static TelemetryService MakeTelemetryService() + public static TelemetryService MakeTelemetryService() => new TelemetryService(Context, MakeTelemetryTracker(), TimezoneService, CacheDb); - public static WellService MakeWellService() + public static WellService MakeWellService() => new WellService(Context, CacheDb, MakeTelemetryService(), TimezoneService); public static WellOperationService MakeWellOperationsService() @@ -76,7 +76,7 @@ namespace ConsoleApp1 public static OperationsStatService MakeOperationsStatService() => new OperationsStatService(Context, CacheDb, MakeWellService()); - public static ScheduleReportService MakeScheduleReportService() + public static ScheduleReportService MakeScheduleReportService() => new ScheduleReportService(MakeOperationsStatService(), MakeWellService()); } }