public override SystemFunc <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(SystemFunc <T, object>), resultExpression, parameterExpression);

            SystemFunc <T, object> compiled = (SystemFunc <T, object>)lambdaExpression.Compile();

            return(compiled);
        }
        public override SystemFunc <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));

            SystemFunc <T, object> compiled = Expression.Lambda <SystemFunc <T, object> >(fieldExpression, sourceParameter).Compile();

            return(compiled);
        }
        public override SystemFunc <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(SystemFunc <T>), expression);

                SystemFunc <T> compiled = (SystemFunc <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));
            }
        }
Exemple #4
0
        public ThreadSafeStore(SystemFunc <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
        }
Exemple #5
0
        public static JsonConverter GetJsonConverter(object attributeProvider)
        {
            JsonConverterAttribute converterAttribute = GetCachedAttribute <JsonConverterAttribute>(attributeProvider);

            if (converterAttribute != null)
            {
                SystemFunc <object[], object> creator = CreatorCache.Get(converterAttribute.ConverterType);
                if (creator != null)
                {
                    return((JsonConverter)creator(converterAttribute.ConverterParameters));
                }
            }

            return(null);
        }
        /// <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, SystemFunc <T, bool> predicate)
        {
            int index = 0;

            foreach (T value in collection)
            {
                if (predicate(value))
                {
                    return(index);
                }

                index++;
            }

            return(-1);
        }
        public override SystemFunc <T, object> CreateGet <T>(FieldInfo fieldInfo)
        {
            if (fieldInfo.IsLiteral)
            {
                object constantValue          = fieldInfo.GetValue(null);
                SystemFunc <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((SystemFunc <T, object>)dynamicMethod.CreateDelegate(typeof(SystemFunc <T, object>)));
        }
Exemple #9
0
        private static SystemFunc <object[], object> GetCreator(Type type)
        {
            SystemFunc <object> defaultConstructor = (ReflectionUtils.HasDefaultConstructor(type, false))
                ? ReflectionDelegateFactory.CreateDefaultConstructor <object>(type)
                : null;

            return((parameters) =>
            {
                try
                {
                    if (parameters != null)
                    {
                        Type[] paramTypes = parameters.Select(param => param.GetType()).ToArray();
                        ConstructorInfo parameterizedConstructorInfo = type.GetConstructor(paramTypes);

                        if (null != parameterizedConstructorInfo)
                        {
                            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);
                }
            });
        }
Exemple #10
0
 static void test_exportData()
 {
     Debug.Assert(SystemFunc.exportData());
 }
Exemple #11
0
 static void test_resetData()
 {
     Debug.Assert(SystemFunc.resetData());
 }
Exemple #12
0
 public ActFunc(SystemFunc func, bool active)
 {
     this.func   = func;
     this.active = active;
 }
Exemple #13
0
        public static NamingStrategy CreateNamingStrategyInstance(Type namingStrategyType, object[] converterArgs)
        {
            SystemFunc <object[], object> converterCreator = CreatorCache.Get(namingStrategyType);

            return((NamingStrategy)converterCreator(converterArgs));
        }
Exemple #14
0
        /// <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="converterArgs">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[] converterArgs)
        {
            SystemFunc <object[], object> converterCreator = CreatorCache.Get(converterType);

            return((JsonConverter)converterCreator(converterArgs));
        }
Exemple #15
0
        public object GetValue(object target, string member)
        {
            SystemFunc <object, object> getter = Members[member].Getter;

            return(getter(target));
        }
        public static TSource ForgivingCaseSensitiveFind <TSource>(this IEnumerable <TSource> source, SystemFunc <TSource, string> valueSelector, string testValue)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }
            if (valueSelector == null)
            {
                throw new ArgumentNullException(nameof(valueSelector));
            }

            IEnumerable <TSource> 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
                IEnumerable <TSource> caseSensitiveResults = source.Where(s => string.Equals(valueSelector(s), testValue, StringComparison.Ordinal));
                return(caseSensitiveResults.SingleOrDefault());
            }
        }
Exemple #17
0
        public static ReflectionObject Create(Type t, MethodBase creator, params string[] memberNames)
        {
            ReflectionDelegateFactory delegateFactory = JsonTypeReflector.ReflectionDelegateFactory;

            ObjectConstructor <object> creatorConstructor = null;

            if (creator != null)
            {
                creatorConstructor = delegateFactory.CreateParameterizedConstructor(creator);
            }
            else
            {
                if (ReflectionUtils.HasDefaultConstructor(t, false))
                {
                    SystemFunc <object> ctor = delegateFactory.CreateDefaultConstructor <object>(t);

                    creatorConstructor = args => ctor();
                }
            }

            ReflectionObject d = new ReflectionObject(creatorConstructor);

            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);
        }