Merge branch 'dev' into feature/27526736-cache-table

This commit is contained in:
on.nemtina 2024-02-02 11:15:29 +05:00
commit d7cd45210a
24 changed files with 716 additions and 581 deletions

View File

@ -0,0 +1,12 @@
using System.Collections.Generic;
namespace AsbCloudApp.Data;
/// <summary>
/// Результат парсинга файла
/// </summary>
/// <typeparam name="TDto"></typeparam>
public class ParserResultDto<TDto> : ValidationResultDto<IEnumerable<ValidationResultDto<TDto>>>
where TDto : class, IId
{
}

View File

@ -5,7 +5,7 @@ namespace AsbCloudApp.Data.Trajectory
/// <summary>
/// Базовая географическая траектория
/// </summary>
public abstract class TrajectoryGeoDto
public abstract class TrajectoryGeoDto : IId
{
/// <summary>
/// ИД строки с координатами

View File

@ -0,0 +1,19 @@
namespace AsbCloudApp.Requests.ParserOptions;
/// <summary>
/// Параметры парсинга
/// </summary>
public interface IParserOptionsRequest
{
private static DummyOptions empty => new();
private class DummyOptions : IParserOptionsRequest
{
}
/// <summary>
/// Получение пустого объекта опций
/// </summary>
/// <returns></returns>
public static IParserOptionsRequest Empty() => empty;
}

View File

@ -0,0 +1,38 @@
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using AsbCloudApp.Data;
using AsbCloudApp.Requests.ParserOptions;
namespace AsbCloudApp.Services;
/// <summary>
/// Сервис парсинга
/// </summary>
/// <typeparam name="TDto"></typeparam>
/// <typeparam name="TOptions"></typeparam>
public interface IParserService<TDto, in TOptions> : IParserService
where TDto : class, IId
where TOptions : IParserOptionsRequest
{
/// <summary>
/// Распарсить файл
/// </summary>
/// <param name="file"></param>
/// <param name="options"></param>
/// <returns></returns>
ParserResultDto<TDto> Parse(Stream file, TOptions options);
/// <summary>
/// Получение шаблона для заполнения
/// </summary>
/// <returns></returns>
Stream GetTemplateFile();
}
/// <summary>
/// Сервис парсинга(интерфейс маркер)
/// </summary>
public interface IParserService
{
}

View File

@ -1,30 +1,50 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudInfrastructure
{
public static class AssemblyExtensions
{
public static async Task<Stream> GetTemplateCopyStreamAsync(this Assembly assembly, string templateName, CancellationToken cancellationToken)
{
var resourceName = assembly
.GetManifestResourceNames()
.FirstOrDefault(n => n.EndsWith(templateName))!;
public static class AssemblyExtensions
{
public static Stream GetTemplateCopyStream(this Assembly assembly, string templateName)
{
var resourceName = assembly
.GetManifestResourceNames()
.FirstOrDefault(n => n.EndsWith(templateName));
using var stream = Assembly.GetExecutingAssembly()
.GetManifestResourceStream(resourceName)!;
if (string.IsNullOrWhiteSpace(resourceName))
throw new ArgumentNullException(nameof(resourceName));
var memoryStream = new MemoryStream();
await stream.CopyToAsync(memoryStream, cancellationToken);
memoryStream.Position = 0;
using var stream = Assembly.GetExecutingAssembly()
.GetManifestResourceStream(resourceName);
return memoryStream;
}
}
}
var memoryStream = new MemoryStream();
stream?.CopyTo(memoryStream);
memoryStream.Position = 0;
return memoryStream;
}
[Obsolete]
public static async Task<Stream> GetTemplateCopyStreamAsync(this Assembly assembly,
string templateName,
CancellationToken cancellationToken)
{
var resourceName = assembly
.GetManifestResourceNames()
.FirstOrDefault(n => n.EndsWith(templateName))!;
using var stream = Assembly.GetExecutingAssembly()
.GetManifestResourceStream(resourceName)!;
var memoryStream = new MemoryStream();
await stream.CopyToAsync(memoryStream, cancellationToken);
memoryStream.Position = 0;
return memoryStream;
}
}
}

View File

@ -30,7 +30,6 @@ using AsbCloudInfrastructure.Services.SAUB;
using AsbCloudInfrastructure.Services.Subsystems;
using AsbCloudInfrastructure.Services.Trajectory;
using AsbCloudInfrastructure.Services.Trajectory.Export;
using AsbCloudInfrastructure.Services.Trajectory.Import;
using AsbCloudInfrastructure.Services.WellOperationImport;
using AsbCloudInfrastructure.Services.WellOperationImport.FileParser;
using AsbCloudInfrastructure.Services.WellOperationService;
@ -46,6 +45,7 @@ using AsbCloudDb.Model.WellSections;
using AsbCloudInfrastructure.Services.ProcessMaps;
using AsbCloudApp.Data.ProcessMapPlan;
using AsbCloudApp.Requests;
using AsbCloudInfrastructure.Services.Trajectory.Parser;
namespace AsbCloudInfrastructure
{
@ -328,6 +328,8 @@ namespace AsbCloudInfrastructure
services.AddTransient<IProcessMapPlanService<ProcessMapPlanWellReamDto>, ProcessMapPlanService<ProcessMapPlanWellReamDto>>();
services.AddTransient<IWellSectionPlanRepository, WellSectionPlanRepository>();
services.AddSingleton<ParserServiceFactory>();
return services;
}

View File

