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>
where Tdto : Data.IId
{
List<string> Incledes { get; }
List<string> Includes { get; }
Task<int> InsertAsync(Tdto newItem, CancellationToken token = default);
Task<int> InsertRangeAsync(IEnumerable<Tdto> newItems, CancellationToken token = default);
Task<IEnumerable<Tdto>> GetAllAsync(CancellationToken token = default);

View File

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

View File

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

View File

@ -26,7 +26,7 @@ namespace AsbCloudInfrastructure
public static IServiceCollection AddInfrastructure(this IServiceCollection services, IConfiguration configuration)
{
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<IFileShareService, GoogleDriveService>();

View File

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

View File

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

View File

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

View File

@ -44,7 +44,8 @@ namespace AsbCloudInfrastructure.Services.Cache
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.data = data;
@ -57,7 +58,10 @@ namespace AsbCloudInfrastructure.Services.Cache
Refresh(false);
}
public TEntity this[int index] { get => cached.ElementAt(index); }
public TEntity this[int index]
{
get => cached.ElementAt(index);
}
/// <summary>
/// Runs action like atomic operation.
@ -87,6 +91,7 @@ namespace AsbCloudInfrastructure.Services.Cache
{
semaphore.Release();
}
return result;
}
@ -97,7 +102,8 @@ namespace AsbCloudInfrastructure.Services.Cache
/// </summary>
/// <param name="action">(wasFree) => {...}</param>
/// <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;
T result = default;
@ -111,7 +117,8 @@ namespace AsbCloudInfrastructure.Services.Cache
}
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.StackTrace);
}
@ -119,6 +126,7 @@ namespace AsbCloudInfrastructure.Services.Cache
{
semaphore.Release();
}
return result;
}
@ -133,6 +141,7 @@ namespace AsbCloudInfrastructure.Services.Cache
cached.AddRange(entities);
data.LastResreshDate = DateTime.Now;
}
return cached.Count;
}
@ -148,18 +157,20 @@ namespace AsbCloudInfrastructure.Services.Cache
cached.AddRange(entities);
data.LastResreshDate = DateTime.Now;
}
return cached.Count;
}
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)
{
return SyncAsync(async (wasFree, token) =>
{
return wasFree ? await InternalRefreshAsync(force, token).ConfigureAwait(false) : 0;
}, token);
return SyncAsync(
async (wasFree, token) =>
{
return wasFree ? await InternalRefreshAsync(force, token).ConfigureAwait(false) : 0;
}, token);
}
public bool Contains(Func<TEntity, bool> predicate)
@ -169,22 +180,22 @@ namespace AsbCloudInfrastructure.Services.Cache
=> await FirstOrDefaultAsync(predicate, token) != default;
public TEntity GetOrCreate(Func<TEntity, bool> predicate, Func<TEntity> makeNew)
=> Sync(wasFree =>
{
var result = cached.FirstOrDefault(predicate);
if (result != default)
return result;
=> Sync(wasFree =>
{
var result = cached.FirstOrDefault(predicate);
if (result != default)
return result;
InternalRefresh(true);
result = cached.FirstOrDefault(predicate);
if (result != default)
return result;
InternalRefresh(true);
result = cached.FirstOrDefault(predicate);
if (result != default)
return result;
var entry = dbSet.Add(makeNew());
context.SaveChanges();
InternalRefresh(true);
return entry.Entity;
});
var entry = dbSet.Add(makeNew());
context.SaveChanges();
InternalRefresh(true);
return entry.Entity;
});
public TEntity FirstOrDefault()
{
@ -278,17 +289,17 @@ namespace AsbCloudInfrastructure.Services.Cache
}
public Task<int> UpsertAsync(TEntity entity, CancellationToken token = default)
=> SyncAsync(async (wasFree, token) =>
{
if (dbSet.Contains(entity))
dbSet.Update(entity);
else
dbSet.Add(entity);
var affected = await context.SaveChangesAsync(token).ConfigureAwait(false);
if (affected > 0)
await InternalRefreshAsync(true, token).ConfigureAwait(false);
return affected;
}, token);
=> SyncAsync(async (wasFree, token) =>
{
if (dbSet.Contains(entity))
dbSet.Update(entity);
else
dbSet.Add(entity);
var affected = await context.SaveChangesAsync(token).ConfigureAwait(false);
if (affected > 0)
await InternalRefreshAsync(true, token).ConfigureAwait(false);
return affected;
}, token);
public int Upsert(IEnumerable<TEntity> entities)
{
@ -304,6 +315,7 @@ namespace AsbCloudInfrastructure.Services.Cache
else
dbSet.Add(entity);
}
var affected = context.SaveChanges();
if (affected > 0)
InternalRefresh(true);
@ -326,6 +338,7 @@ namespace AsbCloudInfrastructure.Services.Cache
else
dbSet.Add(entity);
}
var affected = await context.SaveChangesAsync(token).ConfigureAwait(false);
if (affected > 0)
await InternalRefreshAsync(true, token).ConfigureAwait(false);
@ -334,7 +347,7 @@ namespace AsbCloudInfrastructure.Services.Cache
}
public int Remove(Func<TEntity, bool> predicate)
=> Sync(_ =>
=> Sync(_ =>
{
dbSet.RemoveRange(dbSet.Where(predicate));
var affected = context.SaveChanges();
@ -368,25 +381,25 @@ namespace AsbCloudInfrastructure.Services.Cache
public Task<TEntity> InsertAsync(TEntity entity, CancellationToken token = default)
{
return SyncAsync(async (wasFree, token) =>
{
var entry = dbSet.Add(entity);
var affected = await context.SaveChangesAsync(token).ConfigureAwait(false);
if (affected > 0)
await InternalRefreshAsync(true, token).ConfigureAwait(false);
return entry.Entity;
}, token);
{
var entry = dbSet.Add(entity);
var affected = await context.SaveChangesAsync(token).ConfigureAwait(false);
if (affected > 0)
await InternalRefreshAsync(true, token).ConfigureAwait(false);
return entry.Entity;
}, token);
}
public int Insert(IEnumerable<TEntity> newEntities)
{
return Sync(_ =>
{
dbSet.AddRange(newEntities);
var affected = context.SaveChanges();
if (affected > 0)
InternalRefresh(true);
return affected;
});
{
dbSet.AddRange(newEntities);
var affected = context.SaveChanges();
if (affected > 0)
InternalRefresh(true);
return affected;
});
}
public Task<int> InsertAsync(IEnumerable<TEntity> newEntities, CancellationToken token = default)
@ -405,4 +418,4 @@ namespace AsbCloudInfrastructure.Services.Cache
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
}
}

