Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Updates #26

Merged
merged 8 commits into from
Apr 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .config/dotnet-tools.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"version": 1,
"isRoot": true,
"tools": {
"csharpier": {
"version": "0.28.2",
"commands": [
"dotnet-csharpier"
]
}
}
}
570 changes: 570 additions & 0 deletions .editorconfig

Large diffs are not rendered by default.

6 changes: 6 additions & 0 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
version: 2
updates:
- package-ecosystem: "github-actions" # search for actions - there are other options available
directory: "/" # search in .github/workflows under root `/`
schedule:
interval: "weekly" # check for action update every week
22 changes: 22 additions & 0 deletions .github/workflows/dotnetcore.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
name: Narochno.Primitives
on:
push:
branches:
- 'master'
pull_request:
types: [ opened, synchronize, reopened, ready_for_review ]

jobs:
build:
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v4
- uses: actions/setup-dotnet@v4
with:
dotnet-version: 8.0.x
- run: dotnet run --project build/build.csproj
- uses: actions/upload-artifact@v4
with:
name: narochno.primitives.nupkg
path: artifacts/*
16 changes: 16 additions & 0 deletions Directory.Build.props
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<Project>
<PropertyGroup>
<LangVersion>latest</LangVersion>
<Nullable>enable</Nullable>
<AnalysisMode>Recommended</AnalysisMode>
<WarningsAsErrors>true</WarningsAsErrors>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<CodeAnalysisTreatWarningsAsErrors>true</CodeAnalysisTreatWarningsAsErrors>
<EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<RunAnalyzersDuringLiveAnalysis>False</RunAnalyzersDuringLiveAnalysis>
<RunAnalyzersDuringBuild>False</RunAnalyzersDuringBuild>
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
<RestorePackagesWithLockFile>true</RestorePackagesWithLockFile>
</PropertyGroup>
</Project>
11 changes: 11 additions & 0 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<Project>
<ItemGroup>
<PackageVersion Include="Bullseye" Version="5.0.0" />
<PackageVersion Include="Glob" Version="1.1.9" />
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.9.0" />
<PackageVersion Include="Newtonsoft.Json" Version="13.0.2" />
<PackageVersion Include="SimpleExec" Version="12.0.0" />
<PackageVersion Include="xunit" Version="2.8.0" />
<PackageVersion Include="xunit.runner.visualstudio" Version="2.8.0" />
</ItemGroup>
</Project>
14 changes: 14 additions & 0 deletions Narochno.Primitives.sln
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,16 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Narochno.Primitives.Tests",
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Narochno.Primitives.Json.Tests", "test\Narochno.Primitives.Json.Tests\Narochno.Primitives.Json.Tests.csproj", "{E04F8B42-125C-4362-93A4-0B2E57112AA6}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Config", "Config", "{ED5BB2CC-D22A-4CA3-A773-B796036EB7EA}"
ProjectSection(SolutionItems) = preProject
.editorconfig = .editorconfig
Directory.Build.props = Directory.Build.props
Directory.Packages.props = Directory.Packages.props
global.json = global.json
EndProjectSection
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "build", "build\build.csproj", "{7126AFE3-188B-4785-8C01-A565303B3757}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand All @@ -37,6 +47,10 @@ Global
{E04F8B42-125C-4362-93A4-0B2E57112AA6}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E04F8B42-125C-4362-93A4-0B2E57112AA6}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E04F8B42-125C-4362-93A4-0B2E57112AA6}.Release|Any CPU.Build.0 = Release|Any CPU
{7126AFE3-188B-4785-8C01-A565303B3757}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7126AFE3-188B-4785-8C01-A565303B3757}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7126AFE3-188B-4785-8C01-A565303B3757}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7126AFE3-188B-4785-8C01-A565303B3757}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
9 changes: 9 additions & 0 deletions NuGet.config
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSourceMapping>
<!-- key value for <packageSource> should match key values from <packageSources> element -->
<packageSource key="nuget.org">
<package pattern="*" />
</packageSource>
</packageSourceMapping>
</configuration>
28 changes: 2 additions & 26 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,33 +2,9 @@

Classes designed to make working with C# code easier.

## Optional&lt;T&gt;
## NotNull and Empty

A generic struct to allow for optional reference values. It allows you to write code that assumes all variables except those wrapped with `Optional<T>` are specified, avoiding the need for null checks and possible null reference exceptions.

It is the same concept as `Nullable<T>`, but can be used for reference types instead of value types.

### Example Usage

```csharp
public async Task RecordInformation(Information information, Optional<Location> location)
{
var document = new Document();
document["name"] = information.Name;
document["email"] = information.Email;

if (location.HasValue)
{
document["country"] = location.Value.Country;
document["city"] = location.Value.City;
}

await Table.LoadTable(dynamoClient, "Information")
.PutItemAsync(document);
}
```

The use of `Optional<T>` in the code above to wrap the `Location` object is an explicit way to show that it may not be set, without a null check. Anyone calling and editing the code can see the intent of the parameter from a glance.
Helpers that remove of the constant issues around checking `null` on all types and collections. If you find yourself doing "if not then throw" or "null or empty collection" then these help you out.

## Generic Parsing

Expand Down
94 changes: 94 additions & 0 deletions build/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
using System;
using System.Collections.Generic;
using System.IO;
using GlobExpressions;
using static Bullseye.Targets;
using static SimpleExec.Command;

const string Clean = "clean";
const string Restore = "restore";
const string Build = "build";
const string Test = "test";
const string Format = "format";
const string Publish = "publish";

Target(
Clean,
ForEach("**/bin", "**/obj"),
dir =>
{
IEnumerable<string> GetDirectories(string d)
{
return Glob.Directories(".", d);
}

void RemoveDirectory(string d)
{
if (Directory.Exists(d))
{
Console.WriteLine(d);
Directory.Delete(d, true);
}
}

foreach (var d in GetDirectories(dir))
{
RemoveDirectory(d);
}
}
);