@ -0,0 +1,72 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Linq;
using AsbCloudApp.Data;
using AsbCloudApp.Requests.ParserOptions;
using AsbCloudApp.Services;
using ClosedXML.Excel;
namespace AsbCloudInfrastructure;
public abstract class ParserServiceBase<TDto, TOptions> : IParserService<TDto, TOptions>
where TDto : class, IId
where TOptions : IParserOptionsRequest
{
protected readonly IServiceProvider serviceProvider;
protected ParserServiceBase(IServiceProvider serviceProvider)
{
this.serviceProvider = serviceProvider;
}
public abstract ParserResultDto<TDto> Parse(Stream file, TOptions options);
public abstract Stream GetTemplateFile();
protected virtual ParserResultDto<TDto> ParseExcelSheet(IXLWorksheet sheet,
Func<IXLRow, ValidationResultDto<TDto>> parseRow,
int columnCount,
int headerRowsCount = 0)
{
if (sheet.RangeUsed().RangeAddress.LastAddress.ColumnNumber < columnCount)
throw new FileFormatException($"Лист {sheet.Name} содержит меньшее количество столбцов.");
var count = sheet.RowsUsed().Count() - headerRowsCount;
if (count > 1024)
throw new FileFormatException($"Лист {sheet.Name} содержит слишком большое количество строк.");
if (count <= 0)
return new ParserResultDto<TDto>();
var dtos = new List<ValidationResultDto<TDto>>(count);
var warnings = new List<ValidationResult>();
for (var i = 0; i < count; i++)
{
var row = sheet.Row(1 + i + headerRowsCount);
try
{
var dto = parseRow.Invoke(row);
dtos.Add(dto);
}
catch (FileFormatException ex)
{
var warning = new ValidationResult(ex.Message);
warnings.Add(warning);
}
}
var parserResult = new ParserResultDto<TDto>
{
Item = dtos
};
if (warnings.Any())
parserResult.Warnings = warnings;
return parserResult;
}
}

View File

@ -0,0 +1,36 @@
using System;
using System.Collections.Generic;
using AsbCloudApp.Data;
using AsbCloudApp.Requests.ParserOptions;
using AsbCloudApp.Services;
using AsbCloudInfrastructure.Services.Trajectory.Parser;
namespace AsbCloudInfrastructure.Services;
public class ParserServiceFactory
{
public const int IdTrajectoryFactManualParserService = 1;
public const int IdTrajectoryPlanParserService = 2;
private readonly IDictionary<int, Func<IParserService>> parsers;
public ParserServiceFactory(IServiceProvider serviceProvider)
{
parsers = new Dictionary<int, Func<IParserService>>
{
{ IdTrajectoryPlanParserService, () => new TrajectoryPlanParserService(serviceProvider) },
{ IdTrajectoryFactManualParserService, () => new TrajectoryFactManualParserService(serviceProvider) }
};
}
public IParserService<TDto, TOptions> Create<TDto, TOptions>(int idParserService)
where TDto : class, IId
where TOptions : IParserOptionsRequest
{
if (!parsers.TryGetValue(idParserService, out var parserService))
throw new ArgumentNullException(nameof(idParserService), "Не правильный идентификатор парсера");
return parserService.Invoke() as IParserService<TDto, TOptions>
?? throw new ArgumentNullException(nameof(idParserService), "Ошибка приведения типа");
}
}

View File

@ -299,7 +299,7 @@ namespace AsbCloudInfrastructure.Services.SAUB
if (request.LeDate.HasValue)
{
var leDate = request.LeDate.Value.ToRemoteDateTime(cacheItem.TimezoneHours);
data = data.Where(d => d.DateTime >= request.LeDate);
data = data.Where(d => d.DateTime <= request.LeDate);
}
if (request.Divider > 1)

View File

@ -1,30 +0,0 @@
using AsbCloudApp.Data.Trajectory;
using ClosedXML.Excel;
namespace AsbCloudInfrastructure.Services.Trajectory.Import
{
public class TrajectoryFactManualParserService : TrajectoryParserService<TrajectoryGeoFactDto>
{
public override string templateFileName { get; } = "TrajectoryFactManualTemplate.xlsx";
public override string usingTemplateFile { get; } = "AsbCloudInfrastructure.Services.Trajectory.Templates";
public override string sheetName { get; } = "Фактическая траектория";
public override int headerRowsCount { get; } = 2;
protected override TrajectoryGeoFactDto ParseRow(IXLRow row)
{
var trajectoryRow = new TrajectoryGeoFactDto
{
WellboreDepth = row.Cell(1).GetCellValue<double>(),
ZenithAngle = row.Cell(2).GetCellValue<double>(),
AzimuthGeo = row.Cell(3).GetCellValue<double>(),
AzimuthMagnetic = row.Cell(4).GetCellValue<double>(),
VerticalDepth = row.Cell(5).GetCellValue<double>(),
Comment = row.Cell(6).GetCellValue<string?>()
};
//TODO: Добавить валидацию модели IValidatableObject
return trajectoryRow;
}
}
}

View File

@ -1,78 +0,0 @@
using AsbCloudApp.Data.Trajectory;
using ClosedXML.Excel;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace AsbCloudInfrastructure.Services.Trajectory.Import
{
public abstract class TrajectoryParserService<T>
where T : TrajectoryGeoDto
{
public abstract string templateFileName { get; }
public abstract string usingTemplateFile { get; }
public abstract string sheetName { get; }
public abstract int headerRowsCount { get; }
protected abstract T ParseRow(IXLRow row);
public IEnumerable<T> Import(Stream stream)
{
using var workbook = new XLWorkbook(stream, XLEventTracking.Disabled);
var trajectoryRows = ParseFileStream(stream);
return trajectoryRows;
}
private IEnumerable<T> ParseFileStream(Stream stream)
{
using var workbook = new XLWorkbook(stream, XLEventTracking.Disabled);
return ParseWorkbook(workbook);
}
private IEnumerable<T> ParseWorkbook(IXLWorkbook workbook)
{
var sheetTrajectory = workbook.Worksheets.FirstOrDefault(ws => ws.Name == sheetName);
if (sheetTrajectory is null)
throw new FileFormatException($"Книга excel не содержит листа {sheetName}.");
var trajectoryRows = ParseSheet(sheetTrajectory);
return trajectoryRows;
}
private IEnumerable<T> ParseSheet(IXLWorksheet sheet)
{
if (sheet.RangeUsed().RangeAddress.LastAddress.ColumnNumber < 6)
throw new FileFormatException($"Лист {sheet.Name} содержит меньшее количество столбцов.");
var count = sheet.RowsUsed().Count() - headerRowsCount;
if (count > 1024)
throw new FileFormatException($"Лист {sheet.Name} содержит слишком большое количество строк.");
if (count <= 0)
throw new FileFormatException($"Лист {sheet.Name} некорректного формата либо пустой");
var trajectoryRows = new List<T>(count);
var parseErrors = new List<string>();
for (int i = 0; i < count; i++)
{
var row = sheet.Row(1 + i + headerRowsCount);
try
{
var trajectoryRow = ParseRow(row);
trajectoryRows.Add(trajectoryRow);
}
catch (FileFormatException ex)
{
parseErrors.Add(ex.Message);
}
}
if (parseErrors.Any())
throw new FileFormatException(string.Join("\r\n", parseErrors));
return trajectoryRows;
}
}
}

