Skip to content

Commit

Permalink
Включена нулабельность типов, добавлены тесты, поправлен конвейер пуб…
Browse files Browse the repository at this point in the history
…ликации, в.1.0-а1
  • Loading branch information
a-postx committed Sep 6, 2022
1 parent 2b93919 commit 0b26fda
Show file tree
Hide file tree
Showing 15 changed files with 699 additions and 88 deletions.
80 changes: 49 additions & 31 deletions .github/workflows/build-and-test-and-publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,20 @@ jobs:
runs-on: ${{matrix.os}}
strategy:
matrix:
os: [ubuntu-latest, windows-latest]
os: [ubuntu-latest]
steps:
- name: 'Checkout'
uses: actions/checkout@v2
- name: 'Setup .NET Core'
uses: actions/setup-dotnet@v1
uses: actions/setup-dotnet@v2.0.0
with:
dotnet-version: '6.0.x'
- uses: actions/cache@v3
with:
path: ~/.nuget/packages
key: ${{ runner.os }}-nuget-${{ hashFiles('**/packages.lock.json') }}
restore-keys: |
${{ runner.os }}-nuget
- name: 'Install dependencies'
run: dotnet restore
- name: 'Build'
Expand All @@ -40,40 +46,52 @@ jobs:
run: dotnet test --no-restore --verbosity normal
- name: 'Pack'
run: dotnet pack --no-build --configuration Release src/Delobytes.NetCore.EntityReportGeneration.csproj --output distr
- name: 'Publish Artefacts'
uses: actions/upload-artifact@v2
- name: 'Upload package'
uses: actions/upload-artifact@v3.0.0
with:
name: ${{matrix.os}}
path: distr
path: "distr"
if-no-files-found: error
retention-days: 1

check-tag:
name: 'Check tag'
runs-on: ubuntu-latest
outputs:
tagName: ${{ steps.tagName.outputs.tag }}
steps:
- name: 'Get tag'
id: tag
uses: dawidd6/action-get-tag@v1
with:
strip_v: true
- name: 'Fail if no tag'
if: ${{ steps.tag.outputs.tag == '' }}
run: exit 1

push-github-packages:
push-github-package:
name: 'Push GitHub Package'
needs: build
runs-on: windows-latest
needs: [build, check-tag]
if: success()
runs-on: ubuntu-latest
steps:
- name: 'Download Artefact'
uses: actions/download-artifact@v2
with:
name: 'windows-latest'
- name: 'Dotnet NuGet Add Source'
run: dotnet nuget add source https://nuget.pkg.github.com/Delobytes.NetCore.EntityReportGeneration/index.json --name GitHub --username a-postx --password ${{secrets.GITHUB_TOKEN}}
shell: pwsh
- name: 'Dotnet NuGet Push'
run: dotnet nuget push .\*.nupkg --api-key ${{ github.token }} --source GitHub --skip-duplicate
shell: pwsh
- name: 'Download Artefact'
uses: actions/[email protected]
with:
name: 'ubuntu-latest'
- name: 'Dotnet NuGet Push'
run: |
dotnet nuget push *.nupkg --source https://nuget.pkg.github.com/Delobytes.NetCore.EntityReportGeneration/index.json --skip-duplicate --api-key ${{ github.token }}
push-nuget:
push-nuget-package:
name: 'Push NuGet Package'
needs: build
runs-on: windows-latest
needs: [build, check-tag]
runs-on: ubuntu-latest
steps:
- name: 'Download Artefact'
uses: actions/download-artifact@v1
with:
name: 'windows-latest'
- name: 'Dotnet NuGet Push'
run: |
Get-ChildItem .\windows-latest -Filter *.nupkg |
Where-Object { !$_.Name.Contains('preview') } |
ForEach-Object { dotnet nuget push $_ --source https://api.nuget.org/v3/index.json --skip-duplicate --api-key ${{secrets.NUGET_API_KEY}} }
shell: pwsh
- name: 'Download Artefact'
uses: actions/[email protected]
with:
name: 'ubuntu-latest'
- name: 'Dotnet NuGet Push'
run: |
dotnet nuget push *.nupkg --skip-duplicate --source https://api.nuget.org/v3/index.json --api-key ${{secrets.NUGET_API_KEY}}
50 changes: 50 additions & 0 deletions .github/workflows/build-and-test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
name: 'Build and test'

on:
push:
branches: [ main ]
paths-ignore:
- '**.md'
pull_request:
branches: [ main ]
paths-ignore:
- '**.md'

env:
# Disable the .NET logo in the console output.
DOTNET_NOLOGO: true
# Disable the .NET first time experience to skip caching NuGet packages and speed up the build.
DOTNET_SKIP_FIRST_TIME_EXPERIENCE: true
# Disable sending .NET CLI telemetry to Microsoft.
DOTNET_CLI_TELEMETRY_OPTOUT: true
# Set the build number in MinVer.
MINVERBUILDMETADATA: build.${{github.run_number}}

jobs:
build:
name: Build-${{matrix.os}}
runs-on: ${{matrix.os}}
strategy:
matrix:
os: [ubuntu-latest]
steps:
- name: 'Checkout'
uses: actions/checkout@v2
- name: 'Setup .NET Core'
uses: actions/[email protected]
with:
dotnet-version: '6.0.x'
- name: 'Install dependencies'
run: dotnet restore
- name: 'Build'
run: dotnet build --configuration Release --no-restore
- name: 'Test'
run: dotnet test --no-restore --verbosity normal --logger trx --results-directory "TestResults-${{ matrix.os }}"
- name: 'Upload test results'
if: always()
uses: actions/[email protected]
with:
name: dotnet-results-${{ matrix.os }}
path: TestResults-${{ matrix.os }}
if-no-files-found: error
retention-days: 3
6 changes: 6 additions & 0 deletions Delobytes.NetCore.EntityReportGeneration.sln
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ VisualStudioVersion = 17.2.32630.192
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Delobytes.NetCore.EntityReportGeneration", "src\Delobytes.NetCore.EntityReportGeneration.csproj", "{7F7D4BED-32C4-4003-A1A1-6A051D225746}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Delobytes.NetCore.EntityReportGeneration.Tests", "test\Delobytes.NetCore.EntityReportGeneration.Tests.csproj", "{B6BF229B-5323-4543-A6D3-41FBC3EE2036}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand All @@ -15,6 +17,10 @@ Global
{7F7D4BED-32C4-4003-A1A1-6A051D225746}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7F7D4BED-32C4-4003-A1A1-6A051D225746}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7F7D4BED-32C4-4003-A1A1-6A051D225746}.Release|Any CPU.Build.0 = Release|Any CPU
{B6BF229B-5323-4543-A6D3-41FBC3EE2036}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B6BF229B-5323-4543-A6D3-41FBC3EE2036}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B6BF229B-5323-4543-A6D3-41FBC3EE2036}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B6BF229B-5323-4543-A6D3-41FBC3EE2036}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
9 changes: 9 additions & 0 deletions README.en.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# Delobytes.NetCore.EntityReportGeneration