Target(
Format,
() =>
{
Run("dotnet", "tool restore");
Run("dotnet", "csharpier --check .");
}
);
Target(Restore, DependsOn(Format), () => Run("dotnet", "restore"));

Target(
Build,
DependsOn(Restore),
() =>
{
Run(
"dotnet",
"build src/Narochno.Primitives/Narochno.Primitives.csproj -c Release --no-restore"
);
}
);

Target(
Test,
DependsOn(Build),
() =>
{
IEnumerable<string> GetFiles(string d)
{
return Glob.Files(".", d);
}

foreach (var file in GetFiles("**/*.Test.csproj"))
{
Run("dotnet", $"test {file} -c Release -f net8.0 --no-restore --verbosity=normal");
}
}
);

Target(
Publish,
DependsOn(Test),
() =>
{
Run(
"dotnet",
"pack src/Narochno.Primitives/Narochno.Primitives.csproj -c Release -o artifacts/"
);
}
);

Target("default", DependsOn(Publish), () => Console.WriteLine("Done!"));

await RunTargetsAndExitAsync(args);
14 changes: 14 additions & 0 deletions build/build.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Bullseye" />
<PackageReference Include="Glob" />
<PackageReference Include="SimpleExec" />
</ItemGroup>

</Project>
25 changes: 25 additions & 0 deletions build/packages.lock.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"version": 2,
"dependencies": {
"net8.0": {
"Bullseye": {
"type": "Direct",
"requested": "[5.0.0, )",
"resolved": "5.0.0",
"contentHash": "bqyt+m17ym+5aN45C5oZRAjuLDt8jKiCm/ys1XfymIXSkrTFwvI/QsbY3ucPSHDz7SF7uON7B57kXFv5H2k1ew=="
},
"Glob": {
"type": "Direct",
"requested": "[1.1.9, )",
"resolved": "1.1.9",
"contentHash": "AfK5+ECWYTP7G3AAdnU8IfVj+QpGjrh9GC2mpdcJzCvtQ4pnerAGwHsxJ9D4/RnhDUz2DSzd951O/lQjQby2Sw=="
},
"SimpleExec": {
"type": "Direct",
"requested": "[12.0.0, )",
"resolved": "12.0.0",
"contentHash": "ptxlWtxC8vM6Y6e3h9ZTxBBkOWnWrm/Sa1HT+2i1xcXY3Hx2hmKDZP5RShPf8Xr9D+ivlrXNy57ktzyH8kyt+Q=="
}
}
}
}
6 changes: 6 additions & 0 deletions global copy.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"sdk": {
"version": "8.0.100",
"rollForward": "latestFeature"
}
}
58 changes: 27 additions & 31 deletions src/Narochno.Primitives.Json/EnumStringConverter.cs
Original file line number Diff line number Diff line change
@@ -1,45 +1,41 @@
using System;
using Newtonsoft.Json;
using System.Reflection;
using Narochno.Primitives.Parsing;
using Newtonsoft.Json;

