autoclean.

This commit is contained in:
ngfrolov 2022-06-15 14:57:37 +05:00
parent 341375bf1f
commit 7080b3e855
76 changed files with 347 additions and 464 deletions

View File

@ -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; }
/// <summary>
/// Коэффициент эффективности
/// Коэффициент эффективности, %
/// </summary>
public double? Efficiency { get; set; }

View File

@ -16,7 +16,7 @@ namespace AsbCloudApp.Data
/// <summary>
/// Интерфейс записи данных телеметрии
/// </summary>
public interface ITelemetryData: ITelemetryRelated
public interface ITelemetryData : ITelemetryRelated
{
/// <summary>
/// Отметка времени для этой записи

View File

@ -1,6 +1,4 @@
using System;
namespace AsbCloudApp.Data
namespace AsbCloudApp.Data
{
/// <summary>
/// Описание целевых/нормативных показателей операций

View File

@ -5,7 +5,7 @@ namespace AsbCloudApp.Data
/// <summary>
/// DTO времени
/// </summary>
public class TimeDto: IComparable<TimeDto>
public class TimeDto : IComparable<TimeDto>
{
private int hour = 0;
private int minute = 0;
@ -14,13 +14,15 @@ namespace AsbCloudApp.Data
/// <summary>
/// час
/// </summary>
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;
}
}
/// <summary>

View File

@ -3,7 +3,7 @@
/// <summary>
/// DTO категория операции
/// </summary>
public class WellOperationCategoryDto: IId
public class WellOperationCategoryDto : IId
{
/// <inheritdoc/>
public int Id { get; set; }

View File

@ -1,12 +1,12 @@
using System.Collections.Generic;
using System;
using System;
using System.Collections.Generic;
namespace AsbCloudApp.Requests
{
/// <summary>
/// Параметры запроса на получение операций определенных по телеметрии
/// </summary>
public class DetectedOperationRequest: RequestBase
public class DetectedOperationRequest : RequestBase
{
/// <summary>
/// категории операций

View File

@ -9,9 +9,9 @@ namespace AsbCloudApp.Services
/// <summary>
/// Сервис получения, добавления, изменения, удаления данных
/// </summary>
/// <typeparam name="Tdto"></typeparam>
public interface ICrudService<Tdto>
where Tdto : Data.IId
/// <typeparam name="TDto"></typeparam>
public interface ICrudService<TDto>
where TDto : Data.IId
{
/// <summary>
/// Код возврата ошибки: Id не найден в БД.
@ -23,7 +23,7 @@ namespace AsbCloudApp.Services
/// </summary>
/// <param name="token"></param>
/// <returns>emptyList if nothing found</returns>
Task<IEnumerable<Tdto>> GetAllAsync(CancellationToken token);
Task<IEnumerable<TDto>> GetAllAsync(CancellationToken token);
/// <summary>
/// Получить запись по id
@ -31,14 +31,14 @@ namespace AsbCloudApp.Services
/// <param name="id"></param>
/// <param name="token"></param>
/// <returns>null if not found</returns>
Task<Tdto?> GetAsync(int id, CancellationToken token);
Task<TDto?> GetAsync(int id, CancellationToken token);
/// <summary>
/// Получить запись по id
/// </summary>
/// <param name="id"></param>
/// <returns>null if not found</returns>
Tdto? Get(int id);
TDto? Get(int id);
/// <summary>
/// Добавление новой записи
@ -46,7 +46,7 @@ namespace AsbCloudApp.Services
/// <param name="newItem"></param>
/// <param name="token"></param>
/// <returns>Id новой записи</returns>
Task<int> InsertAsync(Tdto newItem, CancellationToken token);
Task<int> InsertAsync(TDto newItem, CancellationToken token);
/// <summary>
/// Добавление нескольких записей
@ -54,7 +54,7 @@ namespace AsbCloudApp.Services
/// <param name="newItems"></param>
/// <param name="token"></param>
/// <returns>количество добавленных</returns>
Task<int> InsertRangeAsync(IEnumerable<Tdto> newItems, CancellationToken token);
Task<int> InsertRangeAsync(IEnumerable<TDto> newItems, CancellationToken token);
/// <summary>
/// Отредактировать запись
@ -62,7 +62,7 @@ namespace AsbCloudApp.Services
/// <param name="item"></param>
/// <param name="token"></param>
/// <returns>если больше 0 - Id записи, если меньше 0 - код ошибки</returns>
Task<int> UpdateAsync(Tdto item, CancellationToken token);
Task<int> UpdateAsync(TDto item, CancellationToken token);
/// <summary>
/// Удалить запись

View File

@ -11,7 +11,7 @@ namespace AsbCloudApp.Services
/// </summary>
/// <typeparam name="Tdto"></typeparam>
public interface ICrudWellRelatedService<Tdto> : ICrudService<Tdto>
where Tdto: IId, IWellRelated
where Tdto : IId, IWellRelated
{
/// <summary>
/// Получение всех записей по скважине

View File

@ -1,6 +1,5 @@
using AsbCloudApp.Data;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

View File

@ -10,8 +10,8 @@ namespace AsbCloudApp.Services
Task<int> InsertAsync(SetpointsRequestDto setpoints, CancellationToken token);
Task<IEnumerable<SetpointsRequestDto>> GetAsync(int idWell, CancellationToken token);
Task<IEnumerable<SetpointsRequestDto>> GetForPanelAsync(string uid, CancellationToken token);
Task<int> TryDelete(int idWell, int id, CancellationToken token);
Task<int> UpdateStateAsync(string uid, int id, SetpointsRequestDto setpointsRequestDto, CancellationToken token);
IEnumerable<SetpointInfoDto> GetSetpointsNames(int idWell);
Task<int> TryDelete(int id, CancellationToken token);
Task<int> UpdateStateAsync(int id, SetpointsRequestDto setpointsRequestDto, CancellationToken token);
IEnumerable<SetpointInfoDto> GetSetpointsNames();
}
}

View File

@ -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<T>(this DbSet<T> dbSet, IEnumerable<T> 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))
{

View File

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

View File

@ -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("Имя")]

View File

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

View File

@ -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("Идентификатор бурильщика")]

View File

@ -65,7 +65,7 @@ namespace AsbCloudInfrastructure
TypeAdapterConfig.GlobalSettings.Default.Config
.ForType<ClusterDto, Cluster>()
.Ignore(dst => dst.Deposit,
dst=>dst.Wells);
dst => dst.Wells);
}
@ -120,7 +120,7 @@ namespace AsbCloudInfrastructure
services.AddTransient<IOperationValueService, OperationValueService>();
// admin crud services:
services.AddTransient<ICrudService<TelemetryDto>, CrudServiceBase<TelemetryDto, Telemetry>>(s =>
services.AddTransient<ICrudService<TelemetryDto>, CrudServiceBase<TelemetryDto, Telemetry>>(s =>
new CrudCacheServiceBase<TelemetryDto, Telemetry>(
s.GetService<IAsbCloudDbContext>(),
dbSet => dbSet.Include(t => t.Well))); // может быть включен в сервис TelemetryService
@ -132,9 +132,9 @@ namespace AsbCloudInfrastructure
services.AddTransient<ICrudService<CompanyDto>, CrudCacheServiceBase<CompanyDto, Company>>(s =>
new CrudCacheServiceBase<CompanyDto, Company>(
s.GetService<IAsbCloudDbContext>(),
dbSet => dbSet.Include(c=>c.CompanyType)));
dbSet => dbSet.Include(c => c.CompanyType)));
services.AddTransient<ICrudService<CompanyTypeDto>, CrudCacheServiceBase<CompanyTypeDto, CompanyType>>();
services.AddTransient<ICrudService<ClusterDto>, CrudCacheServiceBase<ClusterDto, Cluster>>(s =>
services.AddTransient<ICrudService<ClusterDto>, CrudCacheServiceBase<ClusterDto, Cluster>>(s =>
new CrudCacheServiceBase<ClusterDto, Cluster>(
s.GetService<IAsbCloudDbContext>(),
dbSet => dbSet

View File

@ -42,7 +42,7 @@ namespace AsbCloudInfrastructure.EfCache
{
if (Data is Dictionary<TKey, TModel> typedData)
return typedData;
if (Data is Dictionary<TKey, TEntity > typedEntityData)
if (Data is Dictionary<TKey, TEntity> typedEntityData)
{
if (semaphore.Wait(0))
{
@ -375,16 +375,16 @@ namespace AsbCloudInfrastructure.EfCache
/// <param name="token"></param>
/// <returns></returns>
public static async Task<Dictionary<TKey, TEntity>> FromCacheDictionaryAsync<TKey, TEntity>(
this IQueryable<TEntity> query,
string tag,
TimeSpan obsolescence,
Func<TEntity, TKey> keySelector,
this IQueryable<TEntity> query,
string tag,
TimeSpan obsolescence,
Func<TEntity, TKey> keySelector,
CancellationToken token = default)
where TEntity : class
where TKey : notnull
{
async Task<IDictionary> 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<TKey, TEntity>();
}

View File

@ -15,7 +15,7 @@ namespace AsbCloudInfrastructure.EfCache
/// </summary>
public static class EfCacheExtensions
{
private static readonly Dictionary<string, CacheItem> caches = new(16);
private static readonly Dictionary<string, CacheItem> 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<TModel> FromCache<TEntity, TModel>(this IQueryable<TEntity> query, string tag, TimeSpan obsolescence, Func<TEntity, TModel> 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<IEnumerable> 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);
}

View File

@ -4,5 +4,5 @@
/// Тип для поиска этой сборки
/// </summary>
public interface IInfrastructureMarker
{}
{ }
}

View File

@ -1,8 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace Mapster
namespace Mapster
{
public static class MapsterExtension
{

View File

@ -15,7 +15,7 @@ namespace AsbCloudInfrastructure.Services
/// </summary>
/// <typeparam name="TDto"></typeparam>
/// <typeparam name="TEntity"></typeparam>
public class CrudCacheServiceBase<TDto, TEntity>: CrudServiceBase<TDto, TEntity>
public class CrudCacheServiceBase<TDto, TEntity> : CrudServiceBase<TDto, TEntity>
where TDto : AsbCloudApp.Data.IId
where TEntity : class, AsbCloudDb.Model.IId
{
@ -87,6 +87,15 @@ namespace AsbCloudInfrastructure.Services
return result;
}
/// <inheritdoc/>
public override async Task<int> UpdateRangeAsync(IEnumerable<TDto> dtos, CancellationToken token)
{
var result = await base.UpdateRangeAsync(dtos, token);
if (result > 0)
DropCache();
return result;
}
/// <inheritdoc/>
public override async Task<int> DeleteAsync(int id, CancellationToken token)
{

View File

@ -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<TEntity>();
GetQuery = () => {
GetQuery = () =>
{
IQueryable<TEntity> 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<TDto>.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<int> UpdateRangeAsync(IEnumerable<TDto> 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<TDto>.ErrorIdNotFound;
foreach (var dto in dtos)
{
var entity = Convert(dto);
var entry = dbSet.Update(entity);
}
var affected = await dbContext.SaveChangesAsync(token);
return affected;
}
/// <inheritdoc/>
public virtual Task<int> DeleteAsync(int id, CancellationToken token = default)
{

View File

@ -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<string> includes)
public CrudWellRelatedServiceBase(IAsbCloudDbContext dbContext, ISet<string> includes)
: base(dbContext, includes) { }
public CrudWellRelatedServiceBase(IAsbCloudDbContext context, Func<DbSet<TEntity>, IQueryable<TEntity>> makeQuery)
public CrudWellRelatedServiceBase(IAsbCloudDbContext context, Func<DbSet<TEntity>, IQueryable<TEntity>> makeQuery)
: base(context, makeQuery) { }
public async Task<IEnumerable<TDto>> GetByIdWellAsync(int idWell, CancellationToken token)
@ -36,9 +36,9 @@ namespace AsbCloudInfrastructure.Services
{
if (!idsWells.Any())
return Enumerable.Empty<TDto>();
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;

View File

@ -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<IEnumerable<DailyReportDto>> 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<DailyReportInfo>();
var entity = dto.Adapt<DailyReportInfo>();
entity.ReportDate = dto.ReportDate
.ToUtcDateTimeOffset(offsetHours)
.Date;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -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<SetpointsRequestDto, SetpointsRequest>
public class SetpointsService : ISetpointsService
{
// ## Инфо от АПГ от 26.11.2021, дополнения ШОВ от 26.11.2021
private static readonly Dictionary<string, SetpointInfoDto> 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<SetpointsRequest> cacheSetpoints;
private readonly IAsbCloudDbContext db;
private readonly ITelemetryService telemetryService;
private readonly CrudCacheServiceBase<SetpointsRequestDto, SetpointsRequest> setpointsRepository;
public SetpointsService(IAsbCloudDbContext db, CacheDb cacheDb, ITelemetryService telemetryService)
public SetpointsService(IAsbCloudDbContext db, ITelemetryService telemetryService)
{
cacheSetpoints = cacheDb.GetCachedTable<SetpointsRequest>(
(AsbCloudDbContext)db,
nameof(SetpointsRequest.Author),
nameof(SetpointsRequest.Well));
setpointsRepository = new CrudCacheServiceBase<SetpointsRequestDto, SetpointsRequest>(db, q => q.Include(s => s.Author).Include(s => s.Well));
this.db = db;
this.telemetryService = telemetryService;
}
public async Task<int> InsertAsync(SetpointsRequestDto setpoints, CancellationToken token)
public async Task<int> 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<IEnumerable<SetpointsRequestDto>> 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<int> UpdateStateAsync(string uid, int id, SetpointsRequestDto setpointsRequestDto, CancellationToken token)
public async Task<int> 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<int> TryDelete(int idWell, int id, CancellationToken token)
public async Task<int> 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<SetpointsRequest>();
return entity;
}
public SetpointsRequestDto Convert(SetpointsRequest src)
{
var dto = src.Adapt<SetpointsRequestDto>();
return dto;
}
public IEnumerable<SetpointInfoDto> GetSetpointsNames(int idWell)
=> SetpointInfos.Values;
public IEnumerable<SetpointInfoDto> GetSetpointsNames()
=> SetpointInfos.Values;
}
}

View File

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

View File

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

View File

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

View File

@ -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<Well> MakeQueryWell(DbSet<Well> dbSet)
private static IQueryable<Well> MakeQueryWell(DbSet<Well> 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<IEnumerable<WellDto>> 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)

View File

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

View File

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

View File

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

View File

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

View File

@ -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<Cluster> 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<Well> 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<CompanyType> companiesTypes = new()
{
new CompanyType { Id = 1, Caption = "test company type"}
};
private readonly List<Company> 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<RelationCompanyWell> relations = new()
{
new RelationCompanyWell { IdCompany = 1, IdWell = 1 },
new RelationCompanyWell { IdCompany = 1, IdWell = 2 },
new RelationCompanyWell { IdCompany = 2, IdWell = 2 }
};
private readonly List<WellSectionType> 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);
}
}

View File

@ -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<TDto>
where TDto: AsbCloudApp.Data.IId
where TDto : AsbCloudApp.Data.IId
{
private readonly ICrudService<TDto> service;

View File

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

View File

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

View File

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

View File

@ -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<Well> wells = new()
@ -27,15 +26,15 @@ namespace AsbCloudWebApi.Tests.ServicesTests
new Well { Id = 3002, Caption = "well 2", Timezone = baseTimezone },
};
private static readonly List<Company> companies = new() {
private static readonly List<Company> 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<User> 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();

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -12,6 +12,6 @@ namespace AsbCloudWebApi.Controllers
{
public AdminClusterController(ICrudService<ClusterDto> service)
: base(service)
{}
{ }
}
}

View File

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

View File

@ -14,7 +14,7 @@ namespace AsbCloudWebApi.Controllers
{
public AdminWellController(IWellService service)
: base(service)
{}
{ }
[HttpPost("EnshureTimezonesIsSet")]
[Permission]

View File

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

View File

@ -22,7 +22,7 @@ namespace AsbCloudWebApi.Controllers
where T : IId, IWellRelated
where TService : ICrudWellRelatedService<T>
{
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<ActionResult<int>> 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;
}
}
}

View File

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

View File

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

View File

@ -11,7 +11,7 @@ namespace AsbCloudWebApi.Controllers
public class DrillerController : CrudController<DrillerDto, IDrillerService>
{
public DrillerController(IDrillerService drillerService)
:base(drillerService)
{}
: base(drillerService)
{ }
}
}

View File

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

View File

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

View File

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

View File

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

View File

@ -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<ScheduleDto, IScheduleService>
public class ScheduleController : CrudWellRelatedController<ScheduleDto, IScheduleService>
{
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;
}
/// <summary>
/// список расписаний бурильщиков по скважине
/// </summary>
/// <param name="idWell"></param>
/// <param name="token"></param>
/// <returns></returns>
[HttpGet("byWellId/{idWell}")]
[ProducesResponseType(typeof(IEnumerable<ScheduleDto>), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> 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);
}
/// <summary>
/// Получить бурильщика работавшего на скважине в определенное время.
/// </summary>
@ -53,11 +31,10 @@ namespace AsbCloudWebApi.Controllers
[HttpGet("driller")]
public async Task<ActionResult<DrillerDto>> 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);
}

View File

@ -1,5 +1,4 @@
using AsbCloudApp.Data;
using AsbCloudApp.Data.WITS;
using AsbCloudApp.Services;
using AsbCloudWebApi.SignalR;
using Microsoft.AspNetCore.Authorization;

View File

@ -1,5 +1,4 @@
using AsbCloudInfrastructure.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;

View File

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

View File

@ -22,15 +22,16 @@ namespace AsbCloudWebApi
services.AddControllers()
.AddJsonOptions(new System.Action<Microsoft.AspNetCore.Mvc.JsonOptions>(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();

View File

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

View File

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

View File

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

View File

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

View File

@ -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<Google.Apis.Drive.v3.Data.File> 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;
}

View File

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

View File

@ -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 = "<html><boby><H1>this is a test text</H1></boby></html>";
message.IsBodyHtml = true;

View File

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