forked from ddrilling/AsbCloudServer
Merge branch 'dev' into MaxAndAverageRop
# Conflicts: # AsbCloudInfrastructure/Services/WellService.cs
This commit is contained in:
commit
cb52f96069
@ -13,8 +13,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ConsoleApp1", "ConsoleApp1\
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AsbCloudDb", "AsbCloudDb\AsbCloudDb.csproj", "{40FBD29B-724B-4496-B5D9-1A5D14102456}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DataTable", "DataTable\DataTable.csproj", "{28AD7CD5-17A0-448C-8C16-A34AE5DE40FB}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AsbCloudWebApi.Tests", "AsbCloudWebApi.Tests\AsbCloudWebApi.Tests.csproj", "{9CF6FBB1-9AF5-45AB-A521-24F11A79B540}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AsbCloudDevOperations", "AsbCloudDbDemoData\AsbCloudDevOperations.csproj", "{1208822E-9099-4D13-B72F-8721E5758577}"
|
||||
@ -45,10 +43,6 @@ Global
|
||||
{40FBD29B-724B-4496-B5D9-1A5D14102456}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{40FBD29B-724B-4496-B5D9-1A5D14102456}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{40FBD29B-724B-4496-B5D9-1A5D14102456}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{28AD7CD5-17A0-448C-8C16-A34AE5DE40FB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{28AD7CD5-17A0-448C-8C16-A34AE5DE40FB}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{28AD7CD5-17A0-448C-8C16-A34AE5DE40FB}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{28AD7CD5-17A0-448C-8C16-A34AE5DE40FB}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{9CF6FBB1-9AF5-45AB-A521-24F11A79B540}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{9CF6FBB1-9AF5-45AB-A521-24F11A79B540}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{9CF6FBB1-9AF5-45AB-A521-24F11A79B540}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
|
24
AsbCloudApp/Data/TelemetryTimeZoneDto.cs
Normal file
24
AsbCloudApp/Data/TelemetryTimeZoneDto.cs
Normal file
@ -0,0 +1,24 @@
|
||||
namespace AsbCloudApp.Data
|
||||
{
|
||||
public class TelemetryTimeZoneDto
|
||||
{
|
||||
public double Hours { get; set; }
|
||||
public string TimeZoneId { get; set; }
|
||||
public bool IsOverride { get; set; }
|
||||
|
||||
public override bool Equals(object obj)
|
||||
{
|
||||
if(obj is TelemetryTimeZoneDto tTimeZone
|
||||
&& tTimeZone.Hours == Hours
|
||||
&& tTimeZone.TimeZoneId == TimeZoneId
|
||||
&& tTimeZone.IsOverride == IsOverride)
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
public override int GetHashCode()
|
||||
=> Hours.GetHashCode()
|
||||
| TimeZoneId.GetHashCode()
|
||||
| IsOverride.GetHashCode();
|
||||
}
|
||||
}
|
4
AsbCloudApp/Data/TimeZoneInfo.cs
Normal file
4
AsbCloudApp/Data/TimeZoneInfo.cs
Normal file
@ -0,0 +1,4 @@
|
||||
namespace AsbCloudApp.Data
|
||||
{
|
||||
|
||||
}
|
@ -9,10 +9,11 @@ namespace AsbCloudApp.Services
|
||||
public interface IMessageService
|
||||
{
|
||||
Task<PaginationContainer<MessageDto>> GetMessagesAsync(int idWell,
|
||||
IEnumerable<int> categoryids = null, DateTime begin = default,
|
||||
IEnumerable<int> categoryids = default, DateTime begin = default,
|
||||
DateTime end = default, string searchString = default,
|
||||
int skip = 0, int take = 32, CancellationToken token = default);
|
||||
Task<DatesRangeDto> GetMessagesDatesRangeAsync(int idWell,
|
||||
int skip = 0, int take = 32, bool isUtc = true,
|
||||
CancellationToken token = default);
|
||||
Task<DatesRangeDto> GetMessagesDatesRangeAsync(int idWell, bool isUtc,
|
||||
CancellationToken token = default);
|
||||
Task InsertAsync(string uid, IEnumerable<TelemetryMessageDto> dtos,
|
||||
CancellationToken token);
|
||||
|
@ -14,12 +14,11 @@ namespace AsbCloudApp.Services
|
||||
Action<object, int> handleReportProgress);
|
||||
int GetReportPagesCount(int idWell, DateTime begin, DateTime end,
|
||||
int stepSeconds, int format);
|
||||
|
||||
Task<List<ReportPropertiesDto>> GetSuitableReportsAsync(int idWell,
|
||||
DateTime begin, DateTime end, int stepSeconds, int format,
|
||||
CancellationToken token);
|
||||
Task<DatesRangeDto> GetReportsDatesRangeAsync(int idWell,
|
||||
CancellationToken token);
|
||||
Task<DatesRangeDto> GetReportsDatesRangeAsync(int idWell, bool isUtc,
|
||||
CancellationToken token = default);
|
||||
Task<List<ReportPropertiesDto>> GetAllReportsByWellAsync(int idWell, CancellationToken token);
|
||||
}
|
||||
}
|
||||
|
@ -24,7 +24,7 @@ namespace AsbCloudApp.Services
|
||||
int intervalHoursTimestamp, int workBeginTimestamp,
|
||||
CancellationToken token = default);
|
||||
Task AnalyzeAndSaveTelemetriesAsync(CancellationToken token = default);
|
||||
Task<DatesRangeDto> GetOperationsDateRangeAsync(int idWell,
|
||||
Task<DatesRangeDto> GetOperationsDateRangeAsync(int idWell, bool isUtc,
|
||||
CancellationToken token = default);
|
||||
}
|
||||
}
|
||||
|
@ -8,8 +8,11 @@ namespace AsbCloudApp.Services
|
||||
{
|
||||
public interface ITelemetryDataService<TDto> where TDto : ITelemetryData
|
||||
{
|
||||
Task<IEnumerable<TDto>> GetAsync(int idWell, DateTime dateBegin = default, double intervalSec = 600, int approxPointsCount = 1024, CancellationToken token = default);
|
||||
Task<DatesRangeDto> GetDataDatesRangeAsync(int idWell, CancellationToken token = default);
|
||||
Task<IEnumerable<TDto>> GetAsync(int idWell,
|
||||
DateTime dateBegin = default, double intervalSec = 600d,
|
||||
int approxPointsCount = 1024, bool isUtc = false, CancellationToken token = default);
|
||||
Task<DatesRangeDto> GetDataDatesRangeAsync(int idWell, bool isUtc = false,
|
||||
CancellationToken token = default);
|
||||
Task<int> UpdateDataAsync(string uid, IEnumerable<TDto> dtos, CancellationToken token = default);
|
||||
}
|
||||
}
|
@ -8,10 +8,17 @@ namespace AsbCloudApp.Services
|
||||
{
|
||||
public interface ITelemetryService
|
||||
{
|
||||
ITimeZoneService TimeZoneService { get; }
|
||||
ITelemetryTracker TelemetryTracker { get; }
|
||||
|
||||
int? GetidWellByTelemetryUid(string uid);
|
||||
int GetOrCreateTemetryIdByUid(string uid);
|
||||
double GetTimezoneOffsetByTelemetryId(int idTelemetry);
|
||||
void UpdateInfo(string uid, TelemetryInfoDto info);
|
||||
Task UpdateInfoAsync(string uid, TelemetryInfoDto info, CancellationToken token);
|
||||
Task<double?> GetTelemetryTimeZoneOffsetAsync(int idTelemetry, CancellationToken token);
|
||||
Task<DatesRangeDto> FixDatesRangeByTimeZoneAsync(int telemetryId, DatesRangeDto result,
|
||||
CancellationToken token);
|
||||
Task UpdateTimeZoneAsync(string uid, TelemetryTimeZoneDto telemetryTimeZoneInfo, CancellationToken token);
|
||||
int? GetIdTelemetryByIdWell(int idWell);
|
||||
int Merge(IEnumerable<int> telemetryIds);
|
||||
IEnumerable<(string Key, int[] Ids)> GetRedundentRemoteUids();
|
||||
|
@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using AsbCloudApp.Data;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace AsbCloudApp.Services
|
||||
@ -6,6 +7,7 @@ namespace AsbCloudApp.Services
|
||||
public interface ITelemetryTracker
|
||||
{
|
||||
DateTime GetLastTelemetryDateByUid(string uid);
|
||||
DatesRangeDto GetTelemetryDateRangeByUid(string uid);
|
||||
IEnumerable<string> GetTransmittingTelemetriesUids();
|
||||
void SaveRequestDate(string uid, DateTime remoteDate);
|
||||
}
|
||||
|
13
AsbCloudApp/Services/ITimeZoneService.cs
Normal file
13
AsbCloudApp/Services/ITimeZoneService.cs
Normal file
@ -0,0 +1,13 @@
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace AsbCloudApp.Services
|
||||
{
|
||||
public interface ITimeZoneService
|
||||
{
|
||||
DateTime DateToUtc(DateTime date, double remoteOTimezoneffsetHours);
|
||||
DateTime DateToTimeZone(DateTime date, double remoteOTimezoneffsetHours);
|
||||
Task<Data.TelemetryTimeZoneDto> GetByCoordinatesAsync(double latitude, double longitude, CancellationToken token);
|
||||
}
|
||||
}
|
2768
AsbCloudDb/Migrations/20211116080138_Add_Telemetry_TimeZone.Designer.cs
generated
Normal file
2768
AsbCloudDb/Migrations/20211116080138_Add_Telemetry_TimeZone.Designer.cs
generated
Normal file
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,25 @@
|
||||
using AsbCloudDb.Model;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
namespace AsbCloudDb.Migrations
|
||||
{
|
||||
public partial class Add_Telemetry_TimeZone : Migration
|
||||
{
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<TelemetryTimeZone>(
|
||||
name: "timezone",
|
||||
table: "t_telemetry",
|
||||
type: "jsonb",
|
||||
nullable: true,
|
||||
comment: "Смещение часового пояса от UTC");
|
||||
}
|
||||
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropColumn(
|
||||
name: "timezone",
|
||||
table: "t_telemetry");
|
||||
}
|
||||
}
|
||||
}
|
@ -768,6 +768,11 @@ namespace AsbCloudDb.Migrations
|
||||
.HasColumnName("remote_uid")
|
||||
.HasComment("Идентификатор передающего устройства. Может повторяться в списке, так как комплекты оборудования переезжают от скв. к скв.");
|
||||
|
||||
b.Property<TelemetryTimeZone>("TelemetryTimeZone")
|
||||
.HasColumnType("jsonb")
|
||||
.HasColumnName("timezone")
|
||||
.HasComment("Смещение часового пояса от UTC");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex(new[] { "RemoteUid" }, "t_telemetry_remote_uid_index");
|
||||
|
@ -1,5 +1,4 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
@ -27,6 +26,9 @@ namespace AsbCloudDb.Model
|
||||
|
||||
[Column("info", TypeName = "jsonb"), Comment("Информация с панели о скважине")]
|
||||
public TelemetryInfo Info { get; set; }
|
||||
|
||||
[Column("timezone", TypeName = "jsonb"), Comment("Смещение часового пояса от UTC")]
|
||||
public TelemetryTimeZone TelemetryTimeZone { get; set; }
|
||||
|
||||
[InverseProperty(nameof(Model.Well.Telemetry))]
|
||||
public virtual Well Well { get; set; }
|
||||
|
9
AsbCloudDb/Model/TelemetryTimeZone.cs
Normal file
9
AsbCloudDb/Model/TelemetryTimeZone.cs
Normal file
@ -0,0 +1,9 @@
|
||||
namespace AsbCloudDb.Model
|
||||
{
|
||||
public class TelemetryTimeZone
|
||||
{
|
||||
public double Hours { get; set; }
|
||||
public string TimeZoneId { get; set; }
|
||||
public bool IsOverride { get; set; }
|
||||
}
|
||||
}
|
@ -47,6 +47,7 @@ namespace AsbCloudInfrastructure
|
||||
services.AddTransient<IDrillingProgramService, DrillingProgramService>();
|
||||
services.AddTransient<IDrillParamsService, DrillParamsService>();
|
||||
services.AddTransient<IDrillFlowChartService, DrillFlowChartService>();
|
||||
services.AddTransient<ITimeZoneService, TimeZoneService>();
|
||||
|
||||
// admin crud services:
|
||||
services.AddTransient<ICrudService<DepositDto>, CrudServiceBase<DepositDto, Deposit>>();
|
||||
|
@ -40,7 +40,8 @@ namespace AsbCloudInfrastructure.Services.Analysis
|
||||
try
|
||||
{
|
||||
using var context = new AsbCloudDbContext(options);
|
||||
var telemetryService = new TelemetryService(context, telemetryTracker, cacheDb);
|
||||
var timeZoneService = new TimeZoneService();
|
||||
var telemetryService = new TelemetryService(context, telemetryTracker, timeZoneService, cacheDb);
|
||||
var analyticsService = new TelemetryAnalyticsService(context,
|
||||
telemetryService, cacheDb);
|
||||
|
||||
|
@ -231,13 +231,9 @@ namespace AsbCloudInfrastructure.Services.Analysis
|
||||
|
||||
public async Task AnalyzeAndSaveTelemetriesAsync(CancellationToken token = default)
|
||||
{
|
||||
var allTelemetryIds = await db.TelemetryDataSaub
|
||||
.Select(t => t.IdTelemetry)
|
||||
.Distinct()
|
||||
.ToListAsync(token)
|
||||
.ConfigureAwait(false);
|
||||
var allTelemetryIds = await db.Telemetries.Select(t => t.Id).ToListAsync(token).ConfigureAwait(false);
|
||||
|
||||
foreach(var idTelemetry in allTelemetryIds)
|
||||
foreach (var idTelemetry in allTelemetryIds)
|
||||
{
|
||||
var analyzeStartDate = await GetLastAnalysisDateAsync(idTelemetry, token).ConfigureAwait(false);
|
||||
await AnalyseAndSaveTelemetryAsync(idTelemetry, analyzeStartDate, token).ConfigureAwait(false);
|
||||
@ -294,7 +290,7 @@ namespace AsbCloudInfrastructure.Services.Analysis
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<DatesRangeDto> GetOperationsDateRangeAsync(int idWell,
|
||||
public async Task<DatesRangeDto> GetOperationsDateRangeAsync(int idWell, bool isUtc,
|
||||
CancellationToken token = default)
|
||||
{
|
||||
var telemetryId = telemetryService.GetIdTelemetryByIdWell(idWell);
|
||||
@ -315,13 +311,21 @@ namespace AsbCloudInfrastructure.Services.Analysis
|
||||
.FirstOrDefaultAsync(token)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
return new DatesRangeDto
|
||||
var result = new DatesRangeDto
|
||||
{
|
||||
From = DateTimeOffset.FromUnixTimeSeconds(datesRange.From).DateTime,
|
||||
To = datesRange.To == default
|
||||
? DateTime.MaxValue
|
||||
: DateTimeOffset.FromUnixTimeSeconds(datesRange.To).DateTime
|
||||
};
|
||||
|
||||
if (isUtc)
|
||||
return result;
|
||||
|
||||
result = await telemetryService.FixDatesRangeByTimeZoneAsync((int)telemetryId, result, token)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private async Task<DateTime> GetLastAnalysisDateAsync(int idTelemetry, CancellationToken token = default)
|
||||
|
@ -16,6 +16,7 @@ namespace AsbCloudInfrastructure.Services
|
||||
{
|
||||
private readonly IAsbCloudDbContext db;
|
||||
private readonly ITelemetryService telemetryService;
|
||||
private readonly CacheTable<Telemetry> cacheTelemetry;
|
||||
private readonly CacheTable<TelemetryEvent> cacheEvents;
|
||||
private readonly CacheTable<TelemetryUser> cacheTUsers;
|
||||
|
||||
@ -23,6 +24,7 @@ namespace AsbCloudInfrastructure.Services
|
||||
{
|
||||
this.db = db;
|
||||
this.telemetryService = telemetryService;
|
||||
cacheTelemetry = cacheDb.GetCachedTable<Telemetry>((AsbCloudDbContext)db);
|
||||
cacheEvents = cacheDb.GetCachedTable<TelemetryEvent>((AsbCloudDbContext)db);
|
||||
cacheTUsers = cacheDb.GetCachedTable<TelemetryUser>((AsbCloudDbContext)db);
|
||||
}
|
||||
@ -35,18 +37,19 @@ namespace AsbCloudInfrastructure.Services
|
||||
string searchString = default,
|
||||
int skip = 0,
|
||||
int take = 32,
|
||||
bool isUtc = true,
|
||||
CancellationToken token = default)
|
||||
{
|
||||
var telemetryId = telemetryService.GetIdTelemetryByIdWell(idWell);
|
||||
if (telemetryId is null)
|
||||
var idTelemetry = telemetryService.GetIdTelemetryByIdWell(idWell);
|
||||
if (idTelemetry is null)
|
||||
return null;
|
||||
|
||||
var events = cacheEvents.Where(e => e.IdTelemetry == telemetryId);
|
||||
var events = cacheEvents.Where(e => e.IdTelemetry == idTelemetry);
|
||||
|
||||
if (!events.Any())
|
||||
return null;
|
||||
|
||||
var query = db.TelemetryMessages.Where(m => m.IdTelemetry == telemetryId)
|
||||
var query = db.TelemetryMessages.Where(m => m.IdTelemetry == idTelemetry)
|
||||
.OrderBy(m => m.Date).AsNoTracking();
|
||||
|
||||
if ((categoryids?.Any() == true) || !string.IsNullOrEmpty(searchString))
|
||||
@ -67,6 +70,16 @@ namespace AsbCloudInfrastructure.Services
|
||||
|
||||
query = query.OrderByDescending(m => m.Date);
|
||||
|
||||
|
||||
var timeOffset = await telemetryService.GetTelemetryTimeZoneOffsetAsync(idTelemetry??default, token)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
if (timeOffset is not null)
|
||||
{
|
||||
begin = telemetryService.TimeZoneService.DateToUtc(begin, timeOffset ?? default);
|
||||
end = telemetryService.TimeZoneService.DateToUtc(end, timeOffset ?? default);
|
||||
}
|
||||
|
||||
if (begin != default)
|
||||
query = query.Where(m => m.Date >= begin);
|
||||
|
||||
@ -89,7 +102,7 @@ namespace AsbCloudInfrastructure.Services
|
||||
if (messagesList.Count == 0)
|
||||
return result;
|
||||
|
||||
var users = cacheTUsers.Where(u => u.IdTelemetry == telemetryId);
|
||||
var users = cacheTUsers.Where(u => u.IdTelemetry == idTelemetry);
|
||||
|
||||
foreach (var message in messagesList)
|
||||
{
|
||||
@ -121,10 +134,19 @@ namespace AsbCloudInfrastructure.Services
|
||||
result.Items.Add(messageDto);
|
||||
}
|
||||
|
||||
if (isUtc && timeOffset is not null)
|
||||
return result;
|
||||
|
||||
result.Items = result.Items.Select(m =>
|
||||
{
|
||||
m.Date = telemetryService.TimeZoneService.DateToTimeZone( m.Date, timeOffset ?? default);
|
||||
return m;
|
||||
}).ToList();
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public async Task<DatesRangeDto> GetMessagesDatesRangeAsync(int idWell,
|
||||
public async Task<DatesRangeDto> GetMessagesDatesRangeAsync(int idWell, bool isUtc,
|
||||
CancellationToken token = default)
|
||||
{
|
||||
var telemetryId = telemetryService.GetIdTelemetryByIdWell(idWell);
|
||||
@ -134,7 +156,15 @@ namespace AsbCloudInfrastructure.Services
|
||||
var (From, To) = await db.GetDatesRangeAsync<TelemetryMessage>((int)telemetryId, token)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
return new DatesRangeDto { From = From, To = To };
|
||||
var result = new DatesRangeDto { From = From, To = To };
|
||||
|
||||
if (isUtc)
|
||||
return result;
|
||||
|
||||
result = await telemetryService.FixDatesRangeByTimeZoneAsync((int)telemetryId, result, token)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public Task InsertAsync(string uid, IEnumerable<TelemetryMessageDto> dtos,
|
||||
|
@ -97,7 +97,7 @@ namespace AsbCloudInfrastructure.Services
|
||||
return generator.GetPagesCount();
|
||||
}
|
||||
|
||||
public async Task<DatesRangeDto> GetReportsDatesRangeAsync(int idWell,
|
||||
public async Task<DatesRangeDto> GetReportsDatesRangeAsync(int idWell, bool isUtc,
|
||||
CancellationToken token = default)
|
||||
{
|
||||
var telemetryId = telemetryService.GetIdTelemetryByIdWell(idWell);
|
||||
@ -121,11 +121,19 @@ namespace AsbCloudInfrastructure.Services
|
||||
.FirstOrDefaultAsync(token)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
return new DatesRangeDto
|
||||
var result = new DatesRangeDto
|
||||
{
|
||||
From = datesRange.From,
|
||||
To = datesRange.To.Year == 1 ? DateTime.MaxValue : datesRange.To
|
||||
};
|
||||
|
||||
if (isUtc)
|
||||
return result;
|
||||
|
||||
result = await telemetryService.FixDatesRangeByTimeZoneAsync((int)telemetryId, result, token)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public Task<List<ReportPropertiesDto>> GetSuitableReportsAsync(int idWell, DateTime begin, DateTime end, int stepSeconds, int format, CancellationToken token) =>
|
||||
|
@ -4,7 +4,6 @@ using AsbCloudDb.Model;
|
||||
using AsbCloudDb;
|
||||
using AsbCloudInfrastructure.Services.Cache;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.ChangeTracking;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
@ -20,7 +19,6 @@ namespace AsbCloudInfrastructure.Services
|
||||
{
|
||||
private readonly IAsbCloudDbContext db;
|
||||
private readonly ITelemetryService telemetryService;
|
||||
|
||||
protected readonly CacheTable<Telemetry> cacheTelemetry;
|
||||
protected readonly CacheTable<TelemetryUser> cacheTelemetryUsers;
|
||||
protected readonly CacheTable<Well> cacheWells;
|
||||
@ -32,7 +30,6 @@ namespace AsbCloudInfrastructure.Services
|
||||
{
|
||||
this.db = db;
|
||||
this.telemetryService = telemetryService;
|
||||
|
||||
cacheTelemetry = cacheDb.GetCachedTable<Telemetry>((AsbCloudDbContext)db);
|
||||
cacheTelemetryUsers = cacheDb.GetCachedTable<TelemetryUser>((AsbCloudDbContext)db);
|
||||
cacheWells = cacheDb.GetCachedTable<Well>((AsbCloudDbContext)db);
|
||||
@ -59,36 +56,42 @@ namespace AsbCloudInfrastructure.Services
|
||||
foreach (var duplicate in duplicates)
|
||||
dtosList.Remove(duplicate);
|
||||
}
|
||||
|
||||
var offsetHours = await telemetryService.GetTelemetryTimeZoneOffsetAsync(idTelemetry, token);
|
||||
|
||||
var enitties = dtosList.Select(d => {
|
||||
var e = Convert(d);
|
||||
e.IdTelemetry = idTelemetry;
|
||||
return e;
|
||||
var entities = dtosList.Select(d => {
|
||||
var e = Convert(d);
|
||||
e.IdTelemetry = idTelemetry;
|
||||
if(offsetHours is not null)
|
||||
e.Date = telemetryService.TimeZoneService.DateToUtc(d.Date, (double)offsetHours);
|
||||
return e;
|
||||
});
|
||||
|
||||
var dbset = db.Set<TModel>();
|
||||
try
|
||||
{
|
||||
return await db.Database.ExecInsertOrUpdateAsync(dbset, enitties, token).ConfigureAwait(false);
|
||||
return await db.Database.ExecInsertOrUpdateAsync(dbset, entities, token).ConfigureAwait(false);
|
||||
}
|
||||
catch(Exception ex)
|
||||
{
|
||||
Trace.WriteLine($"Fail to save data telemerty uid: {uid}, idTelemetry {idTelemetry} count: {enitties.Count()} dataDate: {enitties.FirstOrDefault()?.Date}. Message: {ex.Message}");
|
||||
Trace.WriteLine($"Fail to save data telemerty uid: {uid}, idTelemetry {idTelemetry} count: {entities.Count()} dataDate: {entities.FirstOrDefault()?.Date}. Message: {ex.Message}");
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
public virtual async Task<IEnumerable<TDto>> GetAsync(int idWell,
|
||||
DateTime dateBegin = default, double intervalSec = 600d,
|
||||
int approxPointsCount = 1024, CancellationToken token = default)
|
||||
int approxPointsCount = 1024, bool isUtc = false, CancellationToken token = default)
|
||||
{
|
||||
var well = cacheWells.FirstOrDefault(w => w.Id == idWell);
|
||||
if (well?.IdTelemetry is null)
|
||||
return default;
|
||||
|
||||
var idTelemetry = well?.IdTelemetry ?? default;
|
||||
|
||||
if (dateBegin == default)
|
||||
{
|
||||
dateBegin = telemetryService.GetLastTelemetryDate(well.IdTelemetry ?? 0);
|
||||
dateBegin = telemetryService.GetLastTelemetryDate(idTelemetry);
|
||||
if (dateBegin != default)
|
||||
dateBegin = dateBegin.AddSeconds(-intervalSec);
|
||||
}
|
||||
@ -99,13 +102,19 @@ namespace AsbCloudInfrastructure.Services
|
||||
if (dateBegin.Kind == DateTimeKind.Unspecified)
|
||||
dateBegin = DateTime.SpecifyKind(dateBegin, DateTimeKind.Utc);
|
||||
|
||||
var datEnd = dateBegin.AddSeconds(intervalSec);
|
||||
var timeOffset = await telemetryService.GetTelemetryTimeZoneOffsetAsync(idTelemetry, token)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
if(timeOffset is not null)
|
||||
dateBegin = telemetryService.TimeZoneService.DateToUtc(dateBegin, timeOffset?? default);
|
||||
|
||||
var dateEnd = dateBegin.AddSeconds(intervalSec);
|
||||
var dbSet = db.Set<TModel>();
|
||||
|
||||
var query = from data in dbSet
|
||||
where data.IdTelemetry == well.IdTelemetry
|
||||
&& data.Date >= dateBegin && data.Date < datEnd
|
||||
select data;
|
||||
var query = dbSet
|
||||
.Where(d => d.IdTelemetry == idTelemetry
|
||||
&& d.Date >= dateBegin
|
||||
&& d.Date < dateEnd);
|
||||
|
||||
var fullDataCount = await query.CountAsync(token)
|
||||
.ConfigureAwait(false);
|
||||
@ -128,20 +137,41 @@ namespace AsbCloudInfrastructure.Services
|
||||
|
||||
var dtos = entities.Select(e => Convert(e));
|
||||
|
||||
if (isUtc)
|
||||
return dtos;
|
||||
|
||||
if (timeOffset is null)
|
||||
return dtos;
|
||||
|
||||
dtos = dtos.Select(d =>
|
||||
{
|
||||
d.Date = telemetryService.TimeZoneService.DateToTimeZone(d.Date, timeOffset ?? default);
|
||||
return d;
|
||||
});
|
||||
|
||||
return dtos;
|
||||
}
|
||||
|
||||
public virtual async Task<DatesRangeDto> GetDataDatesRangeAsync(int idWell,
|
||||
public virtual async Task<DatesRangeDto> GetDataDatesRangeAsync(int idWell, bool isUtc,
|
||||
CancellationToken token = default)
|
||||
{
|
||||
var telemetryId = telemetryService.GetIdTelemetryByIdWell(idWell);
|
||||
if (telemetryId is null)
|
||||
return null;
|
||||
|
||||
var (From, To) = await db.GetDatesRangeAsync<TModel>((int)telemetryId, token)
|
||||
var telemetry = await cacheTelemetry.FirstOrDefaultAsync(t => t.Id == telemetryId, token)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
return new DatesRangeDto { From = From, To = To };
|
||||
var dto = telemetryService.TelemetryTracker.GetTelemetryDateRangeByUid(telemetry.RemoteUid);
|
||||
|
||||
if (isUtc)
|
||||
return dto;
|
||||
|
||||
dto = await telemetryService.FixDatesRangeByTimeZoneAsync((int)telemetryId, dto, token)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
return dto;
|
||||
|
||||
}
|
||||
|
||||
public abstract TDto Convert(TModel src);
|
||||
|
@ -6,7 +6,7 @@ using Mapster;
|
||||
|
||||
namespace AsbCloudInfrastructure.Services
|
||||
{
|
||||
public class TelemetryDataSaubService: TelemetryDataBaseService<AsbCloudApp.Data.TelemetryDataSaubDto, AsbCloudDb.Model.TelemetryDataSaub>
|
||||
public class TelemetryDataSaubService: TelemetryDataBaseService<TelemetryDataSaubDto, TelemetryDataSaub>
|
||||
{
|
||||
public TelemetryDataSaubService(
|
||||
IAsbCloudDbContext db,
|
||||
|
@ -6,7 +6,7 @@ using Mapster;
|
||||
|
||||
namespace AsbCloudInfrastructure.Services
|
||||
{
|
||||
public class TelemetryDataSpinService : TelemetryDataBaseService<AsbCloudApp.Data.TelemetryDataSpinDto, AsbCloudDb.Model.TelemetryDataSpin>
|
||||
public class TelemetryDataSpinService : TelemetryDataBaseService<TelemetryDataSpinDto, TelemetryDataSpin>
|
||||
{
|
||||
public TelemetryDataSpinService(
|
||||
IAsbCloudDbContext db,
|
||||
|
@ -5,7 +5,9 @@ using AsbCloudInfrastructure.Services.Cache;
|
||||
using Mapster;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using System;
|
||||
using System.Threading;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace AsbCloudInfrastructure.Services
|
||||
@ -14,16 +16,28 @@ namespace AsbCloudInfrastructure.Services
|
||||
{
|
||||
private readonly CacheTable<Telemetry> cacheTelemetry;
|
||||
private readonly CacheTable<Well> cacheWells;
|
||||
private readonly CacheTable<Cluster> cacheClusters;
|
||||
private readonly CacheTable<Deposit> cacheDeposits;
|
||||
private readonly IAsbCloudDbContext db;
|
||||
private readonly ITelemetryTracker telemetryTracker;
|
||||
private readonly ITimeZoneService timeZoneService;
|
||||
|
||||
public TelemetryService(IAsbCloudDbContext db, ITelemetryTracker telemetryTracker,
|
||||
public ITimeZoneService TimeZoneService => timeZoneService;
|
||||
public ITelemetryTracker TelemetryTracker => telemetryTracker;
|
||||
|
||||
public TelemetryService(
|
||||
IAsbCloudDbContext db,
|
||||
ITelemetryTracker telemetryTracker,
|
||||
ITimeZoneService timeZoneService,
|
||||
CacheDb cacheDb)
|
||||
{
|
||||
cacheTelemetry = cacheDb.GetCachedTable<Telemetry>((AsbCloudDbContext)db);
|
||||
cacheWells = cacheDb.GetCachedTable<Well>((AsbCloudDbContext)db);
|
||||
cacheClusters = cacheDb.GetCachedTable<Cluster>((AsbCloudDbContext)db);
|
||||
cacheDeposits = cacheDb.GetCachedTable<Deposit>((AsbCloudDbContext)db);
|
||||
this.db = db;
|
||||
this.telemetryTracker = telemetryTracker;
|
||||
this.timeZoneService = timeZoneService;
|
||||
}
|
||||
|
||||
public IEnumerable<TelemetryDto> GetTransmittingTelemetriesAsync(int idCompany)
|
||||
@ -69,11 +83,92 @@ namespace AsbCloudInfrastructure.Services
|
||||
public double GetTimezoneOffsetByTelemetryId(int idTelemetry) =>
|
||||
cacheTelemetry.FirstOrDefault(t => t.Id == idTelemetry).Info?.TimeZoneOffsetTotalHours ?? 0d;
|
||||
|
||||
public void UpdateInfo(string uid, TelemetryInfoDto info)
|
||||
public async Task UpdateInfoAsync(string uid, TelemetryInfoDto info,
|
||||
CancellationToken token)
|
||||
{
|
||||
var telemetry = GetOrCreateTelemetryByUid(uid);
|
||||
telemetry.Info = info.Adapt<TelemetryInfo>();
|
||||
cacheTelemetry.Upsert(telemetry);
|
||||
|
||||
if (!string.IsNullOrEmpty(info.TimeZoneId) &&
|
||||
telemetry.TelemetryTimeZone?.IsOverride != true)
|
||||
telemetry.TelemetryTimeZone = new TelemetryTimeZone()
|
||||
{
|
||||
Hours = info.TimeZoneOffsetTotalHours,
|
||||
TimeZoneId = info.TimeZoneId
|
||||
};
|
||||
|
||||
await cacheTelemetry.UpsertAsync(telemetry, token)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public async Task<double?> GetTelemetryTimeZoneOffsetAsync(int idTelemetry, CancellationToken token)
|
||||
{
|
||||
var telemetry =
|
||||
await cacheTelemetry.FirstOrDefaultAsync(t => t.Id == idTelemetry, token);
|
||||
|
||||
if (!string.IsNullOrEmpty(telemetry.TelemetryTimeZone?.TimeZoneId))
|
||||
return telemetry.TelemetryTimeZone.Hours;
|
||||
|
||||
if (!string.IsNullOrEmpty(telemetry.Info?.TimeZoneId))
|
||||
{
|
||||
telemetry.TelemetryTimeZone = new TelemetryTimeZone
|
||||
{
|
||||
Hours = telemetry.Info.TimeZoneOffsetTotalHours,
|
||||
IsOverride = false,
|
||||
TimeZoneId = telemetry.Info.TimeZoneId,
|
||||
};
|
||||
}
|
||||
else
|
||||
{
|
||||
var well = await cacheWells.FirstOrDefaultAsync(t => t.IdTelemetry == telemetry.Id, token)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
if (well is null)
|
||||
return null;
|
||||
|
||||
var coordinates = await GetWellCoordinatesAsync(well.Id, token);
|
||||
|
||||
if (coordinates is null)
|
||||
return null;
|
||||
|
||||
var requestedTimeZone = await timeZoneService.GetByCoordinatesAsync(coordinates.Value.latitude, coordinates.Value.longitude, token)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
if (requestedTimeZone is null)
|
||||
return null;
|
||||
|
||||
telemetry.TelemetryTimeZone = requestedTimeZone.Adapt<TelemetryTimeZone>();
|
||||
}
|
||||
|
||||
await cacheTelemetry.UpsertAsync(telemetry, token).ConfigureAwait(false);
|
||||
|
||||
return telemetry.TelemetryTimeZone.Hours;
|
||||
}
|
||||
|
||||
public async Task<DatesRangeDto> FixDatesRangeByTimeZoneAsync(int idTelemetry, DatesRangeDto range,
|
||||
CancellationToken token)
|
||||
{
|
||||
var offset = await GetTelemetryTimeZoneOffsetAsync(idTelemetry, token);
|
||||
|
||||
if (offset is null)
|
||||
return range;
|
||||
|
||||
return new DatesRangeDto()
|
||||
{
|
||||
From = timeZoneService.DateToTimeZone(range.From, offset ?? default),
|
||||
To = timeZoneService.DateToTimeZone(range.To, offset ?? default),
|
||||
};
|
||||
}
|
||||
|
||||
public async Task UpdateTimeZoneAsync(string uid, TelemetryTimeZoneDto timeZoneInfo,
|
||||
CancellationToken token)
|
||||
{
|
||||
var telemetry = GetOrCreateTelemetryByUid(uid);
|
||||
var newTelemetryTimeZone = timeZoneInfo.Adapt<TelemetryTimeZone>();
|
||||
if (newTelemetryTimeZone?.Equals(telemetry.TelemetryTimeZone) == true)
|
||||
return;
|
||||
await cacheTelemetry.UpsertAsync(telemetry, token)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public int? GetIdTelemetryByIdWell(int idWell)
|
||||
@ -85,6 +180,33 @@ namespace AsbCloudInfrastructure.Services
|
||||
return well.IdTelemetry;
|
||||
}
|
||||
|
||||
private async Task<(double latitude, double longitude)?> GetWellCoordinatesAsync(int idWell,
|
||||
CancellationToken token)
|
||||
{
|
||||
var well = await cacheWells.FirstOrDefaultAsync(w => w.Id == idWell, token)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
if (well is null)
|
||||
return null;
|
||||
|
||||
if (well.Latitude is not null && well.Longitude is not null)
|
||||
return (well.Latitude ?? default, well.Longitude??default);
|
||||
|
||||
var cluster = await cacheClusters.FirstOrDefaultAsync(c => c.Id == well.IdCluster, token)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
if (cluster.Latitude is not null && cluster.Longitude is not null)
|
||||
return (cluster.Latitude ?? default, cluster.Longitude ?? default);
|
||||
|
||||
var deposit = await cacheDeposits.FirstOrDefaultAsync(d => d.Id == cluster.IdDeposit, token)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
if (deposit.Latitude is not null && deposit.Longitude is not null)
|
||||
return (deposit.Latitude ?? default, deposit.Longitude ?? default);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private Well GetWellByTelemetryUid(string uid)
|
||||
{
|
||||
var tele = cacheTelemetry.FirstOrDefault(t => t.RemoteUid == uid);
|
||||
@ -247,5 +369,7 @@ namespace AsbCloudInfrastructure.Services
|
||||
|
||||
return rows;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
@ -8,6 +8,7 @@ using Microsoft.EntityFrameworkCore;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using AsbCloudApp.Data;
|
||||
|
||||
namespace AsbCloudInfrastructure.Services
|
||||
{
|
||||
@ -25,70 +26,78 @@ namespace AsbCloudInfrastructure.Services
|
||||
public DateTime LastTimeServer { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Время указанное в данных последнего запроса (из удаленного источника)
|
||||
/// Дата первых данных в БД
|
||||
/// </summary>
|
||||
public DateTime LastTimeRemote { get; set; }
|
||||
public DateTime TelemetryDateMin { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Дата последних данных в БД
|
||||
/// </summary>
|
||||
public DateTime TelemetryDateMax { get; set; }
|
||||
|
||||
}
|
||||
|
||||
private readonly ConcurrentDictionary<string, TrackerStat> requests;
|
||||
private readonly ConcurrentDictionary<string, TrackerStat> telemetriesStats;
|
||||
|
||||
public TelemetryTracker(CacheDb cacheDb, IConfiguration configuration)
|
||||
{
|
||||
var options = new DbContextOptionsBuilder<AsbCloudDbContext>()
|
||||
.UseNpgsql(configuration.GetConnectionString("DefaultConnection"))
|
||||
.Options;
|
||||
using var db = new AsbCloudDbContext(options);
|
||||
var db = new AsbCloudDbContext(options);
|
||||
|
||||
var cacheTelemetry = cacheDb.GetCachedTable<Telemetry>(db);
|
||||
var keyValuePairs = new Dictionary<string, TrackerStat>(cacheTelemetry.Count());
|
||||
foreach (var telemetry in cacheTelemetry)
|
||||
{
|
||||
var date = telemetry.Info?.DrillingStartDate
|
||||
?? GetDateByUidOrDefault(telemetry.RemoteUid, DateTime.MinValue);
|
||||
var date = telemetry.Info?.DrillingStartDate
|
||||
?? ParseDateFromUidOrDefault(telemetry.RemoteUid, DateTime.MinValue);
|
||||
|
||||
keyValuePairs[telemetry.RemoteUid] = new TrackerStat {
|
||||
keyValuePairs[telemetry.RemoteUid] = new TrackerStat
|
||||
{
|
||||
RemoteUid = telemetry.RemoteUid,
|
||||
LastTimeRemote = date,
|
||||
TelemetryDateMin = date,
|
||||
TelemetryDateMax = date,
|
||||
LastTimeServer = date,
|
||||
};
|
||||
}
|
||||
requests = new ConcurrentDictionary<string, TrackerStat>(keyValuePairs);
|
||||
telemetriesStats = new ConcurrentDictionary<string, TrackerStat>(keyValuePairs);
|
||||
|
||||
Task.Run(async() => {
|
||||
db.Database.SetCommandTimeout(2 * 60);
|
||||
Task.Run(async () =>
|
||||
{
|
||||
db.Database.SetCommandTimeout(2 * 60);
|
||||
var dates = await db.TelemetryDataSaub
|
||||
.GroupBy(d => d.IdTelemetry)
|
||||
.Select(g => new
|
||||
{
|
||||
IdTelemetry = g.Key,
|
||||
Date = g.Max(d=>d.Date)
|
||||
DateMax = g.Max(d => d.Date),
|
||||
DateMin = g.Min(d => d.Date),
|
||||
})
|
||||
.AsNoTracking()
|
||||
.ToListAsync()
|
||||
.ConfigureAwait(false);
|
||||
|
||||
db.Dispose();
|
||||
|
||||
|
||||
var oldReqs = dates.Select(t => new
|
||||
{
|
||||
Uid = cacheTelemetry.FirstOrDefault(c => c.Id == t.IdTelemetry).RemoteUid,
|
||||
t.Date,
|
||||
});
|
||||
Uid = cacheTelemetry.FirstOrDefault(c => c.Id == t.IdTelemetry)?.RemoteUid,
|
||||
t.DateMax,
|
||||
t.DateMin,
|
||||
}).Where(s => !string.IsNullOrEmpty(s.Uid));
|
||||
|
||||
foreach (var oldReq in oldReqs)
|
||||
{
|
||||
var request = requests.GetValueOrDefault(oldReq.Uid);
|
||||
if(request is not null)
|
||||
{
|
||||
if (request.LastTimeRemote < oldReq.Date)
|
||||
request.LastTimeRemote = oldReq.Date;
|
||||
if (request.LastTimeServer < oldReq.Date)
|
||||
request.LastTimeServer = oldReq.Date;
|
||||
}
|
||||
var telemetryStat = telemetriesStats.GetOrAdd(oldReq.Uid, (uid) => new TrackerStat { RemoteUid = uid });
|
||||
telemetryStat.TelemetryDateMin = oldReq.DateMin;
|
||||
telemetryStat.TelemetryDateMax = oldReq.DateMax;
|
||||
telemetryStat.LastTimeServer = oldReq.DateMax;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static DateTime GetDateByUidOrDefault(string remoteUid, DateTime defaultValue = default)
|
||||
private static DateTime ParseDateFromUidOrDefault(string remoteUid, DateTime defaultValue = default)
|
||||
{
|
||||
//eg: uid = 20211102_173407926
|
||||
if (string.IsNullOrEmpty(remoteUid) || (remoteUid.Length != 18))
|
||||
@ -105,20 +114,30 @@ namespace AsbCloudInfrastructure.Services
|
||||
|
||||
public void SaveRequestDate(string uid, DateTime remoteDate)
|
||||
{
|
||||
var stat = requests.GetValueOrDefault(uid);
|
||||
if(stat is null)
|
||||
{
|
||||
stat = new TrackerStat{ RemoteUid = uid };
|
||||
requests[uid] = stat;
|
||||
}
|
||||
var stat = telemetriesStats.GetOrAdd(uid, (uid) => new TrackerStat {
|
||||
RemoteUid = uid,
|
||||
TelemetryDateMin = remoteDate}
|
||||
);
|
||||
stat.LastTimeServer = DateTime.Now;
|
||||
stat.LastTimeRemote = remoteDate;
|
||||
stat.TelemetryDateMax = remoteDate;
|
||||
}
|
||||
|
||||
public DateTime GetLastTelemetryDateByUid(string uid) =>
|
||||
requests.GetValueOrDefault(uid)?.LastTimeRemote ?? default;
|
||||
telemetriesStats.GetValueOrDefault(uid)?.TelemetryDateMax ?? default;
|
||||
|
||||
|
||||
public DatesRangeDto GetTelemetryDateRangeByUid(string uid)
|
||||
{
|
||||
var stat = telemetriesStats.GetValueOrDefault(uid);
|
||||
var range = new DatesRangeDto
|
||||
{
|
||||
From = stat?.TelemetryDateMin ?? default,
|
||||
To = stat?.TelemetryDateMax ?? default,
|
||||
};
|
||||
return range;
|
||||
}
|
||||
|
||||
public IEnumerable<string> GetTransmittingTelemetriesUids() =>
|
||||
requests.Keys;
|
||||
telemetriesStats.Keys;
|
||||
}
|
||||
}
|
||||
|
92
AsbCloudInfrastructure/Services/TimeZoneService.cs
Normal file
92
AsbCloudInfrastructure/Services/TimeZoneService.cs
Normal file
@ -0,0 +1,92 @@
|
||||
using AsbCloudApp.Services;
|
||||
using System.Net.Http;
|
||||
using AsbCloudApp.Data;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System;
|
||||
|
||||
namespace AsbCloudInfrastructure.Services
|
||||
{
|
||||
public class TimeZoneService : ITimeZoneService
|
||||
{
|
||||
class TimeZoneInfo
|
||||
{
|
||||
public string Sunrise { get; set; }
|
||||
public double Lng { get; set; }
|
||||
public double Lat { get; set; }
|
||||
public string CountryCode { get; set; }
|
||||
public double GmtOffset { get; set; }
|
||||
public double RawOffset { get; set; }
|
||||
public string Sunset { get; set; }
|
||||
public string TimezoneId { get; set; }
|
||||
public double DstOffset { get; set; }
|
||||
public string CountryName { get; set; }
|
||||
public string Time { get; set; }
|
||||
}
|
||||
|
||||
private readonly string timeZoneApiUrl = "http://api.geonames.org/timezoneJSON";
|
||||
private readonly string timezoneApiUserName = "asbautodrilling";
|
||||
|
||||
public async Task<TelemetryTimeZoneDto> GetByCoordinatesAsync(double latitude, double longitude, CancellationToken token)
|
||||
{
|
||||
var lat = latitude.ToString(System.Globalization.CultureInfo.InvariantCulture);
|
||||
var lng = longitude.ToString(System.Globalization.CultureInfo.InvariantCulture);
|
||||
|
||||
var url =
|
||||
$"{timeZoneApiUrl}?lat={lat}&lng={lng}&username={timezoneApiUserName}";
|
||||
|
||||
using var client = new HttpClient();
|
||||
|
||||
var response = await client.GetAsync(url, token)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
var responseJson = await response.Content.ReadAsStringAsync(token)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
if (!(responseJson.Contains("timezoneId") && responseJson.Contains("dstOffset")))
|
||||
return null;
|
||||
|
||||
var options = new JsonSerializerOptions
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
var timeZoneInfo = JsonSerializer.Deserialize<TimeZoneInfo>(responseJson, options);
|
||||
|
||||
return new TelemetryTimeZoneDto
|
||||
{
|
||||
Hours = timeZoneInfo.DstOffset,
|
||||
IsOverride = false,
|
||||
TimeZoneId = timeZoneInfo.TimezoneId,
|
||||
};
|
||||
}
|
||||
|
||||
public DateTime DateToUtc(DateTime date, double remoteTimezoneOffsetHours)
|
||||
{
|
||||
if (date == default)
|
||||
return new DateTime(0, DateTimeKind.Utc);
|
||||
|
||||
var newDate = date.Kind switch
|
||||
{
|
||||
DateTimeKind.Local => date.ToUniversalTime(),
|
||||
DateTimeKind.Unspecified => date.AddHours(-remoteTimezoneOffsetHours),
|
||||
_ => date,
|
||||
};
|
||||
return DateTime.SpecifyKind(newDate, DateTimeKind.Utc);
|
||||
}
|
||||
|
||||
public DateTime DateToTimeZone(DateTime date, double remoteTimezoneOffsetHours)
|
||||
{
|
||||
if (date == default)
|
||||
return new DateTime(0, DateTimeKind.Unspecified);
|
||||
|
||||
var newDate = date.Kind switch
|
||||
{
|
||||
DateTimeKind.Local => date.ToUniversalTime().AddHours(remoteTimezoneOffsetHours),
|
||||
DateTimeKind.Utc => date.AddHours(remoteTimezoneOffsetHours),
|
||||
_ => date,
|
||||
};
|
||||
return DateTime.SpecifyKind(newDate, DateTimeKind.Unspecified);
|
||||
}
|
||||
}
|
||||
}
|
@ -110,6 +110,7 @@ namespace AsbCloudInfrastructure.Services
|
||||
|
||||
return dto;
|
||||
}
|
||||
|
||||
public async Task<string> GetWellCaptionByIdAsync(int idWell, CancellationToken token)
|
||||
{
|
||||
var entity = await cacheWells.FirstOrDefaultAsync(w => w.Id == idWell, token).ConfigureAwait(false);
|
||||
@ -138,30 +139,14 @@ namespace AsbCloudInfrastructure.Services
|
||||
};
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<int>> GetClusterWellsIdsAsync(int idWell, CancellationToken token)
|
||||
{
|
||||
var well = await cacheWells.FirstOrDefaultAsync(w => w.Id == idWell)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
if (well is null)
|
||||
return null;
|
||||
|
||||
var clusterWells = await cacheWells.WhereAsync(w => w.IdCluster == well.IdCluster)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
return clusterWells.Select(w => w.Id);
|
||||
|
||||
}
|
||||
|
||||
private WellDto Convert(Well well)
|
||||
{
|
||||
return new WellDto
|
||||
{
|
||||
Id = well.Id,
|
||||
Caption = well.Caption,
|
||||
IdCluster = well.IdCluster,
|
||||
Cluster = well.Cluster.Caption,
|
||||
Deposit = well.Cluster.Deposit.Caption,
|
||||
Cluster = well.Cluster?.Caption,
|
||||
Deposit = well.Cluster?.Deposit?.Caption,
|
||||
LastTelemetryDate = GetLastTelemetryDate(well.Id),
|
||||
IdWellType = well.IdWellType ?? default,
|
||||
IdState = well.IdState,
|
||||
|
@ -42,5 +42,7 @@
|
||||
<Folder Include="wwwroot\admin\" />
|
||||
</ItemGroup>
|
||||
|
||||
<ProjectExtensions><VisualStudio><UserProperties appsettings_1json__JsonSchema="" /></VisualStudio></ProjectExtensions>
|
||||
|
||||
|
||||
</Project>
|
||||
|
@ -31,6 +31,7 @@ namespace AsbCloudWebApi.Controllers
|
||||
/// <param name="skip">для пагинации кол-во записей пропустить</param>
|
||||
/// <param name="take">для пагинации кол-во записей </param>
|
||||
/// <param name="searchString"> Строка поиска </param>
|
||||
/// <param name="isUtc">Даты в формате UTC или часового пояса скважины</param>
|
||||
/// <param name="token">Токен для отмены задачи</param>
|
||||
/// <returns>список сообщений по скважине</returns>
|
||||
[HttpGet]
|
||||
@ -39,6 +40,7 @@ namespace AsbCloudWebApi.Controllers
|
||||
[FromQuery] IEnumerable<int> categoryids = default,
|
||||
DateTime begin = default, DateTime end = default,
|
||||
string searchString = default,
|
||||
bool isUtc = true,
|
||||
CancellationToken token = default)
|
||||
{
|
||||
if (take > 1024)
|
||||
@ -49,7 +51,7 @@ namespace AsbCloudWebApi.Controllers
|
||||
|
||||
var result = await messageService.GetMessagesAsync(idWell,
|
||||
categoryids, begin, end, searchString,
|
||||
skip, take, token).ConfigureAwait(false);
|
||||
skip, take, isUtc, token).ConfigureAwait(false);
|
||||
|
||||
if (result is null || result.Count == 0)
|
||||
return NoContent();
|
||||
@ -62,11 +64,12 @@ namespace AsbCloudWebApi.Controllers
|
||||
/// </summary>
|
||||
/// <param name="idWell">id скважины</param>
|
||||
/// <param name="token">Токен для отмены задачи</param>
|
||||
/// <param name="isUtc">Смена дат с UTC формата на часовой пояс скважины</param>
|
||||
/// <returns>список сообщений по скважине</returns>
|
||||
[HttpGet]
|
||||
[Route("datesRange")]
|
||||
[ProducesResponseType(typeof(DatesRangeDto), (int)System.Net.HttpStatusCode.OK)]
|
||||
public async Task<IActionResult> GetMessagesDateRangeAsync(int idWell,
|
||||
public async Task<IActionResult> GetMessagesDateRangeAsync(int idWell, bool isUtc = true,
|
||||
CancellationToken token = default)
|
||||
{
|
||||
int? idCompany = User.GetCompanyId();
|
||||
@ -80,8 +83,8 @@ namespace AsbCloudWebApi.Controllers
|
||||
if (!isCompanyOwnsWell)
|
||||
return Forbid();
|
||||
|
||||
DatesRangeDto wellMessagesDatesRange = await messageService.GetMessagesDatesRangeAsync(idWell,
|
||||
token);
|
||||
var wellMessagesDatesRange = await messageService.GetMessagesDatesRangeAsync(idWell,
|
||||
isUtc, token);
|
||||
|
||||
return Ok(wellMessagesDatesRange);
|
||||
}
|
||||
|
@ -167,11 +167,12 @@ namespace AsbCloudWebApi.Controllers
|
||||
/// </summary>
|
||||
/// <param name="idWell">id скважины</param>
|
||||
/// <param name="token">Токен для отмены задачи</param>
|
||||
/// <param name="isUtc">Смена дат с UTC формата на часовой пояс скважины</param>
|
||||
/// <returns>Даты самого старого и самого свежего отчетов в БД</returns>
|
||||
[HttpGet]
|
||||
[Route("datesRange")]
|
||||
[ProducesResponseType(typeof(DatesRangeDto), (int)System.Net.HttpStatusCode.OK)]
|
||||
public async Task<IActionResult> GetReportsDateRangeAsync(int idWell,
|
||||
public async Task<IActionResult> GetReportsDateRangeAsync(int idWell, bool isUtc = true,
|
||||
CancellationToken token = default)
|
||||
{
|
||||
int? idCompany = User.GetCompanyId();
|
||||
@ -183,7 +184,7 @@ namespace AsbCloudWebApi.Controllers
|
||||
idWell, token).ConfigureAwait(false))
|
||||
return Forbid();
|
||||
|
||||
DatesRangeDto wellReportsDatesRange = await reportService.GetReportsDatesRangeAsync(idWell,
|
||||
var wellReportsDatesRange = await reportService.GetReportsDatesRangeAsync(idWell, isUtc,
|
||||
token).ConfigureAwait(false);
|
||||
|
||||
return Ok(wellReportsDatesRange);
|
||||
|
@ -176,11 +176,12 @@ namespace AsbCloudWebApi.Controllers
|
||||
/// </summary>
|
||||
/// <param name="idWell">id скважины</param>
|
||||
/// <param name="token">Токен для отмены задачи</param>
|
||||
/// <param name="isUtc">Смена дат с UTC формата на часовой пояс скважины</param>
|
||||
/// <returns>Даты самой первой и самой последней операций на скважине</returns>
|
||||
[HttpGet]
|
||||
[Route("datesRange")]
|
||||
[ProducesResponseType(typeof(DatesRangeDto), (int)System.Net.HttpStatusCode.OK)]
|
||||
public async Task<IActionResult> GetOperationsDateRangeAsync(int idWell,
|
||||
public async Task<IActionResult> GetOperationsDateRangeAsync(int idWell, bool isUtc = true,
|
||||
CancellationToken token = default)
|
||||
{
|
||||
int? idCompany = User.GetCompanyId();
|
||||
@ -192,8 +193,8 @@ namespace AsbCloudWebApi.Controllers
|
||||
idWell, token).ConfigureAwait(false))
|
||||
return Forbid();
|
||||
|
||||
DatesRangeDto wellOperationsDatesRange = await analyticsService.GetOperationsDateRangeAsync(idWell,
|
||||
token).ConfigureAwait(false);
|
||||
var wellOperationsDatesRange = await analyticsService.GetOperationsDateRangeAsync(idWell,
|
||||
isUtc, token).ConfigureAwait(false);
|
||||
|
||||
return Ok(wellOperationsDatesRange);
|
||||
}
|
||||
|
@ -42,13 +42,32 @@ namespace AsbCloudWebApi.Controllers
|
||||
/// Принимает общую информацию по скважине
|
||||
/// </summary>
|
||||
/// <param name="uid">Уникальный идентификатор отправителя</param>
|
||||
/// <param name="info">нформация об отправителе</param>
|
||||
/// <param name="info">Информация об отправителе</param>
|
||||
/// <param name="token">Токен отмены задачи</param>
|
||||
/// <returns></returns>
|
||||
[HttpPost]
|
||||
[Route("{uid}/info")]
|
||||
public IActionResult PostInfo(string uid, [FromBody] TelemetryInfoDto info)
|
||||
public async Task<IActionResult> PostInfoAsync(string uid, [FromBody] TelemetryInfoDto info,
|
||||
CancellationToken token = default)
|
||||
{
|
||||
telemetryService.UpdateInfo(uid, info);
|
||||
await telemetryService.UpdateInfoAsync(uid, info, token).ConfigureAwait(false);
|
||||
return Ok();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Обновляет часовой пояс скважины
|
||||
/// </summary>
|
||||
/// <param name="uid">Уникальный идентификатор отправителя</param>
|
||||
/// <param name="timeZoneInfo">Информация о часовом поясе</param>
|
||||
/// <param name="token">Токен отмены задачи</param>
|
||||
/// <returns></returns>
|
||||
[HttpPost]
|
||||
[Route("{uid}/timeZone")]
|
||||
public async Task<IActionResult> UpdateTimeZoneAsync(string uid, TelemetryTimeZoneDto timeZoneInfo,
|
||||
CancellationToken token = default)
|
||||
{
|
||||
await telemetryService.UpdateTimeZoneAsync(uid, timeZoneInfo, token)
|
||||
.ConfigureAwait(false);
|
||||
return Ok();
|
||||
}
|
||||
|
||||
@ -104,33 +123,5 @@ namespace AsbCloudWebApi.Controllers
|
||||
telemetryUserService.Upsert(uid, users);
|
||||
return Ok();
|
||||
}
|
||||
|
||||
///// <summary>
|
||||
///// Загрузка архива (sqlite3).
|
||||
///// <example>
|
||||
///// var fileName = @"C:\temp\default.sqlite3";
|
||||
///// var fileStream = System.IO.File.OpenRead(fileName);
|
||||
///// var file = new FileParameter(fileStream, System.IO.Path.GetFileName(fileName));
|
||||
///// cli.ApiTelemetryDbAsync("1", new List<FileParameter> { file }).Wait();
|
||||
///// </example>
|
||||
///// </summary>
|
||||
///// <param name="uid"></param>
|
||||
///// <param name="files"></param>
|
||||
///// <returns></returns>
|
||||
//[HttpPost]
|
||||
//[Route("{uid}/db")]
|
||||
//public IActionResult PostDb(string uid, IFormFileCollection files)
|
||||
//{
|
||||
// foreach (var file in files)
|
||||
// {
|
||||
// var fileName = string.IsNullOrEmpty(file.FileName)
|
||||
// ? System.IO.Path.GetTempFileName()
|
||||
// : file.FileName;
|
||||
// using (var stream = System.IO.File.Create(fileName))
|
||||
// file.CopyTo(stream);
|
||||
// }
|
||||
// return Ok();
|
||||
//}
|
||||
|
||||
}
|
||||
}
|
||||
|
@ -68,11 +68,12 @@ namespace AsbCloudWebApi.Controllers
|
||||
/// <param name="begin">дата начала выборки. По умолчанию: текущее время - intervalSec</param>
|
||||
/// <param name="intervalSec">интервал времени даты начала выборки, секунды</param>
|
||||
/// <param name="approxPointsCount">желаемое количество точек. Если в выборке точек будет больше, то выборка будет прорежена.</param>
|
||||
/// <param name="isUtc">Даты в формате UTC или часового пояса скважины</param>
|
||||
/// <param name="token">Токен завершения задачи</param>
|
||||
/// <returns></returns>
|
||||
[HttpGet("{idWell}")]
|
||||
public virtual async Task<ActionResult<TDto>> GetDataAsync(int idWell, DateTime begin = default,
|
||||
int intervalSec = 600, int approxPointsCount = 1024, CancellationToken token = default)
|
||||
int intervalSec = 600, int approxPointsCount = 1024, bool isUtc = false, CancellationToken token = default)
|
||||
{
|
||||
int? idCompany = User.GetCompanyId();
|
||||
|
||||
@ -86,7 +87,7 @@ namespace AsbCloudWebApi.Controllers
|
||||
return Forbid();
|
||||
|
||||
var content = await telemetryDataService.GetAsync(idWell, begin,
|
||||
intervalSec, approxPointsCount, token).ConfigureAwait(false);
|
||||
intervalSec, approxPointsCount, isUtc, token).ConfigureAwait(false);
|
||||
|
||||
return Ok(content);
|
||||
}
|
||||
@ -95,12 +96,13 @@ namespace AsbCloudWebApi.Controllers
|
||||
/// Возвращает диапазон дат сохраненных данных.
|
||||
/// </summary>
|
||||
/// <param name="idWell">id скважины</param>
|
||||
/// <param name="isUtc">Смена дат с UTC формата на часовой пояс скважины</param>
|
||||
/// <param name="token">Токен завершения задачи</param>
|
||||
/// <returns></returns>
|
||||
[HttpGet]
|
||||
[Route("{idWell}/datesRange")]
|
||||
[ProducesResponseType(typeof(DatesRangeDto), (int)System.Net.HttpStatusCode.OK)]
|
||||
public virtual async Task<IActionResult> GetDataDatesRangeAsync(int idWell,
|
||||
public virtual async Task<IActionResult> GetDataDatesRangeAsync(int idWell, bool isUtc = false,
|
||||
CancellationToken token = default)
|
||||
{
|
||||
int? idCompany = User.GetCompanyId();
|
||||
@ -114,7 +116,7 @@ namespace AsbCloudWebApi.Controllers
|
||||
if (!isCompanyOwnsWell)
|
||||
return Forbid();
|
||||
|
||||
var dataDatesRange = await telemetryDataService.GetDataDatesRangeAsync(idWell,
|
||||
var dataDatesRange = await telemetryDataService.GetDataDatesRangeAsync(idWell, isUtc,
|
||||
token).ConfigureAwait(false);
|
||||
|
||||
return Ok(dataDatesRange);
|
||||
|
12
AsbCloudWebApi/Docs/Timezone info api credentials.md
Normal file
12
AsbCloudWebApi/Docs/Timezone info api credentials.md
Normal file
@ -0,0 +1,12 @@
|
||||
# url
|
||||
https://www.geonames.org/commercial-webservices.html
|
||||
|
||||
# учетная запись для аутентификации на сайте
|
||||
Имя пользователя: asbautodrilling
|
||||
Пароль: asbautodrilling1!
|
||||
|
||||
# имя пользователя для запросов
|
||||
asbautodrilling
|
||||
|
||||
# Пример запроса
|
||||
http://api.geonames.org/timezoneJSON?lat=60.8705722222222&lng=70.3811888888889&username=asbautodrilling
|
@ -7,6 +7,7 @@ namespace AsbCloudWebApi
|
||||
{
|
||||
public static void Main(string[] args)
|
||||
{
|
||||
//new TraceListenerView(); // to trace mysterious errors
|
||||
CreateHostBuilder(args).Build().Run();
|
||||
}
|
||||
|
||||
|
31
AsbCloudWebApi/TraceListenerView.cs
Normal file
31
AsbCloudWebApi/TraceListenerView.cs
Normal file
@ -0,0 +1,31 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace AsbCloudWebApi
|
||||
{
|
||||
public class TraceListenerView : TraceListener
|
||||
{
|
||||
public TraceListenerView()
|
||||
{
|
||||
Trace.Listeners.Add(this);
|
||||
}
|
||||
|
||||
public override void Write(object o)
|
||||
{
|
||||
base.Write(o);
|
||||
}
|
||||
|
||||
public override void Write(string message)
|
||||
{
|
||||
//throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public override void WriteLine(string message)
|
||||
{
|
||||
//throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
}
|
@ -7,7 +7,7 @@
|
||||
}
|
||||
},
|
||||
"ConnectionStrings": {
|
||||
"DefaultConnection": "Host=localhost;Database=postgres;Username=postgres;Password=q;Persist Security Info=True;",
|
||||
"DefaultConnection": "Host=localhost;Database=postgres;Username=postgres;Password=q;Persist Security Info=True",
|
||||
"DebugConnection": "Host=localhost;Database=postgres;Username=postgres;Password=q;Persist Security Info=True;Include Error Detail=True",
|
||||
"ServerConnection": "Host=192.168.1.70;Database=postgres;Username=postgres;Password=q;Persist Security Info=True",
|
||||
"LocalConnection": "Host=localhost;Database=postgres;Username=postgres;Password=q;Persist Security Info=True"
|
||||
|
@ -1,8 +0,0 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net5.0</TargetFramework>
|
||||
</PropertyGroup>
|
||||
|
||||
</Project>
|
@ -1,13 +0,0 @@
|
||||
using System;
|
||||
|
||||
namespace DataTable
|
||||
{
|
||||
[Serializable]
|
||||
public class Header
|
||||
{
|
||||
public string Name { get; set; }
|
||||
public string Desctiption { get; set; }
|
||||
//public System.Type ColumnType { get; set; } = typeof(object);
|
||||
public string ColumnType { get; set; }
|
||||
}
|
||||
}
|
@ -1,83 +0,0 @@
|
||||
namespace DataTable
|
||||
{
|
||||
class Program
|
||||
{
|
||||
static void Main(/*string[] args*/)
|
||||
{
|
||||
//var listDtos = new List<TestDto>(100);
|
||||
|
||||
/* *** Size of TestDto calc ***
|
||||
*
|
||||
* ** data binary size (Not implemented) **
|
||||
* Date : DateTime : 4b
|
||||
* Mode : int32? : 4b
|
||||
* User : string : 2-64b
|
||||
* WellDepth : double? : 8b
|
||||
* TOTAL data size = 18-80b
|
||||
*
|
||||
* ** header binary size (Not implemented) **
|
||||
*
|
||||
*DateTime : len("DateTime") + 2 + len("Date") + 2 = 16b
|
||||
* Mode : 14b
|
||||
* User : 14b
|
||||
* WellDepth : 20b
|
||||
* columnsCount : 2b
|
||||
* TOTAL header size = 66b
|
||||
*
|
||||
* ** json as tab **
|
||||
*
|
||||
* header size: 137b
|
||||
* json row size: 63b
|
||||
*
|
||||
* total for 1 record : 200b
|
||||
* total for 2 records : 263b
|
||||
*
|
||||
* ** json as list **
|
||||
*
|
||||
* Raw listItem size: 175b
|
||||
* total for 2 records : 350b
|
||||
*
|
||||
* ** example 100 records **
|
||||
* tabJsonBytes: 6602
|
||||
* listJsonBytes: 9628
|
||||
* tabBinBytes: 7765 (by dangerous BinaryFormatter)
|
||||
* listBinBytes: 4366 (by dangerous BinaryFormatter)
|
||||
*/
|
||||
|
||||
//for (int i = 0; i < 100; i++)
|
||||
// listDtos.Add(new TestDto{
|
||||
// Date = DateTime.Now.AddSeconds(i),
|
||||
// Mode = 1,
|
||||
// WellDepth = i * Math.PI
|
||||
// });
|
||||
|
||||
//var tMapper = new TableMapper<TestDto>();
|
||||
|
||||
//var tab = tMapper.MakeTable(listDtos);
|
||||
|
||||
//var e = tMapper.AsEnumerable(tab);
|
||||
|
||||
//var tabJson = JsonSerializer.Serialize(tab);
|
||||
//var listJson = JsonSerializer.Serialize(listDtos);
|
||||
|
||||
//var tabJsonBytes = JsonSerializer.SerializeToUtf8Bytes(tab);
|
||||
//var listJsonBytes = JsonSerializer.SerializeToUtf8Bytes(listDtos);
|
||||
|
||||
//var formatter = new BinaryFormatter();
|
||||
//var mem = new MemoryStream();
|
||||
//formatter.Serialize(mem, tab);
|
||||
//var tabBinBytes = new byte[mem.Length];
|
||||
//Array.Copy(mem.GetBuffer(), tabBinBytes, mem.Length);
|
||||
|
||||
//mem = new MemoryStream();
|
||||
//formatter.Serialize(mem, listDtos);
|
||||
//var listBinBytes = new byte[mem.Length];
|
||||
//Array.Copy(mem.GetBuffer(), listBinBytes, mem.Length);
|
||||
|
||||
//Console.WriteLine($"tabJsonBytes:{tabJsonBytes.Length}");
|
||||
//Console.WriteLine($"listJsonBytes:{listJsonBytes.Length}");
|
||||
//Console.WriteLine($"tabBinBytes:{tabBinBytes.Length}");
|
||||
//Console.WriteLine($"listBinBytes:{listBinBytes.Length}");
|
||||
}
|
||||
}
|
||||
}
|
@ -1,62 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Linq.Expressions;
|
||||
using System.Reflection;
|
||||
|
||||
namespace DataTable
|
||||
{
|
||||
/// <summary>
|
||||
/// Ускоренный обработчик свойства
|
||||
/// </summary>
|
||||
class PropertyHelper
|
||||
{
|
||||
delegate void SetterDelegate(object instanse, object[] values);
|
||||
|
||||
delegate object GetterDelegate(object instanse);
|
||||
|
||||
public string PropertyName { get; }
|
||||
public string PropertyDesctiption { get; }
|
||||
public Type PropertyType { get; }
|
||||
public string Id { get; }
|
||||
|
||||
SetterDelegate Setter { get; }
|
||||
GetterDelegate Getter { get; }
|
||||
public PropertyHelper(PropertyInfo property)
|
||||
{
|
||||
PropertyName = property.Name;
|
||||
PropertyType = property.PropertyType;
|
||||
Id = MakeIdentity(property.PropertyType.Name, property.Name);
|
||||
PropertyDesctiption = GetDescription(property);
|
||||
|
||||
var setter = property.SetMethod;
|
||||
var getter = property.GetMethod;
|
||||
|
||||
var instanceExpression = Expression.Parameter(typeof(object), "instance");
|
||||
var argumentsExpression = Expression.Parameter(typeof(object[]), "arguments");
|
||||
var argumentExpressions = new List<Expression> { Expression.Convert(Expression.ArrayIndex(argumentsExpression, Expression.Constant(0)), PropertyType) };
|
||||
var callExpression = Expression.Call(Expression.Convert(instanceExpression, setter.ReflectedType), setter, argumentExpressions);
|
||||
Setter = Expression.Lambda<SetterDelegate>(callExpression, instanceExpression, argumentsExpression).Compile();
|
||||
callExpression = Expression.Call(Expression.Convert(instanceExpression, getter.ReflectedType), getter);
|
||||
Getter = Expression.Lambda<GetterDelegate>(Expression.Convert(callExpression, typeof(object)), instanceExpression).Compile();
|
||||
}
|
||||
|
||||
private string GetDescription(PropertyInfo property)
|
||||
{
|
||||
var descriptionAttr = property.GetCustomAttribute<DescriptionAttribute>();
|
||||
return descriptionAttr?.Description ?? string.Empty;
|
||||
}
|
||||
|
||||
void SetValues(object instance, params object[] values)
|
||||
=> Setter(instance, values);
|
||||
|
||||
public void Set(object instance, object value)
|
||||
=> SetValues(instance, value);
|
||||
|
||||
public object Get(object instance)
|
||||
=> Getter(instance);
|
||||
|
||||
public static string MakeIdentity(string propertyTypeName, string propertyName)
|
||||
=> $"{propertyTypeName}_{propertyName}".ToLower();
|
||||
}
|
||||
}
|
@ -1,14 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace DataTable
|
||||
{
|
||||
[Serializable]
|
||||
public class Table
|
||||
{
|
||||
public IEnumerable<Header> Headers { get; set; }
|
||||
|
||||
public IEnumerable<IEnumerable<object>> Rows { get; set; }
|
||||
|
||||
}
|
||||
}
|
@ -1,87 +0,0 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
namespace DataTable
|
||||
{
|
||||
public class TableMapper<T>
|
||||
where T : new()
|
||||
{
|
||||
private readonly Dictionary<string, PropertyHelper> props;
|
||||
|
||||
public TableMapper()
|
||||
{
|
||||
var props = typeof(T).GetProperties();
|
||||
this.props = new Dictionary<string, PropertyHelper>(props.Length);
|
||||
foreach (var prop in props)
|
||||
{
|
||||
var helper = new PropertyHelper(prop);
|
||||
this.props.Add(helper.Id, helper);
|
||||
}
|
||||
}
|
||||
|
||||
public IEnumerable<T> AsEnumerable(Table table)
|
||||
{
|
||||
if ((table?.Headers is null) ||
|
||||
(table?.Rows is null) ||
|
||||
(!table.Headers.Any()) ||
|
||||
(!table.Rows.Any()) ||
|
||||
(!props.Any()))
|
||||
yield break;
|
||||
|
||||
var headerIdToProp = new Dictionary<int, PropertyHelper>(props.Count);
|
||||
foreach (var (_, propHelper) in props)
|
||||
for (var i = 0; i < table.Headers.Count(); i++)
|
||||
{
|
||||
var header = table.Headers.ElementAt(i);
|
||||
var columnType = System.Type.GetType(header.ColumnType);
|
||||
if (columnType.IsAssignableTo(propHelper.PropertyType) &&
|
||||
((header.Name == propHelper.PropertyName) ||
|
||||
(header.Name.ToLower() == propHelper.PropertyName.ToLower())))
|
||||
headerIdToProp.Add(i, propHelper);
|
||||
}
|
||||
|
||||
if (!headerIdToProp.Any())
|
||||
yield break;
|
||||
|
||||
foreach (var row in table.Rows)
|
||||
{
|
||||
var obj = new T();
|
||||
foreach (var (i, propHelper) in headerIdToProp)
|
||||
propHelper.Set(obj, row.ElementAt(i));
|
||||
yield return obj;
|
||||
}
|
||||
|
||||
yield break;
|
||||
}
|
||||
|
||||
public Table MakeTable(IEnumerable<T> data)
|
||||
{
|
||||
var table = new Table();
|
||||
table.Headers = props.Select(pair => new Header
|
||||
{
|
||||
Name = pair.Value.PropertyName,
|
||||
ColumnType = pair.Value.PropertyType.Name,
|
||||
}).ToArray();
|
||||
|
||||
var rows = new List<List<object>>(data.Count());
|
||||
foreach (var dataItem in data)
|
||||
rows.Add(MakeRow(dataItem));
|
||||
|
||||
table.Rows = rows;
|
||||
|
||||
return table;
|
||||
}
|
||||
|
||||
private List<object> MakeRow(T dataItem)
|
||||
{
|
||||
var colunms = new List<object>(props.Count);
|
||||
foreach (var (_, propHelper) in props)
|
||||
{
|
||||
var propValue = propHelper.Get(dataItem);
|
||||
colunms.Add(propValue);
|
||||
}
|
||||
return colunms;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
@ -1,20 +0,0 @@
|
||||
using System;
|
||||
using System.ComponentModel;
|
||||
|
||||
namespace DataTable
|
||||
{
|
||||
[Serializable]
|
||||
public class TestDto
|
||||
{
|
||||
[Description("Дата")]
|
||||
public DateTime Date { get; set; } = DateTime.Now;
|
||||
|
||||
public int? Mode { get; set; }
|
||||
|
||||
[Description("Пользователь")]
|
||||
public string User { get; set; }
|
||||
|
||||
[Description("Глубина забоя")]
|
||||
public double? WellDepth { get; set; }
|
||||
}
|
||||
}
|
File diff suppressed because it is too large
Load Diff
@ -1,99 +0,0 @@
|
||||
{
|
||||
"runtime": "NetCore21",
|
||||
"defaultVariables": null,
|
||||
"documentGenerator": {
|
||||
"fromDocument": {
|
||||
"url": "https://localhost:5001/swagger/v1/swagger.json",
|
||||
"output": "AsbCloudApi.nswag.json",
|
||||
"newLineBehavior": "Auto"
|
||||
}
|
||||
},
|
||||
"codeGenerators": {
|
||||
"openApiToCSharpClient": {
|
||||
"clientBaseClass": null,
|
||||
"configurationClass": null,
|
||||
"generateClientClasses": true,
|
||||
"generateClientInterfaces": false,
|
||||
"clientBaseInterface": null,
|
||||
"injectHttpClient": true,
|
||||
"disposeHttpClient": true,
|
||||
"protectedMethods": [],
|
||||
"generateExceptionClasses": true,
|
||||
"exceptionClass": "ApiException",
|
||||
"wrapDtoExceptions": true,
|
||||
"useHttpClientCreationMethod": false,
|
||||
"httpClientType": "System.Net.Http.HttpClient",
|
||||
"useHttpRequestMessageCreationMethod": false,
|
||||
"useBaseUrl": true,
|
||||
"generateBaseUrlProperty": true,
|
||||
"generateSyncMethods": false,
|
||||
"generatePrepareRequestAndProcessResponseAsAsyncMethods": false,
|
||||
"exposeJsonSerializerSettings": false,
|
||||
"clientClassAccessModifier": "public",
|
||||
"typeAccessModifier": "public",
|
||||
"generateContractsOutput": false,
|
||||
"contractsNamespace": null,
|
||||
"contractsOutputFilePath": null,
|
||||
"parameterDateTimeFormat": "s",
|
||||
"parameterDateFormat": "yyyy-MM-dd",
|
||||
"generateUpdateJsonSerializerSettingsMethod": true,
|
||||
"useRequestAndResponseSerializationSettings": false,
|
||||
"serializeTypeInformation": false,
|
||||
"queryNullValue": "",
|
||||
"className": "{controller}Client",
|
||||
"operationGenerationMode": "SingleClientFromPathSegments",
|
||||
"additionalNamespaceUsages": [],
|
||||
"additionalContractNamespaceUsages": [],
|
||||
"generateOptionalParameters": false,
|
||||
"generateJsonMethods": false,
|
||||
"enforceFlagEnums": false,
|
||||
"parameterArrayType": "System.Collections.Generic.IEnumerable",
|
||||
"parameterDictionaryType": "System.Collections.Generic.IDictionary",
|
||||
"responseArrayType": "System.Collections.Generic.ICollection",
|
||||
"responseDictionaryType": "System.Collections.Generic.IDictionary",
|
||||
"wrapResponses": false,
|
||||
"wrapResponseMethods": [],
|
||||
"generateResponseClasses": true,
|
||||
"responseClass": "SwaggerResponse",
|
||||
"namespace": "SyncDicts.AsbCloudApi",
|
||||
"requiredPropertiesMustBeDefined": true,
|
||||
"dateType": "System.DateTimeOffset",
|
||||
"jsonConverters": null,
|
||||
"anyType": "object",
|
||||
"dateTimeType": "System.DateTimeOffset",
|
||||
"timeType": "System.TimeSpan",
|
||||
"timeSpanType": "System.TimeSpan",
|
||||
"arrayType": "System.Collections.Generic.ICollection",
|
||||
"arrayInstanceType": "System.Collections.ObjectModel.Collection",
|
||||
"dictionaryType": "System.Collections.Generic.IDictionary",
|
||||
"dictionaryInstanceType": "System.Collections.Generic.Dictionary",
|
||||
"arrayBaseType": "System.Collections.ObjectModel.Collection",
|
||||
"dictionaryBaseType": "System.Collections.Generic.Dictionary",
|
||||
"classStyle": "Poco",
|
||||
"jsonLibrary": "SystemTextJson",
|
||||
"generateDefaultValues": true,
|
||||
"generateDataAnnotations": true,
|
||||
"excludedTypeNames": [],
|
||||
"excludedParameterNames": [],
|
||||
"handleReferences": false,
|
||||
"generateImmutableArrayProperties": false,
|
||||
"generateImmutableDictionaryProperties": false,
|
||||
"jsonSerializerSettingsTransformationMethod": null,
|
||||
"inlineNamedArrays": false,
|
||||
"inlineNamedDictionaries": false,
|
||||
"inlineNamedTuples": true,
|
||||
"inlineNamedAny": false,
|
||||
"generateDtoTypes": true,
|
||||
"generateOptionalPropertiesAsNullable": false,
|
||||
"generateNullableReferenceTypes": false,
|
||||
"templateDirectory": null,
|
||||
"typeNameGeneratorType": null,
|
||||
"propertyNameGeneratorType": null,
|
||||
"enumNameGeneratorType": null,
|
||||
"serviceHost": null,
|
||||
"serviceSchemes": null,
|
||||
"output": "AsbCloudApi.cs",
|
||||
"newLineBehavior": "Auto"
|
||||
}
|
||||
}
|
||||
}
|
File diff suppressed because it is too large
Load Diff
@ -1,162 +0,0 @@
|
||||
{
|
||||
"ProviderId": "Unchase.OpenAPI.ConnectedService",
|
||||
"Version": "1.5.20.0",
|
||||
"GettingStartedDocument": {
|
||||
"Uri": "https://github.com/unchase/Unchase.OpenAPI.Connectedservice/"
|
||||
},
|
||||
"ExtendedData": {
|
||||
"ServiceName": "AsbCloudApi",
|
||||
"GeneratedFileName": "AsbCloudApi",
|
||||
"Endpoint": "https://localhost:5001/swagger/v1/swagger.json",
|
||||
"GeneratedFileNamePrefix": null,
|
||||
"GenerateCSharpClient": true,
|
||||
"GenerateTypeScriptClient": false,
|
||||
"GenerateCSharpController": false,
|
||||
"OpenApiToCSharpClientCommand": {
|
||||
"ClientBaseClass": null,
|
||||
"ConfigurationClass": null,
|
||||
"GenerateClientClasses": true,
|
||||
"GenerateClientInterfaces": false,
|
||||
"ClientBaseInterface": null,
|
||||
"InjectHttpClient": true,
|
||||
"DisposeHttpClient": true,
|
||||
"ProtectedMethods": [],
|
||||
"GenerateExceptionClasses": true,
|
||||
"ExceptionClass": "ApiException",
|
||||
"WrapDtoExceptions": true,
|
||||
"UseHttpClientCreationMethod": false,
|
||||
"HttpClientType": "System.Net.Http.HttpClient",
|
||||
"UseHttpRequestMessageCreationMethod": false,
|
||||
"UseBaseUrl": true,
|
||||
"GenerateBaseUrlProperty": true,
|
||||
"GenerateSyncMethods": false,
|
||||
"GeneratePrepareRequestAndProcessResponseAsAsyncMethods": false,
|
||||
"ExposeJsonSerializerSettings": false,
|
||||
"ClientClassAccessModifier": "public",
|
||||
"TypeAccessModifier": "public",
|
||||
"GenerateContractsOutput": false,
|
||||
"ContractsNamespace": null,
|
||||
"ContractsOutputFilePath": null,
|
||||
"ParameterDateTimeFormat": "s",
|
||||
"ParameterDateFormat": "yyyy-MM-dd",
|
||||
"GenerateUpdateJsonSerializerSettingsMethod": true,
|
||||
"UseRequestAndResponseSerializationSettings": false,
|
||||
"SerializeTypeInformation": false,
|
||||
"QueryNullValue": "",
|
||||
"ClassName": "{controller}Client",
|
||||
"OperationGenerationMode": 5,
|
||||
"AdditionalNamespaceUsages": [],
|
||||
"AdditionalContractNamespaceUsages": [],
|
||||
"GenerateOptionalParameters": false,
|
||||
"GenerateJsonMethods": false,
|
||||
"EnforceFlagEnums": false,
|
||||
"ParameterArrayType": "System.Collections.Generic.IEnumerable",
|
||||
"ParameterDictionaryType": "System.Collections.Generic.IDictionary",
|
||||
"ResponseArrayType": "System.Collections.Generic.ICollection",
|
||||
"ResponseDictionaryType": "System.Collections.Generic.IDictionary",
|
||||
"WrapResponses": false,
|
||||
"WrapResponseMethods": [],
|
||||
"GenerateResponseClasses": true,
|
||||
"ResponseClass": "SwaggerResponse",
|
||||
"Namespace": "SyncDicts.AsbCloudApi",
|
||||
"RequiredPropertiesMustBeDefined": true,
|
||||
"DateType": "System.DateTimeOffset",
|
||||
"JsonConverters": null,
|
||||
"AnyType": "object",
|
||||
"DateTimeType": "System.DateTimeOffset",
|
||||
"TimeType": "System.TimeSpan",
|
||||
"TimeSpanType": "System.TimeSpan",
|
||||
"ArrayType": "System.Collections.Generic.ICollection",
|
||||
"ArrayInstanceType": "System.Collections.ObjectModel.Collection",
|
||||
"DictionaryType": "System.Collections.Generic.IDictionary",
|
||||
"DictionaryInstanceType": "System.Collections.Generic.Dictionary",
|
||||
"ArrayBaseType": "System.Collections.ObjectModel.Collection",
|
||||
"DictionaryBaseType": "System.Collections.Generic.Dictionary",
|
||||
"ClassStyle": 0,
|
||||
"JsonLibrary": 1,
|
||||
"GenerateDefaultValues": true,
|
||||
"GenerateDataAnnotations": true,
|
||||
"ExcludedTypeNames": [],
|
||||
"ExcludedParameterNames": [],
|
||||
"HandleReferences": false,
|
||||
"GenerateImmutableArrayProperties": false,
|
||||
"GenerateImmutableDictionaryProperties": false,
|
||||
"JsonSerializerSettingsTransformationMethod": null,
|
||||
"InlineNamedArrays": false,
|
||||
"InlineNamedDictionaries": false,
|
||||
"InlineNamedTuples": true,
|
||||
"InlineNamedAny": false,
|
||||
"GenerateDtoTypes": true,
|
||||
"GenerateOptionalPropertiesAsNullable": false,
|
||||
"GenerateNullableReferenceTypes": false,
|
||||
"TemplateDirectory": null,
|
||||
"TypeNameGeneratorType": null,
|
||||
"PropertyNameGeneratorType": null,
|
||||
"EnumNameGeneratorType": null,
|
||||
"ServiceHost": null,
|
||||
"ServiceSchemes": null,
|
||||
"output": "AsbCloudApi.cs",
|
||||
"newLineBehavior": 0
|
||||
},
|
||||
"ExcludeTypeNamesLater": false,
|
||||
"OpenApiToTypeScriptClientCommand": null,
|
||||
"OpenApiToCSharpControllerCommand": null,
|
||||
"Variables": null,
|
||||
"Runtime": 0,
|
||||
"CopySpecification": false,
|
||||
"OpenGeneratedFilesOnComplete": false,
|
||||
"UseRelativePath": false,
|
||||
"ConvertFromOdata": false,
|
||||
"OpenApiConvertSettings": {
|
||||
"ServiceRoot": "http://localhost",
|
||||
"Version": {
|
||||
"Major": 1,
|
||||
"Minor": 0,
|
||||
"Build": 1,
|
||||
"Revision": -1,
|
||||
"MajorRevision": -1,
|
||||
"MinorRevision": -1
|
||||
},
|
||||
"EnableKeyAsSegment": null,
|
||||
"EnableUnqualifiedCall": false,
|
||||
"EnableOperationPath": true,
|
||||
"EnableOperationImportPath": true,
|
||||
"EnableNavigationPropertyPath": true,
|
||||
"TagDepth": 4,
|
||||
"PrefixEntityTypeNameBeforeKey": false,
|
||||
"OpenApiSpecVersion": 1,
|
||||
"EnableOperationId": true,
|
||||
"EnableUriEscapeFunctionCall": false,
|
||||
"VerifyEdmModel": false,
|
||||
"IEEE754Compatible": false,
|
||||
"TopExample": 50,
|
||||
"EnablePagination": false,
|
||||
"PageableOperationName": "listMore",
|
||||
"EnableDiscriminatorValue": false,
|
||||
"EnableDerivedTypesReferencesForResponses": false,
|
||||
"EnableDerivedTypesReferencesForRequestBody": false,
|
||||
"PathPrefix": "OData",
|
||||
"RoutePathPrefixProvider": {
|
||||
"PathPrefix": "OData",
|
||||
"Parameters": null
|
||||
},
|
||||
"ShowLinks": false,
|
||||
"ShowSchemaExamples": false,
|
||||
"RequireDerivedTypesConstraintForBoundOperations": false,
|
||||
"ShowRootPath": false,
|
||||
"ShowMsDosGroupPath": true,
|
||||
"PathProvider": null
|
||||
},
|
||||
"OpenApiSpecVersion": 0,
|
||||
"UseNetworkCredentials": false,
|
||||
"NetworkCredentialsUserName": null,
|
||||
"NetworkCredentialsPassword": null,
|
||||
"NetworkCredentialsDomain": null,
|
||||
"WebProxyUri": null,
|
||||
"UseWebProxy": false,
|
||||
"UseWebProxyCredentials": false,
|
||||
"WebProxyNetworkCredentialsUserName": null,
|
||||
"WebProxyNetworkCredentialsPassword": null,
|
||||
"WebProxyNetworkCredentialsDomain": null
|
||||
}
|
||||
}
|
@ -1,120 +0,0 @@
|
||||
using SyncDicts.AsbCloudApi;
|
||||
using System.Collections.Generic;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace SyncDicts
|
||||
{
|
||||
class Program
|
||||
{
|
||||
/// <summary>
|
||||
/// Описывает процесс синхронизации словарей БД
|
||||
/// </summary>
|
||||
/// <param name="args"></param>
|
||||
static void Main(/*string[] args*/)
|
||||
{
|
||||
//bool res;
|
||||
//var context = new ArchiveDbContext(@"c:\temp\default.sqlite3");
|
||||
|
||||
//// sync Events
|
||||
//var events = context.EventsDictionary.ToList()
|
||||
// .Select(e => new EventDto
|
||||
// {
|
||||
// EventType = e.EventType,
|
||||
// Id = e.Id,
|
||||
// IdCategory = e.CategoryId,
|
||||
// IdSound = e.SoundId,
|
||||
// Message = e.MessageTemplate,
|
||||
// Tag = e.Tag,
|
||||
// });
|
||||
|
||||
//var info = new TelemetryInfoDto
|
||||
//{
|
||||
// Caption = "скв 111",
|
||||
// Deposit = "мр 111",
|
||||
// Cluster = "куст 111",
|
||||
// TimeZoneId = TimeZoneInfo.Local.Id,
|
||||
// TimeZoneOffsetTotalHours = TimeZoneInfo.Local.BaseUtcOffset.TotalHours,
|
||||
// Date = DateTime.Now,
|
||||
//};
|
||||
|
||||
//var users = context.Users.ToList()
|
||||
// .Select(u => new TelemetryUserDto
|
||||
// {
|
||||
// Id = u.Id,
|
||||
// Level = u.Level,
|
||||
// Name = u.Name,
|
||||
// Patronymic = u.Patronymic,
|
||||
// Surname = u.Surname,
|
||||
// });
|
||||
|
||||
//var messages = context.Messages.Take(1024).ToList()
|
||||
// .Select(m => new TelemetryMessageDto
|
||||
// {
|
||||
// Id = m.Id,
|
||||
// Date = DateTime.UnixEpoch.AddSeconds(m.TimeStamp),
|
||||
// IdEvent = m.EventItemId,
|
||||
// IdTelemetryUser = m.UserId,
|
||||
// State = m.State,
|
||||
// Arg0 = m.Arg0,
|
||||
// Arg1 = m.Arg1,
|
||||
// Arg2 = m.Arg2,
|
||||
// Arg3 = m.Arg3,
|
||||
// });
|
||||
|
||||
var cli = new AsbCloudApi.Client("https://localhost:5001/", new System.Net.Http.HttpClient());
|
||||
|
||||
var fileName = @"C:\temp\default.sqlite3";
|
||||
var fileStream = System.IO.File.OpenRead(fileName);
|
||||
var file = new FileParameter(fileStream, System.IO.Path.GetFileName(fileName));
|
||||
cli.ApiTelemetryDbAsync("1", new List<FileParameter> { file }).Wait();
|
||||
|
||||
//var cli = new swaggerClient("https://localhost:5001/", new System.Net.Http.HttpClient());
|
||||
//cli.InfoAsync("aaa",info).Wait();
|
||||
|
||||
//res = Send("http://127.0.0.1:5000/api/telemetry/asdasd/event", events);
|
||||
//res = Send("http://127.0.0.1:5000/api/telemetry/asdasd/info", info);
|
||||
//res = Send("http://127.0.0.1:5000/api/telemetry/asdasd/user", users);
|
||||
//res = Send("http://127.0.0.1:5000/api/telemetry/asdasd/message", messages);
|
||||
}
|
||||
|
||||
//private static bool Send<T>(string url, T obj)
|
||||
//{
|
||||
// // sending data
|
||||
// var requestBodyJson = JsonSerializer.Serialize(obj);
|
||||
// var data = Encoding.UTF8.GetBytes(requestBodyJson);
|
||||
|
||||
// var request = MakeRequest(url);
|
||||
// using var streamWriter = request.GetRequestStream();
|
||||
// streamWriter.Write(data);
|
||||
// streamWriter.Close();
|
||||
|
||||
// // getting response
|
||||
// if (request.GetResponse() is not HttpWebResponse response)
|
||||
// {//FAILED
|
||||
// return false;
|
||||
// }
|
||||
|
||||
// if (response.StatusCode == HttpStatusCode.OK)
|
||||
// {// sent succesfilly
|
||||
// return true;
|
||||
// }
|
||||
// else
|
||||
// {//failed
|
||||
// return false;
|
||||
// }
|
||||
//}
|
||||
|
||||
private static HttpWebRequest MakeRequest(string url, string contentType = "application/json")
|
||||
{
|
||||
var request = WebRequest.CreateHttp(url);
|
||||
request.Method = "POST";
|
||||
request.Timeout = 4900;
|
||||
request.ContentType = contentType;
|
||||
request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
|
||||
request.ServicePoint.Expect100Continue = false;
|
||||
return request;
|
||||
}
|
||||
}
|
||||
}
|
@ -1,38 +0,0 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net5.0</TargetFramework>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="5.0.5" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="5.0.5" />
|
||||
<PackageReference Include="Microsoft.Extensions.ApiDescription.Client" Version="3.0.0">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
|
||||
<PackageReference Include="NSwag.ApiDescription.Client" Version="13.0.5">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="System.ComponentModel.Annotations" Version="5.0.0" />
|
||||
<PackageReference Include="System.Net.Http" Version="4.3.4" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\AsbCloudApp\AsbCloudApp.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Reference Include="AsbSaubDbModel">
|
||||
<HintPath>..\..\..\SAUB\asbsaub3\AsbSaubDbModel\bin\Release\netcoreapp3.1\AsbSaubDbModel.dll</HintPath>
|
||||
</Reference>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<WCFMetadata Include="Connected Services" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
Loading…
Reference in New Issue
Block a user