some rider recommendations and spelling

This commit is contained in:
Фролов 2021-12-07 18:27:52 +05:00
parent 1e9078079a
commit 5752ad40b7
30 changed files with 163 additions and 219 deletions

View File

@ -7,7 +7,7 @@ namespace AsbCloudApp.Services
public interface ICrudService<Tdto> public interface ICrudService<Tdto>
where Tdto : Data.IId where Tdto : Data.IId
{ {
List<string> Incledes { get; } List<string> Includes { get; }
Task<int> InsertAsync(Tdto newItem, CancellationToken token = default); Task<int> InsertAsync(Tdto newItem, CancellationToken token = default);
Task<int> InsertRangeAsync(IEnumerable<Tdto> newItems, CancellationToken token = default); Task<int> InsertRangeAsync(IEnumerable<Tdto> newItems, CancellationToken token = default);
Task<IEnumerable<Tdto>> GetAllAsync(CancellationToken token = default); Task<IEnumerable<Tdto>> GetAllAsync(CancellationToken token = default);

View File

@ -6,8 +6,8 @@ namespace AsbCloudApp.Services
{ {
public interface ITimeZoneService public interface ITimeZoneService
{ {
DateTime DateToUtc(DateTime date, double remoteOTimezoneffsetHours); DateTime DateToUtc(DateTime date, double remoteTimezoneOffsetHours);
DateTime DateToTimeZone(DateTime date, double remoteOTimezoneffsetHours); DateTime DateToTimeZone(DateTime date, double remoteTimezoneOffsetHours);
Task<Data.TelemetryTimeZoneDto> GetByCoordinatesAsync(double latitude, double longitude, CancellationToken token); Task<Data.TelemetryTimeZoneDto> GetByCoordinatesAsync(double latitude, double longitude, CancellationToken token);
} }
} }

View File

@ -12,7 +12,7 @@ namespace AsbCloudApp.Services
Task<PaginationContainer<WellOperationDto>> GetOperationsAsync( Task<PaginationContainer<WellOperationDto>> GetOperationsAsync(
int idWell, int idWell,
int? opertaionType = null, int? operationType = null,
IEnumerable<int> sectionTypeIds = null, IEnumerable<int> sectionTypeIds = null,
IEnumerable<int> operationCategoryIds = null, IEnumerable<int> operationCategoryIds = null,
DateTime begin = default, DateTime begin = default,

View File

@ -26,7 +26,7 @@ namespace AsbCloudInfrastructure
public static IServiceCollection AddInfrastructure(this IServiceCollection services, IConfiguration configuration) public static IServiceCollection AddInfrastructure(this IServiceCollection services, IConfiguration configuration)
{ {
services.AddDbContext<AsbCloudDbContext>(options => services.AddDbContext<AsbCloudDbContext>(options =>
options.UseNpgsql(configuration.GetConnectionString("DefaultConnection")), ServiceLifetime.Scoped); options.UseNpgsql(configuration.GetConnectionString("DefaultConnection")));
services.AddScoped<IAsbCloudDbContext>(provider => provider.GetService<AsbCloudDbContext>()); services.AddScoped<IAsbCloudDbContext>(provider => provider.GetService<AsbCloudDbContext>());
services.AddScoped<IFileShareService, GoogleDriveService>(); services.AddScoped<IFileShareService, GoogleDriveService>();

View File

@ -1,5 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
namespace Mapster namespace Mapster
{ {
@ -7,24 +8,21 @@ namespace Mapster
{ {
public static IEnumerable<TDestination> Adapt<TDestination>(this IEnumerable<object> sourceList) public static IEnumerable<TDestination> Adapt<TDestination>(this IEnumerable<object> sourceList)
{ {
foreach (var item in sourceList) return sourceList.Select(item => item.Adapt<TDestination>());
yield return item.Adapt<TDestination>();
} }
public static TDestination Adapt<TDestination>(this object source, Action<TDestination> afterMapAction = default) public static TDestination Adapt<TDestination>(this object source, Action<TDestination> afterMapAction = default)
{ {
var dest = source.Adapt<TDestination>(); var dest = source.Adapt<TDestination>();
if (afterMapAction != default) afterMapAction?.Invoke(dest);
afterMapAction(dest);
return dest; return dest;
} }
public static TDestination Adapt<TDestination, TSource>(this TSource source, Action<TDestination, TSource> afterMapAction = default) public static TDestination Adapt<TDestination, TSource>(this TSource source, Action<TDestination, TSource> afterMapAction = default)
{ {
var dest = source.Adapt<TDestination>(); var dest = source.Adapt<TDestination>();
if (afterMapAction != default) afterMapAction?.Invoke(dest, source);
afterMapAction(dest, source);
return dest; return dest;
} }
@ -33,8 +31,7 @@ namespace Mapster
foreach (var item in sourceList) foreach (var item in sourceList)
{ {
var dest = item.Adapt<TDestination>(); var dest = item.Adapt<TDestination>();
if (eachAfterMapAction != default) eachAfterMapAction?.Invoke(dest, item);
eachAfterMapAction(dest, item);
yield return dest; yield return dest;
} }

View File

@ -1,11 +1,11 @@
using AsbCloudDb.Model; using System;
using AsbSaubReport.Model;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using AsbCloudDb.Model;
using AsbSaubReport.Model;
using Microsoft.EntityFrameworkCore;
namespace AsbSaubReport namespace AsbCloudInfrastructure
{ {
public class ReportDataSourcePgCloud : IReportDataSource public class ReportDataSourcePgCloud : IReportDataSource
{ {
@ -48,13 +48,13 @@ namespace AsbSaubReport
info = new WellInfoReport info = new WellInfoReport
{ {
Deposit = well.Cluster.Deposit.Caption, Deposit = well?.Cluster?.Deposit?.Caption,
Cluster = well.Cluster.Caption, Cluster = well?.Cluster?.Caption,
Well = well.Caption, Well = well?.Caption,
Customer = well.RelationCompaniesWells.FirstOrDefault(c => c.Company.IdCompanyType == 1)?.Company.Caption, Customer = well?.RelationCompaniesWells.FirstOrDefault(c => c.Company.IdCompanyType == 1)?.Company.Caption,
DrillingStartDate = well.Telemetry?.Info?.DrillingStartDate ?? default, DrillingStartDate = well?.Telemetry?.Info?.DrillingStartDate ?? default,
TimeZoneId = well.Telemetry?.Info?.TimeZoneId ?? default, TimeZoneId = well?.Telemetry?.Info?.TimeZoneId ?? default,
TimeZoneOffsetTotalHours = well.Telemetry?.Info?.TimeZoneOffsetTotalHours ?? default, TimeZoneOffsetTotalHours = well?.Telemetry?.Info?.TimeZoneOffsetTotalHours ?? default,
}; };
} }

View File

@ -26,15 +26,15 @@ namespace AsbCloudInfrastructure.Services
public const string issuer = "a"; public const string issuer = "a";
public const string audience = "a"; public const string audience = "a";
public static readonly SymmetricSecurityKey securityKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("супер секретный ключ для шифрования")); public static readonly SymmetricSecurityKey securityKey = new (Encoding.ASCII.GetBytes("супер секретный ключ для шифрования"));
public const string algorithms = SecurityAlgorithms.HmacSha256; private const string algorithms = SecurityAlgorithms.HmacSha256;
private static readonly TimeSpan expiresTimespan = TimeSpan.FromDays(365.25); private static readonly TimeSpan expiresTimespan = TimeSpan.FromDays(365.25);
private static readonly Encoding encoding = Encoding.UTF8; private static readonly Encoding encoding = Encoding.UTF8;
private const int PasswordSaltLength = 5; private const int PasswordSaltLength = 5;
private const string claimIdUser = "id"; private const string claimIdUser = "id";
private const string claimNameidCompany = "idCompany"; private const string claimNameIdCompany = "idCompany";
private readonly HashAlgorithm hashAlgoritm; private readonly HashAlgorithm hashAlgorithm;
private readonly Random rnd; private readonly Random rnd;
public AuthService(IAsbCloudDbContext db, CacheDb cacheDb) public AuthService(IAsbCloudDbContext db, CacheDb cacheDb)
@ -44,7 +44,7 @@ namespace AsbCloudInfrastructure.Services
cacheUsersUserRoles = cacheDb.GetCachedTable<RelationUserUserRole>((AsbCloudDbContext)db); cacheUsersUserRoles = cacheDb.GetCachedTable<RelationUserUserRole>((AsbCloudDbContext)db);
cachePermissions = cacheDb.GetCachedTable<PermissionInfo>((AsbCloudDbContext)db); cachePermissions = cacheDb.GetCachedTable<PermissionInfo>((AsbCloudDbContext)db);
cacheUserRolesPermissions = cacheDb.GetCachedTable<Permission>((AsbCloudDbContext)db); cacheUserRolesPermissions = cacheDb.GetCachedTable<Permission>((AsbCloudDbContext)db);
hashAlgoritm = SHA384.Create(); hashAlgorithm = SHA384.Create();
rnd = new Random((int)(DateTime.Now.Ticks % 2147480161)); rnd = new Random((int)(DateTime.Now.Ticks % 2147480161));
} }
@ -123,7 +123,7 @@ namespace AsbCloudInfrastructure.Services
try try
{ {
db.SaveChanges(); db.SaveChanges();
db.RelationUserUserRoles.Add(new RelationUserUserRole() db.RelationUserUserRoles.Add(new RelationUserUserRole
{ {
IdUser = newUser.Id, IdUser = newUser.Id,
IdUserRole = 2 IdUserRole = 2
@ -167,8 +167,8 @@ namespace AsbCloudInfrastructure.Services
var now = DateTime.Now; var now = DateTime.Now;
var jwt = new JwtSecurityToken( var jwt = new JwtSecurityToken(
issuer: issuer, issuer,
audience: audience, audience,
notBefore: now, notBefore: now,
claims: claims, claims: claims,
expires: now.Add(expiresTimespan), expires: now.Add(expiresTimespan),
@ -214,14 +214,11 @@ namespace AsbCloudInfrastructure.Services
if (!CheckPassword(user.PasswordHash, password)) if (!CheckPassword(user.PasswordHash, password))
return default; return default;
var userRolesNames = GetUserRoles(user.Id)
.Select(r => r.Caption);
var claims = new List<Claim> var claims = new List<Claim>
{ {
new Claim(claimIdUser, user.Id.ToString()), new (claimIdUser, user.Id.ToString()),
new Claim(ClaimsIdentity.DefaultNameClaimType, user.Login), new (ClaimsIdentity.DefaultNameClaimType, user.Login),
new Claim(claimNameidCompany, user.IdCompany.ToString()), new (claimNameIdCompany, user.IdCompany.ToString()),
}; };
var claimsIdentity = new ClaimsIdentity(claims, "Token", ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType); var claimsIdentity = new ClaimsIdentity(claims, "Token", ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType);
@ -244,18 +241,18 @@ namespace AsbCloudInfrastructure.Services
private string ComputeHash(string salt, string password) private string ComputeHash(string salt, string password)
{ {
var hashBytes = hashAlgoritm.ComputeHash(encoding.GetBytes(salt + password)); var hashBytes = hashAlgorithm.ComputeHash(encoding.GetBytes(salt + password));
var hashString = BitConverter.ToString(hashBytes) var hashString = BitConverter.ToString(hashBytes)
.Replace("-", "") .Replace("-", "")
.ToLower(); .ToLower();
return hashString; return hashString;
} }
public string GenerateSalt() private string GenerateSalt()
{ {
const string saltChars = "sHwiaX7kZT1QRp0cPILGUuK2Sz=9q8lmejDNfoYCE3B_WtgyVv6M5OxAJ4Frbhnd"; const string saltChars = "sHwiaX7kZT1QRp0cPILGUuK2Sz=9q8lmejDNfoYCE3B_WtgyVv6M5OxAJ4Frbhnd";
string salt = ""; var salt = "";
for (int i = 0; i < PasswordSaltLength - 1; i++) for (var i = 0; i < PasswordSaltLength - 1; i++)
salt += saltChars[rnd.Next(0, saltChars.Length)]; salt += saltChars[rnd.Next(0, saltChars.Length)];
salt += "|"; salt += "|";
return salt; return salt;

View File

@ -44,7 +44,8 @@ namespace AsbCloudInfrastructure.Services.Cache
Refresh(false); Refresh(false);
} }
internal CacheTable(DbContext context, CacheTableDataStore data, Func<DbSet<TEntity>, IQueryable<TEntity>> configureDbSet = null) internal CacheTable(DbContext context, CacheTableDataStore data,
Func<DbSet<TEntity>, IQueryable<TEntity>> configureDbSet = null)
{ {
this.context = context; this.context = context;
this.data = data; this.data = data;
@ -57,7 +58,10 @@ namespace AsbCloudInfrastructure.Services.Cache
Refresh(false); Refresh(false);
} }
public TEntity this[int index] { get => cached.ElementAt(index); } public TEntity this[int index]
{
get => cached.ElementAt(index);
}
/// <summary> /// <summary>
/// Runs action like atomic operation. /// Runs action like atomic operation.
@ -87,6 +91,7 @@ namespace AsbCloudInfrastructure.Services.Cache
{ {
semaphore.Release(); semaphore.Release();
} }
return result; return result;
} }
@ -97,7 +102,8 @@ namespace AsbCloudInfrastructure.Services.Cache
/// </summary> /// </summary>
/// <param name="action">(wasFree) => {...}</param> /// <param name="action">(wasFree) => {...}</param>
/// <returns>default if semaphoreTimeout. Or result of func(..)</returns> /// <returns>default if semaphoreTimeout. Or result of func(..)</returns>
private static async Task<T> SyncAsync<T>(Func<bool, CancellationToken, Task<T>> funcAsync, CancellationToken token = default) private static async Task<T> SyncAsync<T>(Func<bool, CancellationToken, Task<T>> funcAsync,
CancellationToken token = default)
{ {
var wasFree = semaphore.CurrentCount > 0; var wasFree = semaphore.CurrentCount > 0;
T result = default; T result = default;
@ -111,7 +117,8 @@ namespace AsbCloudInfrastructure.Services.Cache
} }
catch (Exception ex) catch (Exception ex)
{ {
Trace.WriteLine($"{DateTime.Now:yyyy.MM.dd HH:mm:ss:fff} error in CacheTable<{nameOfTEntity}>.SyncAsync()"); Trace.WriteLine(
$"{DateTime.Now:yyyy.MM.dd HH:mm:ss:fff} error in CacheTable<{nameOfTEntity}>.SyncAsync()");
Trace.WriteLine(ex.Message); Trace.WriteLine(ex.Message);
Trace.WriteLine(ex.StackTrace); Trace.WriteLine(ex.StackTrace);
} }
@ -119,6 +126,7 @@ namespace AsbCloudInfrastructure.Services.Cache
{ {
semaphore.Release(); semaphore.Release();
} }
return result; return result;
} }
@ -133,6 +141,7 @@ namespace AsbCloudInfrastructure.Services.Cache
cached.AddRange(entities); cached.AddRange(entities);
data.LastResreshDate = DateTime.Now; data.LastResreshDate = DateTime.Now;
} }
return cached.Count; return cached.Count;
} }
@ -148,18 +157,20 @@ namespace AsbCloudInfrastructure.Services.Cache
cached.AddRange(entities); cached.AddRange(entities);
data.LastResreshDate = DateTime.Now; data.LastResreshDate = DateTime.Now;
} }
return cached.Count; return cached.Count;
} }
public int Refresh(bool force) public int Refresh(bool force)
=> Sync((wasFree) => wasFree ? InternalRefresh(force) : 0); => Sync((wasFree) => wasFree ? InternalRefresh(force) : 0);
public Task<int> RefreshAsync(bool force, CancellationToken token = default) public Task<int> RefreshAsync(bool force, CancellationToken token = default)
{ {
return SyncAsync(async (wasFree, token) => return SyncAsync(
{ async (wasFree, token) =>
return wasFree ? await InternalRefreshAsync(force, token).ConfigureAwait(false) : 0; {
}, token); return wasFree ? await InternalRefreshAsync(force, token).ConfigureAwait(false) : 0;
}, token);
} }
public bool Contains(Func<TEntity, bool> predicate) public bool Contains(Func<TEntity, bool> predicate)
@ -169,22 +180,22 @@ namespace AsbCloudInfrastructure.Services.Cache
=> await FirstOrDefaultAsync(predicate, token) != default; => await FirstOrDefaultAsync(predicate, token) != default;
public TEntity GetOrCreate(Func<TEntity, bool> predicate, Func<TEntity> makeNew) public TEntity GetOrCreate(Func<TEntity, bool> predicate, Func<TEntity> makeNew)
=> Sync(wasFree => => Sync(wasFree =>
{ {
var result = cached.FirstOrDefault(predicate); var result = cached.FirstOrDefault(predicate);
if (result != default) if (result != default)
return result; return result;
InternalRefresh(true); InternalRefresh(true);
result = cached.FirstOrDefault(predicate); result = cached.FirstOrDefault(predicate);
if (result != default) if (result != default)
return result; return result;
var entry = dbSet.Add(makeNew()); var entry = dbSet.Add(makeNew());
context.SaveChanges(); context.SaveChanges();
InternalRefresh(true); InternalRefresh(true);
return entry.Entity; return entry.Entity;
}); });
public TEntity FirstOrDefault() public TEntity FirstOrDefault()
{ {
@ -278,17 +289,17 @@ namespace AsbCloudInfrastructure.Services.Cache
} }
public Task<int> UpsertAsync(TEntity entity, CancellationToken token = default) public Task<int> UpsertAsync(TEntity entity, CancellationToken token = default)
=> SyncAsync(async (wasFree, token) => => SyncAsync(async (wasFree, token) =>
{ {
if (dbSet.Contains(entity)) if (dbSet.Contains(entity))
dbSet.Update(entity); dbSet.Update(entity);
else else
dbSet.Add(entity); dbSet.Add(entity);
var affected = await context.SaveChangesAsync(token).ConfigureAwait(false); var affected = await context.SaveChangesAsync(token).ConfigureAwait(false);
if (affected > 0) if (affected > 0)
await InternalRefreshAsync(true, token).ConfigureAwait(false); await InternalRefreshAsync(true, token).ConfigureAwait(false);
return affected; return affected;
}, token); }, token);
public int Upsert(IEnumerable<TEntity> entities) public int Upsert(IEnumerable<TEntity> entities)
{ {
@ -304,6 +315,7 @@ namespace AsbCloudInfrastructure.Services.Cache
else else
dbSet.Add(entity); dbSet.Add(entity);
} }
var affected = context.SaveChanges(); var affected = context.SaveChanges();
if (affected > 0) if (affected > 0)
InternalRefresh(true); InternalRefresh(true);
@ -326,6 +338,7 @@ namespace AsbCloudInfrastructure.Services.Cache
else else
dbSet.Add(entity); dbSet.Add(entity);
} }
var affected = await context.SaveChangesAsync(token).ConfigureAwait(false); var affected = await context.SaveChangesAsync(token).ConfigureAwait(false);
if (affected > 0) if (affected > 0)
await InternalRefreshAsync(true, token).ConfigureAwait(false); await InternalRefreshAsync(true, token).ConfigureAwait(false);
@ -334,7 +347,7 @@ namespace AsbCloudInfrastructure.Services.Cache
} }
public int Remove(Func<TEntity, bool> predicate) public int Remove(Func<TEntity, bool> predicate)
=> Sync(_ => => Sync(_ =>
{ {
dbSet.RemoveRange(dbSet.Where(predicate)); dbSet.RemoveRange(dbSet.Where(predicate));
var affected = context.SaveChanges(); var affected = context.SaveChanges();
@ -368,25 +381,25 @@ namespace AsbCloudInfrastructure.Services.Cache
public Task<TEntity> InsertAsync(TEntity entity, CancellationToken token = default) public Task<TEntity> InsertAsync(TEntity entity, CancellationToken token = default)
{ {
return SyncAsync(async (wasFree, token) => return SyncAsync(async (wasFree, token) =>
{ {
var entry = dbSet.Add(entity); var entry = dbSet.Add(entity);
var affected = await context.SaveChangesAsync(token).ConfigureAwait(false); var affected = await context.SaveChangesAsync(token).ConfigureAwait(false);
if (affected > 0) if (affected > 0)
await InternalRefreshAsync(true, token).ConfigureAwait(false); await InternalRefreshAsync(true, token).ConfigureAwait(false);
return entry.Entity; return entry.Entity;
}, token); }, token);
} }
public int Insert(IEnumerable<TEntity> newEntities) public int Insert(IEnumerable<TEntity> newEntities)
{ {
return Sync(_ => return Sync(_ =>
{ {
dbSet.AddRange(newEntities); dbSet.AddRange(newEntities);
var affected = context.SaveChanges(); var affected = context.SaveChanges();
if (affected > 0) if (affected > 0)
InternalRefresh(true); InternalRefresh(true);
return affected; return affected;
}); });
} }
public Task<int> InsertAsync(IEnumerable<TEntity> newEntities, CancellationToken token = default) public Task<int> InsertAsync(IEnumerable<TEntity> newEntities, CancellationToken token = default)
@ -405,4 +418,4 @@ namespace AsbCloudInfrastructure.Services.Cache
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
} }
} }

View File

@ -18,7 +18,7 @@ namespace AsbCloudInfrastructure.Services
protected readonly IAsbCloudDbContext context; protected readonly IAsbCloudDbContext context;
protected readonly DbSet<TModel> dbSet; protected readonly DbSet<TModel> dbSet;
public List<string> Incledes { get; } = new List<string>(); public List<string> Includes { get; } = new List<string>();
public CrudServiceBase(IAsbCloudDbContext context) public CrudServiceBase(IAsbCloudDbContext context)
{ {
@ -139,7 +139,7 @@ namespace AsbCloudInfrastructure.Services
private IQueryable<TModel> GetQueryWithIncludes() private IQueryable<TModel> GetQueryWithIncludes()
{ {
IQueryable<TModel> query = dbSet; IQueryable<TModel> query = dbSet;
foreach (var include in Incledes) foreach (var include in Includes)
query = query.Include(include); query = query.Include(include);
return query; return query;
} }

View File

@ -26,7 +26,7 @@ namespace AsbCloudInfrastructure.Services
if (!dtos.Any()) if (!dtos.Any())
return; return;
var telemetryId = telemetryService.GetOrCreateTemetryIdByUid(uid); var telemetryId = telemetryService.GetOrCreateTelemetryIdByUid(uid);
var entities = dtos.Select(dto => new TelemetryEvent var entities = dtos.Select(dto => new TelemetryEvent
{ {

View File

@ -171,7 +171,7 @@ namespace AsbCloudInfrastructure.Services
if (!dtos.Any()) if (!dtos.Any())
return null; return null;
var telemetryId = telemetryService.GetOrCreateTemetryIdByUid(uid); var telemetryId = telemetryService.GetOrCreateTelemetryIdByUid(uid);
var maxDateDto = dtos.Max(m => m.Date); var maxDateDto = dtos.Max(m => m.Date);
telemetryService.SaveRequestDate(uid, maxDateDto); telemetryService.SaveRequestDate(uid, maxDateDto);

View File

@ -61,7 +61,7 @@ namespace AsbCloudInfrastructure.Services
public async Task<IEnumerable<SetpointsRequestDto>> GetForPanelAsync(string uid, CancellationToken token) public async Task<IEnumerable<SetpointsRequestDto>> GetForPanelAsync(string uid, CancellationToken token)
{ {
var idWell = telemetryService.GetidWellByTelemetryUid(uid) ?? -1; var idWell = telemetryService.GetIdWellByTelemetryUid(uid) ?? -1;
if (idWell < 0) if (idWell < 0)
return null; return null;
@ -91,7 +91,7 @@ namespace AsbCloudInfrastructure.Services
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 idWell = telemetryService.GetIdWellByTelemetryUid(uid) ?? -1;
if (idWell < 0) if (idWell < 0)
return 0; return 0;

View File

@ -40,7 +40,7 @@ namespace AsbCloudInfrastructure.Services
if (dtos == default || !dtos.Any()) if (dtos == default || !dtos.Any())
return 0; return 0;
var idTelemetry = telemetryService.GetOrCreateTemetryIdByUid(uid); var idTelemetry = telemetryService.GetOrCreateTelemetryIdByUid(uid);
var lastTelemetryDate = telemetryService.GetLastTelemetryDate(uid); var lastTelemetryDate = telemetryService.GetLastTelemetryDate(uid);
var dtosList = dtos.OrderBy(d => d.Date).ToList(); var dtosList = dtos.OrderBy(d => d.Date).ToList();

View File

@ -43,14 +43,13 @@ namespace AsbCloudInfrastructure.Services
public IEnumerable<TelemetryDto> GetTransmittingTelemetries() public IEnumerable<TelemetryDto> GetTransmittingTelemetries()
{ {
var telemetryDtos = new List<TelemetryDto>(); var telemetryDtos = new List<TelemetryDto>();
IEnumerable<string> activeTelemetriesUids = telemetryTracker.GetTransmittingTelemetriesUids(); var activeTelemetriesUids = telemetryTracker.GetTransmittingTelemetriesUids();
if (activeTelemetriesUids.Any()) if (!activeTelemetriesUids.Any())
{ return telemetryDtos;
var telemetries = cacheTelemetry var telemetries = cacheTelemetry
.Where(t => activeTelemetriesUids.Contains(t.RemoteUid)); .Where(t => activeTelemetriesUids.Contains(t.RemoteUid));
telemetryDtos = telemetries.Adapt<TelemetryDto>().ToList(); telemetryDtos = telemetries.Adapt<TelemetryDto>().ToList();
}
return telemetryDtos; return telemetryDtos;
} }
@ -174,10 +173,7 @@ namespace AsbCloudInfrastructure.Services
public int? GetIdTelemetryByIdWell(int idWell) public int? GetIdTelemetryByIdWell(int idWell)
{ {
var well = cacheWells.FirstOrDefault(w => w.Id == idWell); var well = cacheWells.FirstOrDefault(w => w.Id == idWell);
if (well is null) return well?.IdTelemetry;
return null;
return well.IdTelemetry;
} }
private async Task<(double latitude, double longitude)?> GetWellCoordinatesAsync(int idWell, private async Task<(double latitude, double longitude)?> GetWellCoordinatesAsync(int idWell,

View File

@ -78,14 +78,14 @@ namespace AsbCloudInfrastructure.Services
.ToListAsync() .ToListAsync()
.ConfigureAwait(false); .ConfigureAwait(false);
var oldReqs = dates.Select(t => new var oldRequests = dates.Select(t => new
{ {
Uid = cacheTelemetry.FirstOrDefault(c => c.Id == t.IdTelemetry)?.RemoteUid, Uid = cacheTelemetry.FirstOrDefault(c => c.Id == t.IdTelemetry)?.RemoteUid,
t.DateMax, t.DateMax,
t.DateMin, t.DateMin,
}).Where(s => !string.IsNullOrEmpty(s.Uid)); }).Where(s => !string.IsNullOrEmpty(s.Uid));
foreach (var oldReq in oldReqs) foreach (var oldReq in oldRequests)
{ {
var telemetryStat = telemetriesStats.GetOrAdd(oldReq.Uid, (uid) => new TrackerStat { RemoteUid = uid }); var telemetryStat = telemetriesStats.GetOrAdd(oldReq.Uid, (uid) => new TrackerStat { RemoteUid = uid });
telemetryStat.TelemetryDateMin = oldReq.DateMin; telemetryStat.TelemetryDateMin = oldReq.DateMin;
@ -116,7 +116,7 @@ namespace AsbCloudInfrastructure.Services
public void SaveRequestDate(string uid, DateTime remoteDate) public void SaveRequestDate(string uid, DateTime remoteDate)
{ {
var stat = telemetriesStats.GetOrAdd(uid, (uid) => new TrackerStat { var stat = telemetriesStats.GetOrAdd(uid, _ => new TrackerStat {
RemoteUid = uid, RemoteUid = uid,
TelemetryDateMin = remoteDate} TelemetryDateMin = remoteDate}
); );

View File

@ -24,7 +24,7 @@ namespace AsbCloudInfrastructure.Services
if (!dtos.Any()) if (!dtos.Any())
return; return;
var telemetryId = telemetryService.GetOrCreateTemetryIdByUid(uid); var telemetryId = telemetryService.GetOrCreateTelemetryIdByUid(uid);
var entities = dtos.Distinct(new TelemetryUserDtoComparer()).Select(dto => new TelemetryUser var entities = dtos.Distinct(new TelemetryUserDtoComparer()).Select(dto => new TelemetryUser
{ {

View File

@ -10,7 +10,7 @@ namespace AsbCloudInfrastructure.Services
{ {
public class TimeZoneService : ITimeZoneService public class TimeZoneService : ITimeZoneService
{ {
class TimeZoneInfo private class TimeZoneInfo
{ {
public string Sunrise { get; set; } public string Sunrise { get; set; }
public double Lng { get; set; } public double Lng { get; set; }
@ -25,8 +25,8 @@ namespace AsbCloudInfrastructure.Services
public string Time { get; set; } public string Time { get; set; }
} }
private readonly string timeZoneApiUrl = "http://api.geonames.org/timezoneJSON"; private const string timeZoneApiUrl = "http://api.geonames.org/timezoneJSON";
private readonly string timezoneApiUserName = "asbautodrilling"; private const string timezoneApiUserName = "asbautodrilling";
public async Task<TelemetryTimeZoneDto> GetByCoordinatesAsync(double latitude, double longitude, CancellationToken token) public async Task<TelemetryTimeZoneDto> GetByCoordinatesAsync(double latitude, double longitude, CancellationToken token)
{ {

View File

@ -16,11 +16,11 @@ namespace AsbCloudInfrastructure.Services
private readonly CacheTable<UserRole> cacheUserRoles; private readonly CacheTable<UserRole> cacheUserRoles;
private readonly IPermissionService permissionService; private readonly IPermissionService permissionService;
public List<string> Incledes { get; } = new(); public List<string> Includes { get; } = new();
public UserRoleService(IAsbCloudDbContext context, CacheDb cacheDb, IPermissionService permissionService) public UserRoleService(IAsbCloudDbContext context, CacheDb cacheDb, IPermissionService permissionService)
{ {
cacheUserRoles = cacheDb.GetCachedTable<UserRole>((AsbCloudDbContext)context, new string[] { nameof(UserRole.Permissions) }); cacheUserRoles = cacheDb.GetCachedTable<UserRole>((AsbCloudDbContext)context, new [] { nameof(UserRole.Permissions) });
this.permissionService = permissionService; this.permissionService = permissionService;
} }
@ -44,14 +44,13 @@ namespace AsbCloudInfrastructure.Services
{ {
var entity = dto.Adapt<UserRole>(); var entity = dto.Adapt<UserRole>();
var updatedEntity = await cacheUserRoles.InsertAsync(entity, token).ConfigureAwait(false); var updatedEntity = await cacheUserRoles.InsertAsync(entity, token).ConfigureAwait(false);
if (dto.Permissions?.Any() == true) if (dto.Permissions?.Any() != true)
{ return updatedEntity?.Id ?? 0;
foreach (var permission in dto.Permissions) foreach (var permission in dto.Permissions)
permission.IdUserRole = updatedEntity.Id; permission.IdUserRole = updatedEntity.Id;
await permissionService.InsertRangeAsync(dto.Permissions, token).ConfigureAwait(false); await permissionService.InsertRangeAsync(dto.Permissions, token).ConfigureAwait(false);
await cacheUserRoles.RefreshAsync(true, token) await cacheUserRoles.RefreshAsync(true, token)
.ConfigureAwait(false); .ConfigureAwait(false);
}
return updatedEntity?.Id ?? 0; return updatedEntity?.Id ?? 0;
} }
@ -91,22 +90,21 @@ namespace AsbCloudInfrastructure.Services
private IEnumerable<Permission> GetNestedPermissions(UserRole role, int counter = 10) private IEnumerable<Permission> GetNestedPermissions(UserRole role, int counter = 10)
{ {
List<Permission> permissions = role.Permissions.ToList(); var permissions = role.Permissions.ToList();
if (role.IdParent is not null) if (role.IdParent is null)
return permissions;
if (counter == 0)
{ {
if (counter == 0) Trace.WriteLine($"User role with id: {role.Id} has more than 10 nested childs");
{ return permissions;
Trace.WriteLine($"User role with id: {role.Id} has more than 10 nested childs");
return permissions;
}
var parentRole = cacheUserRoles.FirstOrDefault(r => r.Id == role.IdParent);
if (parentRole is null)
return permissions;
var parentPermissions = GetNestedPermissions(parentRole, counter--);
Merge(ref permissions, parentPermissions);
} }
var parentRole = cacheUserRoles.FirstOrDefault(r => r.Id == role.IdParent);
if (parentRole is null)
return permissions;
var parentPermissions = GetNestedPermissions(parentRole, --counter);
Merge(ref permissions, parentPermissions);
return permissions; return permissions;
} }

View File

@ -3,10 +3,8 @@ using AsbCloudApp.Services;
using AsbCloudDb.Model; using AsbCloudDb.Model;
using Mapster; using Mapster;
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; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
@ -37,7 +35,7 @@ namespace AsbCloudInfrastructure.Services
.Where(c => c.IdWell == idWell)); .Where(c => c.IdWell == idWell));
var entities = wellComposites var entities = wellComposites
.Adapt<WellComposite, WellCompositeDto>((s, d) => { s.IdWell = idWell; }); .Adapt<WellComposite, WellCompositeDto>((s, _) => { s.IdWell = idWell; });
context.WellComposites.AddRange(entities); context.WellComposites.AddRange(entities);
return context.SaveChangesAsync(token); return context.SaveChangesAsync(token);

View File

@ -50,7 +50,7 @@ namespace AsbCloudInfrastructure.Services.WellOperationService
public async Task<ClusterRopStatDto> GetRopStatByUidAsync(string uid, public async Task<ClusterRopStatDto> GetRopStatByUidAsync(string uid,
CancellationToken token) CancellationToken token)
{ {
var idWell = telemetryService.GetidWellByTelemetryUid(uid); var idWell = telemetryService.GetIdWellByTelemetryUid(uid);
if (idWell is null) if (idWell is null)
return null; return null;

View File

@ -34,17 +34,10 @@ namespace AsbCloudInfrastructure.Services.WellOperationService
private readonly IAsbCloudDbContext db; private readonly IAsbCloudDbContext db;
private List<WellOperationCategory> categories = null; private List<WellOperationCategory> categories = null;
public List<WellOperationCategory> Categories public List<WellOperationCategory> Categories =>
{ categories ?? (categories = db.WellOperationCategories
get .AsNoTracking()
{ .ToList());
if (categories is null)
categories = db.WellOperationCategories
.AsNoTracking()
.ToList();
return categories;
}
}
private List<WellSectionType> sections = null; private List<WellSectionType> sections = null;
public List<WellSectionType> Sections public List<WellSectionType> Sections

View File

@ -17,7 +17,7 @@ namespace AsbCloudInfrastructure.Services.WellOperationService
private readonly IAsbCloudDbContext context; private readonly IAsbCloudDbContext context;
private readonly CacheTable<WellOperationCategory> cachedOperationCategories; private readonly CacheTable<WellOperationCategory> cachedOperationCategories;
public WellOperationService(IAsbCloudDbContext context, Cache.CacheDb cache) public WellOperationService(IAsbCloudDbContext context, CacheDb cache)
{ {
this.context = context; this.context = context;
cachedOperationCategories = cache.GetCachedTable<WellOperationCategory>((DbContext)context); cachedOperationCategories = cache.GetCachedTable<WellOperationCategory>((DbContext)context);
@ -35,7 +35,7 @@ namespace AsbCloudInfrastructure.Services.WellOperationService
public async Task<PaginationContainer<WellOperationDto>> GetOperationsAsync( public async Task<PaginationContainer<WellOperationDto>> GetOperationsAsync(
int idWell, int idWell,
int? opertaionType = default, int? operationType = default,
IEnumerable<int> sectionTypeIds = default, IEnumerable<int> sectionTypeIds = default,
IEnumerable<int> operationCategoryIds = default, IEnumerable<int> operationCategoryIds = default,
DateTime begin = default, DateTime begin = default,
@ -51,10 +51,10 @@ namespace AsbCloudInfrastructure.Services.WellOperationService
.Include(s => s.OperationCategory) .Include(s => s.OperationCategory)
.Where(s => s.IdWell == idWell); .Where(s => s.IdWell == idWell);
if (opertaionType != default) if (operationType != default)
query = query.Where(e => e.IdType == (int)opertaionType); query = query.Where(e => e.IdType == (int)operationType);
if ((sectionTypeIds != default) && sectionTypeIds.Any()) if (sectionTypeIds != default && sectionTypeIds.Any())
query = query.Where(e => sectionTypeIds.Contains(e.IdWellSectionType)); query = query.Where(e => sectionTypeIds.Contains(e.IdWellSectionType));
if (operationCategoryIds != default && operationCategoryIds.Any()) if (operationCategoryIds != default && operationCategoryIds.Any())

View File

@ -1,48 +0,0 @@
//using AsbCloudApp.Data;
//using AsbCloudApp.Services;
//using AsbCloudDb.Model;
//using AsbCloudInfrastructure.Services.Cache;
//using Mapster;
//using Microsoft.EntityFrameworkCore;
//using System;
//using System.Linq;
//using System.Threading;
//using System.Threading.Tasks;
//namespace AsbCloudInfrastructure.Services
//{
// public class _CachedCrudService<Tdto, TModel> : ICachedCrudService<Tdto>
// where TModel : class, AsbCloudDb.Model.IId
// where Tdto : AsbCloudApp.Data.IId
// {
// private readonly CacheTable<TModel> cache;
// public _CachedCrudService(IAsbCloudDbContext db, Cache.CacheDb cacheDb)
// {
// cache = cacheDb.GetCachedTable<TModel>((DbContext)db);
// }
// public virtual async Task<PaginationContainer<Tdto>> GetAsync(int skip = 0, int take = 32, CancellationToken token = default)
// {
// var count = cache.Count();
// var result = new PaginationContainer<Tdto> { Skip = skip, Take = take, Count = count };
// if (count <= skip)
// return result;
// var items = await cache.WhereAsync(token).ConfigureAwait(false);
// result.Items.AddRange(items.OrderBy(i => i.Id).Skip(skip).Take(take).Select(i => Convert(i)));
// return result;
// }
// public virtual Task<Tdto> GetAsync(int id, CancellationToken token = default)
// {
// throw new NotImplementedException();
// }
// public virtual Tdto Convert(TModel src) => src.Adapt<Tdto>();
// public virtual TModel Convert(Tdto src) => src.Adapt<TModel>();
// }
//}

View File

@ -13,7 +13,7 @@ namespace AsbCloudWebApi.Controllers
public AdminClusterController(ICrudService<ClusterDto> service) public AdminClusterController(ICrudService<ClusterDto> service)
:base(service) :base(service)
{ {
service.Incledes.Add("Wells"); service.Includes.Add("Wells");
} }
} }
} }

View File

@ -13,7 +13,7 @@ namespace AsbCloudWebApi.Controllers
public AdminDepositController(ICrudService<DepositDto> service) public AdminDepositController(ICrudService<DepositDto> service)
:base(service) :base(service)
{ {
service.Incledes.Add("Clusters"); service.Includes.Add("Clusters");
} }
} }
} }

View File

@ -18,7 +18,7 @@ namespace AsbCloudWebApi.Controllers
ITelemetryService telemetryService) ITelemetryService telemetryService)
: base(service) : base(service)
{ {
service.Incledes.Add("Well"); service.Includes.Add("Well");
this.telemetryService = telemetryService; this.telemetryService = telemetryService;
} }
@ -27,7 +27,7 @@ namespace AsbCloudWebApi.Controllers
[Route("/reduntentUids")] [Route("/reduntentUids")]
public IActionResult GetRedundentRemoteUids() public IActionResult GetRedundentRemoteUids()
{ {
var result = telemetryService.GetRedundentRemoteUids().Select(i => new { i.Key, ids = i.Ids }); var result = telemetryService.GetRedundantRemoteUids().Select(i => new { i.Key, ids = i.Ids });
return Ok(result); return Ok(result);
} }

View File

@ -13,7 +13,7 @@ namespace AsbCloudWebApi.Controllers
public AdminWellController(ICrudService<WellDto> service) public AdminWellController(ICrudService<WellDto> service)
:base(service) :base(service)
{ {
service.Incledes.Add("Telemetry"); service.Includes.Add("Telemetry");
} }
} }
} }

View File

@ -66,7 +66,7 @@ namespace AsbCloudWebApi.Controllers
[ProducesResponseType(typeof(IEnumerable<DrillFlowChartDto>), (int) System.Net.HttpStatusCode.OK)] [ProducesResponseType(typeof(IEnumerable<DrillFlowChartDto>), (int) System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> GetByTelemetryAsync(string uid, DateTime updateFrom = default, CancellationToken token = default) public async Task<IActionResult> GetByTelemetryAsync(string uid, DateTime updateFrom = default, CancellationToken token = default)
{ {
var idWell = telemetryService.GetidWellByTelemetryUid(uid); var idWell = telemetryService.GetIdWellByTelemetryUid(uid);
if (idWell is null) if (idWell is null)
return BadRequest($"Wrong uid {uid}"); return BadRequest($"Wrong uid {uid}");

View File

@ -83,7 +83,7 @@ namespace AsbCloudWebApi.Controllers
public async Task<IActionResult> PostMessagesAsync(string uid, [FromBody] IEnumerable<TelemetryMessageDto> dtos, public async Task<IActionResult> PostMessagesAsync(string uid, [FromBody] IEnumerable<TelemetryMessageDto> dtos,
CancellationToken token = default) CancellationToken token = default)
{ {
var idWell = telemetryService.GetidWellByTelemetryUid(uid); var idWell = telemetryService.GetIdWellByTelemetryUid(uid);
await messageService.InsertAsync(uid, dtos, token).ConfigureAwait(false); await messageService.InsertAsync(uid, dtos, token).ConfigureAwait(false);
if (dtos.Any()) if (dtos.Any())

View File

@ -52,7 +52,7 @@ namespace AsbCloudWebApi.Controllers
{ {
await telemetryDataService.UpdateDataAsync(uid, dtos, token).ConfigureAwait(false); await telemetryDataService.UpdateDataAsync(uid, dtos, token).ConfigureAwait(false);
var idWell = telemetryService.GetidWellByTelemetryUid(uid); var idWell = telemetryService.GetIdWellByTelemetryUid(uid);
if (idWell != null && dtos.Any()) if (idWell != null && dtos.Any())
await Task.Run(() => telemetryHubContext.Clients.Group($"well_{idWell}") await Task.Run(() => telemetryHubContext.Clients.Group($"well_{idWell}")
.SendAsync(SirnalRMethodGetDataName, dtos), token).ConfigureAwait(false); .SendAsync(SirnalRMethodGetDataName, dtos), token).ConfigureAwait(false);