View File

@ -18,7 +18,7 @@ namespace AsbCloudInfrastructure.Services
protected readonly IAsbCloudDbContext context;
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)
{
@ -139,7 +139,7 @@ namespace AsbCloudInfrastructure.Services
private IQueryable<TModel> GetQueryWithIncludes()
{
IQueryable<TModel> query = dbSet;
foreach (var include in Incledes)
foreach (var include in Includes)
query = query.Include(include);
return query;
}

View File

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

View File

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

View File

@ -61,7 +61,7 @@ namespace AsbCloudInfrastructure.Services
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)
return null;
@ -91,7 +91,7 @@ namespace AsbCloudInfrastructure.Services
if (setpointsRequestDto.IdState != 3 && setpointsRequestDto.IdState != 4)
throw new ArgumentOutOfRangeException(nameof(setpointsRequestDto), $"{nameof(setpointsRequestDto.IdState)} = {setpointsRequestDto.IdState}. Mast be 3 or 4.");
var idWell = telemetryService.GetidWellByTelemetryUid(uid) ?? -1;
var idWell = telemetryService.GetIdWellByTelemetryUid(uid) ?? -1;
if (idWell < 0)
return 0;

View File

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

View File

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

View File

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

View File

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

View File

@ -10,7 +10,7 @@ namespace AsbCloudInfrastructure.Services
{
public class TimeZoneService : ITimeZoneService
{
class TimeZoneInfo
private class TimeZoneInfo
{
public string Sunrise { get; set; }
public double Lng { get; set; }
@ -25,8 +25,8 @@ namespace AsbCloudInfrastructure.Services
public string Time { get; set; }
}
private readonly string timeZoneApiUrl = "http://api.geonames.org/timezoneJSON";
private readonly string timezoneApiUserName = "asbautodrilling";
private const string timeZoneApiUrl = "http://api.geonames.org/timezoneJSON";
private const string timezoneApiUserName = "asbautodrilling";
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 IPermissionService permissionService;
public List<string> Incledes { get; } = new();
public List<string> Includes { get; } = new();
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;
}
@ -44,14 +44,13 @@ namespace AsbCloudInfrastructure.Services
{
var entity = dto.Adapt<UserRole>();
var updatedEntity = await cacheUserRoles.InsertAsync(entity, token).ConfigureAwait(false);
if (dto.Permissions?.Any() == true)
{
foreach (var permission in dto.Permissions)
permission.IdUserRole = updatedEntity.Id;
await permissionService.InsertRangeAsync(dto.Permissions, token).ConfigureAwait(false);
await cacheUserRoles.RefreshAsync(true, token)
.ConfigureAwait(false);
}
if (dto.Permissions?.Any() != true)
return updatedEntity?.Id ?? 0;
foreach (var permission in dto.Permissions)
permission.IdUserRole = updatedEntity.Id;
await permissionService.InsertRangeAsync(dto.Permissions, token).ConfigureAwait(false);
await cacheUserRoles.RefreshAsync(true, token)
.ConfigureAwait(false);
return updatedEntity?.Id ?? 0;
}
@ -91,22 +90,21 @@ namespace AsbCloudInfrastructure.Services
private IEnumerable<Permission> GetNestedPermissions(UserRole role, int counter = 10)
{
List<Permission> permissions = role.Permissions.ToList();
if (role.IdParent is not null)
var permissions = role.Permissions.ToList();
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;
}
var parentRole = cacheUserRoles.FirstOrDefault(r => r.Id == role.IdParent);
if (parentRole is null)
return permissions;
var parentPermissions = GetNestedPermissions(parentRole, counter--);
Merge(ref permissions, parentPermissions);
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);
return permissions;
}