View File

@ -1,33 +0,0 @@
using AsbCloudApp.Data.Trajectory;
using ClosedXML.Excel;
namespace AsbCloudInfrastructure.Services.Trajectory.Import
{
public class TrajectoryPlanParserService : TrajectoryParserService<TrajectoryGeoPlanDto>
{
public override string templateFileName { get; } = "TrajectoryPlanTemplate.xlsx";
public override string usingTemplateFile { get; } = "AsbCloudInfrastructure.Services.Trajectory.Templates";
public override string sheetName { get; } = "Плановая траектория";
public override int headerRowsCount { get; } = 2;
protected override TrajectoryGeoPlanDto ParseRow(IXLRow row)
{
var trajectoryRow = new TrajectoryGeoPlanDto
{
WellboreDepth = row.Cell(1).GetCellValue<double>(),
ZenithAngle = row.Cell(2).GetCellValue<double>(),
AzimuthGeo = row.Cell(3).GetCellValue<double>(),
AzimuthMagnetic = row.Cell(4).GetCellValue<double>(),
VerticalDepth = row.Cell(5).GetCellValue<double>(),
Radius = row.Cell(6).GetCellValue<double>(),
Comment = row.Cell(7).GetCellValue<string?>()
};
//TODO: Добавить валидацию модели IValidatableObject
return trajectoryRow;
}
}
}

View File

@ -0,0 +1,39 @@
using System;
using AsbCloudApp.Data;
using AsbCloudApp.Data.Trajectory;
using ClosedXML.Excel;
namespace AsbCloudInfrastructure.Services.Trajectory.Parser;
public class TrajectoryFactManualParserService : TrajectoryParserService<TrajectoryGeoFactDto>
{
protected override string SheetName => "Фактическая траектория";
protected override string TemplateFileName => "TrajectoryFactManualTemplate.xlsx";
public TrajectoryFactManualParserService(IServiceProvider serviceProvider)
: base(serviceProvider)
{
}
protected override ValidationResultDto<TrajectoryGeoFactDto> ParseRow(IXLRow row)
{
var trajectoryRow = new TrajectoryGeoFactDto
{
WellboreDepth = row.Cell(1).GetCellValue<double>(),
ZenithAngle = row.Cell(2).GetCellValue<double>(),
AzimuthGeo = row.Cell(3).GetCellValue<double>(),
AzimuthMagnetic = row.Cell(4).GetCellValue<double>(),
VerticalDepth = row.Cell(5).GetCellValue<double>(),
Comment = row.Cell(6).GetCellValue<string?>()
};
//TODO: Добавить валидацию модели
var validationResult = new ValidationResultDto<TrajectoryGeoFactDto>
{
Item = trajectoryRow
};
return validationResult;
}
}

View File

@ -0,0 +1,44 @@
using System;
using AsbCloudApp.Data.Trajectory;
using ClosedXML.Excel;
using System.IO;
using System.Linq;
using System.Reflection;
using AsbCloudApp.Data;
using AsbCloudApp.Requests.ParserOptions;
namespace AsbCloudInfrastructure.Services.Trajectory.Parser;
public abstract class TrajectoryParserService<T> : ParserServiceBase<T, IParserOptionsRequest>
where T : TrajectoryGeoDto
{
private const int HeaderRowsCount = 2;
private const int ColumnCount = 6;
protected TrajectoryParserService(IServiceProvider serviceProvider)
: base(serviceProvider)
{
}
protected abstract string SheetName { get; }
protected abstract string TemplateFileName { get; }
protected abstract ValidationResultDto<T> ParseRow(IXLRow row);
public override Stream GetTemplateFile() =>
Assembly.GetExecutingAssembly().GetTemplateCopyStream(TemplateFileName)
?? throw new ArgumentNullException($"Файл '{TemplateFileName}' не найден");
public override ParserResultDto<T> Parse(Stream file, IParserOptionsRequest options)
{
using var workbook = new XLWorkbook(file, XLEventTracking.Disabled);
var sheet = workbook.Worksheets.FirstOrDefault(ws =>
ws.Name.ToLower().Trim() == SheetName.ToLower().Trim())
?? throw new FileFormatException($"Книга excel не содержит листа {SheetName}.");
var trajectoryRows = ParseExcelSheet(sheet, ParseRow, ColumnCount, HeaderRowsCount);
return trajectoryRows;
}
}

View File

@ -0,0 +1,40 @@
using System;
using AsbCloudApp.Data;
using AsbCloudApp.Data.Trajectory;
using ClosedXML.Excel;
namespace AsbCloudInfrastructure.Services.Trajectory.Parser;
public class TrajectoryPlanParserService : TrajectoryParserService<TrajectoryGeoPlanDto>
{
protected override string SheetName => "Плановая траектория";
protected override string TemplateFileName => "TrajectoryPlanTemplate.xlsx";
public TrajectoryPlanParserService(IServiceProvider serviceProvider)
: base(serviceProvider)
{
}
protected override ValidationResultDto<TrajectoryGeoPlanDto> ParseRow(IXLRow row)
{
var trajectoryRow = new TrajectoryGeoPlanDto
{
WellboreDepth = row.Cell(1).GetCellValue<double>(),
ZenithAngle = row.Cell(2).GetCellValue<double>(),
AzimuthGeo = row.Cell(3).GetCellValue<double>(),
AzimuthMagnetic = row.Cell(4).GetCellValue<double>(),
VerticalDepth = row.Cell(5).GetCellValue<double>(),
Radius = row.Cell(6).GetCellValue<double>(),
Comment = row.Cell(7).GetCellValue<string?>()
};
//TODO: Добавить валидацию модели
var validationResult = new ValidationResultDto<TrajectoryGeoPlanDto>
{
Item = trajectoryRow
};
return validationResult;
}
}

