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

Add support for custom types in arrays and custom collections #203

Merged
merged 4 commits into from
Mar 25, 2020
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
Original file line number Diff line number Diff line change
Expand Up @@ -27,15 +27,12 @@ public static AssemblyFinder Auto()

public static AssemblyFinder ForSource(ConfigurationAssemblySource configurationAssemblySource)
{
switch (configurationAssemblySource)
return configurationAssemblySource switch
{
case ConfigurationAssemblySource.UseLoadedAssemblies:
return Auto();
case ConfigurationAssemblySource.AlwaysScanDllFiles:
return new DllScanningAssemblyFinder();
default:
throw new ArgumentOutOfRangeException(nameof(configurationAssemblySource), configurationAssemblySource, null);
}
ConfigurationAssemblySource.UseLoadedAssemblies => Auto(),
ConfigurationAssemblySource.AlwaysScanDllFiles => new DllScanningAssemblyFinder(),
_ => throw new ArgumentOutOfRangeException(nameof(configurationAssemblySource), configurationAssemblySource, null),
};
}

public static AssemblyFinder ForDependencyContext(DependencyContext dependencyContext)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ where IsCaseInsensitiveMatch(assemblyFileName, nameToFind)

return query.ToList().AsReadOnly();

AssemblyName TryGetAssemblyNameFrom(string path)
static AssemblyName TryGetAssemblyNameFrom(string path)
{
try
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -220,39 +220,14 @@ internal ILookup<string, Dictionary<string, IConfigurationArgumentValue>> GetMet
select new
{
Name = argument.Key,
Value = GetArgumentValue(argument)
Value = GetArgumentValue(argument, _configurationAssemblies)
}).ToDictionary(p => p.Name, p => p.Value)
select new { Name = name, Args = callArgs }))
.ToLookup(p => p.Name, p => p.Args);

return result;

IConfigurationArgumentValue GetArgumentValue(IConfigurationSection argumentSection)
{
IConfigurationArgumentValue argumentValue;

// Reject configurations where an element has both scalar and complex
// values as a result of reading multiple configuration sources.
if (argumentSection.Value != null && argumentSection.GetChildren().Any())
throw new InvalidOperationException(
$"The value for the argument '{argumentSection.Path}' is assigned different value " +
"types in more than one configuration source. Ensure all configurations consistently " +
"use either a scalar (int, string, boolean) or a complex (array, section, list, " +
"POCO, etc.) type for this argument value.");

if (argumentSection.Value != null)
{
argumentValue = new StringArgumentValue(argumentSection.Value);
}
else
{
argumentValue = new ObjectArgumentValue(argumentSection, _configurationAssemblies);
}

return argumentValue;
}

string GetSectionName(IConfigurationSection s)
static string GetSectionName(IConfigurationSection s)
{
var name = s.GetSection("Name");
if (name.Value == null)
Expand All @@ -262,6 +237,31 @@ string GetSectionName(IConfigurationSection s)
}
}

internal static IConfigurationArgumentValue GetArgumentValue(IConfigurationSection argumentSection, IReadOnlyCollection<Assembly> configurationAssemblies)
{
IConfigurationArgumentValue argumentValue;

// Reject configurations where an element has both scalar and complex
// values as a result of reading multiple configuration sources.
if (argumentSection.Value != null && argumentSection.GetChildren().Any())
throw new InvalidOperationException(
$"The value for the argument '{argumentSection.Path}' is assigned different value " +
"types in more than one configuration source. Ensure all configurations consistently " +
"use either a scalar (int, string, boolean) or a complex (array, section, list, " +
"POCO, etc.) type for this argument value.");

if (argumentSection.Value != null)
{
argumentValue = new StringArgumentValue(argumentSection.Value);
}
else
{
argumentValue = new ObjectArgumentValue(argumentSection, configurationAssemblies);
}

return argumentValue;
}

static IReadOnlyCollection<Assembly> LoadConfigurationAssemblies(IConfigurationSection section, AssemblyFinder assemblyFinder)
{
var assemblies = new Dictionary<string, Assembly>();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
using Microsoft.Extensions.Configuration;
using Serilog.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

using Serilog.Configuration;

namespace Serilog.Settings.Configuration
{
class ObjectArgumentValue : IConfigurationArgumentValue
Expand Down Expand Up @@ -47,8 +47,72 @@ public object ConvertTo(Type toType, ResolutionContext resolutionContext)
}
}