[RU](README.md), [EN](README.en.md)

Report generator that allows to export objects into table representation.
Supported formats: CSV, XLSX.

## License
[MIT](https://github.com/a-postx/Delobytes.NetCore.EntityReportGeneration/blob/main/LICENSE)
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# Delobytes.NetCore.EntityReportGeneration

[RU](README.md), [EN](README.en.md)

Генератор отчётов, позволяющий экспортировать сущности в табличное представление.
Поддерживаемые форматы: CSV, XLSX.

## Лицензия
[МИТ](https://github.com/a-postx/Delobytes.NetCore.EntityReportGeneration/blob/main/LICENSE)
6 changes: 2 additions & 4 deletions src/DataTableExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,17 @@ internal static class DataTableExtensions
{
public static string ToCSV(this DataTable dataTable, string delimiter)
{
string result = null;

StringBuilder sb = new StringBuilder();
IEnumerable<string> columnNames = dataTable.Columns.Cast<DataColumn>().Select(column => column.ColumnName);
sb.AppendLine(string.Join(delimiter, columnNames));

foreach (DataRow row in dataTable.Rows)
{
IEnumerable<string> fields = row.ItemArray.Select(field => field.ToString());
IEnumerable<string?> fields = row.ItemArray.Select(field => field?.ToString());
sb.AppendLine(string.Join(delimiter, fields));
}

result = sb.ToString();
string result = sb.ToString();

return result;
}
Expand Down
4 changes: 3 additions & 1 deletion src/Delobytes.NetCore.EntityReportGeneration.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Version>0.0.2.0</Version>
<Version>1.0.0.0-alpha1</Version>
<LangVersion>latest</LangVersion>
<Authors>Алексей Якубин</Authors>
<Company>Делобайты</Company>
Expand All @@ -12,6 +12,8 @@
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<RepositoryUrl>https://github.com/a-postx/Delobytes.NetCore.EntityReportGeneration.git</RepositoryUrl>
<RepositoryType>git</RepositoryType>
<GenerateDocumentationFile>True</GenerateDocumentationFile>
<Nullable>enable</Nullable>
</PropertyGroup>

<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
Expand Down
24 changes: 3 additions & 21 deletions src/Delobytes.NetCore.EntityReportGeneration.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

41 changes: 12 additions & 29 deletions src/EntityReportGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,14 @@ public class EntityReportGenerator : IEntityReportGenerator
/// <param name="options">Настройки генератора.</param>
/// <param name="logger">Логировщик.</param>
public EntityReportGenerator(IOptions<EntityReportGeneratorOptions> options,
ILogger<EntityReportGenerator> logger = null)
ILogger<EntityReportGenerator>? logger = null)
{
_options = options.Value;
_log = logger;
}

private readonly EntityReportGeneratorOptions _options;
private readonly ILogger<EntityReportGenerator> _log;
private readonly ILogger<EntityReportGenerator>? _log;

private static string RemoveDelimiterChar(string s, string delimiter)
{
Expand Down Expand Up @@ -72,7 +72,8 @@ private DataTable ConvertObjectsToExcelDataTable<T>(IEnumerable<T> items, string

for (var i = 0; i < properties.Length; i++)
{
objectRow[i] = properties[i].GetValue(item, null);
object? objValue = properties[i].GetValue(item, null);
objectRow[i] = objValue ?? string.Empty;
}

result.Rows.Add(objectRow);
Expand All @@ -87,15 +88,10 @@ private DataTable ConvertObjectsToExcelDataTable<T>(IEnumerable<T> items, string
return result;
}

/// <summary>
/// Сгенерировать содержимое эксель-файла для ряда страниц. Страница состоит из названия и ряда строк.
/// Метод подходит для экспорта объектов определённых в виде класса.
/// </summary>
/// <param name="pagesDataset">Набор объектов для преобразования в страницы файла.</param>
/// <returns>Содержимое файла.</returns>
///<inheritdoc/>
public byte[] GenerateExcelContent<T>(IDictionary<string, IEnumerable<T>> pagesDataset) where T : class
{
byte[] result = null;
byte[] result;

using (ExcelFile file = new ExcelFile())
{
Expand All @@ -114,15 +110,10 @@ public byte[] GenerateExcelContent<T>(IDictionary<string, IEnumerable<T>> pagesD
return result;
}

/// <summary>
/// Сгенерировать содержимое эксель-файла для ряда страниц. Страница состоит из названия и ряда строк.
/// Метод подходит для экспорта динамически создаваемых объектов типа ExpandoObject.
/// </summary>
/// <param name="pagesDataset">Набор объектов для преобразования в страницы файла.</param>
/// <returns>Содержимое файла.</returns>
///<inheritdoc/>
public byte[] GenerateExcelContent(IDictionary<string, IEnumerable<IDictionary<string, object>>> pagesDataset)
{
byte[] result = null;
byte[] result;

using (ExcelFile file = new ExcelFile())
{
Expand All @@ -138,18 +129,10 @@ public byte[] GenerateExcelContent(IDictionary<string, IEnumerable<IDictionary<s
return result;
}

/// <summary>
/// Сгенерировать содержимое эксель-файла для одной страницы без использования
/// промежуточного преобразования к таблице.
/// Метод подходит для экспорта объектов определённых в виде класса.
/// </summary>
/// <typeparam name="T">Тип объекта.</typeparam>
/// <param name="sheetName">Название страницы.</param>
/// <param name="dataset">Список объектов.</param>
/// <returns>Содержимое файла.</returns>
///<inheritdoc/>
public byte[] GenerateExcelContentDirect<T>(string sheetName, IEnumerable<T> dataset) where T : class
{
byte[] result = null;
byte[] result;

using (ExcelFile file = new ExcelFile())
{
Expand Down Expand Up @@ -189,7 +172,7 @@ private DataTable ConvertObjectsToDataTableForCsv<T>(IEnumerable<T> items, strin
{
if (properties[i].PropertyType == typeof(List<string>))
{
string stringValue = string.Empty;
string? stringValue = string.Empty;

if (properties[i].GetValue(item, null) is IEnumerable enumerable)
{
Expand All @@ -203,7 +186,7 @@ private DataTable ConvertObjectsToDataTableForCsv<T>(IEnumerable<T> items, strin
}
else
{
object propertyValue = properties[i].GetValue(item, null);
object? propertyValue = properties[i].GetValue(item, null);
string cellValue = propertyValue?.ToString() ?? string.Empty;
dataRow[i] = string.IsNullOrEmpty(stringToCleanup) ? cellValue : RemoveDelimiterChar(cellValue, stringToCleanup);
}
Expand Down
2 changes: 1 addition & 1 deletion src/ExcelFile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ internal void AddWorkSheet(string name, IEnumerable<IDictionary<string, object>>

if (printHeaders)
{
IDictionary<string, object> headerObject = valueDics.FirstOrDefault();
IDictionary<string, object>? headerObject = valueDics.FirstOrDefault();

if (headerObject is not null)
{
Expand Down
2 changes: 1 addition & 1 deletion src/ServiceCollectionExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ public static class ServiceCollectionExtensions
/// <param name="services">Коллеция сервисов.</param>
/// <param name="configure">Настройки.</param>
/// <returns>Коллеция сервисов.</returns>
public static IServiceCollection AddEntityReportGenerator(this IServiceCollection services, Action<EntityReportGeneratorOptions> configure = null)
public static IServiceCollection AddEntityReportGenerator(this IServiceCollection services, Action<EntityReportGeneratorOptions>? configure = null)
{
ArgumentNullException.ThrowIfNull(services, nameof(services));

Expand Down
Loading

0 comments on commit 0b26fda

Please sign in to comment.