public override Serialization.Func <T, object> CreateGet <T>(PropertyInfo propertyInfo) { ValidationUtils.ArgumentNotNull(propertyInfo, nameof(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(Serialization.Func <T, object>), resultExpression, parameterExpression); Serialization.Func <T, object> compiled = (Serialization.Func <T, object>)lambdaExpression.Compile(); return(compiled); }
private static object EnsureTypeAssignable(object value, Type initialType, Type targetType) { Type valueType = (value != null) ? value.GetType() : null; if (value != null) { if (targetType.IsAssignableFrom(valueType)) { return(value); } Serialization.Func <object, object> castConverter = CastConverters.Get(new TypeConvertKey(valueType, targetType)); if (castConverter != null) { return(castConverter(value)); } } else { if (ReflectionUtils.IsNullable(targetType)) { return(null); } } throw new ArgumentException("Could not cast or convert from {0} to {1}.".FormatWith(CultureInfo.InvariantCulture, (initialType != null) ? initialType.ToString() : "{null}", targetType)); }
public override Serialization.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)); } try { Type resultType = typeof(T); Expression expression = Expression.New(type); expression = EnsureCastExpression(expression, resultType); LambdaExpression lambdaExpression = Expression.Lambda(typeof(Serialization.Func <T>), expression); Serialization.Func <T> compiled = (Serialization.Func <T>)lambdaExpression.Compile(); return(compiled); } catch { // an error can be thrown if constructor is not valid on Win8 // will have INVOCATION_FLAGS_NON_W8P_FX_API invocation flag return(() => (T)Activator.CreateInstance(type)); } }
/// <summary> /// Creates a new <see cref="JsonSerializer"/> instance. /// The <see cref="JsonSerializer"/> will use default settings. /// </summary> /// <returns> /// A new <see cref="JsonSerializer"/> instance. /// The <see cref="JsonSerializer"/> will use default settings. /// </returns> public static JsonSerializer CreateDefault() { // copy static to local variable to avoid concurrency issues Serialization.Func <JsonSerializerSettings> defaultSettingsCreator = JsonConvert.DefaultSettings; JsonSerializerSettings defaultSettings = (defaultSettingsCreator != null) ? defaultSettingsCreator() : null; return(Create(defaultSettings)); }
public ThreadSafeStore(Serialization.Func <TKey, TValue> creator) { if (creator == null) { throw new ArgumentNullException("creator"); } _creator = creator; _store = new Dictionary <TKey, TValue>(); }
public ThreadSafeStore(Serialization.Func <TKey, TValue> creator) { ValidationUtils.ArgumentNotNull(creator, nameof(creator)); _creator = creator; #if HAVE_CONCURRENT_DICTIONARY _concurrentStore = new ConcurrentDictionary <TKey, TValue>(); #else _store = new Dictionary <TKey, TValue>(); #endif }
public static JsonConverter GetJsonConverter(object attributeProvider) { JsonConverterAttribute converterAttribute = GetCachedAttribute <JsonConverterAttribute>(attributeProvider); if (converterAttribute != null) { Serialization.Func <object[], object> creator = CreatorCache.Get(converterAttribute.ConverterType); if (creator != null) { return((JsonConverter)creator(converterAttribute.ConverterParameters)); } } return(null); }
public override Serialization.Func <T, object> CreateGet <T>(FieldInfo fieldInfo) { if (fieldInfo.IsLiteral) { object constantValue = fieldInfo.GetValue(null); Serialization.Func <T, object> getter = o => constantValue; return(getter); } DynamicMethod dynamicMethod = CreateDynamicMethod("Get" + fieldInfo.Name, typeof(T), new[] { typeof(object) }, fieldInfo.DeclaringType); ILGenerator generator = dynamicMethod.GetILGenerator(); GenerateCreateGetFieldIL(fieldInfo, generator); return((Serialization.Func <T, object>)dynamicMethod.CreateDelegate(typeof(Serialization.Func <T, object>))); }
/// <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); } }
public static int IndexOf <T>(this IEnumerable <T> collection, Serialization.Func <T, bool> predicate) { int index = 0; foreach (T value in collection) { if (predicate(value)) { return(index); } index++; } return(-1); }
private static Serialization.Func <object[], object> GetCreator(Type type) { Serialization.Func <object> defaultConstructor = (ReflectionUtils.HasDefaultConstructor(type, false)) ? ReflectionDelegateFactory.CreateDefaultConstructor <object>(type) : null; return((parameters) => { try { if (parameters != null) { Type[] paramTypes = parameters.Select(param => { if (param == null) { throw new InvalidOperationException("Cannot pass a null parameter to the constructor."); } return param.GetType(); }).ToArray(); ConstructorInfo parameterizedConstructorInfo = type.GetConstructor(paramTypes); if (parameterizedConstructorInfo != null) { ObjectConstructor <object> parameterizedConstructor = ReflectionDelegateFactory.CreateParameterizedConstructor(parameterizedConstructorInfo); return parameterizedConstructor(parameters); } else { throw new JsonException("No matching parameterized constructor found for '{0}'.".FormatWith(CultureInfo.InvariantCulture, type)); } } if (defaultConstructor == null) { throw new JsonException("No parameterless constructor defined for '{0}'.".FormatWith(CultureInfo.InvariantCulture, type)); } return defaultConstructor(); } catch (Exception ex) { throw new JsonException("Error creating '{0}'.".FormatWith(CultureInfo.InvariantCulture, type), ex); } }); }
public override Serialization.Func <T, object> CreateGet <T>(FieldInfo fieldInfo) { ValidationUtils.ArgumentNotNull(fieldInfo, nameof(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)); Serialization.Func <T, object> compiled = Expression.Lambda <Serialization.Func <T, object> >(fieldExpression, sourceParameter).Compile(); return(compiled); }
public static ReflectionObject Create(Type t, MethodBase creator, params string[] memberNames) { ReflectionObject d = new ReflectionObject(); ReflectionDelegateFactory delegateFactory = JsonTypeReflector.ReflectionDelegateFactory; if (creator != null) { d.Creator = delegateFactory.CreateParametrizedConstructor(creator); } else { if (ReflectionUtils.HasDefaultConstructor(t, false)) { Serialization.Func <object> ctor = delegateFactory.CreateDefaultConstructor <object>(t); d.Creator = args => ctor(); } } foreach (string memberName in memberNames) { MemberInfo[] members = t.GetMember(memberName, BindingFlags.Instance | BindingFlags.Public); if (members.Length != 1) { throw new ArgumentException("Expected a single member with the name '{0}'.".FormatWith(CultureInfo.InvariantCulture, memberName)); } MemberInfo member = members.Single(); ReflectionMember reflectionMember = new ReflectionMember(); switch (member.MemberType()) { case MemberTypes.Field: case MemberTypes.Property: if (ReflectionUtils.CanReadMemberValue(member, false)) { reflectionMember.Getter = delegateFactory.CreateGet <object>(member); } if (ReflectionUtils.CanSetMemberValue(member, false, false)) { reflectionMember.Setter = delegateFactory.CreateSet <object>(member); } break; case MemberTypes.Method: MethodInfo method = (MethodInfo)member; if (method.IsPublic) { ParameterInfo[] parameters = method.GetParameters(); if (parameters.Length == 0 && method.ReturnType != typeof(void)) { MethodCall <object, object> call = delegateFactory.CreateMethodCall <object>(method); reflectionMember.Getter = target => call(target); } else if (parameters.Length == 1 && method.ReturnType == typeof(void)) { MethodCall <object, object> call = delegateFactory.CreateMethodCall <object>(method); reflectionMember.Setter = (target, arg) => call(target, arg); } } break; default: throw new ArgumentException("Unexpected member type '{0}' for member '{1}'.".FormatWith(CultureInfo.InvariantCulture, member.MemberType(), member.Name)); } if (ReflectionUtils.CanReadMemberValue(member, false)) { reflectionMember.Getter = delegateFactory.CreateGet <object>(member); } if (ReflectionUtils.CanSetMemberValue(member, false, false)) { reflectionMember.Setter = delegateFactory.CreateSet <object>(member); } reflectionMember.MemberType = ReflectionUtils.GetMemberUnderlyingType(member); d.Members[memberName] = reflectionMember; } return(d); }
public object GetValue(object target, string member) { Serialization.Func <object, object> getter = Members[member].Getter; return(getter(target)); }
public static TSource ForgivingCaseSensitiveFind <TSource>(this IEnumerable <TSource> source, Serialization.Func <TSource, string> valueSelector, string testValue) { if (source == null) { throw new ArgumentNullException("source"); } if (valueSelector == null) { throw new ArgumentNullException("valueSelector"); } var caseInsensitiveResults = source.Where(s => string.Equals(valueSelector(s), testValue, StringComparison.OrdinalIgnoreCase)); if (caseInsensitiveResults.Count() <= 1) { return(caseInsensitiveResults.SingleOrDefault()); } else { // multiple results returned. now filter using case sensitivity var caseSensitiveResults = source.Where(s => string.Equals(valueSelector(s), testValue, StringComparison.Ordinal)); return(caseSensitiveResults.SingleOrDefault()); } }
/// <summary> /// Lookup and create an instance of the <see cref="JsonConverter"/> type described by the argument. /// </summary> /// <param name="converterType">The <see cref="JsonConverter"/> type to create.</param> /// <param name="args">Optional arguments to pass to an initializing constructor of the JsonConverter. /// If <c>null</c>, the default constructor is used.</param> public static JsonConverter CreateJsonConverterInstance(Type converterType, object[] args) { Serialization.Func <object[], object> converterCreator = CreatorCache.Get(converterType); return((JsonConverter)converterCreator(args)); }
public static NamingStrategy CreateNamingStrategyInstance(Type namingStrategyType, object[] args) { Serialization.Func <object[], object> converterCreator = CreatorCache.Get(namingStrategyType); return((NamingStrategy)converterCreator(args)); }