View File

@ -2,96 +2,11 @@
using System;
using System.Globalization;
using System.IO;
using AsbCloudInfrastructure.Services.DailyReport;
namespace AsbCloudInfrastructure;
internal static class XLExtentions
{
internal static IXLRange _SetValue(this IXLRange range, object value)
{
var mergedRange = range.Merge();
mergedRange.FirstCell()._SetValue(value);
var colWidth = mergedRange.FirstCell().WorksheetColumn().Width;
var maxCharsToWrap = colWidth / (0.1d * mergedRange.FirstCell().Style.Font.FontSize);
if (value is string valueString && valueString.Length > maxCharsToWrap)
{
var row = mergedRange.FirstCell().WorksheetRow();
var baseHeight = row.Height;
row.Height = 0.5d * baseHeight * Math.Ceiling(1d + valueString.Length / maxCharsToWrap);
}
mergedRange.Style.SetAllBorders()
.Alignment.SetWrapText(true);
return mergedRange;
}
internal static IXLCell _SetValue(this IXLCell cell, object value)
{
switch (value)
{
case DateTime dateTime:
cell._SetValue(dateTime);
break;
case IFormattable formattable:
cell._SetValue(formattable);
break;
case string valueString:
cell._SetValue(valueString);
break;
default:
cell.Value = value;
break;
}
return cell;
}
internal static IXLCell _SetValue(this IXLCell cell, string value, bool adaptRowHeight = false)
{
cell.Value = value;
cell.Style
.SetAllBorders()
.Alignment.WrapText = true;
cell.Value = value;
if (adaptRowHeight)
{
var colWidth = cell.WorksheetColumn().Width;
var maxCharsToWrap = colWidth / (0.1d * cell.Style.Font.FontSize);
if (value.Length > maxCharsToWrap)
{
var row = cell.WorksheetRow();
var baseHeight = row.Height;
row.Height = 0.5d * baseHeight * Math.Ceiling(1d + value.Length / maxCharsToWrap);
}
}
return cell;
}
internal static IXLCell _ValueNoBorder(this IXLCell cell, string value, bool adaptRowHeight = false)
{
cell.Value = value;
cell.Style.Alignment.WrapText = true;
cell.Value = value;
if (adaptRowHeight)
{
var colWidth = cell.WorksheetColumn().Width;
var maxCharsToWrap = colWidth / (0.1d * cell.Style.Font.FontSize);
if (value.Length > maxCharsToWrap)
{
var row = cell.WorksheetRow();
var baseHeight = row.Height;
row.Height = 0.5d * baseHeight * Math.Ceiling(1d + value.Length / maxCharsToWrap);
}
}
return cell;
}
internal static IXLCell _SetValue(this IXLCell cell, DateTime value, string dateFormat = "DD.MM.YYYY HH:MM:SS", bool setAllBorders = true)
{
cell.Value = value;
@ -111,21 +26,6 @@ internal static class XLExtentions
return cell;
}
internal static IXLCell _SetValue(this IXLCell cell, IFormattable value, string format = "0.00")
{
cell.Value = value;
cell.Style
.SetAllBorders()
.Alignment.WrapText = true;
cell.Value = value;
cell.DataType = XLDataType.Number;
cell.Style.NumberFormat.Format = "0.00";
return cell;
}
public static IXLCell SetVal(this IXLCell cell, double? value, string format = "0.00")
{
cell.Value = (value is not null && double.IsFinite(value.Value)) ? value : null;
@ -161,7 +61,7 @@ internal static class XLExtentions
return cell;
}
internal static IXLStyle SetAllBorders(this IXLStyle style, XLBorderStyleValues borderStyle = XLBorderStyleValues.Thin)
private static IXLStyle SetAllBorders(this IXLStyle style, XLBorderStyleValues borderStyle = XLBorderStyleValues.Thin)
{
style.Border.RightBorder = borderStyle;
style.Border.LeftBorder = borderStyle;
@ -172,20 +72,6 @@ internal static class XLExtentions
return style;
}
internal static IXLStyle SetBaseFont(this IXLStyle style)
{
style.Font.FontName = "Calibri";
style.Font.FontSize = 10;
return style;
}
internal static IXLStyle SetH1(this IXLStyle style)
{
style.Font.FontName = "Calibri";
style.Font.FontSize = 14;
return style;
}
internal static T? GetCellValue<T>(this IXLCell cell)
{
try
@ -204,7 +90,7 @@ internal static class XLExtentions
catch
{
throw new FileFormatException(
$"Лист '{cell.Worksheet.Name}'. Ячейка: ({cell.Address.RowNumber},{cell.Address.ColumnNumber}) содержит некорректное значение");
$"Лист '{cell.Worksheet.Name}'. {cell.Address.RowNumber} строка содержит некорректное значение в {cell.Address.ColumnNumber} столбце");
}
}
}

View File

@ -1,48 +0,0 @@
using AsbCloudInfrastructure.Services.Trajectory.Import;
using System.Linq;
using Xunit;
namespace AsbCloudWebApi.Tests.Services.Trajectory
{
public class TrajectoryImportTest
{
private readonly TrajectoryPlanParserService trajectoryPlanImportService;
private readonly TrajectoryFactManualParserService trajectoryFactManualImportService;
private string usingTemplateFile = "AsbCloudWebApi.Tests.Services.Trajectory.Templates";
public TrajectoryImportTest()
{
trajectoryPlanImportService = new TrajectoryPlanParserService();
trajectoryFactManualImportService = new TrajectoryFactManualParserService();
}
[Fact]
public void Import_trajectory_plan()
{
var stream = System.Reflection.Assembly.GetExecutingAssembly()
.GetManifestResourceStream($"{usingTemplateFile}.TrajectoryPlanTemplate.xlsx");
if (stream is null)
Assert.Fail("Файла для импорта не существует");
var trajectoryRows = trajectoryPlanImportService.Import(stream);
Assert.Equal(3, trajectoryRows.Count());
}
[Fact]
public void Import_trajectory_fact_manual()
{
var stream = System.Reflection.Assembly.GetExecutingAssembly()
.GetManifestResourceStream($"{usingTemplateFile}.TrajectoryFactManualTemplate.xlsx");
if (stream is null)
Assert.Fail("Файла для импорта не существует");
var trajectoryRows = trajectoryFactManualImportService.Import(stream);
Assert.Equal(4, trajectoryRows.Count());
}
}
}

