Skip to content

Commit

Permalink
Merge config path fix for dotnet/extensions#779 (dotnet/extensions#1819)
Browse files Browse the repository at this point in the history
* Include the path to the configuration value in conversion error messages

* Add a test that demonstrates the inclusion of path in nested binding failure

* Fix resources


Commit migrated from dotnet/extensions@9607d6b
  • Loading branch information
HaoK authored Jun 11, 2019
1 parent efefb51 commit c937b5e
Show file tree
Hide file tree
Showing 3 changed files with 82 additions and 46 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -167,10 +167,11 @@ public static object GetValue(this IConfiguration configuration, Type type, stri
/// <returns>The converted value.</returns>
public static object GetValue(this IConfiguration configuration, Type type, string key, object defaultValue)
{
var value = configuration.GetSection(key).Value;
var section = configuration.GetSection(key);
var value = section.Value;
if (value != null)
{
return ConvertValue(type, value);
return ConvertValue(type, value, section.Path);
}
return defaultValue;
}
Expand Down Expand Up @@ -292,7 +293,7 @@ private static object BindInstance(Type type, object instance, IConfiguration co
var configValue = section?.Value;
object convertedValue;
Exception error;
if (configValue != null && TryConvertValue(type, configValue, out convertedValue, out error))
if (configValue != null && TryConvertValue(type, configValue, section.Path, out convertedValue, out error))
{
if (error != null)
{
Expand Down Expand Up @@ -484,7 +485,7 @@ private static Array BindArray(Array source, IConfiguration config, BinderOption
return newArray;
}

private static bool TryConvertValue(Type type, string value, out object result, out Exception error)
private static bool TryConvertValue(Type type, string value, string path, out object result, out Exception error)
{
error = null;
result = null;
Expand All @@ -493,16 +494,16 @@ private static bool TryConvertValue(Type type, string value, out object result,
result = value;
return true;
}

if (type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
{
if (string.IsNullOrEmpty(value))
{
return true;
}
return TryConvertValue(Nullable.GetUnderlyingType(type), value, out result, out error);
return TryConvertValue(Nullable.GetUnderlyingType(type), value, path, out result, out error);
}

var converter = TypeDescriptor.GetConverter(type);
if (converter.CanConvertFrom(typeof(string)))
{
Expand All @@ -512,19 +513,19 @@ private static bool TryConvertValue(Type type, string value, out object result,
}
catch (Exception ex)
{
error = new InvalidOperationException(Resources.FormatError_FailedBinding(type), ex);
error = new InvalidOperationException(Resources.FormatError_FailedBinding(path, type), ex);
}
return true;
}

return false;
}

private static object ConvertValue(Type type, string value)
private static object ConvertValue(Type type, string value, string path)
{
object result;
Exception error;
TryConvertValue(type, value, out result, out error);
TryConvertValue(type, value, path, out result, out error);
if (error != null)
{
throw error;
Expand All @@ -535,12 +536,12 @@ private static object ConvertValue(Type type, string value)
private static Type FindOpenGenericInterface(Type expected, Type actual)
{
var actualTypeInfo = actual.GetTypeInfo();
if(actualTypeInfo.IsGenericType &&
if(actualTypeInfo.IsGenericType &&
actual.GetGenericTypeDefinition() == expected)
{
return actual;
}
}

var interfaces = actualTypeInfo.ImplementedInterfaces;
foreach (var interfaceType in interfaces)
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
Expand All @@ -26,36 +26,36 @@
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
Expand Down Expand Up @@ -121,7 +121,7 @@
<value>Cannot create instance of type '{0}' because it is either abstract or an interface.</value>
</data>
<data name="Error_FailedBinding" xml:space="preserve">
<value>Failed to convert configuration value to type '{0}'.</value>
<value>Failed to convert configuration value at '{0}' to type '{1}'.</value>
</data>
<data name="Error_FailedToActivate" xml:space="preserve">
<value>Failed to create instance of type '{0}'.</value>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,16 @@ public class GenericOptions<T>
public T Value { get; set; }
}

public class OptionsWithNesting
{
public NestedOptions Nested { get; set; }

public class NestedOptions
{
public int Value { get; set; }
}
}

public class ConfigurationInterfaceOptions
{
public IConfigurationSection Section { get; set; }
Expand Down Expand Up @@ -362,9 +372,10 @@ public void ConsistentExceptionOnFailedBinding(Type type)
{
// arrange
const string IncorrectValue = "Invalid data";
const string ConfigKey = "Value";
var dic = new Dictionary<string, string>
{
{"Value", IncorrectValue}
{ConfigKey, IncorrectValue}
};
var configurationBuilder = new ConfigurationBuilder();
configurationBuilder.AddInMemoryCollection(dic);
Expand All @@ -387,16 +398,40 @@ public void ConsistentExceptionOnFailedBinding(Type type)
Assert.NotNull(exception.InnerException);
Assert.NotNull(getException.InnerException);
Assert.Equal(
Resources.FormatError_FailedBinding(type),
Resources.FormatError_FailedBinding(ConfigKey, type),
exception.Message);
Assert.Equal(
Resources.FormatError_FailedBinding(type),
Resources.FormatError_FailedBinding(ConfigKey, type),
getException.Message);
Assert.Equal(
Resources.FormatError_FailedBinding(type),
Resources.FormatError_FailedBinding(ConfigKey, type),
getValueException.Message);
}

[Fact]
public void ExceptionOnFailedBindingIncludesPath()
{
const string IncorrectValue = "Invalid data";
const string ConfigKey = "Nested:Value";

var dic = new Dictionary<string, string>
{
{ConfigKey, IncorrectValue}
};

var configurationBuilder = new ConfigurationBuilder();
configurationBuilder.AddInMemoryCollection(dic);
var config = configurationBuilder.Build();

var options = new OptionsWithNesting();

var exception = Assert.Throws<InvalidOperationException>(
() => config.Bind(options));

Assert.Equal(Resources.FormatError_FailedBinding(ConfigKey, typeof(int)),
exception.Message);
}

[Fact]
public void BinderIgnoresIndexerProperties()
{
Expand Down

0 comments on commit c937b5e

Please sign in to comment.