namespace Narochno.Primitives.Json
namespace Narochno.Primitives.Json;

public class EnumStringConverter : JsonConverter
{
public class EnumStringConverter : JsonConverter
{
private IParserLibrary parserLibrary = DefaultParserLibrary.Instance;
private IParserLibrary parserLibrary = DefaultParserLibrary.Instance;

public EnumStringConverter()
{
}
public EnumStringConverter() { }

public EnumStringConverter(IParserLibrary parserLibrary)
{
this.parserLibrary = parserLibrary;
}
public EnumStringConverter(IParserLibrary parserLibrary) => this.parserLibrary = parserLibrary;

public override bool CanConvert(Type objectType)
{
#if PORTABLE40
return objectType.GetNullableUnderlyingType().IsEnum;
#else
return objectType.GetNullableUnderlyingType().GetTypeInfo().IsEnum;
#endif
}
public override bool CanConvert(Type objectType) =>
objectType.GetNullableUnderlyingType().GetTypeInfo().IsEnum;

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
public override object? ReadJson(
JsonReader reader,
Type objectType,
object? existingValue,
JsonSerializer serializer
)
{
if (objectType.IsNullable() && reader.Value == null)
{
if (objectType.IsNullable() && reader.Value == null)
{
return existingValue;
}

return parserLibrary.GetParser(objectType.GetNullableUnderlyingType()).Parse(reader.Value?.ToString());
return existingValue;
}

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var parser = parserLibrary.GetParser(value.GetType());
writer.WriteValue(parser.ToString(value)); }
return parserLibrary
.GetParser(objectType.GetNullableUnderlyingType().NotNull())
.Parse(reader.Value.NotNull().ToString());
}

public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
var parser = parserLibrary.GetParser(value.NotNull().GetType().NotNull());
writer.WriteValue(parser.ToString(value.NotNull()));
}
}
6 changes: 3 additions & 3 deletions src/Narochno.Primitives.Json/Narochno.Primitives.Json.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

<PropertyGroup>
<Description>Classes designed to make working with C# code easier.</Description>
<VersionPrefix>3.0.1</VersionPrefix>
<VersionPrefix>4.0.0</VersionPrefix>
<Authors>alanedwardes;adamhathcock</Authors>
<TargetFramework>netstandard2.0</TargetFramework>
<AssemblyName>Narochno.Primitives.Json</AssemblyName>
Expand All @@ -15,8 +15,8 @@
<ItemGroup>
<ProjectReference Include="..\Narochno.Primitives\Narochno.Primitives.csproj" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="11.0.2" />
<PackageReference Include="Newtonsoft.Json" />
</ItemGroup>
</Project>
Loading