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.Collections.Generic;
using System.Linq;
namespace AsbCloudApp.Data namespace AsbCloudApp.Data
{ {
@ -31,7 +29,7 @@ namespace AsbCloudApp.Data
public double? AverageTargetValue { get; set; } public double? AverageTargetValue { get; set; }
/// <summary> /// <summary>
/// Коэффициент эффективности /// Коэффициент эффективности, %
/// </summary> /// </summary>
public double? Efficiency { get; set; } public double? Efficiency { get; set; }

View File

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

View File

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

View File

@ -5,7 +5,7 @@ namespace AsbCloudApp.Data
/// <summary> /// <summary>
/// DTO времени /// DTO времени
/// </summary> /// </summary>
public class TimeDto: IComparable<TimeDto> public class TimeDto : IComparable<TimeDto>
{ {
private int hour = 0; private int hour = 0;
private int minute = 0; private int minute = 0;
@ -14,9 +14,11 @@ namespace AsbCloudApp.Data
/// <summary> /// <summary>
/// час /// час
/// </summary> /// </summary>
public int Hour { public int Hour
{
get => hour; get => hour;
set { set
{
if (value > 23 || value < 0) if (value > 23 || value < 0)
throw new ArgumentOutOfRangeException(nameof(Hour), "hour should be in [0; 23]"); throw new ArgumentOutOfRangeException(nameof(Hour), "hour should be in [0; 23]");
hour = value; hour = value;

View File

@ -3,7 +3,7 @@
/// <summary> /// <summary>
/// DTO категория операции /// DTO категория операции
/// </summary> /// </summary>
public class WellOperationCategoryDto: IId public class WellOperationCategoryDto : IId
{ {
/// <inheritdoc/> /// <inheritdoc/>
public int Id { get; set; } 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 namespace AsbCloudApp.Requests
{ {
/// <summary> /// <summary>
/// Параметры запроса на получение операций определенных по телеметрии /// Параметры запроса на получение операций определенных по телеметрии
/// </summary> /// </summary>
public class DetectedOperationRequest: RequestBase public class DetectedOperationRequest : RequestBase
{ {
/// <summary> /// <summary>
/// категории операций /// категории операций

View File

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

View File

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

View File

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

View File

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

View File

@ -61,7 +61,7 @@ namespace AsbCloudDb
public static (int updated, int inserted) UpsertRange<T>(this DbSet<T> dbSet, IEnumerable<T> values) public static (int updated, int inserted) UpsertRange<T>(this DbSet<T> dbSet, IEnumerable<T> values)
where T : class where T : class
{ {
(int updated, int inserted) stat = (0,0); (int updated, int inserted) stat = (0, 0);
foreach (var value in values) foreach (var value in values)
if (dbSet.Contains(value)) if (dbSet.Contains(value))
{ {

View File

@ -1,6 +1,5 @@
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using System; using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations.Schema;
using System.Text.Json.Serialization; using System.Text.Json.Serialization;

View File

@ -7,10 +7,10 @@ using System.Text.Json.Serialization;
namespace AsbCloudDb.Model namespace AsbCloudDb.Model
{ {
[Table("t_driller"), Comment("Бурильщик")] [Table("t_driller"), Comment("Бурильщик")]
public class Driller: IId public class Driller : IId
{ {
[Key] [Key]
[Column("id"),Comment("Идентификатор")] [Column("id"), Comment("Идентификатор")]
public int Id { get; set; } public int Id { get; set; }
[Column("name"), Comment("Имя")] [Column("name"), Comment("Имя")]

View File

@ -5,7 +5,7 @@ using System.ComponentModel.DataAnnotations.Schema;
namespace AsbCloudDb.Model namespace AsbCloudDb.Model
{ {
[Table("t_operationvalue"), Comment("Целевые/нормативные показатели операции")] [Table("t_operationvalue"), Comment("Целевые/нормативные показатели операции")]
public class OperationValue: IId, IWellRelated public class OperationValue : IId, IWellRelated
{ {
[Key] [Key]
[Column("id"), Comment("Идентификатор")] [Column("id"), Comment("Идентификатор")]
@ -24,7 +24,7 @@ namespace AsbCloudDb.Model
public double StandardValue { get; set; } public double StandardValue { get; set; }
[Column("depth_start"), Comment("Старотовая глубина")] [Column("depth_start"), Comment("Старотовая глубина")]
public double DepthStart { get; set; } public double DepthStart { get; set; }
[Column("depth_end"), Comment("Конечная глубина")] [Column("depth_end"), Comment("Конечная глубина")]
public double DepthEnd { get; set; } public double DepthEnd { get; set; }

View File

@ -6,10 +6,10 @@ using System.ComponentModel.DataAnnotations.Schema;
namespace AsbCloudDb.Model namespace AsbCloudDb.Model
{ {
[Table("t_schedule"), Comment("График работы бурильщика")] [Table("t_schedule"), Comment("График работы бурильщика")]
public class Schedule: IId, IWellRelated public class Schedule : IId, IWellRelated
{ {
[Key] [Key]
[Column("id"),Comment("Идентификатор")] [Column("id"), Comment("Идентификатор")]
public int Id { get; set; } public int Id { get; set; }
[Column("id_driller"), Comment("Идентификатор бурильщика")] [Column("id_driller"), Comment("Идентификатор бурильщика")]

View File

@ -65,7 +65,7 @@ namespace AsbCloudInfrastructure
TypeAdapterConfig.GlobalSettings.Default.Config TypeAdapterConfig.GlobalSettings.Default.Config
.ForType<ClusterDto, Cluster>() .ForType<ClusterDto, Cluster>()
.Ignore(dst => dst.Deposit, .Ignore(dst => dst.Deposit,
dst=>dst.Wells); dst => dst.Wells);
} }
@ -132,7 +132,7 @@ namespace AsbCloudInfrastructure
services.AddTransient<ICrudService<CompanyDto>, CrudCacheServiceBase<CompanyDto, Company>>(s => services.AddTransient<ICrudService<CompanyDto>, CrudCacheServiceBase<CompanyDto, Company>>(s =>
new CrudCacheServiceBase<CompanyDto, Company>( new CrudCacheServiceBase<CompanyDto, Company>(
s.GetService<IAsbCloudDbContext>(), 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<CompanyTypeDto>, CrudCacheServiceBase<CompanyTypeDto, CompanyType>>();
services.AddTransient<ICrudService<ClusterDto>, CrudCacheServiceBase<ClusterDto, Cluster>>(s => services.AddTransient<ICrudService<ClusterDto>, CrudCacheServiceBase<ClusterDto, Cluster>>(s =>
new CrudCacheServiceBase<ClusterDto, Cluster>( new CrudCacheServiceBase<ClusterDto, Cluster>(

View File

@ -42,7 +42,7 @@ namespace AsbCloudInfrastructure.EfCache
{ {
if (Data is Dictionary<TKey, TModel> typedData) if (Data is Dictionary<TKey, TModel> typedData)
return typedData; return typedData;
if (Data is Dictionary<TKey, TEntity > typedEntityData) if (Data is Dictionary<TKey, TEntity> typedEntityData)
{ {
if (semaphore.Wait(0)) if (semaphore.Wait(0))
{ {

View File

@ -71,7 +71,7 @@ namespace AsbCloudInfrastructure.EfCache
} }
} }
} }
if(attempt > 0) if (attempt > 0)
return GetData(convert, --attempt); return GetData(convert, --attempt);
throw new TypeAccessException("Cache data has wrong type. Possible 'tag' is not unique."); throw new TypeAccessException("Cache data has wrong type. Possible 'tag' is not unique.");
} }
@ -84,7 +84,8 @@ namespace AsbCloudInfrastructure.EfCache
{ {
if (semaphore.Wait(0)) if (semaphore.Wait(0))
{ {
try { try
{
cache = new CacheItem(); cache = new CacheItem();
caches.Add(tag, cache); caches.Add(tag, cache);
} }
@ -141,7 +142,7 @@ namespace AsbCloudInfrastructure.EfCache
cache.semaphore.Release(); cache.semaphore.Release();
} }
} }
else if(cache.DateObsoleteTotal < DateTime.Now) else if (cache.DateObsoleteTotal < DateTime.Now)
{ {
if (cache.semaphore.Wait(semaphoreTimeout)) if (cache.semaphore.Wait(semaphoreTimeout))
{ {
@ -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) public static IEnumerable<TModel> FromCache<TEntity, TModel>(this IQueryable<TEntity> query, string tag, TimeSpan obsolescence, Func<TEntity, TModel> convert)
where TEntity : class where TEntity : class
{ {
IEnumerable factory () => query.AsNoTracking().ToList(); IEnumerable factory() => query.AsNoTracking().ToList();
var cache = GetOrAddCache(tag, factory, obsolescence); var cache = GetOrAddCache(tag, factory, obsolescence);
return cache.GetData(convert); return cache.GetData(convert);
} }

View File

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

View File

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

View File

@ -15,7 +15,7 @@ namespace AsbCloudInfrastructure.Services
/// </summary> /// </summary>
/// <typeparam name="TDto"></typeparam> /// <typeparam name="TDto"></typeparam>
/// <typeparam name="TEntity"></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 TDto : AsbCloudApp.Data.IId
where TEntity : class, AsbCloudDb.Model.IId where TEntity : class, AsbCloudDb.Model.IId
{ {
@ -87,6 +87,15 @@ namespace AsbCloudInfrastructure.Services
return result; 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/> /// <inheritdoc/>
public override async Task<int> DeleteAsync(int id, CancellationToken token) public override async Task<int> DeleteAsync(int id, CancellationToken token)
{ {

View File

@ -3,7 +3,6 @@ using AsbCloudDb.Model;
using Mapster; using Mapster;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using System; using System;
using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading; using System.Threading;
@ -37,7 +36,8 @@ namespace AsbCloudInfrastructure.Services
this.dbContext = dbContext; this.dbContext = dbContext;
dbSet = dbContext.Set<TEntity>(); dbSet = dbContext.Set<TEntity>();
GetQuery = () => { GetQuery = () =>
{
IQueryable<TEntity> query = dbSet; IQueryable<TEntity> query = dbSet;
foreach (var include in includes) foreach (var include in includes)
query = query.Include(include); query = query.Include(include);
@ -140,6 +140,29 @@ namespace AsbCloudInfrastructure.Services
return entry.Entity.Id; 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/> /// <inheritdoc/>
public virtual Task<int> DeleteAsync(int id, CancellationToken token = default) public virtual Task<int> DeleteAsync(int id, CancellationToken token = default)
{ {

View File

@ -38,7 +38,7 @@ namespace AsbCloudInfrastructure.Services
return Enumerable.Empty<TDto>(); return Enumerable.Empty<TDto>();
var entities = await GetQuery() var entities = await GetQuery()
.Where(e => idsWells.Contains( e.IdWell)) .Where(e => idsWells.Contains(e.IdWell))
.ToListAsync(token); .ToListAsync(token);
var dtos = entities.Select(Convert).ToList(); var dtos = entities.Select(Convert).ToList();
return dtos; 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.IO;
using System.Linq; using System.Linq;
using System.Threading; using System.Threading;
using System.Threading.Tasks; 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 namespace AsbCloudInfrastructure.Services.DailyReport
{ {

View File

@ -13,7 +13,7 @@ using System.Threading.Tasks;
namespace AsbCloudInfrastructure.Services.DetectOperations namespace AsbCloudInfrastructure.Services.DetectOperations
{ {
public class DetectedOperationService: IDetectedOperationService public class DetectedOperationService : IDetectedOperationService
{ {
public const int IdOperationRotor = 1; public const int IdOperationRotor = 1;
public const int IdOperationSlide = 3; public const int IdOperationSlide = 3;

View File

@ -20,7 +20,7 @@ namespace AsbCloudInfrastructure.Services.DetectOperations.Detectors
System.Math.Abs((float)delta) > 1d) System.Math.Abs((float)delta) > 1d)
return false; return false;
var fragment = telemetry[position .. (position + FragmentLength)]; var fragment = telemetry[position..(position + FragmentLength)];
const double minRop = 5; //м/час const double minRop = 5; //м/час
const double minRotorSpeed = 5; //об/мин const double minRotorSpeed = 5; //об/мин
@ -31,7 +31,7 @@ namespace AsbCloudInfrastructure.Services.DetectOperations.Detectors
return false; return false;
var lineWellDepth = new InterpolationLine(fragment.Select(d => (d.WellDepth ?? 0d, d.DateTime.Ticks / ticksPerHour))); var lineWellDepth = new InterpolationLine(fragment.Select(d => (d.WellDepth ?? 0d, d.DateTime.Ticks / ticksPerHour)));
if(!lineWellDepth.IsYIncreases(minRop)) if (!lineWellDepth.IsYIncreases(minRop))
return false; return false;
var lineRotorSpeed = new InterpolationLine(fragment.Select(d => (d.RotorSpeed ?? 0d, d.DateTime.Ticks / ticksPerHour))); 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) System.Math.Abs((float)delta) > 1d)
return false; return false;
var fragment = telemetry[position .. (position + FragmentLength)]; var fragment = telemetry[position..(position + FragmentLength)];
const double minRop = 5; //м/час const double minRop = 5; //м/час
const double minRotorSpeed = 5; //об/мин const double minRotorSpeed = 5; //об/мин
@ -30,7 +30,7 @@ namespace AsbCloudInfrastructure.Services.DetectOperations.Detectors
return false; return false;
var lineWellDepth = new InterpolationLine(fragment.Select(d => (d.WellDepth ?? 0d, d.DateTime.Ticks / ticksPerHour))); var lineWellDepth = new InterpolationLine(fragment.Select(d => (d.WellDepth ?? 0d, d.DateTime.Ticks / ticksPerHour)));
if(!lineWellDepth.IsYIncreases(minRop)) if (!lineWellDepth.IsYIncreases(minRop))
return false; return false;
var lineRotorSpeed = new InterpolationLine(fragment.Select(d => (d.RotorSpeed ?? 0d, d.DateTime.Ticks / ticksPerHour))); 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 #nullable enable
class DetectorSlipsTime : DetectorAbstract class DetectorSlipsTime : DetectorAbstract
{ {
public DetectorSlipsTime() :base(14) {} public DetectorSlipsTime() : base(14) { }
public double HookWeightSP { get; set; } = 20; public double HookWeightSP { get; set; } = 20;
public double PressureSP { get; set; } = 15; public double PressureSP { get; set; } = 15;
public double PosisionSP { get; set; } = 8; public double PosisionSP { get; set; } = 8;

View File

@ -4,10 +4,10 @@ using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Hosting;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics;
using System.Linq; using System.Linq;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Diagnostics;
namespace AsbCloudInfrastructure.Services.DetectOperations namespace AsbCloudInfrastructure.Services.DetectOperations
{ {
@ -95,12 +95,12 @@ namespace AsbCloudInfrastructure.Services.DetectOperations
(outer, inner) => new (outer, inner) => new
{ {
IdTelemetry = outer, IdTelemetry = outer,
LastDate = inner.SingleOrDefault()?.LastDate , LastDate = inner.SingleOrDefault()?.LastDate,
}); });
var affected = 0; var affected = 0;
foreach (var item in JounedlastDetectedDates) 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()) if (newOperations.Any())
{ {
db.DetectedOperations.AddRange(newOperations); db.DetectedOperations.AddRange(newOperations);
@ -115,7 +115,8 @@ namespace AsbCloudInfrastructure.Services.DetectOperations
var query = db.TelemetryDataSaub var query = db.TelemetryDataSaub
.AsNoTracking() .AsNoTracking()
.Where(d => d.IdTelemetry == idTelemetry) .Where(d => d.IdTelemetry == idTelemetry)
.Select(d => new DetectableTelemetry{ .Select(d => new DetectableTelemetry
{
DateTime = d.DateTime, DateTime = d.DateTime,
IdUser = d.IdUser, IdUser = d.IdUser,
WellDepth = d.WellDepth, WellDepth = d.WellDepth,
@ -162,7 +163,7 @@ namespace AsbCloudInfrastructure.Services.DetectOperations
foreach (var detector in detectors) foreach (var detector in detectors)
{ {
if(data.Length < skip + detector.StepLength + detector.FragmentLength) if (data.Length < skip + detector.StepLength + detector.FragmentLength)
continue; continue;
var detectedOperation = detector.DetectOrDefault(data, ref skip); var detectedOperation = detector.DetectOrDefault(data, ref skip);

View File

@ -1,11 +1,6 @@
using AsbCloudApp.Data; using AsbCloudApp.Data;
using AsbCloudApp.Services; using AsbCloudApp.Services;
using AsbCloudDb.Model; using AsbCloudDb.Model;
using AsbCloudInfrastructure.Services.Cache;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudInfrastructure.Services namespace AsbCloudInfrastructure.Services
{ {

View File

@ -181,7 +181,7 @@ namespace AsbCloudInfrastructure.Services.DrillingProgram
await RemoveDrillingProgramAsync(part.IdWell, token); await RemoveDrillingProgramAsync(part.IdWell, token);
await NotifyApproversAsync(part, result.Id, fileFullName, token); await NotifyApproversAsync(part, result.Id, fileFullName, token);
return result.Id; return result.Id;
} }
@ -229,7 +229,7 @@ namespace AsbCloudInfrastructure.Services.DrillingProgram
throw new ArgumentInvalidException($"User id == {idUser} does not exist", nameof(idUser)); throw new ArgumentInvalidException($"User id == {idUser} does not exist", nameof(idUser));
var part = await context.DrillingProgramParts var part = await context.DrillingProgramParts
.Include(p=>p.FileCategory) .Include(p => p.FileCategory)
.FirstOrDefaultAsync(p => p.IdWell == idWell && p.IdFileCategory == idFileCategory, token); .FirstOrDefaultAsync(p => p.IdWell == idWell && p.IdFileCategory == idFileCategory, token);
if (part is null) if (part is null)

View File

@ -1,8 +1,7 @@
using AsbCloudApp.Data.SAUB; using AsbCloudApp.Data.SAUB;
using AsbCloudApp.Services; using AsbCloudApp.Services;
using AsbCloudDb.Model; using AsbCloudDb.Model;
using AsbCloudInfrastructure.Services.Cache; using Microsoft.EntityFrameworkCore;
using Mapster;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
@ -11,7 +10,7 @@ using System.Threading.Tasks;
namespace AsbCloudInfrastructure.Services.SAUB namespace AsbCloudInfrastructure.Services.SAUB
{ {
public class SetpointsService : ISetpointsService, IConverter<SetpointsRequestDto, SetpointsRequest> public class SetpointsService : ISetpointsService
{ {
// ## Инфо от АПГ от 26.11.2021, дополнения ШОВ от 26.11.2021 // ## Инфо от АПГ от 26.11.2021, дополнения ШОВ от 26.11.2021
private static readonly Dictionary<string, SetpointInfoDto> SetpointInfos = new() private static readonly Dictionary<string, SetpointInfoDto> SetpointInfos = new()
@ -23,38 +22,33 @@ namespace AsbCloudInfrastructure.Services.SAUB
{ "speedRotorSp", new SetpointInfoDto { Name = "speedRotorSp", DisplayName = "Скорость бурения в роторе, м/ч" } }, { "speedRotorSp", new SetpointInfoDto { Name = "speedRotorSp", DisplayName = "Скорость бурения в роторе, м/ч" } },
{ "speedSlideSp", new SetpointInfoDto { Name = "speedSlideSp", DisplayName = "Скорость бурения в слайде, м/ч" } }, { "speedSlideSp", new SetpointInfoDto { Name = "speedSlideSp", DisplayName = "Скорость бурения в слайде, м/ч" } },
{ "speedDevelopSp", new SetpointInfoDto { Name = "speedDevelopSp", 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 = "Обороты ВСП, об/мин" } }, // Оно в ПЛК спинмастера, пока сделать нельзя, позднее можно.
//{ "", new SetpointInfoDto { Name = "", DisplayName = "Расход промывочной жидкости, л/с" } }, // Нет в контроллере //{ "", new SetpointInfoDto { Name = "", DisplayName = "Расход промывочной жидкости, л/с" } }, // Нет в контроллере
}; };
private readonly IAsbCloudDbContext db;
private readonly CacheTable<SetpointsRequest> cacheSetpoints;
private readonly ITelemetryService telemetryService; 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>( setpointsRepository = new CrudCacheServiceBase<SetpointsRequestDto, SetpointsRequest>(db, q => q.Include(s => s.Author).Include(s => s.Well));
(AsbCloudDbContext)db, this.db = db;
nameof(SetpointsRequest.Author),
nameof(SetpointsRequest.Well));
this.telemetryService = telemetryService; this.telemetryService = telemetryService;
} }
public async Task<int> InsertAsync(SetpointsRequestDto setpoints, CancellationToken token) public async Task<int> InsertAsync(SetpointsRequestDto setpointsRequest, CancellationToken token)
{ {
setpoints.IdState = 1; setpointsRequest.IdState = 1;
setpoints.UploadDate = DateTime.UtcNow; setpointsRequest.UploadDate = DateTime.UtcNow;
var dto = Convert(setpoints); var result = await setpointsRepository.InsertAsync(setpointsRequest, token);
var inserted = await cacheSetpoints.InsertAsync(dto, token) return result;
.ConfigureAwait(false);
return inserted?.Id ?? 0;
} }
public async Task<IEnumerable<SetpointsRequestDto>> GetAsync(int idWell, CancellationToken token) public async Task<IEnumerable<SetpointsRequestDto>> GetAsync(int idWell, CancellationToken token)
{ {
var entities = await cacheSetpoints.WhereAsync(s => s.IdWell == idWell, token) var all = await setpointsRepository.GetAllAsync(token);
.ConfigureAwait(false); var dtos = all.Where(s => s.IdWell == idWell);
var dtos = entities.Select(s => Convert(s));
return dtos; return dtos;
} }
@ -64,79 +58,45 @@ namespace AsbCloudInfrastructure.Services.SAUB
if (idWell < 0) if (idWell < 0)
return null; 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 => if (!filtered.Any())
s.IdWell == idWell && s.IdState == 1 && s.UploadDate.AddSeconds(s.ObsolescenceSec) > DateTime.Now,
token)
.ConfigureAwait(false))
.ToList();// без .ToList() работает не правильно.
if (!entities.Any())
return null; return null;
foreach (var entity in entities) foreach (var entity in filtered)
entity.IdState = 2; entity.IdState = 2;
await cacheSetpoints.UpsertAsync(entities, token) await setpointsRepository.UpdateRangeAsync(filtered, token);
.ConfigureAwait(false);
var dtos = entities.Select(Convert); return filtered;
return dtos;
} }
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) if (setpointsRequestDto.IdState != 3 && setpointsRequestDto.IdState != 4)
throw new ArgumentOutOfRangeException(nameof(setpointsRequestDto), $"{nameof(setpointsRequestDto.IdState)} = {setpointsRequestDto.IdState}. Mast be 3 or 4."); throw new ArgumentOutOfRangeException(nameof(setpointsRequestDto), $"{nameof(setpointsRequestDto.IdState)} = {setpointsRequestDto.IdState}. Mast be 3 or 4.");
var idWell = telemetryService.GetIdWellByTelemetryUid(uid) ?? -1; var entity = await setpointsRepository.GetAsync(id, token);
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);
if (entity is null) if (entity is null)
return 0; return 0;
entity.IdState = setpointsRequestDto.IdState; entity.IdState = setpointsRequestDto.IdState;
await cacheSetpoints.UpsertAsync(entity, token) var affected = await setpointsRepository.UpdateAsync(entity, token);
.ConfigureAwait(false); return affected;
return 1;
} }
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 affected = await setpointsRepository.DeleteAsync(id, token);
var isExist = await cacheSetpoints.ContainsAsync(Predicate, token) return affected;
.ConfigureAwait(false);
if (!isExist)
return 0;
await cacheSetpoints.RemoveAsync(Predicate, token)
.ConfigureAwait(false);
return 1;
} }
public SetpointsRequest Convert(SetpointsRequestDto src) public IEnumerable<SetpointInfoDto> GetSetpointsNames()
{ => SetpointInfos.Values;
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;
} }
} }

View File

@ -4,7 +4,6 @@ using AsbCloudApp.Services;
using AsbCloudDb; using AsbCloudDb;
using AsbCloudDb.Model; using AsbCloudDb.Model;
using AsbCloudInfrastructure.EfCache; using AsbCloudInfrastructure.EfCache;
using AsbCloudInfrastructure.Services.Cache;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading; using System.Threading;

View File

@ -4,7 +4,6 @@ using AsbCloudDb.Model;
using Mapster; using Mapster;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using System; using System;
using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
@ -28,7 +27,7 @@ namespace AsbCloudInfrastructure.Services
var date = workTime.ToUtcDateTimeOffset(hoursOffset); var date = workTime.ToUtcDateTimeOffset(hoursOffset);
var entities = await GetQuery() var entities = await GetQuery()
.Where(s => s.IdWell==idWell .Where(s => s.IdWell == idWell
&& s.DrillStart <= date && s.DrillStart <= date
&& s.DrillEnd >= date) && s.DrillEnd >= date)
.ToListAsync(token); .ToListAsync(token);

View File

@ -52,7 +52,7 @@ namespace AsbCloudInfrastructure.Services.WellOperationService
public DateTimeOffset? FirstOperationDate(int idWell) public DateTimeOffset? FirstOperationDate(int idWell)
{ {
if(firstOperationsCache is null) if (firstOperationsCache is null)
{ {
var query = db.WellOperations var query = db.WellOperations
.GroupBy(o => o.IdWell) .GroupBy(o => o.IdWell)

View File

@ -2,8 +2,8 @@
using AsbCloudApp.Exceptions; using AsbCloudApp.Exceptions;
using AsbCloudApp.Services; using AsbCloudApp.Services;
using AsbCloudDb.Model; using AsbCloudDb.Model;
using AsbCloudInfrastructure.Services.Cache;
using AsbCloudInfrastructure.EfCache; using AsbCloudInfrastructure.EfCache;
using AsbCloudInfrastructure.Services.Cache;
using Mapster; using Mapster;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using System; using System;
@ -81,7 +81,7 @@ namespace AsbCloudInfrastructure.Services
var wellsDtos = (await GetCacheAsync(token)) var wellsDtos = (await GetCacheAsync(token))
.Where(kv => wellsIds.Contains(kv.Key)) .Where(kv => wellsIds.Contains(kv.Key))
.Select(kv =>kv.Value); .Select(kv => kv.Value);
return wellsDtos.ToList(); return wellsDtos.ToList();
} }
@ -227,7 +227,7 @@ namespace AsbCloudInfrastructure.Services
dto.WellType = entity.WellType?.Caption; dto.WellType = entity.WellType?.Caption;
dto.Cluster = entity.Cluster?.Caption; dto.Cluster = entity.Cluster?.Caption;
dto.Deposit = entity.Cluster?.Deposit?.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.LastTelemetryDate = telemetryService.GetLastTelemetryDate((int)entity.IdTelemetry);
dto.Companies = entity.RelationCompaniesWells dto.Companies = entity.RelationCompaniesWells
.Select(r => Convert(r.Company)) .Select(r => Convert(r.Company))

View File

@ -7,8 +7,8 @@ namespace AsbCloudInfrastructure.Validators
{ {
public TimeDtoValidator() public TimeDtoValidator()
{ {
RuleFor(x=>x.Hour) RuleFor(x => x.Hour)
.InclusiveBetween(0,23) .InclusiveBetween(0, 23)
.WithMessage("hour should be in [0; 23]"); .WithMessage("hour should be in [0; 23]");
RuleFor(x => x.Minute) RuleFor(x => x.Minute)

View File

@ -1,17 +1,4 @@
using AsbCloudApp.Data; namespace AsbCloudWebApi.Tests.ControllersTests
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
{ {
//public class AnalyticsControllerTests //public class AnalyticsControllerTests
//{ //{

View File

@ -1,11 +1,6 @@
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims; using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
namespace AsbCloudWebApi.Tests.ControllersTests namespace AsbCloudWebApi.Tests.ControllersTests
{ {

View File

@ -1,17 +1,8 @@
using AsbCloudApp.Data.SAUB; using AsbCloudApp.Data.SAUB;
using AsbCloudApp.Services; using AsbCloudApp.Services;
using AsbCloudDb.Model;
using AsbCloudWebApi.Controllers;
using AsbCloudWebApi.SignalR; using AsbCloudWebApi.SignalR;
using Microsoft.AspNetCore.SignalR; using Microsoft.AspNetCore.SignalR;
using Microsoft.EntityFrameworkCore;
using Moq; using Moq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace AsbCloudWebApi.Tests.ControllersTests namespace AsbCloudWebApi.Tests.ControllersTests
{ {

View File

@ -1,11 +1,11 @@
using AsbCloudApp.Services;
using AsbCloudDb.Model; using AsbCloudDb.Model;
using AsbCloudInfrastructure.Services; using AsbCloudInfrastructure.Services;
using Moq;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using Moq;
using Xunit; using Xunit;
using AsbCloudApp.Services;
namespace AsbCloudWebApi.Tests.ServicesTests; namespace AsbCloudWebApi.Tests.ServicesTests;
@ -79,7 +79,7 @@ public class ClusterServiceTest
context.RelationCompaniesWells.RemoveRange(context.RelationCompaniesWells); context.RelationCompaniesWells.RemoveRange(context.RelationCompaniesWells);
context.WellSectionTypes.RemoveRange(context.WellSectionTypes); context.WellSectionTypes.RemoveRange(context.WellSectionTypes);
context.DrillParams.RemoveRange(context.DrillParams); context.DrillParams.RemoveRange(context.DrillParams);
if(context.ChangeTracker.HasChanges()) if (context.ChangeTracker.HasChanges())
context.SaveChanges(); context.SaveChanges();
context.Deposits.AddRange(deposits); context.Deposits.AddRange(deposits);
context.Clusters.AddRange(clusters); context.Clusters.AddRange(clusters);
@ -160,7 +160,7 @@ public class ClusterServiceTest
public async Task GetClustersAsync_with_deposit_returns_two_clusters() public async Task GetClustersAsync_with_deposit_returns_two_clusters()
{ {
var service = new ClusterService(context, wellService.Object); 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()); Assert.Equal(2, dtos.Count());
} }
@ -169,7 +169,7 @@ public class ClusterServiceTest
public async Task GetWellsAsync_returns_one_well_by_cluster_and_company() public async Task GetWellsAsync_returns_one_well_by_cluster_and_company()
{ {
var service = new ClusterService(context, wellService.Object); var service = new ClusterService(context, wellService.Object);
var dtos = await service.GetWellsAsync(1,1); var dtos = await service.GetWellsAsync(1, 1);
Assert.Single(dtos); Assert.Single(dtos);
} }

View File

@ -1,5 +1,4 @@
using AsbCloudApp.Services; using AsbCloudApp.Services;
using System;
using System.Linq; using System.Linq;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
@ -8,7 +7,7 @@ using Xunit;
namespace AsbCloudWebApi.Tests.ServicesTests namespace AsbCloudWebApi.Tests.ServicesTests
{ {
public abstract class CrudServiceTestAbstract<TDto> public abstract class CrudServiceTestAbstract<TDto>
where TDto: AsbCloudApp.Data.IId where TDto : AsbCloudApp.Data.IId
{ {
private readonly ICrudService<TDto> service; private readonly ICrudService<TDto> service;

View File

@ -14,7 +14,7 @@ namespace AsbCloudWebApi.Tests.ServicesTests
Caption = "test deposit", Caption = "test deposit",
Latitude = 1, Latitude = 1,
Longitude = 2, Longitude = 2,
Timezone = new SimpleTimezoneDto { Hours = 5, TimezoneId = "test Never-land"} Timezone = new SimpleTimezoneDto { Hours = 5, TimezoneId = "test Never-land" }
}; };
return item; return item;
} }

View File

@ -1,5 +1,4 @@
using AsbCloudApp.Data; using AsbCloudApp.Data;
using AsbCloudApp.Data.SAUB;
using AsbCloudApp.Services; using AsbCloudApp.Services;
using AsbCloudDb.Model; using AsbCloudDb.Model;
using AsbCloudInfrastructure.Services; using AsbCloudInfrastructure.Services;
@ -7,9 +6,6 @@ using AsbCloudInfrastructure.Services.Cache;
using AsbCloudInfrastructure.Services.DetectOperations; using AsbCloudInfrastructure.Services.DetectOperations;
using Moq; using Moq;
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Xunit; using Xunit;
@ -28,7 +24,7 @@ namespace AsbCloudWebApi.Tests.ServicesTests
{ {
Id = 1, Id = 1,
Caption = "Test well 1", Caption = "Test well 1",
IdTelemetry=1, IdTelemetry = 1,
IdCluster = 1, IdCluster = 1,
Timezone = new SimpleTimezone { Hours = 5 } Timezone = new SimpleTimezone { Hours = 5 }
}; };
@ -51,12 +47,12 @@ namespace AsbCloudWebApi.Tests.ServicesTests
}; };
private Telemetry telemetry = new Telemetry private Telemetry telemetry = new Telemetry
{ {
Id=1, Id = 1,
RemoteUid = Guid.NewGuid().ToString() RemoteUid = Guid.NewGuid().ToString()
}; };
#endregion #endregion
public DetectedOperationServiceTest() public DetectedOperationServiceTest()
{ {
context = TestHelpter.MakeTestContext(); context = TestHelpter.MakeTestContext();
context.SaveChanges(); context.SaveChanges();

View File

@ -1,11 +1,7 @@
using AsbCloudApp.Data; using AsbCloudApp.Data;
using AsbCloudApp.Services;
using AsbCloudDb.Model; using AsbCloudDb.Model;
using AsbCloudInfrastructure.Services; using AsbCloudInfrastructure.Services;
using AsbCloudInfrastructure.Services.Cache; using AsbCloudInfrastructure.Services.Cache;
using Moq;
using System;
using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;

View File

@ -1,24 +1,23 @@
using AsbCloudDb.Model; using AsbCloudApp.Data;
using AsbCloudInfrastructure.Services; 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.Collections.Generic;
using System.Linq; 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 System.Threading;
using AsbCloudApp.Data; using System.Threading.Tasks;
using Mapster; using Xunit;
using System;
namespace AsbCloudWebApi.Tests.ServicesTests namespace AsbCloudWebApi.Tests.ServicesTests
{ {
public class DrillingProgramServiceTest public class DrillingProgramServiceTest
{ {
private const int idWell = 3001; 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 readonly AsbCloudDbContext db;
private static readonly List<Well> wells = new() private static readonly List<Well> wells = new()
@ -33,9 +32,9 @@ namespace AsbCloudWebApi.Tests.ServicesTests
new Company { Id = 3003, 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 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 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 approver2 = new() { Id = 3003, IdCompany = 3002, Login = "user 3", Email = "aa@aa.aa", IdState = 2 };
private static readonly List<User> users = new() 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 }, 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, Id = 3001,
IdWell = idWell, IdWell = idWell,
@ -58,7 +57,7 @@ namespace AsbCloudWebApi.Tests.ServicesTests
UploadDate = System.DateTimeOffset.UtcNow, UploadDate = System.DateTimeOffset.UtcNow,
}; };
private static readonly FileInfo file1002 = new () private static readonly FileInfo file1002 = new()
{ {
Id = 3002, Id = 3002,
IdWell = idWell, IdWell = idWell,
@ -141,7 +140,7 @@ namespace AsbCloudWebApi.Tests.ServicesTests
[Fact] [Fact]
public async Task RemovePartsAsync_returns_1() 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(); db.SaveChanges();
var service = new DrillingProgramService( var service = new DrillingProgramService(
db, db,
@ -185,7 +184,8 @@ namespace AsbCloudWebApi.Tests.ServicesTests
{ {
const int idUserRole = 1; const int idUserRole = 1;
const int idFileCategory = 1001; const int idFileCategory = 1001;
var entry = db.DrillingProgramParts.Add(new DrillingProgramPart { var entry = db.DrillingProgramParts.Add(new DrillingProgramPart
{
IdFileCategory = idFileCategory, IdFileCategory = idFileCategory,
IdWell = idWell IdWell = idWell
}); });
@ -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 = approver1.Id, IdMarkType = 1, DateCreated = DateTimeOffset.UtcNow },
new FileMark { IdFile = file1002.Id, IdUser = approver2.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(); await db.SaveChangesAsync();

View File

@ -1,14 +1,13 @@
using AsbCloudApp.Data.SAUB;
using AsbCloudApp.Services;
using AsbCloudDb.Model; using AsbCloudDb.Model;
using AsbCloudInfrastructure.Services.Cache; using AsbCloudInfrastructure.Services.Cache;
using AsbCloudInfrastructure.Services; using AsbCloudInfrastructure.Services.SAUB;
using Moq;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using AsbCloudApp.Services;
using Moq;
using Xunit; using Xunit;
using AsbCloudApp.Data.SAUB;
using AsbCloudInfrastructure.Services.SAUB;
namespace AsbCloudWebApi.Tests.ServicesTests; namespace AsbCloudWebApi.Tests.ServicesTests;

View File

@ -41,8 +41,9 @@ namespace AsbCloudWebApi.Tests.ServicesTests
}; };
} }
private Well well = new Well { private Well well = new Well
Id=1, {
Id = 1,
Caption = "Test well 1", Caption = "Test well 1",
IdCluster = 1, IdCluster = 1,
Timezone = new SimpleTimezone { Hours = 5 } Timezone = new SimpleTimezone { Hours = 5 }
@ -55,7 +56,7 @@ namespace AsbCloudWebApi.Tests.ServicesTests
Surname = "Тестович" Surname = "Тестович"
}; };
public ScheduleServiceTest() public ScheduleServiceTest()
{ {
context = TestHelpter.MakeTestContext(); context = TestHelpter.MakeTestContext();
context.SaveChanges(); context.SaveChanges();

View File

@ -2,7 +2,6 @@
using AsbCloudDb.Model; using AsbCloudDb.Model;
using AsbCloudInfrastructure.Services; using AsbCloudInfrastructure.Services;
using AsbCloudInfrastructure.Services.Cache; using AsbCloudInfrastructure.Services.Cache;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading; using System.Threading;
@ -62,7 +61,8 @@ namespace AsbCloudWebApi.Tests.ServicesTests
context.SaveChanges(); context.SaveChanges();
} }
~UserRoleServiceTest(){ ~UserRoleServiceTest()
{
context.UserRoles.RemoveRange(roles); context.UserRoles.RemoveRange(roles);
context.Permissions.RemoveRange(permissions); context.Permissions.RemoveRange(permissions);
context.RelationUserRoleUserRoles.RemoveRange(relationRoleRole); context.RelationUserRoleUserRoles.RemoveRange(relationRoleRole);
@ -104,7 +104,7 @@ namespace AsbCloudWebApi.Tests.ServicesTests
Caption = "new role", Caption = "new role",
IdType = 0, IdType = 0,
}; };
var id = await service.InsertAsync(newRole, CancellationToken.None ); var id = await service.InsertAsync(newRole, CancellationToken.None);
Assert.NotEqual(0, id); Assert.NotEqual(0, id);
} }
@ -116,7 +116,7 @@ namespace AsbCloudWebApi.Tests.ServicesTests
{ {
Caption = "new role", Caption = "new role",
IdType = 0, 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); var entity = await service.GetAsync(id);
@ -131,7 +131,7 @@ namespace AsbCloudWebApi.Tests.ServicesTests
{ {
Caption = "new role", Caption = "new role",
IdType = 0, 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 id = await service.InsertAsync(newRole, CancellationToken.None);
var entity = await service.GetAsync(id); var entity = await service.GetAsync(id);

View File

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

View File

@ -19,7 +19,7 @@ namespace AsbCloudWebApi.Controllers
return Task.FromResult(role?.IdType == 1); return Task.FromResult(role?.IdType == 1);
}; };
UpdateForbidAsync = async ( dto, token) => UpdateForbidAsync = async (dto, token) =>
{ {
var role = await service.GetAsync(dto.Id, token); var role = await service.GetAsync(dto.Id, token);
return role?.IdType == 1; return role?.IdType == 1;

View File

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

View File

@ -94,7 +94,7 @@ namespace AsbCloudWebApi.Controllers
if (InsertForbidAsync is not null) if (InsertForbidAsync is not null)
foreach (var value in values) foreach (var value in values)
if(await InsertForbidAsync(value, token)) if (await InsertForbidAsync(value, token))
return Forbid(); return Forbid();
var result = await service.InsertRangeAsync(values, token).ConfigureAwait(false); var result = await service.InsertRangeAsync(values, token).ConfigureAwait(false);

View File

@ -22,7 +22,7 @@ namespace AsbCloudWebApi.Controllers
where T : IId, IWellRelated where T : IId, IWellRelated
where TService : ICrudWellRelatedService<T> where TService : ICrudWellRelatedService<T>
{ {
private readonly IWellService wellService; protected readonly IWellService wellService;
protected CrudWellRelatedController(IWellService wellService, TService service) protected CrudWellRelatedController(IWellService wellService, TService service)
: base(service) : base(service)
@ -74,7 +74,7 @@ namespace AsbCloudWebApi.Controllers
{ {
var actionResult = await base.GetAsync(id, token); var actionResult = await base.GetAsync(id, token);
var result = actionResult.Value; var result = actionResult.Value;
if(!await UserHasAccesToWellAsync(result.IdWell, token)) if (!await UserHasAccesToWellAsync(result.IdWell, token))
return Forbid(); return Forbid();
return Ok(result); return Ok(result);
} }
@ -113,7 +113,7 @@ namespace AsbCloudWebApi.Controllers
public override async Task<ActionResult<int>> DeleteAsync(int id, CancellationToken token) public override async Task<ActionResult<int>> DeleteAsync(int id, CancellationToken token)
{ {
var item = await service.GetAsync(id, token); var item = await service.GetAsync(id, token);
if(item is null) if (item is null)
return NoContent(); return NoContent();
if (!await UserHasAccesToWellAsync(item.IdWell, token)) if (!await UserHasAccesToWellAsync(item.IdWell, token))
return Forbid(); return Forbid();
@ -130,6 +130,4 @@ namespace AsbCloudWebApi.Controllers
return false; return false;
} }
} }
} }

View File

@ -1,4 +1,5 @@
using AsbCloudApp.Data; using AsbCloudApp.Data;
using AsbCloudApp.Services;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using System; using System;
@ -6,7 +7,6 @@ using System.Collections.Generic;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using AsbCloudApp.Services;
namespace AsbCloudWebApi.Controllers namespace AsbCloudWebApi.Controllers
{ {

View File

@ -22,7 +22,7 @@ namespace AsbCloudWebApi.Controllers
public DrillFlowChartController(IWellService wellService, IDrillFlowChartService service, public DrillFlowChartController(IWellService wellService, IDrillFlowChartService service,
ITelemetryService telemetryService) ITelemetryService telemetryService)
:base(wellService, service) : base(wellService, service)
{ {
this.telemetryService = telemetryService; this.telemetryService = telemetryService;
this.wellService = wellService; this.wellService = wellService;

View File

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

View File

@ -1,12 +1,7 @@
using AsbCloudApp.Data; using Microsoft.AspNetCore.Mvc;
using AsbCloudApp.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using ProtoBuf.Meta; using ProtoBuf.Meta;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudWebApi.Controllers namespace AsbCloudWebApi.Controllers
{ {

View File

@ -1,10 +1,10 @@
using AsbCloudApp.Data; using AsbCloudApp.Data;
using AsbCloudApp.Requests;
using AsbCloudApp.Services; using AsbCloudApp.Services;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading.Tasks;
using System.Threading; using System.Threading;
using AsbCloudApp.Requests; using System.Threading.Tasks;
namespace AsbCloudWebApi.Controllers.SAUB namespace AsbCloudWebApi.Controllers.SAUB
{ {

View File

@ -34,7 +34,7 @@ namespace AsbCloudWebApi.Controllers.SAUB
[AllowAnonymous] [AllowAnonymous]
public IActionResult GetSetpointsNamesByIdWellAsync([FromRoute] int idWell) public IActionResult GetSetpointsNamesByIdWellAsync([FromRoute] int idWell)
{ {
var result = setpointsService.GetSetpointsNames(idWell); var result = setpointsService.GetSetpointsNames();
return Ok(result); return Ok(result);
} }
@ -115,7 +115,7 @@ namespace AsbCloudWebApi.Controllers.SAUB
[AllowAnonymous] [AllowAnonymous]
public async Task<IActionResult> UpdateByTelemetryUidAsync([FromRoute] string uid, int id, SetpointsRequestDto setpointsRequestDto, CancellationToken token = default) 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); .ConfigureAwait(false);
return Ok(result); return Ok(result);
@ -156,7 +156,7 @@ namespace AsbCloudWebApi.Controllers.SAUB
if (idCompany is null || idUser is null) if (idCompany is null || idUser is null)
return Forbid(); return Forbid();
var result = await setpointsService.TryDelete(idWell, id, token) var result = await setpointsService.TryDelete(id, token)
.ConfigureAwait(false); .ConfigureAwait(false);
return Ok(result); return Ok(result);

View File

@ -3,7 +3,6 @@ using AsbCloudApp.Services;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using System; using System;
using System.Collections.Generic;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
@ -12,37 +11,16 @@ namespace AsbCloudWebApi.Controllers
[Route("api/schedule")] [Route("api/schedule")]
[ApiController] [ApiController]
[Authorize] [Authorize]
public class ScheduleController : CrudController<ScheduleDto, IScheduleService> public class ScheduleController : CrudWellRelatedController<ScheduleDto, IScheduleService>
{ {
private readonly IScheduleService scheduleService; private readonly IScheduleService scheduleService;
private readonly IWellService wellService;
public ScheduleController(IScheduleService scheduleService, IWellService wellService) public ScheduleController(IScheduleService scheduleService, IWellService wellService)
:base(scheduleService) : base(wellService, scheduleService)
{ {
this.scheduleService = service; 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>
/// Получить бурильщика работавшего на скважине в определенное время. /// Получить бурильщика работавшего на скважине в определенное время.
/// </summary> /// </summary>
@ -53,11 +31,10 @@ namespace AsbCloudWebApi.Controllers
[HttpGet("driller")] [HttpGet("driller")]
public async Task<ActionResult<DrillerDto>> GetDrillerAsync(int idWell, DateTime workTime, CancellationToken token) public async Task<ActionResult<DrillerDto>> GetDrillerAsync(int idWell, DateTime workTime, CancellationToken token)
{ {
var idCompany = User.GetCompanyId(); if (!await UserHasAccesToWellAsync(idWell, token))
if (idCompany is null || !wellService.IsCompanyInvolvedInWell((int)idCompany, idWell))
return Forbid(); return Forbid();
var result = await scheduleService.GetDrillerAsync(idWell,workTime, token); var result = await scheduleService.GetDrillerAsync(idWell, workTime, token);
return Ok(result); return Ok(result);
} }

View File

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

View File

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

View File

@ -3,7 +3,6 @@ using AsbCloudApp.Services;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;

View File

@ -24,7 +24,8 @@ namespace AsbCloudWebApi
{ {
options.JsonSerializerOptions.NumberHandling = options.JsonSerializerOptions.NumberHandling =
System.Text.Json.Serialization.JsonNumberHandling.AllowNamedFloatingPointLiterals | System.Text.Json.Serialization.JsonNumberHandling.AllowNamedFloatingPointLiterals |
System.Text.Json.Serialization.JsonNumberHandling.AllowReadingFromString;})) System.Text.Json.Serialization.JsonNumberHandling.AllowReadingFromString;
}))
.AddProtoBufNet(); .AddProtoBufNet();
ProtobufModel.EnshureRegistered(); ProtobufModel.EnshureRegistered();

View File

@ -1,10 +1,7 @@
using AsbCloudDb.Model; using AsbCloudDb.Model;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1 namespace ConsoleApp1
{ {

View File

@ -1,12 +1,11 @@
using AsbCloudApp.Data.SAUB;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Net.Http; using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Text; using System.Text;
using System.Text.Json; using System.Text.Json;
using AsbCloudApp.Data; using System.Threading;
using AsbCloudApp.Data.SAUB; using System.Threading.Tasks;
namespace ConsoleApp1 namespace ConsoleApp1
{ {
@ -117,13 +116,13 @@ namespace ConsoleApp1
return dto; 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; 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); var val = (float)(min + Math.Sin(angle) * (max - min) / 2);
return val; return val;

View File

@ -1,13 +1,6 @@
using AsbCloudDb.Model; using AsbCloudDb.Model;
using AsbCloudInfrastructure.Services;
using AsbCloudInfrastructure.Services.Cache;
using AsbCloudInfrastructure.Services.WellOperationService;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1 namespace ConsoleApp1
{ {

View File

@ -1,14 +1,6 @@
using AsbCloudApp.Data; using AsbCloudApp.Data;
using AsbCloudDb.Model;
using AsbCloudInfrastructure.Services;
using AsbCloudInfrastructure.Services.Cache;
using AsbCloudInfrastructure.Services.WellOperationService;
using Microsoft.EntityFrameworkCore;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1 namespace ConsoleApp1
{ {

View File

@ -2,11 +2,10 @@ using Google.Apis.Auth.OAuth2;
using Google.Apis.Auth.OAuth2.Flows; using Google.Apis.Auth.OAuth2.Flows;
using Google.Apis.Auth.OAuth2.Responses; using Google.Apis.Auth.OAuth2.Responses;
using Google.Apis.Drive.v3; using Google.Apis.Drive.v3;
using Google.Apis.Drive.v3.Data;
using Google.Apis.Services; using Google.Apis.Services;
using Google.Apis.Util.Store; using Google.Apis.Util.Store;
using Google.Apis.Drive.v3.Data;
using System.IO; using System.IO;
using System.Collections.Generic;
using System.Linq; using System.Linq;
// usage example at the very bottom // usage example at the very bottom
@ -34,7 +33,7 @@ namespace ConsoleApp1
ClientId = "1020584579240-f7amqg35qg7j94ta1ntgitajq27cgh49.apps.googleusercontent.com", ClientId = "1020584579240-f7amqg35qg7j94ta1ntgitajq27cgh49.apps.googleusercontent.com",
ClientSecret = "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" ClientSecret = "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"
}, },
Scopes = new[] {DriveService.Scope.Drive}, Scopes = new[] { DriveService.Scope.Drive },
DataStore = new FileDataStore(applicationName) DataStore = new FileDataStore(applicationName)
}); });
@ -92,7 +91,7 @@ namespace ConsoleApp1
public void CreatePublicPermissionForFile(string idFile) 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); var addPermissionRequest = service.Permissions.Create(permission, idFile);
addPermissionRequest.Execute(); addPermissionRequest.Execute();
} }

View File

@ -1,9 +1,5 @@
using AsbCloudApp.Data; using AsbCloudInfrastructure.EfCache;
using AsbCloudDb.Model;
using AsbCloudInfrastructure.EfCache;
using Microsoft.EntityFrameworkCore;
using System; using System;
using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
@ -21,7 +17,8 @@ namespace ConsoleApp1
for (int i = 0; i < 24; i++) for (int i = 0; i < 24; i++)
{ {
var t = new Thread(_ => { var t = new Thread(_ =>
{
for (int j = 0; j < 32; j++) for (int j = 0; j < 32; j++)
//Task.Run(GetDataAsync).Wait(); //Task.Run(GetDataAsync).Wait();
GetData(); GetData();
@ -60,7 +57,7 @@ namespace ConsoleApp1
.Where(t => t.IdTelemetry == 135) .Where(t => t.IdTelemetry == 135)
.OrderBy(t => t.DateTime) .OrderBy(t => t.DateTime)
.Take(100_000) .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(); .ToList();
sw.Stop(); sw.Stop();
Console.WriteLine($"{DateTime.Now}\tth: {Thread.CurrentThread.ManagedThreadId}\ttime {sw.ElapsedMilliseconds}\tcount {cs.Count}"); Console.WriteLine($"{DateTime.Now}\tth: {Thread.CurrentThread.ManagedThreadId}\ttime {sw.ElapsedMilliseconds}\tcount {cs.Count}");

View File

@ -1,9 +1,4 @@
using System; using System.Net.Mail;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1 namespace ConsoleApp1
{ {