-Added compiled expressions reflection option

This commit is contained in:
James Newton-King
2013-04-24 22:56:53 +12:00
parent 2bdf5c9b88
commit c2a7341dbc
20 changed files with 699 additions and 4 deletions
@@ -26,7 +26,6 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Numerics;
using System.Text;
#if !NETFX_CORE
using NUnit.Framework;
@@ -39,6 +38,9 @@ using Newtonsoft.Json;
using System.IO;
using System.Xml;
using Newtonsoft.Json.Utilities;
#if !(NET20 || NET35 || SILVERLIGHT || PORTABLE40 || PORTABLE)
using System.Numerics;
#endif
namespace Newtonsoft.Json.Tests
{
@@ -238,6 +238,7 @@
<Compile Include="TestObjects\WagePerson.cs" />
<Compile Include="Utilities\DateTimeUtilsTests.cs" />
<Compile Include="Utilities\DynamicReflectionDelegateFactoryTests.cs" />
<Compile Include="Utilities\ExpressionReflectionDelegateFactoryTests.cs" />
<Compile Include="Utilities\ReflectionUtilsTests.cs" />
<Compile Include="Utilities\StringUtilsTests.cs" />
</ItemGroup>
@@ -280,6 +280,7 @@
<Compile Include="TestObjects\UserNullable.cs" />
<Compile Include="Utilities\DateTimeUtilsTests.cs" />
<Compile Include="Utilities\DynamicReflectionDelegateFactoryTests.cs" />
<Compile Include="Utilities\ExpressionReflectionDelegateFactoryTests.cs" />
<Compile Include="Utilities\ReflectionUtilsTests.cs" />
<Compile Include="Utilities\StringUtilsTests.cs" />
</ItemGroup>
@@ -398,6 +398,7 @@
<Compile Include="TestObjects\UserNullable.cs" />
<Compile Include="Utilities\DateTimeUtilsTests.cs" />
<Compile Include="Utilities\DynamicReflectionDelegateFactoryTests.cs" />
<Compile Include="Utilities\ExpressionReflectionDelegateFactoryTests.cs" />
<Compile Include="Utilities\ReflectionUtilsTests.cs" />
<Compile Include="Utilities\StringUtilsTests.cs" />
</ItemGroup>
@@ -277,6 +277,7 @@
<Compile Include="TestObjects\TypeClass.cs" />
<Compile Include="TestObjects\TypedSubHashtable.cs" />
<Compile Include="TestObjects\UserNullable.cs" />
<Compile Include="Utilities\ExpressionReflectionDelegateFactoryTests.cs" />
<Compile Include="Utilities\DateTimeUtilsTests.cs" />
<Compile Include="Utilities\DynamicReflectionDelegateFactoryTests.cs" />
<Compile Include="Utilities\ReflectionUtilsTests.cs" />
@@ -279,6 +279,7 @@
<Compile Include="TestObjects\UserNullable.cs" />
<Compile Include="Utilities\DateTimeUtilsTests.cs" />
<Compile Include="Utilities\DynamicReflectionDelegateFactoryTests.cs" />
<Compile Include="Utilities\ExpressionReflectionDelegateFactoryTests.cs" />
<Compile Include="Utilities\ReflectionUtilsTests.cs" />
<Compile Include="Utilities\StringUtilsTests.cs" />
</ItemGroup>
@@ -342,6 +342,7 @@
<Compile Include="TestObjects\WagePerson.cs" />
<Compile Include="Utilities\DateTimeUtilsTests.cs" />
<Compile Include="Utilities\DynamicReflectionDelegateFactoryTests.cs" />
<Compile Include="Utilities\ExpressionReflectionDelegateFactoryTests.cs" />
<Compile Include="Utilities\ReflectionUtilsTests.cs" />
<Compile Include="Utilities\StringUtilsTests.cs" />
</ItemGroup>
@@ -75,4 +75,4 @@ using System.Security;
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("4.5.0.0")]
[assembly: AssemblyFileVersion("5.0.4.16023")]
[assembly: AssemblyFileVersion("5.0.4.16024")]
@@ -0,0 +1,302 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
#if !(PORTABLE40 || NET20 || NET35)
using System;
using System.Diagnostics;
using System.Reflection;
#if !NETFX_CORE
using NUnit.Framework;
#else
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
#endif
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Utilities;
using Newtonsoft.Json.Tests.TestObjects;
using Newtonsoft.Json.Tests.Serialization;
namespace Newtonsoft.Json.Tests.Utilities
{
[TestFixture]
public class ExpressionReflectionDelegateFactoryTests : TestFixtureBase
{
[Test]
public void DefaultConstructor()
{
Func<object> create = ExpressionReflectionDelegateFactory.Instance.CreateDefaultConstructor<object>(typeof(Movie));
Movie m = (Movie)create();
Assert.IsNotNull(m);
}
[Test]
public void DefaultConstructor_Struct()
{
Func<object> create = ExpressionReflectionDelegateFactory.Instance.CreateDefaultConstructor<object>(typeof(StructTest));
StructTest m = (StructTest)create();
Assert.IsNotNull(m);
}
[Test]
public void DefaultConstructor_Abstract()
{
ExceptionAssert.Throws<MissingMethodException>("Cannot create an abstract class.",
() =>
{
Func<object> create = ExpressionReflectionDelegateFactory.Instance.CreateDefaultConstructor<object>(typeof(Type));
create();
});
}
[Test]
public void CreatePropertySetter()
{
Action<object, object> setter = ExpressionReflectionDelegateFactory.Instance.CreateSet<object>(typeof(Movie).GetProperty("Name"));
Movie m = new Movie();
setter(m, "OH HAI!");
Assert.AreEqual("OH HAI!", m.Name);
}
[Test]
public void CreatePropertyGetter()
{
Func<object, object> getter = ExpressionReflectionDelegateFactory.Instance.CreateGet<object>(typeof(Movie).GetProperty("Name"));
Movie m = new Movie();
m.Name = "OH HAI!";
object value = getter(m);
Assert.AreEqual("OH HAI!", value);
}
[Test]
public void CreateMethodCall()
{
MethodCall<object, object> method = ExpressionReflectionDelegateFactory.Instance.CreateMethodCall<object>(typeof(Movie).GetMethod("ToString"));
Movie m = new Movie();
object result = method(m);
Assert.AreEqual("Newtonsoft.Json.Tests.TestObjects.Movie", result);
method = ExpressionReflectionDelegateFactory.Instance.CreateMethodCall<object>(typeof(Movie).GetMethod("Equals"));
result = method(m, m);
Assert.AreEqual(true, result);
}
[Test]
public void CreateMethodCall_Constructor()
{
MethodCall<object, object> method = ExpressionReflectionDelegateFactory.Instance.CreateMethodCall<object>(typeof(Movie).GetConstructor(new Type[0]));
object result = method(null);
Assert.IsTrue(result is Movie);
}
public static class StaticTestClass
{
public static string StringField;
public static string StringProperty { get; set; }
}
[Test]
public void GetStatic()
{
StaticTestClass.StringField = "Field!";
StaticTestClass.StringProperty = "Property!";
Func<object, object> getter = ExpressionReflectionDelegateFactory.Instance.CreateGet<object>(typeof(StaticTestClass).GetProperty("StringProperty"));
object v = getter(null);
Assert.AreEqual(StaticTestClass.StringProperty, v);
getter = ExpressionReflectionDelegateFactory.Instance.CreateGet<object>(typeof(StaticTestClass).GetField("StringField"));
v = getter(null);
Assert.AreEqual(StaticTestClass.StringField, v);
}
[Test]
public void SetStatic()
{
Action<object, object> setter = ExpressionReflectionDelegateFactory.Instance.CreateSet<object>(typeof(StaticTestClass).GetProperty("StringProperty"));
setter(null, "New property!");
Assert.AreEqual("New property!", StaticTestClass.StringProperty);
setter = ExpressionReflectionDelegateFactory.Instance.CreateSet<object>(typeof(StaticTestClass).GetField("StringField"));
setter(null, "New field!");
Assert.AreEqual("New field!", StaticTestClass.StringField);
}
public class FieldsTestClass
{
public string StringField;
public bool BoolField;
public readonly int IntReadOnlyField = int.MaxValue;
}
[Test]
public void CreateGetField()
{
FieldsTestClass c = new FieldsTestClass
{
BoolField = true,
StringField = "String!"
};
Func<object, object> getter = ExpressionReflectionDelegateFactory.Instance.CreateGet<object>(typeof(FieldsTestClass).GetField("StringField"));
object value = getter(c);
Assert.AreEqual("String!", value);
getter = ExpressionReflectionDelegateFactory.Instance.CreateGet<object>(typeof(FieldsTestClass).GetField("BoolField"));
value = getter(c);
Assert.AreEqual(true, value);
}
[Test]
public void CreateSetField_ReadOnly()
{
FieldsTestClass c = new FieldsTestClass();
Action<object, object> setter = ExpressionReflectionDelegateFactory.Instance.CreateSet<object>(typeof(FieldsTestClass).GetField("IntReadOnlyField"));
setter(c, int.MinValue);
Assert.AreEqual(int.MinValue, c.IntReadOnlyField);
}
[Test]
public void CreateSetField()
{
FieldsTestClass c = new FieldsTestClass();
Action<object, object> setter = ExpressionReflectionDelegateFactory.Instance.CreateSet<object>(typeof(FieldsTestClass).GetField("StringField"));
setter(c, "String!");
Assert.AreEqual("String!", c.StringField);
setter = ExpressionReflectionDelegateFactory.Instance.CreateSet<object>(typeof(FieldsTestClass).GetField("BoolField"));
setter(c, true);
Assert.AreEqual(true, c.BoolField);
}
[Test]
public void SetOnStruct()
{
object structTest = new StructTest();
Action<object, object> setter = ExpressionReflectionDelegateFactory.Instance.CreateSet<object>(typeof(StructTest).GetProperty("StringProperty"));
setter(structTest, "Hi1");
Assert.AreEqual("Hi1", ((StructTest)structTest).StringProperty);
setter = ExpressionReflectionDelegateFactory.Instance.CreateSet<object>(typeof(StructTest).GetField("StringField"));
setter(structTest, "Hi2");
Assert.AreEqual("Hi2", ((StructTest)structTest).StringField);
}
[Test]
public void CreateGetWithBadObjectTarget()
{
ExceptionAssert.Throws<InvalidCastException>("Unable to cast object of type 'Newtonsoft.Json.Tests.TestObjects.Person' to type 'Newtonsoft.Json.Tests.TestObjects.Movie'.",
() =>
{
Person p = new Person();
p.Name = "Hi";
Func<object, object> setter = ExpressionReflectionDelegateFactory.Instance.CreateGet<object>(typeof(Movie).GetProperty("Name"));
setter(p);
});
}
[Test]
public void CreateSetWithBadObjectTarget()
{
ExceptionAssert.Throws<InvalidCastException>("Unable to cast object of type 'Newtonsoft.Json.Tests.TestObjects.Person' to type 'Newtonsoft.Json.Tests.TestObjects.Movie'.",
() =>
{
Person p = new Person();
Movie m = new Movie();
Action<object, object> setter = ExpressionReflectionDelegateFactory.Instance.CreateSet<object>(typeof(Movie).GetProperty("Name"));
setter(m, "Hi");
Assert.AreEqual(m.Name, "Hi");
setter(p, "Hi");
Assert.AreEqual(p.Name, "Hi");
});
}
[Test]
public void CreateSetWithBadObjectValue()
{
ExceptionAssert.Throws<InvalidCastException>("Unable to cast object of type 'System.Version' to type 'System.String'.",
() =>
{
Movie m = new Movie();
Action<object, object> setter = ExpressionReflectionDelegateFactory.Instance.CreateSet<object>(typeof(Movie).GetProperty("Name"));
setter(m, new Version("1.1.1.1"));
});
}
[Test]
public void CreateStaticMethodCall()
{
MethodInfo castMethodInfo = typeof(JsonSerializerTest.DictionaryKey).GetMethod("op_Implicit", new[] { typeof(string) });
Assert.IsNotNull(castMethodInfo);
MethodCall<object, object> call = ExpressionReflectionDelegateFactory.Instance.CreateMethodCall<object>(castMethodInfo);
object result = call(null, "First!");
Assert.IsNotNull(result);
JsonSerializerTest.DictionaryKey key = (JsonSerializerTest.DictionaryKey) result;
Assert.AreEqual("First!", key.Value);
}
}
}
#endif
@@ -107,6 +107,7 @@
<Compile Include="Linq\JPropertyKeyedCollection.cs" />
<Compile Include="SerializationBinder.cs" />
<Compile Include="Serialization\DiagnosticsTraceWriter.cs" />
<Compile Include="Serialization\ExpressionValueProvider.cs" />
<Compile Include="Serialization\ITraceWriter.cs" />
<Compile Include="Serialization\JsonContainerContract.cs" />
<Compile Include="Serialization\JsonDynamicContract.cs" />
@@ -114,6 +115,10 @@
<Compile Include="StreamingContext.cs" />
<Compile Include="StringEscapeHandling.cs" />
<Compile Include="Utilities\DateTimeParser.cs" />
<Compile Include="Utilities\DynamicProxy.cs" />
<Compile Include="Utilities\DynamicProxyMetaObject.cs" />
<Compile Include="Utilities\DynamicUtils.cs" />
<Compile Include="Utilities\ExpressionReflectionDelegateFactory.cs" />
<Compile Include="Utilities\LinqBridge.cs" />
<Compile Include="Linq\JPath.cs" />
<Compile Include="Linq\JPropertyDescriptor.cs" />
@@ -119,6 +119,7 @@
<Compile Include="Linq\JPropertyKeyedCollection.cs" />
<Compile Include="SerializationBinder.cs" />
<Compile Include="Serialization\DiagnosticsTraceWriter.cs" />
<Compile Include="Serialization\ExpressionValueProvider.cs" />
<Compile Include="Serialization\ITraceWriter.cs" />
<Compile Include="Serialization\JsonContainerContract.cs" />
<Compile Include="Serialization\MemoryTraceWriter.cs" />
@@ -226,7 +227,9 @@
<Compile Include="Utilities\DynamicWrapper.cs" />
<Compile Include="Utilities\DynamicReflectionDelegateFactory.cs" />
<Compile Include="Serialization\ObjectConstructor.cs" />
<Compile Include="Utilities\ExpressionReflectionDelegateFactory.cs" />
<Compile Include="Utilities\ILGeneratorExtensions.cs" />
<Compile Include="Utilities\LinqBridge.cs" />
<Compile Include="Utilities\ReflectionDelegateFactory.cs" />
<Compile Include="Utilities\LateBoundReflectionDelegateFactory.cs" />
<Compile Include="Utilities\MethodCall.cs" />
@@ -119,6 +119,7 @@
<Compile Include="JsonPosition.cs" />
<Compile Include="Linq\JPropertyKeyedCollection.cs" />
<Compile Include="Serialization\DiagnosticsTraceWriter.cs" />
<Compile Include="Serialization\ExpressionValueProvider.cs" />
<Compile Include="Serialization\ITraceWriter.cs" />
<Compile Include="Serialization\JsonContainerContract.cs" />
<Compile Include="Serialization\MemoryTraceWriter.cs" />
@@ -225,7 +226,9 @@
<Compile Include="Utilities\DynamicWrapper.cs" />
<Compile Include="Utilities\DynamicReflectionDelegateFactory.cs" />
<Compile Include="Serialization\ObjectConstructor.cs" />
<Compile Include="Utilities\ExpressionReflectionDelegateFactory.cs" />
<Compile Include="Utilities\ILGeneratorExtensions.cs" />
<Compile Include="Utilities\LinqBridge.cs" />
<Compile Include="Utilities\ReflectionDelegateFactory.cs" />
<Compile Include="Utilities\LateBoundReflectionDelegateFactory.cs" />
<Compile Include="Utilities\MethodCall.cs" />
@@ -147,6 +147,7 @@
<Compile Include="SerializationBinder.cs" />
<Compile Include="Serialization\CachedAttributeGetter.cs" />
<Compile Include="Serialization\CamelCasePropertyNamesContractResolver.cs" />
<Compile Include="Serialization\ExpressionValueProvider.cs" />
<Compile Include="Serialization\DefaultContractResolver.cs" />
<Compile Include="Serialization\DefaultReferenceResolver.cs" />
<Compile Include="Serialization\DefaultSerializationBinder.cs" />
@@ -190,6 +191,7 @@
<Compile Include="Utilities\CollectionUtils.cs" />
<Compile Include="Utilities\CollectionWrapper.cs" />
<Compile Include="Utilities\ConvertUtils.cs" />
<Compile Include="Utilities\ExpressionReflectionDelegateFactory.cs" />
<Compile Include="Utilities\DateTimeParser.cs" />
<Compile Include="Utilities\DateTimeUtils.cs" />
<Compile Include="Utilities\DictionaryWrapper.cs" />
@@ -154,6 +154,7 @@
<Compile Include="Serialization\DynamicValueProvider.cs" />
<Compile Include="Serialization\ErrorContext.cs" />
<Compile Include="Serialization\ErrorEventArgs.cs" />
<Compile Include="Serialization\ExpressionValueProvider.cs" />
<Compile Include="Serialization\IContractResolver.cs" />
<Compile Include="Serialization\IReferenceResolver.cs" />
<Compile Include="Serialization\ITraceWriter.cs" />
@@ -201,6 +202,7 @@
<Compile Include="Utilities\EnumUtils.cs" />
<Compile Include="Utilities\EnumValue.cs" />
<Compile Include="Utilities\EnumValues.cs" />
<Compile Include="Utilities\ExpressionReflectionDelegateFactory.cs" />
<Compile Include="Utilities\ILGeneratorExtensions.cs" />
<Compile Include="Utilities\JavaScriptUtils.cs" />
<Compile Include="Utilities\LateBoundReflectionDelegateFactory.cs" />
@@ -154,6 +154,7 @@
<Compile Include="Serialization\DynamicValueProvider.cs" />
<Compile Include="Serialization\ErrorContext.cs" />
<Compile Include="Serialization\ErrorEventArgs.cs" />
<Compile Include="Serialization\ExpressionValueProvider.cs" />
<Compile Include="Serialization\IContractResolver.cs" />
<Compile Include="Serialization\IReferenceResolver.cs" />
<Compile Include="Serialization\ITraceWriter.cs" />
@@ -201,6 +202,7 @@
<Compile Include="Utilities\EnumUtils.cs" />
<Compile Include="Utilities\EnumValue.cs" />
<Compile Include="Utilities\EnumValues.cs" />
<Compile Include="Utilities\ExpressionReflectionDelegateFactory.cs" />
<Compile Include="Utilities\ILGeneratorExtensions.cs" />
<Compile Include="Utilities\JavaScriptUtils.cs" />
<Compile Include="Utilities\LateBoundReflectionDelegateFactory.cs" />
@@ -92,6 +92,6 @@ using System.Security;
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("4.5.0.0")]
[assembly: AssemblyFileVersion("5.0.4.16023")]
[assembly: AssemblyFileVersion("5.0.4.16024")]
[assembly: CLSCompliant(true)]
@@ -926,6 +926,8 @@ namespace Newtonsoft.Json.Serialization
valueProvider = new DynamicValueProvider(member);
else
valueProvider = new ReflectionValueProvider(member);
#elif !(PORTABLE40)
valueProvider = new ExpressionValueProvider(member);
#else
valueProvider = new ReflectionValueProvider(member);
#endif
@@ -0,0 +1,113 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
#if !(NET20 || NET35 || PORTABLE40)
using System;
using System.Collections.Generic;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#endif
using System.Text;
using System.Reflection;
using Newtonsoft.Json.Utilities;
using System.Globalization;
namespace Newtonsoft.Json.Serialization
{
/// <summary>
/// Get and set values for a <see cref="MemberInfo"/> using dynamic methods.
/// </summary>
public class ExpressionValueProvider : IValueProvider
{
private readonly MemberInfo _memberInfo;
private Func<object, object> _getter;
private Action<object, object> _setter;
/// <summary>
/// Initializes a new instance of the <see cref="ExpressionValueProvider"/> class.
/// </summary>
/// <param name="memberInfo">The member info.</param>
public ExpressionValueProvider(MemberInfo memberInfo)
{
ValidationUtils.ArgumentNotNull(memberInfo, "memberInfo");
_memberInfo = memberInfo;
}
/// <summary>
/// Sets the value.
/// </summary>
/// <param name="target">The target to set the value on.</param>
/// <param name="value">The value to set on the target.</param>
public void SetValue(object target, object value)
{
try
{
if (_setter == null)
_setter = ExpressionReflectionDelegateFactory.Instance.CreateSet<object>(_memberInfo);
#if DEBUG
// dynamic method doesn't check whether the type is 'legal' to set
// add this check for unit tests
if (value == null)
{
if (!ReflectionUtils.IsNullable(ReflectionUtils.GetMemberUnderlyingType(_memberInfo)))
throw new JsonSerializationException("Incompatible value. Cannot set {0} to null.".FormatWith(CultureInfo.InvariantCulture, _memberInfo));
}
else if (!ReflectionUtils.GetMemberUnderlyingType(_memberInfo).IsAssignableFrom(value.GetType()))
{
throw new JsonSerializationException("Incompatible value. Cannot set {0} to type {1}.".FormatWith(CultureInfo.InvariantCulture, _memberInfo, value.GetType()));
}
#endif
_setter(target, value);
}
catch (Exception ex)
{
throw new JsonSerializationException("Error setting value to '{0}' on '{1}'.".FormatWith(CultureInfo.InvariantCulture, _memberInfo.Name, target.GetType()), ex);
}
}
/// <summary>
/// Gets the value.
/// </summary>
/// <param name="target">The target to get the value from.</param>
/// <returns>The value.</returns>
public object GetValue(object target)
{
try
{
if (_getter == null)
_getter = ExpressionReflectionDelegateFactory.Instance.CreateGet<object>(_memberInfo);
return _getter(target);
}
catch (Exception ex)
{
throw new JsonSerializationException("Error getting value from '{0}' on '{1}'.".FormatWith(CultureInfo.InvariantCulture, _memberInfo.Name, target.GetType()), ex);
}
}
}
}
#endif
@@ -436,9 +436,13 @@ namespace Newtonsoft.Json.Serialization
#if !(SILVERLIGHT || PORTABLE40 || PORTABLE || NETFX_CORE)
if (DynamicCodeGeneration)
return DynamicReflectionDelegateFactory.Instance;
#endif
return LateBoundReflectionDelegateFactory.Instance;
#elif !(PORTABLE40)
return ExpressionReflectionDelegateFactory.Instance;
#else
return LateBoundReflectionDelegateFactory.Instance;
#endif
}
}
}
@@ -0,0 +1,249 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
#if !(PORTABLE40 || NET20 || NET35)
using System;
using System.Linq.Expressions;
using System.Reflection;
namespace Newtonsoft.Json.Utilities
{
internal class ExpressionReflectionDelegateFactory : ReflectionDelegateFactory
{
private static readonly ExpressionReflectionDelegateFactory _instance = new ExpressionReflectionDelegateFactory();
internal static ReflectionDelegateFactory Instance
{
get { return _instance; }
}
public override MethodCall<T, object> CreateMethodCall<T>(MethodBase method)
{
ValidationUtils.ArgumentNotNull(method, "method");
Type type = typeof(object);
ParameterExpression targetParameterExpression = Expression.Parameter(type, "target");
ParameterExpression argsParameterExpression = Expression.Parameter(typeof(object[]), "args");
ParameterInfo[] parametersInfo = method.GetParameters();
Expression[] argsExpression = new Expression[parametersInfo.Length];
for (int i = 0; i < parametersInfo.Length; i++)
{
Expression indexExpression = Expression.Constant(i);
Expression paramAccessorExpression = Expression.ArrayIndex(argsParameterExpression, indexExpression);
paramAccessorExpression = EnsureCastExpression(paramAccessorExpression, parametersInfo[i].ParameterType);
argsExpression[i] = paramAccessorExpression;
}
Expression callExpression;
if (method.IsConstructor)
{
callExpression = Expression.New((ConstructorInfo)method, argsExpression);
}
else if (method.IsStatic)
{
callExpression = Expression.Call((MethodInfo)method, argsExpression);
}
else
{
Expression readParameter = EnsureCastExpression(targetParameterExpression, method.DeclaringType);
callExpression = Expression.Call(readParameter, (MethodInfo)method, argsExpression);
}
if (method is MethodInfo)
callExpression = EnsureCastExpression(callExpression, type);
LambdaExpression lambdaExpression = Expression.Lambda(typeof(MethodCall<T, object>), callExpression, targetParameterExpression, argsParameterExpression);
MethodCall<T, object> compiled = (MethodCall<T, object>)lambdaExpression.Compile();
return compiled;
}
public override Func<T> CreateDefaultConstructor<T>(Type type)
{
ValidationUtils.ArgumentNotNull(type, "type");
// avoid error from expressions compiler because of abstract class
if (type.IsAbstract())
return () => (T)Activator.CreateInstance(type);
Type resultType = typeof(T);
Expression expression = Expression.New(type);
expression = EnsureCastExpression(expression, resultType);
LambdaExpression lambdaExpression = Expression.Lambda(typeof(Func<T>), expression);
Func<T> compiled = (Func<T>)lambdaExpression.Compile();
return compiled;
}
public override Func<T, object> CreateGet<T>(PropertyInfo propertyInfo)
{
ValidationUtils.ArgumentNotNull(propertyInfo, "propertyInfo");
Type instanceType = typeof(T);
Type resultType = typeof(object);
ParameterExpression parameterExpression = Expression.Parameter(instanceType, "instance");
Expression resultExpression;
MethodInfo getMethod = propertyInfo.GetGetMethod(true);
if (getMethod.IsStatic)
{
resultExpression = Expression.MakeMemberAccess(null, propertyInfo);
}
else
{
Expression readParameter = EnsureCastExpression(parameterExpression, propertyInfo.DeclaringType);
resultExpression = Expression.MakeMemberAccess(readParameter, propertyInfo);
}
resultExpression = EnsureCastExpression(resultExpression, resultType);
LambdaExpression lambdaExpression = Expression.Lambda(typeof(Func<T, object>), resultExpression, parameterExpression);
Func<T, object> compiled = (Func<T, object>)lambdaExpression.Compile();
return compiled;
}
public override Func<T, object> CreateGet<T>(FieldInfo fieldInfo)
{
ValidationUtils.ArgumentNotNull(fieldInfo, "fieldInfo");
ParameterExpression sourceParameter = Expression.Parameter(typeof(T), "source");
Expression fieldExpression;
if (fieldInfo.IsStatic)
{
fieldExpression = Expression.Field(null, fieldInfo);
}
else
{
Expression sourceExpression = EnsureCastExpression(sourceParameter, fieldInfo.DeclaringType);
fieldExpression = Expression.Field(sourceExpression, fieldInfo);
}
fieldExpression = EnsureCastExpression(fieldExpression, typeof(object));
Func<T, object> compiled = Expression.Lambda<Func<T, object>>(fieldExpression, sourceParameter).Compile();
return compiled;
}
public override Action<T, object> CreateSet<T>(FieldInfo fieldInfo)
{
ValidationUtils.ArgumentNotNull(fieldInfo, "fieldInfo");
// use reflection for structs
// expression doesn't correctly set value
if (fieldInfo.DeclaringType.IsValueType() || fieldInfo.IsInitOnly)
return LateBoundReflectionDelegateFactory.Instance.CreateSet<T>(fieldInfo);
ParameterExpression sourceParameterExpression = Expression.Parameter(typeof(T), "source");
ParameterExpression valueParameterExpression = Expression.Parameter(typeof(object), "value");
Expression fieldExpression;
if (fieldInfo.IsStatic)
{
fieldExpression = Expression.Field(null, fieldInfo);
}
else
{
Expression sourceExpression = EnsureCastExpression(sourceParameterExpression, fieldInfo.DeclaringType);
fieldExpression = Expression.Field(sourceExpression, fieldInfo);
}
Expression valueExpression = EnsureCastExpression(valueParameterExpression, fieldExpression.Type);
BinaryExpression assignExpression = Expression.Assign(fieldExpression, valueExpression);
LambdaExpression lambdaExpression = Expression.Lambda(typeof(Action<T, object>), assignExpression, sourceParameterExpression, valueParameterExpression);
Action<T, object> compiled = (Action<T, object>)lambdaExpression.Compile();
return compiled;
}
public override Action<T, object> CreateSet<T>(PropertyInfo propertyInfo)
{
ValidationUtils.ArgumentNotNull(propertyInfo, "propertyInfo");
// use reflection for structs
// expression doesn't correctly set value
if (propertyInfo.DeclaringType.IsValueType())
return LateBoundReflectionDelegateFactory.Instance.CreateSet<T>(propertyInfo);
Type instanceType = typeof(T);
Type valueType = typeof(object);
ParameterExpression instanceParameter = Expression.Parameter(instanceType, "instance");
ParameterExpression valueParameter = Expression.Parameter(valueType, "value");
Expression readValueParameter = EnsureCastExpression(valueParameter, propertyInfo.PropertyType);
MethodInfo setMethod = propertyInfo.GetSetMethod(true);
Expression setExpression;
if (setMethod.IsStatic)
{
setExpression = Expression.Call(setMethod, readValueParameter);
}
else
{
Expression readInstanceParameter = EnsureCastExpression(instanceParameter, propertyInfo.DeclaringType);
setExpression = Expression.Call(readInstanceParameter, setMethod, readValueParameter);
}
LambdaExpression lambdaExpression = Expression.Lambda(typeof(Action<T, object>), setExpression, instanceParameter, valueParameter);
Action<T, object> compiled = (Action<T, object>)lambdaExpression.Compile();
return compiled;
}
private Expression EnsureCastExpression(Expression expression, Type targetType)
{
Type expressionType = expression.Type;
// check if a cast or conversion is required
if (expressionType == targetType || (!expressionType.IsValueType() && targetType.IsAssignableFrom(expressionType)))
return expression;
return Expression.Convert(expression, targetType);
}
}
}
#endif