View File

@ -0,0 +1,63 @@
using System;
using System.Linq;
using AsbCloudApp.Data.Trajectory;
using AsbCloudApp.Requests.ParserOptions;
using AsbCloudInfrastructure.Services;
using Microsoft.Extensions.DependencyInjection;
using NSubstitute;
using Xunit;
namespace AsbCloudWebApi.Tests.Services.Trajectory;
public class TrajectoryParserTest
{
private const string UsingTemplateFile = "AsbCloudWebApi.Tests.Services.Trajectory.Templates";
private readonly IServiceProvider serviceProviderMock = Substitute.For<IServiceProvider, ISupportRequiredService>();
private readonly IServiceScope serviceScopeMock = Substitute.For<IServiceScope>();
private readonly IServiceScopeFactory serviceScopeFactoryMock = Substitute.For<IServiceScopeFactory>();
private readonly ParserServiceFactory parserServiceFactory;
public TrajectoryParserTest()
{
serviceScopeFactoryMock.CreateScope().Returns(serviceScopeMock);
((ISupportRequiredService)serviceProviderMock).GetRequiredService(typeof(IServiceScopeFactory)).Returns(serviceScopeFactoryMock);
parserServiceFactory = new ParserServiceFactory(serviceProviderMock);
}
[Fact]
public void Parse_trajectory_plan()
{
var stream = System.Reflection.Assembly.GetExecutingAssembly()
.GetManifestResourceStream($"{UsingTemplateFile}.TrajectoryPlanTemplate.xlsx");
if (stream is null)
Assert.Fail("Файла для импорта не существует");
var parserService = parserServiceFactory.Create<TrajectoryGeoPlanDto, IParserOptionsRequest>(
ParserServiceFactory.IdTrajectoryPlanParserService);
var trajectoryRows = parserService.Parse(stream, IParserOptionsRequest.Empty());
Assert.Equal(3, trajectoryRows.Item.Count());
}
[Fact]
public void Parse_trajectory_fact_manual()
{
var stream = System.Reflection.Assembly.GetExecutingAssembly()
.GetManifestResourceStream($"{UsingTemplateFile}.TrajectoryFactManualTemplate.xlsx");
if (stream is null)
Assert.Fail("Файла для импорта не существует");
var parserService = parserServiceFactory.Create<TrajectoryGeoFactDto, IParserOptionsRequest>(
ParserServiceFactory.IdTrajectoryFactManualParserService);
var trajectoryRows = parserService.Parse(stream, IParserOptionsRequest.Empty());
Assert.Equal(4, trajectoryRows.Item.Count());
}
}

View File

@ -0,0 +1,13 @@
using System.IO;
using AsbCloudApp.Data;
using Microsoft.AspNetCore.Mvc;
namespace AsbCloudWebApi.Controllers.Interfaces;
public interface IControllerWithParser<TDto, in TOptions>
where TDto : class, IId
{
ActionResult<ParserResultDto<TDto>> Parse(Stream file, TOptions options);
IActionResult GetTemplate();
}

View File