// MS Config binding
if (toType.IsArray)
return CreateArray();

if (IsContainer(toType, out var elementType) && TryCreateContainer(out var result))
return result;

// MS Config binding can work with a limited set of primitive types and collections
return _section.Get(toType);

object CreateArray()
{
var elementType = toType.GetElementType();
var configurationElements = _section.GetChildren().ToArray();
var result = Array.CreateInstance(elementType, configurationElements.Length);
for (int i = 0; i < configurationElements.Length; ++i)
{
var argumentValue = ConfigurationReader.GetArgumentValue(configurationElements[i], _configurationAssemblies);
var value = argumentValue.ConvertTo(elementType, resolutionContext);
result.SetValue(value, i);
}

return result;
}

bool TryCreateContainer(out object result)
{
result = null;

if (toType.GetConstructor(Type.EmptyTypes) == null)
return false;

// https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/object-and-collection-initializers#collection-initializers
var addMethod = toType.GetMethods().FirstOrDefault(m => !m.IsStatic && m.Name == "Add" && m.GetParameters()?.Length == 1 && m.GetParameters()[0].ParameterType == elementType);
if (addMethod == null)
return false;

var configurationElements = _section.GetChildren().ToArray();
result = Activator.CreateInstance(toType);

for (int i = 0; i < configurationElements.Length; ++i)
{
var argumentValue = ConfigurationReader.GetArgumentValue(configurationElements[i], _configurationAssemblies);
var value = argumentValue.ConvertTo(elementType, resolutionContext);
addMethod.Invoke(result, new object[] { value });
}

return true;
}
}

private static bool IsContainer(Type type, out Type elementType)
{
elementType = null;
foreach (var iface in type.GetInterfaces())
{
if (iface.IsGenericType)
{
if (iface.GetGenericTypeDefinition() == typeof(IEnumerable<>))
{
elementType = iface.GetGenericArguments()[0];
return true;
}
}
}

return false;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -615,6 +615,46 @@ public void SinkWithStringArrayArgument()
Assert.Equal(1, DummyRollingFileSink.Emitted.Count);
}

[Fact]
public void DestructureWithCollectionsOfTypeArgument()
{
var json = @"{
""Serilog"": {
""Using"": [ ""TestDummies"" ],
""Destructure"": [{
""Name"": ""DummyArrayOfType"",
""Args"": {
""list"": [
""System.Byte"",
""System.Int16""
],
""array"" : [
""System.Int32"",
""System.String""
],
""type"" : ""System.TimeSpan"",
""custom"" : [
""System.Int64""
],
""customString"" : [
""System.UInt32""
]
}
}]
}
}";

DummyPolicy.Current = null;

ConfigFromJson(json);

Assert.Equal(typeof(TimeSpan), DummyPolicy.Current.Type);
Assert.Equal(new[] { typeof(int), typeof(string) }, DummyPolicy.Current.Array);
Assert.Equal(new[] { typeof(byte), typeof(short) }, DummyPolicy.Current.List);
Assert.Equal(typeof(long), DummyPolicy.Current.Custom.First);
Assert.Equal("System.UInt32", DummyPolicy.Current.CustomStrings.First);
}

[Fact]
public void SinkWithIntArrayArgument()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ public void ShouldProbePrivateBinPath()
AppDomain.Unload(ad);
}

void DoTestInner()
static void DoTestInner()
{
var assemblyNames = new DllScanningAssemblyFinder().FindAssembliesContainingName("customSink");
Assert.Equal(2, assemblyNames.Count);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,7 @@ public class DelegatingSink : ILogEventSink

public DelegatingSink(Action<LogEvent> write)
{
if (write == null) throw new ArgumentNullException(nameof(write));
_write = write;
_write = write ?? throw new ArgumentNullException(nameof(write));
}

public void Emit(LogEvent logEvent)
Expand Down
10 changes: 10 additions & 0 deletions test/Serilog.Settings.Configuration.Tests/Support/Extensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,15 @@ public static object LiteralValue(this LogEventPropertyValue @this)
{
return ((ScalarValue)@this).Value;
}

// netcore3.0 error:
// Could not parse the JSON file. System.Text.Json.JsonReaderException : ''' is an invalid start of a property name. Expected a '"'
public static string ToValidJson(this string str)
{
#if NETCOREAPP3_1
str = str.Replace('\'', '"');
#endif
return str;
}
}
}
Loading