View File

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

View File

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

View File

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

View File

@ -17,7 +17,7 @@ namespace AsbCloudInfrastructure.Services.WellOperationService
private readonly IAsbCloudDbContext context;
private readonly CacheTable<WellOperationCategory> cachedOperationCategories;
public WellOperationService(IAsbCloudDbContext context, Cache.CacheDb cache)
public WellOperationService(IAsbCloudDbContext context, CacheDb cache)
{
this.context = context;
cachedOperationCategories = cache.GetCachedTable<WellOperationCategory>((DbContext)context);
@ -35,7 +35,7 @@ namespace AsbCloudInfrastructure.Services.WellOperationService
public async Task<PaginationContainer<WellOperationDto>> GetOperationsAsync(
int idWell,
int? opertaionType = default,
int? operationType = default,
IEnumerable<int> sectionTypeIds = default,
IEnumerable<int> operationCategoryIds = default,
DateTime begin = default,
@ -51,10 +51,10 @@ namespace AsbCloudInfrastructure.Services.WellOperationService
.Include(s => s.OperationCategory)
.Where(s => s.IdWell == idWell);
if (opertaionType != default)
query = query.Where(e => e.IdType == (int)opertaionType);
if (operationType != default)
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));
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)
:base(service)
{
service.Incledes.Add("Wells");
service.Includes.Add("Wells");
}
}
}

View File

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

View File

@ -18,7 +18,7 @@ namespace AsbCloudWebApi.Controllers
ITelemetryService telemetryService)
: base(service)
{
service.Incledes.Add("Well");
service.Includes.Add("Well");
this.telemetryService = telemetryService;
}
@ -27,7 +27,7 @@ namespace AsbCloudWebApi.Controllers
[Route("/reduntentUids")]
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);
}

View File

@ -13,7 +13,7 @@ namespace AsbCloudWebApi.Controllers
public AdminWellController(ICrudService<WellDto> 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)]
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)
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,
CancellationToken token = default)
{
var idWell = telemetryService.GetidWellByTelemetryUid(uid);
var idWell = telemetryService.GetIdWellByTelemetryUid(uid);
await messageService.InsertAsync(uid, dtos, token).ConfigureAwait(false);
if (dtos.Any())

View File

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