@ -2,7 +2,6 @@
using AsbCloudApp.Repositories;
using AsbCloudApp.Services;
using AsbCloudInfrastructure.Services.Trajectory.Export;
using AsbCloudInfrastructure.Services.Trajectory.Import;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
@ -10,6 +9,10 @@ using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using AsbCloudApp.Data;
using AsbCloudApp.Requests.ParserOptions;
using AsbCloudInfrastructure.Services;
using AsbCloudWebApi.Controllers.Interfaces;
namespace AsbCloudWebApi.Controllers.Trajectory
{
@ -19,28 +22,41 @@ namespace AsbCloudWebApi.Controllers.Trajectory
/// </summary>
[ApiController]
[Authorize]
public abstract class TrajectoryEditableController<TDto> : TrajectoryController<TDto>
public abstract class TrajectoryEditableController<TDto> : TrajectoryController<TDto>,
IControllerWithParser<TDto, IParserOptionsRequest>
where TDto : TrajectoryGeoDto
{
private readonly TrajectoryParserService<TDto> trajectoryImportService;
private readonly TrajectoryExportService<TDto> trajectoryExportService;
private readonly ITrajectoryEditableRepository<TDto> trajectoryRepository;
{
private readonly IParserService<TDto, IParserOptionsRequest> parserService;
private readonly ITrajectoryEditableRepository<TDto> trajectoryRepository;
public TrajectoryEditableController(IWellService wellService,
TrajectoryParserService<TDto> trajectoryImportService,
TrajectoryExportService<TDto> trajectoryExportService,
ITrajectoryEditableRepository<TDto> trajectoryRepository)
protected TrajectoryEditableController(IWellService wellService,
ParserServiceFactory parserServiceFactory,
TrajectoryExportService<TDto> trajectoryExportService,
ITrajectoryEditableRepository<TDto> trajectoryRepository,
int idParserService)
: base(
wellService,
trajectoryExportService,
trajectoryRepository)
{
this.trajectoryImportService = trajectoryImportService;
this.trajectoryExportService = trajectoryExportService;
this.trajectoryRepository = trajectoryRepository;
}
parserService = parserServiceFactory.Create<TDto, IParserOptionsRequest>(idParserService);
this.trajectoryRepository = trajectoryRepository;
}
ActionResult<ParserResultDto<TDto>> IControllerWithParser<TDto, IParserOptionsRequest>.Parse(Stream file,
IParserOptionsRequest options)
{
try
{
var parserResult = parserService.Parse(file, options);
return Ok(parserResult);
}
catch (FileFormatException ex)
{
return this.ValidationBadRequest("files", ex.Message);
}
}
/// <summary>
/// Возвращает excel шаблон для заполнения строк траектории
/// </summary>
@ -51,110 +67,96 @@ namespace AsbCloudWebApi.Controllers.Trajectory
[ProducesResponseType(StatusCodes.Status204NoContent)]
public IActionResult GetTemplate()
{
var stream = trajectoryExportService.GetTemplateFile();
var stream = parserService.GetTemplateFile();
return File(stream, "application/octet-stream", fileName);
}
/// <summary>
/// Импортирует координаты из excel (xlsx) файла
/// </summary>
/// <param name="idWell">id скважины</param>
/// <param name="files">Коллекция из одного файла xlsx</param>
/// <param name="deleteBeforeImport">Удалить операции перед импортом, если фал валидный</param>
/// <param name="token"> Токен отмены задачи </param>
/// <returns>количество успешно записанных строк в БД</returns>
[HttpPost("import/{deleteBeforeImport}")]
[ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
[ProducesResponseType(typeof(ValidationProblemDetails), (int)System.Net.HttpStatusCode.BadRequest)]
public async Task<IActionResult> ImportAsync(int idWell,
[FromForm] IFormFileCollection files,
bool deleteBeforeImport,
CancellationToken token)
{
int? idUser = User.GetUserId();
if (!idUser.HasValue)
return Forbid();
if (!await CanUserAccessToWellAsync(idWell,
token).ConfigureAwait(false))
return Forbid();
if (files.Count < 1)
return this.ValidationBadRequest(nameof(files), "нет файла");
var file = files[0];
if (Path.GetExtension(file.FileName).ToLower() != ".xlsx")
return this.ValidationBadRequest(nameof(files), "Требуется xlsx файл.");
using Stream stream = file.OpenReadStream();
/// <summary>
/// Импортирует координаты из excel (xlsx) файла
/// </summary>
/// <param name="idWell">id скважины</param>
/// <param name="files">Коллекция из одного файла xlsx</param>
/// <param name="token"> Токен отмены задачи </param>
/// <returns>количество успешно записанных строк в БД</returns>
[HttpPost("parse")]
[ProducesResponseType((int)System.Net.HttpStatusCode.OK)]
[ProducesResponseType(typeof(ValidationProblemDetails), (int)System.Net.HttpStatusCode.BadRequest)]
public async Task<ActionResult<ParserResultDto<TDto>>> Parse(int idWell,
[FromForm] IFormFileCollection files,
CancellationToken token)
{
var idUser = User.GetUserId();
try
{
var trajectoryRows = trajectoryImportService.Import(stream);
foreach (var row in trajectoryRows)
{
row.IdWell = idWell;
row.IdUser = idUser.Value;
}
if (!idUser.HasValue)
return Forbid();
if (deleteBeforeImport)
await trajectoryRepository.DeleteByIdWellAsync(idWell, token);
if (!await CanUserAccessToWellAsync(idWell, token))
return Forbid();
var rowsCount = await trajectoryRepository.AddRangeAsync(trajectoryRows, token);
return this.ParseExcelFile(files, IParserOptionsRequest.Empty());
}
/// <summary>
/// Добавление
/// </summary>
/// <param name="idWell"></param>
/// <param name="dtos"></param>
/// <param name="token"></param>
/// <returns></returns>
[HttpPost]
[ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> InsertRangeAsync(int idWell, [FromBody] IEnumerable<TDto> dtos, CancellationToken token)
{
if (!await CanUserAccessToWellAsync(idWell, token))
return Forbid();
var idUser = User.GetUserId();
if (!idUser.HasValue)
return Forbid();
foreach (var dto in dtos)
{
dto.IdUser = idUser.Value;
dto.IdWell = idWell;
}
return Ok(rowsCount);
}
catch (FileFormatException ex)
{
return this.ValidationBadRequest(nameof(files), ex.Message);
}
}
var result = await trajectoryRepository.AddRangeAsync(dtos, token);
return Ok(result);
}
/// <summary>
/// Удалить все по скважине и добавить новые
/// </summary>
/// <param name="idWell"></param>
/// <param name="dtos"></param>
/// <param name="token"></param>
/// <returns></returns>
[HttpPost("replace")]
[ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> ClearAndInsertRangeAsync(int idWell, [FromBody] IEnumerable<TDto> dtos, CancellationToken token)
{
//TODO: это вся радость требует рефакторинга.
//Удаление с добавлением новых записей должно происходить в рамках одной транзакции, да и вообще должно быть реализовано на уровне репозиторий.
//Рефакторинг будет когда доберёмся до журнала изменений для траекторий.
if (!await CanUserAccessToWellAsync(idWell, token))
return Forbid();
var idUser = User.GetUserId();
if (!idUser.HasValue)
return Forbid();
foreach (var dto in dtos)
{
dto.IdUser = idUser.Value;
dto.IdWell = idWell;
}
/// <summary>
/// Добавить одну новую строчку координат для плановой траектории
/// </summary>
/// <param name="idWell"></param>
/// <param name="row"></param>
/// <param name="token"></param>
/// <returns>количество успешно записанных строк в БД</returns>
[HttpPost]
[ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> AddAsync(int idWell, [FromBody] TDto row,
CancellationToken token)
{
if (!await CanUserAccessToWellAsync(idWell, token).ConfigureAwait(false))
return Forbid();
var idUser = User.GetUserId();
if (!idUser.HasValue)
return Forbid();
row.IdUser = idUser.Value;
row.IdWell = idWell;
var result = await trajectoryRepository.AddAsync(row, token);
return Ok(result);
}
/// <summary>
/// Добавить массив строчек координат для плановой траектории
/// </summary>
/// <param name="idWell"></param>
/// <param name="rows"></param>
/// <param name="token"></param>
/// <returns>количество успешно записанных строк в БД</returns>
[HttpPost("range")]
[ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> AddRangeAsync(int idWell, [FromBody] IEnumerable<TDto> rows,
CancellationToken token)
{
if (!await CanUserAccessToWellAsync(idWell, token).ConfigureAwait(false))
return Forbid();
int? idUser = User.GetUserId();
if (!idUser.HasValue)
return Forbid();
foreach (var item in rows)
{
item.IdUser = idUser.Value;
item.IdWell = idWell;
}
var result = await trajectoryRepository.AddRangeAsync(rows, token);
return Ok(result);
}
await trajectoryRepository.DeleteByIdWellAsync(idWell, token);
var result = await trajectoryRepository.AddRangeAsync(dtos, token);
return Ok(result);
}
/// <summary>
/// Изменить выбранную строку с координатами
@ -201,4 +203,4 @@ namespace AsbCloudWebApi.Controllers.Trajectory
return Ok(result);
}
}
}
}

View File

@ -1,8 +1,8 @@
using AsbCloudApp.Data.Trajectory;
using AsbCloudApp.Repositories;
using AsbCloudApp.Services;
using AsbCloudInfrastructure.Services;
using AsbCloudInfrastructure.Services.Trajectory.Export;
using AsbCloudInfrastructure.Services.Trajectory.Import;
using Microsoft.AspNetCore.Mvc;
namespace AsbCloudWebApi.Controllers.Trajectory;
@ -14,15 +14,17 @@ namespace AsbCloudWebApi.Controllers.Trajectory;
[Route("api/well/{idWell}/[controller]")]
public class TrajectoryFactManualController : TrajectoryEditableController<TrajectoryGeoFactDto>
{
protected override string fileName => "ЕЦП_шаблон_файлаактическая_траектория.xlsx";
public TrajectoryFactManualController(IWellService wellService,
TrajectoryFactManualParserService factTrajectoryImportService,
TrajectoryFactManualExportService factTrajectoryExportService,
ITrajectoryEditableRepository<TrajectoryGeoFactDto> trajectoryFactRepository)
: base(
wellService,
factTrajectoryImportService,
factTrajectoryExportService,
trajectoryFactRepository)
{ }
protected override string fileName => "ЕЦП_шаблон_файлаактическая_траектория.xlsx";
public TrajectoryFactManualController(IWellService wellService,
TrajectoryFactManualExportService trajectoryExportService,
ParserServiceFactory parserServiceFactory,
ITrajectoryEditableRepository<TrajectoryGeoFactDto> trajectoryRepository)
: base(wellService,
parserServiceFactory,
trajectoryExportService,
trajectoryRepository,
ParserServiceFactory.IdTrajectoryFactManualParserService)
{
}
}

View File

@ -2,58 +2,58 @@
using AsbCloudApp.Repositories;
using AsbCloudApp.Services;
using AsbCloudInfrastructure.Services.Trajectory;
using AsbCloudInfrastructure.Services.Trajectory.Import;
using AsbCloudInfrastructure.Services.Trajectory.Export;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using AsbCloudInfrastructure.Services;
namespace AsbCloudWebApi.Controllers.Trajectory
{
/// <summary>
/// Плановая траектория (загрузка и хранение)
/// </summary>
[Route("api/well/{idWell}/[controller]")]
[ApiController]
public class TrajectoryPlanController : TrajectoryEditableController<TrajectoryGeoPlanDto>
{
private readonly TrajectoryService trajectoryVisualizationService;
/// <summary>
/// Плановая траектория (загрузка и хранение)
/// </summary>
[Route("api/well/{idWell}/[controller]")]
[ApiController]
public class TrajectoryPlanController : TrajectoryEditableController<TrajectoryGeoPlanDto>
{
private readonly TrajectoryService trajectoryVisualizationService;
protected override string fileName => "ЕЦП_шаблон_файла_плановая_траектория.xlsx";
protected override string fileName => "ЕЦП_шаблон_файла_плановая_траектория.xlsx";
public TrajectoryPlanController(IWellService wellService,
TrajectoryPlanExportService trajectoryExportService,
ParserServiceFactory parserServiceFactory,
ITrajectoryEditableRepository<TrajectoryGeoPlanDto> trajectoryRepository,
TrajectoryService trajectoryVisualizationService)
: base(wellService,
parserServiceFactory,
trajectoryExportService,
trajectoryRepository,
ParserServiceFactory.IdTrajectoryPlanParserService)
{
this.trajectoryVisualizationService = trajectoryVisualizationService;
}
public TrajectoryPlanController(IWellService wellService,
TrajectoryPlanParserService trajectoryPlanImportService,
TrajectoryPlanExportService trajectoryPlanExportService,
ITrajectoryEditableRepository<TrajectoryGeoPlanDto> trajectoryPlanRepository,
TrajectoryService trajectoryVisualizationService)
: base(
wellService,
trajectoryPlanImportService,
trajectoryPlanExportService,
trajectoryPlanRepository)
{
this.trajectoryVisualizationService = trajectoryVisualizationService;
}
/// <summary>
/// Получение координат для визуализации траектории (плановой и фактической)
/// </summary>
/// <param name="idWell"></param>
/// <param name="token"></param>
/// <returns></returns>
[HttpGet("trajectoryCartesianPlanFact")]
[ProducesResponseType(
typeof(TrajectoryPlanFactDto<IEnumerable<TrajectoryCartesianPlanDto>, IEnumerable<TrajectoryCartesianFactDto>>),
(int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> GetTrajectoryCartesianPlanFactAsync(int idWell, CancellationToken token)
{
if (!await CanUserAccessToWellAsync(idWell,
token).ConfigureAwait(false))
return Forbid();
/// <summary>
/// Получение координат для визуализации траектории (плановой и фактической)
/// </summary>
/// <param name="idWell"></param>
/// <param name="token"></param>
/// <returns></returns>
[HttpGet("trajectoryCartesianPlanFact")]
[ProducesResponseType(typeof(TrajectoryPlanFactDto<IEnumerable<TrajectoryCartesianPlanDto>, IEnumerable<TrajectoryCartesianFactDto>>), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> GetTrajectoryCartesianPlanFactAsync(int idWell, CancellationToken token)
{
if (!await CanUserAccessToWellAsync(idWell,
token).ConfigureAwait(false))
return Forbid();
var result = await trajectoryVisualizationService.GetTrajectoryCartesianAsync(idWell, token);
return Ok(result);
}
}
}
var result = await trajectoryVisualizationService.GetTrajectoryCartesianAsync(idWell, token);
return Ok(result);
}
}
}

View File

@ -0,0 +1,125 @@
using AsbCloudApp.Data.User;
using AsbCloudWebApi.Converters;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Security.Claims;
using AsbCloudApp.Data;
using AsbCloudApp.Requests.ParserOptions;
using AsbCloudWebApi.Controllers.Interfaces;
using Microsoft.AspNetCore.Http;
namespace Microsoft.AspNetCore.Mvc;
public static class Extensions
{
public static int? GetCompanyId(this ClaimsPrincipal user)
{
var claimIdCompany = user.FindFirst(nameof(UserDto.IdCompany));
if (claimIdCompany is null)
return null;
return int.TryParse(claimIdCompany.Value, out int uid)
? uid
: null;
}
public static int? GetUserId(this ClaimsPrincipal user)
{
var userId = user.FindFirst(nameof(UserDto.Id));
if (userId is null)
return null;
return int.TryParse(userId.Value, out int uid)
? uid
: null;
}
/// <summary>
/// <para>
/// Returns BadRequest with ValidationProblemDetails as body
/// </para>
/// <para>
/// Используйте этот метод только если валидацию нельзя сделать через
/// атрибуты валидации или IValidatableObject модели.
/// </para>
/// </summary>
/// <param name="controller"></param>
/// <param name="paramName"></param>
/// <param name="error"></param>
/// <returns></returns>
public static BadRequestObjectResult ValidationBadRequest(this ControllerBase controller, string paramName, string error)
{
return MakeBadRequestObjectResult(paramName, error);
}
private static BadRequestObjectResult MakeBadRequestObjectResult(string paramName, string error)
{
var errors = new Dictionary<string, string[]> {
{ paramName, new[]{ error } }
};
var problem = new ValidationProblemDetails(errors);
var badRequestObject = new BadRequestObjectResult(problem);
return badRequestObject;
}
/// <summary>
/// <para>
/// Returns BadRequest with ValidationProblemDetails as body
/// </para>
/// <para>
/// Используйте этот метод только если валидацию нельзя сделать через
/// атрибуты валидации или IValidatableObject модели.
/// </para>
/// </summary>
/// <param name="controller"></param>
/// <param name="validationResults"></param>
/// <returns></returns>
public static BadRequestObjectResult ValidationBadRequest(this ControllerBase controller, IEnumerable<ValidationResult> validationResults)
{
var errors = validationResults
.SelectMany(e => e.MemberNames.Select(name => new { name, e.ErrorMessage }))
.GroupBy(e => e.name)
.ToDictionary(e => e.Key, e => e.Select(el => el.ErrorMessage ?? string.Empty).ToArray());
var problem = new ValidationProblemDetails(errors);
return controller.BadRequest(problem);
}
public static MvcOptions UseDateOnlyTimeOnlyStringConverters(this MvcOptions options)
{
TypeDescriptor.AddAttributes(typeof(DateOnly), new TypeConverterAttribute(typeof(DateOnlyTypeConverter)));
return options;
}
/// <summary>
/// Вызов парсера со стандартной валидацией входного файла
/// </summary>
/// <typeparam name="TDto"></typeparam>
/// <typeparam name="TOptions"></typeparam>
/// <param name="controller"></param>
/// <param name="files"></param>
/// <param name="options"></param>
/// <returns></returns>
public static ActionResult<ParserResultDto<TDto>> ParseExcelFile<TDto, TOptions>(
this IControllerWithParser<TDto, TOptions> controller,
IFormFileCollection files,
TOptions options)
where TDto : class, IId
where TOptions : class, IParserOptionsRequest
{
if (files.Count < 1)
return MakeBadRequestObjectResult(nameof(files), "Нет файла");
var file = files[0];
if (Path.GetExtension(file.FileName).ToLower() != ".xlsx")
return MakeBadRequestObjectResult(nameof(files), "Требуется .xlsx файл.");
var stream = file.OpenReadStream();
return controller.Parse(stream, options);
}
}

View File

@ -1,89 +0,0 @@
using AsbCloudApp.Data.User;
using AsbCloudWebApi.Converters;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Security.Claims;
namespace Microsoft.AspNetCore.Mvc
{
public static class Extentions
{
public static int? GetCompanyId(this ClaimsPrincipal user)
{
var claimIdCompany = user.FindFirst(nameof(UserDto.IdCompany));
if (claimIdCompany is null)
return null;
return int.TryParse(claimIdCompany.Value, out int uid)
? uid
: null;
}
public static int? GetUserId(this ClaimsPrincipal user)
{
var userId = user.FindFirst(nameof(UserDto.Id));
if (userId is null)
return null;
return int.TryParse(userId.Value, out int uid)
? uid
: null;
}
/// <summary>
/// <para>
/// Returns BadRequest with ValidationProblemDetails as body
/// </para>
/// <para>
/// Используйте этот метод только если валидацию нельзя сделать через
/// атрибуты валидации или IValidatableObject модели.
/// </para>
/// </summary>
/// <param name="controller"></param>
/// <param name="paramName"></param>
/// <param name="error"></param>
/// <returns></returns>
public static BadRequestObjectResult ValidationBadRequest(this ControllerBase controller, string paramName, string error)
{
var errors = new Dictionary<string, string[]> {
{ paramName, new[]{ error } }
};
var problem = new ValidationProblemDetails(errors);
return controller.BadRequest(problem);
}
/// <summary>
/// <para>
/// Returns BadRequest with ValidationProblemDetails as body
/// </para>
/// <para>
/// Используйте этот метод только если валидацию нельзя сделать через
/// атрибуты валидации или IValidatableObject модели.
/// </para>
/// </summary>
/// <param name="controller"></param>
/// <param name="validationResults"></param>
/// <returns></returns>
public static BadRequestObjectResult ValidationBadRequest(this ControllerBase controller, IEnumerable<ValidationResult> validationResults)
{
var errors = validationResults
.SelectMany(e => e.MemberNames.Select(name => new { name, e.ErrorMessage }))
.GroupBy(e => e.name)
.ToDictionary(e => e.Key, e => e.Select(el => el.ErrorMessage ?? string.Empty).ToArray());
var problem = new ValidationProblemDetails(errors);
return controller.BadRequest(problem);
}
public static MvcOptions UseDateOnlyTimeOnlyStringConverters(this MvcOptions options)
{
TypeDescriptor.AddAttributes(typeof(DateOnly), new TypeConverterAttribute(typeof(DateOnlyTypeConverter)));
return options;
}
}
}